diff --git a/mifosng-provider/src/main/java/org/mifosng/platform/api/ClientsApiResource.java b/mifosng-provider/src/main/java/org/mifosng/platform/api/ClientsApiResource.java index 5c99ec082..8da641fc2 100644 --- a/mifosng-provider/src/main/java/org/mifosng/platform/api/ClientsApiResource.java +++ b/mifosng-provider/src/main/java/org/mifosng/platform/api/ClientsApiResource.java @@ -23,6 +23,7 @@ import javax.ws.rs.core.Response; import javax.ws.rs.core.UriInfo; import org.apache.commons.lang.StringUtils; +import org.mifosng.platform.api.commands.ClientCommand; import org.mifosng.platform.api.commands.NoteCommand; import org.mifosng.platform.api.data.ClientAccountSummaryCollectionData; import org.mifosng.platform.api.data.ClientData; @@ -31,6 +32,7 @@ import org.mifosng.platform.api.data.NoteData; import org.mifosng.platform.api.infrastructure.ApiConstants; import org.mifosng.platform.api.infrastructure.PortfolioApiDataConversionService; import org.mifosng.platform.api.infrastructure.PortfolioApiJsonSerializerService; +import org.mifosng.platform.api.infrastructure.PortfolioCommandSerializerService; import org.mifosng.platform.client.service.ClientReadPlatformService; import org.mifosng.platform.client.service.ClientWritePlatformService; import org.mifosng.platform.exceptions.ImageNotFoundException; @@ -61,33 +63,38 @@ public class ClientsApiResource { private final static Logger logger = LoggerFactory.getLogger(ClientsApiResource.class); - @Autowired - private ClientReadPlatformService clientReadPlatformService; + private final PlatformSecurityContext context; + private final ClientReadPlatformService clientReadPlatformService; + private final ClientWritePlatformService clientWritePlatformService; + private final OfficeReadPlatformService officeReadPlatformService; + private final PortfolioApiDataConversionService apiDataConversionService; + private final PortfolioCommandSerializerService commandSerializerService; + private final PortfolioApiJsonSerializerService apiJsonSerializerService; + private final PortfolioCommandsReadPlatformService commandSourceReadPlatformService; + private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService; @Autowired - private ClientWritePlatformService clientWritePlatformService; - - @Autowired - private PortfolioCommandsReadPlatformService commandSourceReadPlatformService; - - @Autowired - private PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService; - - @Autowired - private OfficeReadPlatformService officeReadPlatformService; - - @Autowired - private PortfolioApiDataConversionService apiDataConversionService; - - @Autowired - private PortfolioApiJsonSerializerService apiJsonSerializerService; - - @Autowired - private PlatformSecurityContext context; + public ClientsApiResource(final PlatformSecurityContext context, final ClientReadPlatformService readPlatformService, + final ClientWritePlatformService clientWritePlatformService, final OfficeReadPlatformService officeReadPlatformService, + final PortfolioApiDataConversionService apiDataConversionService, + final PortfolioCommandSerializerService commandSerializerService, + final PortfolioApiJsonSerializerService apiJsonSerializerService, + final PortfolioCommandsReadPlatformService commandsReadPlatformService, + final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService) { + this.context = context; + this.clientReadPlatformService = readPlatformService; + this.clientWritePlatformService = clientWritePlatformService; + this.officeReadPlatformService = officeReadPlatformService; + this.apiDataConversionService = apiDataConversionService; + this.commandSerializerService = commandSerializerService; + this.apiJsonSerializerService = apiJsonSerializerService; + this.commandSourceReadPlatformService = commandsReadPlatformService; + this.commandsSourceWritePlatformService = commandsSourceWritePlatformService; + } @GET - @Consumes({MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_JSON}) + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) public String retrieveAllIndividualClients(@Context final UriInfo uriInfo, @QueryParam("sqlSearch") final String sqlSearch, @QueryParam("officeId") final Integer officeId, @QueryParam("externalId") final String externalId, @QueryParam("displayName") final String displayName, @QueryParam("firstName") final String firstName, @@ -150,8 +157,8 @@ public class ClientsApiResource { @GET @Path("{clientId}") - @Consumes({MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_JSON}) + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) public String retrieveClient(@PathParam("clientId") final Long clientId, @Context final UriInfo uriInfo) { context.authenticatedUser().validateHasReadPermission("CLIENT"); @@ -170,14 +177,16 @@ public class ClientsApiResource { clientData = handleRequestToIntegrateProposedChangesFromCommand(clientId, commandId, clientData); } - // pick up possibility of changes by default - might push down a layer into the retrieve client method + // pick up possibility of changes by default - might push down a layer + // into the retrieve client method final Collection dataChanges = retrieveAllUnprocessedDataChanges(clientId); clientData = ClientData.integrateChanges(clientData, clientData.currentChange(), dataChanges); return this.apiJsonSerializerService.serializeClientDataToJson(prettyPrint, responseParameters, clientData); } - private ClientData handleRequestToIntegrateProposedChangesFromCommand(final Long clientId, final Long commandId, final ClientData clientData) { + private ClientData handleRequestToIntegrateProposedChangesFromCommand(final Long clientId, final Long commandId, + final ClientData clientData) { final CommandSourceData entry = this.commandSourceReadPlatformService.retrieveById(commandId); final ClientData currentChange = this.apiDataConversionService.convertInternalJsonFormatToClientDataChange(clientId, entry.json()); @@ -205,8 +214,8 @@ public class ClientsApiResource { @GET @Path("template") - @Consumes({MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_JSON}) + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) public String newClientDetails(@Context final UriInfo uriInfo) { context.authenticatedUser().validateHasReadPermission("CLIENT"); @@ -224,43 +233,49 @@ public class ClientsApiResource { } @POST - @Consumes({MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_JSON}) - public String createClient(final String jsonRequestBody) { + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) + public String createClient(final String apiRequestBodyAsJson) { final List allowedPermissions = Arrays.asList("ALL_FUNCTIONS", "PORTFOLIO_MANAGEMENT_SUPER_USER", "CREATE_CLIENT"); context.authenticatedUser().validateHasPermissionTo("CREATE_CLIENT", allowedPermissions); - - final EntityIdentifier result = this.commandsSourceWritePlatformService - .logCommandSource("CREATE", "clients", null, jsonRequestBody); + + final ClientCommand command = this.apiDataConversionService.convertApiRequestJsonToClientCommand(null, apiRequestBodyAsJson); + final String commandSerializedAsJson = this.commandSerializerService.serializeCommandToJson(command); + + final EntityIdentifier result = this.commandsSourceWritePlatformService.logCommandSource("CREATE", "clients", null, + commandSerializedAsJson); return this.apiJsonSerializerService.serializeEntityIdentifier(result); } @PUT @Path("{clientId}") - @Consumes({MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_JSON}) - public String updateClient(@PathParam("clientId") final Long clientId, final String jsonRequestBody) { + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) + public String updateClient(@PathParam("clientId") final Long clientId, final String apiRequestBodyAsJson) { final List allowedPermissions = Arrays.asList("ALL_FUNCTIONS", "PORTFOLIO_MANAGEMENT_SUPER_USER", "UPDATE_CLIENT"); context.authenticatedUser().validateHasPermissionTo("UPDATE_CLIENT", allowedPermissions); - + + final ClientCommand command = this.apiDataConversionService.convertApiRequestJsonToClientCommand(clientId, apiRequestBodyAsJson); + final String commandSerializedAsJson = this.commandSerializerService.serializeCommandToJson(command); + final EntityIdentifier result = this.commandsSourceWritePlatformService.logCommandSource("UPDATE", "clients", clientId, - jsonRequestBody); + commandSerializedAsJson); return this.apiJsonSerializerService.serializeEntityIdentifier(result); } @DELETE @Path("{clientId}") - @Consumes({MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_JSON}) + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) public String deleteClient(@PathParam("clientId") final Long clientId) { final List allowedPermissions = Arrays.asList("ALL_FUNCTIONS", "PORTFOLIO_MANAGEMENT_SUPER_USER", "DELETE_CLIENT"); context.authenticatedUser().validateHasPermissionTo("DELETE_CLIENT", allowedPermissions); - + final EntityIdentifier result = this.commandsSourceWritePlatformService.logCommandSource("DELETE", "clients", clientId, "{}"); return this.apiJsonSerializerService.serializeEntityIdentifier(result); @@ -268,8 +283,8 @@ public class ClientsApiResource { @GET @Path("{clientId}/loans") - @Consumes({MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_JSON}) + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) public String retrieveClientAccount(@PathParam("clientId") final Long clientId, @Context final UriInfo uriInfo) { context.authenticatedUser().validateHasReadPermission("CLIENT"); @@ -285,8 +300,8 @@ public class ClientsApiResource { @GET @Path("{clientId}/notes") - @Consumes({MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_JSON}) + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) public String retrieveAllClientNotes(@PathParam("clientId") final Long clientId, @Context final UriInfo uriInfo) { context.authenticatedUser().validateHasReadPermission("CLIENTNOTE"); @@ -301,8 +316,8 @@ public class ClientsApiResource { @POST @Path("{clientId}/notes") - @Consumes({MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_JSON}) + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) public Response addNewClientNote(@PathParam("clientId") final Long clientId, final String jsonRequestBody) { final NoteCommand command = this.apiDataConversionService.convertJsonToNoteCommand(null, clientId, jsonRequestBody); @@ -314,8 +329,8 @@ public class ClientsApiResource { @GET @Path("{clientId}/notes/{noteId}") - @Consumes({MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_JSON}) + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) public String retrieveClientNote(@PathParam("clientId") final Long clientId, @PathParam("noteId") final Long noteId, @Context final UriInfo uriInfo) { @@ -331,8 +346,8 @@ public class ClientsApiResource { @PUT @Path("{clientId}/notes/{noteId}") - @Consumes({MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_JSON}) + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) public Response updateClientNote(@PathParam("clientId") final Long clientId, @PathParam("noteId") final Long noteId, final String jsonRequestBody) { @@ -348,8 +363,8 @@ public class ClientsApiResource { */ @POST @Path("{clientId}/image") - @Consumes({MediaType.MULTIPART_FORM_DATA}) - @Produces({MediaType.APPLICATION_JSON}) + @Consumes({ MediaType.MULTIPART_FORM_DATA }) + @Produces({ MediaType.APPLICATION_JSON }) public Response addNewClientImage(@PathParam("clientId") final Long clientId, @HeaderParam("Content-Length") Long fileSize, @FormDataParam("file") InputStream inputStream, @FormDataParam("file") FormDataContentDisposition fileDetails, @FormDataParam("file") FormDataBodyPart bodyPart) { @@ -361,10 +376,10 @@ public class ClientsApiResource { FileUtils.validateImageMimeType(bodyPart.getMediaType().toString()); FileUtils.validateFileSizeWithinPermissibleRange(fileSize, fileDetails.getFileName(), ApiConstants.MAX_FILE_UPLOAD_SIZE_IN_MB); -// logger.debug(bodyPart.getMediaType().toString()); + // logger.debug(bodyPart.getMediaType().toString()); - final EntityIdentifier entityIdentifier = this.clientWritePlatformService.saveOrUpdateClientImage(clientId, fileDetails.getFileName(), - inputStream); + final EntityIdentifier entityIdentifier = this.clientWritePlatformService.saveOrUpdateClientImage(clientId, + fileDetails.getFileName(), inputStream); return Response.ok().entity(entityIdentifier).build(); } @@ -374,8 +389,8 @@ public class ClientsApiResource { */ @POST @Path("{clientId}/image") - @Consumes({MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_JSON}) + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) public Response addNewClientImage(@PathParam("clientId") final Long clientId, final String jsonRequestBody) { final Base64EncodedImage base64EncodedImage = FileUtils.extractImageFromDataURL(jsonRequestBody); @@ -390,8 +405,8 @@ public class ClientsApiResource { */ @GET @Path("{clientId}/image") - @Consumes({MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_JSON}) + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) public Response retrieveClientImage(@PathParam("clientId") final Long clientId) { context.authenticatedUser().validateHasReadPermission("CLIENTIMAGE"); @@ -408,8 +423,8 @@ public class ClientsApiResource { */ @PUT @Path("{clientId}/image") - @Consumes({MediaType.MULTIPART_FORM_DATA}) - @Produces({MediaType.APPLICATION_JSON}) + @Consumes({ MediaType.MULTIPART_FORM_DATA }) + @Produces({ MediaType.APPLICATION_JSON }) public Response updateClientImage(@PathParam("clientId") final Long clientId, @HeaderParam("Content-Length") Long fileSize, @FormDataParam("file") InputStream inputStream, @FormDataParam("file") FormDataContentDisposition fileDetails, @FormDataParam("file") FormDataBodyPart bodyPart) { @@ -418,8 +433,8 @@ public class ClientsApiResource { @DELETE @Path("{clientId}/image") - @Consumes({MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_JSON}) + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) public Response deleteClientImage(@PathParam("clientId") final Long clientId) { this.clientWritePlatformService.deleteClientImage(clientId); return Response.ok(new EntityIdentifier(clientId)).build(); @@ -433,8 +448,8 @@ public class ClientsApiResource { */ @PUT @Path("{clientId}/image") - @Consumes({MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_JSON}) + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) public Response updateClientImage(@PathParam("clientId") final Long clientId, final String jsonRequestBody) { return addNewClientImage(clientId, jsonRequestBody); } diff --git a/mifosng-provider/src/main/java/org/mifosng/platform/api/infrastructure/GoogleGsonPortfolioApiJsonSerializerService.java b/mifosng-provider/src/main/java/org/mifosng/platform/api/infrastructure/GoogleGsonPortfolioApiJsonSerializerService.java index f0c62c081..b28ffa689 100644 --- a/mifosng-provider/src/main/java/org/mifosng/platform/api/infrastructure/GoogleGsonPortfolioApiJsonSerializerService.java +++ b/mifosng-provider/src/main/java/org/mifosng/platform/api/infrastructure/GoogleGsonPortfolioApiJsonSerializerService.java @@ -5,7 +5,6 @@ import java.util.Collection; import java.util.HashSet; import java.util.Set; -import org.mifosng.platform.api.commands.ClientCommand; import org.mifosng.platform.api.data.ClientAccountSummaryCollectionData; import org.mifosng.platform.api.data.ClientData; import org.mifosng.platform.api.data.ClientIdentifierData; @@ -358,13 +357,6 @@ public class GoogleGsonPortfolioApiJsonSerializerService implements PortfolioApi return helper.serializedJsonFrom(gsonDeserializer, account); } - @Override - public String serializeClientCommandToJson(final ClientCommand command) { - final Gson gsonDeserializer = helper.createGsonBuilderWithParameterExclusionSerializationStrategy(new HashSet(), false, - new HashSet()); - return helper.serializedJsonFrom(gsonDeserializer, command); - } - @Override public String serializeClientDataToJson(final ClientData client) { return serializeClientDataToJson(false, new HashSet(), client); diff --git a/mifosng-provider/src/main/java/org/mifosng/platform/api/infrastructure/PortfolioApiDataConversionService.java b/mifosng-provider/src/main/java/org/mifosng/platform/api/infrastructure/PortfolioApiDataConversionService.java index 9d6f584f1..b027b47a1 100644 --- a/mifosng-provider/src/main/java/org/mifosng/platform/api/infrastructure/PortfolioApiDataConversionService.java +++ b/mifosng-provider/src/main/java/org/mifosng/platform/api/infrastructure/PortfolioApiDataConversionService.java @@ -30,12 +30,12 @@ import org.mifosplatform.infrastructure.user.command.PermissionsCommand; import org.mifosplatform.infrastructure.user.command.RoleCommand; import org.mifosplatform.infrastructure.user.command.RolePermissionCommand; import org.mifosplatform.infrastructure.user.command.UserCommand; -import org.mifosplatform.portfolio.charge.command.ChargeCommand; +import org.mifosplatform.portfolio.charge.command.ChargeDefinitionCommand; import org.mifosplatform.portfolio.fund.command.FundCommand; public interface PortfolioApiDataConversionService { - ChargeCommand convertJsonToChargeCommand(Long resourceIdentifier, String json); + ChargeDefinitionCommand convertApiRequestJsonToChargeDefinitionCommand(Long resourceIdentifier, String json); FundCommand convertApiRequestJsonToFundCommand(Long resourceIdentifier, String json); @@ -59,8 +59,6 @@ public interface PortfolioApiDataConversionService { ClientCommand convertApiRequestJsonToClientCommand(Long resourceIdentifier, String json); - ClientCommand convertInternalJsonFormatToClientCommand(Long resourceIdentifier, String json, boolean checkerApproved); - ClientData convertInternalJsonFormatToClientDataChange(Long clientId, String json); ClientCommand detectChanges(Long resourceId, String baseJson, String workingJson); diff --git a/mifosng-provider/src/main/java/org/mifosng/platform/api/infrastructure/PortfolioApiDataConversionServiceImpl.java b/mifosng-provider/src/main/java/org/mifosng/platform/api/infrastructure/PortfolioApiDataConversionServiceImpl.java index 3338d1392..89f43fb60 100644 --- a/mifosng-provider/src/main/java/org/mifosng/platform/api/infrastructure/PortfolioApiDataConversionServiceImpl.java +++ b/mifosng-provider/src/main/java/org/mifosng/platform/api/infrastructure/PortfolioApiDataConversionServiceImpl.java @@ -52,7 +52,7 @@ import org.mifosplatform.infrastructure.user.command.PermissionsCommand; import org.mifosplatform.infrastructure.user.command.RoleCommand; import org.mifosplatform.infrastructure.user.command.RolePermissionCommand; import org.mifosplatform.infrastructure.user.command.UserCommand; -import org.mifosplatform.portfolio.charge.command.ChargeCommand; +import org.mifosplatform.portfolio.charge.command.ChargeDefinitionCommand; import org.mifosplatform.portfolio.fund.command.FundCommand; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.format.number.NumberFormatter; @@ -92,7 +92,7 @@ public class PortfolioApiDataConversionServiceImpl implements PortfolioApiDataCo } @Override - public ChargeCommand convertJsonToChargeCommand(final Long resourceIdentifier, final String json) { + public ChargeDefinitionCommand convertApiRequestJsonToChargeDefinitionCommand(final Long resourceIdentifier, final String json) { if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } final Type typeOfMap = new TypeToken>() {}.getType(); @@ -103,21 +103,25 @@ public class PortfolioApiDataConversionServiceImpl implements PortfolioApiDataCo "active")); checkForUnsupportedParameters(requestMap, supportedParams); + + final JsonParserHelper helper = new JsonParserHelper(); + JsonParser parser = new JsonParser(); + final JsonElement element = parser.parse(json); - Set modifiedParameters = new HashSet(); + final Set parametersPassedInRequest = new HashSet(); - final String name = extractStringParameter("name", requestMap, modifiedParameters); - final BigDecimal amount = extractBigDecimalParameter("amount", requestMap, modifiedParameters); - final String currencyCode = extractStringParameter("currencyCode", requestMap, modifiedParameters); - - final Integer chargeTimeType = extractIntegerParameter("chargeTimeType", requestMap, modifiedParameters); - final Integer chargeAppliesTo = extractIntegerParameter("chargeAppliesTo", requestMap, modifiedParameters); - final Integer chargeCalculationType = extractIntegerParameter("chargeCalculationType", requestMap, modifiedParameters); - - final boolean penalty = extractBooleanParameter("penalty", requestMap, modifiedParameters); - final boolean active = extractBooleanParameter("active", requestMap, modifiedParameters); - - return new ChargeCommand(modifiedParameters, resourceIdentifier, name, amount, currencyCode, chargeTimeType, chargeAppliesTo, + final String name = helper.extractStringNamed("name", element, parametersPassedInRequest); + final String currencyCode = helper.extractStringNamed("currencyCode", element, parametersPassedInRequest); + final BigDecimal amount = helper.extractBigDecimalWithLocaleNamed("amount", element.getAsJsonObject(), parametersPassedInRequest); + + final Integer chargeTimeType = helper.extractIntegerWithLocaleNamed("chargeTimeType", element, parametersPassedInRequest); + final Integer chargeAppliesTo = helper.extractIntegerWithLocaleNamed("chargeAppliesTo", element, parametersPassedInRequest); + final Integer chargeCalculationType = helper.extractIntegerWithLocaleNamed("chargeCalculationType", element, parametersPassedInRequest); + + final Boolean penalty = helper.extractBooleanNamed("penalty", element, parametersPassedInRequest); + final Boolean active = helper.extractBooleanNamed("active", element, parametersPassedInRequest); + + return new ChargeDefinitionCommand(parametersPassedInRequest, false, resourceIdentifier, name, amount, currencyCode, chargeTimeType, chargeAppliesTo, chargeCalculationType, penalty, active); } @@ -466,39 +470,10 @@ public class PortfolioApiDataConversionServiceImpl implements PortfolioApiDataCo officeId, joiningDate, false); } - @Override - public ClientCommand convertInternalJsonFormatToClientCommand(final Long resourceIdentifier, final String json, - final boolean checkerApproved) { - if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } - - final Type typeOfMap = new TypeToken>() {}.getType(); - final Map requestMap = gsonConverter.fromJson(json, typeOfMap); - - final Set supportedParams = new HashSet(Arrays.asList("id", "externalId", "firstname", "lastname", - "clientOrBusinessName", "officeId", "joiningDate")); - - checkForUnsupportedParameters(requestMap, supportedParams); - - final JsonParser parser = new JsonParser(); - final JsonElement element = parser.parse(json); - final JsonParserHelper helper = new JsonParserHelper(); - final Set parametersPassedInRequest = new HashSet(); - - final Long officeId = helper.extractLongNamed("officeId", element, parametersPassedInRequest); - final String externalId = helper.extractStringNamed("externalId", element, parametersPassedInRequest); - final String firstname = helper.extractStringNamed("firstname", element, parametersPassedInRequest); - final String lastname = helper.extractStringNamed("lastname", element, parametersPassedInRequest); - final String clientOrBusinessName = helper.extractStringNamed("clientOrBusinessName", element, parametersPassedInRequest); - final LocalDate joiningDate = helper.extractLocalDateAsArrayNamed("joiningDate", element, parametersPassedInRequest); - - return new ClientCommand(parametersPassedInRequest, resourceIdentifier, externalId, firstname, lastname, clientOrBusinessName, - officeId, joiningDate, checkerApproved); - } - @Override public ClientData convertInternalJsonFormatToClientDataChange(final Long resourceIdentifier, final String json) { - final ClientCommand command = convertInternalJsonFormatToClientCommand(resourceIdentifier, json, false); + final ClientCommand command = this.portfolioCommandDeserializerService.deserializeClientCommand(resourceIdentifier, json, false); return ClientData.dataChangeInstance(resourceIdentifier, command.getOfficeId(), command.getExternalId(), command.getFirstname(), command.getLastname(), command.getClientOrBusinessName(), command.getJoiningDate()); @@ -570,14 +545,14 @@ public class PortfolioApiDataConversionServiceImpl implements PortfolioApiDataCo .extractLongNamed("transactionProcessingStrategyId", element, modifiedParameters); final String currencyCode = helper.extractStringNamed("currencyCode", element, modifiedParameters); - final Integer digitsAfterDecimal = helper.extractIntegerNamed("digitsAfterDecimal", element, modifiedParameters); + final Integer digitsAfterDecimal = helper.extractIntegerWithLocaleNamed("digitsAfterDecimal", element, modifiedParameters); - final BigDecimal principal = helper.extractBigDecimalNamed("principal", element, modifiedParameters); - final BigDecimal inArrearsTolerance = helper.extractBigDecimalNamed("inArrearsTolerance", element, modifiedParameters); - final BigDecimal interestRatePerPeriod = helper.extractBigDecimalNamed("interestRatePerPeriod", element, modifiedParameters); - final Integer repaymentEvery = helper.extractIntegerNamed("repaymentEvery", element, modifiedParameters); - final Integer numberOfRepayments = helper.extractIntegerNamed("numberOfRepayments", element, modifiedParameters); - final Integer repaymentFrequencyType = helper.extractIntegerNamed("repaymentFrequencyType", element, modifiedParameters); + final BigDecimal principal = helper.extractBigDecimalWithLocaleNamed("principal", element, modifiedParameters); + final BigDecimal inArrearsTolerance = helper.extractBigDecimalWithLocaleNamed("inArrearsTolerance", element, modifiedParameters); + final BigDecimal interestRatePerPeriod = helper.extractBigDecimalWithLocaleNamed("interestRatePerPeriod", element, modifiedParameters); + final Integer repaymentEvery = helper.extractIntegerWithLocaleNamed("repaymentEvery", element, modifiedParameters); + final Integer numberOfRepayments = helper.extractIntegerWithLocaleNamed("numberOfRepayments", element, modifiedParameters); + final Integer repaymentFrequencyType = helper.extractIntegerWithLocaleNamed("repaymentFrequencyType", element, modifiedParameters); // FIXME - A - LoanProduct - KW - should loan term fields be part of // product also as are basic part of 'loan terms' @@ -587,10 +562,10 @@ public class PortfolioApiDataConversionServiceImpl implements PortfolioApiDataCo // final Integer loanTermFrequencyType = // helper.extractIntegerNamed("loanTermFrequencyType", element, // modifiedParameters); - final Integer interestRateFrequencyType = helper.extractIntegerNamed("interestRateFrequencyType", element, modifiedParameters); - final Integer amortizationType = helper.extractIntegerNamed("amortizationType", element, modifiedParameters); - final Integer interestType = helper.extractIntegerNamed("interestType", element, modifiedParameters); - final Integer interestCalculationPeriodType = helper.extractIntegerNamed("interestCalculationPeriodType", element, + final Integer interestRateFrequencyType = helper.extractIntegerWithLocaleNamed("interestRateFrequencyType", element, modifiedParameters); + final Integer amortizationType = helper.extractIntegerWithLocaleNamed("amortizationType", element, modifiedParameters); + final Integer interestType = helper.extractIntegerWithLocaleNamed("interestType", element, modifiedParameters); + final Integer interestCalculationPeriodType = helper.extractIntegerWithLocaleNamed("interestCalculationPeriodType", element, modifiedParameters); String[] charges = null; @@ -642,20 +617,20 @@ public class PortfolioApiDataConversionServiceImpl implements PortfolioApiDataCo final Long transactionProcessingStrategyId = helper.extractLongNamed("transactionProcessingStrategyId", element, parametersPassedInCommand); final String externalId = helper.extractStringNamed("externalId", element, parametersPassedInCommand); - final BigDecimal principal = helper.extractBigDecimalNamed("principal", element, parametersPassedInCommand); - final BigDecimal inArrearsToleranceValue = helper.extractBigDecimalNamed("inArrearsTolerance", element, parametersPassedInCommand); - final BigDecimal interestRatePerPeriod = helper.extractBigDecimalNamed("interestRatePerPeriod", element, parametersPassedInCommand); + final BigDecimal principal = helper.extractBigDecimalWithLocaleNamed("principal", element, parametersPassedInCommand); + final BigDecimal inArrearsToleranceValue = helper.extractBigDecimalWithLocaleNamed("inArrearsTolerance", element, parametersPassedInCommand); + final BigDecimal interestRatePerPeriod = helper.extractBigDecimalWithLocaleNamed("interestRatePerPeriod", element, parametersPassedInCommand); - final Integer repaymentEvery = helper.extractIntegerNamed("repaymentEvery", element, parametersPassedInCommand); - final Integer numberOfRepayments = helper.extractIntegerNamed("numberOfRepayments", element, parametersPassedInCommand); - final Integer repaymentFrequencyType = helper.extractIntegerNamed("repaymentFrequencyType", element, parametersPassedInCommand); - final Integer loanTermFrequency = helper.extractIntegerNamed("loanTermFrequency", element, parametersPassedInCommand); - final Integer loanTermFrequencyType = helper.extractIntegerNamed("loanTermFrequencyType", element, parametersPassedInCommand); - final Integer interestRateFrequencyType = helper.extractIntegerNamed("interestRateFrequencyType", element, + final Integer repaymentEvery = helper.extractIntegerWithLocaleNamed("repaymentEvery", element, parametersPassedInCommand); + final Integer numberOfRepayments = helper.extractIntegerWithLocaleNamed("numberOfRepayments", element, parametersPassedInCommand); + final Integer repaymentFrequencyType = helper.extractIntegerWithLocaleNamed("repaymentFrequencyType", element, parametersPassedInCommand); + final Integer loanTermFrequency = helper.extractIntegerWithLocaleNamed("loanTermFrequency", element, parametersPassedInCommand); + final Integer loanTermFrequencyType = helper.extractIntegerWithLocaleNamed("loanTermFrequencyType", element, parametersPassedInCommand); + final Integer interestRateFrequencyType = helper.extractIntegerWithLocaleNamed("interestRateFrequencyType", element, parametersPassedInCommand); - final Integer amortizationType = helper.extractIntegerNamed("amortizationType", element, parametersPassedInCommand); - final Integer interestType = helper.extractIntegerNamed("interestType", element, parametersPassedInCommand); - final Integer interestCalculationPeriodType = helper.extractIntegerNamed("interestCalculationPeriodType", element, + final Integer amortizationType = helper.extractIntegerWithLocaleNamed("amortizationType", element, parametersPassedInCommand); + final Integer interestType = helper.extractIntegerWithLocaleNamed("interestType", element, parametersPassedInCommand); + final Integer interestCalculationPeriodType = helper.extractIntegerWithLocaleNamed("interestCalculationPeriodType", element, parametersPassedInCommand); final LocalDate expectedDisbursementDate = helper.extractLocalDateNamed("expectedDisbursementDate", element, diff --git a/mifosng-provider/src/main/java/org/mifosng/platform/api/infrastructure/PortfolioApiJsonSerializerService.java b/mifosng-provider/src/main/java/org/mifosng/platform/api/infrastructure/PortfolioApiJsonSerializerService.java index 9f54dcf7d..0c39479ac 100644 --- a/mifosng-provider/src/main/java/org/mifosng/platform/api/infrastructure/PortfolioApiJsonSerializerService.java +++ b/mifosng-provider/src/main/java/org/mifosng/platform/api/infrastructure/PortfolioApiJsonSerializerService.java @@ -3,7 +3,6 @@ package org.mifosng.platform.api.infrastructure; import java.util.Collection; import java.util.Set; -import org.mifosng.platform.api.commands.ClientCommand; import org.mifosng.platform.api.data.ClientAccountSummaryCollectionData; import org.mifosng.platform.api.data.ClientData; import org.mifosng.platform.api.data.ClientIdentifierData; @@ -90,8 +89,6 @@ public interface PortfolioApiJsonSerializerService { String serializeDepositAccountDataToJson(boolean prettyPrint, Set responseParameters, DepositAccountData account); - String serializeClientCommandToJson(ClientCommand command); - String serializeClientDataToJson(ClientData clientData); String serializeClientDataToJson(boolean prettyPrint, Set responseParameters, ClientData clientData); diff --git a/mifosng-provider/src/main/java/org/mifosng/platform/api/infrastructure/PortfolioCommandDeerializerServiceGoogleGson.java b/mifosng-provider/src/main/java/org/mifosng/platform/api/infrastructure/PortfolioCommandDeerializerServiceGoogleGson.java index efadf536b..7b4044bff 100644 --- a/mifosng-provider/src/main/java/org/mifosng/platform/api/infrastructure/PortfolioCommandDeerializerServiceGoogleGson.java +++ b/mifosng-provider/src/main/java/org/mifosng/platform/api/infrastructure/PortfolioCommandDeerializerServiceGoogleGson.java @@ -7,6 +7,7 @@ import java.util.Set; import org.apache.commons.lang.StringUtils; import org.joda.time.LocalDate; +import org.mifosng.platform.api.commands.ClientCommand; import org.mifosng.platform.infrastructure.api.JsonParserHelper; import org.mifosng.platform.infrastructure.errorhandling.InvalidJsonException; import org.mifosplatform.infrastructure.codes.command.CodeCommand; @@ -18,6 +19,7 @@ import org.mifosplatform.infrastructure.user.command.PermissionsCommand; import org.mifosplatform.infrastructure.user.command.RoleCommand; import org.mifosplatform.infrastructure.user.command.RolePermissionCommand; import org.mifosplatform.infrastructure.user.command.UserCommand; +import org.mifosplatform.portfolio.charge.command.ChargeDefinitionCommand; import org.mifosplatform.portfolio.fund.command.FundCommand; import org.springframework.stereotype.Service; @@ -221,4 +223,51 @@ public class PortfolioCommandDeerializerServiceGoogleGson implements PortfolioCo return new CurrencyCommand(makerCheckerApproval, currencies); } + + @Override + public ChargeDefinitionCommand deserializeChargeDefinitionCommand(final Long chargeDefinitionId, final String commandAsJson, final boolean makerCheckerApproval) { + + if (StringUtils.isBlank(commandAsJson)) { throw new InvalidJsonException(); } + + final JsonParserHelper helper = new JsonParserHelper(); + final JsonElement element = parser.parse(commandAsJson); + + final Set parametersPassedInRequest = new HashSet(); + + final String name = helper.extractStringNamed("name", element, parametersPassedInRequest); + final String currencyCode = helper.extractStringNamed("currencyCode", element, parametersPassedInRequest); + final BigDecimal amount = helper.extractBigDecimalNamed("amount", element.getAsJsonObject(), Locale.US, parametersPassedInRequest); + + final Integer chargeTimeType = helper.extractIntegerNamed("chargeTimeType", element, Locale.US, parametersPassedInRequest); + final Integer chargeAppliesTo = helper.extractIntegerNamed("chargeAppliesTo", element, Locale.US, parametersPassedInRequest); + final Integer chargeCalculationType = helper.extractIntegerNamed("chargeCalculationType", element, Locale.US, parametersPassedInRequest); + + final Boolean penalty = helper.extractBooleanNamed("penalty", element, parametersPassedInRequest); + final Boolean active = helper.extractBooleanNamed("active", element, parametersPassedInRequest); + + return new ChargeDefinitionCommand(parametersPassedInRequest, makerCheckerApproval, chargeDefinitionId, name, amount, currencyCode, chargeTimeType, chargeAppliesTo, + chargeCalculationType, penalty, active); + } + + @Override + public ClientCommand deserializeClientCommand(final Long clientId, final String commandAsJson, final boolean makerCheckerApproval) { + + if (StringUtils.isBlank(commandAsJson)) { throw new InvalidJsonException(); } + + final JsonParserHelper helper = new JsonParserHelper(); + final JsonElement element = parser.parse(commandAsJson); + + final Set parametersPassedInRequest = new HashSet(); + + final Long officeId = helper.extractLongNamed("officeId", element, parametersPassedInRequest); + final String externalId = helper.extractStringNamed("externalId", element, parametersPassedInRequest); + final String firstname = helper.extractStringNamed("firstname", element, parametersPassedInRequest); + final String lastname = helper.extractStringNamed("lastname", element, parametersPassedInRequest); + final String clientOrBusinessName = helper.extractStringNamed("clientOrBusinessName", element, parametersPassedInRequest); + final LocalDate joiningDate = helper.extractLocalDateAsArrayNamed("joiningDate", element, parametersPassedInRequest); + + return new ClientCommand(parametersPassedInRequest, clientId, externalId, firstname, lastname, clientOrBusinessName, + officeId, joiningDate, makerCheckerApproval); + + } } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosng/platform/api/infrastructure/PortfolioCommandDeserializerService.java b/mifosng-provider/src/main/java/org/mifosng/platform/api/infrastructure/PortfolioCommandDeserializerService.java index ae972d21c..67745edcc 100644 --- a/mifosng-provider/src/main/java/org/mifosng/platform/api/infrastructure/PortfolioCommandDeserializerService.java +++ b/mifosng-provider/src/main/java/org/mifosng/platform/api/infrastructure/PortfolioCommandDeserializerService.java @@ -1,5 +1,6 @@ package org.mifosng.platform.api.infrastructure; +import org.mifosng.platform.api.commands.ClientCommand; import org.mifosplatform.infrastructure.codes.command.CodeCommand; import org.mifosplatform.infrastructure.configuration.command.CurrencyCommand; import org.mifosplatform.infrastructure.office.command.BranchMoneyTransferCommand; @@ -9,6 +10,7 @@ import org.mifosplatform.infrastructure.user.command.PermissionsCommand; import org.mifosplatform.infrastructure.user.command.RoleCommand; import org.mifosplatform.infrastructure.user.command.RolePermissionCommand; import org.mifosplatform.infrastructure.user.command.UserCommand; +import org.mifosplatform.portfolio.charge.command.ChargeDefinitionCommand; import org.mifosplatform.portfolio.fund.command.FundCommand; /** @@ -42,4 +44,8 @@ public interface PortfolioCommandDeserializerService { BranchMoneyTransferCommand deserializeOfficeTransactionCommand(String commandAsJson, boolean makerCheckerApproval); CurrencyCommand deserializeCurrencyCommand(String commandAsJson, boolean makerCheckerApproval); + + ChargeDefinitionCommand deserializeChargeDefinitionCommand(Long chargeDefinitionId, String commandAsJson, boolean makerCheckerApproval); + + ClientCommand deserializeClientCommand(Long clientId, String commandAsJson, boolean makerCheckerApproval); } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosng/platform/api/infrastructure/PortfolioCommandSerializerService.java b/mifosng-provider/src/main/java/org/mifosng/platform/api/infrastructure/PortfolioCommandSerializerService.java index e56884f4f..dde64bf76 100644 --- a/mifosng-provider/src/main/java/org/mifosng/platform/api/infrastructure/PortfolioCommandSerializerService.java +++ b/mifosng-provider/src/main/java/org/mifosng/platform/api/infrastructure/PortfolioCommandSerializerService.java @@ -38,4 +38,6 @@ public interface PortfolioCommandSerializerService { String serializeOfficeTransactionCommandToJson(BranchMoneyTransferCommand command); String serializeCurrencyCommandToJson(CurrencyCommand command); + + String serializeCommandToJson(Object command); } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosng/platform/api/infrastructure/PortfolioCommandSerializerServiceJson.java b/mifosng-provider/src/main/java/org/mifosng/platform/api/infrastructure/PortfolioCommandSerializerServiceJson.java index 0798cb821..ba0624cba 100644 --- a/mifosng-provider/src/main/java/org/mifosng/platform/api/infrastructure/PortfolioCommandSerializerServiceJson.java +++ b/mifosng-provider/src/main/java/org/mifosng/platform/api/infrastructure/PortfolioCommandSerializerServiceJson.java @@ -92,4 +92,10 @@ public class PortfolioCommandSerializerServiceJson implements PortfolioCommandSe final Gson gsonDeserializer = helper.createGsonBuilderWithParameterExclusionSerializationStrategy(new HashSet(), false, new HashSet()); return helper.serializedJsonFrom(gsonDeserializer, command); } + + @Override + public String serializeCommandToJson(Object command) { + final Gson gsonDeserializer = helper.createGsonBuilderWithParameterExclusionSerializationStrategy(new HashSet(), false, new HashSet()); + return helper.serializedJsonFrom(gsonDeserializer, command); + } } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosng/platform/client/service/ClientWritePlatformServiceJpaRepositoryImpl.java b/mifosng-provider/src/main/java/org/mifosng/platform/client/service/ClientWritePlatformServiceJpaRepositoryImpl.java index fe077fe02..20cab9c25 100644 --- a/mifosng-provider/src/main/java/org/mifosng/platform/client/service/ClientWritePlatformServiceJpaRepositoryImpl.java +++ b/mifosng-provider/src/main/java/org/mifosng/platform/client/service/ClientWritePlatformServiceJpaRepositoryImpl.java @@ -27,11 +27,10 @@ import org.mifosng.platform.infrastructure.FileUtils; import org.mifosplatform.infrastructure.codes.domain.CodeValue; import org.mifosplatform.infrastructure.codes.domain.CodeValueRepository; import org.mifosplatform.infrastructure.codes.exception.CodeValueNotFoundException; +import org.mifosplatform.infrastructure.configuration.service.ConfigurationDomainService; import org.mifosplatform.infrastructure.office.domain.Office; import org.mifosplatform.infrastructure.office.domain.OfficeRepository; import org.mifosplatform.infrastructure.security.service.PlatformSecurityContext; -import org.mifosplatform.infrastructure.user.domain.Permission; -import org.mifosplatform.infrastructure.user.domain.PermissionRepository; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -50,19 +49,20 @@ public class ClientWritePlatformServiceJpaRepositoryImpl implements ClientWriteP private final OfficeRepository officeRepository; private final NoteRepository noteRepository; private final CodeValueRepository codeValueRepository; - private final PermissionRepository permissionRepository; + private final ConfigurationDomainService configurationDomainService; @Autowired public ClientWritePlatformServiceJpaRepositoryImpl(final PlatformSecurityContext context, final ClientRepository clientRepository, final ClientIdentifierRepository clientIdentifierRepository, final OfficeRepository officeRepository, - NoteRepository noteRepository, final CodeValueRepository codeValueRepository, final PermissionRepository permissionRepository) { + final NoteRepository noteRepository, final CodeValueRepository codeValueRepository, + final ConfigurationDomainService configurationDomainService) { this.context = context; this.clientRepository = clientRepository; this.clientIdentifierRepository = clientIdentifierRepository; this.officeRepository = officeRepository; this.noteRepository = noteRepository; this.codeValueRepository = codeValueRepository; - this.permissionRepository = permissionRepository; + this.configurationDomainService = configurationDomainService; } @Transactional @@ -76,9 +76,8 @@ public class ClientWritePlatformServiceJpaRepositoryImpl implements ClientWriteP client.delete(); this.clientRepository.save(client); - final Permission thisTask = this.permissionRepository.findOneByCode("DELETE_CLIENT"); - if (thisTask.hasMakerCheckerEnabled() && !command.isApprovedByChecker()) { throw new RollbackTransactionAsCommandIsNotApprovedByCheckerException(); } - + if (this.configurationDomainService.isMakerCheckerEnabledForTask("DELETE_CLIENT") && !command.isApprovedByChecker()) { throw new RollbackTransactionAsCommandIsNotApprovedByCheckerException(); } + return new EntityIdentifier(client.getId()); } @@ -121,9 +120,8 @@ public class ClientWritePlatformServiceJpaRepositoryImpl implements ClientWriteP final Client newClient = Client.newClient(clientOffice, firstname, lastname, command.getJoiningDate(), command.getExternalId()); this.clientRepository.save(newClient); - - final Permission thisTask = this.permissionRepository.findOneByCode("CREATE_CLIENT"); - if (thisTask.hasMakerCheckerEnabled() && !command.isApprovedByChecker()) { throw new RollbackTransactionAsCommandIsNotApprovedByCheckerException(); } + + if (this.configurationDomainService.isMakerCheckerEnabledForTask("CREATE_CLIENT") && !command.isApprovedByChecker()) { throw new RollbackTransactionAsCommandIsNotApprovedByCheckerException(); } return newClient.getId(); } catch (DataIntegrityViolationException dve) { @@ -155,9 +153,8 @@ public class ClientWritePlatformServiceJpaRepositoryImpl implements ClientWriteP this.clientRepository.saveAndFlush(clientForUpdate); - final Permission thisTask = this.permissionRepository.findOneByCode("UPDATE_CLIENT"); - if (thisTask.hasMakerCheckerEnabled() && !command.isApprovedByChecker()) { throw new RollbackTransactionAsCommandIsNotApprovedByCheckerException(); } - + if (this.configurationDomainService.isMakerCheckerEnabledForTask("UPDATE_CLIENT") && !command.isApprovedByChecker()) { throw new RollbackTransactionAsCommandIsNotApprovedByCheckerException(); } + return new EntityIdentifier(clientForUpdate.getId()); } catch (DataIntegrityViolationException dve) { handleDataIntegrityIssues(command, dve); diff --git a/mifosng-provider/src/main/java/org/mifosng/platform/exceptions/AbstractPlatformResourceNotFoundException.java b/mifosng-provider/src/main/java/org/mifosng/platform/exceptions/AbstractPlatformResourceNotFoundException.java index e0c6fb75e..d05d2c722 100644 --- a/mifosng-provider/src/main/java/org/mifosng/platform/exceptions/AbstractPlatformResourceNotFoundException.java +++ b/mifosng-provider/src/main/java/org/mifosng/platform/exceptions/AbstractPlatformResourceNotFoundException.java @@ -10,8 +10,8 @@ public abstract class AbstractPlatformResourceNotFoundException extends RuntimeE private final String defaultUserMessage; private final Object[] defaultUserMessageArgs; - public AbstractPlatformResourceNotFoundException(String globalisationMessageCode, String defaultUserMessage, - Object... defaultUserMessageArgs) { + public AbstractPlatformResourceNotFoundException(final String globalisationMessageCode, final String defaultUserMessage, + final Object... defaultUserMessageArgs) { this.globalisationMessageCode = globalisationMessageCode; this.defaultUserMessage = defaultUserMessage; this.defaultUserMessageArgs = defaultUserMessageArgs; diff --git a/mifosng-provider/src/main/java/org/mifosng/platform/exceptions/PermissionCantBeMakerCheckerableException.java b/mifosng-provider/src/main/java/org/mifosng/platform/exceptions/PermissionCantBeMakerCheckerableException.java deleted file mode 100644 index 0f0edceab..000000000 --- a/mifosng-provider/src/main/java/org/mifosng/platform/exceptions/PermissionCantBeMakerCheckerableException.java +++ /dev/null @@ -1,13 +0,0 @@ -package org.mifosng.platform.exceptions; - -/** - * A {@link RuntimeException} thrown when permission resources are not found. - */ -public class PermissionCantBeMakerCheckerableException extends - AbstractPlatformResourceNotFoundException { - - public PermissionCantBeMakerCheckerableException(String code) { - super("error.msg.permission.code.not.makercheckerable", "Permission with Code " - + code + " can't be Maker Checkerable", code); - } -} \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosng/platform/exceptions/PermissionNotFoundException.java b/mifosng-provider/src/main/java/org/mifosng/platform/exceptions/PermissionNotFoundException.java deleted file mode 100644 index e00e7753a..000000000 --- a/mifosng-provider/src/main/java/org/mifosng/platform/exceptions/PermissionNotFoundException.java +++ /dev/null @@ -1,13 +0,0 @@ -package org.mifosng.platform.exceptions; - -/** - * A {@link RuntimeException} thrown when permission resources are not found. - */ -public class PermissionNotFoundException extends - AbstractPlatformResourceNotFoundException { - - public PermissionNotFoundException(String code) { - super("error.msg.permission.code.invalid", "Permission with Code " - + code + " does not exist", code); - } -} \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosng/platform/infrastructure/api/JsonParserHelper.java b/mifosng-provider/src/main/java/org/mifosng/platform/infrastructure/api/JsonParserHelper.java index 774472bf9..94748e50f 100644 --- a/mifosng-provider/src/main/java/org/mifosng/platform/infrastructure/api/JsonParserHelper.java +++ b/mifosng-provider/src/main/java/org/mifosng/platform/infrastructure/api/JsonParserHelper.java @@ -74,7 +74,7 @@ public class JsonParserHelper { return stringValue; } - public BigDecimal extractBigDecimalNamed(final String parameterName, final JsonElement element, final Set modifiedParameters) { + public BigDecimal extractBigDecimalWithLocaleNamed(final String parameterName, final JsonElement element, final Set modifiedParameters) { BigDecimal value = null; if (element.isJsonObject()) { final JsonObject object = element.getAsJsonObject(); @@ -101,7 +101,7 @@ public class JsonParserHelper { return value; } - public Integer extractIntegerNamed(final String parameterName, final JsonElement element, final Set modifiedParameters) { + public Integer extractIntegerWithLocaleNamed(final String parameterName, final JsonElement element, final Set modifiedParameters) { Integer value = null; if (element.isJsonObject()) { final JsonObject object = element.getAsJsonObject(); diff --git a/mifosng-provider/src/main/java/org/mifosplatform/commands/domain/CommandSource.java b/mifosng-provider/src/main/java/org/mifosplatform/commands/domain/CommandSource.java index 6bac77fef..799f4e924 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/commands/domain/CommandSource.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/commands/domain/CommandSource.java @@ -49,20 +49,21 @@ public class CommandSource extends AbstractPersistable { @Temporal(TemporalType.DATE) private Date checkedOnDate; - public static CommandSource createdBy(final String apiOperation, final String resource, final Long resourceId, final AppUser maker, - final LocalDate madeOnDate) { - return new CommandSource(apiOperation, resource, resourceId, maker, madeOnDate); + public static CommandSource createdBy(final String apiOperation, final String resource, final Long resourceId, + final String commandSerializedAsJson, final AppUser maker, final LocalDate madeOnDate) { + return new CommandSource(apiOperation, resource, resourceId, commandSerializedAsJson, maker, madeOnDate); } protected CommandSource() { // } - private CommandSource(final String apiOperation, final String resource, final Long resourceId, final AppUser maker, + private CommandSource(final String apiOperation, final String resource, final Long resourceId, final String commandSerializedAsJson, final AppUser maker, final LocalDate madeOnDate) { this.apiOperation = StringUtils.defaultIfEmpty(apiOperation, null); this.resource = StringUtils.defaultIfEmpty(resource, null); this.resourceId = resourceId; + this.commandAsJson = commandSerializedAsJson; this.maker = maker; this.madeOnDate = madeOnDate.toDate(); } @@ -72,7 +73,7 @@ public class CommandSource extends AbstractPersistable { if (this.madeOnDate != null) { madeOnLocalDate = new LocalDate(this.madeOnDate); } - return new CommandSource(this.apiOperation, this.resource, this.resourceId, this.maker, madeOnLocalDate); + return new CommandSource(this.apiOperation, this.resource, this.resourceId, this.commandAsJson, this.maker, madeOnLocalDate); } public void markAsChecked(final AppUser checker, final LocalDate checkedOnDate) { @@ -114,7 +115,8 @@ public class CommandSource extends AbstractPersistable { public boolean isUpdate() { // permissions resource has special update which involves no resource. - return (isPermissionResource() && isUpdateOperation()) || (isCurrencyResource() && isUpdateOperation()) || (isUpdateOperation() && this.resourceId != null); + return (isPermissionResource() && isUpdateOperation()) || (isCurrencyResource() && isUpdateOperation()) + || (isUpdateOperation() && this.resourceId != null); } private boolean isUpdateOperation() { @@ -132,7 +134,7 @@ public class CommandSource extends AbstractPersistable { public boolean isPermissionResource() { return this.resource.equalsIgnoreCase("PERMISSIONS"); } - + public boolean isRoleResource() { return this.resource.equalsIgnoreCase("ROLES"); } @@ -144,7 +146,7 @@ public class CommandSource extends AbstractPersistable { public boolean isCurrencyResource() { return this.resource.equalsIgnoreCase("CURRENCIES"); } - + public boolean isCodeResource() { return this.resource.equalsIgnoreCase("CODES"); } @@ -152,11 +154,11 @@ public class CommandSource extends AbstractPersistable { public boolean isStaffResource() { return this.resource.equalsIgnoreCase("STAFF"); } - + public boolean isFundResource() { return this.resource.equalsIgnoreCase("FUNDS"); } - + public boolean isOfficeResource() { return this.resource.equalsIgnoreCase("OFFICES"); } @@ -164,8 +166,13 @@ public class CommandSource extends AbstractPersistable { public boolean isOfficeTransactionResource() { return this.resource.equalsIgnoreCase("OFFICETRANSACTIONS"); } - + + public boolean isChargeDefinitionResource() { + return this.resource.equalsIgnoreCase("CHARGES"); + } + public boolean isClientResource() { return this.resource.equalsIgnoreCase("CLIENTS"); } + } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/commands/handler/ChargeDefinitionCommandHandler.java b/mifosng-provider/src/main/java/org/mifosplatform/commands/handler/ChargeDefinitionCommandHandler.java new file mode 100644 index 000000000..155934181 --- /dev/null +++ b/mifosng-provider/src/main/java/org/mifosplatform/commands/handler/ChargeDefinitionCommandHandler.java @@ -0,0 +1,120 @@ +package org.mifosplatform.commands.handler; + +import java.util.Arrays; +import java.util.List; + +import org.joda.time.LocalDate; +import org.mifosng.platform.api.infrastructure.PortfolioCommandDeserializerService; +import org.mifosng.platform.client.service.RollbackTransactionAsCommandIsNotApprovedByCheckerException; +import org.mifosplatform.commands.domain.CommandSource; +import org.mifosplatform.commands.service.ChangeDetectionService; +import org.mifosplatform.infrastructure.security.service.PlatformSecurityContext; +import org.mifosplatform.infrastructure.user.domain.AppUser; +import org.mifosplatform.portfolio.charge.command.ChargeDefinitionCommand; +import org.mifosplatform.portfolio.charge.service.ChargeWritePlatformService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +@Service +public class ChargeDefinitionCommandHandler implements CommandSourceHandler { + + private final PlatformSecurityContext context; + private final ChangeDetectionService changeDetectionService; + private final PortfolioCommandDeserializerService commandDeserializerService; + private final ChargeWritePlatformService writePlatformService; + + @Autowired + public ChargeDefinitionCommandHandler(final PlatformSecurityContext context, final ChangeDetectionService changeDetectionService, + final PortfolioCommandDeserializerService commandDeserializerService, + final ChargeWritePlatformService writePlatformService) { + this.context = context; + this.changeDetectionService = changeDetectionService; + this.commandDeserializerService = commandDeserializerService; + this.writePlatformService = writePlatformService; + } + + /* + * Used when users with 'create' capability create a command. If 'maker-checker' is not + * enabled for this specific command then the 'creator' is also marked 'as the checker' and command + * automatically is processed and changes state of system. + */ + public CommandSource handle(final CommandSource commandSource, final String commandSerializedAsJson) { + + final AppUser maker = context.authenticatedUser(); + final LocalDate asToday = new LocalDate(); + + CommandSource commandSourceResult = commandSource.copy(); + + final Long resourceId = commandSource.resourceId(); + final ChargeDefinitionCommand command = this.commandDeserializerService.deserializeChargeDefinitionCommand(resourceId, commandSourceResult.json(), true); + + if (commandSource.isCreate()) { + try { + Long newResourceId = this.writePlatformService.createCharge(command); + commandSourceResult.markAsChecked(maker, asToday); + commandSourceResult.updateResourceId(newResourceId); + } catch (RollbackTransactionAsCommandIsNotApprovedByCheckerException e) { + // swallow this rollback transaction by design + } + } else if (commandSource.isUpdate()) { + try { + final String jsonOfChangesOnly = this.changeDetectionService.detectChangesOnUpdate(commandSource.resourceName(), commandSource.resourceId(), commandSource.json()); + commandSourceResult.updateJsonTo(jsonOfChangesOnly); + + final ChargeDefinitionCommand changesOnly = this.commandDeserializerService.deserializeChargeDefinitionCommand(resourceId, jsonOfChangesOnly, false); + + this.writePlatformService.updateCharge(changesOnly); + + commandSourceResult.markAsChecked(maker, asToday); + } catch (RollbackTransactionAsCommandIsNotApprovedByCheckerException e) { + // swallow this rollback transaction by design + } + } else if (commandSource.isDelete()) { + try { + this.writePlatformService.deleteCharge(command); + commandSourceResult.markAsChecked(maker, asToday); + } catch (RollbackTransactionAsCommandIsNotApprovedByCheckerException e) { + // swallow this rollback transaction by design + } + } + + return commandSourceResult; + } + + /* + * Used when users with 'checker' capability approve a command. + */ + public CommandSource handle(final CommandSource commandSourceResult) { + + final AppUser checker = context.authenticatedUser(); + + Long resourceId = commandSourceResult.resourceId(); + final ChargeDefinitionCommand command = this.commandDeserializerService.deserializeChargeDefinitionCommand(resourceId, commandSourceResult.json(), true); + + if (commandSourceResult.isUserResource()) { + if (commandSourceResult.isCreate()) { + final List allowedPermissions = Arrays.asList("ALL_FUNCTIONS", "ORGANISATION_ADMINISTRATION_SUPER_USER", "CREATE_CHARGE_MAKER"); + context.authenticatedUser().validateHasPermissionTo("CREATE_CHARGE_MAKER", allowedPermissions); + + resourceId = this.writePlatformService.createCharge(command); + commandSourceResult.updateResourceId(resourceId); + commandSourceResult.markAsChecked(checker, new LocalDate()); + } else if (commandSourceResult.isUpdate()) { + final List allowedPermissions = Arrays.asList("ALL_FUNCTIONS", "ORGANISATION_ADMINISTRATION_SUPER_USER", "UPDATE_CHARGE_MAKER"); + context.authenticatedUser().validateHasPermissionTo("UPDATE_CHARGE_MAKER", allowedPermissions); + + this.writePlatformService.updateCharge(command); + + commandSourceResult.markAsChecked(checker, new LocalDate()); + } else if (commandSourceResult.isDelete()) { + final List allowedPermissions = Arrays.asList("ALL_FUNCTIONS", "ORGANISATION_ADMINISTRATION_SUPER_USER", "DELETE_CHARGE_MAKER"); + context.authenticatedUser().validateHasPermissionTo("DELETE_CHARGE_MAKER", allowedPermissions); + + this.writePlatformService.deleteCharge(command); + commandSourceResult.markAsChecked(checker, new LocalDate()); + } + } + + return commandSourceResult; + } +} \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/commands/handler/ClientCommandHandler.java b/mifosng-provider/src/main/java/org/mifosplatform/commands/handler/ClientCommandHandler.java index 11ad2e3ff..751066a6c 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/commands/handler/ClientCommandHandler.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/commands/handler/ClientCommandHandler.java @@ -6,8 +6,7 @@ import java.util.List; import org.joda.time.LocalDate; import org.mifosng.platform.api.commands.ClientCommand; import org.mifosng.platform.api.data.EntityIdentifier; -import org.mifosng.platform.api.infrastructure.PortfolioApiDataConversionService; -import org.mifosng.platform.api.infrastructure.PortfolioApiJsonSerializerService; +import org.mifosng.platform.api.infrastructure.PortfolioCommandDeserializerService; import org.mifosng.platform.client.service.ClientWritePlatformService; import org.mifosng.platform.client.service.RollbackTransactionAsCommandIsNotApprovedByCheckerException; import org.mifosplatform.commands.domain.CommandSource; @@ -22,35 +21,30 @@ public class ClientCommandHandler implements CommandSourceHandler { private final PlatformSecurityContext context; private final ChangeDetectionService changeDetectionService; - private final PortfolioApiDataConversionService apiDataConversionService; - private final PortfolioApiJsonSerializerService apiJsonSerializerService; private final ClientWritePlatformService clientWritePlatformService; + private final PortfolioCommandDeserializerService commandDeserializerService; @Autowired public ClientCommandHandler(final PlatformSecurityContext context, final ChangeDetectionService changeDetectionService, - final PortfolioApiDataConversionService apiDataConversionService, - final PortfolioApiJsonSerializerService apiJsonSerializerService, final ClientWritePlatformService clientWritePlatformService) { + final PortfolioCommandDeserializerService commandDeserializerService, + final ClientWritePlatformService clientWritePlatformService) { this.context = context; this.changeDetectionService = changeDetectionService; - this.apiDataConversionService = apiDataConversionService; - this.apiJsonSerializerService = apiJsonSerializerService; + this.commandDeserializerService = commandDeserializerService; this.clientWritePlatformService = clientWritePlatformService; } - public CommandSource handle(final CommandSource commandSource, final String apiRequestBodyInJson) { + public CommandSource handle(final CommandSource commandSource, final String commandSerializedAsJson) { final AppUser maker = context.authenticatedUser(); final LocalDate asToday = new LocalDate(); + final ClientCommand command = this.commandDeserializerService.deserializeClientCommand(commandSource.resourceId(), + commandSource.json(), false); + CommandSource commandSourceResult = commandSource.copy(); - - final Long resourceId = commandSource.resourceId(); Long newResourceId = null; - final ClientCommand command = this.apiDataConversionService.convertApiRequestJsonToClientCommand(resourceId, apiRequestBodyInJson); - final String commandSerializedAsJson = this.apiJsonSerializerService.serializeClientCommandToJson(command); - commandSourceResult.updateJsonTo(commandSerializedAsJson); - if (commandSource.isCreate()) { try { newResourceId = this.clientWritePlatformService.createClient(command); @@ -61,11 +55,12 @@ public class ClientCommandHandler implements CommandSourceHandler { } } else if (commandSource.isUpdate()) { try { - final String jsonOfChangesOnly = this.changeDetectionService.detectChangesOnUpdate(commandSource.resourceName(), commandSource.resourceId(), commandSerializedAsJson); + final String jsonOfChangesOnly = this.changeDetectionService.detectChangesOnUpdate(commandSource.resourceName(), + commandSource.resourceId(), commandSource.json()); commandSourceResult.updateJsonTo(jsonOfChangesOnly); - final ClientCommand changesOnly = this.apiDataConversionService.convertInternalJsonFormatToClientCommand( - commandSource.resourceId(), jsonOfChangesOnly, false); + final ClientCommand changesOnly = this.commandDeserializerService.deserializeClientCommand(commandSource.resourceId(), + jsonOfChangesOnly, false); EntityIdentifier result = this.clientWritePlatformService.updateClientDetails(changesOnly); newResourceId = result.getEntityId(); @@ -90,34 +85,35 @@ public class ClientCommandHandler implements CommandSourceHandler { public CommandSource handle(final CommandSource commandSourceResult) { final AppUser checker = context.authenticatedUser(); - - Long resourceId = null; - if (commandSourceResult.isClientResource()) { - final ClientCommand command = this.apiDataConversionService.convertInternalJsonFormatToClientCommand( - commandSourceResult.resourceId(), commandSourceResult.json(), true); - if (commandSourceResult.isCreate()) { - final List allowedPermissions = Arrays.asList("ALL_FUNCTIONS", "PORTFOLIO_MANAGEMENT_SUPER_USER", "CREATE_CLIENT_CHECKER"); - context.authenticatedUser().validateHasPermissionTo("CREATE_CLIENT_CHECKER", allowedPermissions); - - resourceId = this.clientWritePlatformService.createClient(command); - commandSourceResult.updateResourceId(resourceId); - commandSourceResult.markAsChecked(checker, new LocalDate()); - } else if (commandSourceResult.isUpdate()) { - final List allowedPermissions = Arrays.asList("ALL_FUNCTIONS", "PORTFOLIO_MANAGEMENT_SUPER_USER", "UPDATE_CLIENT_CHECKER"); - context.authenticatedUser().validateHasPermissionTo("UPDATE_CLIENT_CHECKER", allowedPermissions); - - EntityIdentifier result = this.clientWritePlatformService.updateClientDetails(command); - resourceId = result.getEntityId(); - commandSourceResult.markAsChecked(checker, new LocalDate()); - } else if (commandSourceResult.isDelete()) { - final List allowedPermissions = Arrays.asList("ALL_FUNCTIONS", "PORTFOLIO_MANAGEMENT_SUPER_USER", "DELETE_CLIENT_CHECKER"); - context.authenticatedUser().validateHasPermissionTo("DELETE_CLIENT_CHECKER", allowedPermissions); - - EntityIdentifier result = this.clientWritePlatformService.deleteClient(command); - resourceId = result.getEntityId(); - commandSourceResult.markAsChecked(checker, new LocalDate()); - } + Long resourceId = null; + final ClientCommand command = this.commandDeserializerService.deserializeClientCommand(commandSourceResult.resourceId(), + commandSourceResult.json(), true); + + if (commandSourceResult.isCreate()) { + final List allowedPermissions = Arrays.asList("ALL_FUNCTIONS", "PORTFOLIO_MANAGEMENT_SUPER_USER", + "CREATE_CLIENT_CHECKER"); + context.authenticatedUser().validateHasPermissionTo("CREATE_CLIENT_CHECKER", allowedPermissions); + + resourceId = this.clientWritePlatformService.createClient(command); + commandSourceResult.updateResourceId(resourceId); + commandSourceResult.markAsChecked(checker, new LocalDate()); + } else if (commandSourceResult.isUpdate()) { + final List allowedPermissions = Arrays.asList("ALL_FUNCTIONS", "PORTFOLIO_MANAGEMENT_SUPER_USER", + "UPDATE_CLIENT_CHECKER"); + context.authenticatedUser().validateHasPermissionTo("UPDATE_CLIENT_CHECKER", allowedPermissions); + + EntityIdentifier result = this.clientWritePlatformService.updateClientDetails(command); + resourceId = result.getEntityId(); + commandSourceResult.markAsChecked(checker, new LocalDate()); + } else if (commandSourceResult.isDelete()) { + final List allowedPermissions = Arrays.asList("ALL_FUNCTIONS", "PORTFOLIO_MANAGEMENT_SUPER_USER", + "DELETE_CLIENT_CHECKER"); + context.authenticatedUser().validateHasPermissionTo("DELETE_CLIENT_CHECKER", allowedPermissions); + + EntityIdentifier result = this.clientWritePlatformService.deleteClient(command); + resourceId = result.getEntityId(); + commandSourceResult.markAsChecked(checker, new LocalDate()); } return commandSourceResult; diff --git a/mifosng-provider/src/main/java/org/mifosplatform/commands/handler/CommandSourceHandlerDelegator.java b/mifosng-provider/src/main/java/org/mifosplatform/commands/handler/CommandSourceHandlerDelegator.java index ec36f9c68..f27e00f5d 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/commands/handler/CommandSourceHandlerDelegator.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/commands/handler/CommandSourceHandlerDelegator.java @@ -23,6 +23,7 @@ public class CommandSourceHandlerDelegator { private final OfficeCommandHandler officeCommandHandler; private final OfficeTransactionCommandHandler officeTransactionCommandHandler; private final CurrencyCommandHandler currencyCommandHandler; + private final ChargeDefinitionCommandHandler chargeDefinitionCommandHandler; @Autowired public CommandSourceHandlerDelegator(final PlatformSecurityContext context, @@ -35,7 +36,8 @@ public class CommandSourceHandlerDelegator { final FundCommandHandler fundCommandHandler, final OfficeCommandHandler officeCommandHandler, final OfficeTransactionCommandHandler officeTransactionCommandHandler, - final CurrencyCommandHandler currencyCommandHandler) { + final CurrencyCommandHandler currencyCommandHandler, + final ChargeDefinitionCommandHandler chargeDefinitionCommandHandler) { this.context = context; this.clientCommandHandler = clientCommandHandler; this.roleCommandHandler = roleCommandHandler; @@ -47,6 +49,7 @@ public class CommandSourceHandlerDelegator { this.officeCommandHandler = officeCommandHandler; this.officeTransactionCommandHandler = officeTransactionCommandHandler; this.currencyCommandHandler = currencyCommandHandler; + this.chargeDefinitionCommandHandler = chargeDefinitionCommandHandler; } public CommandSource handle(final CommandSource commandSource, final String apiRequestBodyInJson) { @@ -73,6 +76,8 @@ public class CommandSourceHandlerDelegator { commandSourceResult = officeTransactionCommandHandler.handle(commandSource, apiRequestBodyInJson); } else if (commandSource.isCurrencyResource()) { commandSourceResult = currencyCommandHandler.handle(commandSource, apiRequestBodyInJson); + } else if (commandSource.isChargeDefinitionResource()) { + commandSourceResult = chargeDefinitionCommandHandler.handle(commandSource, apiRequestBodyInJson); } else { throw new UnsupportedCommandException(commandSource.commandName()); } @@ -103,6 +108,8 @@ public class CommandSourceHandlerDelegator { commandSourceResult = officeTransactionCommandHandler.handle(existingCommandSource); } else if (existingCommandSource.isCurrencyResource()) { commandSourceResult = currencyCommandHandler.handle(existingCommandSource); + } else if (existingCommandSource.isChargeDefinitionResource()) { + commandSourceResult = chargeDefinitionCommandHandler.handle(existingCommandSource); } else { throw new UnsupportedCommandException(existingCommandSource.commandName()); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/commands/handler/CurrencyCommandHandler.java b/mifosng-provider/src/main/java/org/mifosplatform/commands/handler/CurrencyCommandHandler.java index adde0f9a0..9de2e8440 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/commands/handler/CurrencyCommandHandler.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/commands/handler/CurrencyCommandHandler.java @@ -12,7 +12,7 @@ import org.mifosng.platform.infrastructure.errorhandling.UnsupportedCommandExcep import org.mifosplatform.commands.domain.CommandSource; import org.mifosplatform.commands.service.ChangeDetectionService; import org.mifosplatform.infrastructure.configuration.command.CurrencyCommand; -import org.mifosplatform.infrastructure.configuration.service.ConfigurationWritePlatformService; +import org.mifosplatform.infrastructure.configuration.service.CurrencyWritePlatformService; import org.mifosplatform.infrastructure.security.service.PlatformSecurityContext; import org.mifosplatform.infrastructure.user.domain.AppUser; import org.springframework.beans.factory.annotation.Autowired; @@ -26,14 +26,14 @@ public class CurrencyCommandHandler implements CommandSourceHandler { private final PortfolioApiDataConversionService apiDataConversionService; private final PortfolioCommandSerializerService commandSerializerService; private final PortfolioCommandDeserializerService commandDeserializerService; - private final ConfigurationWritePlatformService writePlatformService; + private final CurrencyWritePlatformService writePlatformService; @Autowired public CurrencyCommandHandler(final PlatformSecurityContext context, final ChangeDetectionService changeDetectionService, final PortfolioApiDataConversionService apiDataConversionService, final PortfolioCommandSerializerService commandSerializerService, - final PortfolioCommandDeserializerService commandDeserializerService, final ConfigurationWritePlatformService writePlatformService) { + final PortfolioCommandDeserializerService commandDeserializerService, final CurrencyWritePlatformService writePlatformService) { this.context = context; this.changeDetectionService = changeDetectionService; this.apiDataConversionService = apiDataConversionService; diff --git a/mifosng-provider/src/main/java/org/mifosplatform/commands/handler/RoleCommandHandler.java b/mifosng-provider/src/main/java/org/mifosplatform/commands/handler/RoleCommandHandler.java index 6fe39d9f8..c8db22b1a 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/commands/handler/RoleCommandHandler.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/commands/handler/RoleCommandHandler.java @@ -4,9 +4,7 @@ import java.util.Arrays; import java.util.List; import org.joda.time.LocalDate; -import org.mifosng.platform.api.infrastructure.PortfolioApiDataConversionService; import org.mifosng.platform.api.infrastructure.PortfolioCommandDeserializerService; -import org.mifosng.platform.api.infrastructure.PortfolioCommandSerializerService; import org.mifosng.platform.client.service.RollbackTransactionAsCommandIsNotApprovedByCheckerException; import org.mifosng.platform.infrastructure.errorhandling.UnsupportedCommandException; import org.mifosplatform.commands.domain.CommandSource; @@ -24,20 +22,14 @@ public class RoleCommandHandler implements CommandSourceHandler { private final PlatformSecurityContext context; private final ChangeDetectionService changeDetectionService; - private final PortfolioApiDataConversionService apiDataConversionService; - private final PortfolioCommandSerializerService commandSerializerService; private final PortfolioCommandDeserializerService commandDeserializerService; private final RoleWritePlatformService writePlatformService; @Autowired public RoleCommandHandler(final PlatformSecurityContext context, final ChangeDetectionService changeDetectionService, - final PortfolioApiDataConversionService apiDataConversionService, - final PortfolioCommandSerializerService commandSerializerService, final PortfolioCommandDeserializerService commandDeserializerService, final RoleWritePlatformService writePlatformService) { this.context = context; this.changeDetectionService = changeDetectionService; - this.apiDataConversionService = apiDataConversionService; - this.commandSerializerService = commandSerializerService; this.commandDeserializerService = commandDeserializerService; this.writePlatformService = writePlatformService; } @@ -48,7 +40,7 @@ public class RoleCommandHandler implements CommandSourceHandler { * 'creator' is also marked 'as the checker' and command automatically is * processed and changes state of system. */ - public CommandSource handle(final CommandSource commandSource, final String apiRequestBodyInJson) { + public CommandSource handle(final CommandSource commandSource, final String commandSerializedAsJson) { final AppUser maker = context.authenticatedUser(); final LocalDate asToday = new LocalDate(); @@ -60,12 +52,10 @@ public class RoleCommandHandler implements CommandSourceHandler { if (commandSource.isCreate()) { try { - final RoleCommand command = this.apiDataConversionService.convertApiRequestJsonToRoleCommand(resourceId, - apiRequestBodyInJson); - final String commandSerializedAsJson = this.commandSerializerService.serializeRoleCommandToJson(command); - commandSourceResult.updateJsonTo(commandSerializedAsJson); + final RoleCommand command = this.commandDeserializerService.deserializeRoleCommand(resourceId, commandSource.json(), false); newResourceId = this.writePlatformService.createRole(command); + commandSourceResult.markAsChecked(maker, asToday); commandSourceResult.updateResourceId(newResourceId); } catch (RollbackTransactionAsCommandIsNotApprovedByCheckerException e) { @@ -73,13 +63,8 @@ public class RoleCommandHandler implements CommandSourceHandler { } } else if (commandSource.isUpdate()) { try { - final RoleCommand command = this.apiDataConversionService.convertApiRequestJsonToRoleCommand(resourceId, - apiRequestBodyInJson); - final String commandSerializedAsJson = this.commandSerializerService.serializeRoleCommandToJson(command); - commandSourceResult.updateJsonTo(commandSerializedAsJson); - final String jsonOfChangesOnly = this.changeDetectionService.detectChangesOnUpdate(commandSource.resourceName(), - commandSource.resourceId(), commandSerializedAsJson); + commandSource.resourceId(), commandSource.json()); commandSourceResult.updateJsonTo(jsonOfChangesOnly); final RoleCommand changesOnly = this.commandDeserializerService @@ -93,13 +78,8 @@ public class RoleCommandHandler implements CommandSourceHandler { } } else if (commandSource.isUpdateRolePermissions()) { try { - final RolePermissionCommand command = this.apiDataConversionService.convertApiRequestJsonToRolePermissionCommand( - resourceId, apiRequestBodyInJson); - final String commandSerializedAsJson = this.commandSerializerService.serializeRolePermissionCommandToJson(command); - commandSourceResult.updateJsonTo(commandSerializedAsJson); - final String jsonOfChangesOnly = this.changeDetectionService.detectChangesOnUpdate(commandSource.resourceName(), - commandSource.resourceId(), commandSerializedAsJson); + commandSource.resourceId(), commandSource.json()); commandSourceResult.updateJsonTo(jsonOfChangesOnly); final RolePermissionCommand changesOnly = this.commandDeserializerService.deserializeRolePermissionCommand(resourceId, @@ -124,38 +104,34 @@ public class RoleCommandHandler implements CommandSourceHandler { final AppUser checker = context.authenticatedUser(); Long resourceId = commandSourceResult.resourceId(); - if (commandSourceResult.isRoleResource()) { - if (commandSourceResult.isCreate()) { - final List allowedPermissions = Arrays.asList("ALL_FUNCTIONS", "USER_ADMINISTRATION_SUPER_USER", - "CREATE_ROLE_CHECKER"); - context.authenticatedUser().validateHasPermissionTo("CREATE_ROLE_CHECKER", allowedPermissions); + if (commandSourceResult.isCreate()) { + final List allowedPermissions = Arrays.asList("ALL_FUNCTIONS", "USER_ADMINISTRATION_SUPER_USER", "CREATE_ROLE_CHECKER"); + context.authenticatedUser().validateHasPermissionTo("CREATE_ROLE_CHECKER", allowedPermissions); - final RoleCommand command = this.commandDeserializerService.deserializeRoleCommand(resourceId, commandSourceResult.json(), - true); - resourceId = this.writePlatformService.createRole(command); - commandSourceResult.markAsChecked(checker, new LocalDate()); - } else if (commandSourceResult.isUpdate()) { - final List allowedPermissions = Arrays.asList("ALL_FUNCTIONS", "USER_ADMINISTRATION_SUPER_USER", - "UPDATE_ROLE_CHECKER"); - context.authenticatedUser().validateHasPermissionTo("UPDATE_ROLE_CHECKER", allowedPermissions); + final RoleCommand command = this.commandDeserializerService + .deserializeRoleCommand(resourceId, commandSourceResult.json(), true); + resourceId = this.writePlatformService.createRole(command); + commandSourceResult.updateResourceId(resourceId); + commandSourceResult.markAsChecked(checker, new LocalDate()); - final RoleCommand command = this.commandDeserializerService.deserializeRoleCommand(resourceId, commandSourceResult.json(), - true); - resourceId = this.writePlatformService.updateRole(command); - commandSourceResult.markAsChecked(checker, new LocalDate()); - } else if (commandSourceResult.isUpdateRolePermissions()) { - final List allowedPermissions = Arrays.asList("ALL_FUNCTIONS", "USER_ADMINISTRATION_SUPER_USER", - "PERMISSIONS_ROLE_CHECKER"); - context.authenticatedUser().validateHasPermissionTo("PERMISSIONS_ROLE_CHECKER", allowedPermissions); + } else if (commandSourceResult.isUpdate()) { + final List allowedPermissions = Arrays.asList("ALL_FUNCTIONS", "USER_ADMINISTRATION_SUPER_USER", "UPDATE_ROLE_CHECKER"); + context.authenticatedUser().validateHasPermissionTo("UPDATE_ROLE_CHECKER", allowedPermissions); - final RolePermissionCommand command = this.commandDeserializerService.deserializeRolePermissionCommand(resourceId, - commandSourceResult.json(), true); - resourceId = this.writePlatformService.updateRolePermissions(command); - commandSourceResult.markAsChecked(checker, new LocalDate()); - } else if (commandSourceResult.isDelete()) { throw new UnsupportedCommandException(commandSourceResult.commandName()); } - } + final RoleCommand command = this.commandDeserializerService + .deserializeRoleCommand(resourceId, commandSourceResult.json(), true); + resourceId = this.writePlatformService.updateRole(command); + commandSourceResult.markAsChecked(checker, new LocalDate()); + } else if (commandSourceResult.isUpdateRolePermissions()) { + final List allowedPermissions = Arrays.asList("ALL_FUNCTIONS", "USER_ADMINISTRATION_SUPER_USER", + "PERMISSIONS_ROLE_CHECKER"); + context.authenticatedUser().validateHasPermissionTo("PERMISSIONS_ROLE_CHECKER", allowedPermissions); - commandSourceResult.updateResourceId(resourceId); + final RolePermissionCommand command = this.commandDeserializerService.deserializeRolePermissionCommand(resourceId, + commandSourceResult.json(), true); + resourceId = this.writePlatformService.updateRolePermissions(command); + commandSourceResult.markAsChecked(checker, new LocalDate()); + } else if (commandSourceResult.isDelete()) { throw new UnsupportedCommandException(commandSourceResult.commandName()); } return commandSourceResult; } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/commands/service/ChangeDetectionServiceJdbc.java b/mifosng-provider/src/main/java/org/mifosplatform/commands/service/ChangeDetectionServiceJdbc.java index 35ce09632..d164ea56a 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/commands/service/ChangeDetectionServiceJdbc.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/commands/service/ChangeDetectionServiceJdbc.java @@ -4,6 +4,7 @@ import org.mifosng.platform.api.commands.ClientCommand; import org.mifosng.platform.api.data.ClientData; import org.mifosng.platform.api.infrastructure.PortfolioApiDataConversionService; import org.mifosng.platform.api.infrastructure.PortfolioApiJsonSerializerService; +import org.mifosng.platform.api.infrastructure.PortfolioCommandSerializerService; import org.mifosng.platform.client.service.ClientReadPlatformService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @@ -14,11 +15,16 @@ public class ChangeDetectionServiceJdbc implements ChangeDetectionService { private final PortfolioApiDataConversionService apiDataConversionService; private final PortfolioApiJsonSerializerService apiJsonSerializerService; private final ClientReadPlatformService clientReadPlatformService; + private final PortfolioCommandSerializerService commandSerializerService; @Autowired - public ChangeDetectionServiceJdbc(final PortfolioApiDataConversionService apiDataConversionService, - final PortfolioApiJsonSerializerService apiJsonSerializerService, final ClientReadPlatformService clientReadPlatformService) { + public ChangeDetectionServiceJdbc( + final PortfolioApiDataConversionService apiDataConversionService, + final PortfolioCommandSerializerService commandSerializerService, + final PortfolioApiJsonSerializerService apiJsonSerializerService, + final ClientReadPlatformService clientReadPlatformService) { this.apiDataConversionService = apiDataConversionService; + this.commandSerializerService = commandSerializerService; this.apiJsonSerializerService = apiJsonSerializerService; this.clientReadPlatformService = clientReadPlatformService; } @@ -40,7 +46,7 @@ public class ChangeDetectionServiceJdbc implements ChangeDetectionService { final String workingJson = this.apiJsonSerializerService.serializeClientDataToJson(changedClient); final ClientCommand changesOnly = this.apiDataConversionService.detectChanges(resourceId, baseJson, workingJson); - changesOnlyJson = this.apiJsonSerializerService.serializeClientCommandToJson(changesOnly); + changesOnlyJson = this.commandSerializerService.serializeCommandToJson(changesOnly); } else { changesOnlyJson = commandSerializedAsJson; } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/commands/service/PortfolioCommandSourceWritePlatformService.java b/mifosng-provider/src/main/java/org/mifosplatform/commands/service/PortfolioCommandSourceWritePlatformService.java index 10ca71fea..37afc728d 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/commands/service/PortfolioCommandSourceWritePlatformService.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/commands/service/PortfolioCommandSourceWritePlatformService.java @@ -4,7 +4,7 @@ import org.mifosng.platform.api.data.EntityIdentifier; public interface PortfolioCommandSourceWritePlatformService { - EntityIdentifier logCommandSource(String apiOperation, String resource, Long resourceId, String jsonRequestBody); + EntityIdentifier logCommandSource(String apiOperation, String resource, Long resourceId, String commandSerializedAsJson); EntityIdentifier approveEntry(Long id); diff --git a/mifosng-provider/src/main/java/org/mifosplatform/commands/service/PortfolioCommandSourceWritePlatformServiceImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/commands/service/PortfolioCommandSourceWritePlatformServiceImpl.java index c6e7cc745..6e9f4ffc9 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/commands/service/PortfolioCommandSourceWritePlatformServiceImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/commands/service/PortfolioCommandSourceWritePlatformServiceImpl.java @@ -29,13 +29,13 @@ public class PortfolioCommandSourceWritePlatformServiceImpl implements Portfolio // NOT TRANSACTIONAL BY DESIGN FOR NOW @Override public EntityIdentifier logCommandSource(final String apiOperation, final String resource, final Long resourceId, - final String apiRequestBodyInJson) { + final String commandSerializedAsJson) { final AppUser maker = context.authenticatedUser(); final LocalDate asToday = new LocalDate(); - final CommandSource commandSourceInput = CommandSource.createdBy(apiOperation, resource, resourceId, maker, asToday); - final CommandSource commandSourceResult = this.commandSourceHandlerDelegator.handle(commandSourceInput, apiRequestBodyInJson); + final CommandSource commandSourceInput = CommandSource.createdBy(apiOperation, resource, resourceId, commandSerializedAsJson, maker, asToday); + final CommandSource commandSourceResult = this.commandSourceHandlerDelegator.handle(commandSourceInput, commandSerializedAsJson); commandSourceRepository.save(commandSourceResult); return EntityIdentifier.makerChecker(commandSourceResult.resourceId(), commandSourceResult.getId()); diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/codes/service/CodeWritePlatformServiceJpaRepositoryImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/codes/service/CodeWritePlatformServiceJpaRepositoryImpl.java index b672b3427..4551ef44a 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/codes/service/CodeWritePlatformServiceJpaRepositoryImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/codes/service/CodeWritePlatformServiceJpaRepositoryImpl.java @@ -8,9 +8,8 @@ import org.mifosplatform.infrastructure.codes.domain.Code; import org.mifosplatform.infrastructure.codes.domain.CodeRepository; import org.mifosplatform.infrastructure.codes.exception.CodeNotFoundException; import org.mifosplatform.infrastructure.codes.exception.SystemDefinedCodeCannotBeChangedException; +import org.mifosplatform.infrastructure.configuration.service.ConfigurationDomainService; import org.mifosplatform.infrastructure.security.service.PlatformSecurityContext; -import org.mifosplatform.infrastructure.user.domain.Permission; -import org.mifosplatform.infrastructure.user.domain.PermissionRepository; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -25,14 +24,15 @@ public class CodeWritePlatformServiceJpaRepositoryImpl implements CodeWritePlatf private final PlatformSecurityContext context; private final CodeRepository codeRepository; - private final PermissionRepository permissionRepository; + + private final ConfigurationDomainService configurationDomainService; @Autowired public CodeWritePlatformServiceJpaRepositoryImpl(final PlatformSecurityContext context, final CodeRepository codeRepository, - final PermissionRepository permissionRepository) { + final ConfigurationDomainService configurationDomainService) { this.context = context; this.codeRepository = codeRepository; - this.permissionRepository = permissionRepository; + this.configurationDomainService = configurationDomainService; } @Transactional @@ -47,9 +47,8 @@ public class CodeWritePlatformServiceJpaRepositoryImpl implements CodeWritePlatf this.codeRepository.save(code); - final Permission thisTask = this.permissionRepository.findOneByCode("CREATE_CODE"); - if (thisTask.hasMakerCheckerEnabled() && !command.isApprovedByChecker()) { throw new RollbackTransactionAsCommandIsNotApprovedByCheckerException(); } - + if (this.configurationDomainService.isMakerCheckerEnabledForTask("CREATE_CODE") && !command.isApprovedByChecker()) { throw new RollbackTransactionAsCommandIsNotApprovedByCheckerException(); } + return code.getId(); } catch (DataIntegrityViolationException dve) { return Long.valueOf(-1); @@ -69,9 +68,8 @@ public class CodeWritePlatformServiceJpaRepositoryImpl implements CodeWritePlatf this.codeRepository.save(code); - final Permission thisTask = this.permissionRepository.findOneByCode("UPDATE_CODE"); - if (thisTask.hasMakerCheckerEnabled() && !command.isApprovedByChecker()) { throw new RollbackTransactionAsCommandIsNotApprovedByCheckerException(); } - + if (this.configurationDomainService.isMakerCheckerEnabledForTask("UPDATE_CODE") && !command.isApprovedByChecker()) { throw new RollbackTransactionAsCommandIsNotApprovedByCheckerException(); } + return code.getId(); } catch (DataIntegrityViolationException dve) { handleCodeDataIntegrityIssues(command, dve); @@ -106,9 +104,8 @@ public class CodeWritePlatformServiceJpaRepositoryImpl implements CodeWritePlatf this.codeRepository.delete(code); - final Permission thisTask = this.permissionRepository.findOneByCode("DELETE_CODE"); - if (thisTask.hasMakerCheckerEnabled() && !command.isApprovedByChecker()) { throw new RollbackTransactionAsCommandIsNotApprovedByCheckerException(); } - + if (this.configurationDomainService.isMakerCheckerEnabledForTask("DELETE_CODE") && !command.isApprovedByChecker()) { throw new RollbackTransactionAsCommandIsNotApprovedByCheckerException(); } + return new EntityIdentifier(code.getId()); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/configuration/api/CurrenciesApiResource.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/configuration/api/CurrenciesApiResource.java index 7b7508b6f..aa704574c 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/configuration/api/CurrenciesApiResource.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/configuration/api/CurrenciesApiResource.java @@ -18,7 +18,7 @@ import org.mifosng.platform.api.infrastructure.PortfolioApiJsonSerializerService import org.mifosng.platform.infrastructure.api.ApiParameterHelper; import org.mifosplatform.commands.service.PortfolioCommandSourceWritePlatformService; import org.mifosplatform.infrastructure.configuration.data.ConfigurationData; -import org.mifosplatform.infrastructure.configuration.service.ConfigurationReadPlatformService; +import org.mifosplatform.infrastructure.configuration.service.OrganisationCurrencyReadPlatformService; import org.mifosplatform.infrastructure.security.service.PlatformSecurityContext; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; @@ -32,13 +32,13 @@ public class CurrenciesApiResource { private final String resourceNameForPermissions = "CURRENCY"; private final PlatformSecurityContext context; - private final ConfigurationReadPlatformService readPlatformService; + private final OrganisationCurrencyReadPlatformService readPlatformService; private final PortfolioApiJsonSerializerService apiJsonSerializerService; private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService; @Autowired public CurrenciesApiResource(final PlatformSecurityContext context, - final ConfigurationReadPlatformService readPlatformService, + final OrganisationCurrencyReadPlatformService readPlatformService, final PortfolioApiJsonSerializerService apiJsonSerializerService, final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService) { this.context = context; diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/configuration/service/ConfigurationDomainService.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/configuration/service/ConfigurationDomainService.java new file mode 100644 index 000000000..a049778d0 --- /dev/null +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/configuration/service/ConfigurationDomainService.java @@ -0,0 +1,7 @@ +package org.mifosplatform.infrastructure.configuration.service; + +public interface ConfigurationDomainService { + + boolean isMakerCheckerEnabledForTask(String taskPermissionCode); + +} diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/configuration/service/ConfigurationDomainServiceJpa.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/configuration/service/ConfigurationDomainServiceJpa.java new file mode 100644 index 000000000..3e94ca8bf --- /dev/null +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/configuration/service/ConfigurationDomainServiceJpa.java @@ -0,0 +1,33 @@ +package org.mifosplatform.infrastructure.configuration.service; + +import org.mifosplatform.infrastructure.user.domain.Permission; +import org.mifosplatform.infrastructure.user.domain.PermissionRepository; +import org.mifosplatform.infrastructure.user.exception.PermissionNotFoundException; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +@Service +public class ConfigurationDomainServiceJpa implements ConfigurationDomainService { + + private final PermissionRepository permissionRepository; + + /* + * hard code to false to disable maker checker across the board. + */ + private final boolean makerCheckerGloablConfigurationEnabled = false; + + @Autowired + public ConfigurationDomainServiceJpa(final PermissionRepository permissionRepository) { + this.permissionRepository = permissionRepository; + } + + @Override + public boolean isMakerCheckerEnabledForTask(final String taskPermissionCode) { + final Permission thisTask = this.permissionRepository.findOneByCode(taskPermissionCode); + if (thisTask == null) { + throw new PermissionNotFoundException(taskPermissionCode); + } + + return thisTask.hasMakerCheckerEnabled() && this.makerCheckerGloablConfigurationEnabled; + } +} \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/configuration/service/ConfigurationWritePlatformService.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/configuration/service/CurrencyWritePlatformService.java similarity index 79% rename from mifosng-provider/src/main/java/org/mifosplatform/infrastructure/configuration/service/ConfigurationWritePlatformService.java rename to mifosng-provider/src/main/java/org/mifosplatform/infrastructure/configuration/service/CurrencyWritePlatformService.java index e38d81c53..657ad6e5c 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/configuration/service/ConfigurationWritePlatformService.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/configuration/service/CurrencyWritePlatformService.java @@ -2,7 +2,7 @@ package org.mifosplatform.infrastructure.configuration.service; import org.mifosplatform.infrastructure.configuration.command.CurrencyCommand; -public interface ConfigurationWritePlatformService { +public interface CurrencyWritePlatformService { void updateAllowedCurrencies(CurrencyCommand command); diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/configuration/service/ConfigurationWritePlatformServiceJpaRepositoryImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/configuration/service/CurrencyWritePlatformServiceJpaRepositoryImpl.java similarity index 81% rename from mifosng-provider/src/main/java/org/mifosplatform/infrastructure/configuration/service/ConfigurationWritePlatformServiceJpaRepositoryImpl.java rename to mifosng-provider/src/main/java/org/mifosplatform/infrastructure/configuration/service/CurrencyWritePlatformServiceJpaRepositoryImpl.java index 53f07a62c..6fc57a296 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/configuration/service/ConfigurationWritePlatformServiceJpaRepositoryImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/configuration/service/CurrencyWritePlatformServiceJpaRepositoryImpl.java @@ -15,29 +15,26 @@ import org.mifosplatform.infrastructure.configuration.domain.ApplicationCurrency import org.mifosplatform.infrastructure.office.domain.OrganisationCurrency; import org.mifosplatform.infrastructure.office.domain.OrganisationCurrencyRepository; import org.mifosplatform.infrastructure.security.service.PlatformSecurityContext; -import org.mifosplatform.infrastructure.user.domain.Permission; -import org.mifosplatform.infrastructure.user.domain.PermissionRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @Service -public class ConfigurationWritePlatformServiceJpaRepositoryImpl implements ConfigurationWritePlatformService { +public class CurrencyWritePlatformServiceJpaRepositoryImpl implements CurrencyWritePlatformService { private final PlatformSecurityContext context; private final ApplicationCurrencyRepository applicationCurrencyRepository; private final OrganisationCurrencyRepository organisationCurrencyRepository; - private final PermissionRepository permissionRepository; + private final ConfigurationDomainService configurationDomainService; @Autowired - public ConfigurationWritePlatformServiceJpaRepositoryImpl(final PlatformSecurityContext context, + public CurrencyWritePlatformServiceJpaRepositoryImpl(final PlatformSecurityContext context, final ApplicationCurrencyRepository applicationCurrencyRepository, - final OrganisationCurrencyRepository organisationCurrencyRepository, - final PermissionRepository permissionRepository) { + final OrganisationCurrencyRepository organisationCurrencyRepository, final ConfigurationDomainService configurationDomainService) { this.context = context; this.applicationCurrencyRepository = applicationCurrencyRepository; this.organisationCurrencyRepository = organisationCurrencyRepository; - this.permissionRepository = permissionRepository; + this.configurationDomainService = configurationDomainService; } @Transactional @@ -72,9 +69,8 @@ public class ConfigurationWritePlatformServiceJpaRepositoryImpl implements Confi this.organisationCurrencyRepository.deleteAll(); this.organisationCurrencyRepository.save(allowedCurrencies); - - final Permission thisTask = this.permissionRepository.findOneByCode("UPDATE_CURRENCY"); - if (thisTask.hasMakerCheckerEnabled() && !command.isApprovedByChecker()) { throw new RollbackTransactionAsCommandIsNotApprovedByCheckerException(); } + + if (this.configurationDomainService.isMakerCheckerEnabledForTask("UPDATE_CURRENCY") && !command.isApprovedByChecker()) { throw new RollbackTransactionAsCommandIsNotApprovedByCheckerException(); } if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.", dataValidationErrors); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/configuration/service/ConfigurationReadPlatformService.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/configuration/service/OrganisationCurrencyReadPlatformService.java similarity index 77% rename from mifosng-provider/src/main/java/org/mifosplatform/infrastructure/configuration/service/ConfigurationReadPlatformService.java rename to mifosng-provider/src/main/java/org/mifosplatform/infrastructure/configuration/service/OrganisationCurrencyReadPlatformService.java index cc869af53..37e71f3c3 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/configuration/service/ConfigurationReadPlatformService.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/configuration/service/OrganisationCurrencyReadPlatformService.java @@ -2,7 +2,7 @@ package org.mifosplatform.infrastructure.configuration.service; import org.mifosplatform.infrastructure.configuration.data.ConfigurationData; -public interface ConfigurationReadPlatformService { +public interface OrganisationCurrencyReadPlatformService { ConfigurationData retrieveCurrencyConfiguration(); diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/configuration/service/ConfigurationReadPlatformServiceImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/configuration/service/OrganisationCurrencyReadPlatformServiceImpl.java similarity index 81% rename from mifosng-provider/src/main/java/org/mifosplatform/infrastructure/configuration/service/ConfigurationReadPlatformServiceImpl.java rename to mifosng-provider/src/main/java/org/mifosplatform/infrastructure/configuration/service/OrganisationCurrencyReadPlatformServiceImpl.java index dd82f140a..d1088c3d4 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/configuration/service/ConfigurationReadPlatformServiceImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/configuration/service/OrganisationCurrencyReadPlatformServiceImpl.java @@ -8,12 +8,12 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service -public class ConfigurationReadPlatformServiceImpl implements ConfigurationReadPlatformService { +public class OrganisationCurrencyReadPlatformServiceImpl implements OrganisationCurrencyReadPlatformService { private final CurrencyReadPlatformService currencyReadPlatformService; @Autowired - public ConfigurationReadPlatformServiceImpl(final CurrencyReadPlatformService currencyReadPlatformService) { + public OrganisationCurrencyReadPlatformServiceImpl(final CurrencyReadPlatformService currencyReadPlatformService) { this.currencyReadPlatformService = currencyReadPlatformService; } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/office/service/OfficeWritePlatformServiceJpaRepositoryImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/office/service/OfficeWritePlatformServiceJpaRepositoryImpl.java index 0e4215b27..cb58456fc 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/office/service/OfficeWritePlatformServiceJpaRepositoryImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/office/service/OfficeWritePlatformServiceJpaRepositoryImpl.java @@ -9,6 +9,7 @@ import org.mifosplatform.infrastructure.configuration.domain.ApplicationCurrency import org.mifosplatform.infrastructure.configuration.domain.ApplicationCurrencyRepository; import org.mifosplatform.infrastructure.configuration.domain.MonetaryCurrency; import org.mifosplatform.infrastructure.configuration.domain.Money; +import org.mifosplatform.infrastructure.configuration.service.ConfigurationDomainService; import org.mifosplatform.infrastructure.office.command.BranchMoneyTransferCommand; import org.mifosplatform.infrastructure.office.command.OfficeCommand; import org.mifosplatform.infrastructure.office.domain.Office; @@ -17,8 +18,6 @@ import org.mifosplatform.infrastructure.office.domain.OfficeTransaction; import org.mifosplatform.infrastructure.office.domain.OfficeTransactionRepository; import org.mifosplatform.infrastructure.security.service.PlatformSecurityContext; import org.mifosplatform.infrastructure.user.domain.AppUser; -import org.mifosplatform.infrastructure.user.domain.Permission; -import org.mifosplatform.infrastructure.user.domain.PermissionRepository; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -35,17 +34,17 @@ public class OfficeWritePlatformServiceJpaRepositoryImpl implements OfficeWriteP private final OfficeRepository officeRepository; private final OfficeTransactionRepository officeMonetaryTransferRepository; private final ApplicationCurrencyRepository applicationCurrencyRepository; - private final PermissionRepository permissionRepository; + private final ConfigurationDomainService configurationDomainService; @Autowired public OfficeWritePlatformServiceJpaRepositoryImpl(final PlatformSecurityContext context, final OfficeRepository officeRepository, final OfficeTransactionRepository officeMonetaryTransferRepository, - final ApplicationCurrencyRepository applicationCurrencyRepository, final PermissionRepository permissionRepository) { + final ApplicationCurrencyRepository applicationCurrencyRepository, final ConfigurationDomainService configurationDomainService) { this.context = context; this.officeRepository = officeRepository; this.officeMonetaryTransferRepository = officeMonetaryTransferRepository; this.applicationCurrencyRepository = applicationCurrencyRepository; - this.permissionRepository = permissionRepository; + this.configurationDomainService = configurationDomainService; } @Transactional @@ -66,9 +65,8 @@ public class OfficeWritePlatformServiceJpaRepositoryImpl implements OfficeWriteP office.generateHierarchy(); this.officeRepository.save(office); - - final Permission thisTask = this.permissionRepository.findOneByCode("CREATE_OFFICE"); - if (thisTask.hasMakerCheckerEnabled() && !command.isApprovedByChecker()) { throw new RollbackTransactionAsCommandIsNotApprovedByCheckerException(); } + + if (this.configurationDomainService.isMakerCheckerEnabledForTask("CREATE_OFFICE") && !command.isApprovedByChecker()) { throw new RollbackTransactionAsCommandIsNotApprovedByCheckerException(); } return office.getId(); } catch (DataIntegrityViolationException dve) { @@ -95,9 +93,8 @@ public class OfficeWritePlatformServiceJpaRepositoryImpl implements OfficeWriteP } this.officeRepository.save(office); - - final Permission thisTask = this.permissionRepository.findOneByCode("UPDATE_OFFICE"); - if (thisTask.hasMakerCheckerEnabled() && !command.isApprovedByChecker()) { throw new RollbackTransactionAsCommandIsNotApprovedByCheckerException(); } + + if (this.configurationDomainService.isMakerCheckerEnabledForTask("UPDATE_OFFICE") && !command.isApprovedByChecker()) { throw new RollbackTransactionAsCommandIsNotApprovedByCheckerException(); } return office.getId(); } catch (DataIntegrityViolationException dve) { @@ -135,9 +132,8 @@ public class OfficeWritePlatformServiceJpaRepositoryImpl implements OfficeWriteP command.getDescription()); this.officeMonetaryTransferRepository.save(entity); - - final Permission thisTask = this.permissionRepository.findOneByCode("CREATE_OFFICETRANSACTION"); - if (thisTask.hasMakerCheckerEnabled() && !command.isApprovedByChecker()) { throw new RollbackTransactionAsCommandIsNotApprovedByCheckerException(); } + + if (this.configurationDomainService.isMakerCheckerEnabledForTask("CREATE_OFFICETRANSACTION") && !command.isApprovedByChecker()) { throw new RollbackTransactionAsCommandIsNotApprovedByCheckerException(); } return entity.getId(); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/staff/service/StaffWritePlatformServiceJpaRepositoryImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/staff/service/StaffWritePlatformServiceJpaRepositoryImpl.java index 5c2bfc272..72d3c0885 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/staff/service/StaffWritePlatformServiceJpaRepositoryImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/staff/service/StaffWritePlatformServiceJpaRepositoryImpl.java @@ -5,14 +5,13 @@ import org.mifosng.platform.client.service.RollbackTransactionAsCommandIsNotAppr import org.mifosng.platform.exceptions.OfficeNotFoundException; import org.mifosng.platform.exceptions.PlatformDataIntegrityException; import org.mifosng.platform.exceptions.StaffNotFoundException; +import org.mifosplatform.infrastructure.configuration.service.ConfigurationDomainService; import org.mifosplatform.infrastructure.office.domain.Office; import org.mifosplatform.infrastructure.office.domain.OfficeRepository; import org.mifosplatform.infrastructure.security.service.PlatformSecurityContext; import org.mifosplatform.infrastructure.staff.command.StaffCommand; import org.mifosplatform.infrastructure.staff.domain.Staff; import org.mifosplatform.infrastructure.staff.domain.StaffRepository; -import org.mifosplatform.infrastructure.user.domain.Permission; -import org.mifosplatform.infrastructure.user.domain.PermissionRepository; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -28,15 +27,15 @@ public class StaffWritePlatformServiceJpaRepositoryImpl implements StaffWritePla private final PlatformSecurityContext context; private final StaffRepository staffRepository; private final OfficeRepository officeRepository; - private final PermissionRepository permissionRepository; + private final ConfigurationDomainService configurationDomainService; @Autowired public StaffWritePlatformServiceJpaRepositoryImpl(final PlatformSecurityContext context, final StaffRepository staffRepository, - final OfficeRepository officeRepository, final PermissionRepository permissionRepository) { + final OfficeRepository officeRepository, final ConfigurationDomainService configurationDomainService) { this.context = context; this.staffRepository = staffRepository; this.officeRepository = officeRepository; - this.permissionRepository = permissionRepository; + this.configurationDomainService = configurationDomainService; } @Transactional @@ -54,8 +53,7 @@ public class StaffWritePlatformServiceJpaRepositoryImpl implements StaffWritePla this.staffRepository.save(staff); - final Permission thisTask = this.permissionRepository.findOneByCode("CREATE_STAFF"); - if (thisTask.hasMakerCheckerEnabled() && !command.isApprovedByChecker()) { throw new RollbackTransactionAsCommandIsNotApprovedByCheckerException(); } + if (this.configurationDomainService.isMakerCheckerEnabledForTask("CREATE_STAFF") && !command.isApprovedByChecker()) { throw new RollbackTransactionAsCommandIsNotApprovedByCheckerException(); } return staff.getId(); } catch (DataIntegrityViolationException dve) { @@ -87,8 +85,7 @@ public class StaffWritePlatformServiceJpaRepositoryImpl implements StaffWritePla this.staffRepository.save(staff); - final Permission thisTask = this.permissionRepository.findOneByCode("UPDATE_STAFF"); - if (thisTask.hasMakerCheckerEnabled() && !command.isApprovedByChecker()) { throw new RollbackTransactionAsCommandIsNotApprovedByCheckerException(); } + if (this.configurationDomainService.isMakerCheckerEnabledForTask("UPDATE_STAFF") && !command.isApprovedByChecker()) { throw new RollbackTransactionAsCommandIsNotApprovedByCheckerException(); } return staff.getId(); } catch (DataIntegrityViolationException dve) { diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/user/api/RolesApiResource.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/user/api/RolesApiResource.java index 1cee2f07b..aff346c04 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/user/api/RolesApiResource.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/user/api/RolesApiResource.java @@ -18,8 +18,10 @@ import javax.ws.rs.core.MediaType; import javax.ws.rs.core.UriInfo; import org.mifosng.platform.api.data.EntityIdentifier; +import org.mifosng.platform.api.infrastructure.PortfolioApiDataConversionService; import org.mifosng.platform.api.infrastructure.PortfolioApiJsonSerializerService; import org.mifosng.platform.api.infrastructure.PortfolioCommandDeserializerService; +import org.mifosng.platform.api.infrastructure.PortfolioCommandSerializerService; import org.mifosng.platform.infrastructure.api.ApiParameterHelper; import org.mifosplatform.commands.api.data.CommandSourceData; import org.mifosplatform.commands.service.PortfolioCommandSourceWritePlatformService; @@ -45,6 +47,8 @@ public class RolesApiResource { private final RoleReadPlatformService roleReadPlatformService; private final PermissionReadPlatformService permissionReadPlatformService; private final PortfolioApiJsonSerializerService apiJsonSerializerService; + private final PortfolioApiDataConversionService apiDataConversionService; + private final PortfolioCommandSerializerService commandSerializerService; private final PortfolioCommandsReadPlatformService commandSourceReadPlatformService; private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService; private final PortfolioCommandDeserializerService commandDeserializerService; @@ -57,6 +61,8 @@ public class RolesApiResource { final RoleReadPlatformService readPlatformService, final PermissionReadPlatformService permissionReadPlatformService, final PortfolioApiJsonSerializerService apiJsonSerializerService, + final PortfolioApiDataConversionService apiDataConversionService, + final PortfolioCommandSerializerService commandSerializerService, final PortfolioCommandsReadPlatformService commandSourceReadPlatformService, final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService, final PortfolioCommandDeserializerService commandDeserializerService) { @@ -64,6 +70,8 @@ public class RolesApiResource { this.roleReadPlatformService = readPlatformService; this.permissionReadPlatformService = permissionReadPlatformService; this.apiJsonSerializerService = apiJsonSerializerService; + this.apiDataConversionService = apiDataConversionService; + this.commandSerializerService = commandSerializerService; this.commandSourceReadPlatformService = commandSourceReadPlatformService; this.commandsSourceWritePlatformService = commandsSourceWritePlatformService; this.commandDeserializerService = commandDeserializerService; @@ -91,9 +99,12 @@ public class RolesApiResource { final List allowedPermissions = Arrays.asList("ALL_FUNCTIONS", "USER_ADMINISTRATION_SUPER_USER", "CREATE_ROLE"); context.authenticatedUser().validateHasPermissionTo("CREATE_ROLE", allowedPermissions); + + final RoleCommand command = this.apiDataConversionService.convertApiRequestJsonToRoleCommand(null,apiRequestBodyAsJson); + final String commandSerializedAsJson = this.commandSerializerService.serializeRoleCommandToJson(command); final EntityIdentifier result = this.commandsSourceWritePlatformService.logCommandSource("CREATE", "roles", null, - apiRequestBodyAsJson); + commandSerializedAsJson); return this.apiJsonSerializerService.serializeEntityIdentifier(result); } @@ -140,8 +151,11 @@ public class RolesApiResource { final List allowedPermissions = Arrays.asList("ALL_FUNCTIONS", "USER_ADMINISTRATION_SUPER_USER", "UPDATE_ROLE"); context.authenticatedUser().validateHasPermissionTo("UPDATE_ROLE", allowedPermissions); + final RoleCommand command = this.apiDataConversionService.convertApiRequestJsonToRoleCommand(roleId, apiRequestBodyAsJson); + final String commandSerializedAsJson = this.commandSerializerService.serializeRoleCommandToJson(command); + final EntityIdentifier result = this.commandsSourceWritePlatformService.logCommandSource("UPDATE", "roles", roleId, - apiRequestBodyAsJson); + commandSerializedAsJson); return this.apiJsonSerializerService.serializeEntityIdentifier(result); } @@ -200,8 +214,11 @@ public class RolesApiResource { final List allowedPermissions = Arrays.asList("ALL_FUNCTIONS", "USER_ADMINISTRATION_SUPER_USER", "PERMISSIONS_ROLE"); context.authenticatedUser().validateHasPermissionTo("PERMISSIONS_ROLE", allowedPermissions); + final RolePermissionCommand command = this.apiDataConversionService.convertApiRequestJsonToRolePermissionCommand(roleId, apiRequestBodyAsJson); + final String commandSerializedAsJson = this.commandSerializerService.serializeRolePermissionCommandToJson(command); + final EntityIdentifier result = this.commandsSourceWritePlatformService.logCommandSource("UPDATEPERMISSIONS", "roles", roleId, - apiRequestBodyAsJson); + commandSerializedAsJson); return this.apiJsonSerializerService.serializeEntityIdentifier(result); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/user/domain/JpaUserDomainService.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/user/domain/JpaUserDomainService.java index 1ac87739e..6dbe0a108 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/user/domain/JpaUserDomainService.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/user/domain/JpaUserDomainService.java @@ -5,6 +5,7 @@ import org.mifosng.platform.infrastructure.EmailDetail; import org.mifosng.platform.infrastructure.PlatformEmailService; import org.mifosng.platform.infrastructure.PlatformPasswordEncoder; import org.mifosng.platform.infrastructure.RandomPasswordGenerator; +import org.mifosplatform.infrastructure.configuration.service.ConfigurationDomainService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @@ -15,21 +16,21 @@ public class JpaUserDomainService implements UserDomainService { private final AppUserRepository userRepository; private final PlatformPasswordEncoder applicationPasswordEncoder; private final PlatformEmailService emailService; - private final PermissionRepository permissionRepository; - + private final ConfigurationDomainService configurationDomainService; + @Autowired public JpaUserDomainService(final AppUserRepository userRepository, final PlatformPasswordEncoder applicationPasswordEncoder, - final PlatformEmailService emailService, final PermissionRepository permissionRepository) { + final PlatformEmailService emailService, final ConfigurationDomainService configurationDomainService) { this.userRepository = userRepository; this.applicationPasswordEncoder = applicationPasswordEncoder; this.emailService = emailService; - this.permissionRepository = permissionRepository; + this.configurationDomainService = configurationDomainService; } - + @Transactional @Override public void create(final AppUser appUser, final boolean isApprovedByChecker) { - + generateKeyUsedForPasswordSalting(appUser); String unencodedPassword = appUser.getPassword(); @@ -42,11 +43,11 @@ public class JpaUserDomainService implements UserDomainService { appUser.updatePassword(encodePassword); this.userRepository.save(appUser); - - final Permission thisTask = this.permissionRepository.findOneByCode("CREATE_USER"); - if (thisTask.hasMakerCheckerEnabled() && !isApprovedByChecker) { throw new RollbackTransactionAsCommandIsNotApprovedByCheckerException(); } - final EmailDetail emailDetail = new EmailDetail(appUser.getFirstname(), appUser.getFirstname(), appUser.getEmail(), appUser.getUsername()); + if (this.configurationDomainService.isMakerCheckerEnabledForTask("CREATE_USER") && !isApprovedByChecker) { throw new RollbackTransactionAsCommandIsNotApprovedByCheckerException(); } + + final EmailDetail emailDetail = new EmailDetail(appUser.getFirstname(), appUser.getFirstname(), appUser.getEmail(), + appUser.getUsername()); this.emailService.sendToUserAccount(emailDetail, unencodedPassword); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/user/exception/PermissionCantBeMakerCheckerableException.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/user/exception/PermissionCantBeMakerCheckerableException.java new file mode 100644 index 000000000..3b14f4289 --- /dev/null +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/user/exception/PermissionCantBeMakerCheckerableException.java @@ -0,0 +1,13 @@ +package org.mifosplatform.infrastructure.user.exception; + +import org.mifosng.platform.exceptions.AbstractPlatformResourceNotFoundException; + +/** + * A {@link RuntimeException} thrown when permission is attempted to be set as maker-checker enabled. + */ +public class PermissionCantBeMakerCheckerableException extends AbstractPlatformResourceNotFoundException { + + public PermissionCantBeMakerCheckerableException(final String code) { + super("error.msg.permission.code.not.makercheckerable", "Permission with Code " + code + " can't be maker-checkerable", code); + } +} \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/user/exception/PermissionNotFoundException.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/user/exception/PermissionNotFoundException.java new file mode 100644 index 000000000..096cb31ce --- /dev/null +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/user/exception/PermissionNotFoundException.java @@ -0,0 +1,13 @@ +package org.mifosplatform.infrastructure.user.exception; + +import org.mifosng.platform.exceptions.AbstractPlatformResourceNotFoundException; + +/** + * A {@link RuntimeException} thrown when permission resources are not found. + */ +public class PermissionNotFoundException extends AbstractPlatformResourceNotFoundException { + + public PermissionNotFoundException(final String code) { + super("error.msg.permission.code.invalid", "Permission with Code " + code + " does not exist", code); + } +} \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/user/service/AppUserWritePlatformServiceJpaRepositoryImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/user/service/AppUserWritePlatformServiceJpaRepositoryImpl.java index 20aa1aa20..1bf2a2541 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/user/service/AppUserWritePlatformServiceJpaRepositoryImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/user/service/AppUserWritePlatformServiceJpaRepositoryImpl.java @@ -15,6 +15,7 @@ import org.mifosng.platform.exceptions.RoleNotFoundException; import org.mifosng.platform.exceptions.UserNotFoundException; import org.mifosng.platform.infrastructure.PlatformEmailSendException; import org.mifosng.platform.infrastructure.PlatformPasswordEncoder; +import org.mifosplatform.infrastructure.configuration.service.ConfigurationDomainService; import org.mifosplatform.infrastructure.office.domain.Office; import org.mifosplatform.infrastructure.office.domain.OfficeRepository; import org.mifosplatform.infrastructure.security.domain.BasicPasswordEncodablePlatformUser; @@ -24,8 +25,6 @@ import org.mifosplatform.infrastructure.user.command.UserCommand; import org.mifosplatform.infrastructure.user.command.UserCommandValidator; import org.mifosplatform.infrastructure.user.domain.AppUser; import org.mifosplatform.infrastructure.user.domain.AppUserRepository; -import org.mifosplatform.infrastructure.user.domain.Permission; -import org.mifosplatform.infrastructure.user.domain.PermissionRepository; import org.mifosplatform.infrastructure.user.domain.Role; import org.mifosplatform.infrastructure.user.domain.RoleRepository; import org.mifosplatform.infrastructure.user.domain.UserDomainService; @@ -48,19 +47,19 @@ public class AppUserWritePlatformServiceJpaRepositoryImpl implements AppUserWrit private final AppUserRepository appUserRepository; private final OfficeRepository officeRepository; private final RoleRepository roleRepository; - private final PermissionRepository permissionRepository; - + private final ConfigurationDomainService configurationDomainService; + @Autowired public AppUserWritePlatformServiceJpaRepositoryImpl(final PlatformSecurityContext context, final AppUserRepository appUserRepository, final UserDomainService userDomainService, final OfficeRepository officeRepository, final RoleRepository roleRepository, - final PlatformPasswordEncoder platformPasswordEncoder, final PermissionRepository permissionRepository) { + final PlatformPasswordEncoder platformPasswordEncoder, final ConfigurationDomainService configurationDomainService) { this.context = context; this.appUserRepository = appUserRepository; this.userDomainService = userDomainService; this.officeRepository = officeRepository; this.roleRepository = roleRepository; this.platformPasswordEncoder = platformPasswordEncoder; - this.permissionRepository = permissionRepository; + this.configurationDomainService = configurationDomainService; } @Transactional @@ -87,7 +86,7 @@ public class AppUserWritePlatformServiceJpaRepositoryImpl implements AppUserWrit command.getLastname(), password); this.userDomainService.create(appUser, command.isApprovedByChecker()); - + return appUser.getId(); } catch (DataIntegrityViolationException dve) { handleDataIntegrityIssues(command, dve); @@ -109,10 +108,10 @@ public class AppUserWritePlatformServiceJpaRepositoryImpl implements AppUserWrit try { context.authenticatedUser(); - + UserCommandValidator validator = new UserCommandValidator(command); validator.validateForUpdate(); - + final Set allRoles = assembleSetOfRoles(command); Office office = null; @@ -137,8 +136,7 @@ public class AppUserWritePlatformServiceJpaRepositoryImpl implements AppUserWrit this.appUserRepository.saveAndFlush(userToUpdate); } - final Permission thisTask = this.permissionRepository.findOneByCode("UPDATE_USER"); - if (thisTask.hasMakerCheckerEnabled() && !command.isApprovedByChecker()) { throw new RollbackTransactionAsCommandIsNotApprovedByCheckerException(); } + if (this.configurationDomainService.isMakerCheckerEnabledForTask("UPDATE_USER") && !command.isApprovedByChecker()) { throw new RollbackTransactionAsCommandIsNotApprovedByCheckerException(); } return userToUpdate.getId(); } catch (DataIntegrityViolationException dve) { @@ -155,10 +153,10 @@ public class AppUserWritePlatformServiceJpaRepositoryImpl implements AppUserWrit @Transactional @Override public Long updateUsersOwnAccountDetails(final UserCommand command) { - + try { context.authenticatedUser(); - + UserCommandValidator validator = new UserCommandValidator(command); validator.validateForUpdate(); @@ -185,7 +183,7 @@ public class AppUserWritePlatformServiceJpaRepositoryImpl implements AppUserWrit userToUpdate.updatePassword(newPasswordEncoded); this.appUserRepository.saveAndFlush(userToUpdate); } - + return userToUpdate.getId(); } catch (DataIntegrityViolationException dve) { handleDataIntegrityIssues(command, dve); @@ -213,8 +211,6 @@ public class AppUserWritePlatformServiceJpaRepositoryImpl implements AppUserWrit @Transactional @Override public void deleteUser(final UserCommand command) { - - final Permission permissionForThisTask = this.permissionRepository.findOneByCode("UPDATE_USER"); final Long userId = command.getId(); AppUser user = this.appUserRepository.findOne(userId); @@ -222,8 +218,8 @@ public class AppUserWritePlatformServiceJpaRepositoryImpl implements AppUserWrit user.delete(); this.appUserRepository.save(user); - - if (permissionForThisTask.hasMakerCheckerEnabled() && !command.isApprovedByChecker()) { throw new RollbackTransactionAsCommandIsNotApprovedByCheckerException(); } + + if (this.configurationDomainService.isMakerCheckerEnabledForTask("DELETE_USER") && !command.isApprovedByChecker()) { throw new RollbackTransactionAsCommandIsNotApprovedByCheckerException(); } } /* diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/user/service/PermissionWritePlatformServiceJpaRepositoryImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/user/service/PermissionWritePlatformServiceJpaRepositoryImpl.java index 7d9d305d9..5f824a276 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/user/service/PermissionWritePlatformServiceJpaRepositoryImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/user/service/PermissionWritePlatformServiceJpaRepositoryImpl.java @@ -3,11 +3,11 @@ package org.mifosplatform.infrastructure.user.service; import java.util.Collection; import java.util.Map; -import org.mifosng.platform.exceptions.PermissionNotFoundException; import org.mifosplatform.infrastructure.security.service.PlatformSecurityContext; import org.mifosplatform.infrastructure.user.command.PermissionsCommand; import org.mifosplatform.infrastructure.user.domain.Permission; import org.mifosplatform.infrastructure.user.domain.PermissionRepository; +import org.mifosplatform.infrastructure.user.exception.PermissionNotFoundException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/user/service/RoleWritePlatformServiceJpaRepositoryImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/user/service/RoleWritePlatformServiceJpaRepositoryImpl.java index b64d3bc8d..19ec4629f 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/user/service/RoleWritePlatformServiceJpaRepositoryImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/user/service/RoleWritePlatformServiceJpaRepositoryImpl.java @@ -4,8 +4,8 @@ import java.util.Collection; import java.util.Map; import org.mifosng.platform.client.service.RollbackTransactionAsCommandIsNotApprovedByCheckerException; -import org.mifosng.platform.exceptions.PermissionNotFoundException; import org.mifosng.platform.exceptions.RoleNotFoundException; +import org.mifosplatform.infrastructure.configuration.service.ConfigurationDomainService; import org.mifosplatform.infrastructure.security.service.PlatformSecurityContext; import org.mifosplatform.infrastructure.user.command.RoleCommand; import org.mifosplatform.infrastructure.user.command.RoleCommandValidator; @@ -14,6 +14,7 @@ import org.mifosplatform.infrastructure.user.domain.Permission; import org.mifosplatform.infrastructure.user.domain.PermissionRepository; import org.mifosplatform.infrastructure.user.domain.Role; import org.mifosplatform.infrastructure.user.domain.RoleRepository; +import org.mifosplatform.infrastructure.user.exception.PermissionNotFoundException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @@ -24,13 +25,16 @@ public class RoleWritePlatformServiceJpaRepositoryImpl implements RoleWritePlatf private final PlatformSecurityContext context; private final RoleRepository roleRepository; private final PermissionRepository permissionRepository; + private final ConfigurationDomainService configurationDomainService; @Autowired public RoleWritePlatformServiceJpaRepositoryImpl(final PlatformSecurityContext context, final RoleRepository roleRepository, - final PermissionRepository permissionRepository) { + final PermissionRepository permissionRepository, + final ConfigurationDomainService configurationDomainService) { this.context = context; this.roleRepository = roleRepository; this.permissionRepository = permissionRepository; + this.configurationDomainService = configurationDomainService; } @Transactional @@ -46,8 +50,7 @@ public class RoleWritePlatformServiceJpaRepositoryImpl implements RoleWritePlatf this.roleRepository.save(entity); - final Permission thisTask = this.permissionRepository.findOneByCode("CREATE_ROLE"); - if (thisTask.hasMakerCheckerEnabled() && !command.isApprovedByChecker()) { throw new RollbackTransactionAsCommandIsNotApprovedByCheckerException(); } + if (this.configurationDomainService.isMakerCheckerEnabledForTask("CREATE_ROLE") && !command.isApprovedByChecker()) { throw new RollbackTransactionAsCommandIsNotApprovedByCheckerException(); } return entity.getId(); } @@ -67,9 +70,8 @@ public class RoleWritePlatformServiceJpaRepositoryImpl implements RoleWritePlatf this.roleRepository.save(role); - final Permission thisTask = this.permissionRepository.findOneByCode("UPDATE_ROLE"); - if (thisTask.hasMakerCheckerEnabled() && !command.isApprovedByChecker()) { throw new RollbackTransactionAsCommandIsNotApprovedByCheckerException(); } - + if (this.configurationDomainService.isMakerCheckerEnabledForTask("UPDATE_ROLE") && !command.isApprovedByChecker()) { throw new RollbackTransactionAsCommandIsNotApprovedByCheckerException(); } + return role.getId(); } @@ -97,8 +99,7 @@ public class RoleWritePlatformServiceJpaRepositoryImpl implements RoleWritePlatf this.roleRepository.save(role); - final Permission thisTask = this.permissionRepository.findOneByCode("PERMISSIONS_ROLE"); - if (thisTask.hasMakerCheckerEnabled() && !command.isApprovedByChecker()) { throw new RollbackTransactionAsCommandIsNotApprovedByCheckerException(); } + if (this.configurationDomainService.isMakerCheckerEnabledForTask("PERMISSIONS_ROLE") && !command.isApprovedByChecker()) { throw new RollbackTransactionAsCommandIsNotApprovedByCheckerException(); } return role.getId(); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/api/ChargesApiResource.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/api/ChargesApiResource.java index 22317e3bf..501e20b2c 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/api/ChargesApiResource.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/api/ChargesApiResource.java @@ -1,6 +1,8 @@ package org.mifosplatform.portfolio.charge.api; +import java.util.Arrays; import java.util.Collection; +import java.util.List; import java.util.Set; import javax.ws.rs.Consumes; @@ -13,18 +15,18 @@ import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; import javax.ws.rs.core.UriInfo; import org.mifosng.platform.api.data.EntityIdentifier; import org.mifosng.platform.api.infrastructure.PortfolioApiDataConversionService; import org.mifosng.platform.api.infrastructure.PortfolioApiJsonSerializerService; +import org.mifosng.platform.api.infrastructure.PortfolioCommandSerializerService; import org.mifosng.platform.infrastructure.api.ApiParameterHelper; +import org.mifosplatform.commands.service.PortfolioCommandSourceWritePlatformService; import org.mifosplatform.infrastructure.security.service.PlatformSecurityContext; -import org.mifosplatform.portfolio.charge.command.ChargeCommand; +import org.mifosplatform.portfolio.charge.command.ChargeDefinitionCommand; import org.mifosplatform.portfolio.charge.data.ChargeData; import org.mifosplatform.portfolio.charge.service.ChargeReadPlatformService; -import org.mifosplatform.portfolio.charge.service.ChargeWritePlatformService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; @@ -34,34 +36,41 @@ import org.springframework.stereotype.Component; @Scope("singleton") public class ChargesApiResource { - private final String entityType = "CHARGE"; + private final String resourceNameForPermissions = "CHARGE"; + + private final PlatformSecurityContext context; + private final ChargeReadPlatformService readPlatformService; + private final PortfolioApiDataConversionService apiDataConversionService; + private final PortfolioCommandSerializerService commandSerializerService; + private final PortfolioApiJsonSerializerService apiJsonSerializerService; + private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService; @Autowired - private ChargeReadPlatformService chargeReadPlatformService; - - @Autowired - private ChargeWritePlatformService chargeWritePlatformService; - - @Autowired - private PortfolioApiDataConversionService apiDataConversionService; - - @Autowired - private PortfolioApiJsonSerializerService apiJsonSerializerService; - - @Autowired - private PlatformSecurityContext context; - + public ChargesApiResource(final PlatformSecurityContext context, + final ChargeReadPlatformService readPlatformService, + final PortfolioApiDataConversionService apiDataConversionService, + final PortfolioCommandSerializerService commandSerializerService, + final PortfolioApiJsonSerializerService apiJsonSerializerService, + final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService) { + this.context = context; + this.readPlatformService = readPlatformService; + this.apiDataConversionService = apiDataConversionService; + this.commandSerializerService = commandSerializerService; + this.apiJsonSerializerService = apiJsonSerializerService; + this.commandsSourceWritePlatformService = commandsSourceWritePlatformService; + } + @GET @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) public String retrieveAllCharges(@Context final UriInfo uriInfo) { - context.authenticatedUser().validateHasReadPermission(entityType); + context.authenticatedUser().validateHasReadPermission(resourceNameForPermissions); final Set responseParameters = ApiParameterHelper.extractFieldsForResponseIfProvided(uriInfo.getQueryParameters()); final boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo.getQueryParameters()); - final Collection charges = this.chargeReadPlatformService.retrieveAllCharges(); + final Collection charges = this.readPlatformService.retrieveAllCharges(); return this.apiJsonSerializerService.serializeChargeDataToJson(prettyPrint, responseParameters, charges); } @@ -72,16 +81,16 @@ public class ChargesApiResource { @Produces({ MediaType.APPLICATION_JSON }) public String retrieveCharge(@PathParam("chargeId") final Long chargeId, @Context final UriInfo uriInfo) { - context.authenticatedUser().validateHasReadPermission(entityType); + context.authenticatedUser().validateHasReadPermission(resourceNameForPermissions); final Set responseParameters = ApiParameterHelper.extractFieldsForResponseIfProvided(uriInfo.getQueryParameters()); final boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo.getQueryParameters()); final boolean template = ApiParameterHelper.template(uriInfo.getQueryParameters()); - ChargeData charge = this.chargeReadPlatformService.retrieveCharge(chargeId); + ChargeData charge = this.readPlatformService.retrieveCharge(chargeId); if (template) { - ChargeData templateData = this.chargeReadPlatformService.retrieveNewChargeDetails(); + ChargeData templateData = this.readPlatformService.retrieveNewChargeDetails(); charge = new ChargeData(charge, templateData); } @@ -94,13 +103,13 @@ public class ChargesApiResource { @Produces({ MediaType.APPLICATION_JSON }) public String retrieveNewChargeDetails(@Context final UriInfo uriInfo) { - context.authenticatedUser().validateHasReadPermission(entityType); + context.authenticatedUser().validateHasReadPermission(resourceNameForPermissions); final Set responseParameters = ApiParameterHelper.extractFieldsForResponseIfProvided(uriInfo.getQueryParameters()); final boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo.getQueryParameters()); - final ChargeData chargeData = this.chargeReadPlatformService.retrieveNewChargeDetails(); + final ChargeData chargeData = this.readPlatformService.retrieveNewChargeDetails(); return this.apiJsonSerializerService.serializeChargeDataToJson(prettyPrint, responseParameters, chargeData); } @@ -108,36 +117,47 @@ public class ChargesApiResource { @POST @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - public Response createCharge(final String jsonRequestBody) { + public String createCharge(final String apiRequestBodyAsJson) { + + final List allowedPermissions = Arrays.asList("ALL_FUNCTIONS", "ORGANISATION_ADMINISTRATION_SUPER_USER", "CREATE_CHARGE"); + context.authenticatedUser().validateHasPermissionTo("CREATE_CHARGE", allowedPermissions); - final ChargeCommand command = this.apiDataConversionService.convertJsonToChargeCommand(null, jsonRequestBody); + final ChargeDefinitionCommand command = this.apiDataConversionService.convertApiRequestJsonToChargeDefinitionCommand(null, apiRequestBodyAsJson); + final String commandSerializedAsJson = this.commandSerializerService.serializeCommandToJson(command); + + final EntityIdentifier result = this.commandsSourceWritePlatformService.logCommandSource("CREATE", "charges", null, commandSerializedAsJson); - final Long chargeId = this.chargeWritePlatformService.createCharge(command); - - return Response.ok().entity(new EntityIdentifier(chargeId)).build(); + return this.apiJsonSerializerService.serializeEntityIdentifier(result); } @PUT @Path("{chargeId}") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - public Response updateCharge(@PathParam("chargeId") final Long chargeId, final String jsonRequestBody) { + public String updateCharge(@PathParam("chargeId") final Long chargeId, final String apiRequestBodyAsJson) { + + final List allowedPermissions = Arrays.asList("ALL_FUNCTIONS", "ORGANISATION_ADMINISTRATION_SUPER_USER", "UPDATE_CHARGE"); + context.authenticatedUser().validateHasPermissionTo("UPDATE_CHARGE", allowedPermissions); + + final ChargeDefinitionCommand command = this.apiDataConversionService.convertApiRequestJsonToChargeDefinitionCommand(chargeId, apiRequestBodyAsJson); + final String commandSerializedAsJson = this.commandSerializerService.serializeCommandToJson(command); + + final EntityIdentifier result = this.commandsSourceWritePlatformService.logCommandSource("UPDATE", "charges", chargeId, commandSerializedAsJson); - final ChargeCommand command = this.apiDataConversionService.convertJsonToChargeCommand(chargeId, jsonRequestBody); - - final Long entityId = this.chargeWritePlatformService.updateCharge(command); - - return Response.ok().entity(new EntityIdentifier(entityId)).build(); + return this.apiJsonSerializerService.serializeEntityIdentifier(result); } @DELETE @Path("{chargeId}") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - public Response deleteCharge(@PathParam("chargeId") final Long chargeId) { + public String deleteCharge(@PathParam("chargeId") final Long chargeId) { - Long entityId = this.chargeWritePlatformService.deleteCharge(chargeId); + final List allowedPermissions = Arrays.asList("ALL_FUNCTIONS", "ORGANISATION_ADMINISTRATION_SUPER_USER", "DELETE_CHARGE"); + context.authenticatedUser().validateHasPermissionTo("DELETE_CHARGE", allowedPermissions); + + final EntityIdentifier result = this.commandsSourceWritePlatformService.logCommandSource("DELETE", "charges", chargeId, "{}"); - return Response.ok().entity(new EntityIdentifier(entityId)).build(); + return this.apiJsonSerializerService.serializeEntityIdentifier(result); } -} +} \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/command/ChargeCommand.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/command/ChargeCommand.java deleted file mode 100644 index 112872fe4..000000000 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/command/ChargeCommand.java +++ /dev/null @@ -1,123 +0,0 @@ -package org.mifosplatform.portfolio.charge.command; - -import java.math.BigDecimal; -import java.util.Set; - -/** - * Immutable data object for creating and modifying defined charges. - */ -public class ChargeCommand { - - private final Long id; - private final String name; - private final BigDecimal amount; - private final String currencyCode; - - private final Integer chargeTimeType; - private final Integer chargeAppliesTo; - private final Integer chargeCalculationType; - - private final boolean penalty; - private final boolean active; - - private final Set modifiedParameters; - - public ChargeCommand( - final Set modifiedParameters, - final Long id, - final String name, - final BigDecimal amount, - final String currencyCode, - final Integer chargeTimeType, - final Integer chargeAppliesTo, - final Integer chargeCalculationType, - final boolean penalty, - final boolean active) { - this.id = id; - this.name = name; - this.amount = amount; - this.currencyCode = currencyCode; - this.chargeTimeType = chargeTimeType; - this.chargeAppliesTo = chargeAppliesTo; - this.chargeCalculationType = chargeCalculationType; - this.modifiedParameters = modifiedParameters; - this.penalty = penalty; - this.active = active; - } - - public Long getId() { - return id; - } - - public String getName() { - return name; - } - - public BigDecimal getAmount() { - return amount; - } - - public Set getModifiedParameters() { - return modifiedParameters; - } - - public String getCurrencyCode() { - return currencyCode; - } - - public Integer getChargeCalculationType() { - return chargeCalculationType; - } - - public Integer getChargeAppliesTo() { - return chargeAppliesTo; - } - - public Integer getChargeTimeType() { - return chargeTimeType; - } - - public boolean isPenalty() { - return penalty; - } - - public boolean isFee() { - return !penalty; - } - - public boolean isActive() { - return active; - } - - public boolean isNameChanged(){ - return this.modifiedParameters.contains("name"); - } - - public boolean isAmountChanged(){ - return this.modifiedParameters.contains("amount"); - } - - public boolean isCurrencyCodeChanged(){ - return this.modifiedParameters.contains("currencyCode"); - } - - public boolean isChargeTimeTypeChanged(){ - return this.modifiedParameters.contains("chargeTimeType"); - } - - public boolean isChargeAppliesToChanged(){ - return this.modifiedParameters.contains("chargeAppliesTo"); - } - - public boolean isChargeCalculationTypeChanged(){ - return this.modifiedParameters.contains("chargeCalculationType"); - } - - public boolean isPenaltyChanged(){ - return this.modifiedParameters.contains("penalty"); - } - - public boolean isActiveChanged(){ - return this.modifiedParameters.contains("active"); - } -} \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/command/ChargeCommandValidator.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/command/ChargeCommandValidator.java deleted file mode 100644 index 29dc923dc..000000000 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/command/ChargeCommandValidator.java +++ /dev/null @@ -1,56 +0,0 @@ -package org.mifosplatform.portfolio.charge.command; - -import org.mifosng.platform.DataValidatorBuilder; -import org.mifosng.platform.api.data.ApiParameterError; -import org.mifosng.platform.exceptions.PlatformApiDataValidationException; - -import java.util.ArrayList; -import java.util.List; - -public class ChargeCommandValidator { - - private final ChargeCommand command; - - public ChargeCommandValidator(final ChargeCommand command) { - this.command = command; - } - - public void validateForCreate() { - List dataValidationErrors = new ArrayList(); - - DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("charge"); - - baseDataValidator.reset().parameter("name").value(command.getName()).notBlank().notExceedingLengthOf(100); - baseDataValidator.reset().parameter("amount").value(command.getAmount()).notNull().positiveAmount(); - baseDataValidator.reset().parameter("currencyCode").value(command.getCurrencyCode()).notBlank(); - baseDataValidator.reset().parameter("chargeAppliesTo").value(command.getChargeAppliesTo()).notNull().inMinMaxRange(1, 1); - baseDataValidator.reset().parameter("chargeTimeType").value(command.getChargeTimeType()).notNull().inMinMaxRange(1, 2); - baseDataValidator.reset().parameter("chargeCalculationType").value(command.getChargeCalculationType()).notNull().inMinMaxRange(1, 4); - - if (command.isPenalty() && command.getChargeTimeType().equals(Integer.valueOf(1))) { - // FIXME - KW - cannot have penalty charge at time of disbursement - } - - if (!dataValidationErrors.isEmpty()) { - throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.", dataValidationErrors); - } - } - - public void validateForUpdate() { - List dataValidationErrors = new ArrayList(); - - DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("charge"); - - baseDataValidator.reset().parameter("id").value(command.getId()).notNull(); - baseDataValidator.reset().parameter("name").value(command.getName()).ignoreIfNull().notBlank().notExceedingLengthOf(100); - baseDataValidator.reset().parameter("amount").value(command.getAmount()).ignoreIfNull().positiveAmount(); - baseDataValidator.reset().parameter("currencyCode").value(command.getCurrencyCode()).ignoreIfNull().notBlank(); - baseDataValidator.reset().parameter("chargeAppliesTo").value(command.getChargeAppliesTo()).ignoreIfNull().notNull().inMinMaxRange(1, 1); - baseDataValidator.reset().parameter("chargeTimeType").value(command.getChargeTimeType()).ignoreIfNull().notNull().inMinMaxRange(1, 2); - baseDataValidator.reset().parameter("chargeCalculationType").value(command.getChargeCalculationType()).ignoreIfNull().notNull().inMinMaxRange(1, 4); - - if (!dataValidationErrors.isEmpty()) { - throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.", dataValidationErrors); - } - } -} diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/command/ChargeDefinitionCommand.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/command/ChargeDefinitionCommand.java new file mode 100644 index 000000000..aa1c8d312 --- /dev/null +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/command/ChargeDefinitionCommand.java @@ -0,0 +1,175 @@ +package org.mifosplatform.portfolio.charge.command; + +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; +import java.util.Set; + +import org.mifosng.platform.DataValidatorBuilder; +import org.mifosng.platform.api.data.ApiParameterError; +import org.mifosng.platform.exceptions.PlatformApiDataValidationException; + +/** + * Immutable data object for creating and modifying defined charges. + */ +public class ChargeDefinitionCommand { + + private final String name; + private final BigDecimal amount; + private final String currencyCode; + + private final Integer chargeTimeType; + private final Integer chargeAppliesTo; + private final Integer chargeCalculationType; + + private final boolean penalty; + private final boolean active; + + private final transient Set modifiedParameters; + private final transient boolean makerCheckerApproval; + private final transient Long id; + + public ChargeDefinitionCommand( + final Set modifiedParameters, + final boolean makerCheckerApproval, + final Long id, + final String name, + final BigDecimal amount, + final String currencyCode, + final Integer chargeTimeType, + final Integer chargeAppliesTo, + final Integer chargeCalculationType, + final boolean penalty, + final boolean active) { + this.makerCheckerApproval = makerCheckerApproval; + this.id = id; + this.name = name; + this.amount = amount; + this.currencyCode = currencyCode; + this.chargeTimeType = chargeTimeType; + this.chargeAppliesTo = chargeAppliesTo; + this.chargeCalculationType = chargeCalculationType; + this.modifiedParameters = modifiedParameters; + this.penalty = penalty; + this.active = active; + } + + public Long getId() { + return id; + } + + public String getName() { + return name; + } + + public BigDecimal getAmount() { + return amount; + } + + public Set getModifiedParameters() { + return modifiedParameters; + } + + public String getCurrencyCode() { + return currencyCode; + } + + public Integer getChargeCalculationType() { + return chargeCalculationType; + } + + public Integer getChargeAppliesTo() { + return chargeAppliesTo; + } + + public Integer getChargeTimeType() { + return chargeTimeType; + } + + public boolean isPenalty() { + return penalty; + } + + public boolean isFee() { + return !penalty; + } + + public boolean isActive() { + return active; + } + + public boolean isNameChanged(){ + return this.modifiedParameters.contains("name"); + } + + public boolean isAmountChanged(){ + return this.modifiedParameters.contains("amount"); + } + + public boolean isCurrencyCodeChanged(){ + return this.modifiedParameters.contains("currencyCode"); + } + + public boolean isChargeTimeTypeChanged(){ + return this.modifiedParameters.contains("chargeTimeType"); + } + + public boolean isChargeAppliesToChanged(){ + return this.modifiedParameters.contains("chargeAppliesTo"); + } + + public boolean isChargeCalculationTypeChanged(){ + return this.modifiedParameters.contains("chargeCalculationType"); + } + + public boolean isPenaltyChanged(){ + return this.modifiedParameters.contains("penalty"); + } + + public boolean isActiveChanged(){ + return this.modifiedParameters.contains("active"); + } + + public boolean isApprovedByChecker() { + return this.makerCheckerApproval; + } + + public void validateForCreate() { + List dataValidationErrors = new ArrayList(); + + DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("charge"); + + baseDataValidator.reset().parameter("name").value(this.name).notBlank().notExceedingLengthOf(100); + baseDataValidator.reset().parameter("amount").value(this.amount).notNull().positiveAmount(); + baseDataValidator.reset().parameter("currencyCode").value(this.currencyCode).notBlank(); + baseDataValidator.reset().parameter("chargeAppliesTo").value(this.chargeAppliesTo).notNull().inMinMaxRange(1, 1); + baseDataValidator.reset().parameter("chargeTimeType").value(this.chargeTimeType).notNull().inMinMaxRange(1, 2); + baseDataValidator.reset().parameter("chargeCalculationType").value(this.chargeCalculationType).notNull().inMinMaxRange(1, 4); + + if (this.penalty && this.chargeTimeType.equals(Integer.valueOf(1))) { + // FIXME - KW - cannot have penalty charge at time of disbursement + } + + if (!dataValidationErrors.isEmpty()) { + throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.", dataValidationErrors); + } + } + + public void validateForUpdate() { + List dataValidationErrors = new ArrayList(); + + DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("charge"); + + baseDataValidator.reset().parameter("id").value(this.id).notNull(); + baseDataValidator.reset().parameter("name").value(this.name).ignoreIfNull().notBlank().notExceedingLengthOf(100); + baseDataValidator.reset().parameter("amount").value(this.amount).ignoreIfNull().positiveAmount(); + baseDataValidator.reset().parameter("currencyCode").value(this.currencyCode).ignoreIfNull().notBlank(); + baseDataValidator.reset().parameter("chargeAppliesTo").value(this.chargeAppliesTo).ignoreIfNull().notNull().inMinMaxRange(1, 1); + baseDataValidator.reset().parameter("chargeTimeType").value(this.chargeTimeType).ignoreIfNull().notNull().inMinMaxRange(1, 2); + baseDataValidator.reset().parameter("chargeCalculationType").value(this.chargeCalculationType).ignoreIfNull().notNull().inMinMaxRange(1, 4); + + if (!dataValidationErrors.isEmpty()) { + throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.", dataValidationErrors); + } + } +} \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/domain/Charge.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/domain/Charge.java index 117715ace..29f93b23d 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/domain/Charge.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/domain/Charge.java @@ -2,7 +2,7 @@ package org.mifosplatform.portfolio.charge.domain; import org.mifosng.platform.infrastructure.AbstractAuditableCustom; import org.mifosplatform.infrastructure.user.domain.AppUser; -import org.mifosplatform.portfolio.charge.command.ChargeCommand; +import org.mifosplatform.portfolio.charge.command.ChargeDefinitionCommand; import javax.persistence.*; import java.math.BigDecimal; @@ -93,7 +93,7 @@ public class Charge extends AbstractAuditableCustom { return deleted; } - public void update(final ChargeCommand command) { + public void update(final ChargeDefinitionCommand command) { if (command.isNameChanged()) { this.name = command.getName(); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/service/ChargeDropdownReadPlatformService.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/service/ChargeDropdownReadPlatformService.java index daa927349..68c28032c 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/service/ChargeDropdownReadPlatformService.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/service/ChargeDropdownReadPlatformService.java @@ -6,10 +6,9 @@ import org.mifosng.platform.api.data.EnumOptionData; public interface ChargeDropdownReadPlatformService { - List retrieveCalculationTypes(); + List retrieveCalculationTypes(); - List retrieveApplicableToTypes(); - - List retrieveCollectionTimeTypes(); + List retrieveApplicableToTypes(); + List retrieveCollectionTimeTypes(); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/service/ChargeDropdownReadPlatformServiceImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/service/ChargeDropdownReadPlatformServiceImpl.java index 906862316..7dfd119a0 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/service/ChargeDropdownReadPlatformServiceImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/service/ChargeDropdownReadPlatformServiceImpl.java @@ -16,23 +16,23 @@ import org.springframework.stereotype.Service; @Service public class ChargeDropdownReadPlatformServiceImpl implements ChargeDropdownReadPlatformService { - @Override - public List retrieveCalculationTypes() { + @Override + public List retrieveCalculationTypes() { - return Arrays.asList(chargeCalculationType(ChargeCalculationType.FLAT), - chargeCalculationType(ChargeCalculationType.PERCENT_OF_AMOUNT) - // chargeCalculationType(ChargeCalculationType.PERCENT_OF_AMOUNT_AND_INTEREST), - // chargeCalculationType(ChargeCalculationType.PERCENT_OF_INTEREST) - ); - } + return Arrays.asList(chargeCalculationType(ChargeCalculationType.FLAT), + chargeCalculationType(ChargeCalculationType.PERCENT_OF_AMOUNT) + // chargeCalculationType(ChargeCalculationType.PERCENT_OF_AMOUNT_AND_INTEREST), + // chargeCalculationType(ChargeCalculationType.PERCENT_OF_INTEREST) + ); + } - @Override - public List retrieveApplicableToTypes() { - return Arrays.asList(chargeAppliesTo(ChargeAppliesTo.LOAN)); - } + @Override + public List retrieveApplicableToTypes() { + return Arrays.asList(chargeAppliesTo(ChargeAppliesTo.LOAN)); + } - @Override - public List retrieveCollectionTimeTypes() { - return Arrays.asList(chargeTimeType(ChargeTimeType.DISBURSEMENT), chargeTimeType(ChargeTimeType.SPECIFIED_DUE_DATE)); - } + @Override + public List retrieveCollectionTimeTypes() { + return Arrays.asList(chargeTimeType(ChargeTimeType.DISBURSEMENT), chargeTimeType(ChargeTimeType.SPECIFIED_DUE_DATE)); + } } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/service/ChargeEnumerations.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/service/ChargeEnumerations.java index ae4b38f1d..571825f5f 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/service/ChargeEnumerations.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/service/ChargeEnumerations.java @@ -7,65 +7,73 @@ import org.mifosplatform.portfolio.charge.domain.ChargeTimeType; public class ChargeEnumerations { - public static EnumOptionData chargeTimeType(final int id){ + public static EnumOptionData chargeTimeType(final int id) { return chargeTimeType(ChargeTimeType.fromInt(id)); } - public static EnumOptionData chargeTimeType(final ChargeTimeType type){ + public static EnumOptionData chargeTimeType(final ChargeTimeType type) { EnumOptionData optionData = null; - switch (type){ + switch (type) { case DISBURSEMENT: - optionData = new EnumOptionData(ChargeTimeType.DISBURSEMENT.getValue().longValue(), ChargeTimeType.DISBURSEMENT.getCode(), "Disbursement"); - break; + optionData = new EnumOptionData(ChargeTimeType.DISBURSEMENT.getValue().longValue(), ChargeTimeType.DISBURSEMENT.getCode(), + "Disbursement"); + break; case SPECIFIED_DUE_DATE: - optionData = new EnumOptionData(ChargeTimeType.SPECIFIED_DUE_DATE.getValue().longValue(), ChargeTimeType.SPECIFIED_DUE_DATE.getCode(), "Specified due date"); - break; + optionData = new EnumOptionData(ChargeTimeType.SPECIFIED_DUE_DATE.getValue().longValue(), + ChargeTimeType.SPECIFIED_DUE_DATE.getCode(), "Specified due date"); + break; default: optionData = new EnumOptionData(ChargeTimeType.INVALID.getValue().longValue(), ChargeTimeType.INVALID.getCode(), "Invalid"); - break; + break; } return optionData; } - public static EnumOptionData chargeAppliesTo(final int id){ + public static EnumOptionData chargeAppliesTo(final int id) { return chargeAppliesTo(ChargeAppliesTo.fromInt(id)); } - public static EnumOptionData chargeAppliesTo(final ChargeAppliesTo type){ + public static EnumOptionData chargeAppliesTo(final ChargeAppliesTo type) { EnumOptionData optionData = null; - switch (type){ + switch (type) { case LOAN: optionData = new EnumOptionData(ChargeAppliesTo.LOAN.getValue().longValue(), ChargeAppliesTo.LOAN.getCode(), "Loan"); - break; + break; default: - optionData = new EnumOptionData(ChargeAppliesTo.INVALID.getValue().longValue(), ChargeAppliesTo.INVALID.getCode(), "Invalid"); - break; + optionData = new EnumOptionData(ChargeAppliesTo.INVALID.getValue().longValue(), ChargeAppliesTo.INVALID.getCode(), + "Invalid"); + break; } return optionData; } - public static EnumOptionData chargeCalculationType(final int id){ + public static EnumOptionData chargeCalculationType(final int id) { return chargeCalculationType(ChargeCalculationType.fromInt(id)); } - public static EnumOptionData chargeCalculationType(final ChargeCalculationType type){ + public static EnumOptionData chargeCalculationType(final ChargeCalculationType type) { EnumOptionData optionData = null; - switch (type){ + switch (type) { case FLAT: - optionData = new EnumOptionData(ChargeCalculationType.FLAT.getValue().longValue(), ChargeCalculationType.FLAT.getCode(), "Flat"); - break; + optionData = new EnumOptionData(ChargeCalculationType.FLAT.getValue().longValue(), ChargeCalculationType.FLAT.getCode(), + "Flat"); + break; case PERCENT_OF_AMOUNT: - optionData = new EnumOptionData(ChargeCalculationType.PERCENT_OF_AMOUNT.getValue().longValue(), ChargeCalculationType.PERCENT_OF_AMOUNT.getCode(), "% Amount"); - break; + optionData = new EnumOptionData(ChargeCalculationType.PERCENT_OF_AMOUNT.getValue().longValue(), + ChargeCalculationType.PERCENT_OF_AMOUNT.getCode(), "% Amount"); + break; case PERCENT_OF_AMOUNT_AND_INTEREST: - optionData = new EnumOptionData(ChargeCalculationType.PERCENT_OF_AMOUNT_AND_INTEREST.getValue().longValue(), ChargeCalculationType.PERCENT_OF_AMOUNT_AND_INTEREST.getCode(), "% Loan Amount + Interest"); - break; + optionData = new EnumOptionData(ChargeCalculationType.PERCENT_OF_AMOUNT_AND_INTEREST.getValue().longValue(), + ChargeCalculationType.PERCENT_OF_AMOUNT_AND_INTEREST.getCode(), "% Loan Amount + Interest"); + break; case PERCENT_OF_INTEREST: - optionData = new EnumOptionData(ChargeCalculationType.PERCENT_OF_INTEREST.getValue().longValue(), ChargeCalculationType.PERCENT_OF_INTEREST.getCode(), "% Interest"); - break; + optionData = new EnumOptionData(ChargeCalculationType.PERCENT_OF_INTEREST.getValue().longValue(), + ChargeCalculationType.PERCENT_OF_INTEREST.getCode(), "% Interest"); + break; default: - optionData = new EnumOptionData(ChargeCalculationType.INVALID.getValue().longValue(), ChargeCalculationType.INVALID.getCode(), "Invalid"); - break; + optionData = new EnumOptionData(ChargeCalculationType.INVALID.getValue().longValue(), + ChargeCalculationType.INVALID.getCode(), "Invalid"); + break; } return optionData; } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/service/ChargeWritePlatformService.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/service/ChargeWritePlatformService.java index 786bd1091..c8787727b 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/service/ChargeWritePlatformService.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/service/ChargeWritePlatformService.java @@ -1,16 +1,12 @@ package org.mifosplatform.portfolio.charge.service; -import org.mifosplatform.portfolio.charge.command.ChargeCommand; -import org.springframework.security.access.prepost.PreAuthorize; +import org.mifosplatform.portfolio.charge.command.ChargeDefinitionCommand; public interface ChargeWritePlatformService { - @PreAuthorize(value = "hasAnyRole('ALL_FUNCTIONS', 'ORGANISATION_ADMINISTRATION_SUPER_USER', 'CREATE_CHARGE')") - Long createCharge(final ChargeCommand command); + Long createCharge(ChargeDefinitionCommand command); - @PreAuthorize(value = "hasAnyRole('ALL_FUNCTIONS', 'ORGANISATION_ADMINISTRATION_SUPER_USER', 'UPDATE_CHARGE')") - Long updateCharge(final ChargeCommand command); + Long updateCharge(ChargeDefinitionCommand command); - @PreAuthorize(value = "hasAnyRole('ALL_FUNCTIONS', 'ORGANISATION_ADMINISTRATION_SUPER_USER', 'DELETE_CHARGE')") - Long deleteCharge(final Long chargeId); + Long deleteCharge(ChargeDefinitionCommand command); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/service/ChargeWritePlatformServiceJpaRepositoryImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/service/ChargeWritePlatformServiceJpaRepositoryImpl.java index d6ac6240f..fd3f26342 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/service/ChargeWritePlatformServiceJpaRepositoryImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/service/ChargeWritePlatformServiceJpaRepositoryImpl.java @@ -1,10 +1,11 @@ package org.mifosplatform.portfolio.charge.service; +import org.mifosng.platform.client.service.RollbackTransactionAsCommandIsNotApprovedByCheckerException; import org.mifosng.platform.exceptions.ChargeNotFoundException; import org.mifosng.platform.exceptions.PlatformDataIntegrityException; +import org.mifosplatform.infrastructure.configuration.service.ConfigurationDomainService; import org.mifosplatform.infrastructure.security.service.PlatformSecurityContext; -import org.mifosplatform.portfolio.charge.command.ChargeCommand; -import org.mifosplatform.portfolio.charge.command.ChargeCommandValidator; +import org.mifosplatform.portfolio.charge.command.ChargeDefinitionCommand; import org.mifosplatform.portfolio.charge.domain.Charge; import org.mifosplatform.portfolio.charge.domain.ChargeAppliesTo; import org.mifosplatform.portfolio.charge.domain.ChargeCalculationType; @@ -24,21 +25,21 @@ public class ChargeWritePlatformServiceJpaRepositoryImpl implements ChargeWriteP private final PlatformSecurityContext context; private final ChargeRepository chargeRepository; + private final ConfigurationDomainService configurationDomainService; @Autowired - public ChargeWritePlatformServiceJpaRepositoryImpl(final PlatformSecurityContext context, final ChargeRepository chargeRepository) { + public ChargeWritePlatformServiceJpaRepositoryImpl(final PlatformSecurityContext context, final ChargeRepository chargeRepository, final ConfigurationDomainService configurationDomainService) { this.context = context; this.chargeRepository = chargeRepository; + this.configurationDomainService = configurationDomainService; } @Transactional @Override - public Long createCharge(final ChargeCommand command) { + public Long createCharge(final ChargeDefinitionCommand command) { try { this.context.authenticatedUser(); - - final ChargeCommandValidator validator = new ChargeCommandValidator(command); - validator.validateForCreate(); + command.validateForCreate(); final ChargeAppliesTo chargeAppliesTo = ChargeAppliesTo.fromInt(command.getChargeAppliesTo()); final ChargeTimeType chargeTimeType = ChargeTimeType.fromInt(command.getChargeTimeType()); @@ -47,8 +48,10 @@ public class ChargeWritePlatformServiceJpaRepositoryImpl implements ChargeWriteP final Charge charge = Charge.createNew(command.getName(), command.getAmount(), command.getCurrencyCode(), chargeAppliesTo, chargeTimeType, chargeCalculationType, command.isPenalty(), command.isActive()); - this.chargeRepository.saveAndFlush(charge); + this.chargeRepository.save(charge); + if (this.configurationDomainService.isMakerCheckerEnabledForTask("CREATE_CHARGE") && !command.isApprovedByChecker()) { throw new RollbackTransactionAsCommandIsNotApprovedByCheckerException(); } + return charge.getId(); } catch (DataIntegrityViolationException dve) { handleDataIntegrityIssues(command, dve); @@ -58,22 +61,22 @@ public class ChargeWritePlatformServiceJpaRepositoryImpl implements ChargeWriteP @Transactional @Override - public Long updateCharge(final ChargeCommand command) { + public Long updateCharge(final ChargeDefinitionCommand command) { try { - this.context.authenticatedUser(); - ChargeCommandValidator validator = new ChargeCommandValidator(command); - validator.validateForUpdate(); + command.validateForUpdate(); final Long chargeId = command.getId(); final Charge chargeForUpdate = this.chargeRepository.findOne(chargeId); - if (chargeForUpdate == null) { throw new ChargeNotFoundException(chargeId); } + chargeForUpdate.update(command); - this.chargeRepository.saveAndFlush(chargeForUpdate); + this.chargeRepository.save(chargeForUpdate); + if (this.configurationDomainService.isMakerCheckerEnabledForTask("UPDATE_CHARGE") && !command.isApprovedByChecker()) { throw new RollbackTransactionAsCommandIsNotApprovedByCheckerException(); } + return chargeForUpdate.getId(); } catch (DataIntegrityViolationException dve) { handleDataIntegrityIssues(command, dve); @@ -83,16 +86,20 @@ public class ChargeWritePlatformServiceJpaRepositoryImpl implements ChargeWriteP @Transactional @Override - public Long deleteCharge(Long chargeId) { + public Long deleteCharge(final ChargeDefinitionCommand command) { this.context.authenticatedUser(); + final Long chargeId = command.getId(); final Charge chargeForDelete = this.chargeRepository.findOne(chargeId); if (chargeForDelete == null || chargeForDelete.isDeleted()) { throw new ChargeNotFoundException(chargeId); } + chargeForDelete.delete(); - chargeRepository.saveAndFlush(chargeForDelete); + chargeRepository.save(chargeForDelete); + if (this.configurationDomainService.isMakerCheckerEnabledForTask("DELETE_CHARGE") && !command.isApprovedByChecker()) { throw new RollbackTransactionAsCommandIsNotApprovedByCheckerException(); } + return chargeForDelete.getId(); } @@ -100,7 +107,7 @@ public class ChargeWritePlatformServiceJpaRepositoryImpl implements ChargeWriteP * Guaranteed to throw an exception no matter what the data integrity issue * is. */ - private void handleDataIntegrityIssues(final ChargeCommand command, final DataIntegrityViolationException dve) { + private void handleDataIntegrityIssues(final ChargeDefinitionCommand command, final DataIntegrityViolationException dve) { Throwable realCause = dve.getMostSpecificCause(); if (realCause.getMessage().contains("name")) { throw new PlatformDataIntegrityException("error.msg.charge.duplicate.name", diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/fund/service/FundWritePlatformServiceJpaRepositoryImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/fund/service/FundWritePlatformServiceJpaRepositoryImpl.java index a65c4dfc4..5233e333c 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/fund/service/FundWritePlatformServiceJpaRepositoryImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/fund/service/FundWritePlatformServiceJpaRepositoryImpl.java @@ -3,9 +3,8 @@ package org.mifosplatform.portfolio.fund.service; import org.mifosng.platform.client.service.RollbackTransactionAsCommandIsNotApprovedByCheckerException; import org.mifosng.platform.exceptions.FundNotFoundException; import org.mifosng.platform.exceptions.PlatformDataIntegrityException; +import org.mifosplatform.infrastructure.configuration.service.ConfigurationDomainService; import org.mifosplatform.infrastructure.security.service.PlatformSecurityContext; -import org.mifosplatform.infrastructure.user.domain.Permission; -import org.mifosplatform.infrastructure.user.domain.PermissionRepository; import org.mifosplatform.portfolio.fund.command.FundCommand; import org.mifosplatform.portfolio.fund.domain.Fund; import org.mifosplatform.portfolio.fund.domain.FundRepository; @@ -23,15 +22,14 @@ public class FundWritePlatformServiceJpaRepositoryImpl implements FundWritePlatf private final PlatformSecurityContext context; private final FundRepository fundRepository; - - private final PermissionRepository permissionRepository; + private final ConfigurationDomainService configurationDomainService; @Autowired public FundWritePlatformServiceJpaRepositoryImpl(final PlatformSecurityContext context, final FundRepository fundRepository, - final PermissionRepository permissionRepository) { + final ConfigurationDomainService configurationDomainService) { this.context = context; this.fundRepository = fundRepository; - this.permissionRepository = permissionRepository; + this.configurationDomainService = configurationDomainService; } @Transactional @@ -46,8 +44,7 @@ public class FundWritePlatformServiceJpaRepositoryImpl implements FundWritePlatf this.fundRepository.save(fund); - final Permission thisTask = this.permissionRepository.findOneByCode("CREATE_FUND"); - if (thisTask.hasMakerCheckerEnabled() && !command.isApprovedByChecker()) { throw new RollbackTransactionAsCommandIsNotApprovedByCheckerException(); } + if (this.configurationDomainService.isMakerCheckerEnabledForTask("CREATE_FUND") && !command.isApprovedByChecker()) { throw new RollbackTransactionAsCommandIsNotApprovedByCheckerException(); } return fund.getId(); } catch (DataIntegrityViolationException dve) { @@ -71,9 +68,8 @@ public class FundWritePlatformServiceJpaRepositoryImpl implements FundWritePlatf this.fundRepository.save(fund); - final Permission thisTask = this.permissionRepository.findOneByCode("UPDATE_FUND"); - if (thisTask.hasMakerCheckerEnabled() && !command.isApprovedByChecker()) { throw new RollbackTransactionAsCommandIsNotApprovedByCheckerException(); } - + if (this.configurationDomainService.isMakerCheckerEnabledForTask("UPDATE_FUND") && !command.isApprovedByChecker()) { throw new RollbackTransactionAsCommandIsNotApprovedByCheckerException(); } + return fund.getId(); } catch (DataIntegrityViolationException dve) { handleFundDataIntegrityIssues(command, dve); @@ -92,8 +88,7 @@ public class FundWritePlatformServiceJpaRepositoryImpl implements FundWritePlatf throw new PlatformDataIntegrityException("error.msg.fund.duplicate.externalId", "A fund with external id '" + command.getExternalId() + "' already exists", "externalId", command.getExternalId()); } else if (realCause.getMessage().contains("fund_name_org")) { throw new PlatformDataIntegrityException( - "error.msg.fund.duplicate.name", "A fund with name '" + command.getName() + "' already exists", "name", - command.getName()); } + "error.msg.fund.duplicate.name", "A fund with name '" + command.getName() + "' already exists", "name", command.getName()); } logger.error(dve.getMessage(), dve); throw new PlatformDataIntegrityException("error.msg.fund.unknown.data.integrity.issue", diff --git a/mifosng-provider/src/main/resources/META-INF/spring/appContext.xml b/mifosng-provider/src/main/resources/META-INF/spring/appContext.xml index 54056b0f3..6d3b2a4a9 100644 --- a/mifosng-provider/src/main/resources/META-INF/spring/appContext.xml +++ b/mifosng-provider/src/main/resources/META-INF/spring/appContext.xml @@ -17,7 +17,7 @@ + org.mifosplatform.*.*.service, org.mifosplatform.*.*.domain, org.mifosplatform, org.mifosplatform.commands, org.mifosplatform.infrastructure.*.service">