MIFOSX-9: Audit related work

This commit is contained in:
Keith Woodlock
2013-01-06 17:36:05 +00:00
parent 06f6ad2dff
commit 690f0d4abc
148 changed files with 2757 additions and 2110 deletions
@@ -0,0 +1,28 @@
DROP TABLE IF EXISTS `m_portfolio_command_source`;
CREATE TABLE `m_portfolio_command_source` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`action_name` varchar(50) NOT NULL,
`entity_name` varchar(50) NOT NULL,
`office_id` bigint(20) DEFAULT NULL,
`group_id` bigint(20) DEFAULT NULL,
`client_id` bigint(20) DEFAULT NULL,
`loan_id` bigint(20) DEFAULT NULL,
`api_get_url` varchar(100) NOT NULL,
`resource_id` bigint(20) DEFAULT NULL,
`command_as_json` text NOT NULL,
`maker_id` bigint(20) NOT NULL,
`made_on_date` datetime NOT NULL,
`checker_id` bigint(20) DEFAULT NULL,
`checked_on_date` datetime DEFAULT NULL,
`processing_result_enum` smallint(5) NOT NULL,
PRIMARY KEY (`id`),
KEY `FK_m_maker_m_appuser` (`maker_id`),
KEY `FK_m_checker_m_appuser` (`checker_id`),
KEY `action_name` (`action_name`),
KEY `entity_name` (`entity_name`,`resource_id`),
KEY `made_on_date` (`made_on_date`),
KEY `checked_on_date` (`checked_on_date`),
KEY `processing_result_enum` (`processing_result_enum`),
CONSTRAINT `FK_m_checker_m_appuser` FOREIGN KEY (`checker_id`) REFERENCES `m_appuser` (`id`),
CONSTRAINT `FK_m_maker_m_appuser` FOREIGN KEY (`maker_id`) REFERENCES `m_appuser` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
@@ -24,7 +24,7 @@ import org.mifosplatform.accounting.api.infrastructure.AccountingApiJsonSerializ
import org.mifosplatform.accounting.service.GLAccountReadPlatformService; import org.mifosplatform.accounting.service.GLAccountReadPlatformService;
import org.mifosplatform.accounting.service.GLAccountWritePlatformService; import org.mifosplatform.accounting.service.GLAccountWritePlatformService;
import org.mifosplatform.infrastructure.core.api.ApiParameterHelper; import org.mifosplatform.infrastructure.core.api.ApiParameterHelper;
import org.mifosplatform.infrastructure.core.data.EntityIdentifier; import org.mifosplatform.infrastructure.core.data.CommandProcessingResult;
import org.mifosplatform.infrastructure.security.service.PlatformSecurityContext; import org.mifosplatform.infrastructure.security.service.PlatformSecurityContext;
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;
@@ -109,7 +109,7 @@ public class GLAccountsApiResource {
final Long coaId = glAccountWritePlatformService.createGLAccount(command); final Long coaId = glAccountWritePlatformService.createGLAccount(command);
return this.apiJsonSerializerService.serializeEntityIdentifier(new EntityIdentifier(coaId)); return this.apiJsonSerializerService.serializeEntityIdentifier(new CommandProcessingResult(coaId));
} }
@PUT @PUT
@@ -122,7 +122,7 @@ public class GLAccountsApiResource {
final Long coaId = glAccountWritePlatformService.updateGLAccount(glAccountId, command); final Long coaId = glAccountWritePlatformService.updateGLAccount(glAccountId, command);
return this.apiJsonSerializerService.serializeEntityIdentifier(new EntityIdentifier(coaId)); return this.apiJsonSerializerService.serializeEntityIdentifier(new CommandProcessingResult(coaId));
} }
@DELETE @DELETE
@@ -133,6 +133,6 @@ public class GLAccountsApiResource {
this.glAccountWritePlatformService.deleteGLAccount(glAccountId); this.glAccountWritePlatformService.deleteGLAccount(glAccountId);
return Response.ok(new EntityIdentifier(glAccountId)).build(); return Response.ok(new CommandProcessingResult(glAccountId)).build();
} }
} }
@@ -25,7 +25,7 @@ import org.mifosplatform.accounting.api.infrastructure.AccountingApiJsonSerializ
import org.mifosplatform.accounting.service.GLClosureReadPlatformService; import org.mifosplatform.accounting.service.GLClosureReadPlatformService;
import org.mifosplatform.accounting.service.GLClosureWritePlatformService; import org.mifosplatform.accounting.service.GLClosureWritePlatformService;
import org.mifosplatform.infrastructure.core.api.ApiParameterHelper; import org.mifosplatform.infrastructure.core.api.ApiParameterHelper;
import org.mifosplatform.infrastructure.core.data.EntityIdentifier; import org.mifosplatform.infrastructure.core.data.CommandProcessingResult;
import org.mifosplatform.infrastructure.security.service.PlatformSecurityContext; import org.mifosplatform.infrastructure.security.service.PlatformSecurityContext;
import org.mifosplatform.organisation.office.data.OfficeLookup; import org.mifosplatform.organisation.office.data.OfficeLookup;
import org.mifosplatform.organisation.office.service.OfficeReadPlatformService; import org.mifosplatform.organisation.office.service.OfficeReadPlatformService;
@@ -105,7 +105,7 @@ public class GLClosuresApiResource {
final Long coaId = glClosureWritePlatformService.createGLClosure(command); final Long coaId = glClosureWritePlatformService.createGLClosure(command);
return this.apiJsonSerializerService.serializeEntityIdentifier(new EntityIdentifier(coaId)); return this.apiJsonSerializerService.serializeEntityIdentifier(new CommandProcessingResult(coaId));
} }
@PUT @PUT
@@ -118,7 +118,7 @@ public class GLClosuresApiResource {
final Long coaId = glClosureWritePlatformService.updateGLClosure(glClosureId, command); final Long coaId = glClosureWritePlatformService.updateGLClosure(glClosureId, command);
return this.apiJsonSerializerService.serializeEntityIdentifier(new EntityIdentifier(coaId)); return this.apiJsonSerializerService.serializeEntityIdentifier(new CommandProcessingResult(coaId));
} }
@DELETE @DELETE
@@ -129,6 +129,6 @@ public class GLClosuresApiResource {
this.glClosureWritePlatformService.deleteGLClosure(glClosureId); this.glClosureWritePlatformService.deleteGLClosure(glClosureId);
return Response.ok(new EntityIdentifier(glClosureId)).build(); return Response.ok(new CommandProcessingResult(glClosureId)).build();
} }
} }
@@ -7,12 +7,12 @@ import org.mifosplatform.accounting.api.data.GLAccountData;
import org.mifosplatform.accounting.api.data.GLClosureData; import org.mifosplatform.accounting.api.data.GLClosureData;
import org.mifosplatform.accounting.api.data.GLJournalEntryData; import org.mifosplatform.accounting.api.data.GLJournalEntryData;
import org.mifosplatform.accounting.api.data.JournalEntryIdentifier; import org.mifosplatform.accounting.api.data.JournalEntryIdentifier;
import org.mifosplatform.infrastructure.core.data.EntityIdentifier; import org.mifosplatform.infrastructure.core.data.CommandProcessingResult;
public interface AccountingApiJsonSerializerService { public interface AccountingApiJsonSerializerService {
String serializeEntityIdentifier(final EntityIdentifier identifier); String serializeEntityIdentifier(final CommandProcessingResult identifier);
String serializeJournalEntryIdentifier(final JournalEntryIdentifier identifier); String serializeJournalEntryIdentifier(final JournalEntryIdentifier identifier);
@@ -11,7 +11,7 @@ import org.mifosplatform.accounting.api.data.GLJournalEntryData;
import org.mifosplatform.accounting.api.data.JournalEntryIdentifier; import org.mifosplatform.accounting.api.data.JournalEntryIdentifier;
import org.mifosplatform.accounting.api.infrastructure.AccountingApiJsonSerializerService; import org.mifosplatform.accounting.api.infrastructure.AccountingApiJsonSerializerService;
import org.mifosplatform.infrastructure.core.api.PortfolioApiJsonSerializerService; import org.mifosplatform.infrastructure.core.api.PortfolioApiJsonSerializerService;
import org.mifosplatform.infrastructure.core.data.EntityIdentifier; import org.mifosplatform.infrastructure.core.data.CommandProcessingResult;
import org.mifosplatform.infrastructure.core.serialization.GoogleGsonSerializerHelper; import org.mifosplatform.infrastructure.core.serialization.GoogleGsonSerializerHelper;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@@ -46,7 +46,7 @@ public class GoogleGsonAccountingApiJsonSerializerService implements AccountingA
} }
@Override @Override
public String serializeEntityIdentifier(final EntityIdentifier identifier) { public String serializeEntityIdentifier(final CommandProcessingResult identifier) {
final Gson gsonDeserializer = helper.createGsonBuilderWithParameterExclusionSerializationStrategy(DATA_PARAMETERS, false, final Gson gsonDeserializer = helper.createGsonBuilderWithParameterExclusionSerializationStrategy(DATA_PARAMETERS, false,
DATA_PARAMETERS); DATA_PARAMETERS);
return helper.serializedJsonFrom(gsonDeserializer, identifier); return helper.serializedJsonFrom(gsonDeserializer, identifier);
@@ -14,16 +14,8 @@ public final class AuditData {
@SuppressWarnings("unused") @SuppressWarnings("unused")
private final String entityName; private final String entityName;
@SuppressWarnings("unused") @SuppressWarnings("unused")
private final String apiOperation;
@SuppressWarnings("unused")
private final String resource;
@SuppressWarnings("unused")
private final Long resourceId; private final Long resourceId;
@SuppressWarnings("unused") @SuppressWarnings("unused")
private final String subResource;
@SuppressWarnings("unused")
private final Long subResourceId;
@SuppressWarnings("unused")
private final String maker; private final String maker;
@SuppressWarnings("unused") @SuppressWarnings("unused")
private final DateTime madeOnDate; private final DateTime madeOnDate;
@@ -36,22 +28,14 @@ public final class AuditData {
@SuppressWarnings("unused") @SuppressWarnings("unused")
private final String commandAsJson; private final String commandAsJson;
public AuditData(final Long id, final String actionName, public AuditData(final Long id, final String actionName, final String entityName, final Long resourceId, final String maker,
final String entityName, final String apiOperation, final DateTime madeOnDate, final String checker, final DateTime checkedOnDate, final String processingResult,
final String resource, final Long resourceId, final String commandAsJson) {
final String subResource, final Long subResourceId,
final String maker, final DateTime madeOnDate,
final String checker, final DateTime checkedOnDate,
final String processingResult, final String commandAsJson) {
this.id = id; this.id = id;
this.actionName = actionName; this.actionName = actionName;
this.entityName = entityName; this.entityName = entityName;
this.apiOperation = apiOperation;
this.resource = resource;
this.resourceId = resourceId; this.resourceId = resourceId;
this.subResource = subResource;
this.subResourceId = subResourceId;
this.maker = maker; this.maker = maker;
this.madeOnDate = madeOnDate; this.madeOnDate = madeOnDate;
this.checker = checker; this.checker = checker;
@@ -25,15 +25,13 @@ import org.springframework.stereotype.Service;
@Service @Service
public class AuditReadPlatformServiceImpl implements AuditReadPlatformService { public class AuditReadPlatformServiceImpl implements AuditReadPlatformService {
private final static Logger logger = LoggerFactory private final static Logger logger = LoggerFactory.getLogger(AuditReadPlatformServiceImpl.class);
.getLogger(AuditReadPlatformServiceImpl.class);
private final JdbcTemplate jdbcTemplate; private final JdbcTemplate jdbcTemplate;
private final PlatformSecurityContext context; private final PlatformSecurityContext context;
private final AppUserReadPlatformService appUserReadPlatformService; private final AppUserReadPlatformService appUserReadPlatformService;
@Autowired @Autowired
public AuditReadPlatformServiceImpl(final PlatformSecurityContext context, public AuditReadPlatformServiceImpl(final PlatformSecurityContext context, final TenantAwareRoutingDataSource dataSource,
final TenantAwareRoutingDataSource dataSource,
final AppUserReadPlatformService appUserReadPlatformService) { final AppUserReadPlatformService appUserReadPlatformService) {
this.context = context; this.context = context;
this.jdbcTemplate = new JdbcTemplate(dataSource); this.jdbcTemplate = new JdbcTemplate(dataSource);
@@ -45,38 +43,27 @@ public class AuditReadPlatformServiceImpl implements AuditReadPlatformService {
public String schema(boolean includeJson) { public String schema(boolean includeJson) {
String commandAsJsonString = ""; String commandAsJsonString = "";
if (includeJson) if (includeJson) commandAsJsonString = ", aud.command_as_json as commandAsJson ";
commandAsJsonString = ", aud.command_as_json as commandAsJson ";
return " aud.id as id, aud.action_name as actionName, aud.entity_name as entityName, aud.api_operation as apiOperation, " return " aud.id as id, aud.action_name as actionName, aud.entity_name as entityName," + " aud.resource_id as resourceId,"
+ " aud.api_resource as resource, aud.resource_id as resourceId, aud.api_subresource as subResource, aud.subresource_id as subResourceId," + " mk.username as maker, aud.made_on_date as madeOnDate, "
+ " mk.username as maker, aud.made_on_date as madeOnDate, ck.username as checker, aud.checked_on_date as checkedOnDate, ev.enum_message_property as processingResult " + "ck.username as checker, aud.checked_on_date as checkedOnDate, ev.enum_message_property as processingResult "
+ commandAsJsonString + commandAsJsonString + " from m_portfolio_command_source aud " + " left join m_appuser mk on mk.id = aud.maker_id"
+ " from m_portfolio_command_source aud "
+ " left join m_appuser mk on mk.id = aud.maker_id"
+ " left join m_appuser ck on ck.id = aud.checker_id" + " left join m_appuser ck on ck.id = aud.checker_id"
+ " left join r_enum_value ev on ev.enum_name = 'processing_result_enum' and ev.enum_id = aud.processing_result_enum"; + " left join r_enum_value ev on ev.enum_name = 'processing_result_enum' and ev.enum_id = aud.processing_result_enum";
} }
@Override @Override
public AuditData mapRow(final ResultSet rs, public AuditData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) throws SQLException {
@SuppressWarnings("unused") final int rowNum)
throws SQLException {
final Long id = rs.getLong("id"); final Long id = rs.getLong("id");
final String actionName = rs.getString("actionName"); final String actionName = rs.getString("actionName");
final String entityName = rs.getString("entityName"); final String entityName = rs.getString("entityName");
final String apiOperation = rs.getString("apiOperation");
final String resource = rs.getString("resource");
final Long resourceId = JdbcSupport.getLong(rs, "resourceId"); final Long resourceId = JdbcSupport.getLong(rs, "resourceId");
final String subResource = rs.getString("subResource");
final Long subResourceId = JdbcSupport.getLong(rs, "subResourceId");
final String maker = rs.getString("maker"); final String maker = rs.getString("maker");
final DateTime madeOnDate = JdbcSupport.getDateTime(rs, final DateTime madeOnDate = JdbcSupport.getDateTime(rs, "madeOnDate");
"madeOnDate");
final String checker = rs.getString("checker"); final String checker = rs.getString("checker");
final DateTime checkedOnDate = JdbcSupport.getDateTime(rs, final DateTime checkedOnDate = JdbcSupport.getDateTime(rs, "checkedOnDate");
"checkedOnDate");
final String processingResult = rs.getString("processingResult"); final String processingResult = rs.getString("processingResult");
String commandAsJson; String commandAsJson;
// commandAsJson might not be on the select list of columns // commandAsJson might not be on the select list of columns
@@ -85,23 +72,19 @@ public class AuditReadPlatformServiceImpl implements AuditReadPlatformService {
} catch (SQLException e) { } catch (SQLException e) {
commandAsJson = null; commandAsJson = null;
} }
return new AuditData(id, actionName, entityName, apiOperation, return new AuditData(id, actionName, entityName, resourceId, maker, madeOnDate, checker, checkedOnDate, processingResult,
resource, resourceId, subResource, subResourceId, maker,
madeOnDate, checker, checkedOnDate, processingResult,
commandAsJson); commandAsJson);
} }
} }
@Override @Override
public Collection<AuditData> retrieveAuditEntries(String extraCriteria, public Collection<AuditData> retrieveAuditEntries(String extraCriteria, boolean includeJson) {
boolean includeJson) {
context.authenticatedUser(); context.authenticatedUser();
final AuditMapper rm = new AuditMapper(); final AuditMapper rm = new AuditMapper();
String sql = "select " + rm.schema(includeJson); String sql = "select " + rm.schema(includeJson);
if (StringUtils.isNotBlank(extraCriteria)) if (StringUtils.isNotBlank(extraCriteria)) sql += " where (" + extraCriteria + ")";
sql += " where (" + extraCriteria + ")";
sql += " order by aud.id DESC"; sql += " order by aud.id DESC";
logger.info("sql: " + sql); logger.info("sql: " + sql);
return this.jdbcTemplate.query(sql, rm, new Object[] {}); return this.jdbcTemplate.query(sql, rm, new Object[] {});
@@ -121,31 +104,24 @@ public class AuditReadPlatformServiceImpl implements AuditReadPlatformService {
@Override @Override
public AuditSearchData retrieveSearchTemplate() { public AuditSearchData retrieveSearchTemplate() {
Collection<AppUserLookup> appUsers = appUserReadPlatformService Collection<AppUserLookup> appUsers = appUserReadPlatformService.retrieveSearchTemplate();
.retrieveSearchTemplate();
ActionNamesMapper mapper = new ActionNamesMapper(); ActionNamesMapper mapper = new ActionNamesMapper();
List<String> actionNames = this.jdbcTemplate.query(mapper.schema(), List<String> actionNames = this.jdbcTemplate.query(mapper.schema(), mapper, new Object[] {});
mapper, new Object[] {});
EntityNamesMapper mapper2 = new EntityNamesMapper(); EntityNamesMapper mapper2 = new EntityNamesMapper();
List<String> entityNames = this.jdbcTemplate.query(mapper2.schema(), List<String> entityNames = this.jdbcTemplate.query(mapper2.schema(), mapper2, new Object[] {});
mapper2, new Object[] {});
ProcessingResultsMapper mapper3 = new ProcessingResultsMapper(); ProcessingResultsMapper mapper3 = new ProcessingResultsMapper();
Collection<ProcessingResultLookup> processingResults = this.jdbcTemplate Collection<ProcessingResultLookup> processingResults = this.jdbcTemplate.query(mapper3.schema(), mapper3, new Object[] {});
.query(mapper3.schema(), mapper3, new Object[] {});
return new AuditSearchData(appUsers, actionNames, entityNames, return new AuditSearchData(appUsers, actionNames, entityNames, processingResults);
processingResults);
} }
private static final class ActionNamesMapper implements RowMapper<String> { private static final class ActionNamesMapper implements RowMapper<String> {
@Override @Override
public String mapRow(final ResultSet rs, public String mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) throws SQLException {
@SuppressWarnings("unused") final int rowNum)
throws SQLException {
return rs.getString("actionName"); return rs.getString("actionName");
} }
@@ -162,9 +138,7 @@ public class AuditReadPlatformServiceImpl implements AuditReadPlatformService {
private static final class EntityNamesMapper implements RowMapper<String> { private static final class EntityNamesMapper implements RowMapper<String> {
@Override @Override
public String mapRow(final ResultSet rs, public String mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) throws SQLException {
@SuppressWarnings("unused") final int rowNum)
throws SQLException {
return rs.getString("entityName"); return rs.getString("entityName");
} }
@@ -174,13 +148,10 @@ public class AuditReadPlatformServiceImpl implements AuditReadPlatformService {
} }
} }
private static final class ProcessingResultsMapper implements private static final class ProcessingResultsMapper implements RowMapper<ProcessingResultLookup> {
RowMapper<ProcessingResultLookup> {
@Override @Override
public ProcessingResultLookup mapRow(final ResultSet rs, public ProcessingResultLookup mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) throws SQLException {
@SuppressWarnings("unused") final int rowNum)
throws SQLException {
Long id = JdbcSupport.getLong(rs, "id"); Long id = JdbcSupport.getLong(rs, "id");
String processingResult = rs.getString("processingResult"); String processingResult = rs.getString("processingResult");
@@ -22,7 +22,7 @@ import org.mifosplatform.commands.data.CommandSourceData;
import org.mifosplatform.commands.service.PortfolioCommandSourceWritePlatformService; import org.mifosplatform.commands.service.PortfolioCommandSourceWritePlatformService;
import org.mifosplatform.commands.service.PortfolioCommandsReadPlatformService; import org.mifosplatform.commands.service.PortfolioCommandsReadPlatformService;
import org.mifosplatform.infrastructure.core.api.ApiRequestParameterHelper; import org.mifosplatform.infrastructure.core.api.ApiRequestParameterHelper;
import org.mifosplatform.infrastructure.core.data.EntityIdentifier; import org.mifosplatform.infrastructure.core.data.CommandProcessingResult;
import org.mifosplatform.infrastructure.core.exception.UnrecognizedQueryParamException; import org.mifosplatform.infrastructure.core.exception.UnrecognizedQueryParamException;
import org.mifosplatform.infrastructure.core.serialization.ApiRequestJsonSerializationSettings; import org.mifosplatform.infrastructure.core.serialization.ApiRequestJsonSerializationSettings;
import org.mifosplatform.infrastructure.core.serialization.DefaultToApiJsonSerializer; import org.mifosplatform.infrastructure.core.serialization.DefaultToApiJsonSerializer;
@@ -76,7 +76,7 @@ public class CommandsApiResource {
@Produces({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON })
public String approveMakerCheckerEntry(@PathParam("commandId") final Long commandId, @QueryParam("command") final String commandParam) { public String approveMakerCheckerEntry(@PathParam("commandId") final Long commandId, @QueryParam("command") final String commandParam) {
EntityIdentifier result = null; CommandProcessingResult result = null;
if (is(commandParam, "approve")) { if (is(commandParam, "approve")) {
result = this.writePlatformService.approveEntry(commandId); result = this.writePlatformService.approveEntry(commandId);
} else { } else {
@@ -98,6 +98,6 @@ public class CommandsApiResource {
final Long id = this.writePlatformService.deleteEntry(commandId); final Long id = this.writePlatformService.deleteEntry(commandId);
return this.toApiJsonSerializer.serialize(EntityIdentifier.commandOnlyResult(id)); return this.toApiJsonSerializer.serialize(CommandProcessingResult.commandOnlyResult(id));
} }
} }
@@ -26,21 +26,29 @@ public class CommandSource extends AbstractPersistable<Long> {
@Column(name = "entity_name", nullable = true, length = 100) @Column(name = "entity_name", nullable = true, length = 100)
private String entityName; private String entityName;
@Column(name = "api_operation", length = 30) @SuppressWarnings("unused")
private String apiOperation; @Column(name = "office_id")
private Long officeId;
@Column(name = "api_resource", length = 100) @SuppressWarnings("unused")
private String resource; @Column(name = "group_id")
private Long groupId;
@SuppressWarnings("unused")
@Column(name = "client_id")
private Long clientId;
@SuppressWarnings("unused")
@Column(name = "loan_id")
private Long loanId;
@SuppressWarnings("unused")
@Column(name = "api_get_url", length = 100)
private String resourceGetUrl;
@Column(name = "resource_id") @Column(name = "resource_id")
private Long resourceId; private Long resourceId;
@Column(name = "api_subresource", length = 100)
private String subResource;
@Column(name = "subresource_id")
private Long subResourceId;
@Column(name = "command_as_json", length = 1000) @Column(name = "command_as_json", length = 1000)
private String commandAsJson; private String commandAsJson;
@@ -69,24 +77,22 @@ public class CommandSource extends AbstractPersistable<Long> {
private Integer processingResult; private Integer processingResult;
public static CommandSource fullEntryFrom(final CommandWrapper wrapper, final JsonCommand command, final AppUser maker) { public static CommandSource fullEntryFrom(final CommandWrapper wrapper, final JsonCommand command, final AppUser maker) {
return new CommandSource(wrapper.actionName(), wrapper.entityName(), wrapper.operation(), wrapper.resourceName(), command.resourceId(), return new CommandSource(wrapper.actionName(), wrapper.entityName(), wrapper.getHref(), command.entityId(), command.json(), maker, DateTime.now());
wrapper.subResourceName(), command.subResourceId(), command.json(), maker, DateTime.now());
} }
protected CommandSource() { protected CommandSource() {
// //
} }
private CommandSource(final String actionName, final String entityName, final String apiOperation, final String resource, final Long resourceId, private CommandSource(
final String subResource, final Long subResourceId, final String commandSerializedAsJson, final AppUser maker, final String actionName, final String entityName, final String href,
final Long resourceId,
final String commandSerializedAsJson, final AppUser maker,
final DateTime madeOnDateTime) { final DateTime madeOnDateTime) {
this.actionName = actionName; this.actionName = actionName;
this.entityName = entityName; this.entityName = entityName;
this.apiOperation = StringUtils.defaultIfEmpty(apiOperation, null); this.resourceGetUrl = href;
this.resource = StringUtils.defaultIfEmpty(resource, null);
this.resourceId = resourceId; this.resourceId = resourceId;
this.subResource = StringUtils.defaultIfEmpty(subResource, null);
this.subResourceId = subResourceId;
this.commandAsJson = commandSerializedAsJson; this.commandAsJson = commandSerializedAsJson;
this.maker = maker; this.maker = maker;
this.madeOnDate = madeOnDateTime.toDate(); this.madeOnDate = madeOnDateTime.toDate();
@@ -103,10 +109,6 @@ public class CommandSource extends AbstractPersistable<Long> {
this.resourceId = resourceId; this.resourceId = resourceId;
} }
public void updateSubResourceId(final Long subResourceId) {
this.subResourceId = subResourceId;
}
public void updateJsonTo(final String json) { public void updateJsonTo(final String json) {
this.commandAsJson = json; this.commandAsJson = json;
} }
@@ -123,18 +125,6 @@ public class CommandSource extends AbstractPersistable<Long> {
return this.commandAsJson; return this.commandAsJson;
} }
public String commandName() {
return this.apiOperation + '-' + this.resource;
}
public String resourceName() {
return this.resource;
}
public String operation() {
return this.apiOperation;
}
public String getActionName() { public String getActionName() {
return this.actionName; return this.actionName;
} }
@@ -147,23 +137,18 @@ public class CommandSource extends AbstractPersistable<Long> {
return this.actionName + "_" + this.entityName; return this.actionName + "_" + this.entityName;
} }
public String getResource() {
return this.resource;
}
public Long getResourceId() { public Long getResourceId() {
return this.resourceId; return this.resourceId;
} }
public String getSubResource() {
return this.subResource;
}
public Long getSubResourceId() {
return this.subResourceId;
}
public void markAsAwaitingApproval() { public void markAsAwaitingApproval() {
this.processingResult = CommandProcessingResultType.AWAITING_APPROVAL.getValue(); this.processingResult = CommandProcessingResultType.AWAITING_APPROVAL.getValue();
} }
public void updateForAudit(final Long officeId, final Long groupId, final Long clientId, final Long loanId) {
this.officeId = officeId;
this.groupId = groupId;
this.clientId = clientId;
this.loanId = loanId;
}
} }
@@ -3,43 +3,61 @@ package org.mifosplatform.commands.domain;
public class CommandWrapper { public class CommandWrapper {
private final Long commandId; private final Long commandId;
@SuppressWarnings("unused")
private final Long officeId;
private final Long groupId;
private final Long clientId;
private final Long loanId;
private final String actionName; private final String actionName;
private final String entityName; private final String entityName;
private final String apiOperation; private final String taskPermissionName;
private final String resource; private final Long entityId;
private final Long resourceId; private final String href;
private final String subResource; private final String json;
private final Long subResourceId; private final Long apptableId;
private final Long datatableId;
public static CommandWrapper wrap(final String actionName, final String enityName, final String apiOperation, final String resource, public static CommandWrapper wrap(final String actionName, final String enityName, final Long resourceId) {
final Long resourceId) { return new CommandWrapper(null, actionName, enityName, resourceId);
return new CommandWrapper(null, actionName, enityName, apiOperation, resource, resourceId, null, null);
}
public static CommandWrapper wrap(final String actionName, final String enityName, final String apiOperation, final String resource,
final Long resourceId, final String subResource, final Long subRescourceId) {
return new CommandWrapper(null, actionName, enityName, apiOperation, resource, resourceId, subResource, subRescourceId);
} }
public static CommandWrapper fromExistingCommand(final Long commandId, final String actionName, final String enityName, public static CommandWrapper fromExistingCommand(final Long commandId, final String actionName, final String enityName,
final String apiOperation, final String resource, final Long resourceId, final String subResource, final Long subRescourceId) { final Long resourceId) {
return new CommandWrapper(commandId, actionName, enityName, apiOperation, resource, resourceId, subResource, subRescourceId); return new CommandWrapper(commandId, actionName, enityName, resourceId);
} }
private CommandWrapper(final Long commandId, final String actionName, final String enityName, final String apiOperation, private CommandWrapper(final Long commandId, final String actionName, final String enityName, final Long resourceId) {
final String resource, final Long resourceId, final String subResource, final Long subResourceId) {
this.commandId = commandId; this.commandId = commandId;
this.officeId = null;
this.groupId = null;
this.clientId = null;
this.loanId = null;
this.actionName = actionName; this.actionName = actionName;
this.entityName = enityName; this.entityName = enityName;
this.apiOperation = apiOperation; this.taskPermissionName = actionName + "_" + entityName;
this.resource = resource; this.entityId = resourceId;
this.resourceId = resourceId; this.apptableId = null;
this.subResource = subResource; this.datatableId = null;
this.subResourceId = subResourceId; this.href = null;
this.json = null;
} }
public String commandName() { public CommandWrapper(final Long officeId, final Long groupId, final Long clientId, final Long loanId, final String actionName,
return this.apiOperation + '-' + this.resource; final String entityName, final Long entityId, final Long apptableId, final Long datatableId, final String href,
final String json) {
this.commandId = null;
this.officeId = officeId;
this.groupId = groupId;
this.clientId = clientId;
this.loanId = loanId;
this.actionName = actionName;
this.entityName = entityName;
this.taskPermissionName = actionName + "_" + entityName;
this.entityId = entityId;
this.apptableId = apptableId;
this.datatableId = datatableId;
this.href = href;
this.json = json;
} }
public Long commandId() { public Long commandId() {
@@ -55,117 +73,141 @@ public class CommandWrapper {
} }
public Long resourceId() { public Long resourceId() {
return this.resourceId; return this.entityId;
}
public String resourceName() {
return this.resource;
}
public Long subResourceId() {
return this.subResourceId;
}
public String subResourceName() {
return this.subResource;
} }
public String taskPermissionName() { public String taskPermissionName() {
return this.actionName + "_" + this.entityName; return this.actionName + "_" + this.entityName;
} }
public String operation() { public boolean isCreate() {
return this.apiOperation; return this.actionName.equalsIgnoreCase("CREATE");
} }
public boolean isCreate() { public String getTaskPermissionName() {
return this.apiOperation.equalsIgnoreCase("CREATE"); return this.taskPermissionName;
}
public String getHref() {
return this.href;
}
public String getJson() {
return this.json;
}
public String getEntityName() {
return this.entityName;
}
public Long getEntityId() {
return this.entityId;
}
public Long getGroupId() {
return this.groupId;
}
public Long getClientId() {
return this.clientId;
}
public Long getLoanId() {
return this.loanId;
}
public Long getApptableId() {
return this.apptableId;
}
public Long getDatatableId() {
return this.datatableId;
} }
public boolean isUpdate() { public boolean isUpdate() {
// permissions resource has special update which involves no resource. // permissions resource has special update which involves no resource.
return (isPermissionResource() && isUpdateOperation()) || (isCurrencyResource() && isUpdateOperation()) return (isPermissionResource() && isUpdateOperation()) || (isCurrencyResource() && isUpdateOperation())
|| (isUpdateOperation() && this.resourceId != null); || (isUpdateOperation() && this.entityId != null);
} }
private boolean isUpdateOperation() { private boolean isUpdateOperation() {
return this.apiOperation.equalsIgnoreCase("UPDATE"); return this.actionName.equalsIgnoreCase("UPDATE");
} }
public boolean isDelete() { public boolean isDelete() {
return this.apiOperation.equalsIgnoreCase("DELETE") && this.resourceId != null; return isDeleteOperation() && this.entityId != null;
}
private boolean isDeleteOperation() {
return this.actionName.equalsIgnoreCase("DELETE");
} }
public boolean isUpdateRolePermissions() { public boolean isUpdateRolePermissions() {
return this.apiOperation.equalsIgnoreCase("UPDATEPERMISSIONS") && this.resourceId != null; return this.actionName.equalsIgnoreCase("PERMISSIONS") && this.entityId != null;
} }
public boolean isPermissionResource() { public boolean isPermissionResource() {
return this.resource.equalsIgnoreCase("PERMISSIONS"); return this.entityName.equalsIgnoreCase("PERMISSION");
} }
public boolean isRoleResource() { public boolean isRoleResource() {
return this.resource.equalsIgnoreCase("ROLES"); return this.entityName.equalsIgnoreCase("ROLE");
} }
public boolean isUserResource() { public boolean isUserResource() {
return this.resource.equalsIgnoreCase("USERS"); return this.entityName.equalsIgnoreCase("USER");
} }
public boolean isCurrencyResource() { public boolean isCurrencyResource() {
return this.resource.equalsIgnoreCase("CURRENCIES"); return this.entityName.equalsIgnoreCase("CURRENCY");
} }
public boolean isCodeResource() { public boolean isCodeResource() {
return this.resource.equalsIgnoreCase("CODES"); return this.entityName.equalsIgnoreCase("CODE");
} }
public boolean isStaffResource() { public boolean isStaffResource() {
return this.resource.equalsIgnoreCase("STAFF"); return this.entityName.equalsIgnoreCase("STAFF");
} }
public boolean isFundResource() { public boolean isFundResource() {
return this.resource.equalsIgnoreCase("FUNDS"); return this.entityName.equalsIgnoreCase("FUND");
} }
public boolean isOfficeResource() { public boolean isOfficeResource() {
return this.resource.equalsIgnoreCase("OFFICES"); return this.entityName.equalsIgnoreCase("OFFICE");
} }
public boolean isOfficeTransactionResource() { public boolean isOfficeTransactionResource() {
return this.resource.equalsIgnoreCase("OFFICETRANSACTIONS"); return this.entityName.equalsIgnoreCase("OFFICETRANSACTION");
} }
public boolean isChargeDefinitionResource() { public boolean isChargeDefinitionResource() {
return this.resource.equalsIgnoreCase("CHARGES"); return this.entityName.equalsIgnoreCase("CHARGE");
} }
public boolean isLoanProductResource() { public boolean isLoanProductResource() {
return this.resource.equalsIgnoreCase("LOANPRODUCTS"); return this.entityName.equalsIgnoreCase("LOANPRODUCT");
} }
public boolean isClientResource() { public boolean isClientResource() {
return this.resource.equalsIgnoreCase("CLIENTS"); return this.entityName.equalsIgnoreCase("CLIENT");
} }
public boolean isClientIdentifierResource() { public boolean isClientIdentifierResource() {
return isClientResource() && isIdentifiersSubResource(); return this.entityName.equals("CLIENTIDENTIFIER");
} }
public boolean isClientNoteResource() { public boolean isClientNoteResource() {
return isClientResource() && isNotesSubResource(); return this.entityName.equals("CLIENTNOTE");
}
public boolean isNotesSubResource() {
return "NOTES".equalsIgnoreCase(this.subResource);
}
public boolean isIdentifiersSubResource() {
return "IDENTIFIERS".equalsIgnoreCase(this.subResource);
} }
public boolean isLoanResource() { public boolean isLoanResource() {
return this.resource.equalsIgnoreCase("LOANS"); return this.entityName.equalsIgnoreCase("LOAN");
}
public boolean isLoanChargeResource() {
return this.entityName.equalsIgnoreCase("LOANCHARGE");
} }
public boolean isApproveLoanApplication() { public boolean isApproveLoanApplication() {
@@ -221,7 +263,7 @@ public class CommandWrapper {
} }
public boolean isDeleteLoanCharge() { public boolean isDeleteLoanCharge() {
return this.actionName.equalsIgnoreCase("DELETE") && this.entityName.equalsIgnoreCase("LOANCHARGE"); return isDeleteOperation() && this.entityName.equalsIgnoreCase("LOANCHARGE");
} }
public boolean isUpdateLoanCharge() { public boolean isUpdateLoanCharge() {
@@ -241,14 +283,26 @@ public class CommandWrapper {
} }
public boolean isDatatableResource() { public boolean isDatatableResource() {
return this.resource.toUpperCase().startsWith("DATATABLES"); return this.apptableId != null;
}
public boolean isDeleteOneToOne() {
return isDatatableResource() && isDeleteOperation() && this.apptableId != null;
} }
public boolean isDeleteMultiple() { public boolean isDeleteMultiple() {
return isDatatableResource() && this.apiOperation.equalsIgnoreCase("DELETE_MULTIPLE"); return isDatatableResource() && isDeleteOperation() && this.apptableId != null && this.datatableId != null;
}
public boolean isUpdateOneToOne() {
return isDatatableResource() && isUpdateOperation() && this.apptableId != null;
} }
public boolean isUpdateMultiple() { public boolean isUpdateMultiple() {
return isDatatableResource() && this.apiOperation.equalsIgnoreCase("UPDATE_MULTIPLE"); return isDatatableResource() && isUpdateOperation() && this.apptableId != null && this.datatableId != null;
}
public String commandName() {
return this.actionName + "_" + this.entityName;
} }
} }
@@ -1,9 +1,9 @@
package org.mifosplatform.commands.handler; package org.mifosplatform.commands.handler;
import org.mifosplatform.infrastructure.core.api.JsonCommand; import org.mifosplatform.infrastructure.core.api.JsonCommand;
import org.mifosplatform.infrastructure.core.data.EntityIdentifier; import org.mifosplatform.infrastructure.core.data.CommandProcessingResult;
public interface NewCommandSourceHandler { public interface NewCommandSourceHandler {
EntityIdentifier processCommand(JsonCommand command); CommandProcessingResult processCommand(JsonCommand command);
} }
@@ -2,12 +2,12 @@ package org.mifosplatform.commands.service;
import org.mifosplatform.commands.domain.CommandWrapper; import org.mifosplatform.commands.domain.CommandWrapper;
import org.mifosplatform.infrastructure.core.api.JsonCommand; import org.mifosplatform.infrastructure.core.api.JsonCommand;
import org.mifosplatform.infrastructure.core.data.EntityIdentifier; import org.mifosplatform.infrastructure.core.data.CommandProcessingResult;
public interface CommandProcessingService { public interface CommandProcessingService {
EntityIdentifier processAndLogCommand(CommandWrapper wrapper, JsonCommand command, boolean isApprovedByChecker); CommandProcessingResult processAndLogCommand(CommandWrapper wrapper, JsonCommand command, boolean isApprovedByChecker);
EntityIdentifier logCommand(CommandWrapper wrapper, JsonCommand command); CommandProcessingResult logCommand(CommandWrapper wrapper, JsonCommand command);
} }
@@ -0,0 +1,385 @@
package org.mifosplatform.commands.service;
import org.mifosplatform.commands.domain.CommandWrapper;
public class CommandWrapperBuilder {
private Long officeId;
private Long groupId;
private Long clientId;
private Long loanId;
private String actionName;
private String entityName;
private Long entityId;
private String href;
private String json;
private Long apptableId;
private Long datatableId;
public CommandWrapper build() {
return new CommandWrapper(this.officeId, this.groupId, this.clientId, this.loanId, this.actionName, this.entityName, this.entityId, this.apptableId, this.datatableId,
this.href, this.json);
}
public CommandWrapperBuilder withEntityId(final Long withId) {
this.entityId = withId;
return this;
}
public CommandWrapperBuilder withLoanId(final Long withLoanId) {
this.loanId = withLoanId;
return this;
}
public CommandWrapperBuilder withClientId(final Long withClientId) {
this.clientId = withClientId;
return this;
}
public CommandWrapperBuilder withJson(final String withJson) {
this.json = withJson;
return this;
}
public CommandWrapperBuilder withUrl(final String withUrl) {
this.href = withUrl;
return this;
}
public CommandWrapperBuilder updatePermissions() {
this.actionName = "UPDATE";
this.entityName = "PERMISSION";
return this;
}
public CommandWrapperBuilder createRole() {
this.actionName = "CREATE";
this.entityName = "ROLE";
return this;
}
public CommandWrapperBuilder updateRole() {
this.actionName = "UPDATE";
this.entityName = "ROLE";
return this;
}
public CommandWrapperBuilder updateRolePermissions() {
this.actionName = "PERMISSIONS";
this.entityName = "ROLE";
return this;
}
public CommandWrapperBuilder createUser() {
this.actionName = "CREATE";
this.entityName = "USER";
return this;
}
public CommandWrapperBuilder updateUser() {
this.actionName = "UPDATE";
this.entityName = "USER";
return this;
}
public CommandWrapperBuilder deleteUser() {
this.actionName = "DELETE";
this.entityName = "USER";
return this;
}
public CommandWrapperBuilder createOffice() {
this.actionName = "CREATE";
this.entityName = "OFFICE";
return this;
}
public CommandWrapperBuilder updateOffice() {
this.actionName = "UPDATE";
this.entityName = "OFFICE";
return this;
}
public CommandWrapperBuilder createOfficeTransaction() {
this.actionName = "CREATE";
this.entityName = "OFFICETRANSACTION";
return this;
}
public CommandWrapperBuilder createStaff() {
this.actionName = "CREATE";
this.entityName = "STAFF";
return this;
}
public CommandWrapperBuilder updateStaff() {
this.actionName = "UPDATE";
this.entityName = "STAFF";
return this;
}
public CommandWrapperBuilder createFund() {
this.actionName = "CREATE";
this.entityName = "FUND";
return this;
}
public CommandWrapperBuilder updateFund() {
this.actionName = "UPDATE";
this.entityName = "FUND";
return this;
}
public CommandWrapperBuilder updateCurrencies() {
this.actionName = "UPDATE";
this.entityName = "CURRENCY";
return this;
}
public CommandWrapperBuilder createCode() {
this.actionName = "CREATE";
this.entityName = "CODE";
return this;
}
public CommandWrapperBuilder updateCode() {
this.actionName = "UPDATE";
this.entityName = "CODE";
return this;
}
public CommandWrapperBuilder deleteCode() {
this.actionName = "DELETE";
this.entityName = "CODE";
return this;
}
public CommandWrapperBuilder createCharge() {
this.actionName = "CREATE";
this.entityName = "CHARGE";
return this;
}
public CommandWrapperBuilder updateCharge() {
this.actionName = "UPDATE";
this.entityName = "CHARGE";
return this;
}
public CommandWrapperBuilder deleteCharge() {
this.actionName = "DELETE";
this.entityName = "CHARGE";
return this;
}
public CommandWrapperBuilder createLoanProduct() {
this.actionName = "CREATE";
this.entityName = "LOANPRODUCT";
return this;
}
public CommandWrapperBuilder updateLoanProduct() {
this.actionName = "UPDATE";
this.entityName = "LOANPRODUCT";
return this;
}
public CommandWrapperBuilder createClientIdentifier() {
this.actionName = "CREATE";
this.entityName = "CLIENTIDENTIFIER";
return this;
}
public CommandWrapperBuilder updateClientIdentifier() {
this.actionName = "UPDATE";
this.entityName = "CLIENTIDENTIFIER";
return this;
}
public CommandWrapperBuilder deleteClientIdentifier() {
this.actionName = "DELETE";
this.entityName = "CLIENTIDENTIFIER";
return this;
}
public CommandWrapperBuilder createClientNote() {
this.actionName = "CREATE";
this.entityName = "CLIENTNOTE";
return this;
}
public CommandWrapperBuilder updateClientNote() {
this.actionName = "UPDATE";
this.entityName = "CLIENTNOTE";
return this;
}
public CommandWrapperBuilder createClient() {
this.actionName = "CREATE";
this.entityName = "CLIENT";
return this;
}
public CommandWrapperBuilder updateClient() {
this.actionName = "UPDATE";
this.entityName = "CLIENT";
return this;
}
public CommandWrapperBuilder deleteClient() {
this.actionName = "DELETE";
this.entityName = "CLIENT";
return this;
}
public CommandWrapperBuilder createDatatable(final String datatable, final Long apptableId, final Long datatableId) {
this.apptableId = apptableId;
this.datatableId = datatableId;
this.actionName = "CREATE";
this.entityName = datatable;
return this;
}
public CommandWrapperBuilder updateDatatable(final String datatable, final Long apptableId, final Long datatableId) {
this.apptableId = apptableId;
this.datatableId = datatableId;
this.actionName = "UPDATE";
this.entityName = datatable;
return this;
}
public CommandWrapperBuilder deleteDatatable(final String datatable, final Long apptableId, final Long datatableId) {
this.apptableId = apptableId;
this.datatableId = datatableId;
this.actionName = "DELETE";
this.entityName = datatable;
return this;
}
public CommandWrapperBuilder createLoanCharge() {
this.actionName = "CREATE";
this.entityName = "LOANCHARGE";
return this;
}
public CommandWrapperBuilder updateLoanCharge() {
this.actionName = "UPDATE";
this.entityName = "LOANCHARGE";
return this;
}
public CommandWrapperBuilder waiveLoanCharge() {
this.actionName = "WAIVE";
this.entityName = "LOANCHARGE";
return this;
}
public CommandWrapperBuilder deleteLoanCharge() {
this.actionName = "DELETE";
this.entityName = "LOANCHARGE";
return this;
}
public CommandWrapperBuilder loanRepaymentTransaction() {
this.actionName = "REPAYMENT";
this.entityName = "LOAN";
return this;
}
public CommandWrapperBuilder waiveInterestPortionTransaction() {
this.actionName = "WAIVEINTERESTPORTION";
this.entityName = "LOAN";
return this;
}
public CommandWrapperBuilder writeOffLoanTransaction() {
this.actionName = "WRITEOFF";
this.entityName = "LOAN";
return this;
}
public CommandWrapperBuilder closeLoanAsRescheduledTransaction() {
this.actionName = "CLOSEASRESCHEDULED";
this.entityName = "LOAN";
return this;
}
public CommandWrapperBuilder closeLoanTransaction() {
this.actionName = "CLOSE";
this.entityName = "LOAN";
return this;
}
public CommandWrapperBuilder adjustTransaction() {
this.actionName = "ADJUST";
this.entityName = "LOAN";
return this;
}
public CommandWrapperBuilder createLoanApplication() {
this.actionName = "CREATE";
this.entityName = "LOAN";
return this;
}
public CommandWrapperBuilder updateLoanApplication() {
this.actionName = "UPDATE";
this.entityName = "LOAN";
return this;
}
public CommandWrapperBuilder deleteLoanApplication() {
this.actionName = "DELETE";
this.entityName = "LOAN";
return this;
}
public CommandWrapperBuilder rejectLoanApplication() {
this.actionName = "REJECT";
this.entityName = "LOAN";
return this;
}
public CommandWrapperBuilder withdrawLoanApplication() {
this.actionName = "WITHDRAW";
this.entityName = "LOAN";
return this;
}
public CommandWrapperBuilder approveLoanApplication() {
this.actionName = "APPROVE";
this.entityName = "LOAN";
return this;
}
public CommandWrapperBuilder disburseLoanApplication() {
this.actionName = "DISBURSE";
this.entityName = "LOAN";
return this;
}
public CommandWrapperBuilder undoLoanApplicationApproval() {
this.actionName = "APPROVALUNDO";
this.entityName = "LOAN";
return this;
}
public CommandWrapperBuilder undoLoanApplicationDisbursal() {
this.actionName = "DISBURSALUNDO";
this.entityName = "LOAN";
return this;
}
public CommandWrapperBuilder assignLoanOfficer() {
this.actionName = "UPDATELOANOFFICER";
this.entityName = "LOAN";
return this;
}
public CommandWrapperBuilder assignLoanOfficersInBulk() {
this.actionName = "BULKREASSIGN";
this.entityName = "LOAN";
return this;
}
}
@@ -1,15 +1,13 @@
package org.mifosplatform.commands.service; package org.mifosplatform.commands.service;
import org.mifosplatform.infrastructure.core.data.EntityIdentifier; import org.mifosplatform.commands.domain.CommandWrapper;
import org.mifosplatform.infrastructure.core.data.CommandProcessingResult;
public interface PortfolioCommandSourceWritePlatformService { public interface PortfolioCommandSourceWritePlatformService {
EntityIdentifier logCommandSource(String actionName, String entityName, String apiOperation, String resource, Long resourceId, String subResource, CommandProcessingResult logCommandSource(CommandWrapper commandRequest);
Long subRescourceId, String json);
EntityIdentifier logCommandSource(String actionName, String entityName, String apiOperation, String resource, Long resourceId, String json); CommandProcessingResult approveEntry(Long id);
EntityIdentifier approveEntry(Long id);
Long deleteEntry(Long makerCheckerId); Long deleteEntry(Long makerCheckerId);
} }
@@ -5,7 +5,7 @@ import org.mifosplatform.commands.domain.CommandSource;
import org.mifosplatform.commands.domain.CommandSourceRepository; import org.mifosplatform.commands.domain.CommandSourceRepository;
import org.mifosplatform.commands.domain.CommandWrapper; import org.mifosplatform.commands.domain.CommandWrapper;
import org.mifosplatform.infrastructure.core.api.JsonCommand; import org.mifosplatform.infrastructure.core.api.JsonCommand;
import org.mifosplatform.infrastructure.core.data.EntityIdentifier; import org.mifosplatform.infrastructure.core.data.CommandProcessingResult;
import org.mifosplatform.infrastructure.core.serialization.FromJsonHelper; import org.mifosplatform.infrastructure.core.serialization.FromJsonHelper;
import org.mifosplatform.infrastructure.security.service.PlatformSecurityContext; import org.mifosplatform.infrastructure.security.service.PlatformSecurityContext;
import org.mifosplatform.portfolio.client.service.RollbackTransactionAsCommandIsNotApprovedByCheckerException; import org.mifosplatform.portfolio.client.service.RollbackTransactionAsCommandIsNotApprovedByCheckerException;
@@ -34,46 +34,17 @@ public class PortfolioCommandSourceWritePlatformServiceImpl implements Portfolio
} }
@Override @Override
public EntityIdentifier logCommandSource(final String actionName, final String entityName, final String apiOperation, public CommandProcessingResult logCommandSource(final CommandWrapper wrapper) {
final String resource, final Long resourceId, final String subResource, final Long subRescourceId, final String json) {
final String taskPermissionName = actionName + "_" + entityName; context.authenticatedUser().validateHasPermissionTo(wrapper.getTaskPermissionName());
context.authenticatedUser().validateHasPermissionTo(taskPermissionName);
final CommandWrapper wrapper = CommandWrapper.wrap(actionName, entityName, apiOperation, resource, resourceId, subResource, final String json = wrapper.getJson();
subRescourceId); CommandProcessingResult result = null;
EntityIdentifier result = null;
try { try {
final JsonElement parsedCommand = this.fromApiJsonHelper.parse(json); final JsonElement parsedCommand = this.fromApiJsonHelper.parse(json);
final JsonCommand command = JsonCommand.from(json, parsedCommand, this.fromApiJsonHelper, entityName, resourceId, subRescourceId); final JsonCommand command = JsonCommand.from(json, parsedCommand, this.fromApiJsonHelper, wrapper.getEntityName(),
final boolean isApprovedByChecker = false; wrapper.getEntityId(), wrapper.getGroupId(), wrapper.getClientId(), wrapper.getLoanId(), wrapper.getApptableId(),
result = this.processAndLogCommandService.processAndLogCommand(wrapper, command, isApprovedByChecker); wrapper.getDatatableId());
} catch (RollbackTransactionAsCommandIsNotApprovedByCheckerException e) {
final String jsonToUse = StringUtils.defaultIfEmpty(e.getJsonOfChangesOnly(), json);
final JsonElement parsedCommand = this.fromApiJsonHelper.parse(jsonToUse);
final JsonCommand command = JsonCommand.from(jsonToUse, parsedCommand, this.fromApiJsonHelper, entityName, resourceId, subRescourceId);
result = this.processAndLogCommandService.logCommand(wrapper, command);
}
return result;
}
@Override
public EntityIdentifier logCommandSource(final String actionName, final String entityName, final String apiOperation, final String resource,
final Long resourceId, final String json) {
final String taskPermissionName = actionName + "_" + entityName;
context.authenticatedUser().validateHasPermissionTo(taskPermissionName);
final CommandWrapper wrapper = CommandWrapper.wrap(actionName, entityName, apiOperation, resource, resourceId);
EntityIdentifier result = null;
try {
final JsonElement parsedCommand = this.fromApiJsonHelper.parse(json);
final JsonCommand command = JsonCommand.from(json, parsedCommand, this.fromApiJsonHelper, entityName, resourceId, null);
final boolean isApprovedByChecker = false; final boolean isApprovedByChecker = false;
result = this.processAndLogCommandService.processAndLogCommand(wrapper, command, isApprovedByChecker); result = this.processAndLogCommandService.processAndLogCommand(wrapper, command, isApprovedByChecker);
@@ -82,7 +53,9 @@ public class PortfolioCommandSourceWritePlatformServiceImpl implements Portfolio
final String jsonToUse = StringUtils.defaultIfEmpty(e.getJsonOfChangesOnly(), json); final String jsonToUse = StringUtils.defaultIfEmpty(e.getJsonOfChangesOnly(), json);
final JsonElement parsedCommand = this.fromApiJsonHelper.parse(jsonToUse); final JsonElement parsedCommand = this.fromApiJsonHelper.parse(jsonToUse);
final JsonCommand command = JsonCommand.from(jsonToUse, parsedCommand, this.fromApiJsonHelper, entityName, resourceId, null); final JsonCommand command = JsonCommand.from(jsonToUse, parsedCommand, this.fromApiJsonHelper, wrapper.getEntityName(),
wrapper.getEntityId(), wrapper.getGroupId(), wrapper.getClientId(), wrapper.getLoanId(), wrapper.getApptableId(),
wrapper.getDatatableId());
result = this.processAndLogCommandService.logCommand(wrapper, command); result = this.processAndLogCommandService.logCommand(wrapper, command);
} }
@@ -91,19 +64,18 @@ public class PortfolioCommandSourceWritePlatformServiceImpl implements Portfolio
} }
@Override @Override
public EntityIdentifier approveEntry(final Long commandId) { public CommandProcessingResult approveEntry(final Long commandId) {
final CommandSource commandSourceInput = this.commandSourceRepository.findOne(commandId); final CommandSource commandSourceInput = this.commandSourceRepository.findOne(commandId);
context.authenticatedUser().validateHasCheckerPermissionTo(commandSourceInput.getPermissionCode()); context.authenticatedUser().validateHasCheckerPermissionTo(commandSourceInput.getPermissionCode());
final CommandWrapper wrapper = CommandWrapper.fromExistingCommand(commandId, commandSourceInput.getActionName(), final CommandWrapper wrapper = CommandWrapper.fromExistingCommand(commandId, commandSourceInput.getActionName(),
commandSourceInput.getEntityName(), commandSourceInput.operation(), commandSourceInput.resourceName(), commandSourceInput.getEntityName(), commandSourceInput.resourceId());
commandSourceInput.resourceId(), commandSourceInput.getSubResource(), commandSourceInput.getSubResourceId());
final JsonElement parsedCommand = this.fromApiJsonHelper.parse(commandSourceInput.json()); final JsonElement parsedCommand = this.fromApiJsonHelper.parse(commandSourceInput.json());
final JsonCommand command = JsonCommand.fromExistingCommand(commandId, commandSourceInput.json(), parsedCommand, final JsonCommand command = JsonCommand.fromExistingCommand(commandId, commandSourceInput.json(), parsedCommand,
this.fromApiJsonHelper, commandSourceInput.resourceId(), commandSourceInput.getSubResourceId()); this.fromApiJsonHelper, commandSourceInput.resourceId());
final boolean makerCheckerApproval = true; final boolean makerCheckerApproval = true;
return this.processAndLogCommandService.processAndLogCommand(wrapper, command, makerCheckerApproval); return this.processAndLogCommandService.processAndLogCommand(wrapper, command, makerCheckerApproval);
@@ -29,7 +29,7 @@ public class PortfolioCommandsReadPlatformServiceImpl implements PortfolioComman
private static final class CommandSourceMapper implements RowMapper<CommandSourceData> { private static final class CommandSourceMapper implements RowMapper<CommandSourceData> {
public String schema() { public String schema() {
return " mc.id as id, mc.api_operation as taskOperation, mc.api_resource as taskEntity, mc.resource_id as entityId," return " mc.id as id, mc.action_name as taskOperation, mc.entity_name as taskEntity, mc.resource_id as entityId,"
+ "mc.command_as_json as taskJson, mc.made_on_date as madeOnDate from m_portfolio_command_source mc "; + "mc.command_as_json as taskJson, mc.made_on_date as madeOnDate from m_portfolio_command_source mc ";
} }
@@ -54,7 +54,7 @@ public class PortfolioCommandsReadPlatformServiceImpl implements PortfolioComman
final CommandSourceMapper rm = new CommandSourceMapper(); final CommandSourceMapper rm = new CommandSourceMapper();
final String sql = "select " + rm.schema() final String sql = "select " + rm.schema()
+ " where mc.checker_id is null and mc.processing_result_enum = 2 order by mc.made_on_date DESC, mc.api_resource ASC, mc.api_operation ASC"; + " where mc.checker_id is null and mc.processing_result_enum = 2 order by mc.made_on_date DESC, mc.api_resource ASC, mc.action_name ASC";
return this.jdbcTemplate.query(sql, rm, new Object[] {}); return this.jdbcTemplate.query(sql, rm, new Object[] {});
} }
@@ -74,7 +74,7 @@ public class PortfolioCommandsReadPlatformServiceImpl implements PortfolioComman
final CommandSourceMapper rm = new CommandSourceMapper(); final CommandSourceMapper rm = new CommandSourceMapper();
final String sql = "select " final String sql = "select "
+ rm.schema() + rm.schema()
+ " where mc.api_resource like ? and mc.resource_id = ? and mc.checker_id is null and mc.processing_result_enum = 2 order by mc.made_on_date DESC, mc.api_operation ASC"; + " where mc.entity_name like ? and mc.resource_id = ? and mc.checker_id is null and mc.processing_result_enum = 2 order by mc.made_on_date DESC, mc.action_name ASC";
return this.jdbcTemplate.query(sql, rm, new Object[] { apiResource, resourceId }); return this.jdbcTemplate.query(sql, rm, new Object[] { apiResource, resourceId });
} }
@@ -9,7 +9,8 @@ import org.mifosplatform.commands.domain.CommandWrapper;
import org.mifosplatform.commands.exception.UnsupportedCommandException; import org.mifosplatform.commands.exception.UnsupportedCommandException;
import org.mifosplatform.commands.handler.NewCommandSourceHandler; import org.mifosplatform.commands.handler.NewCommandSourceHandler;
import org.mifosplatform.infrastructure.core.api.JsonCommand; import org.mifosplatform.infrastructure.core.api.JsonCommand;
import org.mifosplatform.infrastructure.core.data.EntityIdentifier; import org.mifosplatform.infrastructure.core.data.CommandProcessingResult;
import org.mifosplatform.infrastructure.core.data.CommandProcessingResultBuilder;
import org.mifosplatform.infrastructure.core.serialization.ToApiJsonSerializer; import org.mifosplatform.infrastructure.core.serialization.ToApiJsonSerializer;
import org.mifosplatform.infrastructure.security.service.PlatformSecurityContext; import org.mifosplatform.infrastructure.security.service.PlatformSecurityContext;
import org.mifosplatform.organisation.monetary.service.ConfigurationDomainService; import org.mifosplatform.organisation.monetary.service.ConfigurationDomainService;
@@ -44,10 +45,10 @@ public class SynchronousCommandProcessingService implements CommandProcessingSer
@Transactional @Transactional
@Override @Override
public EntityIdentifier processAndLogCommand(final CommandWrapper wrapper, final JsonCommand command, final boolean isApprovedByChecker) { public CommandProcessingResult processAndLogCommand(final CommandWrapper wrapper, final JsonCommand command, final boolean isApprovedByChecker) {
final NewCommandSourceHandler handler = findCommandHandler(wrapper); final NewCommandSourceHandler handler = findCommandHandler(wrapper);
final EntityIdentifier result = handler.processCommand(command); final CommandProcessingResult result = handler.processCommand(command);
final AppUser maker = context.authenticatedUser(); final AppUser maker = context.authenticatedUser();
@@ -59,7 +60,7 @@ public class SynchronousCommandProcessingService implements CommandProcessingSer
commandSourceResult = CommandSource.fullEntryFrom(wrapper, command, maker); commandSourceResult = CommandSource.fullEntryFrom(wrapper, command, maker);
} }
commandSourceResult.updateResourceId(result.resourceId()); commandSourceResult.updateResourceId(result.resourceId());
commandSourceResult.updateSubResourceId(result.subResourceId()); commandSourceResult.updateForAudit(result.getOfficeId(), result.getGroupId(), result.getClientId(), result.getLoanId());
String changesOnlyJson = null; String changesOnlyJson = null;
if (result.hasChanges()) { if (result.hasChanges()) {
@@ -75,14 +76,15 @@ public class SynchronousCommandProcessingService implements CommandProcessingSer
commandSourceRepository.save(commandSourceResult); commandSourceRepository.save(commandSourceResult);
} }
if (this.configurationDomainService.isMakerCheckerEnabledForTask(wrapper.taskPermissionName()) && !isApprovedByChecker) { throw new RollbackTransactionAsCommandIsNotApprovedByCheckerException(changesOnlyJson); } if (this.configurationDomainService.isMakerCheckerEnabledForTask(wrapper.taskPermissionName()) && !isApprovedByChecker) { throw new RollbackTransactionAsCommandIsNotApprovedByCheckerException(
changesOnlyJson); }
return result; return result;
} }
@Transactional @Transactional
@Override @Override
public EntityIdentifier logCommand(final CommandWrapper wrapper, final JsonCommand command) { public CommandProcessingResult logCommand(final CommandWrapper wrapper, final JsonCommand command) {
final AppUser maker = context.authenticatedUser(); final AppUser maker = context.authenticatedUser();
@@ -92,7 +94,7 @@ public class SynchronousCommandProcessingService implements CommandProcessingSer
commandSourceRepository.save(commandSourceResult); commandSourceRepository.save(commandSourceResult);
} }
return EntityIdentifier.resourceResult(commandSourceResult.resourceId(), commandSourceResult.getId()); return new CommandProcessingResultBuilder().withCommandId(command.commandId()).withEntityId(commandSourceResult.resourceId()).build();
} }
private NewCommandSourceHandler findCommandHandler(final CommandWrapper wrapper) { private NewCommandSourceHandler findCommandHandler(final CommandWrapper wrapper) {
@@ -103,17 +105,16 @@ public class SynchronousCommandProcessingService implements CommandProcessingSer
handler = applicationContext.getBean("createDatatableEntryCommandHandler", NewCommandSourceHandler.class); handler = applicationContext.getBean("createDatatableEntryCommandHandler", NewCommandSourceHandler.class);
} else if (wrapper.isUpdateMultiple()) { } else if (wrapper.isUpdateMultiple()) {
handler = applicationContext.getBean("updateOneToManyDatatableEntryCommandHandler", NewCommandSourceHandler.class); handler = applicationContext.getBean("updateOneToManyDatatableEntryCommandHandler", NewCommandSourceHandler.class);
} else if (wrapper.isUpdate()) { } else if (wrapper.isUpdateOneToOne()) {
handler = applicationContext.getBean("updateOneToOneDatatableEntryCommandHandler", NewCommandSourceHandler.class); handler = applicationContext.getBean("updateOneToOneDatatableEntryCommandHandler", NewCommandSourceHandler.class);
} else if (wrapper.isDeleteMultiple()) { } else if (wrapper.isDeleteMultiple()) {
handler = applicationContext.getBean("deleteOneToManyDatatableEntryCommandHandler", NewCommandSourceHandler.class); handler = applicationContext.getBean("deleteOneToManyDatatableEntryCommandHandler", NewCommandSourceHandler.class);
} else if (wrapper.isDelete()) { } else if (wrapper.isDeleteOneToOne()) {
handler = applicationContext.getBean("deleteOneToOneDatatableEntryCommandHandler", NewCommandSourceHandler.class); handler = applicationContext.getBean("deleteOneToOneDatatableEntryCommandHandler", NewCommandSourceHandler.class);
} else { } else {
throw new UnsupportedCommandException(wrapper.commandName()); throw new UnsupportedCommandException(wrapper.commandName());
} }
} } else if (wrapper.isClientNoteResource()) {
else if (wrapper.isClientNoteResource()) {
if (wrapper.isCreate()) { if (wrapper.isCreate()) {
handler = applicationContext.getBean("createClientNoteCommandHandler", NewCommandSourceHandler.class); handler = applicationContext.getBean("createClientNoteCommandHandler", NewCommandSourceHandler.class);
} else if (wrapper.isUpdate()) { } else if (wrapper.isUpdate()) {
@@ -132,7 +133,7 @@ public class SynchronousCommandProcessingService implements CommandProcessingSer
} else { } else {
throw new UnsupportedCommandException(wrapper.commandName()); throw new UnsupportedCommandException(wrapper.commandName());
} }
} else if (wrapper.isClientResource() && !wrapper.isNotesSubResource() && !wrapper.isIdentifiersSubResource()) { } else if (wrapper.isClientResource() && !wrapper.isClientNoteResource() && !wrapper.isClientIdentifierResource()) {
if (wrapper.isCreate()) { if (wrapper.isCreate()) {
handler = applicationContext.getBean("createClientCommandHandler", NewCommandSourceHandler.class); handler = applicationContext.getBean("createClientCommandHandler", NewCommandSourceHandler.class);
} else if (wrapper.isUpdate()) { } else if (wrapper.isUpdate()) {
@@ -226,7 +227,6 @@ public class SynchronousCommandProcessingService implements CommandProcessingSer
throw new UnsupportedCommandException(wrapper.commandName()); throw new UnsupportedCommandException(wrapper.commandName());
} }
} else if (wrapper.isLoanResource()) { } else if (wrapper.isLoanResource()) {
if (wrapper.isApproveLoanApplication()) { if (wrapper.isApproveLoanApplication()) {
handler = applicationContext.getBean("loanApplicationApprovalCommandHandler", NewCommandSourceHandler.class); handler = applicationContext.getBean("loanApplicationApprovalCommandHandler", NewCommandSourceHandler.class);
} else if (wrapper.isUndoApprovalOfLoanApplication()) { } else if (wrapper.isUndoApprovalOfLoanApplication()) {
@@ -251,14 +251,6 @@ public class SynchronousCommandProcessingService implements CommandProcessingSer
handler = applicationContext.getBean("closeLoanCommandHandler", NewCommandSourceHandler.class); handler = applicationContext.getBean("closeLoanCommandHandler", NewCommandSourceHandler.class);
} else if (wrapper.isCloseLoanAsRescheduled()) { } else if (wrapper.isCloseLoanAsRescheduled()) {
handler = applicationContext.getBean("closeLoanAsRescheduledCommandHandler", NewCommandSourceHandler.class); handler = applicationContext.getBean("closeLoanAsRescheduledCommandHandler", NewCommandSourceHandler.class);
} else if (wrapper.isAddLoanCharge()) {
handler = applicationContext.getBean("addLoanChargeCommandHandler", NewCommandSourceHandler.class);
} else if (wrapper.isDeleteLoanCharge()) {
handler = applicationContext.getBean("deleteLoanChargeCommandHandler", NewCommandSourceHandler.class);
} else if (wrapper.isUpdateLoanCharge()) {
handler = applicationContext.getBean("updateLoanChargeCommandHandler", NewCommandSourceHandler.class);
} else if (wrapper.isWaiveLoanCharge()) {
handler = applicationContext.getBean("waiveLoanChargeCommandHandler", NewCommandSourceHandler.class);
} else if (wrapper.isUpdateLoanOfficer()) { } else if (wrapper.isUpdateLoanOfficer()) {
handler = applicationContext.getBean("updateLoanOfficerCommandHandler", NewCommandSourceHandler.class); handler = applicationContext.getBean("updateLoanOfficerCommandHandler", NewCommandSourceHandler.class);
} else if (wrapper.isBulkUpdateLoanOfficer()) { } else if (wrapper.isBulkUpdateLoanOfficer()) {
@@ -272,6 +264,16 @@ public class SynchronousCommandProcessingService implements CommandProcessingSer
} else { } else {
throw new UnsupportedCommandException(wrapper.commandName()); throw new UnsupportedCommandException(wrapper.commandName());
} }
} else if (wrapper.isLoanChargeResource()) {
if (wrapper.isAddLoanCharge()) {
handler = applicationContext.getBean("addLoanChargeCommandHandler", NewCommandSourceHandler.class);
} else if (wrapper.isDeleteLoanCharge()) {
handler = applicationContext.getBean("deleteLoanChargeCommandHandler", NewCommandSourceHandler.class);
} else if (wrapper.isUpdateLoanCharge()) {
handler = applicationContext.getBean("updateLoanChargeCommandHandler", NewCommandSourceHandler.class);
} else if (wrapper.isWaiveLoanCharge()) {
handler = applicationContext.getBean("waiveLoanChargeCommandHandler", NewCommandSourceHandler.class);
}
} else { } else {
throw new UnsupportedCommandException(wrapper.commandName()); throw new UnsupportedCommandException(wrapper.commandName());
} }
@@ -17,11 +17,13 @@ import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriInfo; import javax.ws.rs.core.UriInfo;
import org.mifosplatform.commands.domain.CommandWrapper;
import org.mifosplatform.commands.service.CommandWrapperBuilder;
import org.mifosplatform.commands.service.PortfolioCommandSourceWritePlatformService; import org.mifosplatform.commands.service.PortfolioCommandSourceWritePlatformService;
import org.mifosplatform.infrastructure.codes.data.CodeData; import org.mifosplatform.infrastructure.codes.data.CodeData;
import org.mifosplatform.infrastructure.codes.service.CodeReadPlatformService; import org.mifosplatform.infrastructure.codes.service.CodeReadPlatformService;
import org.mifosplatform.infrastructure.core.api.ApiRequestParameterHelper; import org.mifosplatform.infrastructure.core.api.ApiRequestParameterHelper;
import org.mifosplatform.infrastructure.core.data.EntityIdentifier; import org.mifosplatform.infrastructure.core.data.CommandProcessingResult;
import org.mifosplatform.infrastructure.core.serialization.ApiRequestJsonSerializationSettings; import org.mifosplatform.infrastructure.core.serialization.ApiRequestJsonSerializationSettings;
import org.mifosplatform.infrastructure.core.serialization.DefaultToApiJsonSerializer; import org.mifosplatform.infrastructure.core.serialization.DefaultToApiJsonSerializer;
import org.mifosplatform.infrastructure.security.service.PlatformSecurityContext; import org.mifosplatform.infrastructure.security.service.PlatformSecurityContext;
@@ -75,8 +77,10 @@ public class CodesApiResource {
@Produces({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON })
public String createCode(final String apiRequestBodyAsJson) { public String createCode(final String apiRequestBodyAsJson) {
final EntityIdentifier result = this.commandsSourceWritePlatformService.logCommandSource("CREATE", "CODE", "CREATE", "codes", null, final CommandWrapper commandRequest = new CommandWrapperBuilder().createCode().withUrl("/codes").withJson(apiRequestBodyAsJson)
apiRequestBodyAsJson); .build();
final CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest);
return this.toApiJsonSerializer.serialize(result); return this.toApiJsonSerializer.serialize(result);
} }
@@ -99,8 +103,10 @@ public class CodesApiResource {
@Produces({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON })
public String updateCode(@PathParam("codeId") final Long codeId, final String apiRequestBodyAsJson) { public String updateCode(@PathParam("codeId") final Long codeId, final String apiRequestBodyAsJson) {
final EntityIdentifier result = this.commandsSourceWritePlatformService.logCommandSource("UPDATE", "CODE", "UPDATE", "codes", final CommandWrapper commandRequest = new CommandWrapperBuilder().updateCode().withUrl("/codes").withEntityId(codeId).withJson(apiRequestBodyAsJson)
codeId, apiRequestBodyAsJson); .build();
final CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest);
return this.toApiJsonSerializer.serialize(result); return this.toApiJsonSerializer.serialize(result);
} }
@@ -111,8 +117,10 @@ public class CodesApiResource {
@Produces({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON })
public String deleteCode(@PathParam("codeId") final Long codeId) { public String deleteCode(@PathParam("codeId") final Long codeId) {
final EntityIdentifier result = this.commandsSourceWritePlatformService.logCommandSource("DELETE", "CODE", "DELETE", "codes", final CommandWrapper commandRequest = new CommandWrapperBuilder().deleteCode().withUrl("/codes").withEntityId(codeId).withJson("{}")
codeId, "{}"); .build();
final CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest);
return this.toApiJsonSerializer.serialize(result); return this.toApiJsonSerializer.serialize(result);
} }
@@ -3,7 +3,7 @@ package org.mifosplatform.infrastructure.codes.handler;
import org.mifosplatform.commands.handler.NewCommandSourceHandler; import org.mifosplatform.commands.handler.NewCommandSourceHandler;
import org.mifosplatform.infrastructure.codes.service.CodeWritePlatformService; import org.mifosplatform.infrastructure.codes.service.CodeWritePlatformService;
import org.mifosplatform.infrastructure.core.api.JsonCommand; import org.mifosplatform.infrastructure.core.api.JsonCommand;
import org.mifosplatform.infrastructure.core.data.EntityIdentifier; import org.mifosplatform.infrastructure.core.data.CommandProcessingResult;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
@@ -20,7 +20,7 @@ public class CreateCodeCommandHandler implements NewCommandSourceHandler {
@Transactional @Transactional
@Override @Override
public EntityIdentifier processCommand(final JsonCommand command) { public CommandProcessingResult processCommand(final JsonCommand command) {
return this.writePlatformService.createCode(command); return this.writePlatformService.createCode(command);
} }
@@ -3,7 +3,7 @@ package org.mifosplatform.infrastructure.codes.handler;
import org.mifosplatform.commands.handler.NewCommandSourceHandler; import org.mifosplatform.commands.handler.NewCommandSourceHandler;
import org.mifosplatform.infrastructure.codes.service.CodeWritePlatformService; import org.mifosplatform.infrastructure.codes.service.CodeWritePlatformService;
import org.mifosplatform.infrastructure.core.api.JsonCommand; import org.mifosplatform.infrastructure.core.api.JsonCommand;
import org.mifosplatform.infrastructure.core.data.EntityIdentifier; import org.mifosplatform.infrastructure.core.data.CommandProcessingResult;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
@@ -20,8 +20,8 @@ public class DeleteCodeCommandHandler implements NewCommandSourceHandler {
@Transactional @Transactional
@Override @Override
public EntityIdentifier processCommand(final JsonCommand command) { public CommandProcessingResult processCommand(final JsonCommand command) {
return this.writePlatformService.deleteCode(command.resourceId()); return this.writePlatformService.deleteCode(command.entityId());
} }
} }
@@ -3,7 +3,7 @@ package org.mifosplatform.infrastructure.codes.handler;
import org.mifosplatform.commands.handler.NewCommandSourceHandler; import org.mifosplatform.commands.handler.NewCommandSourceHandler;
import org.mifosplatform.infrastructure.codes.service.CodeWritePlatformService; import org.mifosplatform.infrastructure.codes.service.CodeWritePlatformService;
import org.mifosplatform.infrastructure.core.api.JsonCommand; import org.mifosplatform.infrastructure.core.api.JsonCommand;
import org.mifosplatform.infrastructure.core.data.EntityIdentifier; import org.mifosplatform.infrastructure.core.data.CommandProcessingResult;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
@@ -20,8 +20,8 @@ public class UpdateCodeCommandHandler implements NewCommandSourceHandler {
@Transactional @Transactional
@Override @Override
public EntityIdentifier processCommand(final JsonCommand command) { public CommandProcessingResult processCommand(final JsonCommand command) {
return this.writePlatformService.updateCode(command.resourceId(), command); return this.writePlatformService.updateCode(command.entityId(), command);
} }
} }
@@ -1,13 +1,13 @@
package org.mifosplatform.infrastructure.codes.service; package org.mifosplatform.infrastructure.codes.service;
import org.mifosplatform.infrastructure.core.api.JsonCommand; import org.mifosplatform.infrastructure.core.api.JsonCommand;
import org.mifosplatform.infrastructure.core.data.EntityIdentifier; import org.mifosplatform.infrastructure.core.data.CommandProcessingResult;
public interface CodeWritePlatformService { public interface CodeWritePlatformService {
EntityIdentifier createCode(JsonCommand command); CommandProcessingResult createCode(JsonCommand command);
EntityIdentifier updateCode(Long codeId, JsonCommand command); CommandProcessingResult updateCode(Long codeId, JsonCommand command);
EntityIdentifier deleteCode(Long codeId); CommandProcessingResult deleteCode(Long codeId);
} }
@@ -9,7 +9,8 @@ import org.mifosplatform.infrastructure.codes.exception.CodeNotFoundException;
import org.mifosplatform.infrastructure.codes.exception.SystemDefinedCodeCannotBeChangedException; import org.mifosplatform.infrastructure.codes.exception.SystemDefinedCodeCannotBeChangedException;
import org.mifosplatform.infrastructure.codes.serialization.CodeCommandFromApiJsonDeserializer; import org.mifosplatform.infrastructure.codes.serialization.CodeCommandFromApiJsonDeserializer;
import org.mifosplatform.infrastructure.core.api.JsonCommand; import org.mifosplatform.infrastructure.core.api.JsonCommand;
import org.mifosplatform.infrastructure.core.data.EntityIdentifier; import org.mifosplatform.infrastructure.core.data.CommandProcessingResult;
import org.mifosplatform.infrastructure.core.data.CommandProcessingResultBuilder;
import org.mifosplatform.infrastructure.core.exception.PlatformDataIntegrityException; import org.mifosplatform.infrastructure.core.exception.PlatformDataIntegrityException;
import org.mifosplatform.infrastructure.security.service.PlatformSecurityContext; import org.mifosplatform.infrastructure.security.service.PlatformSecurityContext;
import org.slf4j.Logger; import org.slf4j.Logger;
@@ -38,7 +39,7 @@ public class CodeWritePlatformServiceJpaRepositoryImpl implements CodeWritePlatf
@Transactional @Transactional
@Override @Override
public EntityIdentifier createCode(final JsonCommand command) { public CommandProcessingResult createCode(final JsonCommand command) {
try { try {
context.authenticatedUser(); context.authenticatedUser();
@@ -49,15 +50,15 @@ public class CodeWritePlatformServiceJpaRepositoryImpl implements CodeWritePlatf
final Code code = Code.fromJson(command); final Code code = Code.fromJson(command);
this.codeRepository.save(code); this.codeRepository.save(code);
return EntityIdentifier.resourceResult(code.getId(), null); return new CommandProcessingResultBuilder().withCommandId(command.commandId()).withEntityId(code.getId()).build();
} catch (DataIntegrityViolationException dve) { } catch (DataIntegrityViolationException dve) {
return EntityIdentifier.empty(); return CommandProcessingResult.empty();
} }
} }
@Transactional @Transactional
@Override @Override
public EntityIdentifier updateCode(final Long codeId, final JsonCommand command) { public CommandProcessingResult updateCode(final Long codeId, final JsonCommand command) {
try { try {
context.authenticatedUser(); context.authenticatedUser();
@@ -71,7 +72,7 @@ public class CodeWritePlatformServiceJpaRepositoryImpl implements CodeWritePlatf
this.codeRepository.save(code); this.codeRepository.save(code);
} }
return EntityIdentifier.withChanges(codeId, changes); return new CommandProcessingResultBuilder().withCommandId(command.commandId()).withEntityId(codeId).with(changes).build();
} catch (DataIntegrityViolationException dve) { } catch (DataIntegrityViolationException dve) {
handleCodeDataIntegrityIssues(command, dve); handleCodeDataIntegrityIssues(command, dve);
return null; return null;
@@ -80,7 +81,7 @@ public class CodeWritePlatformServiceJpaRepositoryImpl implements CodeWritePlatf
@Transactional @Transactional
@Override @Override
public EntityIdentifier deleteCode(final Long codeId) { public CommandProcessingResult deleteCode(final Long codeId) {
context.authenticatedUser(); context.authenticatedUser();
@@ -89,7 +90,7 @@ public class CodeWritePlatformServiceJpaRepositoryImpl implements CodeWritePlatf
this.codeRepository.delete(code); this.codeRepository.delete(code);
return new EntityIdentifier(code.getId()); return new CommandProcessingResultBuilder().withEntityId(codeId).build();
} }
private Code retrieveCodeBy(final Long codeId) { private Code retrieveCodeBy(final Long codeId) {
@@ -29,28 +29,39 @@ public final class JsonCommand {
private final FromJsonHelper fromApiJsonHelper; private final FromJsonHelper fromApiJsonHelper;
private final Long commandId; private final Long commandId;
private final Long resourceId; private final Long resourceId;
private final Long subResourceId; private final Long groupId;
private final Long clientId;
private final Long loanId;
private final String entityName; private final String entityName;
private final Long apptableId;
private final Long datatableId;
public static JsonCommand from(final String jsonCommand, final JsonElement parsedCommand, final FromJsonHelper fromApiJsonHelper, public static JsonCommand from(final String jsonCommand, final JsonElement parsedCommand, final FromJsonHelper fromApiJsonHelper,
final String entityName, final Long resourceId, final Long subResourceId) { final String entityName, final Long resourceId, final Long groupId, final Long clientId, final Long loanId,
return new JsonCommand(null, jsonCommand, parsedCommand, fromApiJsonHelper, entityName, resourceId, subResourceId); final Long apptableId, final Long datatableId) {
return new JsonCommand(null, jsonCommand, parsedCommand, fromApiJsonHelper, entityName, resourceId, groupId, clientId, loanId,
apptableId, datatableId);
} }
public static JsonCommand fromExistingCommand(final Long commandId, final String jsonCommand, final JsonElement parsedCommand, final FromJsonHelper fromApiJsonHelper, public static JsonCommand fromExistingCommand(final Long commandId, final String jsonCommand, final JsonElement parsedCommand,
final Long resourceId, final Long subResourceId) { final FromJsonHelper fromApiJsonHelper, final Long resourceId) {
return new JsonCommand(commandId, jsonCommand, parsedCommand, fromApiJsonHelper, null, resourceId, subResourceId); return new JsonCommand(commandId, jsonCommand, parsedCommand, fromApiJsonHelper, null, resourceId, null, null, null, null, null);
} }
public JsonCommand(final Long commandId, final String jsonCommand, final JsonElement parsedCommand, final FromJsonHelper fromApiJsonHelper, public JsonCommand(final Long commandId, final String jsonCommand, final JsonElement parsedCommand,
final String entityName, final Long resourceId, final Long subResourceId) { final FromJsonHelper fromApiJsonHelper, final String entityName, final Long resourceId, final Long groupId,
final Long clientId, final Long loanId, final Long apptableId, final Long datatableId) {
this.commandId = commandId; this.commandId = commandId;
this.jsonCommand = jsonCommand; this.jsonCommand = jsonCommand;
this.parsedCommand = parsedCommand; this.parsedCommand = parsedCommand;
this.fromApiJsonHelper = fromApiJsonHelper; this.fromApiJsonHelper = fromApiJsonHelper;
this.entityName = entityName; this.entityName = entityName;
this.resourceId = resourceId; this.resourceId = resourceId;
this.subResourceId = subResourceId; this.groupId = groupId;
this.clientId = clientId;
this.loanId = loanId;
this.apptableId = apptableId;
this.datatableId = datatableId;
} }
public String json() { public String json() {
@@ -69,12 +80,28 @@ public final class JsonCommand {
return this.entityName; return this.entityName;
} }
public Long resourceId() { public Long entityId() {
return this.resourceId; return this.resourceId;
} }
public Long subResourceId() { public Long getGroupId() {
return this.subResourceId; return this.groupId;
}
public Long getClientId() {
return this.clientId;
}
public Long getLoanId() {
return this.loanId;
}
public Long getApptableId() {
return this.apptableId;
}
public Long getDatatableId() {
return this.datatableId;
} }
private boolean differenceExists(final LocalDate baseValue, final LocalDate workingCopyValue) { private boolean differenceExists(final LocalDate baseValue, final LocalDate workingCopyValue) {
@@ -0,0 +1,124 @@
package org.mifosplatform.infrastructure.core.data;
import java.util.HashMap;
import java.util.Map;
/**
* Represents the successful result of an REST API call that results in
* processing a command.
*/
public class CommandProcessingResult {
private Long commandId;
private Long officeId;
private final Long groupId;
private final Long clientId;
private final Long loanId;
private Long resourceId;
private Map<String, Object> changes;
public static CommandProcessingResult fromDetails(final Long commandId, final Long officeId, final Long groupId, final Long clientId,
final Long loanId, final Long entityId, final Map<String, Object> changes) {
return new CommandProcessingResult(commandId, officeId, groupId, clientId, loanId, entityId, changes);
}
public static CommandProcessingResult commandOnlyResult(final Long commandId) {
return new CommandProcessingResult(null, null, commandId, null);
}
public static CommandProcessingResult resourceResult(final Long resourceId, final Long commandId) {
return new CommandProcessingResult(resourceId, null, commandId, null);
}
public static CommandProcessingResult resourceResult(final Long resourceId, final Long commandId, final Map<String, Object> changes) {
return new CommandProcessingResult(resourceId, null, commandId, changes);
}
public static CommandProcessingResult subResourceResult(final Long resourceId, final Long subResourceId, final Long commandId) {
return new CommandProcessingResult(resourceId, subResourceId, commandId, null);
}
public static CommandProcessingResult subResourceResult(final Long resourceId, final Long subResourceId, final Long commandId,
final Map<String, Object> changes) {
return new CommandProcessingResult(resourceId, subResourceId, commandId, changes);
}
public static CommandProcessingResult withChanges(final Long resourceId, final Map<String, Object> changes) {
return new CommandProcessingResult(resourceId, null, null, changes);
}
public static CommandProcessingResult empty() {
return new CommandProcessingResult(Long.valueOf(-1), Long.valueOf(-1), Long.valueOf(-1), null);
}
public CommandProcessingResult(final Long entityId) {
this.resourceId = entityId;
this.officeId = null;
this.groupId = null;
this.clientId = null;
this.loanId = null;
this.changes = new HashMap<String, Object>();
}
private CommandProcessingResult(final Long commandId, final Long officeId, final Long groupId, final Long clientId, final Long loanId,
final Long resourceId, final Map<String, Object> changesOnly) {
this.commandId = commandId;
this.officeId = officeId;
this.groupId = groupId;
this.clientId = clientId;
this.loanId = loanId;
this.resourceId = resourceId;
this.changes = changesOnly;
}
private CommandProcessingResult(final Long resourceId, final Long officeId, final Long commandId, final Map<String, Object> changesOnly) {
this.resourceId = resourceId;
this.officeId = officeId;
this.groupId = null;
this.clientId = null;
this.loanId = null;
this.commandId = commandId;
this.changes = changesOnly;
}
public Long commandId() {
return this.commandId;
}
public Long resourceId() {
return this.resourceId;
}
public Long getOfficeId() {
return this.officeId;
}
public void setOfficeId(Long officeId) {
this.officeId = officeId;
}
public Long getGroupId() {
return this.groupId;
}
public Long getClientId() {
return this.clientId;
}
public Long getLoanId() {
return this.loanId;
}
public Map<String, Object> getChanges() {
Map<String, Object> checkIfEmpty = null;
if (this.changes != null && !this.changes.isEmpty()) {
checkIfEmpty = this.changes;
}
return checkIfEmpty;
}
public boolean hasChanges() {
final boolean noChanges = this.changes == null || this.changes.isEmpty();
return !noChanges;
}
}
@@ -0,0 +1,57 @@
package org.mifosplatform.infrastructure.core.data;
import java.util.Map;
/**
* Represents the successful result of an REST API call that results in
* processing a command.
*/
public class CommandProcessingResultBuilder {
private Long commandId;
private Long officeId;
private Long groupId;
private Long clientId;
private Long loanId;
private Long entityId;
private Map<String, Object> changes;
public CommandProcessingResult build() {
return CommandProcessingResult.fromDetails(commandId, officeId, groupId, clientId, loanId, entityId, changes);
}
public CommandProcessingResultBuilder withCommandId(final Long withCommandId) {
this.commandId = withCommandId;
return this;
}
public CommandProcessingResultBuilder with(final Map<String, Object> withChanges) {
this.changes = withChanges;
return this;
}
public CommandProcessingResultBuilder withEntityId(final Long withEntityId) {
this.entityId = withEntityId;
return this;
}
public CommandProcessingResultBuilder withOfficeId(final Long withOfficeId) {
this.officeId = withOfficeId;
return this;
}
public CommandProcessingResultBuilder withClientId(final Long withClientId) {
this.clientId = withClientId;
return this;
}
public CommandProcessingResultBuilder withGroupId(final Long withGroupId) {
this.groupId = withGroupId;
return this;
}
public CommandProcessingResultBuilder withLoanId(final Long withLoanId) {
this.loanId = withLoanId;
return this;
}
}
@@ -1,87 +0,0 @@
package org.mifosplatform.infrastructure.core.data;
import java.util.HashMap;
import java.util.Map;
/**
* Represents the successful result of an REST API call.
*
* FIXME - KW - Rename to CommandProcessingResult - make immutable
*/
public class EntityIdentifier {
private Long commandId;
private Long resourceId;
private Long subResourceId;
private Map<String, Object> changes;
public static EntityIdentifier commandOnlyResult(final Long commandId) {
return new EntityIdentifier(null, null, commandId, null);
}
public static EntityIdentifier resourceResult(final Long resourceId, final Long commandId) {
return new EntityIdentifier(resourceId, null, commandId, null);
}
public static EntityIdentifier resourceResult(final Long resourceId, final Long commandId, final Map<String, Object> changes) {
return new EntityIdentifier(resourceId, null, commandId, changes);
}
public static EntityIdentifier subResourceResult(final Long resourceId, final Long subResourceId, final Long commandId) {
return new EntityIdentifier(resourceId, subResourceId, commandId, null);
}
public static EntityIdentifier subResourceResult(final Long resourceId, final Long subResourceId, final Long commandId, final Map<String, Object> changes) {
return new EntityIdentifier(resourceId, subResourceId, commandId, changes);
}
public static EntityIdentifier withChanges(final Long resourceId, final Map<String, Object> changes) {
return new EntityIdentifier(resourceId, null, null, changes);
}
public static EntityIdentifier empty() {
return new EntityIdentifier(Long.valueOf(-1), Long.valueOf(-1), Long.valueOf(-1), null);
}
protected EntityIdentifier() {
//
}
public EntityIdentifier(final Long entityId) {
this.resourceId = entityId;
this.changes = new HashMap<String, Object>();
}
private EntityIdentifier(final Long resourceId, final Long subResourceId, final Long commandId, final Map<String, Object> changesOnly) {
this.resourceId = resourceId;
this.subResourceId = subResourceId;
this.commandId = commandId;
this.changes = changesOnly;
}
public Long commandId() {
return this.commandId;
}
public Long resourceId() {
return this.resourceId;
}
public Long subResourceId() {
return this.subResourceId;
}
public Map<String, Object> getChanges() {
Map<String, Object> checkIfEmpty = null;
if (this.changes != null && !this.changes.isEmpty()) {
checkIfEmpty = this.changes;
}
return checkIfEmpty;
}
public boolean hasChanges() {
final boolean noChanges = this.changes == null || this.changes.isEmpty();
return !noChanges;
}
}
@@ -15,9 +15,11 @@ import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriInfo; import javax.ws.rs.core.UriInfo;
import org.mifosplatform.commands.domain.CommandWrapper;
import org.mifosplatform.commands.service.CommandWrapperBuilder;
import org.mifosplatform.commands.service.PortfolioCommandSourceWritePlatformService; import org.mifosplatform.commands.service.PortfolioCommandSourceWritePlatformService;
import org.mifosplatform.infrastructure.core.api.ApiParameterHelper; import org.mifosplatform.infrastructure.core.api.ApiParameterHelper;
import org.mifosplatform.infrastructure.core.data.EntityIdentifier; import org.mifosplatform.infrastructure.core.data.CommandProcessingResult;
import org.mifosplatform.infrastructure.core.serialization.ToApiJsonSerializer; import org.mifosplatform.infrastructure.core.serialization.ToApiJsonSerializer;
import org.mifosplatform.infrastructure.dataqueries.data.DatatableData; import org.mifosplatform.infrastructure.dataqueries.data.DatatableData;
import org.mifosplatform.infrastructure.dataqueries.data.GenericResultsetData; import org.mifosplatform.infrastructure.dataqueries.data.GenericResultsetData;
@@ -70,7 +72,7 @@ public class DataTableApiResource {
this.readWriteNonCoreDataService.registerDatatable(datatable, apptable); this.readWriteNonCoreDataService.registerDatatable(datatable, apptable);
return this.toApiJsonSerializer.serialize(EntityIdentifier.empty()); return this.toApiJsonSerializer.serialize(CommandProcessingResult.empty());
} }
@POST @POST
@@ -81,7 +83,7 @@ public class DataTableApiResource {
this.readWriteNonCoreDataService.deregisterDatatable(datatable); this.readWriteNonCoreDataService.deregisterDatatable(datatable);
return this.toApiJsonSerializer.serialize(EntityIdentifier.empty()); return this.toApiJsonSerializer.serialize(CommandProcessingResult.empty());
} }
@GET @GET
@@ -139,10 +141,12 @@ public class DataTableApiResource {
public String newDatatableEntry(@PathParam("datatable") final String datatable, @PathParam("apptableId") final Long apptableId, public String newDatatableEntry(@PathParam("datatable") final String datatable, @PathParam("apptableId") final Long apptableId,
final String apiRequestBodyAsJson) { final String apiRequestBodyAsJson) {
final EntityIdentifier entityIdentifier = this.commandsSourceWritePlatformService.logCommandSource("CREATE", datatable, "CREATE", final CommandWrapper commandRequest = new CommandWrapperBuilder().createDatatable(datatable, apptableId, null)
"datatables/" + datatable, apptableId, apiRequestBodyAsJson); .withUrl("/datatables/" + datatable).withJson(apiRequestBodyAsJson).build();
return this.toApiJsonSerializer.serialize(entityIdentifier); final CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest);
return this.toApiJsonSerializer.serialize(result);
} }
@PUT @PUT
@@ -152,10 +156,12 @@ public class DataTableApiResource {
public String updateDatatableEntryOnetoOne(@PathParam("datatable") final String datatable, public String updateDatatableEntryOnetoOne(@PathParam("datatable") final String datatable,
@PathParam("apptableId") final Long apptableId, final String apiRequestBodyAsJson) { @PathParam("apptableId") final Long apptableId, final String apiRequestBodyAsJson) {
final EntityIdentifier entityIdentifier = this.commandsSourceWritePlatformService.logCommandSource("UPDATE", datatable, "UPDATE", final CommandWrapper commandRequest = new CommandWrapperBuilder().updateDatatable(datatable, apptableId, null)
"datatables/" + datatable, apptableId, apiRequestBodyAsJson); .withUrl("/datatables/" + datatable).withJson(apiRequestBodyAsJson).build();
return this.toApiJsonSerializer.serialize(entityIdentifier); final CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest);
return this.toApiJsonSerializer.serialize(result);
} }
@PUT @PUT
@@ -166,10 +172,12 @@ public class DataTableApiResource {
@PathParam("apptableId") final Long apptableId, @PathParam("datatableId") final Long datatableId, @PathParam("apptableId") final Long apptableId, @PathParam("datatableId") final Long datatableId,
final String apiRequestBodyAsJson) { final String apiRequestBodyAsJson) {
final EntityIdentifier entityIdentifier = this.commandsSourceWritePlatformService.logCommandSource("UPDATE", datatable, final CommandWrapper commandRequest = new CommandWrapperBuilder().updateDatatable(datatable, apptableId, datatableId)
"UPDATE_MULTIPLE", "datatables/" + datatable, apptableId, "datatables/" + datatable, datatableId, apiRequestBodyAsJson); .withUrl("/datatables/" + datatable + "/" + apptableId).withJson(apiRequestBodyAsJson).build();
return this.toApiJsonSerializer.serialize(entityIdentifier); final CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest);
return this.toApiJsonSerializer.serialize(result);
} }
@DELETE @DELETE
@@ -178,10 +186,12 @@ public class DataTableApiResource {
@Produces({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON })
public String deleteDatatableEntries(@PathParam("datatable") final String datatable, @PathParam("apptableId") final Long apptableId) { public String deleteDatatableEntries(@PathParam("datatable") final String datatable, @PathParam("apptableId") final Long apptableId) {
final EntityIdentifier entityIdentifier = this.commandsSourceWritePlatformService.logCommandSource("DELETE", datatable, "DELETE", final CommandWrapper commandRequest = new CommandWrapperBuilder().deleteDatatable(datatable, apptableId, null)
"datatables/" + datatable, apptableId, "{}"); .withUrl("/datatables/" + datatable).withJson("{}").build();
return this.toApiJsonSerializer.serialize(entityIdentifier); final CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest);
return this.toApiJsonSerializer.serialize(result);
} }
@DELETE @DELETE
@@ -191,9 +201,11 @@ public class DataTableApiResource {
public String deleteDatatableEntries(@PathParam("datatable") final String datatable, @PathParam("apptableId") final Long apptableId, public String deleteDatatableEntries(@PathParam("datatable") final String datatable, @PathParam("apptableId") final Long apptableId,
@PathParam("datatableId") final Long datatableId) { @PathParam("datatableId") final Long datatableId) {
final EntityIdentifier entityIdentifier = this.commandsSourceWritePlatformService.logCommandSource("DELETE", datatable, final CommandWrapper commandRequest = new CommandWrapperBuilder().deleteDatatable(datatable, apptableId, datatableId)
"DELETE_MULTIPLE", "datatables/" + datatable, apptableId, "datatables/" + datatable, datatableId, "{}"); .withUrl("/datatables/" + datatable + "/" + apptableId).withJson("{}").build();
return this.toApiJsonSerializer.serialize(entityIdentifier); final CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest);
return this.toApiJsonSerializer.serialize(result);
} }
} }
@@ -2,32 +2,31 @@ package org.mifosplatform.infrastructure.dataqueries.handler;
import org.mifosplatform.commands.handler.NewCommandSourceHandler; import org.mifosplatform.commands.handler.NewCommandSourceHandler;
import org.mifosplatform.infrastructure.core.api.JsonCommand; import org.mifosplatform.infrastructure.core.api.JsonCommand;
import org.mifosplatform.infrastructure.core.data.EntityIdentifier; import org.mifosplatform.infrastructure.core.data.CommandProcessingResult;
import org.mifosplatform.infrastructure.core.data.CommandProcessingResultBuilder;
import org.mifosplatform.infrastructure.dataqueries.service.ReadWriteNonCoreDataService; import org.mifosplatform.infrastructure.dataqueries.service.ReadWriteNonCoreDataService;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
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 CreateDatatableEntryCommandHandler implements public class CreateDatatableEntryCommandHandler implements NewCommandSourceHandler {
NewCommandSourceHandler {
private final ReadWriteNonCoreDataService writePlatformService; private final ReadWriteNonCoreDataService writePlatformService;
@Autowired @Autowired
public CreateDatatableEntryCommandHandler( public CreateDatatableEntryCommandHandler(final ReadWriteNonCoreDataService writePlatformService) {
final ReadWriteNonCoreDataService writePlatformService) {
this.writePlatformService = writePlatformService; this.writePlatformService = writePlatformService;
} }
@Transactional @Transactional
@Override @Override
public EntityIdentifier processCommand(final JsonCommand command) { public CommandProcessingResult processCommand(final JsonCommand command) {
this.writePlatformService.newDatatableEntry(command.entityName(), this.writePlatformService.newDatatableEntry(command.entityName(), command.getApptableId(), command);
command.resourceId(), command);
return EntityIdentifier.resourceResult(command.resourceId(), // FIXME - kw - need to find office and either group/client/loan that
command.commandId()); // this datatable is against.
return new CommandProcessingResultBuilder().withCommandId(command.commandId()).withEntityId(command.getApptableId()).build();
} }
} }
@@ -2,31 +2,29 @@ package org.mifosplatform.infrastructure.dataqueries.handler;
import org.mifosplatform.commands.handler.NewCommandSourceHandler; import org.mifosplatform.commands.handler.NewCommandSourceHandler;
import org.mifosplatform.infrastructure.core.api.JsonCommand; import org.mifosplatform.infrastructure.core.api.JsonCommand;
import org.mifosplatform.infrastructure.core.data.EntityIdentifier; import org.mifosplatform.infrastructure.core.data.CommandProcessingResult;
import org.mifosplatform.infrastructure.core.data.CommandProcessingResultBuilder;
import org.mifosplatform.infrastructure.dataqueries.service.ReadWriteNonCoreDataService; import org.mifosplatform.infrastructure.dataqueries.service.ReadWriteNonCoreDataService;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
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 DeleteOneToManyDatatableEntryCommandHandler implements public class DeleteOneToManyDatatableEntryCommandHandler implements NewCommandSourceHandler {
NewCommandSourceHandler {
private final ReadWriteNonCoreDataService writePlatformService; private final ReadWriteNonCoreDataService writePlatformService;
@Autowired @Autowired
public DeleteOneToManyDatatableEntryCommandHandler( public DeleteOneToManyDatatableEntryCommandHandler(final ReadWriteNonCoreDataService writePlatformService) {
final ReadWriteNonCoreDataService writePlatformService) {
this.writePlatformService = writePlatformService; this.writePlatformService = writePlatformService;
} }
@Transactional @Transactional
@Override @Override
public EntityIdentifier processCommand(final JsonCommand command) { public CommandProcessingResult processCommand(final JsonCommand command) {
this.writePlatformService.deleteDatatableEntry(command.entityName(), command.resourceId(), command.subResourceId()); this.writePlatformService.deleteDatatableEntry(command.entityName(), command.getApptableId(), command.getDatatableId());
return EntityIdentifier.subResourceResult(command.resourceId(), command.subResourceId(), return new CommandProcessingResultBuilder().withCommandId(command.commandId()).withEntityId(command.getDatatableId()).build();
command.commandId());
} }
} }
@@ -2,31 +2,29 @@ package org.mifosplatform.infrastructure.dataqueries.handler;
import org.mifosplatform.commands.handler.NewCommandSourceHandler; import org.mifosplatform.commands.handler.NewCommandSourceHandler;
import org.mifosplatform.infrastructure.core.api.JsonCommand; import org.mifosplatform.infrastructure.core.api.JsonCommand;
import org.mifosplatform.infrastructure.core.data.EntityIdentifier; import org.mifosplatform.infrastructure.core.data.CommandProcessingResult;
import org.mifosplatform.infrastructure.core.data.CommandProcessingResultBuilder;
import org.mifosplatform.infrastructure.dataqueries.service.ReadWriteNonCoreDataService; import org.mifosplatform.infrastructure.dataqueries.service.ReadWriteNonCoreDataService;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
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 DeleteOneToOneDatatableEntryCommandHandler implements public class DeleteOneToOneDatatableEntryCommandHandler implements NewCommandSourceHandler {
NewCommandSourceHandler {
private final ReadWriteNonCoreDataService writePlatformService; private final ReadWriteNonCoreDataService writePlatformService;
@Autowired @Autowired
public DeleteOneToOneDatatableEntryCommandHandler( public DeleteOneToOneDatatableEntryCommandHandler(final ReadWriteNonCoreDataService writePlatformService) {
final ReadWriteNonCoreDataService writePlatformService) {
this.writePlatformService = writePlatformService; this.writePlatformService = writePlatformService;
} }
@Transactional @Transactional
@Override @Override
public EntityIdentifier processCommand(final JsonCommand command) { public CommandProcessingResult processCommand(final JsonCommand command) {
this.writePlatformService.deleteDatatableEntries(command.entityName(), command.resourceId()); this.writePlatformService.deleteDatatableEntries(command.entityName(), command.getApptableId());
return EntityIdentifier.resourceResult(command.resourceId(), return new CommandProcessingResultBuilder().withCommandId(command.commandId()).withEntityId(command.getApptableId()).build();
command.commandId());
} }
} }
@@ -4,31 +4,30 @@ import java.util.Map;
import org.mifosplatform.commands.handler.NewCommandSourceHandler; import org.mifosplatform.commands.handler.NewCommandSourceHandler;
import org.mifosplatform.infrastructure.core.api.JsonCommand; import org.mifosplatform.infrastructure.core.api.JsonCommand;
import org.mifosplatform.infrastructure.core.data.EntityIdentifier; import org.mifosplatform.infrastructure.core.data.CommandProcessingResult;
import org.mifosplatform.infrastructure.core.data.CommandProcessingResultBuilder;
import org.mifosplatform.infrastructure.dataqueries.service.ReadWriteNonCoreDataService; import org.mifosplatform.infrastructure.dataqueries.service.ReadWriteNonCoreDataService;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
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 UpdateOneToManyDatatableEntryCommandHandler implements public class UpdateOneToManyDatatableEntryCommandHandler implements NewCommandSourceHandler {
NewCommandSourceHandler {
private final ReadWriteNonCoreDataService writePlatformService; private final ReadWriteNonCoreDataService writePlatformService;
@Autowired @Autowired
public UpdateOneToManyDatatableEntryCommandHandler( public UpdateOneToManyDatatableEntryCommandHandler(final ReadWriteNonCoreDataService writePlatformService) {
final ReadWriteNonCoreDataService writePlatformService) {
this.writePlatformService = writePlatformService; this.writePlatformService = writePlatformService;
} }
@Transactional @Transactional
@Override @Override
public EntityIdentifier processCommand(final JsonCommand command) { public CommandProcessingResult processCommand(final JsonCommand command) {
Map<String, Object> changes = this.writePlatformService.updateDatatableEntryOneToMany(command.entityName(), command.resourceId(), command.subResourceId(), command); final Map<String, Object> changes = this.writePlatformService.updateDatatableEntryOneToMany(command.entityName(),
command.getApptableId(), command.getDatatableId(), command);
return EntityIdentifier.subResourceResult(command.resourceId(), command.subResourceId(), return new CommandProcessingResultBuilder().withCommandId(command.commandId()).withEntityId(command.getDatatableId()).with(changes).build();
command.commandId(), changes);
} }
} }
@@ -4,7 +4,8 @@ import java.util.Map;
import org.mifosplatform.commands.handler.NewCommandSourceHandler; import org.mifosplatform.commands.handler.NewCommandSourceHandler;
import org.mifosplatform.infrastructure.core.api.JsonCommand; import org.mifosplatform.infrastructure.core.api.JsonCommand;
import org.mifosplatform.infrastructure.core.data.EntityIdentifier; import org.mifosplatform.infrastructure.core.data.CommandProcessingResult;
import org.mifosplatform.infrastructure.core.data.CommandProcessingResultBuilder;
import org.mifosplatform.infrastructure.dataqueries.service.ReadWriteNonCoreDataService; import org.mifosplatform.infrastructure.dataqueries.service.ReadWriteNonCoreDataService;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@@ -22,10 +23,12 @@ public class UpdateOneToOneDatatableEntryCommandHandler implements NewCommandSou
@Transactional @Transactional
@Override @Override
public EntityIdentifier processCommand(final JsonCommand command) { public CommandProcessingResult processCommand(final JsonCommand command) {
Map<String, Object> changes = this.writePlatformService.updateDatatableEntryOneToOne(command.entityName(), command.resourceId(), command); final Map<String, Object> changes = this.writePlatformService.updateDatatableEntryOneToOne(command.entityName(), command.getApptableId(),
command);
return EntityIdentifier.resourceResult(command.resourceId(), command.commandId(), changes); return new CommandProcessingResultBuilder().withCommandId(command.commandId()).withEntityId(command.getApptableId()).with(changes)
.build();
} }
} }
@@ -35,19 +35,15 @@ import org.springframework.stereotype.Service;
import com.google.gson.reflect.TypeToken; import com.google.gson.reflect.TypeToken;
@Service @Service
public class ReadWriteNonCoreDataServiceImpl implements public class ReadWriteNonCoreDataServiceImpl implements ReadWriteNonCoreDataService {
ReadWriteNonCoreDataService {
private final static Logger logger = LoggerFactory private final static Logger logger = LoggerFactory.getLogger(ReadWriteNonCoreDataServiceImpl.class);
.getLogger(ReadWriteNonCoreDataServiceImpl.class);
private final PlatformSecurityContext context; private final PlatformSecurityContext context;
private final FromJsonHelper fromJsonHelper; private final FromJsonHelper fromJsonHelper;
@Autowired @Autowired
public ReadWriteNonCoreDataServiceImpl( public ReadWriteNonCoreDataServiceImpl(final PlatformSecurityContext context, final FromJsonHelper fromJsonHelper) {
final PlatformSecurityContext context,
final FromJsonHelper fromJsonHelper) {
this.context = context; this.context = context;
this.fromJsonHelper = fromJsonHelper; this.fromJsonHelper = fromJsonHelper;
} }
@@ -65,36 +61,24 @@ public class ReadWriteNonCoreDataServiceImpl implements
andClause = " and application_table_name = '" + appTable + "'"; andClause = " and application_table_name = '" + appTable + "'";
} }
// PERMITTED datatables // PERMITTED datatables
String sql = "select application_table_name, registered_table_name" String sql = "select application_table_name, registered_table_name" + " from x_registered_table " + " where exists"
+ " from x_registered_table " + " (select 'f'" + " from m_appuser_role ur " + " join m_role r on r.id = ur.role_id"
+ " where exists" + " left join m_role_permission rp on rp.role_id = r.id" + " left join m_permission p on p.id = rp.permission_id"
+ " (select 'f'" + " where ur.appuser_id = " + context.authenticatedUser().getId()
+ " from m_appuser_role ur "
+ " join m_role r on r.id = ur.role_id"
+ " left join m_role_permission rp on rp.role_id = r.id"
+ " left join m_permission p on p.id = rp.permission_id"
+ " where ur.appuser_id = "
+ context.authenticatedUser().getId()
+ " and (p.code in ('ALL_FUNCTIONS', 'ALL_FUNCTIONS_READ') or p.code = concat('READ_', registered_table_name))) " + " and (p.code in ('ALL_FUNCTIONS', 'ALL_FUNCTIONS_READ') or p.code = concat('READ_', registered_table_name))) "
+ andClause + andClause + " order by application_table_name, registered_table_name";
+ " order by application_table_name, registered_table_name";
String sqlErrorMsg = "Application Table Name: " + appTable + " sql: " String sqlErrorMsg = "Application Table Name: " + appTable + " sql: " + sql;
+ sql; CachedRowSet rs = genericDataService.getCachedResultSet(sql, sqlErrorMsg);
CachedRowSet rs = genericDataService.getCachedResultSet(sql,
sqlErrorMsg);
List<DatatableData> datatables = new ArrayList<DatatableData>(); List<DatatableData> datatables = new ArrayList<DatatableData>();
try { try {
while (rs.next()) { while (rs.next()) {
datatables.add(new DatatableData(rs datatables.add(new DatatableData(rs.getString("application_table_name"), rs.getString("registered_table_name")));
.getString("application_table_name"), rs
.getString("registered_table_name")));
} }
} catch (SQLException e) { } catch (SQLException e) {
throw new PlatformDataIntegrityException("error.msg.sql.error", throw new PlatformDataIntegrityException("error.msg.sql.error", e.getMessage(), sqlErrorMsg);
e.getMessage(), sqlErrorMsg);
} }
return datatables; return datatables;
@@ -103,8 +87,6 @@ public class ReadWriteNonCoreDataServiceImpl implements
@Override @Override
public void registerDatatable(final String datatable, final String appTable) { public void registerDatatable(final String datatable, final String appTable) {
// long startTime = System.currentTimeMillis();
validateAppTable(appTable); validateAppTable(appTable);
String createPermission = "'CREATE_" + datatable + "'"; String createPermission = "'CREATE_" + datatable + "'";
@@ -115,68 +97,31 @@ public class ReadWriteNonCoreDataServiceImpl implements
String deletePermission = "'DELETE_" + datatable + "'"; String deletePermission = "'DELETE_" + datatable + "'";
String deletePermissionChecker = "'DELETE_" + datatable + "_CHECKER'"; String deletePermissionChecker = "'DELETE_" + datatable + "_CHECKER'";
// TODO - put in batch command later // TODO - put in batch command later
String sql = "insert into x_registered_table (registered_table_name, application_table_name) values ('" String sql = "insert into x_registered_table (registered_table_name, application_table_name) values ('" + datatable + "', '"
+ datatable + "', '" + appTable + "')"; + appTable + "')";
genericDataService.updateSQL(sql, "SQL: " + sql); genericDataService.updateSQL(sql, "SQL: " + sql);
/* /*
* add all permissions, including checker permissions for maintenance * add all permissions, including checker permissions for maintenance
* tasks * tasks
*/ */
sql = "insert into m_permission (grouping, code, action_name, entity_name, can_maker_checker) values " sql = "insert into m_permission (grouping, code, action_name, entity_name, can_maker_checker) values " + "('datatable', "
+ "('datatable', " + createPermission + ", 'CREATE', '" + datatable + "', true)," + "('datatable', " + createPermissionChecker
+ createPermission + ", 'CREATE', '" + datatable + "', false)," + "('datatable', " + readPermission + ", 'READ', '" + datatable + "', false),"
+ ", 'CREATE', '" + "('datatable', " + updatePermission + ", 'UPDATE', '" + datatable + "', true)," + "('datatable', "
+ datatable + updatePermissionChecker + ", 'UPDATE', '" + datatable + "', false)," + "('datatable', " + deletePermission
+ "', true)," + ", 'DELETE', '" + datatable + "', true)," + "('datatable', " + deletePermissionChecker + ", 'DELETE', '" + datatable
+ "('datatable', " + "', false)";
+ createPermissionChecker
+ ", 'CREATE', '"
+ datatable
+ "', false),"
+ "('datatable', "
+ readPermission
+ ", 'READ', '"
+ datatable
+ "', false),"
+ "('datatable', "
+ updatePermission
+ ", 'UPDATE', '"
+ datatable
+ "', true),"
+ "('datatable', "
+ updatePermissionChecker
+ ", 'UPDATE', '"
+ datatable
+ "', false),"
+ "('datatable', "
+ deletePermission
+ ", 'DELETE', '"
+ datatable
+ "', true),"
+ "('datatable', "
+ deletePermissionChecker
+ ", 'DELETE', '"
+ datatable + "', false)";
genericDataService.updateSQL(sql, "SQL: " + sql); genericDataService.updateSQL(sql, "SQL: " + sql);
// long elapsed = System.currentTimeMillis() - startTime;
// logger.info("FINISHING registerDatatable: Elapsed Time: " +
// elapsed + " - datatable: " + datatable
// + " application table: " + appTable);
} }
@Override @Override
public void deregisterDatatable(final String datatable) { public void deregisterDatatable(final String datatable) {
// long startTime = System.currentTimeMillis();
// TODO - put in batch command later // TODO - put in batch command later
String permissionList = "('CREATE_" + datatable + "', 'CREATE_" String permissionList = "('CREATE_" + datatable + "', 'CREATE_" + datatable + "_CHECKER', 'READ_" + datatable + "', 'UPDATE_"
+ datatable + "_CHECKER', 'READ_" + datatable + "', 'UPDATE_" + datatable + "', 'UPDATE_" + datatable + "_CHECKER', 'DELETE_" + datatable + "', 'DELETE_" + datatable + "_CHECKER')";
+ datatable + "', 'UPDATE_" + datatable + "_CHECKER', 'DELETE_"
+ datatable + "', 'DELETE_" + datatable + "_CHECKER')";
String sql = "delete from m_role_permission where m_role_permission.permission_id in (select id from m_permission where code in " String sql = "delete from m_role_permission where m_role_permission.permission_id in (select id from m_permission where code in "
+ permissionList + ")"; + permissionList + ")";
@@ -185,71 +130,43 @@ public class ReadWriteNonCoreDataServiceImpl implements
sql = "delete from m_permission where code in " + permissionList; sql = "delete from m_permission where code in " + permissionList;
genericDataService.updateSQL(sql, "SQL: " + sql); genericDataService.updateSQL(sql, "SQL: " + sql);
sql = "delete from x_registered_table where registered_table_name = '" sql = "delete from x_registered_table where registered_table_name = '" + datatable + "'";
+ datatable + "'";
genericDataService.updateSQL(sql, "SQL: " + sql); genericDataService.updateSQL(sql, "SQL: " + sql);
// long elapsed = System.currentTimeMillis() - startTime;
// logger.info("FINISHING deregisterDatatable: Elapsed Time: " +
// elapsed + " - datatable: " + datatable);
} }
@Override @Override
public void newDatatableEntry(final String datatable, public void newDatatableEntry(final String datatable, final Long appTableId, final JsonCommand command) {
final Long appTableId, final JsonCommand command) { String appTable = getWithinScopeApplicationTableName(datatable, appTableId);
// long startTime = System.currentTimeMillis();
String appTable = getWithinScopeApplicationTableName(datatable,
appTableId);
List<ResultsetColumnHeader> columnHeaders = getDatatableResultsetColumnHeaders(datatable); List<ResultsetColumnHeader> columnHeaders = getDatatableResultsetColumnHeaders(datatable);
final Type typeOfMap = new TypeToken<Map<String, String>>() { final Type typeOfMap = new TypeToken<Map<String, String>>() {}.getType();
}.getType(); Map<String, String> dataParams = this.fromJsonHelper.extractDataMap(typeOfMap, command.json());
Map<String, String> dataParams = this.fromJsonHelper.extractDataMap(
typeOfMap, command.json());
String sql = getAddSql(columnHeaders, datatable, getFKField(appTable), String sql = getAddSql(columnHeaders, datatable, getFKField(appTable), appTableId, dataParams);
appTableId, dataParams);
genericDataService.updateSQL(sql, "SQL: " + sql); genericDataService.updateSQL(sql, "SQL: " + sql);
// long elapsed = System.currentTimeMillis() - startTime;
// logger.info("FINISHING newDatatableEntry: Elapsed Time: " +
// elapsed + " - datatable: " + datatable + " id: "
// + appTableId);
} }
@Override @Override
public Map<String, Object> updateDatatableEntryOneToOne( public Map<String, Object> updateDatatableEntryOneToOne(final String datatable, final Long appTableId, final JsonCommand command) {
final String datatable, final Long appTableId,
final JsonCommand command) {
GenericResultsetData grs = retrieveDataTableGenericResultSet(datatable, GenericResultsetData grs = retrieveDataTableGenericResultSet(datatable, appTableId, null, null);
appTableId, null, null);
if (grs.getData().size() == 0) if (grs.getData().size() == 0) throw new DataTableNotFoundException(datatable, appTableId);
throw new DataTableNotFoundException(datatable, appTableId);
if (grs.getData().size() > 1) if (grs.getData().size() > 1)
throw new PlatformDataIntegrityException( throw new PlatformDataIntegrityException("error.msg.attempting.multiple.update", "Application Table: " + datatable
"error.msg.attempting.multiple.update", + " Foreign Key Id: " + appTableId);
"Application Table: " + datatable + " Foreign Key Id: "
+ appTableId);
String fkName = getFKField(getApplicationTableName(datatable)); String fkName = getFKField(getApplicationTableName(datatable));
final Type typeOfMap = new TypeToken<Map<String, String>>() { final Type typeOfMap = new TypeToken<Map<String, String>>() {}.getType();
}.getType(); Map<String, String> dataParams = this.fromJsonHelper.extractDataMap(typeOfMap, command.json());
Map<String, String> dataParams = this.fromJsonHelper.extractDataMap(
typeOfMap, command.json());
final Map<String, Object> changes = getAffectedAndChangedColumns(grs, final Map<String, Object> changes = getAffectedAndChangedColumns(grs, dataParams, fkName);
dataParams, fkName);
if (changes.size() == 0) if (changes.size() == 0) return changes;
return changes;
String sql = getUpdateSql(datatable, fkName, appTableId, changes); String sql = getUpdateSql(datatable, fkName, appTableId, changes);
@@ -263,26 +180,19 @@ public class ReadWriteNonCoreDataServiceImpl implements
} }
@Override @Override
public Map<String, Object> updateDatatableEntryOneToMany( public Map<String, Object> updateDatatableEntryOneToMany(final String datatable, final Long appTableId, final Long datatableId,
final String datatable, final Long appTableId, final JsonCommand command) {
final Long datatableId, final JsonCommand command) {
GenericResultsetData grs = retrieveDataTableGenericResultSet(datatable, GenericResultsetData grs = retrieveDataTableGenericResultSet(datatable, appTableId, null, datatableId);
appTableId, null, datatableId);
if (grs.getData().size() == 0) if (grs.getData().size() == 0) throw new DataTableNotFoundException(datatable, appTableId);
throw new DataTableNotFoundException(datatable, appTableId);
final Type typeOfMap = new TypeToken<Map<String, String>>() { final Type typeOfMap = new TypeToken<Map<String, String>>() {}.getType();
}.getType(); Map<String, String> dataParams = this.fromJsonHelper.extractDataMap(typeOfMap, command.json());
Map<String, String> dataParams = this.fromJsonHelper.extractDataMap(
typeOfMap, command.json());
final Map<String, Object> changes = getAffectedAndChangedColumns(grs, final Map<String, Object> changes = getAffectedAndChangedColumns(grs, dataParams, "id");
dataParams, "id");
if (changes.size() == 0) if (changes.size() == 0) return changes;
return changes;
String sql = getUpdateSql(datatable, "id", datatableId, changes); String sql = getUpdateSql(datatable, "id", datatableId, changes);
@@ -296,53 +206,30 @@ public class ReadWriteNonCoreDataServiceImpl implements
} }
@Override @Override
public void deleteDatatableEntries(final String datatable, public void deleteDatatableEntries(final String datatable, final Long appTableId) {
final Long appTableId) {
// long startTime = System.currentTimeMillis();
String appTable = getWithinScopeApplicationTableName(datatable, String appTable = getWithinScopeApplicationTableName(datatable, appTableId);
appTableId);
String sql = getDeleteEntriesSql(datatable, getFKField(appTable), String sql = getDeleteEntriesSql(datatable, getFKField(appTable), appTableId);
appTableId);
genericDataService.updateSQL(sql, "SQL: " + sql); genericDataService.updateSQL(sql, "SQL: " + sql);
// long elapsed = System.currentTimeMillis() - startTime;
// logger.info("FINISHING deleteDatatableEntries: Elapsed Time: " +
// elapsed + " - datatable: " + datatable
// + " App Table Id: " + appTableId);
} }
@Override @Override
public void deleteDatatableEntry(final String datatable, public void deleteDatatableEntry(final String datatable, final Long appTableId, final Long datatableId) {
final Long appTableId, final Long datatableId) {
// long startTime = System.currentTimeMillis();
getWithinScopeApplicationTableName(datatable, appTableId); getWithinScopeApplicationTableName(datatable, appTableId);
String sql = getDeleteEntrySql(datatable, datatableId); String sql = getDeleteEntrySql(datatable, datatableId);
genericDataService.updateSQL(sql, "SQL: " + sql); genericDataService.updateSQL(sql, "SQL: " + sql);
// long elapsed = System.currentTimeMillis() - startTime;
// logger.info("FINISHING deleteDatatableEntry: Elapsed Time: " +
// elapsed + " - datatable: " + datatable
// + " App Table Id: " + appTableId + " Data Table Id: " +
// datatableId);
} }
@Override @Override
public GenericResultsetData retrieveDataTableGenericResultSet( public GenericResultsetData retrieveDataTableGenericResultSet(final String datatable, final Long appTableId, final String order,
final String datatable, final Long appTableId, final String order,
final Long id) { final Long id) {
// long startTime = System.currentTimeMillis(); String appTable = getWithinScopeApplicationTableName(datatable, appTableId);
String appTable = getWithinScopeApplicationTableName(datatable,
appTableId);
List<ResultsetColumnHeader> columnHeaders = getDatatableResultsetColumnHeaders(datatable); List<ResultsetColumnHeader> columnHeaders = getDatatableResultsetColumnHeaders(datatable);
@@ -351,38 +238,27 @@ public class ReadWriteNonCoreDataServiceImpl implements
// id only used for reading a specific entry in a one to many datatable // id only used for reading a specific entry in a one to many datatable
// (when updating) // (when updating)
if (id == null) { if (id == null) {
sql = sql + "select * from `" + datatable + "` where " sql = sql + "select * from `" + datatable + "` where " + getFKField(appTable) + " = " + appTableId;
+ getFKField(appTable) + " = " + appTableId;
} else { } else {
sql = sql + "select * from `" + datatable + "` where id = " + id; sql = sql + "select * from `" + datatable + "` where id = " + id;
} }
if (order != null) if (order != null) sql = sql + " order by " + order;
sql = sql + " order by " + order;
List<ResultsetDataRow> result = fillDatatableResultSetDataRows(sql); List<ResultsetDataRow> result = fillDatatableResultSetDataRows(sql);
// long elapsed = System.currentTimeMillis() - startTime;
// logger.info("FINISHING DATATABLE: " + datatable +
// " Elapsed Time: " + elapsed + " SQL: " + sql);
return new GenericResultsetData(columnHeaders, result); return new GenericResultsetData(columnHeaders, result);
} }
private void checkMainResourceExistsWithinScope(final String appTable, private void checkMainResourceExistsWithinScope(final String appTable, final Long appTableId) {
final Long appTableId) {
String unscopedSql = "select t.id from `" + appTable String unscopedSql = "select t.id from `" + appTable + "` t ${dataScopeCriteria} where t.id = " + appTableId;
+ "` t ${dataScopeCriteria} where t.id = " + appTableId;
String sql = dataScopedSQL(unscopedSql, appTable); String sql = dataScopedSQL(unscopedSql, appTable);
CachedRowSet rs = genericDataService.getCachedResultSet(sql, "SQL : " CachedRowSet rs = genericDataService.getCachedResultSet(sql, "SQL : " + sql);
+ sql);
if (rs.size() == 0) if (rs.size() == 0) throw new DataTableNotFoundException(appTable, appTableId);
throw new DataTableNotFoundException(appTable, appTableId);
} }
private String dataScopedSQL(final String unscopedSQL, final String appTable) { private String dataScopedSQL(final String unscopedSQL, final String appTable) {
@@ -397,45 +273,33 @@ public class ReadWriteNonCoreDataServiceImpl implements
AppUser currentUser = context.authenticatedUser(); AppUser currentUser = context.authenticatedUser();
if (appTable.equalsIgnoreCase("m_client")) { if (appTable.equalsIgnoreCase("m_client")) {
dataScopeCriteria = " join m_office o on o.id = t.office_id and o.hierarchy like '" dataScopeCriteria = " join m_office o on o.id = t.office_id and o.hierarchy like '" + currentUser.getOffice().getHierarchy()
+ currentUser.getOffice().getHierarchy() + "%'"; + "%'";
} }
if (appTable.equalsIgnoreCase("m_loan")) { if (appTable.equalsIgnoreCase("m_loan")) {
dataScopeCriteria = " join m_client c on c.id = t.client_id " dataScopeCriteria = " join m_client c on c.id = t.client_id " + " join m_office o on o.id = c.office_id and o.hierarchy like '"
+ " join m_office o on o.id = c.office_id and o.hierarchy like '"
+ currentUser.getOffice().getHierarchy() + "%'"; + currentUser.getOffice().getHierarchy() + "%'";
} }
if (dataScopeCriteria == null) { if (dataScopeCriteria == null) { throw new PlatformDataIntegrityException("error.msg.invalid.dataScopeCriteria",
throw new PlatformDataIntegrityException( "Application Table: " + appTable + " not catered for in data Scoping"); }
"error.msg.invalid.dataScopeCriteria",
"Application Table: " + appTable
+ " not catered for in data Scoping");
}
return genericDataService.replace(unscopedSQL, "${dataScopeCriteria}", return genericDataService.replace(unscopedSQL, "${dataScopeCriteria}", dataScopeCriteria);
dataScopeCriteria);
} }
private void validateAppTable(final String appTable) { private void validateAppTable(final String appTable) {
if (appTable.equalsIgnoreCase("m_client")) if (appTable.equalsIgnoreCase("m_client")) return;
return; if (appTable.equalsIgnoreCase("m_loan")) return;
if (appTable.equalsIgnoreCase("m_loan"))
return;
throw new PlatformDataIntegrityException( throw new PlatformDataIntegrityException("error.msg.invalid.application.table", "Invalid Application Table: " + appTable);
"error.msg.invalid.application.table",
"Invalid Application Table: " + appTable);
} }
private List<ResultsetDataRow> fillDatatableResultSetDataRows( private List<ResultsetDataRow> fillDatatableResultSetDataRows(final String sql) {
final String sql) {
String sqlErrorMsg = "Sql: " + sql; String sqlErrorMsg = "Sql: " + sql;
CachedRowSet rs = genericDataService.getCachedResultSet(sql, CachedRowSet rs = genericDataService.getCachedResultSet(sql, sqlErrorMsg);
sqlErrorMsg);
List<ResultsetDataRow> resultsetDataRows = new ArrayList<ResultsetDataRow>(); List<ResultsetDataRow> resultsetDataRows = new ArrayList<ResultsetDataRow>();
@@ -461,21 +325,16 @@ public class ReadWriteNonCoreDataServiceImpl implements
return resultsetDataRows; return resultsetDataRows;
} catch (SQLException e) { } catch (SQLException e) {
throw new PlatformDataIntegrityException("error.msg.sql.error", throw new PlatformDataIntegrityException("error.msg.sql.error", e.getMessage(), sqlErrorMsg);
e.getMessage(), sqlErrorMsg);
} }
} }
private String getWithinScopeApplicationTableName(final String datatable, private String getWithinScopeApplicationTableName(final String datatable, final Long appTableId) {
final Long appTableId) { String sql = "SELECT application_table_name FROM x_registered_table where registered_table_name = '" + datatable + "'";
String sql = "SELECT application_table_name FROM x_registered_table where registered_table_name = '"
+ datatable + "'";
CachedRowSet rs = genericDataService.getCachedResultSet(sql, "SQL : " CachedRowSet rs = genericDataService.getCachedResultSet(sql, "SQL : " + sql);
+ sql);
if (rs.size() == 0) if (rs.size() == 0) throw new DataTableNotFoundException(datatable);
throw new DataTableNotFoundException(datatable);
try { try {
rs.next(); rs.next();
@@ -485,29 +344,24 @@ public class ReadWriteNonCoreDataServiceImpl implements
return appTable; return appTable;
} catch (SQLException e) { } catch (SQLException e) {
throw new PlatformDataIntegrityException("error.msg.sql.error", throw new PlatformDataIntegrityException("error.msg.sql.error", e.getMessage());
e.getMessage());
} }
} }
private String getApplicationTableName(final String datatable) { private String getApplicationTableName(final String datatable) {
// TODO - only used for update... can probably remove this after as its // TODO - only used for update... can probably remove this after as its
// a reread // a reread
String sql = "SELECT application_table_name FROM x_registered_table where registered_table_name = '" String sql = "SELECT application_table_name FROM x_registered_table where registered_table_name = '" + datatable + "'";
+ datatable + "'";
CachedRowSet rs = genericDataService.getCachedResultSet(sql, "SQL : " CachedRowSet rs = genericDataService.getCachedResultSet(sql, "SQL : " + sql);
+ sql);
if (rs.size() == 0) if (rs.size() == 0) throw new DataTableNotFoundException(datatable);
throw new DataTableNotFoundException(datatable);
try { try {
rs.next(); rs.next();
return rs.getString("application_table_name"); return rs.getString("application_table_name");
} catch (SQLException e) { } catch (SQLException e) {
throw new PlatformDataIntegrityException("error.msg.sql.error", throw new PlatformDataIntegrityException("error.msg.sql.error", e.getMessage());
e.getMessage());
} }
} }
@@ -519,21 +373,17 @@ public class ReadWriteNonCoreDataServiceImpl implements
private CachedRowSet getDatatableMetaData(final String datatable) { private CachedRowSet getDatatableMetaData(final String datatable) {
String sql = "select COLUMN_NAME, IS_NULLABLE, DATA_TYPE, CHARACTER_MAXIMUM_LENGTH, COLUMN_KEY" String sql = "select COLUMN_NAME, IS_NULLABLE, DATA_TYPE, CHARACTER_MAXIMUM_LENGTH, COLUMN_KEY"
+ " from INFORMATION_SCHEMA.COLUMNS " + " from INFORMATION_SCHEMA.COLUMNS " + " where TABLE_SCHEMA = schema() and TABLE_NAME = '" + datatable
+ " where TABLE_SCHEMA = schema() and TABLE_NAME = '" + "'order by ORDINAL_POSITION";
+ datatable + "'order by ORDINAL_POSITION";
CachedRowSet columnDefinitions = genericDataService.getCachedResultSet( CachedRowSet columnDefinitions = genericDataService.getCachedResultSet(sql, "SQL: " + sql);
sql, "SQL: " + sql);
if (columnDefinitions.size() > 0) if (columnDefinitions.size() > 0) return columnDefinitions;
return columnDefinitions;
throw new DataTableNotFoundException(datatable); throw new DataTableNotFoundException(datatable);
} }
private List<ResultsetColumnHeader> getDatatableResultsetColumnHeaders( private List<ResultsetColumnHeader> getDatatableResultsetColumnHeaders(final String datatable) {
final String datatable) {
CachedRowSet columnDefinitions = getDatatableMetaData(datatable); CachedRowSet columnDefinitions = getDatatableMetaData(datatable);
@@ -558,20 +408,15 @@ public class ReadWriteNonCoreDataServiceImpl implements
else else
rsch.setColumnPrimaryKey(false); rsch.setColumnPrimaryKey(false);
Long columnLength = columnDefinitions Long columnLength = columnDefinitions.getLong("CHARACTER_MAXIMUM_LENGTH");
.getLong("CHARACTER_MAXIMUM_LENGTH"); if (columnLength > 0) rsch.setColumnLength(columnDefinitions.getLong("CHARACTER_MAXIMUM_LENGTH"));
if (columnLength > 0)
rsch.setColumnLength(columnDefinitions
.getLong("CHARACTER_MAXIMUM_LENGTH"));
rsch.setColumnType(columnDefinitions.getString("DATA_TYPE")); rsch.setColumnType(columnDefinitions.getString("DATA_TYPE"));
/* look for codes */ /* look for codes */
if (rsch.getColumnType().equalsIgnoreCase("varchar")) if (rsch.getColumnType().equalsIgnoreCase("varchar")) addCodesValueIfNecessary(rsch, "_cv");
addCodesValueIfNecessary(rsch, "_cv");
if (rsch.getColumnType().equalsIgnoreCase("int")) if (rsch.getColumnType().equalsIgnoreCase("int")) addCodesValueIfNecessary(rsch, "_cd");
addCodesValueIfNecessary(rsch, "_cd");
rsch.setColumnDisplayType(); rsch.setColumnDisplayType();
@@ -581,46 +426,36 @@ public class ReadWriteNonCoreDataServiceImpl implements
return columnHeaders; return columnHeaders;
} catch (SQLException e) { } catch (SQLException e) {
throw new PlatformDataIntegrityException("error.msg.sql.error", throw new PlatformDataIntegrityException("error.msg.sql.error", e.getMessage());
e.getMessage());
} }
} }
private void addCodesValueIfNecessary(final ResultsetColumnHeader rsch, private void addCodesValueIfNecessary(final ResultsetColumnHeader rsch, final String code_suffix) {
final String code_suffix) {
int codePosition = rsch.getColumnName().indexOf(code_suffix); int codePosition = rsch.getColumnName().indexOf(code_suffix);
if (codePosition > 0) { if (codePosition > 0) {
String codeName = rsch.getColumnName().substring(0, codePosition); String codeName = rsch.getColumnName().substring(0, codePosition);
String sql = "select v.id, v.code_value from m_code m " String sql = "select v.id, v.code_value from m_code m " + " join m_code_value v on v.code_id = m.id "
+ " join m_code_value v on v.code_id = m.id " + " where m.code_name = '" + codeName + "' order by v.order_position, v.id";
+ " where m.code_name = '" + codeName
+ "' order by v.order_position, v.id";
CachedRowSet rsValues = genericDataService.getCachedResultSet(sql, CachedRowSet rsValues = genericDataService.getCachedResultSet(sql, "SQL: " + sql);
"SQL: " + sql);
try { try {
while (rsValues.next()) { while (rsValues.next()) {
rsch.getColumnValues().add( rsch.getColumnValues().add(new ResultsetColumnValue(rsValues.getInt("id"), rsValues.getString("code_value")));
new ResultsetColumnValue(rsValues.getInt("id"),
rsValues.getString("code_value")));
} }
} catch (SQLException e) { } catch (SQLException e) {
throw new PlatformDataIntegrityException("error.msg.sql.error", throw new PlatformDataIntegrityException("error.msg.sql.error", e.getMessage());
e.getMessage());
} }
} }
} }
private String getAddSql(final List<ResultsetColumnHeader> columnHeaders, private String getAddSql(final List<ResultsetColumnHeader> columnHeaders, final String datatable, final String fkName,
final String datatable, final String fkName, final Long appTableId, final Long appTableId, final Map<String, String> queryParams) {
final Map<String, String> queryParams) {
final Map<String, String> affectedColumns = getAffectedColumns( final Map<String, String> affectedColumns = getAffectedColumns(columnHeaders, queryParams, fkName);
columnHeaders, queryParams, fkName);
String pValueWrite = ""; String pValueWrite = "";
String addSql = ""; String addSql = "";
@@ -636,24 +471,20 @@ public class ReadWriteNonCoreDataServiceImpl implements
if (StringUtils.isEmpty(pValue)) { if (StringUtils.isEmpty(pValue)) {
pValueWrite = "null"; pValueWrite = "null";
} else { } else {
pValueWrite = singleQuote pValueWrite = singleQuote + genericDataService.replace(pValue, singleQuote, singleQuote + singleQuote) + singleQuote;
+ genericDataService.replace(pValue, singleQuote,
singleQuote + singleQuote) + singleQuote;
} }
columnName = "`" + key + "`"; columnName = "`" + key + "`";
insertColumns += ", " + columnName; insertColumns += ", " + columnName;
selectColumns += "," + pValueWrite + " as " + columnName; selectColumns += "," + pValueWrite + " as " + columnName;
} }
addSql = "insert into `" + datatable + "` (`" + fkName + "` " addSql = "insert into `" + datatable + "` (`" + fkName + "` " + insertColumns + ")" + " select " + appTableId + " as id"
+ insertColumns + ")" + " select " + appTableId + " as id"
+ selectColumns; + selectColumns;
return addSql; return addSql;
} }
private String getUpdateSql(final String datatable, private String getUpdateSql(final String datatable, final String keyFieldName, final Long keyFieldValue,
final String keyFieldName, final Long keyFieldValue,
final Map<String, Object> changedColumns) { final Map<String, Object> changedColumns) {
// just updating fields that have changed since pre-update read - though // just updating fields that have changed since pre-update read - though
@@ -663,8 +494,7 @@ public class ReadWriteNonCoreDataServiceImpl implements
// completeness but its okay to take this risk with additional fields // completeness but its okay to take this risk with additional fields
// data // data
if (changedColumns.size() == 0) if (changedColumns.size() == 0) return null;
return null;
String pValue = null; String pValue = null;
String pValueWrite = ""; String pValueWrite = "";
@@ -684,9 +514,7 @@ public class ReadWriteNonCoreDataServiceImpl implements
if (StringUtils.isEmpty(pValue)) { if (StringUtils.isEmpty(pValue)) {
pValueWrite = "null"; pValueWrite = "null";
} else { } else {
pValueWrite = singleQuote pValueWrite = singleQuote + genericDataService.replace(pValue, singleQuote, singleQuote + singleQuote) + singleQuote;
+ genericDataService.replace(pValue, singleQuote,
singleQuote + singleQuote) + singleQuote;
} }
sql += "`" + key + "` = " + pValueWrite; sql += "`" + key + "` = " + pValueWrite;
} }
@@ -696,12 +524,10 @@ public class ReadWriteNonCoreDataServiceImpl implements
return sql; return sql;
} }
private Map<String, Object> getAffectedAndChangedColumns( private Map<String, Object> getAffectedAndChangedColumns(final GenericResultsetData grs, final Map<String, String> queryParams,
final GenericResultsetData grs, final String fkName) {
final Map<String, String> queryParams, final String fkName) {
Map<String, String> affectedColumns = getAffectedColumns( Map<String, String> affectedColumns = getAffectedColumns(grs.getColumnHeaders(), queryParams, fkName);
grs.getColumnHeaders(), queryParams, fkName);
Map<String, Object> affectedAndChangedColumns = new HashMap<String, Object>(); Map<String, Object> affectedAndChangedColumns = new HashMap<String, Object>();
String columnValue; String columnValue;
@@ -715,8 +541,7 @@ public class ReadWriteNonCoreDataServiceImpl implements
return affectedAndChangedColumns; return affectedAndChangedColumns;
} }
private boolean columnChanged(final String key, final String keyValue, private boolean columnChanged(final String key, final String keyValue, final GenericResultsetData grs) {
final GenericResultsetData grs) {
List<String> columnValues = grs.getData().get(0).getRow(); List<String> columnValues = grs.getData().get(0).getRow();
@@ -727,9 +552,7 @@ public class ReadWriteNonCoreDataServiceImpl implements
columnValue = columnValues.get(i); columnValue = columnValues.get(i);
if (notTheSame(columnValue, keyValue)) { if (notTheSame(columnValue, keyValue)) {
logger.info("Difference - Column: " + key logger.info("Difference - Column: " + key + "- Current Value: " + columnValue + " New Value: " + keyValue);
+ "- Current Value: " + columnValue
+ " New Value: " + keyValue);
return true; return true;
} }
@@ -737,20 +560,16 @@ public class ReadWriteNonCoreDataServiceImpl implements
} }
} }
throw new PlatformDataIntegrityException( throw new PlatformDataIntegrityException("error.msg.invalid.columnName", "Parameter Column Name: " + key + " not found");
"error.msg.invalid.columnName", "Parameter Column Name: " + key
+ " not found");
} }
private Map<String, String> getAffectedColumns( private Map<String, String> getAffectedColumns(final List<ResultsetColumnHeader> columnHeaders, final Map<String, String> queryParams,
final List<ResultsetColumnHeader> columnHeaders, final String keyFieldName) {
final Map<String, String> queryParams, final String keyFieldName) {
String dateFormat = queryParams.get("dateFormat"); String dateFormat = queryParams.get("dateFormat");
Locale clientApplicationLocale = null; Locale clientApplicationLocale = null;
String localeQueryParam = queryParams.get("locale"); String localeQueryParam = queryParams.get("locale");
if (!(StringUtils.isBlank(localeQueryParam))) if (!(StringUtils.isBlank(localeQueryParam))) clientApplicationLocale = new Locale(queryParams.get("locale"));
clientApplicationLocale = new Locale(queryParams.get("locale"));
String underscore = "_"; String underscore = "_";
String space = " "; String space = " ";
@@ -765,124 +584,88 @@ public class ReadWriteNonCoreDataServiceImpl implements
// ignores id and foreign key fields // ignores id and foreign key fields
// also ignores locale and dateformat fields that are used for // also ignores locale and dateformat fields that are used for
// validating numeric and date data // validating numeric and date data
if (!((key.equalsIgnoreCase("id")) if (!((key.equalsIgnoreCase("id")) || (key.equalsIgnoreCase(keyFieldName)) || (key.equals("locale")) || (key
|| (key.equalsIgnoreCase(keyFieldName)) .equals("dateFormat")))) {
|| (key.equals("locale")) || (key.equals("dateFormat")))) {
notFound = true; notFound = true;
// matches incoming fields with and without underscores (spaces // matches incoming fields with and without underscores (spaces
// and underscores considered the same) // and underscores considered the same)
queryParamColumnUnderscored = genericDataService.replace(key, queryParamColumnUnderscored = genericDataService.replace(key, space, underscore);
space, underscore);
for (ResultsetColumnHeader columnHeader : columnHeaders) { for (ResultsetColumnHeader columnHeader : columnHeaders) {
if (notFound) { if (notFound) {
columnHeaderUnderscored = genericDataService columnHeaderUnderscored = genericDataService.replace(columnHeader.getColumnName(), space, underscore);
.replace(columnHeader.getColumnName(), space, if (queryParamColumnUnderscored.equalsIgnoreCase(columnHeaderUnderscored)) {
underscore);
if (queryParamColumnUnderscored
.equalsIgnoreCase(columnHeaderUnderscored)) {
pValue = queryParams.get(key); pValue = queryParams.get(key);
pValue = validateColumn(columnHeader, pValue, pValue = validateColumn(columnHeader, pValue, dateFormat, clientApplicationLocale);
dateFormat, clientApplicationLocale); affectedColumns.put(columnHeader.getColumnName(), pValue);
affectedColumns.put(columnHeader.getColumnName(),
pValue);
notFound = false; notFound = false;
} }
} }
} }
if (notFound) { if (notFound) { throw new PlatformDataIntegrityException("error.msg.column.not.found", "Column: " + key + " Not Found"); }
throw new PlatformDataIntegrityException(
"error.msg.column.not.found", "Column: " + key
+ " Not Found");
}
} }
} }
return affectedColumns; return affectedColumns;
} }
private String validateColumn(final ResultsetColumnHeader columnHeader, private String validateColumn(final ResultsetColumnHeader columnHeader, final String pValue, final String dateFormat,
final String pValue, final String dateFormat,
final Locale clientApplicationLocale) { final Locale clientApplicationLocale) {
String paramValue = pValue; String paramValue = pValue;
if ((StringUtils.isEmpty(paramValue)) if ((StringUtils.isEmpty(paramValue)) && (!(columnHeader.isColumnNullable()))) {
&& (!(columnHeader.isColumnNullable()))) {
List<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>(); List<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>();
ApiParameterError error = ApiParameterError.parameterError( ApiParameterError error = ApiParameterError.parameterError("error.msg.column.mandatory", "Mandatory",
"error.msg.column.mandatory", "Mandatory",
columnHeader.getColumnName()); columnHeader.getColumnName());
dataValidationErrors.add(error); dataValidationErrors.add(error);
throw new PlatformApiDataValidationException( throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.",
"validation.msg.validation.errors.exist", dataValidationErrors);
"Validation errors exist.", dataValidationErrors);
} }
if (!StringUtils.isEmpty(paramValue)) { if (!StringUtils.isEmpty(paramValue)) {
if (columnHeader.getColumnValues().size() > 0) { if (columnHeader.getColumnValues().size() > 0) {
// match code value or id // match code value or id
List<ResultsetColumnValue> allowedValues = columnHeader List<ResultsetColumnValue> allowedValues = columnHeader.getColumnValues();
.getColumnValues();
if (columnHeader.getColumnDisplayType().equals("CODEVALUE")) { if (columnHeader.getColumnDisplayType().equals("CODEVALUE")) {
for (ResultsetColumnValue allowedValue : allowedValues) { for (ResultsetColumnValue allowedValue : allowedValues) {
if (paramValue if (paramValue.equalsIgnoreCase(allowedValue.getValue())) return paramValue;
.equalsIgnoreCase(allowedValue.getValue()))
return paramValue;
} }
List<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>(); List<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>();
ApiParameterError error = ApiParameterError.parameterError( ApiParameterError error = ApiParameterError.parameterError("error.msg.invalid.columnValue",
"error.msg.invalid.columnValue", "Value not found in Allowed Value list", columnHeader.getColumnName(), paramValue);
"Value not found in Allowed Value list",
columnHeader.getColumnName(), paramValue);
dataValidationErrors.add(error); dataValidationErrors.add(error);
throw new PlatformApiDataValidationException( throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.",
"validation.msg.validation.errors.exist", dataValidationErrors);
"Validation errors exist.", dataValidationErrors);
} }
if (columnHeader.getColumnDisplayType().equals("CODELOOKUP")) { if (columnHeader.getColumnDisplayType().equals("CODELOOKUP")) {
for (ResultsetColumnValue allowedValue : allowedValues) { for (ResultsetColumnValue allowedValue : allowedValues) {
if (paramValue.equals(Integer.toString(allowedValue if (paramValue.equals(Integer.toString(allowedValue.getId()))) return paramValue;
.getId())))
return paramValue;
} }
List<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>(); List<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>();
ApiParameterError error = ApiParameterError.parameterError( ApiParameterError error = ApiParameterError.parameterError("error.msg.invalid.columnValue",
"error.msg.invalid.columnValue", "Value not found in Allowed Value list", columnHeader.getColumnName(), paramValue);
"Value not found in Allowed Value list",
columnHeader.getColumnName(), paramValue);
dataValidationErrors.add(error); dataValidationErrors.add(error);
throw new PlatformApiDataValidationException( throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.",
"validation.msg.validation.errors.exist", dataValidationErrors);
"Validation errors exist.", dataValidationErrors);
} }
throw new PlatformDataIntegrityException( throw new PlatformDataIntegrityException("error.msg.invalid.columnType.", "Code: " + columnHeader.getColumnName()
"error.msg.invalid.columnType.", "Code: " + " - Invalid Type " + columnHeader.getColumnType() + " (neither varchar nor int)");
+ columnHeader.getColumnName()
+ " - Invalid Type "
+ columnHeader.getColumnType()
+ " (neither varchar nor int)");
} }
JsonParserHelper helper = new JsonParserHelper(); JsonParserHelper helper = new JsonParserHelper();
if (columnHeader.getColumnDisplayType().equals("DATE")) if (columnHeader.getColumnDisplayType().equals("DATE"))
paramValue = helper.convertFrom(paramValue, paramValue = helper.convertFrom(paramValue, columnHeader.getColumnName(), dateFormat, clientApplicationLocale).toString();
columnHeader.getColumnName(), dateFormat,
clientApplicationLocale).toString();
if (columnHeader.getColumnDisplayType().equals("INTEGER")) if (columnHeader.getColumnDisplayType().equals("INTEGER"))
paramValue = helper.convertToInteger(paramValue, paramValue = helper.convertToInteger(paramValue, columnHeader.getColumnName(), clientApplicationLocale).toString();
columnHeader.getColumnName(), clientApplicationLocale)
.toString();
if (columnHeader.getColumnDisplayType().equals("DECIMAL")) if (columnHeader.getColumnDisplayType().equals("DECIMAL"))
paramValue = helper.convertFrom(paramValue, paramValue = helper.convertFrom(paramValue, columnHeader.getColumnName(), clientApplicationLocale).toString();
columnHeader.getColumnName(), clientApplicationLocale)
.toString();
// logger.info("Converted Value: " + paramValue + " - was: " + // logger.info("Converted Value: " + paramValue + " - was: " +
// pValue); // pValue);
@@ -891,33 +674,26 @@ public class ReadWriteNonCoreDataServiceImpl implements
return paramValue; return paramValue;
} }
private String getDeleteEntriesSql(final String datatable, private String getDeleteEntriesSql(final String datatable, final String FKField, final Long appTableId) {
final String FKField, final Long appTableId) {
return "delete from `" + datatable + "` where `" + FKField + "` = " return "delete from `" + datatable + "` where `" + FKField + "` = " + appTableId;
+ appTableId;
} }
private String getDeleteEntrySql(final String datatable, private String getDeleteEntrySql(final String datatable, final Long datatableId) {
final Long datatableId) {
return "delete from `" + datatable + "` where `id` = " + datatableId; return "delete from `" + datatable + "` where `id` = " + datatableId;
} }
private boolean notTheSame(final String currValue, final String pValue) { private boolean notTheSame(final String currValue, final String pValue) {
if (StringUtils.isEmpty(currValue) && StringUtils.isEmpty(pValue)) if (StringUtils.isEmpty(currValue) && StringUtils.isEmpty(pValue)) return false;
return false;
if (StringUtils.isEmpty(currValue)) if (StringUtils.isEmpty(currValue)) return true;
return true;
if (StringUtils.isEmpty(pValue)) if (StringUtils.isEmpty(pValue)) return true;
return true;
if (currValue.equals(pValue)) if (currValue.equals(pValue)) return false;
return false;
return true; return true;
} }
@@ -24,7 +24,7 @@ import javax.ws.rs.core.UriInfo;
import org.mifosplatform.infrastructure.core.api.ApiConstants; import org.mifosplatform.infrastructure.core.api.ApiConstants;
import org.mifosplatform.infrastructure.core.api.ApiRequestParameterHelper; import org.mifosplatform.infrastructure.core.api.ApiRequestParameterHelper;
import org.mifosplatform.infrastructure.core.data.EntityIdentifier; import org.mifosplatform.infrastructure.core.data.CommandProcessingResult;
import org.mifosplatform.infrastructure.core.serialization.ApiRequestJsonSerializationSettings; import org.mifosplatform.infrastructure.core.serialization.ApiRequestJsonSerializationSettings;
import org.mifosplatform.infrastructure.core.serialization.ToApiJsonSerializer; import org.mifosplatform.infrastructure.core.serialization.ToApiJsonSerializer;
import org.mifosplatform.infrastructure.core.service.FileUtils; import org.mifosplatform.infrastructure.core.service.FileUtils;
@@ -106,7 +106,7 @@ public class DocumentManagementApiResource {
Long documentId = this.documentWritePlatformService.createDocument(documentCommand, inputStream); Long documentId = this.documentWritePlatformService.createDocument(documentCommand, inputStream);
return this.toApiJsonSerializer.serialize(EntityIdentifier.resourceResult(documentId, null)); return this.toApiJsonSerializer.serialize(CommandProcessingResult.resourceResult(documentId, null));
} }
@PUT @PUT
@@ -141,7 +141,7 @@ public class DocumentManagementApiResource {
documentCommand = new DocumentCommand(modifiedParams, documentId, entityType, entityId, name, null, null, null, description, documentCommand = new DocumentCommand(modifiedParams, documentId, entityType, entityId, name, null, null, null, description,
null); null);
} }
EntityIdentifier identifier = this.documentWritePlatformService.updateDocument(documentCommand, inputStream); CommandProcessingResult identifier = this.documentWritePlatformService.updateDocument(documentCommand, inputStream);
return this.toApiJsonSerializer.serialize(identifier); return this.toApiJsonSerializer.serialize(identifier);
} }
@@ -189,7 +189,7 @@ public class DocumentManagementApiResource {
final DocumentCommand documentCommand = new DocumentCommand(null, documentId, entityType, entityId, null, null, null, null, null, final DocumentCommand documentCommand = new DocumentCommand(null, documentId, entityType, entityId, null, null, null, null, null,
null); null);
final EntityIdentifier documentIdentifier = this.documentWritePlatformService.deleteDocument(documentCommand); final CommandProcessingResult documentIdentifier = this.documentWritePlatformService.deleteDocument(documentCommand);
return this.toApiJsonSerializer.serialize(documentIdentifier); return this.toApiJsonSerializer.serialize(documentIdentifier);
} }
@@ -2,7 +2,7 @@ package org.mifosplatform.infrastructure.documentmanagement.service;
import java.io.InputStream; import java.io.InputStream;
import org.mifosplatform.infrastructure.core.data.EntityIdentifier; import org.mifosplatform.infrastructure.core.data.CommandProcessingResult;
import org.mifosplatform.infrastructure.documentmanagement.command.DocumentCommand; import org.mifosplatform.infrastructure.documentmanagement.command.DocumentCommand;
import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.access.prepost.PreAuthorize;
@@ -12,9 +12,9 @@ public interface DocumentWritePlatformService {
Long createDocument(DocumentCommand documentCommand, InputStream inputStream); Long createDocument(DocumentCommand documentCommand, InputStream inputStream);
@PreAuthorize(value = "hasAnyRole('ALL_FUNCTIONS', 'PORTFOLIO_MANAGEMENT_SUPER_USER', 'UPDATE_m_guarantor_external')") @PreAuthorize(value = "hasAnyRole('ALL_FUNCTIONS', 'PORTFOLIO_MANAGEMENT_SUPER_USER', 'UPDATE_m_guarantor_external')")
EntityIdentifier updateDocument(DocumentCommand documentCommand, InputStream inputStream); CommandProcessingResult updateDocument(DocumentCommand documentCommand, InputStream inputStream);
@PreAuthorize(value = "hasAnyRole('ALL_FUNCTIONS', 'PORTFOLIO_MANAGEMENT_SUPER_USER', 'DELETE_m_guarantor_external')") @PreAuthorize(value = "hasAnyRole('ALL_FUNCTIONS', 'PORTFOLIO_MANAGEMENT_SUPER_USER', 'DELETE_m_guarantor_external')")
EntityIdentifier deleteDocument(DocumentCommand documentCommand); CommandProcessingResult deleteDocument(DocumentCommand documentCommand);
} }
@@ -4,7 +4,7 @@ import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import org.mifosplatform.infrastructure.core.data.EntityIdentifier; import org.mifosplatform.infrastructure.core.data.CommandProcessingResult;
import org.mifosplatform.infrastructure.core.exception.PlatformDataIntegrityException; import org.mifosplatform.infrastructure.core.exception.PlatformDataIntegrityException;
import org.mifosplatform.infrastructure.core.service.FileUtils; import org.mifosplatform.infrastructure.core.service.FileUtils;
import org.mifosplatform.infrastructure.documentmanagement.command.DocumentCommand; import org.mifosplatform.infrastructure.documentmanagement.command.DocumentCommand;
@@ -77,7 +77,7 @@ public class DocumentWritePlatformServiceJpaRepositoryImpl implements DocumentWr
@Transactional @Transactional
@Override @Override
public EntityIdentifier updateDocument(final DocumentCommand documentCommand, final InputStream inputStream) { public CommandProcessingResult updateDocument(final DocumentCommand documentCommand, final InputStream inputStream) {
try { try {
context.authenticatedUser(); context.authenticatedUser();
@@ -114,7 +114,7 @@ public class DocumentWritePlatformServiceJpaRepositoryImpl implements DocumentWr
this.documentRepository.saveAndFlush(documentForUpdate); this.documentRepository.saveAndFlush(documentForUpdate);
return new EntityIdentifier(documentForUpdate.getId()); return new CommandProcessingResult(documentForUpdate.getId());
} catch (DataIntegrityViolationException dve) { } catch (DataIntegrityViolationException dve) {
logger.error(dve.getMessage(), dve); logger.error(dve.getMessage(), dve);
throw new PlatformDataIntegrityException("error.msg.document.unknown.data.integrity.issue", throw new PlatformDataIntegrityException("error.msg.document.unknown.data.integrity.issue",
@@ -127,7 +127,7 @@ public class DocumentWritePlatformServiceJpaRepositoryImpl implements DocumentWr
@Transactional @Transactional
@Override @Override
public EntityIdentifier deleteDocument(final DocumentCommand documentCommand) { public CommandProcessingResult deleteDocument(final DocumentCommand documentCommand) {
context.authenticatedUser(); context.authenticatedUser();
validateParentEntityType(documentCommand); validateParentEntityType(documentCommand);
@@ -138,7 +138,7 @@ public class DocumentWritePlatformServiceJpaRepositoryImpl implements DocumentWr
this.documentRepository.delete(document); this.documentRepository.delete(document);
deleteFile(document.getName(), document.getLocation()); deleteFile(document.getName(), document.getLocation());
return new EntityIdentifier(document.getId()); return new CommandProcessingResult(document.getId());
} }
private void deleteFile(String documentName, String location) { private void deleteFile(String documentName, String location) {
@@ -13,9 +13,11 @@ import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriInfo; import javax.ws.rs.core.UriInfo;
import org.mifosplatform.commands.domain.CommandWrapper;
import org.mifosplatform.commands.service.CommandWrapperBuilder;
import org.mifosplatform.commands.service.PortfolioCommandSourceWritePlatformService; import org.mifosplatform.commands.service.PortfolioCommandSourceWritePlatformService;
import org.mifosplatform.infrastructure.core.api.ApiRequestParameterHelper; import org.mifosplatform.infrastructure.core.api.ApiRequestParameterHelper;
import org.mifosplatform.infrastructure.core.data.EntityIdentifier; import org.mifosplatform.infrastructure.core.data.CommandProcessingResult;
import org.mifosplatform.infrastructure.core.serialization.ApiRequestJsonSerializationSettings; import org.mifosplatform.infrastructure.core.serialization.ApiRequestJsonSerializationSettings;
import org.mifosplatform.infrastructure.core.serialization.DefaultToApiJsonSerializer; import org.mifosplatform.infrastructure.core.serialization.DefaultToApiJsonSerializer;
import org.mifosplatform.infrastructure.security.service.PlatformSecurityContext; import org.mifosplatform.infrastructure.security.service.PlatformSecurityContext;
@@ -70,8 +72,10 @@ public class CurrenciesApiResource {
@Produces({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON })
public String updateCurrencies(final String apiRequestBodyAsJson) { public String updateCurrencies(final String apiRequestBodyAsJson) {
final EntityIdentifier result = this.commandsSourceWritePlatformService.logCommandSource("UPDATE", "CURRENCY", "UPDATE", "currencies", final CommandWrapper commandRequest = new CommandWrapperBuilder().updateCurrencies().withUrl("/currencies").withJson(apiRequestBodyAsJson)
null, apiRequestBodyAsJson); .build();
final CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest);
return this.toApiJsonSerializer.serialize(result); return this.toApiJsonSerializer.serialize(result);
} }
@@ -2,7 +2,7 @@ package org.mifosplatform.organisation.monetary.handler;
import org.mifosplatform.commands.handler.NewCommandSourceHandler; import org.mifosplatform.commands.handler.NewCommandSourceHandler;
import org.mifosplatform.infrastructure.core.api.JsonCommand; import org.mifosplatform.infrastructure.core.api.JsonCommand;
import org.mifosplatform.infrastructure.core.data.EntityIdentifier; import org.mifosplatform.infrastructure.core.data.CommandProcessingResult;
import org.mifosplatform.organisation.monetary.service.CurrencyWritePlatformService; import org.mifosplatform.organisation.monetary.service.CurrencyWritePlatformService;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@@ -20,7 +20,7 @@ public class UpdateCurrencyCommandHandler implements NewCommandSourceHandler {
@Transactional @Transactional
@Override @Override
public EntityIdentifier processCommand(final JsonCommand command) { public CommandProcessingResult processCommand(final JsonCommand command) {
return this.writePlatformService.updateAllowedCurrencies(command); return this.writePlatformService.updateAllowedCurrencies(command);
} }
@@ -1,10 +1,10 @@
package org.mifosplatform.organisation.monetary.service; package org.mifosplatform.organisation.monetary.service;
import org.mifosplatform.infrastructure.core.api.JsonCommand; import org.mifosplatform.infrastructure.core.api.JsonCommand;
import org.mifosplatform.infrastructure.core.data.EntityIdentifier; import org.mifosplatform.infrastructure.core.data.CommandProcessingResult;
public interface CurrencyWritePlatformService { public interface CurrencyWritePlatformService {
EntityIdentifier updateAllowedCurrencies(JsonCommand command); CommandProcessingResult updateAllowedCurrencies(JsonCommand command);
} }
@@ -8,7 +8,8 @@ import java.util.Map;
import java.util.Set; import java.util.Set;
import org.mifosplatform.infrastructure.core.api.JsonCommand; import org.mifosplatform.infrastructure.core.api.JsonCommand;
import org.mifosplatform.infrastructure.core.data.EntityIdentifier; import org.mifosplatform.infrastructure.core.data.CommandProcessingResult;
import org.mifosplatform.infrastructure.core.data.CommandProcessingResultBuilder;
import org.mifosplatform.infrastructure.security.service.PlatformSecurityContext; import org.mifosplatform.infrastructure.security.service.PlatformSecurityContext;
import org.mifosplatform.organisation.monetary.command.CurrencyCommand; import org.mifosplatform.organisation.monetary.command.CurrencyCommand;
import org.mifosplatform.organisation.monetary.domain.ApplicationCurrency; import org.mifosplatform.organisation.monetary.domain.ApplicationCurrency;
@@ -42,7 +43,7 @@ public class CurrencyWritePlatformServiceJpaRepositoryImpl implements CurrencyWr
@Transactional @Transactional
@Override @Override
public EntityIdentifier updateAllowedCurrencies(final JsonCommand command) { public CommandProcessingResult updateAllowedCurrencies(final JsonCommand command) {
context.authenticatedUser(); context.authenticatedUser();
@@ -69,6 +70,6 @@ public class CurrencyWritePlatformServiceJpaRepositoryImpl implements CurrencyWr
this.organisationCurrencyRepository.deleteAll(); this.organisationCurrencyRepository.deleteAll();
this.organisationCurrencyRepository.save(allowedCurrencies); this.organisationCurrencyRepository.save(allowedCurrencies);
return EntityIdentifier.withChanges(null, changes); return new CommandProcessingResultBuilder().withCommandId(command.commandId()).with(changes).build();
} }
} }
@@ -14,9 +14,11 @@ import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriInfo; import javax.ws.rs.core.UriInfo;
import org.mifosplatform.commands.domain.CommandWrapper;
import org.mifosplatform.commands.service.CommandWrapperBuilder;
import org.mifosplatform.commands.service.PortfolioCommandSourceWritePlatformService; import org.mifosplatform.commands.service.PortfolioCommandSourceWritePlatformService;
import org.mifosplatform.infrastructure.core.api.ApiRequestParameterHelper; import org.mifosplatform.infrastructure.core.api.ApiRequestParameterHelper;
import org.mifosplatform.infrastructure.core.data.EntityIdentifier; import org.mifosplatform.infrastructure.core.data.CommandProcessingResult;
import org.mifosplatform.infrastructure.core.serialization.ApiRequestJsonSerializationSettings; import org.mifosplatform.infrastructure.core.serialization.ApiRequestJsonSerializationSettings;
import org.mifosplatform.infrastructure.core.serialization.DefaultToApiJsonSerializer; import org.mifosplatform.infrastructure.core.serialization.DefaultToApiJsonSerializer;
import org.mifosplatform.infrastructure.security.service.PlatformSecurityContext; import org.mifosplatform.infrastructure.security.service.PlatformSecurityContext;
@@ -87,8 +89,9 @@ public class OfficeTransactionsApiResource {
@Produces({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON })
public String transferMoneyFrom(final String apiRequestBodyAsJson) { public String transferMoneyFrom(final String apiRequestBodyAsJson) {
final EntityIdentifier result = this.commandsSourceWritePlatformService.logCommandSource("CREATE", "OFFICETRANSACTION", "CREATE", final CommandWrapper commandRequest = new CommandWrapperBuilder().createOfficeTransaction().withUrl("/officetransactions").withJson(apiRequestBodyAsJson).build();
"officetransactions", null, apiRequestBodyAsJson);
final CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest);
return this.toApiJsonSerializer.serialize(result); return this.toApiJsonSerializer.serialize(result);
} }
@@ -18,10 +18,12 @@ import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriInfo; import javax.ws.rs.core.UriInfo;
import org.mifosplatform.commands.domain.CommandWrapper;
import org.mifosplatform.commands.service.CommandWrapperBuilder;
import org.mifosplatform.commands.service.PortfolioCommandSourceWritePlatformService; import org.mifosplatform.commands.service.PortfolioCommandSourceWritePlatformService;
import org.mifosplatform.infrastructure.codes.data.CodeData; import org.mifosplatform.infrastructure.codes.data.CodeData;
import org.mifosplatform.infrastructure.core.api.ApiRequestParameterHelper; import org.mifosplatform.infrastructure.core.api.ApiRequestParameterHelper;
import org.mifosplatform.infrastructure.core.data.EntityIdentifier; import org.mifosplatform.infrastructure.core.data.CommandProcessingResult;
import org.mifosplatform.infrastructure.core.serialization.ApiRequestJsonSerializationSettings; import org.mifosplatform.infrastructure.core.serialization.ApiRequestJsonSerializationSettings;
import org.mifosplatform.infrastructure.core.serialization.DefaultToApiJsonSerializer; import org.mifosplatform.infrastructure.core.serialization.DefaultToApiJsonSerializer;
import org.mifosplatform.infrastructure.security.service.PlatformSecurityContext; import org.mifosplatform.infrastructure.security.service.PlatformSecurityContext;
@@ -97,8 +99,10 @@ public class OfficesApiResource {
@Produces({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON })
public String createOffice(final String apiRequestBodyAsJson) { public String createOffice(final String apiRequestBodyAsJson) {
final EntityIdentifier result = this.commandsSourceWritePlatformService.logCommandSource("CREATE", "OFFICE", "CREATE", "offices", final CommandWrapper commandRequest = new CommandWrapperBuilder().createOffice().withUrl("/offices").withJson(apiRequestBodyAsJson)
null, apiRequestBodyAsJson); .build();
final CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest);
return this.toApiJsonSerializer.serialize(result); return this.toApiJsonSerializer.serialize(result);
} }
@@ -128,8 +132,10 @@ public class OfficesApiResource {
@Produces({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON })
public String updateOffice(@PathParam("officeId") final Long officeId, final String apiRequestBodyAsJson) { public String updateOffice(@PathParam("officeId") final Long officeId, final String apiRequestBodyAsJson) {
final EntityIdentifier result = this.commandsSourceWritePlatformService.logCommandSource("UPDATE", "OFFICE", "UPDATE", "offices", final CommandWrapper commandRequest = new CommandWrapperBuilder().updateOffice().withUrl("/offices").withEntityId(officeId)
officeId, apiRequestBodyAsJson); .withJson(apiRequestBodyAsJson).build();
final CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest);
return this.toApiJsonSerializer.serialize(result); return this.toApiJsonSerializer.serialize(result);
} }
@@ -2,7 +2,7 @@ package org.mifosplatform.organisation.office.handler;
import org.mifosplatform.commands.handler.NewCommandSourceHandler; import org.mifosplatform.commands.handler.NewCommandSourceHandler;
import org.mifosplatform.infrastructure.core.api.JsonCommand; import org.mifosplatform.infrastructure.core.api.JsonCommand;
import org.mifosplatform.infrastructure.core.data.EntityIdentifier; import org.mifosplatform.infrastructure.core.data.CommandProcessingResult;
import org.mifosplatform.organisation.office.service.OfficeWritePlatformService; import org.mifosplatform.organisation.office.service.OfficeWritePlatformService;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@@ -20,7 +20,7 @@ public class CreateOfficeCommandHandler implements NewCommandSourceHandler {
@Transactional @Transactional
@Override @Override
public EntityIdentifier processCommand(final JsonCommand command) { public CommandProcessingResult processCommand(final JsonCommand command) {
return this.writePlatformService.createOffice(command); return this.writePlatformService.createOffice(command);
} }
@@ -2,7 +2,7 @@ package org.mifosplatform.organisation.office.handler;
import org.mifosplatform.commands.handler.NewCommandSourceHandler; import org.mifosplatform.commands.handler.NewCommandSourceHandler;
import org.mifosplatform.infrastructure.core.api.JsonCommand; import org.mifosplatform.infrastructure.core.api.JsonCommand;
import org.mifosplatform.infrastructure.core.data.EntityIdentifier; import org.mifosplatform.infrastructure.core.data.CommandProcessingResult;
import org.mifosplatform.organisation.office.service.OfficeWritePlatformService; import org.mifosplatform.organisation.office.service.OfficeWritePlatformService;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@@ -20,7 +20,7 @@ public class CreateOfficeTransactionCommandHandler implements NewCommandSourceHa
@Transactional @Transactional
@Override @Override
public EntityIdentifier processCommand(final JsonCommand command) { public CommandProcessingResult processCommand(final JsonCommand command) {
return this.writePlatformService.externalBranchMoneyTransfer(command); return this.writePlatformService.externalBranchMoneyTransfer(command);
} }
@@ -2,7 +2,7 @@ package org.mifosplatform.organisation.office.handler;
import org.mifosplatform.commands.handler.NewCommandSourceHandler; import org.mifosplatform.commands.handler.NewCommandSourceHandler;
import org.mifosplatform.infrastructure.core.api.JsonCommand; import org.mifosplatform.infrastructure.core.api.JsonCommand;
import org.mifosplatform.infrastructure.core.data.EntityIdentifier; import org.mifosplatform.infrastructure.core.data.CommandProcessingResult;
import org.mifosplatform.organisation.office.service.OfficeWritePlatformService; import org.mifosplatform.organisation.office.service.OfficeWritePlatformService;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@@ -20,8 +20,8 @@ public class UpdateOfficeCommandHandler implements NewCommandSourceHandler {
@Transactional @Transactional
@Override @Override
public EntityIdentifier processCommand(final JsonCommand command) { public CommandProcessingResult processCommand(final JsonCommand command) {
return this.writePlatformService.updateOffice(command.resourceId(), command); return this.writePlatformService.updateOffice(command.entityId(), command);
} }
} }
@@ -1,13 +1,13 @@
package org.mifosplatform.organisation.office.service; package org.mifosplatform.organisation.office.service;
import org.mifosplatform.infrastructure.core.api.JsonCommand; import org.mifosplatform.infrastructure.core.api.JsonCommand;
import org.mifosplatform.infrastructure.core.data.EntityIdentifier; import org.mifosplatform.infrastructure.core.data.CommandProcessingResult;
public interface OfficeWritePlatformService { public interface OfficeWritePlatformService {
EntityIdentifier createOffice(JsonCommand command); CommandProcessingResult createOffice(JsonCommand command);
EntityIdentifier updateOffice(Long officeId, JsonCommand command); CommandProcessingResult updateOffice(Long officeId, JsonCommand command);
EntityIdentifier externalBranchMoneyTransfer(JsonCommand command); CommandProcessingResult externalBranchMoneyTransfer(JsonCommand command);
} }
@@ -3,7 +3,8 @@ package org.mifosplatform.organisation.office.service;
import java.util.Map; import java.util.Map;
import org.mifosplatform.infrastructure.core.api.JsonCommand; import org.mifosplatform.infrastructure.core.api.JsonCommand;
import org.mifosplatform.infrastructure.core.data.EntityIdentifier; import org.mifosplatform.infrastructure.core.data.CommandProcessingResult;
import org.mifosplatform.infrastructure.core.data.CommandProcessingResultBuilder;
import org.mifosplatform.infrastructure.core.exception.PlatformDataIntegrityException; import org.mifosplatform.infrastructure.core.exception.PlatformDataIntegrityException;
import org.mifosplatform.infrastructure.security.exception.NoAuthorizationException; import org.mifosplatform.infrastructure.security.exception.NoAuthorizationException;
import org.mifosplatform.infrastructure.security.service.PlatformSecurityContext; import org.mifosplatform.infrastructure.security.service.PlatformSecurityContext;
@@ -57,7 +58,7 @@ public class OfficeWritePlatformServiceJpaRepositoryImpl implements OfficeWriteP
@Transactional @Transactional
@Override @Override
public EntityIdentifier createOffice(final JsonCommand command) { public CommandProcessingResult createOffice(final JsonCommand command) {
try { try {
final AppUser currentUser = context.authenticatedUser(); final AppUser currentUser = context.authenticatedUser();
@@ -76,16 +77,17 @@ public class OfficeWritePlatformServiceJpaRepositoryImpl implements OfficeWriteP
this.officeRepository.save(office); this.officeRepository.save(office);
return EntityIdentifier.resourceResult(office.getId(), null); return new CommandProcessingResultBuilder().withCommandId(command.commandId()).withEntityId(office.getId())
.withOfficeId(office.getId()).build();
} catch (DataIntegrityViolationException dve) { } catch (DataIntegrityViolationException dve) {
handleOfficeDataIntegrityIssues(command, dve); handleOfficeDataIntegrityIssues(command, dve);
return EntityIdentifier.empty(); return CommandProcessingResult.empty();
} }
} }
@Transactional @Transactional
@Override @Override
public EntityIdentifier updateOffice(final Long officeId, final JsonCommand command) { public CommandProcessingResult updateOffice(final Long officeId, final JsonCommand command) {
try { try {
final AppUser currentUser = context.authenticatedUser(); final AppUser currentUser = context.authenticatedUser();
@@ -106,16 +108,17 @@ public class OfficeWritePlatformServiceJpaRepositoryImpl implements OfficeWriteP
this.officeRepository.saveAndFlush(office); this.officeRepository.saveAndFlush(office);
} }
return EntityIdentifier.withChanges(office.getId(), changes); return new CommandProcessingResultBuilder().withCommandId(command.commandId()).withEntityId(office.getId())
.withOfficeId(office.getId()).with(changes).build();
} catch (DataIntegrityViolationException dve) { } catch (DataIntegrityViolationException dve) {
handleOfficeDataIntegrityIssues(command, dve); handleOfficeDataIntegrityIssues(command, dve);
return EntityIdentifier.empty(); return CommandProcessingResult.empty();
} }
} }
@Transactional @Transactional
@Override @Override
public EntityIdentifier externalBranchMoneyTransfer(final JsonCommand command) { public CommandProcessingResult externalBranchMoneyTransfer(final JsonCommand command) {
context.authenticatedUser(); context.authenticatedUser();
@@ -123,13 +126,16 @@ public class OfficeWritePlatformServiceJpaRepositoryImpl implements OfficeWriteP
.json()); .json());
moneyTransferCommand.validateBranchTransfer(); moneyTransferCommand.validateBranchTransfer();
Long officeId = null;
Office fromOffice = null; Office fromOffice = null;
if (moneyTransferCommand.getFromOfficeId() != null) { if (moneyTransferCommand.getFromOfficeId() != null) {
fromOffice = this.officeRepository.findOne(moneyTransferCommand.getFromOfficeId()); fromOffice = this.officeRepository.findOne(moneyTransferCommand.getFromOfficeId());
officeId = fromOffice.getId();
} }
Office toOffice = null; Office toOffice = null;
if (moneyTransferCommand.getToOfficeId() != null) { if (moneyTransferCommand.getToOfficeId() != null) {
toOffice = this.officeRepository.findOne(moneyTransferCommand.getToOfficeId()); toOffice = this.officeRepository.findOne(moneyTransferCommand.getToOfficeId());
officeId = toOffice.getId();
} }
if (fromOffice == null && toOffice == null) { throw new OfficeNotFoundException(moneyTransferCommand.getToOfficeId()); } if (fromOffice == null && toOffice == null) { throw new OfficeNotFoundException(moneyTransferCommand.getToOfficeId()); }
@@ -145,7 +151,8 @@ public class OfficeWritePlatformServiceJpaRepositoryImpl implements OfficeWriteP
this.officeMonetaryTransferRepository.save(entity); this.officeMonetaryTransferRepository.save(entity);
return EntityIdentifier.resourceResult(entity.getId(), null); return new CommandProcessingResultBuilder().withCommandId(command.commandId()).withEntityId(entity.getId()).withOfficeId(officeId)
.build();
} }
/* /*
@@ -18,9 +18,11 @@ import javax.ws.rs.core.MediaType;
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.mifosplatform.commands.domain.CommandWrapper;
import org.mifosplatform.commands.service.CommandWrapperBuilder;
import org.mifosplatform.commands.service.PortfolioCommandSourceWritePlatformService; import org.mifosplatform.commands.service.PortfolioCommandSourceWritePlatformService;
import org.mifosplatform.infrastructure.core.api.ApiRequestParameterHelper; import org.mifosplatform.infrastructure.core.api.ApiRequestParameterHelper;
import org.mifosplatform.infrastructure.core.data.EntityIdentifier; import org.mifosplatform.infrastructure.core.data.CommandProcessingResult;
import org.mifosplatform.infrastructure.core.serialization.ApiRequestJsonSerializationSettings; import org.mifosplatform.infrastructure.core.serialization.ApiRequestJsonSerializationSettings;
import org.mifosplatform.infrastructure.core.serialization.DefaultToApiJsonSerializer; import org.mifosplatform.infrastructure.core.serialization.DefaultToApiJsonSerializer;
import org.mifosplatform.infrastructure.security.service.PlatformSecurityContext; import org.mifosplatform.infrastructure.security.service.PlatformSecurityContext;
@@ -86,8 +88,10 @@ public class StaffApiResource {
@Produces({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON })
public String createStaff(final String apiRequestBodyAsJson) { public String createStaff(final String apiRequestBodyAsJson) {
final EntityIdentifier result = this.commandsSourceWritePlatformService.logCommandSource("CREATE", "STAFF", "CREATE", "staff", final CommandWrapper commandRequest = new CommandWrapperBuilder().createStaff().withUrl("/staff").withJson(apiRequestBodyAsJson)
null, apiRequestBodyAsJson); .build();
final CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest);
return this.toApiJsonSerializer.serialize(result); return this.toApiJsonSerializer.serialize(result);
} }
@@ -117,8 +121,10 @@ public class StaffApiResource {
@Produces({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON })
public String updateStaff(@PathParam("staffId") final Long staffId, final String apiRequestBodyAsJson) { public String updateStaff(@PathParam("staffId") final Long staffId, final String apiRequestBodyAsJson) {
final EntityIdentifier result = this.commandsSourceWritePlatformService.logCommandSource("UPDATE", "STAFF", "UPDATE", "staff", final CommandWrapper commandRequest = new CommandWrapperBuilder().updateStaff().withUrl("/staff").withEntityId(staffId).withJson(apiRequestBodyAsJson)
staffId, apiRequestBodyAsJson); .build();
final CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest);
return this.toApiJsonSerializer.serialize(result); return this.toApiJsonSerializer.serialize(result);
} }
@@ -134,4 +134,8 @@ public class Staff extends AbstractAuditableCustom<AppUser, Long> {
public boolean identifiedBy(final Staff staff) { public boolean identifiedBy(final Staff staff) {
return getId().equals(staff.getId()); return getId().equals(staff.getId());
} }
public Long officeId() {
return this.office.getId();
}
} }
@@ -2,7 +2,7 @@ package org.mifosplatform.organisation.staff.handler;
import org.mifosplatform.commands.handler.NewCommandSourceHandler; import org.mifosplatform.commands.handler.NewCommandSourceHandler;
import org.mifosplatform.infrastructure.core.api.JsonCommand; import org.mifosplatform.infrastructure.core.api.JsonCommand;
import org.mifosplatform.infrastructure.core.data.EntityIdentifier; import org.mifosplatform.infrastructure.core.data.CommandProcessingResult;
import org.mifosplatform.organisation.staff.service.StaffWritePlatformService; import org.mifosplatform.organisation.staff.service.StaffWritePlatformService;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@@ -20,7 +20,7 @@ public class CreateStaffCommandHandler implements NewCommandSourceHandler {
@Transactional @Transactional
@Override @Override
public EntityIdentifier processCommand(final JsonCommand command) { public CommandProcessingResult processCommand(final JsonCommand command) {
return this.writePlatformService.createStaff(command); return this.writePlatformService.createStaff(command);
} }
@@ -2,7 +2,7 @@ package org.mifosplatform.organisation.staff.handler;
import org.mifosplatform.commands.handler.NewCommandSourceHandler; import org.mifosplatform.commands.handler.NewCommandSourceHandler;
import org.mifosplatform.infrastructure.core.api.JsonCommand; import org.mifosplatform.infrastructure.core.api.JsonCommand;
import org.mifosplatform.infrastructure.core.data.EntityIdentifier; import org.mifosplatform.infrastructure.core.data.CommandProcessingResult;
import org.mifosplatform.organisation.staff.service.StaffWritePlatformService; import org.mifosplatform.organisation.staff.service.StaffWritePlatformService;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@@ -20,8 +20,8 @@ public class UpdateStaffCommandHandler implements NewCommandSourceHandler {
@Transactional @Transactional
@Override @Override
public EntityIdentifier processCommand(final JsonCommand command) { public CommandProcessingResult processCommand(final JsonCommand command) {
return this.writePlatformService.updateStaff(command.resourceId(), command); return this.writePlatformService.updateStaff(command.entityId(), command);
} }
} }
@@ -1,11 +1,11 @@
package org.mifosplatform.organisation.staff.service; package org.mifosplatform.organisation.staff.service;
import org.mifosplatform.infrastructure.core.api.JsonCommand; import org.mifosplatform.infrastructure.core.api.JsonCommand;
import org.mifosplatform.infrastructure.core.data.EntityIdentifier; import org.mifosplatform.infrastructure.core.data.CommandProcessingResult;
public interface StaffWritePlatformService { public interface StaffWritePlatformService {
EntityIdentifier createStaff(final JsonCommand command); CommandProcessingResult createStaff(final JsonCommand command);
EntityIdentifier updateStaff(final Long staffId, final JsonCommand command); CommandProcessingResult updateStaff(final Long staffId, final JsonCommand command);
} }
@@ -4,7 +4,8 @@ import java.util.Map;
import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.StringUtils;
import org.mifosplatform.infrastructure.core.api.JsonCommand; import org.mifosplatform.infrastructure.core.api.JsonCommand;
import org.mifosplatform.infrastructure.core.data.EntityIdentifier; import org.mifosplatform.infrastructure.core.data.CommandProcessingResult;
import org.mifosplatform.infrastructure.core.data.CommandProcessingResultBuilder;
import org.mifosplatform.infrastructure.core.exception.PlatformDataIntegrityException; import org.mifosplatform.infrastructure.core.exception.PlatformDataIntegrityException;
import org.mifosplatform.infrastructure.security.service.PlatformSecurityContext; import org.mifosplatform.infrastructure.security.service.PlatformSecurityContext;
import org.mifosplatform.organisation.office.domain.Office; import org.mifosplatform.organisation.office.domain.Office;
@@ -44,7 +45,7 @@ public class StaffWritePlatformServiceJpaRepositoryImpl implements StaffWritePla
@Transactional @Transactional
@Override @Override
public EntityIdentifier createStaff(final JsonCommand command) { public CommandProcessingResult createStaff(final JsonCommand command) {
try { try {
context.authenticatedUser(); context.authenticatedUser();
@@ -61,16 +62,17 @@ public class StaffWritePlatformServiceJpaRepositoryImpl implements StaffWritePla
this.staffRepository.save(staff); this.staffRepository.save(staff);
return EntityIdentifier.resourceResult(staff.getId(), null); return new CommandProcessingResultBuilder().withCommandId(command.commandId()).withEntityId(staff.getId())
.withOfficeId(officeId).build();
} catch (DataIntegrityViolationException dve) { } catch (DataIntegrityViolationException dve) {
handleStaffDataIntegrityIssues(command, dve); handleStaffDataIntegrityIssues(command, dve);
return EntityIdentifier.empty(); return CommandProcessingResult.empty();
} }
} }
@Transactional @Transactional
@Override @Override
public EntityIdentifier updateStaff(final Long staffId, final JsonCommand command) { public CommandProcessingResult updateStaff(final Long staffId, final JsonCommand command) {
try { try {
context.authenticatedUser(); context.authenticatedUser();
@@ -78,7 +80,7 @@ public class StaffWritePlatformServiceJpaRepositoryImpl implements StaffWritePla
final StaffCommand staffCommand = this.fromApiJsonDeserializer.commandFromApiJson(command.json()); final StaffCommand staffCommand = this.fromApiJsonDeserializer.commandFromApiJson(command.json());
staffCommand.validateForUpdate(); staffCommand.validateForUpdate();
Staff staffForUpdate = this.staffRepository.findOne(staffId); final Staff staffForUpdate = this.staffRepository.findOne(staffId);
if (staffForUpdate == null) { throw new StaffNotFoundException(staffId); } if (staffForUpdate == null) { throw new StaffNotFoundException(staffId); }
final Map<String, Object> changesOnly = staffForUpdate.update(command); final Map<String, Object> changesOnly = staffForUpdate.update(command);
@@ -95,10 +97,11 @@ public class StaffWritePlatformServiceJpaRepositoryImpl implements StaffWritePla
this.staffRepository.save(staffForUpdate); this.staffRepository.save(staffForUpdate);
} }
return EntityIdentifier.withChanges(staffForUpdate.getId(), changesOnly); return new CommandProcessingResultBuilder().withCommandId(command.commandId()).withEntityId(staffId)
.withOfficeId(staffForUpdate.officeId()).with(changesOnly).build();
} catch (DataIntegrityViolationException dve) { } catch (DataIntegrityViolationException dve) {
handleStaffDataIntegrityIssues(command, dve); handleStaffDataIntegrityIssues(command, dve);
return EntityIdentifier.empty(); return CommandProcessingResult.empty();
} }
} }
@@ -17,9 +17,11 @@ import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriInfo; import javax.ws.rs.core.UriInfo;
import org.mifosplatform.commands.domain.CommandWrapper;
import org.mifosplatform.commands.service.CommandWrapperBuilder;
import org.mifosplatform.commands.service.PortfolioCommandSourceWritePlatformService; import org.mifosplatform.commands.service.PortfolioCommandSourceWritePlatformService;
import org.mifosplatform.infrastructure.core.api.ApiRequestParameterHelper; import org.mifosplatform.infrastructure.core.api.ApiRequestParameterHelper;
import org.mifosplatform.infrastructure.core.data.EntityIdentifier; import org.mifosplatform.infrastructure.core.data.CommandProcessingResult;
import org.mifosplatform.infrastructure.core.serialization.ApiRequestJsonSerializationSettings; import org.mifosplatform.infrastructure.core.serialization.ApiRequestJsonSerializationSettings;
import org.mifosplatform.infrastructure.core.serialization.DefaultToApiJsonSerializer; import org.mifosplatform.infrastructure.core.serialization.DefaultToApiJsonSerializer;
import org.mifosplatform.infrastructure.security.service.PlatformSecurityContext; import org.mifosplatform.infrastructure.security.service.PlatformSecurityContext;
@@ -108,8 +110,10 @@ public class ChargesApiResource {
@Produces({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON })
public String createCharge(final String apiRequestBodyAsJson) { public String createCharge(final String apiRequestBodyAsJson) {
final EntityIdentifier result = this.commandsSourceWritePlatformService.logCommandSource("CREATE", "CHARGE", "CREATE", "charges", final CommandWrapper commandRequest = new CommandWrapperBuilder().createCharge().withUrl("/charges").withJson(apiRequestBodyAsJson)
null, apiRequestBodyAsJson); .build();
final CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest);
return this.toApiJsonSerializer.serialize(result); return this.toApiJsonSerializer.serialize(result);
} }
@@ -120,8 +124,10 @@ public class ChargesApiResource {
@Produces({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON })
public String updateCharge(@PathParam("chargeId") final Long chargeId, final String apiRequestBodyAsJson) { public String updateCharge(@PathParam("chargeId") final Long chargeId, final String apiRequestBodyAsJson) {
final EntityIdentifier result = this.commandsSourceWritePlatformService.logCommandSource("UPDATE", "CHARGE", "UPDATE", "charges", final CommandWrapper commandRequest = new CommandWrapperBuilder().updateCharge().withUrl("/charges").withEntityId(chargeId)
chargeId, apiRequestBodyAsJson); .withJson(apiRequestBodyAsJson).build();
final CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest);
return this.toApiJsonSerializer.serialize(result); return this.toApiJsonSerializer.serialize(result);
} }
@@ -132,8 +138,10 @@ public class ChargesApiResource {
@Produces({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON })
public String deleteCharge(@PathParam("chargeId") final Long chargeId) { public String deleteCharge(@PathParam("chargeId") final Long chargeId) {
final EntityIdentifier result = this.commandsSourceWritePlatformService.logCommandSource("DELETE", "CHARGE", "DELETE", "charges", final CommandWrapper commandRequest = new CommandWrapperBuilder().deleteCharge().withUrl("/charges").withEntityId(chargeId)
chargeId, "{}"); .withJson("{}").build();
final CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest);
return this.toApiJsonSerializer.serialize(result); return this.toApiJsonSerializer.serialize(result);
} }
@@ -2,7 +2,7 @@ package org.mifosplatform.portfolio.charge.handler;
import org.mifosplatform.commands.handler.NewCommandSourceHandler; import org.mifosplatform.commands.handler.NewCommandSourceHandler;
import org.mifosplatform.infrastructure.core.api.JsonCommand; import org.mifosplatform.infrastructure.core.api.JsonCommand;
import org.mifosplatform.infrastructure.core.data.EntityIdentifier; import org.mifosplatform.infrastructure.core.data.CommandProcessingResult;
import org.mifosplatform.portfolio.charge.service.ChargeWritePlatformService; import org.mifosplatform.portfolio.charge.service.ChargeWritePlatformService;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@@ -20,7 +20,7 @@ public class CreateChargeDefinitionCommandHandler implements NewCommandSourceHan
@Transactional @Transactional
@Override @Override
public EntityIdentifier processCommand(final JsonCommand command) { public CommandProcessingResult processCommand(final JsonCommand command) {
return this.clientWritePlatformService.createCharge(command); return this.clientWritePlatformService.createCharge(command);
} }
@@ -2,7 +2,7 @@ package org.mifosplatform.portfolio.charge.handler;
import org.mifosplatform.commands.handler.NewCommandSourceHandler; import org.mifosplatform.commands.handler.NewCommandSourceHandler;
import org.mifosplatform.infrastructure.core.api.JsonCommand; import org.mifosplatform.infrastructure.core.api.JsonCommand;
import org.mifosplatform.infrastructure.core.data.EntityIdentifier; import org.mifosplatform.infrastructure.core.data.CommandProcessingResult;
import org.mifosplatform.portfolio.charge.service.ChargeWritePlatformService; import org.mifosplatform.portfolio.charge.service.ChargeWritePlatformService;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@@ -20,8 +20,8 @@ public class DeleteChargeDefinitionCommandHandler implements NewCommandSourceHan
@Transactional @Transactional
@Override @Override
public EntityIdentifier processCommand(final JsonCommand command) { public CommandProcessingResult processCommand(final JsonCommand command) {
return this.clientWritePlatformService.deleteCharge(command.resourceId()); return this.clientWritePlatformService.deleteCharge(command.entityId());
} }
} }
@@ -2,7 +2,7 @@ package org.mifosplatform.portfolio.charge.handler;
import org.mifosplatform.commands.handler.NewCommandSourceHandler; import org.mifosplatform.commands.handler.NewCommandSourceHandler;
import org.mifosplatform.infrastructure.core.api.JsonCommand; import org.mifosplatform.infrastructure.core.api.JsonCommand;
import org.mifosplatform.infrastructure.core.data.EntityIdentifier; import org.mifosplatform.infrastructure.core.data.CommandProcessingResult;
import org.mifosplatform.portfolio.charge.service.ChargeWritePlatformService; import org.mifosplatform.portfolio.charge.service.ChargeWritePlatformService;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@@ -20,8 +20,8 @@ public class UpdateChargeDefinitionCommandHandler implements NewCommandSourceHan
@Transactional @Transactional
@Override @Override
public EntityIdentifier processCommand(final JsonCommand command) { public CommandProcessingResult processCommand(final JsonCommand command) {
return this.clientWritePlatformService.updateCharge(command.resourceId(), command); return this.clientWritePlatformService.updateCharge(command.entityId(), command);
} }
} }
@@ -1,13 +1,13 @@
package org.mifosplatform.portfolio.charge.service; package org.mifosplatform.portfolio.charge.service;
import org.mifosplatform.infrastructure.core.api.JsonCommand; import org.mifosplatform.infrastructure.core.api.JsonCommand;
import org.mifosplatform.infrastructure.core.data.EntityIdentifier; import org.mifosplatform.infrastructure.core.data.CommandProcessingResult;
public interface ChargeWritePlatformService { public interface ChargeWritePlatformService {
EntityIdentifier createCharge(JsonCommand command); CommandProcessingResult createCharge(JsonCommand command);
EntityIdentifier updateCharge(Long chargeId, JsonCommand command); CommandProcessingResult updateCharge(Long chargeId, JsonCommand command);
EntityIdentifier deleteCharge(Long chargeId); CommandProcessingResult deleteCharge(Long chargeId);
} }
@@ -3,7 +3,8 @@ package org.mifosplatform.portfolio.charge.service;
import java.util.Map; import java.util.Map;
import org.mifosplatform.infrastructure.core.api.JsonCommand; import org.mifosplatform.infrastructure.core.api.JsonCommand;
import org.mifosplatform.infrastructure.core.data.EntityIdentifier; import org.mifosplatform.infrastructure.core.data.CommandProcessingResult;
import org.mifosplatform.infrastructure.core.data.CommandProcessingResultBuilder;
import org.mifosplatform.infrastructure.core.exception.PlatformDataIntegrityException; import org.mifosplatform.infrastructure.core.exception.PlatformDataIntegrityException;
import org.mifosplatform.infrastructure.security.service.PlatformSecurityContext; import org.mifosplatform.infrastructure.security.service.PlatformSecurityContext;
import org.mifosplatform.portfolio.charge.command.ChargeDefinitionCommand; import org.mifosplatform.portfolio.charge.command.ChargeDefinitionCommand;
@@ -29,8 +30,7 @@ public class ChargeWritePlatformServiceJpaRepositoryImpl implements ChargeWriteP
@Autowired @Autowired
public ChargeWritePlatformServiceJpaRepositoryImpl(final PlatformSecurityContext context, public ChargeWritePlatformServiceJpaRepositoryImpl(final PlatformSecurityContext context,
final ChargeDefinitionCommandFromApiJsonDeserializer fromApiJsonDeserializer, final ChargeDefinitionCommandFromApiJsonDeserializer fromApiJsonDeserializer, final ChargeRepository chargeRepository) {
final ChargeRepository chargeRepository) {
this.context = context; this.context = context;
this.fromApiJsonDeserializer = fromApiJsonDeserializer; this.fromApiJsonDeserializer = fromApiJsonDeserializer;
this.chargeRepository = chargeRepository; this.chargeRepository = chargeRepository;
@@ -38,7 +38,7 @@ public class ChargeWritePlatformServiceJpaRepositoryImpl implements ChargeWriteP
@Transactional @Transactional
@Override @Override
public EntityIdentifier createCharge(final JsonCommand command) { public CommandProcessingResult createCharge(final JsonCommand command) {
try { try {
this.context.authenticatedUser(); this.context.authenticatedUser();
@@ -48,16 +48,16 @@ public class ChargeWritePlatformServiceJpaRepositoryImpl implements ChargeWriteP
final Charge charge = Charge.fromJson(command); final Charge charge = Charge.fromJson(command);
this.chargeRepository.save(charge); this.chargeRepository.save(charge);
return EntityIdentifier.resourceResult(charge.getId(), null); return new CommandProcessingResultBuilder().withCommandId(command.commandId()).withEntityId(charge.getId()).build();
} catch (DataIntegrityViolationException dve) { } catch (DataIntegrityViolationException dve) {
handleDataIntegrityIssues(command, dve); handleDataIntegrityIssues(command, dve);
return EntityIdentifier.empty(); return CommandProcessingResult.empty();
} }
} }
@Transactional @Transactional
@Override @Override
public EntityIdentifier updateCharge(final Long chargeId, final JsonCommand command) { public CommandProcessingResult updateCharge(final Long chargeId, final JsonCommand command) {
try { try {
this.context.authenticatedUser(); this.context.authenticatedUser();
@@ -74,16 +74,16 @@ public class ChargeWritePlatformServiceJpaRepositoryImpl implements ChargeWriteP
this.chargeRepository.save(chargeForUpdate); this.chargeRepository.save(chargeForUpdate);
} }
return EntityIdentifier.withChanges(chargeForUpdate.getId(), changes); return new CommandProcessingResultBuilder().withCommandId(command.commandId()).withEntityId(chargeId).with(changes).build();
} catch (DataIntegrityViolationException dve) { } catch (DataIntegrityViolationException dve) {
handleDataIntegrityIssues(command, dve); handleDataIntegrityIssues(command, dve);
return EntityIdentifier.empty(); return CommandProcessingResult.empty();
} }
} }
@Transactional @Transactional
@Override @Override
public EntityIdentifier deleteCharge(final Long chargeId) { public CommandProcessingResult deleteCharge(final Long chargeId) {
this.context.authenticatedUser(); this.context.authenticatedUser();
@@ -94,7 +94,7 @@ public class ChargeWritePlatformServiceJpaRepositoryImpl implements ChargeWriteP
chargeRepository.save(chargeForDelete); chargeRepository.save(chargeForDelete);
return EntityIdentifier.resourceResult(chargeForDelete.getId(), null); return new CommandProcessingResultBuilder().withEntityId(chargeForDelete.getId()).build();
} }
/* /*
@@ -106,8 +106,9 @@ public class ChargeWritePlatformServiceJpaRepositoryImpl implements ChargeWriteP
Throwable realCause = dve.getMostSpecificCause(); Throwable realCause = dve.getMostSpecificCause();
if (realCause.getMessage().contains("name")) { if (realCause.getMessage().contains("name")) {
final String name = command.stringValueOfParameterNamed("name"); final String name = command.stringValueOfParameterNamed("name");
throw new PlatformDataIntegrityException("error.msg.charge.duplicate.name", throw new PlatformDataIntegrityException("error.msg.charge.duplicate.name", "Charge with name `" + name + "` already exists",
"Charge with name `" + name +"` already exists", "name", name); } "name", name);
}
logger.error(dve.getMessage(), dve); logger.error(dve.getMessage(), dve);
throw new PlatformDataIntegrityException("error.msg.charge.unknown.data.integrity.issue", throw new PlatformDataIntegrityException("error.msg.charge.unknown.data.integrity.issue",
@@ -17,11 +17,13 @@ import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriInfo; import javax.ws.rs.core.UriInfo;
import org.mifosplatform.commands.domain.CommandWrapper;
import org.mifosplatform.commands.service.CommandWrapperBuilder;
import org.mifosplatform.commands.service.PortfolioCommandSourceWritePlatformService; import org.mifosplatform.commands.service.PortfolioCommandSourceWritePlatformService;
import org.mifosplatform.infrastructure.codes.data.CodeValueData; import org.mifosplatform.infrastructure.codes.data.CodeValueData;
import org.mifosplatform.infrastructure.codes.service.CodeValueReadPlatformService; import org.mifosplatform.infrastructure.codes.service.CodeValueReadPlatformService;
import org.mifosplatform.infrastructure.core.api.ApiRequestParameterHelper; import org.mifosplatform.infrastructure.core.api.ApiRequestParameterHelper;
import org.mifosplatform.infrastructure.core.data.EntityIdentifier; import org.mifosplatform.infrastructure.core.data.CommandProcessingResult;
import org.mifosplatform.infrastructure.core.serialization.ApiRequestJsonSerializationSettings; import org.mifosplatform.infrastructure.core.serialization.ApiRequestJsonSerializationSettings;
import org.mifosplatform.infrastructure.core.serialization.DefaultToApiJsonSerializer; import org.mifosplatform.infrastructure.core.serialization.DefaultToApiJsonSerializer;
import org.mifosplatform.infrastructure.security.service.PlatformSecurityContext; import org.mifosplatform.infrastructure.security.service.PlatformSecurityContext;
@@ -98,8 +100,10 @@ public class ClientIdentifiersApiResource {
public String createClientIdentifier(@PathParam("clientId") final Long clientId, final String apiRequestBodyAsJson) { public String createClientIdentifier(@PathParam("clientId") final Long clientId, final String apiRequestBodyAsJson) {
try { try {
final EntityIdentifier result = this.commandsSourceWritePlatformService.logCommandSource("CREATE", "CLIENTIDENTIFIER", "CREATE", final CommandWrapper commandRequest = new CommandWrapperBuilder().createClientIdentifier().withClientId(clientId)
"clients", clientId, "identifiers", null, apiRequestBodyAsJson); .withUrl("/clients/" + clientId + "/identifiers").withJson(apiRequestBodyAsJson).build();
final CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest);
return this.toApiJsonSerializer.serialize(result); return this.toApiJsonSerializer.serialize(result);
} catch (DuplicateClientIdentifierException e) { } catch (DuplicateClientIdentifierException e) {
@@ -143,8 +147,11 @@ public class ClientIdentifiersApiResource {
@PathParam("identifierId") final Long clientIdentifierId, final String apiRequestBodyAsJson) { @PathParam("identifierId") final Long clientIdentifierId, final String apiRequestBodyAsJson) {
try { try {
final EntityIdentifier result = this.commandsSourceWritePlatformService.logCommandSource("UPDATE", "CLIENTIDENTIFIER", "UPDATE", final CommandWrapper commandRequest = new CommandWrapperBuilder().updateClientIdentifier()
"clients", clientId, "identifiers", clientIdentifierId, apiRequestBodyAsJson); .withUrl("/clients/" + clientId + "/identifiers").withClientId(clientId).withEntityId(clientIdentifierId)
.withJson(apiRequestBodyAsJson).build();
final CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest);
return this.toApiJsonSerializer.serialize(result); return this.toApiJsonSerializer.serialize(result);
} catch (DuplicateClientIdentifierException e) { } catch (DuplicateClientIdentifierException e) {
@@ -166,8 +173,11 @@ public class ClientIdentifiersApiResource {
public String deleteClientIdentifier(@PathParam("clientId") final Long clientId, public String deleteClientIdentifier(@PathParam("clientId") final Long clientId,
@PathParam("identifierId") final Long clientIdentifierId) { @PathParam("identifierId") final Long clientIdentifierId) {
final EntityIdentifier result = this.commandsSourceWritePlatformService.logCommandSource("DELETE", "CLIENTIDENTIFIER", "DELETE", final CommandWrapper commandRequest = new CommandWrapperBuilder().deleteClientIdentifier()
"clients", clientId, "identifiers", clientIdentifierId, "{}"); .withUrl("/clients/" + clientId + "/identifiers").withClientId(clientId).withEntityId(clientIdentifierId).withJson("{}")
.build();
final CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest);
return this.toApiJsonSerializer.serialize(result); return this.toApiJsonSerializer.serialize(result);
} }
@@ -14,7 +14,7 @@ import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MediaType;
import org.mifosplatform.infrastructure.core.api.ApiConstants; import org.mifosplatform.infrastructure.core.api.ApiConstants;
import org.mifosplatform.infrastructure.core.data.EntityIdentifier; import org.mifosplatform.infrastructure.core.data.CommandProcessingResult;
import org.mifosplatform.infrastructure.core.domain.Base64EncodedImage; import org.mifosplatform.infrastructure.core.domain.Base64EncodedImage;
import org.mifosplatform.infrastructure.core.serialization.DefaultToApiJsonSerializer; import org.mifosplatform.infrastructure.core.serialization.DefaultToApiJsonSerializer;
import org.mifosplatform.infrastructure.core.service.FileUtils; import org.mifosplatform.infrastructure.core.service.FileUtils;
@@ -69,7 +69,7 @@ public class ClientImagesApiResource {
FileUtils.validateImageMimeType(bodyPart.getMediaType().toString()); FileUtils.validateImageMimeType(bodyPart.getMediaType().toString());
FileUtils.validateFileSizeWithinPermissibleRange(fileSize, fileDetails.getFileName(), ApiConstants.MAX_FILE_UPLOAD_SIZE_IN_MB); FileUtils.validateFileSizeWithinPermissibleRange(fileSize, fileDetails.getFileName(), ApiConstants.MAX_FILE_UPLOAD_SIZE_IN_MB);
final EntityIdentifier result = this.clientWritePlatformService.saveOrUpdateClientImage(clientId, fileDetails.getFileName(), final CommandProcessingResult result = this.clientWritePlatformService.saveOrUpdateClientImage(clientId, fileDetails.getFileName(),
inputStream); inputStream);
return this.toApiJsonSerializer.serialize(result); return this.toApiJsonSerializer.serialize(result);
@@ -85,7 +85,7 @@ public class ClientImagesApiResource {
final Base64EncodedImage base64EncodedImage = FileUtils.extractImageFromDataURL(jsonRequestBody); final Base64EncodedImage base64EncodedImage = FileUtils.extractImageFromDataURL(jsonRequestBody);
final EntityIdentifier result = this.clientWritePlatformService.saveOrUpdateClientImage(clientId, base64EncodedImage); final CommandProcessingResult result = this.clientWritePlatformService.saveOrUpdateClientImage(clientId, base64EncodedImage);
return this.toApiJsonSerializer.serialize(result); return this.toApiJsonSerializer.serialize(result);
} }
@@ -127,7 +127,7 @@ public class ClientImagesApiResource {
public String deleteClientImage(@PathParam("clientId") final Long clientId) { public String deleteClientImage(@PathParam("clientId") final Long clientId) {
this.clientWritePlatformService.deleteClientImage(clientId); this.clientWritePlatformService.deleteClientImage(clientId);
return this.toApiJsonSerializer.serialize(new EntityIdentifier(clientId)); return this.toApiJsonSerializer.serialize(new CommandProcessingResult(clientId));
} }
/** /**
@@ -16,9 +16,11 @@ import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriInfo; import javax.ws.rs.core.UriInfo;
import org.mifosplatform.commands.domain.CommandWrapper;
import org.mifosplatform.commands.service.CommandWrapperBuilder;
import org.mifosplatform.commands.service.PortfolioCommandSourceWritePlatformService; import org.mifosplatform.commands.service.PortfolioCommandSourceWritePlatformService;
import org.mifosplatform.infrastructure.core.api.ApiRequestParameterHelper; import org.mifosplatform.infrastructure.core.api.ApiRequestParameterHelper;
import org.mifosplatform.infrastructure.core.data.EntityIdentifier; import org.mifosplatform.infrastructure.core.data.CommandProcessingResult;
import org.mifosplatform.infrastructure.core.serialization.ApiRequestJsonSerializationSettings; import org.mifosplatform.infrastructure.core.serialization.ApiRequestJsonSerializationSettings;
import org.mifosplatform.infrastructure.core.serialization.DefaultToApiJsonSerializer; import org.mifosplatform.infrastructure.core.serialization.DefaultToApiJsonSerializer;
import org.mifosplatform.infrastructure.security.service.PlatformSecurityContext; import org.mifosplatform.infrastructure.security.service.PlatformSecurityContext;
@@ -71,8 +73,10 @@ public class ClientNotesApiResource {
@Produces({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON })
public String addNewClientNote(@PathParam("clientId") final Long clientId, final String apiRequestBodyAsJson) { public String addNewClientNote(@PathParam("clientId") final Long clientId, final String apiRequestBodyAsJson) {
final EntityIdentifier result = this.commandsSourceWritePlatformService.logCommandSource("CREATE", "CLIENTNOTE", "CREATE", final CommandWrapper commandRequest = new CommandWrapperBuilder().createClientNote().withUrl("/clients/" + clientId + "/notes")
"clients", clientId, "notes", null, apiRequestBodyAsJson); .withClientId(clientId).withJson(apiRequestBodyAsJson).build();
final CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest);
return this.toApiJsonSerializer.serialize(result); return this.toApiJsonSerializer.serialize(result);
} }
@@ -99,8 +103,10 @@ public class ClientNotesApiResource {
public String updateClientNote(@PathParam("clientId") final Long clientId, @PathParam("noteId") final Long noteId, public String updateClientNote(@PathParam("clientId") final Long clientId, @PathParam("noteId") final Long noteId,
final String apiRequestBodyAsJson) { final String apiRequestBodyAsJson) {
final EntityIdentifier result = this.commandsSourceWritePlatformService.logCommandSource("UPDATE", "CLIENTNOTE", "UPDATE", final CommandWrapper commandRequest = new CommandWrapperBuilder().updateClientNote().withUrl("/clients/" + clientId + "/notes")
"clients", clientId, "notes", noteId, apiRequestBodyAsJson); .withClientId(clientId).withEntityId(noteId).withJson(apiRequestBodyAsJson).build();
final CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest);
return this.toApiJsonSerializer.serialize(result); return this.toApiJsonSerializer.serialize(result);
} }
@@ -22,12 +22,14 @@ import javax.ws.rs.core.UriInfo;
import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.StringUtils;
import org.mifosplatform.commands.data.CommandSourceData; import org.mifosplatform.commands.data.CommandSourceData;
import org.mifosplatform.commands.domain.CommandWrapper;
import org.mifosplatform.commands.service.CommandWrapperBuilder;
import org.mifosplatform.commands.service.PortfolioCommandSourceWritePlatformService; import org.mifosplatform.commands.service.PortfolioCommandSourceWritePlatformService;
import org.mifosplatform.commands.service.PortfolioCommandsReadPlatformService; import org.mifosplatform.commands.service.PortfolioCommandsReadPlatformService;
import org.mifosplatform.infrastructure.core.api.ApiParameterHelper; import org.mifosplatform.infrastructure.core.api.ApiParameterHelper;
import org.mifosplatform.infrastructure.core.api.ApiRequestParameterHelper; import org.mifosplatform.infrastructure.core.api.ApiRequestParameterHelper;
import org.mifosplatform.infrastructure.core.api.PortfolioApiDataConversionService; import org.mifosplatform.infrastructure.core.api.PortfolioApiDataConversionService;
import org.mifosplatform.infrastructure.core.data.EntityIdentifier; import org.mifosplatform.infrastructure.core.data.CommandProcessingResult;
import org.mifosplatform.infrastructure.core.serialization.ApiRequestJsonSerializationSettings; import org.mifosplatform.infrastructure.core.serialization.ApiRequestJsonSerializationSettings;
import org.mifosplatform.infrastructure.core.serialization.ToApiJsonSerializer; import org.mifosplatform.infrastructure.core.serialization.ToApiJsonSerializer;
import org.mifosplatform.infrastructure.security.service.PlatformSecurityContext; import org.mifosplatform.infrastructure.security.service.PlatformSecurityContext;
@@ -89,7 +91,8 @@ public class ClientsApiResource {
// FIXME - kw - rather than exposing SQL through the api can we not just // FIXME - kw - rather than exposing SQL through the api can we not just
// pass parameter we want to search by and build up sql like is done for // pass parameter we want to search by and build up sql like is done for
// other parameters? // other parameters?
final String extraCriteria = buildSqlStringFromClientCriteria(sqlSearch, officeId, externalId, displayName, firstName, lastName, hierarchy); final String extraCriteria = buildSqlStringFromClientCriteria(sqlSearch, officeId, externalId, displayName, firstName, lastName,
hierarchy);
final Collection<ClientData> clients = this.clientReadPlatformService.retrieveAllIndividualClients(extraCriteria); final Collection<ClientData> clients = this.clientReadPlatformService.retrieveAllIndividualClients(extraCriteria);
@@ -150,7 +153,8 @@ public class ClientsApiResource {
ClientData clientData = this.clientReadPlatformService.retrieveIndividualClient(clientId); ClientData clientData = this.clientReadPlatformService.retrieveIndividualClient(clientId);
if (settings.isTemplate()) { if (settings.isTemplate()) {
// FIXME - KW - no need for special OfficeLookup object, just use OfficeData and only populate with id, name, nameDecorated // FIXME - KW - no need for special OfficeLookup object, just use
// OfficeData and only populate with id, name, nameDecorated
final List<OfficeLookup> allowedOffices = new ArrayList<OfficeLookup>(officeReadPlatformService.retrieveAllOfficesForLookup()); final List<OfficeLookup> allowedOffices = new ArrayList<OfficeLookup>(officeReadPlatformService.retrieveAllOfficesForLookup());
clientData = ClientData.templateOnTop(clientData, allowedOffices); clientData = ClientData.templateOnTop(clientData, allowedOffices);
} }
@@ -216,8 +220,10 @@ public class ClientsApiResource {
@Produces({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON })
public String createClient(final String apiRequestBodyAsJson) { public String createClient(final String apiRequestBodyAsJson) {
final EntityIdentifier result = this.commandsSourceWritePlatformService.logCommandSource("CREATE", "CLIENT", "CREATE", "clients", final CommandWrapper commandRequest = new CommandWrapperBuilder().createClient().withUrl("/clients").withJson(apiRequestBodyAsJson)
null, apiRequestBodyAsJson); .build();
final CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest);
return this.toApiJsonSerializer.serialize(result); return this.toApiJsonSerializer.serialize(result);
} }
@@ -228,8 +234,10 @@ public class ClientsApiResource {
@Produces({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON })
public String updateClient(@PathParam("clientId") final Long clientId, final String apiRequestBodyAsJson) { public String updateClient(@PathParam("clientId") final Long clientId, final String apiRequestBodyAsJson) {
final EntityIdentifier result = this.commandsSourceWritePlatformService.logCommandSource("UPDATE", "CLIENT", "UPDATE", "clients", final CommandWrapper commandRequest = new CommandWrapperBuilder().updateClient().withUrl("/clients").withEntityId(clientId)
clientId, apiRequestBodyAsJson); .withJson(apiRequestBodyAsJson).build();
final CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest);
return this.toApiJsonSerializer.serialize(result); return this.toApiJsonSerializer.serialize(result);
} }
@@ -240,8 +248,10 @@ public class ClientsApiResource {
@Produces({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON })
public String deleteClient(@PathParam("clientId") final Long clientId) { public String deleteClient(@PathParam("clientId") final Long clientId) {
final EntityIdentifier result = this.commandsSourceWritePlatformService.logCommandSource("DELETE", "CLIENT", "DELETE", "clients", final CommandWrapper commandRequest = new CommandWrapperBuilder().deleteClient().withUrl("/clients").withEntityId(clientId)
clientId, "{}"); .withJson("{}").build();
final CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest);
return this.toApiJsonSerializer.serialize(result); return this.toApiJsonSerializer.serialize(result);
} }
@@ -23,6 +23,7 @@ import org.springframework.data.jpa.domain.AbstractPersistable;
@Table(name = "m_client") @Table(name = "m_client")
public class Client extends AbstractPersistable<Long> { public class Client extends AbstractPersistable<Long> {
@SuppressWarnings("unused")
@Column(name = "account_no", length=40, unique=true, nullable=false) @Column(name = "account_no", length=40, unique=true, nullable=false)
private String accountNumber; private String accountNumber;
@@ -81,7 +82,7 @@ public class Client extends AbstractPersistable<Long> {
} }
private Client(final Office office, final String firstName, final String lastName, final LocalDate openingDate, final String externalId) { private Client(final Office office, final String firstName, final String lastName, final LocalDate openingDate, final String externalId) {
this.accountNumber = new RandomPasswordGenerator(25).generate(); this.accountNumber = new RandomPasswordGenerator(19).generate();
this.office = office; this.office = office;
if (StringUtils.isNotBlank(externalId)) { if (StringUtils.isNotBlank(externalId)) {
this.externalId = externalId.trim(); this.externalId = externalId.trim();
@@ -2,7 +2,7 @@ package org.mifosplatform.portfolio.client.handler;
import org.mifosplatform.commands.handler.NewCommandSourceHandler; import org.mifosplatform.commands.handler.NewCommandSourceHandler;
import org.mifosplatform.infrastructure.core.api.JsonCommand; import org.mifosplatform.infrastructure.core.api.JsonCommand;
import org.mifosplatform.infrastructure.core.data.EntityIdentifier; import org.mifosplatform.infrastructure.core.data.CommandProcessingResult;
import org.mifosplatform.portfolio.client.service.ClientWritePlatformService; import org.mifosplatform.portfolio.client.service.ClientWritePlatformService;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@@ -20,7 +20,7 @@ public class CreateClientCommandHandler implements NewCommandSourceHandler {
@Transactional @Transactional
@Override @Override
public EntityIdentifier processCommand(final JsonCommand command) { public CommandProcessingResult processCommand(final JsonCommand command) {
return this.clientWritePlatformService.createClient(command); return this.clientWritePlatformService.createClient(command);
} }
@@ -2,7 +2,7 @@ package org.mifosplatform.portfolio.client.handler;
import org.mifosplatform.commands.handler.NewCommandSourceHandler; import org.mifosplatform.commands.handler.NewCommandSourceHandler;
import org.mifosplatform.infrastructure.core.api.JsonCommand; import org.mifosplatform.infrastructure.core.api.JsonCommand;
import org.mifosplatform.infrastructure.core.data.EntityIdentifier; import org.mifosplatform.infrastructure.core.data.CommandProcessingResult;
import org.mifosplatform.portfolio.client.service.ClientWritePlatformService; import org.mifosplatform.portfolio.client.service.ClientWritePlatformService;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@@ -20,8 +20,8 @@ public class CreateClientIdentifierCommandHandler implements NewCommandSourceHan
@Transactional @Transactional
@Override @Override
public EntityIdentifier processCommand(final JsonCommand command) { public CommandProcessingResult processCommand(final JsonCommand command) {
return this.clientWritePlatformService.addClientIdentifier(command.resourceId(), command); return this.clientWritePlatformService.addClientIdentifier(command.getClientId(), command);
} }
} }
@@ -2,7 +2,7 @@ package org.mifosplatform.portfolio.client.handler;
import org.mifosplatform.commands.handler.NewCommandSourceHandler; import org.mifosplatform.commands.handler.NewCommandSourceHandler;
import org.mifosplatform.infrastructure.core.api.JsonCommand; import org.mifosplatform.infrastructure.core.api.JsonCommand;
import org.mifosplatform.infrastructure.core.data.EntityIdentifier; import org.mifosplatform.infrastructure.core.data.CommandProcessingResult;
import org.mifosplatform.portfolio.client.service.ClientWritePlatformService; import org.mifosplatform.portfolio.client.service.ClientWritePlatformService;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@@ -20,8 +20,8 @@ public class CreateClientNoteCommandHandler implements NewCommandSourceHandler {
@Transactional @Transactional
@Override @Override
public EntityIdentifier processCommand(final JsonCommand command) { public CommandProcessingResult processCommand(final JsonCommand command) {
return this.clientWritePlatformService.addClientNote(command.resourceId(), command); return this.clientWritePlatformService.addClientNote(command.getClientId(), command);
} }
} }
@@ -2,7 +2,7 @@ package org.mifosplatform.portfolio.client.handler;
import org.mifosplatform.commands.handler.NewCommandSourceHandler; import org.mifosplatform.commands.handler.NewCommandSourceHandler;
import org.mifosplatform.infrastructure.core.api.JsonCommand; import org.mifosplatform.infrastructure.core.api.JsonCommand;
import org.mifosplatform.infrastructure.core.data.EntityIdentifier; import org.mifosplatform.infrastructure.core.data.CommandProcessingResult;
import org.mifosplatform.portfolio.client.service.ClientWritePlatformService; import org.mifosplatform.portfolio.client.service.ClientWritePlatformService;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@@ -20,8 +20,8 @@ public class DeleteClientCommandHandler implements NewCommandSourceHandler {
@Transactional @Transactional
@Override @Override
public EntityIdentifier processCommand(final JsonCommand command) { public CommandProcessingResult processCommand(final JsonCommand command) {
return this.clientWritePlatformService.deleteClient(command.resourceId()); return this.clientWritePlatformService.deleteClient(command.entityId());
} }
} }
@@ -2,7 +2,7 @@ package org.mifosplatform.portfolio.client.handler;
import org.mifosplatform.commands.handler.NewCommandSourceHandler; import org.mifosplatform.commands.handler.NewCommandSourceHandler;
import org.mifosplatform.infrastructure.core.api.JsonCommand; import org.mifosplatform.infrastructure.core.api.JsonCommand;
import org.mifosplatform.infrastructure.core.data.EntityIdentifier; import org.mifosplatform.infrastructure.core.data.CommandProcessingResult;
import org.mifosplatform.portfolio.client.service.ClientWritePlatformService; import org.mifosplatform.portfolio.client.service.ClientWritePlatformService;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@@ -20,8 +20,8 @@ public class DeleteClientIdentifierCommandHandler implements NewCommandSourceHan
@Transactional @Transactional
@Override @Override
public EntityIdentifier processCommand(final JsonCommand command) { public CommandProcessingResult processCommand(final JsonCommand command) {
return this.clientWritePlatformService.deleteClientIdentifier(command.resourceId(), command.subResourceId(), command.commandId()); return this.clientWritePlatformService.deleteClientIdentifier(command.getClientId(), command.entityId(), command.commandId());
} }
} }
@@ -2,7 +2,7 @@ package org.mifosplatform.portfolio.client.handler;
import org.mifosplatform.commands.handler.NewCommandSourceHandler; import org.mifosplatform.commands.handler.NewCommandSourceHandler;
import org.mifosplatform.infrastructure.core.api.JsonCommand; import org.mifosplatform.infrastructure.core.api.JsonCommand;
import org.mifosplatform.infrastructure.core.data.EntityIdentifier; import org.mifosplatform.infrastructure.core.data.CommandProcessingResult;
import org.mifosplatform.portfolio.client.service.ClientWritePlatformService; import org.mifosplatform.portfolio.client.service.ClientWritePlatformService;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@@ -20,8 +20,8 @@ public class UpdateClientCommandHandler implements NewCommandSourceHandler {
@Transactional @Transactional
@Override @Override
public EntityIdentifier processCommand(final JsonCommand command) { public CommandProcessingResult processCommand(final JsonCommand command) {
return this.clientWritePlatformService.updateClient(command.resourceId(), command); return this.clientWritePlatformService.updateClient(command.entityId(), command);
} }
} }
@@ -2,7 +2,7 @@ package org.mifosplatform.portfolio.client.handler;
import org.mifosplatform.commands.handler.NewCommandSourceHandler; import org.mifosplatform.commands.handler.NewCommandSourceHandler;
import org.mifosplatform.infrastructure.core.api.JsonCommand; import org.mifosplatform.infrastructure.core.api.JsonCommand;
import org.mifosplatform.infrastructure.core.data.EntityIdentifier; import org.mifosplatform.infrastructure.core.data.CommandProcessingResult;
import org.mifosplatform.portfolio.client.service.ClientWritePlatformService; import org.mifosplatform.portfolio.client.service.ClientWritePlatformService;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@@ -20,8 +20,8 @@ public class UpdateClientIdentifierCommandHandler implements NewCommandSourceHan
@Transactional @Transactional
@Override @Override
public EntityIdentifier processCommand(final JsonCommand command) { public CommandProcessingResult processCommand(final JsonCommand command) {
return this.clientWritePlatformService.updateClientIdentifier(command.resourceId(), command.subResourceId(), command); return this.clientWritePlatformService.updateClientIdentifier(command.getClientId(), command.entityId(), command);
} }
} }
@@ -2,7 +2,7 @@ package org.mifosplatform.portfolio.client.handler;
import org.mifosplatform.commands.handler.NewCommandSourceHandler; import org.mifosplatform.commands.handler.NewCommandSourceHandler;
import org.mifosplatform.infrastructure.core.api.JsonCommand; import org.mifosplatform.infrastructure.core.api.JsonCommand;
import org.mifosplatform.infrastructure.core.data.EntityIdentifier; import org.mifosplatform.infrastructure.core.data.CommandProcessingResult;
import org.mifosplatform.portfolio.client.service.ClientWritePlatformService; import org.mifosplatform.portfolio.client.service.ClientWritePlatformService;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@@ -20,8 +20,8 @@ public class UpdateClientNoteCommandHandler implements NewCommandSourceHandler {
@Transactional @Transactional
@Override @Override
public EntityIdentifier processCommand(final JsonCommand command) { public CommandProcessingResult processCommand(final JsonCommand command) {
return this.clientWritePlatformService.updateClientNote(command.resourceId(), command.subResourceId(), command); return this.clientWritePlatformService.updateClientNote(command.getClientId(), command.entityId(), command);
} }
} }
@@ -3,34 +3,34 @@ package org.mifosplatform.portfolio.client.service;
import java.io.InputStream; import java.io.InputStream;
import org.mifosplatform.infrastructure.core.api.JsonCommand; import org.mifosplatform.infrastructure.core.api.JsonCommand;
import org.mifosplatform.infrastructure.core.data.EntityIdentifier; import org.mifosplatform.infrastructure.core.data.CommandProcessingResult;
import org.mifosplatform.infrastructure.core.domain.Base64EncodedImage; import org.mifosplatform.infrastructure.core.domain.Base64EncodedImage;
import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.access.prepost.PreAuthorize;
public interface ClientWritePlatformService { public interface ClientWritePlatformService {
EntityIdentifier createClient(JsonCommand command); CommandProcessingResult createClient(JsonCommand command);
EntityIdentifier updateClient(Long clientId, JsonCommand command); CommandProcessingResult updateClient(Long clientId, JsonCommand command);
EntityIdentifier deleteClient(Long clientId); CommandProcessingResult deleteClient(Long clientId);
@PreAuthorize(value = "hasAnyRole('ALL_FUNCTIONS', 'PORTFOLIO_MANAGEMENT_SUPER_USER', 'CREATE_CLIENTIMAGE')") @PreAuthorize(value = "hasAnyRole('ALL_FUNCTIONS', 'PORTFOLIO_MANAGEMENT_SUPER_USER', 'CREATE_CLIENTIMAGE')")
EntityIdentifier saveOrUpdateClientImage(Long clientId, String imageName, InputStream inputStream); CommandProcessingResult saveOrUpdateClientImage(Long clientId, String imageName, InputStream inputStream);
@PreAuthorize(value = "hasAnyRole('ALL_FUNCTIONS', 'PORTFOLIO_MANAGEMENT_SUPER_USER', 'CREATE_CLIENTIMAGE')") @PreAuthorize(value = "hasAnyRole('ALL_FUNCTIONS', 'PORTFOLIO_MANAGEMENT_SUPER_USER', 'CREATE_CLIENTIMAGE')")
EntityIdentifier saveOrUpdateClientImage(Long clientId, Base64EncodedImage encodedImage); CommandProcessingResult saveOrUpdateClientImage(Long clientId, Base64EncodedImage encodedImage);
@PreAuthorize(value = "hasAnyRole('ALL_FUNCTIONS', 'PORTFOLIO_MANAGEMENT_SUPER_USER', 'DELETE_CLIENTIMAGE')") @PreAuthorize(value = "hasAnyRole('ALL_FUNCTIONS', 'PORTFOLIO_MANAGEMENT_SUPER_USER', 'DELETE_CLIENTIMAGE')")
EntityIdentifier deleteClientImage(Long clientId); CommandProcessingResult deleteClientImage(Long clientId);
EntityIdentifier addClientNote(Long clientId, JsonCommand command); CommandProcessingResult addClientNote(Long clientId, JsonCommand command);
EntityIdentifier updateClientNote(Long clientId, Long noteId, JsonCommand command); CommandProcessingResult updateClientNote(Long clientId, Long noteId, JsonCommand command);
EntityIdentifier addClientIdentifier(Long clientId, JsonCommand command); CommandProcessingResult addClientIdentifier(Long clientId, JsonCommand command);
EntityIdentifier updateClientIdentifier(Long clientId, Long clientIdentifierId, JsonCommand command); CommandProcessingResult updateClientIdentifier(Long clientId, Long clientIdentifierId, JsonCommand command);
EntityIdentifier deleteClientIdentifier(Long clientId, Long clientIdentifierId, Long commandId); CommandProcessingResult deleteClientIdentifier(Long clientId, Long clientIdentifierId, Long commandId);
} }
@@ -10,7 +10,8 @@ import org.mifosplatform.infrastructure.codes.domain.CodeValue;
import org.mifosplatform.infrastructure.codes.domain.CodeValueRepository; import org.mifosplatform.infrastructure.codes.domain.CodeValueRepository;
import org.mifosplatform.infrastructure.codes.exception.CodeValueNotFoundException; import org.mifosplatform.infrastructure.codes.exception.CodeValueNotFoundException;
import org.mifosplatform.infrastructure.core.api.JsonCommand; import org.mifosplatform.infrastructure.core.api.JsonCommand;
import org.mifosplatform.infrastructure.core.data.EntityIdentifier; import org.mifosplatform.infrastructure.core.data.CommandProcessingResult;
import org.mifosplatform.infrastructure.core.data.CommandProcessingResultBuilder;
import org.mifosplatform.infrastructure.core.domain.Base64EncodedImage; import org.mifosplatform.infrastructure.core.domain.Base64EncodedImage;
import org.mifosplatform.infrastructure.core.exception.PlatformDataIntegrityException; import org.mifosplatform.infrastructure.core.exception.PlatformDataIntegrityException;
import org.mifosplatform.infrastructure.core.service.FileUtils; import org.mifosplatform.infrastructure.core.service.FileUtils;
@@ -79,15 +80,17 @@ public class ClientWritePlatformServiceJpaRepositoryImpl implements ClientWriteP
@Transactional @Transactional
@Override @Override
public EntityIdentifier deleteClient(final Long clientId) { public CommandProcessingResult deleteClient(final Long clientId) {
final Client client = this.clientRepository.findOne(clientId); final Client client = this.clientRepository.findOne(clientId);
if (client == null || client.isDeleted()) { throw new ClientNotFoundException(clientId); } if (client == null || client.isDeleted()) { throw new ClientNotFoundException(clientId); }
final Long officeId = client.getOffice().getId();
client.delete(); client.delete();
this.clientRepository.save(client); this.clientRepository.save(client);
return EntityIdentifier.resourceResult(clientId, null); return new CommandProcessingResultBuilder().withOfficeId(officeId).withClientId(clientId).withEntityId(clientId).build();
} }
/* /*
@@ -111,7 +114,7 @@ public class ClientWritePlatformServiceJpaRepositoryImpl implements ClientWriteP
@Transactional @Transactional
@Override @Override
public EntityIdentifier createClient(final JsonCommand command) { public CommandProcessingResult createClient(final JsonCommand command) {
try { try {
context.authenticatedUser(); context.authenticatedUser();
@@ -128,21 +131,23 @@ public class ClientWritePlatformServiceJpaRepositoryImpl implements ClientWriteP
final Client newClient = Client.fromJson(clientOffice, command); final Client newClient = Client.fromJson(clientOffice, command);
this.clientRepository.save(newClient); this.clientRepository.save(newClient);
// now use client account identifier generator to generate proper account number // now use client account identifier generator to generate proper
// account number
AccountIdentifierGenerator generator = new ClientAccountIdentifierGenerator(newClient.getId(), 9); AccountIdentifierGenerator generator = new ClientAccountIdentifierGenerator(newClient.getId(), 9);
newClient.updateAccountIdentifier(generator.generate()); newClient.updateAccountIdentifier(generator.generate());
this.clientRepository.save(newClient); this.clientRepository.save(newClient);
return EntityIdentifier.resourceResult(newClient.getId(), null); return new CommandProcessingResultBuilder().withCommandId(command.commandId()).withOfficeId(clientOffice.getId())
.withClientId(newClient.getId()).withEntityId(newClient.getId()).build();
} catch (DataIntegrityViolationException dve) { } catch (DataIntegrityViolationException dve) {
handleDataIntegrityIssues(command, dve); handleDataIntegrityIssues(command, dve);
return EntityIdentifier.empty(); return CommandProcessingResult.empty();
} }
} }
@Transactional @Transactional
@Override @Override
public EntityIdentifier updateClient(final Long clientId, final JsonCommand command) { public CommandProcessingResult updateClient(final Long clientId, final JsonCommand command) {
try { try {
context.authenticatedUser(); context.authenticatedUser();
@@ -167,16 +172,17 @@ public class ClientWritePlatformServiceJpaRepositoryImpl implements ClientWriteP
this.clientRepository.save(clientForUpdate); this.clientRepository.save(clientForUpdate);
} }
return EntityIdentifier.withChanges(clientId, changes); return new CommandProcessingResultBuilder().withCommandId(command.commandId())
.withOfficeId(clientForUpdate.getOffice().getId()).withClientId(clientId).withEntityId(clientId).with(changes).build();
} catch (DataIntegrityViolationException dve) { } catch (DataIntegrityViolationException dve) {
handleDataIntegrityIssues(command, dve); handleDataIntegrityIssues(command, dve);
return new EntityIdentifier(Long.valueOf(-1)); return new CommandProcessingResult(Long.valueOf(-1));
} }
} }
@Transactional @Transactional
@Override @Override
public EntityIdentifier addClientNote(final Long clientId, final JsonCommand command) { public CommandProcessingResult addClientNote(final Long clientId, final JsonCommand command) {
context.authenticatedUser(); context.authenticatedUser();
@@ -190,12 +196,13 @@ public class ClientWritePlatformServiceJpaRepositoryImpl implements ClientWriteP
this.noteRepository.save(note); this.noteRepository.save(note);
return EntityIdentifier.subResourceResult(clientId, note.getId(), command.commandId()); return new CommandProcessingResultBuilder().withCommandId(command.commandId()).withOfficeId(clientForUpdate.getOffice().getId())
.withClientId(clientId).withEntityId(note.getId()).build();
} }
@Transactional @Transactional
@Override @Override
public EntityIdentifier updateClientNote(final Long clientId, final Long noteId, final JsonCommand command) { public CommandProcessingResult updateClientNote(final Long clientId, final Long noteId, final JsonCommand command) {
context.authenticatedUser(); context.authenticatedUser();
@@ -206,18 +213,21 @@ public class ClientWritePlatformServiceJpaRepositoryImpl implements ClientWriteP
if (noteForUpdate == null || noteForUpdate.isNotAgainstClientWithIdOf(clientId)) { throw new NoteNotFoundException(noteId, if (noteForUpdate == null || noteForUpdate.isNotAgainstClientWithIdOf(clientId)) { throw new NoteNotFoundException(noteId,
clientId, "client"); } clientId, "client"); }
final Client client = this.clientRepository.findOne(clientId);
final Map<String, Object> changes = noteForUpdate.update(command); final Map<String, Object> changes = noteForUpdate.update(command);
if (!changes.isEmpty()) { if (!changes.isEmpty()) {
this.noteRepository.save(noteForUpdate); this.noteRepository.save(noteForUpdate);
} }
return EntityIdentifier.subResourceResult(clientId, noteId, command.commandId(), changes); return new CommandProcessingResultBuilder().withCommandId(command.commandId()).withOfficeId(client.getOffice().getId())
.withClientId(clientId).withEntityId(noteId).with(changes).build();
} }
@Transactional @Transactional
@Override @Override
public EntityIdentifier addClientIdentifier(final Long clientId, final JsonCommand command) { public CommandProcessingResult addClientIdentifier(final Long clientId, final JsonCommand command) {
context.authenticatedUser(); context.authenticatedUser();
final ClientIdentifierCommand clientIdentifierCommand = this.clientIdentifierCommandFromApiJsonDeserializer final ClientIdentifierCommand clientIdentifierCommand = this.clientIdentifierCommandFromApiJsonDeserializer
@@ -241,16 +251,17 @@ public class ClientWritePlatformServiceJpaRepositoryImpl implements ClientWriteP
this.clientIdentifierRepository.save(clientIdentifier); this.clientIdentifierRepository.save(clientIdentifier);
return EntityIdentifier.subResourceResult(clientId, clientIdentifier.getId(), command.commandId()); return new CommandProcessingResultBuilder().withCommandId(command.commandId()).withOfficeId(client.getOffice().getId())
.withClientId(clientId).withEntityId(clientIdentifier.getId()).build();
} catch (DataIntegrityViolationException dve) { } catch (DataIntegrityViolationException dve) {
handleClientIdentifierDataIntegrityViolation(documentTypeLabel, documentTypeId, documentKey, dve); handleClientIdentifierDataIntegrityViolation(documentTypeLabel, documentTypeId, documentKey, dve);
return EntityIdentifier.empty(); return CommandProcessingResult.empty();
} }
} }
@Transactional @Transactional
@Override @Override
public EntityIdentifier updateClientIdentifier(final Long clientId, final Long identifierId, final JsonCommand command) { public CommandProcessingResult updateClientIdentifier(final Long clientId, final Long identifierId, final JsonCommand command) {
context.authenticatedUser(); context.authenticatedUser();
final ClientIdentifierCommand clientIdentifierCommand = this.clientIdentifierCommandFromApiJsonDeserializer final ClientIdentifierCommand clientIdentifierCommand = this.clientIdentifierCommandFromApiJsonDeserializer
@@ -291,10 +302,13 @@ public class ClientWritePlatformServiceJpaRepositoryImpl implements ClientWriteP
if (!changes.isEmpty()) { if (!changes.isEmpty()) {
this.clientIdentifierRepository.saveAndFlush(clientIdentifierForUpdate); this.clientIdentifierRepository.saveAndFlush(clientIdentifierForUpdate);
} }
return EntityIdentifier.subResourceResult(clientId, identifierId, command.commandId(), changes);
final Client client = this.clientRepository.findOne(clientId);
return new CommandProcessingResultBuilder().withCommandId(command.commandId()).withOfficeId(client.getOffice().getId())
.withClientId(clientId).withEntityId(identifierId).with(changes).build();
} catch (DataIntegrityViolationException dve) { } catch (DataIntegrityViolationException dve) {
handleClientIdentifierDataIntegrityViolation(documentTypeLabel, documentTypeId, documentKey, dve); handleClientIdentifierDataIntegrityViolation(documentTypeLabel, documentTypeId, documentKey, dve);
return new EntityIdentifier(Long.valueOf(-1)); return new CommandProcessingResult(Long.valueOf(-1));
} }
} }
@@ -317,17 +331,19 @@ public class ClientWritePlatformServiceJpaRepositoryImpl implements ClientWriteP
@Transactional @Transactional
@Override @Override
public EntityIdentifier deleteClientIdentifier(final Long clientId, final Long identifierId, final Long commandId) { public CommandProcessingResult deleteClientIdentifier(final Long clientId, final Long identifierId, final Long commandId) {
final ClientIdentifier clientIdentifier = this.clientIdentifierRepository.findOne(identifierId); final ClientIdentifier clientIdentifier = this.clientIdentifierRepository.findOne(identifierId);
if (clientIdentifier == null) { throw new ClientIdentifierNotFoundException(identifierId); } if (clientIdentifier == null) { throw new ClientIdentifierNotFoundException(identifierId); }
this.clientIdentifierRepository.delete(clientIdentifier); this.clientIdentifierRepository.delete(clientIdentifier);
return EntityIdentifier.subResourceResult(clientId, identifierId, commandId); final Client client = this.clientRepository.findOne(clientId);
return new CommandProcessingResultBuilder().withCommandId(commandId).withOfficeId(client.getOffice().getId())
.withClientId(clientId).withEntityId(identifierId).build();
} }
@Transactional @Transactional
@Override @Override
public EntityIdentifier saveOrUpdateClientImage(Long clientId, String imageName, InputStream inputStream) { public CommandProcessingResult saveOrUpdateClientImage(Long clientId, String imageName, InputStream inputStream) {
try { try {
final Client client = this.clientRepository.findOne(clientId); final Client client = this.clientRepository.findOne(clientId);
String imageUploadLocation = setupForClientImageUpdate(clientId, client); String imageUploadLocation = setupForClientImageUpdate(clientId, client);
@@ -343,7 +359,7 @@ public class ClientWritePlatformServiceJpaRepositoryImpl implements ClientWriteP
@Transactional @Transactional
@Override @Override
public EntityIdentifier deleteClientImage(final Long clientId) { public CommandProcessingResult deleteClientImage(final Long clientId) {
final Client client = this.clientRepository.findOne(clientId); final Client client = this.clientRepository.findOne(clientId);
if (client == null || client.isDeleted()) { throw new ClientNotFoundException(clientId); } if (client == null || client.isDeleted()) { throw new ClientNotFoundException(clientId); }
@@ -356,7 +372,7 @@ public class ClientWritePlatformServiceJpaRepositoryImpl implements ClientWriteP
} }
@Override @Override
public EntityIdentifier saveOrUpdateClientImage(final Long clientId, final Base64EncodedImage encodedImage) { public CommandProcessingResult saveOrUpdateClientImage(final Long clientId, final Base64EncodedImage encodedImage) {
try { try {
final Client client = this.clientRepository.findOne(clientId); final Client client = this.clientRepository.findOne(clientId);
final String imageUploadLocation = setupForClientImageUpdate(clientId, client); final String imageUploadLocation = setupForClientImageUpdate(clientId, client);
@@ -386,10 +402,10 @@ public class ClientWritePlatformServiceJpaRepositoryImpl implements ClientWriteP
return imageUploadLocation; return imageUploadLocation;
} }
private EntityIdentifier updateClientImage(final Long clientId, final Client client, final String imageLocation) { private CommandProcessingResult updateClientImage(final Long clientId, final Client client, final String imageLocation) {
client.setImageKey(imageLocation); client.setImageKey(imageLocation);
this.clientRepository.save(client); this.clientRepository.save(client);
return new EntityIdentifier(clientId); return new CommandProcessingResult(clientId);
} }
} }
@@ -16,10 +16,12 @@ import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriInfo; import javax.ws.rs.core.UriInfo;
import org.mifosplatform.commands.domain.CommandWrapper;
import org.mifosplatform.commands.service.CommandWrapperBuilder;
import org.mifosplatform.commands.service.PortfolioCommandSourceWritePlatformService; import org.mifosplatform.commands.service.PortfolioCommandSourceWritePlatformService;
import org.mifosplatform.infrastructure.codes.data.CodeData; import org.mifosplatform.infrastructure.codes.data.CodeData;
import org.mifosplatform.infrastructure.core.api.ApiRequestParameterHelper; import org.mifosplatform.infrastructure.core.api.ApiRequestParameterHelper;
import org.mifosplatform.infrastructure.core.data.EntityIdentifier; import org.mifosplatform.infrastructure.core.data.CommandProcessingResult;
import org.mifosplatform.infrastructure.core.serialization.ApiRequestJsonSerializationSettings; import org.mifosplatform.infrastructure.core.serialization.ApiRequestJsonSerializationSettings;
import org.mifosplatform.infrastructure.core.serialization.DefaultToApiJsonSerializer; import org.mifosplatform.infrastructure.core.serialization.DefaultToApiJsonSerializer;
import org.mifosplatform.infrastructure.security.service.PlatformSecurityContext; import org.mifosplatform.infrastructure.security.service.PlatformSecurityContext;
@@ -76,8 +78,10 @@ public class FundsApiResource {
@Produces({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON })
public String createFund(final String apiRequestBodyAsJson) { public String createFund(final String apiRequestBodyAsJson) {
final EntityIdentifier result = this.commandsSourceWritePlatformService.logCommandSource("CREATE", "FUND", "CREATE", "funds", null, final CommandWrapper commandRequest = new CommandWrapperBuilder().createFund().withUrl("/funds").withJson(apiRequestBodyAsJson)
apiRequestBodyAsJson); .build();
final CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest);
return this.toApiJsonSerializer.serialize(result); return this.toApiJsonSerializer.serialize(result);
} }
@@ -102,8 +106,10 @@ public class FundsApiResource {
@Produces({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON })
public String updateFund(@PathParam("fundId") final Long fundId, final String apiRequestBodyAsJson) { public String updateFund(@PathParam("fundId") final Long fundId, final String apiRequestBodyAsJson) {
final EntityIdentifier result = this.commandsSourceWritePlatformService.logCommandSource("UPDATE", "FUND", "UPDATE", "funds", final CommandWrapper commandRequest = new CommandWrapperBuilder().updateFund().withUrl("/funds").withEntityId(fundId)
fundId, apiRequestBodyAsJson); .withJson(apiRequestBodyAsJson).build();
final CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest);
return this.toApiJsonSerializer.serialize(result); return this.toApiJsonSerializer.serialize(result);
} }
@@ -2,7 +2,7 @@ package org.mifosplatform.portfolio.fund.handler;
import org.mifosplatform.commands.handler.NewCommandSourceHandler; import org.mifosplatform.commands.handler.NewCommandSourceHandler;
import org.mifosplatform.infrastructure.core.api.JsonCommand; import org.mifosplatform.infrastructure.core.api.JsonCommand;
import org.mifosplatform.infrastructure.core.data.EntityIdentifier; import org.mifosplatform.infrastructure.core.data.CommandProcessingResult;
import org.mifosplatform.portfolio.fund.service.FundWritePlatformService; import org.mifosplatform.portfolio.fund.service.FundWritePlatformService;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@@ -20,7 +20,7 @@ public class CreateFundCommandHandler implements NewCommandSourceHandler {
@Transactional @Transactional
@Override @Override
public EntityIdentifier processCommand(final JsonCommand command) { public CommandProcessingResult processCommand(final JsonCommand command) {
return this.writePlatformService.createFund(command); return this.writePlatformService.createFund(command);
} }
@@ -2,7 +2,7 @@ package org.mifosplatform.portfolio.fund.handler;
import org.mifosplatform.commands.handler.NewCommandSourceHandler; import org.mifosplatform.commands.handler.NewCommandSourceHandler;
import org.mifosplatform.infrastructure.core.api.JsonCommand; import org.mifosplatform.infrastructure.core.api.JsonCommand;
import org.mifosplatform.infrastructure.core.data.EntityIdentifier; import org.mifosplatform.infrastructure.core.data.CommandProcessingResult;
import org.mifosplatform.portfolio.fund.service.FundWritePlatformService; import org.mifosplatform.portfolio.fund.service.FundWritePlatformService;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@@ -20,8 +20,8 @@ public class UpdateFundCommandHandler implements NewCommandSourceHandler {
@Transactional @Transactional
@Override @Override
public EntityIdentifier processCommand(final JsonCommand command) { public CommandProcessingResult processCommand(final JsonCommand command) {
return this.writePlatformService.updateFund(command.resourceId(), command); return this.writePlatformService.updateFund(command.entityId(), command);
} }
} }
@@ -1,11 +1,11 @@
package org.mifosplatform.portfolio.fund.service; package org.mifosplatform.portfolio.fund.service;
import org.mifosplatform.infrastructure.core.api.JsonCommand; import org.mifosplatform.infrastructure.core.api.JsonCommand;
import org.mifosplatform.infrastructure.core.data.EntityIdentifier; import org.mifosplatform.infrastructure.core.data.CommandProcessingResult;
public interface FundWritePlatformService { public interface FundWritePlatformService {
EntityIdentifier createFund(JsonCommand command); CommandProcessingResult createFund(JsonCommand command);
EntityIdentifier updateFund(Long fundId, JsonCommand command); CommandProcessingResult updateFund(Long fundId, JsonCommand command);
} }
@@ -3,7 +3,8 @@ package org.mifosplatform.portfolio.fund.service;
import java.util.Map; import java.util.Map;
import org.mifosplatform.infrastructure.core.api.JsonCommand; import org.mifosplatform.infrastructure.core.api.JsonCommand;
import org.mifosplatform.infrastructure.core.data.EntityIdentifier; import org.mifosplatform.infrastructure.core.data.CommandProcessingResult;
import org.mifosplatform.infrastructure.core.data.CommandProcessingResultBuilder;
import org.mifosplatform.infrastructure.core.exception.PlatformDataIntegrityException; import org.mifosplatform.infrastructure.core.exception.PlatformDataIntegrityException;
import org.mifosplatform.infrastructure.security.service.PlatformSecurityContext; import org.mifosplatform.infrastructure.security.service.PlatformSecurityContext;
import org.mifosplatform.portfolio.fund.command.FundCommand; import org.mifosplatform.portfolio.fund.command.FundCommand;
@@ -38,7 +39,7 @@ public class FundWritePlatformServiceJpaRepositoryImpl implements FundWritePlatf
@Transactional @Transactional
@Override @Override
public EntityIdentifier createFund(final JsonCommand command) { public CommandProcessingResult createFund(final JsonCommand command) {
try { try {
context.authenticatedUser(); context.authenticatedUser();
@@ -50,16 +51,16 @@ public class FundWritePlatformServiceJpaRepositoryImpl implements FundWritePlatf
this.fundRepository.save(fund); this.fundRepository.save(fund);
return EntityIdentifier.resourceResult(fund.getId(), null); return new CommandProcessingResultBuilder().withCommandId(command.commandId()).withEntityId(fund.getId()).build();
} catch (DataIntegrityViolationException dve) { } catch (DataIntegrityViolationException dve) {
handleFundDataIntegrityIssues(command, dve); handleFundDataIntegrityIssues(command, dve);
return EntityIdentifier.empty(); return CommandProcessingResult.empty();
} }
} }
@Transactional @Transactional
@Override @Override
public EntityIdentifier updateFund(final Long fundId, final JsonCommand command) { public CommandProcessingResult updateFund(final Long fundId, final JsonCommand command) {
try { try {
context.authenticatedUser(); context.authenticatedUser();
@@ -75,10 +76,10 @@ public class FundWritePlatformServiceJpaRepositoryImpl implements FundWritePlatf
this.fundRepository.saveAndFlush(fund); this.fundRepository.saveAndFlush(fund);
} }
return EntityIdentifier.withChanges(fund.getId(), changes); return new CommandProcessingResultBuilder().withCommandId(command.commandId()).withEntityId(fund.getId()).with(changes).build();
} catch (DataIntegrityViolationException dve) { } catch (DataIntegrityViolationException dve) {
handleFundDataIntegrityIssues(command, dve); handleFundDataIntegrityIssues(command, dve);
return EntityIdentifier.empty(); return CommandProcessingResult.empty();
} }
} }
@@ -22,7 +22,7 @@ import org.apache.commons.lang.StringUtils;
import org.mifosplatform.infrastructure.core.api.ApiParameterHelper; import org.mifosplatform.infrastructure.core.api.ApiParameterHelper;
import org.mifosplatform.infrastructure.core.api.ApiRequestParameterHelper; import org.mifosplatform.infrastructure.core.api.ApiRequestParameterHelper;
import org.mifosplatform.infrastructure.core.api.PortfolioApiDataConversionService; import org.mifosplatform.infrastructure.core.api.PortfolioApiDataConversionService;
import org.mifosplatform.infrastructure.core.data.EntityIdentifier; import org.mifosplatform.infrastructure.core.data.CommandProcessingResult;
import org.mifosplatform.infrastructure.core.serialization.ApiRequestJsonSerializationSettings; import org.mifosplatform.infrastructure.core.serialization.ApiRequestJsonSerializationSettings;
import org.mifosplatform.infrastructure.core.serialization.ToApiJsonSerializer; import org.mifosplatform.infrastructure.core.serialization.ToApiJsonSerializer;
import org.mifosplatform.infrastructure.security.service.PlatformSecurityContext; import org.mifosplatform.infrastructure.security.service.PlatformSecurityContext;
@@ -156,7 +156,7 @@ public class GroupsApiResource {
final GroupCommand command = this.apiDataConversionService.convertJsonToGroupCommand(null, jsonRequestBody); final GroupCommand command = this.apiDataConversionService.convertJsonToGroupCommand(null, jsonRequestBody);
EntityIdentifier entityIdentifier = this.groupWritePlatformService.createGroup(command); CommandProcessingResult entityIdentifier = this.groupWritePlatformService.createGroup(command);
return this.toApiJsonSerializer.serialize(entityIdentifier); return this.toApiJsonSerializer.serialize(entityIdentifier);
} }
@@ -169,7 +169,7 @@ public class GroupsApiResource {
final GroupCommand command = this.apiDataConversionService.convertJsonToGroupCommand(groupId, jsonRequestBody); final GroupCommand command = this.apiDataConversionService.convertJsonToGroupCommand(groupId, jsonRequestBody);
EntityIdentifier entityIdentifier = this.groupWritePlatformService.updateGroup(command); CommandProcessingResult entityIdentifier = this.groupWritePlatformService.updateGroup(command);
return this.toApiJsonSerializer.serialize(entityIdentifier); return this.toApiJsonSerializer.serialize(entityIdentifier);
} }
@@ -180,7 +180,7 @@ public class GroupsApiResource {
@Produces({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON })
public String deleteGroup(@PathParam("groupId") final Long groupId) { public String deleteGroup(@PathParam("groupId") final Long groupId) {
EntityIdentifier entityIdentifier = this.groupWritePlatformService.deleteGroup(groupId); CommandProcessingResult entityIdentifier = this.groupWritePlatformService.deleteGroup(groupId);
return this.toApiJsonSerializer.serialize(entityIdentifier); return this.toApiJsonSerializer.serialize(entityIdentifier);
} }
@@ -33,13 +33,11 @@ public class Group extends AbstractAuditableCustom<AppUser, Long> {
@Column(name = "external_id", length = 100, unique = true) @Column(name = "external_id", length = 100, unique = true)
private String externalId; private String externalId;
@Column(name = "is_deleted", nullable=false) @Column(name = "is_deleted", nullable = false)
private boolean deleted = false; private boolean deleted = false;
@ManyToMany @ManyToMany
@JoinTable(name = "m_group_client", @JoinTable(name = "m_group_client", joinColumns = @JoinColumn(name = "group_id"), inverseJoinColumns = @JoinColumn(name = "client_id"))
joinColumns = @JoinColumn(name = "group_id"),
inverseJoinColumns = @JoinColumn(name = "client_id"))
private Set<Client> clientMembers; private Set<Client> clientMembers;
public Group() { public Group() {
@@ -48,7 +46,7 @@ public class Group extends AbstractAuditableCustom<AppUser, Long> {
this.clientMembers = new HashSet<Client>(); this.clientMembers = new HashSet<Client>();
} }
public static Group newGroup(Office office, String name, String externalId, Set<Client> clientMembers){ public static Group newGroup(Office office, String name, String externalId, Set<Client> clientMembers) {
return new Group(office, name, externalId, clientMembers); return new Group(office, name, externalId, clientMembers);
} }
@@ -64,7 +62,7 @@ public class Group extends AbstractAuditableCustom<AppUser, Long> {
} else { } else {
this.externalId = null; this.externalId = null;
} }
if (clientMembers != null){ if (clientMembers != null) {
this.clientMembers = clientMembers; this.clientMembers = clientMembers;
} }
} }
@@ -82,21 +80,22 @@ public class Group extends AbstractAuditableCustom<AppUser, Long> {
this.name = command.getName(); this.name = command.getName();
} }
if (clientMembers != null && command.isClientMembersChanged()){ if (clientMembers != null && command.isClientMembersChanged()) {
this.clientMembers = clientMembers; this.clientMembers = clientMembers;
} }
} }
public void addClientMember(final Client member){ public void addClientMember(final Client member) {
this.clientMembers.add(member); this.clientMembers.add(member);
} }
public boolean hasClientAsMember(final Client client){ public boolean hasClientAsMember(final Client client) {
return this.clientMembers.contains(client); return this.clientMembers.contains(client);
} }
/** /**
* Delete is a <i>soft delete</i>. Updates flag on group so it wont appear in query/report results. * Delete is a <i>soft delete</i>. Updates flag on group so it wont appear
* in query/report results.
* *
* Any fields with unique constraints and prepended with id of record. * Any fields with unique constraints and prepended with id of record.
*/ */
@@ -1,18 +1,18 @@
package org.mifosplatform.portfolio.group.service; package org.mifosplatform.portfolio.group.service;
import org.mifosplatform.infrastructure.core.data.EntityIdentifier; import org.mifosplatform.infrastructure.core.data.CommandProcessingResult;
import org.mifosplatform.portfolio.group.command.GroupCommand; import org.mifosplatform.portfolio.group.command.GroupCommand;
import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.access.prepost.PreAuthorize;
public interface GroupWritePlatformService { public interface GroupWritePlatformService {
@PreAuthorize(value = "hasAnyRole('ALL_FUNCTIONS', 'PORTFOLIO_MANAGEMENT_SUPER_USER', 'CREATE_GROUP')") @PreAuthorize(value = "hasAnyRole('ALL_FUNCTIONS', 'PORTFOLIO_MANAGEMENT_SUPER_USER', 'CREATE_GROUP')")
EntityIdentifier createGroup(GroupCommand command); CommandProcessingResult createGroup(GroupCommand command);
@PreAuthorize(value = "hasAnyRole('ALL_FUNCTIONS', 'PORTFOLIO_MANAGEMENT_SUPER_USER', 'UPDATE_GROUP')") @PreAuthorize(value = "hasAnyRole('ALL_FUNCTIONS', 'PORTFOLIO_MANAGEMENT_SUPER_USER', 'UPDATE_GROUP')")
EntityIdentifier updateGroup(GroupCommand command); CommandProcessingResult updateGroup(GroupCommand command);
@PreAuthorize(value = "hasAnyRole('ALL_FUNCTIONS', 'PORTFOLIO_MANAGEMENT_SUPER_USER', 'DELETE_GROUP')") @PreAuthorize(value = "hasAnyRole('ALL_FUNCTIONS', 'PORTFOLIO_MANAGEMENT_SUPER_USER', 'DELETE_GROUP')")
EntityIdentifier deleteGroup(Long groupId); CommandProcessingResult deleteGroup(Long groupId);
} }
@@ -3,7 +3,7 @@ package org.mifosplatform.portfolio.group.service;
import java.util.HashSet; import java.util.HashSet;
import java.util.Set; import java.util.Set;
import org.mifosplatform.infrastructure.core.data.EntityIdentifier; import org.mifosplatform.infrastructure.core.data.CommandProcessingResult;
import org.mifosplatform.infrastructure.core.exception.PlatformDataIntegrityException; import org.mifosplatform.infrastructure.core.exception.PlatformDataIntegrityException;
import org.mifosplatform.infrastructure.security.service.PlatformSecurityContext; import org.mifosplatform.infrastructure.security.service.PlatformSecurityContext;
import org.mifosplatform.organisation.office.domain.Office; import org.mifosplatform.organisation.office.domain.Office;
@@ -50,7 +50,7 @@ public class GroupWritePlatformServiceJpaRepositoryImpl implements GroupWritePla
@Transactional @Transactional
@Override @Override
public EntityIdentifier createGroup(GroupCommand command) { public CommandProcessingResult createGroup(GroupCommand command) {
try { try {
this.context.authenticatedUser(); this.context.authenticatedUser();
@@ -68,16 +68,16 @@ public class GroupWritePlatformServiceJpaRepositoryImpl implements GroupWritePla
this.groupRepository.saveAndFlush(newGroup); this.groupRepository.saveAndFlush(newGroup);
return new EntityIdentifier(newGroup.getId()); return new CommandProcessingResult(newGroup.getId());
} catch (DataIntegrityViolationException dve) { } catch (DataIntegrityViolationException dve) {
handleGroupDataIntegrityIssues(command, dve); handleGroupDataIntegrityIssues(command, dve);
return new EntityIdentifier(Long.valueOf(-1)); return new CommandProcessingResult(Long.valueOf(-1));
} }
} }
@Transactional @Transactional
@Override @Override
public EntityIdentifier updateGroup(GroupCommand command) { public CommandProcessingResult updateGroup(GroupCommand command) {
try { try {
context.authenticatedUser(); context.authenticatedUser();
@@ -105,16 +105,16 @@ public class GroupWritePlatformServiceJpaRepositoryImpl implements GroupWritePla
groupRepository.saveAndFlush(groupForUpdate); groupRepository.saveAndFlush(groupForUpdate);
return new EntityIdentifier(groupForUpdate.getId()); return new CommandProcessingResult(groupForUpdate.getId());
} catch (DataIntegrityViolationException dve) { } catch (DataIntegrityViolationException dve) {
handleGroupDataIntegrityIssues(command, dve); handleGroupDataIntegrityIssues(command, dve);
return new EntityIdentifier(Long.valueOf(-1)); return new CommandProcessingResult(Long.valueOf(-1));
} }
} }
@Transactional @Transactional
@Override @Override
public EntityIdentifier deleteGroup(Long groupId) { public CommandProcessingResult deleteGroup(Long groupId) {
context.authenticatedUser(); context.authenticatedUser();
@@ -125,7 +125,7 @@ public class GroupWritePlatformServiceJpaRepositoryImpl implements GroupWritePla
groupForDelete.delete(); groupForDelete.delete();
this.groupRepository.save(groupForDelete); this.groupRepository.save(groupForDelete);
return new EntityIdentifier(groupId); return new CommandProcessingResult(groupId);
} }
private Set<Client> assembleSetOfClients(final GroupCommand command) { private Set<Client> assembleSetOfClients(final GroupCommand command) {
@@ -16,9 +16,11 @@ import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriInfo; import javax.ws.rs.core.UriInfo;
import org.joda.time.LocalDate; import org.joda.time.LocalDate;
import org.mifosplatform.commands.domain.CommandWrapper;
import org.mifosplatform.commands.service.CommandWrapperBuilder;
import org.mifosplatform.commands.service.PortfolioCommandSourceWritePlatformService; import org.mifosplatform.commands.service.PortfolioCommandSourceWritePlatformService;
import org.mifosplatform.infrastructure.core.api.ApiRequestParameterHelper; import org.mifosplatform.infrastructure.core.api.ApiRequestParameterHelper;
import org.mifosplatform.infrastructure.core.data.EntityIdentifier; import org.mifosplatform.infrastructure.core.data.CommandProcessingResult;
import org.mifosplatform.infrastructure.core.serialization.ApiRequestJsonSerializationSettings; import org.mifosplatform.infrastructure.core.serialization.ApiRequestJsonSerializationSettings;
import org.mifosplatform.infrastructure.core.serialization.DefaultToApiJsonSerializer; import org.mifosplatform.infrastructure.core.serialization.DefaultToApiJsonSerializer;
import org.mifosplatform.infrastructure.security.service.PlatformSecurityContext; import org.mifosplatform.infrastructure.security.service.PlatformSecurityContext;
@@ -97,8 +99,10 @@ public class BulkLoansApiResource {
@Produces({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON })
public String loanReassignment(final String apiRequestBodyAsJson) { public String loanReassignment(final String apiRequestBodyAsJson) {
final EntityIdentifier result = this.commandsSourceWritePlatformService.logCommandSource("BULKREASSIGN", "LOAN", "N/A", "loans", final CommandWrapper commandRequest = new CommandWrapperBuilder().assignLoanOfficersInBulk().withUrl("/loans/loanreassignment")
null, apiRequestBodyAsJson); .withJson(apiRequestBodyAsJson).build();
final CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest);
return this.toApiJsonSerializer.serialize(result); return this.toApiJsonSerializer.serialize(result);
} }
@@ -19,9 +19,11 @@ import javax.ws.rs.core.MediaType;
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.mifosplatform.commands.domain.CommandWrapper;
import org.mifosplatform.commands.service.CommandWrapperBuilder;
import org.mifosplatform.commands.service.PortfolioCommandSourceWritePlatformService; import org.mifosplatform.commands.service.PortfolioCommandSourceWritePlatformService;
import org.mifosplatform.infrastructure.core.api.ApiRequestParameterHelper; import org.mifosplatform.infrastructure.core.api.ApiRequestParameterHelper;
import org.mifosplatform.infrastructure.core.data.EntityIdentifier; import org.mifosplatform.infrastructure.core.data.CommandProcessingResult;
import org.mifosplatform.infrastructure.core.exception.UnrecognizedQueryParamException; import org.mifosplatform.infrastructure.core.exception.UnrecognizedQueryParamException;
import org.mifosplatform.infrastructure.core.serialization.ApiRequestJsonSerializationSettings; import org.mifosplatform.infrastructure.core.serialization.ApiRequestJsonSerializationSettings;
import org.mifosplatform.infrastructure.core.serialization.DefaultToApiJsonSerializer; import org.mifosplatform.infrastructure.core.serialization.DefaultToApiJsonSerializer;
@@ -102,8 +104,10 @@ public class LoanChargesApiResource {
@Produces({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON })
public String addLoanCharge(@PathParam("loanId") final Long loanId, final String apiRequestBodyAsJson) { public String addLoanCharge(@PathParam("loanId") final Long loanId, final String apiRequestBodyAsJson) {
final EntityIdentifier result = this.commandsSourceWritePlatformService.logCommandSource("CREATE", "LOANCHARGE", "N/A", "loans", final CommandWrapper commandRequest = new CommandWrapperBuilder().createLoanCharge().withUrl("/loans/" + loanId + "/charges")
loanId, "charges", null, apiRequestBodyAsJson); .withLoanId(loanId).withJson(apiRequestBodyAsJson).build();
final CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest);
return this.toApiJsonSerializer.serialize(result); return this.toApiJsonSerializer.serialize(result);
} }
@@ -115,8 +119,10 @@ public class LoanChargesApiResource {
public String updateLoanCharge(@PathParam("loanId") final Long loanId, @PathParam("loanChargeId") final Long loanChargeId, public String updateLoanCharge(@PathParam("loanId") final Long loanId, @PathParam("loanChargeId") final Long loanChargeId,
final String apiRequestBodyAsJson) { final String apiRequestBodyAsJson) {
final EntityIdentifier result = this.commandsSourceWritePlatformService.logCommandSource("UPDATE", "LOANCHARGE", "N/A", "loans", final CommandWrapper commandRequest = new CommandWrapperBuilder().updateLoanCharge().withUrl("/loans/" + loanId + "/charges")
loanId, "charges", loanChargeId, apiRequestBodyAsJson); .withLoanId(loanId).withEntityId(loanChargeId).withJson(apiRequestBodyAsJson).build();
final CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest);
return this.toApiJsonSerializer.serialize(result); return this.toApiJsonSerializer.serialize(result);
} }
@@ -130,8 +136,10 @@ public class LoanChargesApiResource {
String json = ""; String json = "";
if (is(commandParam, "waive")) { if (is(commandParam, "waive")) {
final EntityIdentifier result = this.commandsSourceWritePlatformService.logCommandSource("WAIVE", "LOANCHARGE", "N/A", "loans", final CommandWrapper commandRequest = new CommandWrapperBuilder().waiveLoanCharge().withUrl("/loans/" + loanId + "/charges")
loanId, "charges", loanChargeId, "{}"); .withLoanId(loanId).withEntityId(loanChargeId).withJson("{}").build();
final CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest);
json = this.toApiJsonSerializer.serialize(result); json = this.toApiJsonSerializer.serialize(result);
} else { } else {
@@ -147,8 +155,10 @@ public class LoanChargesApiResource {
@Produces({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON })
public String deleteLoanCharge(@PathParam("loanId") final Long loanId, @PathParam("chargeId") final Long loanChargeId) { public String deleteLoanCharge(@PathParam("loanId") final Long loanId, @PathParam("chargeId") final Long loanChargeId) {
final EntityIdentifier result = this.commandsSourceWritePlatformService.logCommandSource("DELETE", "LOANCHARGE", "N/A", "loans", final CommandWrapper commandRequest = new CommandWrapperBuilder().deleteLoanCharge().withUrl("/loans/" + loanId + "/charges")
loanId, "charges", loanChargeId, "{}"); .withLoanId(loanId).withEntityId(loanChargeId).withJson("{}").build();
final CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest);
return this.toApiJsonSerializer.serialize(result); return this.toApiJsonSerializer.serialize(result);
} }
@@ -16,9 +16,11 @@ import javax.ws.rs.core.MediaType;
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.mifosplatform.commands.domain.CommandWrapper;
import org.mifosplatform.commands.service.CommandWrapperBuilder;
import org.mifosplatform.commands.service.PortfolioCommandSourceWritePlatformService; import org.mifosplatform.commands.service.PortfolioCommandSourceWritePlatformService;
import org.mifosplatform.infrastructure.core.api.ApiRequestParameterHelper; import org.mifosplatform.infrastructure.core.api.ApiRequestParameterHelper;
import org.mifosplatform.infrastructure.core.data.EntityIdentifier; import org.mifosplatform.infrastructure.core.data.CommandProcessingResult;
import org.mifosplatform.infrastructure.core.exception.UnrecognizedQueryParamException; import org.mifosplatform.infrastructure.core.exception.UnrecognizedQueryParamException;
import org.mifosplatform.infrastructure.core.serialization.ApiRequestJsonSerializationSettings; import org.mifosplatform.infrastructure.core.serialization.ApiRequestJsonSerializationSettings;
import org.mifosplatform.infrastructure.core.serialization.DefaultToApiJsonSerializer; import org.mifosplatform.infrastructure.core.serialization.DefaultToApiJsonSerializer;
@@ -115,22 +117,25 @@ public class LoanTransactionsApiResource {
public String executeLoanTransaction(@PathParam("loanId") final Long loanId, @QueryParam("command") final String commandParam, public String executeLoanTransaction(@PathParam("loanId") final Long loanId, @QueryParam("command") final String commandParam,
final String apiRequestBodyAsJson) { final String apiRequestBodyAsJson) {
EntityIdentifier result = null; CommandWrapperBuilder builder = new CommandWrapperBuilder().withUrl("/loans/" + loanId + "/transactions").withLoanId(loanId)
.withJson(apiRequestBodyAsJson);
CommandProcessingResult result = null;
if (is(commandParam, "repayment")) { if (is(commandParam, "repayment")) {
result = this.commandsSourceWritePlatformService.logCommandSource("REPAYMENT", "LOAN", "N/A", "loans", loanId, "transactions", final CommandWrapper commandRequest = builder.loanRepaymentTransaction().build();
null, apiRequestBodyAsJson); result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest);
} else if (is(commandParam, "waiveinterest")) { } else if (is(commandParam, "waiveinterest")) {
result = this.commandsSourceWritePlatformService.logCommandSource("WAIVEINTERESTPORTION", "LOAN", "N/A", "loans", loanId, final CommandWrapper commandRequest = builder.waiveInterestPortionTransaction().build();
"transactions", null, apiRequestBodyAsJson); result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest);
} else if (is(commandParam, "writeoff")) { } else if (is(commandParam, "writeoff")) {
result = this.commandsSourceWritePlatformService.logCommandSource("WRITEOFF", "LOAN", "N/A", "loans", loanId, "transactions", final CommandWrapper commandRequest = builder.writeOffLoanTransaction().build();
null, apiRequestBodyAsJson); result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest);
} else if (is(commandParam, "close-rescheduled")) { } else if (is(commandParam, "close-rescheduled")) {
result = this.commandsSourceWritePlatformService.logCommandSource("CLOSEASRESCHEDULED", "LOAN", "N/A", "loans", loanId, final CommandWrapper commandRequest = builder.closeLoanAsRescheduledTransaction().build();
"transactions", null, apiRequestBodyAsJson); result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest);
} else if (is(commandParam, "close")) { } else if (is(commandParam, "close")) {
result = this.commandsSourceWritePlatformService final CommandWrapper commandRequest = builder.closeLoanTransaction().build();
.logCommandSource("CLOSE", "LOAN", "N/A", "loans", loanId, apiRequestBodyAsJson); result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest);
} }
if (result == null) { throw new UnrecognizedQueryParamException("command", commandParam); } if (result == null) { throw new UnrecognizedQueryParamException("command", commandParam); }
@@ -145,9 +150,13 @@ public class LoanTransactionsApiResource {
public String adjustLoanTransaction(@PathParam("loanId") final Long loanId, @PathParam("transactionId") final Long transactionId, public String adjustLoanTransaction(@PathParam("loanId") final Long loanId, @PathParam("transactionId") final Long transactionId,
final String apiRequestBodyAsJson) { final String apiRequestBodyAsJson) {
final EntityIdentifier result = this.commandsSourceWritePlatformService.logCommandSource("ADJUST", "LOAN", "N/A", "loans", loanId, CommandWrapperBuilder builder = new CommandWrapperBuilder().withUrl("/loans/" + loanId + "/transactions").withLoanId(loanId).withEntityId(transactionId)
"transactions", transactionId, apiRequestBodyAsJson); .withJson(apiRequestBodyAsJson);
final CommandWrapper commandRequest = builder.adjustTransaction().build();
final CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest);
return this.toApiJsonSerializer.serialize(result); return this.toApiJsonSerializer.serialize(result);
} }
} }
@@ -20,11 +20,13 @@ import javax.ws.rs.core.UriInfo;
import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.StringUtils;
import org.joda.time.LocalDate; import org.joda.time.LocalDate;
import org.mifosplatform.commands.domain.CommandWrapper;
import org.mifosplatform.commands.service.CommandWrapperBuilder;
import org.mifosplatform.commands.service.PortfolioCommandSourceWritePlatformService; import org.mifosplatform.commands.service.PortfolioCommandSourceWritePlatformService;
import org.mifosplatform.infrastructure.core.api.ApiParameterHelper; import org.mifosplatform.infrastructure.core.api.ApiParameterHelper;
import org.mifosplatform.infrastructure.core.api.ApiRequestParameterHelper; import org.mifosplatform.infrastructure.core.api.ApiRequestParameterHelper;
import org.mifosplatform.infrastructure.core.api.JsonQuery; import org.mifosplatform.infrastructure.core.api.JsonQuery;
import org.mifosplatform.infrastructure.core.data.EntityIdentifier; import org.mifosplatform.infrastructure.core.data.CommandProcessingResult;
import org.mifosplatform.infrastructure.core.data.EnumOptionData; import org.mifosplatform.infrastructure.core.data.EnumOptionData;
import org.mifosplatform.infrastructure.core.exception.UnrecognizedQueryParamException; import org.mifosplatform.infrastructure.core.exception.UnrecognizedQueryParamException;
import org.mifosplatform.infrastructure.core.serialization.ApiRequestJsonSerializationSettings; import org.mifosplatform.infrastructure.core.serialization.ApiRequestJsonSerializationSettings;
@@ -331,8 +333,10 @@ public class LoansApiResource {
return this.loanScheduleToApiJsonSerializer.serialize(settings, loanSchedule, new HashSet<String>()); return this.loanScheduleToApiJsonSerializer.serialize(settings, loanSchedule, new HashSet<String>());
} }
final EntityIdentifier result = this.commandsSourceWritePlatformService.logCommandSource("CREATE", "LOAN", "CREATE", "loans", null, final CommandWrapper commandRequest = new CommandWrapperBuilder().createLoanApplication().withUrl("/loans")
apiRequestBodyAsJson); .withJson(apiRequestBodyAsJson).build();
final CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest);
return this.toApiJsonSerializer.serialize(result); return this.toApiJsonSerializer.serialize(result);
} }
@@ -343,8 +347,10 @@ public class LoansApiResource {
@Produces({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON })
public String modifyLoanApplication(@PathParam("loanId") final Long loanId, final String apiRequestBodyAsJson) { public String modifyLoanApplication(@PathParam("loanId") final Long loanId, final String apiRequestBodyAsJson) {
final EntityIdentifier result = this.commandsSourceWritePlatformService.logCommandSource("UPDATE", "LOAN", "UPDATE", "loans", final CommandWrapper commandRequest = new CommandWrapperBuilder().updateLoanApplication().withUrl("/loans").withLoanId(loanId)
loanId, apiRequestBodyAsJson); .withEntityId(loanId).withJson(apiRequestBodyAsJson).build();
final CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest);
return this.toApiJsonSerializer.serialize(result); return this.toApiJsonSerializer.serialize(result);
} }
@@ -355,8 +361,10 @@ public class LoansApiResource {
@Produces({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON })
public String deleteLoanApplication(@PathParam("loanId") final Long loanId) { public String deleteLoanApplication(@PathParam("loanId") final Long loanId) {
final EntityIdentifier result = this.commandsSourceWritePlatformService.logCommandSource("DELETE", "LOAN", "DELETE", "loans", final CommandWrapper commandRequest = new CommandWrapperBuilder().deleteLoanApplication().withUrl("/loans").withLoanId(loanId)
loanId, "{}"); .withEntityId(loanId).withJson("{}").build();
final CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest);
return this.toApiJsonSerializer.serialize(result); return this.toApiJsonSerializer.serialize(result);
} }
@@ -368,28 +376,31 @@ public class LoansApiResource {
public String stateTransitions(@PathParam("loanId") final Long loanId, @QueryParam("command") final String commandParam, public String stateTransitions(@PathParam("loanId") final Long loanId, @QueryParam("command") final String commandParam,
final String apiRequestBodyAsJson) { final String apiRequestBodyAsJson) {
EntityIdentifier result = null; final CommandWrapperBuilder builder = new CommandWrapperBuilder().withUrl("/loans").withLoanId(loanId).withEntityId(loanId)
.withJson(apiRequestBodyAsJson);
CommandProcessingResult result = null;
if (is(commandParam, "reject")) { if (is(commandParam, "reject")) {
result = this.commandsSourceWritePlatformService.logCommandSource("REJECT", "LOAN", "N/A", "loans", loanId, final CommandWrapper commandRequest = builder.rejectLoanApplication().build();
apiRequestBodyAsJson); result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest);
} else if (is(commandParam, "withdrewbyclient")) { } else if (is(commandParam, "withdrewbyclient")) {
result = this.commandsSourceWritePlatformService.logCommandSource("WITHDRAW", "LOAN", "N/A", "loans", loanId, final CommandWrapper commandRequest = builder.withdrawLoanApplication().build();
apiRequestBodyAsJson); result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest);
} else if (is(commandParam, "approve")) { } else if (is(commandParam, "approve")) {
result = this.commandsSourceWritePlatformService.logCommandSource("APPROVE", "LOAN", "N/A", "loans", loanId, final CommandWrapper commandRequest = builder.approveLoanApplication().build();
apiRequestBodyAsJson); result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest);
} else if (is(commandParam, "disburse")) { } else if (is(commandParam, "disburse")) {
result = this.commandsSourceWritePlatformService.logCommandSource("DISBURSE", "LOAN", "N/A", "loans", loanId, final CommandWrapper commandRequest = builder.disburseLoanApplication().build();
apiRequestBodyAsJson); result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest);
} }
if (is(commandParam, "undoapproval")) { if (is(commandParam, "undoapproval")) {
result = this.commandsSourceWritePlatformService.logCommandSource("APPROVALUNDO", "LOAN", "N/A", "loans", loanId, final CommandWrapper commandRequest = builder.undoLoanApplicationApproval().build();
apiRequestBodyAsJson); result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest);
} else if (is(commandParam, "undodisbursal")) { } else if (is(commandParam, "undodisbursal")) {
result = this.commandsSourceWritePlatformService.logCommandSource("DISBURSALUNDO", "LOAN", "N/A", "loans", loanId, final CommandWrapper commandRequest = builder.undoLoanApplicationDisbursal().build();
apiRequestBodyAsJson); result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest);
} }
if (result == null) { throw new UnrecognizedQueryParamException("command", commandParam); } if (result == null) { throw new UnrecognizedQueryParamException("command", commandParam); }
@@ -429,8 +440,10 @@ public class LoansApiResource {
@Produces({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON })
public String assignLoanOfficer(@PathParam("loanId") final Long loanId, final String apiRequestBodyAsJson) { public String assignLoanOfficer(@PathParam("loanId") final Long loanId, final String apiRequestBodyAsJson) {
final EntityIdentifier result = this.commandsSourceWritePlatformService.logCommandSource("UPDATELOANOFFICER", "LOAN", "N/A", final CommandWrapper commandRequest = new CommandWrapperBuilder().assignLoanOfficer().withUrl("/loans").withLoanId(loanId)
"loans", loanId, apiRequestBodyAsJson); .withEntityId(loanId).withJson(apiRequestBodyAsJson).build();
final CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest);
return this.toApiJsonSerializer.serialize(result); return this.toApiJsonSerializer.serialize(result);
} }
@@ -75,7 +75,6 @@ public class Loan extends AbstractAuditableCustom<AppUser, Long> {
@JoinColumn(name = "guarantor_id") @JoinColumn(name = "guarantor_id")
private Client guarantor; private Client guarantor;
@SuppressWarnings("unused")
@ManyToOne(optional = true) @ManyToOne(optional = true)
@JoinColumn(name = "group_id") @JoinColumn(name = "group_id")
private Group group; private Group group;
@@ -212,7 +211,8 @@ public class Loan extends AbstractAuditableCustom<AppUser, Long> {
final Set<LoanCharge> loanCharges) { final Set<LoanCharge> loanCharges) {
final LoanStatus status = null; final LoanStatus status = null;
LoanProductRelatedDetail loanRepaymentScheduleDetail = loanSchedule.loanProductRelatedDetail(); LoanProductRelatedDetail loanRepaymentScheduleDetail = loanSchedule.loanProductRelatedDetail();
return new Loan(client, null, fund, officer, transactionProcessingStrategy, loanProduct, loanRepaymentScheduleDetail, status, loanCharges); return new Loan(client, null, fund, officer, transactionProcessingStrategy, loanProduct, loanRepaymentScheduleDetail, status,
loanCharges);
} }
public static Loan newGroupLoanApplication(final Group group, final LoanProduct loanProduct, final Fund fund, final Staff officer, public static Loan newGroupLoanApplication(final Group group, final LoanProduct loanProduct, final Fund fund, final Staff officer,
@@ -220,12 +220,13 @@ public class Loan extends AbstractAuditableCustom<AppUser, Long> {
final Set<LoanCharge> loanCharges) { final Set<LoanCharge> loanCharges) {
final LoanStatus status = null; final LoanStatus status = null;
LoanProductRelatedDetail loanRepaymentScheduleDetail = loanSchedule.loanProductRelatedDetail(); LoanProductRelatedDetail loanRepaymentScheduleDetail = loanSchedule.loanProductRelatedDetail();
return new Loan(null, group, fund, officer, transactionProcessingStrategy, loanProduct, loanRepaymentScheduleDetail, status, loanCharges); return new Loan(null, group, fund, officer, transactionProcessingStrategy, loanProduct, loanRepaymentScheduleDetail, status,
loanCharges);
} }
public static Loan newIndividualLoanApplicationFromGroup(final Client client, final Group group, final LoanProduct loanProduct, final Fund fund, public static Loan newIndividualLoanApplicationFromGroup(final Client client, final Group group, final LoanProduct loanProduct,
final Staff officer, final LoanTransactionProcessingStrategy transactionProcessingStrategy, final LoanSchedule loanSchedule, final Fund fund, final Staff officer, final LoanTransactionProcessingStrategy transactionProcessingStrategy,
final Set<LoanCharge> loanCharges) { final LoanSchedule loanSchedule, final Set<LoanCharge> loanCharges) {
final LoanStatus status = null; final LoanStatus status = null;
LoanProductRelatedDetail loanRepaymentScheduleDetail = loanSchedule.loanProductRelatedDetail(); LoanProductRelatedDetail loanRepaymentScheduleDetail = loanSchedule.loanProductRelatedDetail();
return new Loan(client, group, fund, officer, transactionProcessingStrategy, loanProduct, loanRepaymentScheduleDetail, status, return new Loan(client, group, fund, officer, transactionProcessingStrategy, loanProduct, loanRepaymentScheduleDetail, status,
@@ -236,9 +237,9 @@ public class Loan extends AbstractAuditableCustom<AppUser, Long> {
// //
} }
private Loan(final Client client, final Group group, Fund fund, Staff loanOfficer, final LoanTransactionProcessingStrategy transactionProcessingStrategy, private Loan(final Client client, final Group group, Fund fund, Staff loanOfficer,
final LoanProduct loanProduct, final LoanProductRelatedDetail loanRepaymentScheduleDetail, final LoanStatus loanStatus, final LoanTransactionProcessingStrategy transactionProcessingStrategy, final LoanProduct loanProduct,
final Set<LoanCharge> loanCharges) { final LoanProductRelatedDetail loanRepaymentScheduleDetail, final LoanStatus loanStatus, final Set<LoanCharge> loanCharges) {
this.client = client; this.client = client;
this.group = group; this.group = group;
this.fund = fund; this.fund = fund;
@@ -436,7 +437,8 @@ public class Loan extends AbstractAuditableCustom<AppUser, Long> {
return actualChanges; return actualChanges;
} }
public LoanTransaction waiveLoanCharge(final LoanCharge loanCharge, final LoanLifecycleStateMachine loanLifecycleStateMachine, final Map<String, Object> changes) { public LoanTransaction waiveLoanCharge(final LoanCharge loanCharge, final LoanLifecycleStateMachine loanLifecycleStateMachine,
final Map<String, Object> changes) {
validateLoanIsNotClosed(loanCharge); validateLoanIsNotClosed(loanCharge);
@@ -968,8 +970,8 @@ public class Loan extends AbstractAuditableCustom<AppUser, Long> {
final LoanSchedule loanSchedule = new LoanSchedule(loanScheduleGenerator, applicationCurrency, principal, interestRatePerPeriod, final LoanSchedule loanSchedule = new LoanSchedule(loanScheduleGenerator, applicationCurrency, principal, interestRatePerPeriod,
interestRatePeriodFrequencyType, defaultAnnualNominalInterestRate, interestMethod, interestCalculationPeriodMethod, interestRatePeriodFrequencyType, defaultAnnualNominalInterestRate, interestMethod, interestCalculationPeriodMethod,
repaymentEvery, repaymentPeriodFrequencyType, numberOfRepayments, amortizationMethod, loanTermFrequency, repaymentEvery, repaymentPeriodFrequencyType, numberOfRepayments, amortizationMethod, loanTermFrequency,
loanTermPeriodFrequencyType, getNullPointerSafeLoanCharges(), this.getDisbursementDate(), this.getExpectedFirstRepaymentOnDate(), loanTermPeriodFrequencyType, getNullPointerSafeLoanCharges(), this.getDisbursementDate(),
this.getInterestChargedFromDate(), inArrearsTolerance); this.getExpectedFirstRepaymentOnDate(), this.getInterestChargedFromDate(), inArrearsTolerance);
final LoanScheduleData generatedData = loanSchedule.generate(); final LoanScheduleData generatedData = loanSchedule.generate();
@@ -1922,4 +1924,30 @@ public class Loan extends AbstractAuditableCustom<AppUser, Long> {
public Client getClient() { public Client getClient() {
return client; return client;
} }
public Long getClientId() {
Long clientId = null;
if (this.client != null) {
clientId = this.client.getId();
}
return clientId;
}
public Long getGroupId() {
Long groupId = null;
if (this.group != null) {
groupId = this.group.getId();
}
return groupId;
}
public Long getOfficeId() {
Long officeId = null;
if (this.client != null) {
officeId = this.client.getOffice().getId();
} else {
// officeId = this.group.getOffice().getId();
}
return officeId;
}
} }
@@ -20,7 +20,7 @@ import javax.ws.rs.core.UriInfo;
import org.mifosplatform.infrastructure.core.api.ApiParameterHelper; import org.mifosplatform.infrastructure.core.api.ApiParameterHelper;
import org.mifosplatform.infrastructure.core.api.PortfolioApiDataConversionService; import org.mifosplatform.infrastructure.core.api.PortfolioApiDataConversionService;
import org.mifosplatform.infrastructure.core.api.PortfolioApiJsonSerializerService; import org.mifosplatform.infrastructure.core.api.PortfolioApiJsonSerializerService;
import org.mifosplatform.infrastructure.core.data.EntityIdentifier; import org.mifosplatform.infrastructure.core.data.CommandProcessingResult;
import org.mifosplatform.infrastructure.security.service.PlatformSecurityContext; import org.mifosplatform.infrastructure.security.service.PlatformSecurityContext;
import org.mifosplatform.portfolio.loanaccount.gaurantor.command.GuarantorCommand; import org.mifosplatform.portfolio.loanaccount.gaurantor.command.GuarantorCommand;
import org.mifosplatform.portfolio.loanaccount.gaurantor.data.GuarantorData; import org.mifosplatform.portfolio.loanaccount.gaurantor.data.GuarantorData;
@@ -82,7 +82,7 @@ public class GuarantorsApiResource {
this.guarantorWritePlatformService.createGuarantor(loanId, command); this.guarantorWritePlatformService.createGuarantor(loanId, command);
// returns the loan Identifier for which the guarantor was associated // returns the loan Identifier for which the guarantor was associated
return Response.ok().entity(new EntityIdentifier(loanId)).build(); return Response.ok().entity(new CommandProcessingResult(loanId)).build();
} }
@PUT @PUT
@@ -93,7 +93,7 @@ public class GuarantorsApiResource {
this.guarantorWritePlatformService.updateGuarantor(loanId, command); this.guarantorWritePlatformService.updateGuarantor(loanId, command);
return Response.ok().entity(new EntityIdentifier(loanId)).build(); return Response.ok().entity(new CommandProcessingResult(loanId)).build();
} }
@DELETE @DELETE
@@ -101,6 +101,6 @@ public class GuarantorsApiResource {
@Produces({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON })
public Response deleteGuarantor(@PathParam("loanId") final Long loanId) { public Response deleteGuarantor(@PathParam("loanId") final Long loanId) {
this.guarantorWritePlatformService.removeGuarantor(loanId); this.guarantorWritePlatformService.removeGuarantor(loanId);
return Response.ok(new EntityIdentifier(loanId)).build(); return Response.ok(new CommandProcessingResult(loanId)).build();
} }
} }
@@ -2,7 +2,7 @@ package org.mifosplatform.portfolio.loanaccount.handler;
import org.mifosplatform.commands.handler.NewCommandSourceHandler; import org.mifosplatform.commands.handler.NewCommandSourceHandler;
import org.mifosplatform.infrastructure.core.api.JsonCommand; import org.mifosplatform.infrastructure.core.api.JsonCommand;
import org.mifosplatform.infrastructure.core.data.EntityIdentifier; import org.mifosplatform.infrastructure.core.data.CommandProcessingResult;
import org.mifosplatform.portfolio.loanaccount.service.LoanWritePlatformService; import org.mifosplatform.portfolio.loanaccount.service.LoanWritePlatformService;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@@ -20,8 +20,8 @@ public class AddLoanChargeCommandHandler implements NewCommandSourceHandler {
@Transactional @Transactional
@Override @Override
public EntityIdentifier processCommand(final JsonCommand command) { public CommandProcessingResult processCommand(final JsonCommand command) {
return this.writePlatformService.addLoanCharge(command.resourceId(), command); return this.writePlatformService.addLoanCharge(command.getLoanId(), command);
} }
} }
@@ -2,7 +2,7 @@ package org.mifosplatform.portfolio.loanaccount.handler;
import org.mifosplatform.commands.handler.NewCommandSourceHandler; import org.mifosplatform.commands.handler.NewCommandSourceHandler;
import org.mifosplatform.infrastructure.core.api.JsonCommand; import org.mifosplatform.infrastructure.core.api.JsonCommand;
import org.mifosplatform.infrastructure.core.data.EntityIdentifier; import org.mifosplatform.infrastructure.core.data.CommandProcessingResult;
import org.mifosplatform.portfolio.loanaccount.service.LoanWritePlatformService; import org.mifosplatform.portfolio.loanaccount.service.LoanWritePlatformService;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@@ -20,7 +20,7 @@ public class BulkUpdateLoanOfficerCommandHandler implements NewCommandSourceHand
@Transactional @Transactional
@Override @Override
public EntityIdentifier processCommand(final JsonCommand command) { public CommandProcessingResult processCommand(final JsonCommand command) {
return this.writePlatformService.bulkLoanReassignment(command); return this.writePlatformService.bulkLoanReassignment(command);
} }
@@ -2,7 +2,7 @@ package org.mifosplatform.portfolio.loanaccount.handler;
import org.mifosplatform.commands.handler.NewCommandSourceHandler; import org.mifosplatform.commands.handler.NewCommandSourceHandler;
import org.mifosplatform.infrastructure.core.api.JsonCommand; import org.mifosplatform.infrastructure.core.api.JsonCommand;
import org.mifosplatform.infrastructure.core.data.EntityIdentifier; import org.mifosplatform.infrastructure.core.data.CommandProcessingResult;
import org.mifosplatform.portfolio.loanaccount.service.LoanWritePlatformService; import org.mifosplatform.portfolio.loanaccount.service.LoanWritePlatformService;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@@ -20,8 +20,8 @@ public class CloseLoanAsRescheduledCommandHandler implements NewCommandSourceHan
@Transactional @Transactional
@Override @Override
public EntityIdentifier processCommand(final JsonCommand command) { public CommandProcessingResult processCommand(final JsonCommand command) {
return this.writePlatformService.closeAsRescheduled(command.resourceId(), command); return this.writePlatformService.closeAsRescheduled(command.getLoanId(), command);
} }
} }
@@ -2,7 +2,7 @@ package org.mifosplatform.portfolio.loanaccount.handler;
import org.mifosplatform.commands.handler.NewCommandSourceHandler; import org.mifosplatform.commands.handler.NewCommandSourceHandler;
import org.mifosplatform.infrastructure.core.api.JsonCommand; import org.mifosplatform.infrastructure.core.api.JsonCommand;
import org.mifosplatform.infrastructure.core.data.EntityIdentifier; import org.mifosplatform.infrastructure.core.data.CommandProcessingResult;
import org.mifosplatform.portfolio.loanaccount.service.LoanWritePlatformService; import org.mifosplatform.portfolio.loanaccount.service.LoanWritePlatformService;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@@ -20,8 +20,8 @@ public class CloseLoanCommandHandler implements NewCommandSourceHandler {
@Transactional @Transactional
@Override @Override
public EntityIdentifier processCommand(final JsonCommand command) { public CommandProcessingResult processCommand(final JsonCommand command) {
return this.writePlatformService.closeLoan(command.resourceId(), command); return this.writePlatformService.closeLoan(command.getLoanId(), command);
} }
} }
@@ -2,7 +2,7 @@ package org.mifosplatform.portfolio.loanaccount.handler;
import org.mifosplatform.commands.handler.NewCommandSourceHandler; import org.mifosplatform.commands.handler.NewCommandSourceHandler;
import org.mifosplatform.infrastructure.core.api.JsonCommand; import org.mifosplatform.infrastructure.core.api.JsonCommand;
import org.mifosplatform.infrastructure.core.data.EntityIdentifier; import org.mifosplatform.infrastructure.core.data.CommandProcessingResult;
import org.mifosplatform.portfolio.loanaccount.service.LoanWritePlatformService; import org.mifosplatform.portfolio.loanaccount.service.LoanWritePlatformService;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@@ -20,8 +20,8 @@ public class DeleteLoanChargeCommandHandler implements NewCommandSourceHandler {
@Transactional @Transactional
@Override @Override
public EntityIdentifier processCommand(final JsonCommand command) { public CommandProcessingResult processCommand(final JsonCommand command) {
return this.writePlatformService.deleteLoanCharge(command.resourceId(), command.subResourceId(), command); return this.writePlatformService.deleteLoanCharge(command.getLoanId(), command.entityId(), command);
} }
} }
@@ -2,7 +2,7 @@ package org.mifosplatform.portfolio.loanaccount.handler;
import org.mifosplatform.commands.handler.NewCommandSourceHandler; import org.mifosplatform.commands.handler.NewCommandSourceHandler;
import org.mifosplatform.infrastructure.core.api.JsonCommand; import org.mifosplatform.infrastructure.core.api.JsonCommand;
import org.mifosplatform.infrastructure.core.data.EntityIdentifier; import org.mifosplatform.infrastructure.core.data.CommandProcessingResult;
import org.mifosplatform.portfolio.loanaccount.service.LoanWritePlatformService; import org.mifosplatform.portfolio.loanaccount.service.LoanWritePlatformService;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@@ -20,8 +20,8 @@ public class DisburseLoanCommandHandler implements NewCommandSourceHandler {
@Transactional @Transactional
@Override @Override
public EntityIdentifier processCommand(final JsonCommand command) { public CommandProcessingResult processCommand(final JsonCommand command) {
return this.writePlatformService.disburseLoan(command.resourceId(), command); return this.writePlatformService.disburseLoan(command.entityId(), command);
} }
} }
@@ -2,7 +2,7 @@ package org.mifosplatform.portfolio.loanaccount.handler;
import org.mifosplatform.commands.handler.NewCommandSourceHandler; import org.mifosplatform.commands.handler.NewCommandSourceHandler;
import org.mifosplatform.infrastructure.core.api.JsonCommand; import org.mifosplatform.infrastructure.core.api.JsonCommand;
import org.mifosplatform.infrastructure.core.data.EntityIdentifier; import org.mifosplatform.infrastructure.core.data.CommandProcessingResult;
import org.mifosplatform.portfolio.loanaccount.service.LoanApplicationWritePlatformService; import org.mifosplatform.portfolio.loanaccount.service.LoanApplicationWritePlatformService;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@@ -20,8 +20,8 @@ public class LoanApplicationApprovalCommandHandler implements NewCommandSourceHa
@Transactional @Transactional
@Override @Override
public EntityIdentifier processCommand(final JsonCommand command) { public CommandProcessingResult processCommand(final JsonCommand command) {
return this.writePlatformService.approveLoanApplication(command.resourceId(), command); return this.writePlatformService.approveLoanApplication(command.entityId(), command);
} }
} }
@@ -2,7 +2,7 @@ package org.mifosplatform.portfolio.loanaccount.handler;
import org.mifosplatform.commands.handler.NewCommandSourceHandler; import org.mifosplatform.commands.handler.NewCommandSourceHandler;
import org.mifosplatform.infrastructure.core.api.JsonCommand; import org.mifosplatform.infrastructure.core.api.JsonCommand;
import org.mifosplatform.infrastructure.core.data.EntityIdentifier; import org.mifosplatform.infrastructure.core.data.CommandProcessingResult;
import org.mifosplatform.portfolio.loanaccount.service.LoanApplicationWritePlatformService; import org.mifosplatform.portfolio.loanaccount.service.LoanApplicationWritePlatformService;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@@ -20,8 +20,8 @@ public class LoanApplicationApprovalUndoCommandHandler implements NewCommandSour
@Transactional @Transactional
@Override @Override
public EntityIdentifier processCommand(final JsonCommand command) { public CommandProcessingResult processCommand(final JsonCommand command) {
return this.writePlatformService.undoLoanApplicationApproval(command.resourceId(), command); return this.writePlatformService.undoLoanApplicationApproval(command.entityId(), command);
} }
} }
@@ -2,7 +2,7 @@ package org.mifosplatform.portfolio.loanaccount.handler;
import org.mifosplatform.commands.handler.NewCommandSourceHandler; import org.mifosplatform.commands.handler.NewCommandSourceHandler;
import org.mifosplatform.infrastructure.core.api.JsonCommand; import org.mifosplatform.infrastructure.core.api.JsonCommand;
import org.mifosplatform.infrastructure.core.data.EntityIdentifier; import org.mifosplatform.infrastructure.core.data.CommandProcessingResult;
import org.mifosplatform.portfolio.loanaccount.service.LoanApplicationWritePlatformService; import org.mifosplatform.portfolio.loanaccount.service.LoanApplicationWritePlatformService;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@@ -20,8 +20,8 @@ public class LoanApplicationDeletionCommandHandler implements NewCommandSourceHa
@Transactional @Transactional
@Override @Override
public EntityIdentifier processCommand(final JsonCommand command) { public CommandProcessingResult processCommand(final JsonCommand command) {
return this.writePlatformService.deleteLoanApplication(command.resourceId()); return this.writePlatformService.deleteLoanApplication(command.entityId());
} }
} }
@@ -2,7 +2,7 @@ package org.mifosplatform.portfolio.loanaccount.handler;
import org.mifosplatform.commands.handler.NewCommandSourceHandler; import org.mifosplatform.commands.handler.NewCommandSourceHandler;
import org.mifosplatform.infrastructure.core.api.JsonCommand; import org.mifosplatform.infrastructure.core.api.JsonCommand;
import org.mifosplatform.infrastructure.core.data.EntityIdentifier; import org.mifosplatform.infrastructure.core.data.CommandProcessingResult;
import org.mifosplatform.portfolio.loanaccount.service.LoanApplicationWritePlatformService; import org.mifosplatform.portfolio.loanaccount.service.LoanApplicationWritePlatformService;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@@ -20,8 +20,8 @@ public class LoanApplicationModificationCommandHandler implements NewCommandSour
@Transactional @Transactional
@Override @Override
public EntityIdentifier processCommand(final JsonCommand command) { public CommandProcessingResult processCommand(final JsonCommand command) {
return this.writePlatformService.modifyLoanApplication(command.resourceId(), command); return this.writePlatformService.modifyLoanApplication(command.entityId(), command);
} }
} }

Some files were not shown because too many files have changed in this diff Show More