FINERACT-1782: Improve code quality - Member of Spring components should be injected
This commit is contained in:
committed by
Arnold Gálovics
parent
f3aeef2f45
commit
f496e2ff0e
+46
-39
@@ -40,11 +40,18 @@ import org.springframework.stereotype.Component;
|
|||||||
@Component
|
@Component
|
||||||
public final class AdHocDataValidator {
|
public final class AdHocDataValidator {
|
||||||
|
|
||||||
|
public static final String NAME = "name";
|
||||||
|
public static final String QUERY = "query";
|
||||||
|
public static final String TABLE_NAME = "tableName";
|
||||||
|
public static final String TABLE_FIELDS = "tableFields";
|
||||||
|
public static final String EMAIL = "email";
|
||||||
|
public static final String REPORT_RUN_FREQUENCY = "reportRunFrequency";
|
||||||
|
public static final String REPORT_RUN_EVERY = "reportRunEvery";
|
||||||
/**
|
/**
|
||||||
* The parameters supported for this command.
|
* The parameters supported for this command.
|
||||||
*/
|
*/
|
||||||
private final Set<String> supportedParameters = new HashSet<>(
|
private static final Set<String> supportedParameters = new HashSet<>(
|
||||||
Arrays.asList("name", "query", "tableName", "tableFields", "email", "isActive", "reportRunFrequency", "reportRunEvery"));
|
Arrays.asList(NAME, QUERY, TABLE_NAME, TABLE_FIELDS, EMAIL, "isActive", REPORT_RUN_FREQUENCY, REPORT_RUN_EVERY));
|
||||||
|
|
||||||
private final FromJsonHelper fromApiJsonHelper;
|
private final FromJsonHelper fromApiJsonHelper;
|
||||||
|
|
||||||
@@ -59,37 +66,37 @@ public final class AdHocDataValidator {
|
|||||||
}
|
}
|
||||||
|
|
||||||
final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType();
|
final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType();
|
||||||
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParameters);
|
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, supportedParameters);
|
||||||
|
|
||||||
final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
|
final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
|
||||||
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("adhoc");
|
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("adhoc");
|
||||||
|
|
||||||
final JsonElement element = this.fromApiJsonHelper.parse(json);
|
final JsonElement element = this.fromApiJsonHelper.parse(json);
|
||||||
|
|
||||||
final String name = this.fromApiJsonHelper.extractStringNamed("name", element);
|
final String name = this.fromApiJsonHelper.extractStringNamed(NAME, element);
|
||||||
baseDataValidator.reset().parameter("name").value(name).notBlank().notExceedingLengthOf(100);
|
baseDataValidator.reset().parameter(NAME).value(name).notBlank().notExceedingLengthOf(100);
|
||||||
|
|
||||||
final String description = this.fromApiJsonHelper.extractStringNamed("query", element);
|
final String description = this.fromApiJsonHelper.extractStringNamed(QUERY, element);
|
||||||
baseDataValidator.reset().parameter("query").value(description).notBlank().notExceedingLengthOf(2000);
|
baseDataValidator.reset().parameter(QUERY).value(description).notBlank().notExceedingLengthOf(2000);
|
||||||
|
|
||||||
final String tableName = this.fromApiJsonHelper.extractStringNamed("tableName", element);
|
final String tableName = this.fromApiJsonHelper.extractStringNamed(TABLE_NAME, element);
|
||||||
baseDataValidator.reset().parameter("tableName").value(tableName).notBlank().notExceedingLengthOf(100);
|
baseDataValidator.reset().parameter(TABLE_NAME).value(tableName).notBlank().notExceedingLengthOf(100);
|
||||||
|
|
||||||
final String tableFields = this.fromApiJsonHelper.extractStringNamed("tableFields", element);
|
final String tableFields = this.fromApiJsonHelper.extractStringNamed(TABLE_FIELDS, element);
|
||||||
baseDataValidator.reset().parameter("tableFields").value(tableFields).notBlank().notExceedingLengthOf(1000);
|
baseDataValidator.reset().parameter(TABLE_FIELDS).value(tableFields).notBlank().notExceedingLengthOf(1000);
|
||||||
|
|
||||||
final String email = this.fromApiJsonHelper.extractStringNamed("email", element);
|
final String email = this.fromApiJsonHelper.extractStringNamed(EMAIL, element);
|
||||||
baseDataValidator.reset().parameter("email").value(email).ignoreIfNull().notExceedingLengthOf(500);
|
baseDataValidator.reset().parameter(EMAIL).value(email).ignoreIfNull().notExceedingLengthOf(500);
|
||||||
|
|
||||||
final Long reportRunFrequencyCode = this.fromApiJsonHelper.extractLongNamed("reportRunFrequency", element);
|
final Long reportRunFrequencyCode = this.fromApiJsonHelper.extractLongNamed(REPORT_RUN_FREQUENCY, element);
|
||||||
if (reportRunFrequencyCode != null) {
|
if (reportRunFrequencyCode != null) {
|
||||||
baseDataValidator.reset().parameter("reportRunFrequency").value(reportRunFrequencyCode)
|
baseDataValidator.reset().parameter(REPORT_RUN_FREQUENCY).value(reportRunFrequencyCode)
|
||||||
.inMinMaxRange((int) ReportRunFrequency.DAILY.getValue(), (int) ReportRunFrequency.CUSTOM.getValue());
|
.inMinMaxRange((int) ReportRunFrequency.DAILY.getValue(), (int) ReportRunFrequency.CUSTOM.getValue());
|
||||||
}
|
}
|
||||||
|
|
||||||
final Long reportRunEvery = this.fromApiJsonHelper.extractLongNamed("reportRunEvery", element);
|
final Long reportRunEvery = this.fromApiJsonHelper.extractLongNamed(REPORT_RUN_EVERY, element);
|
||||||
if (reportRunEvery != null) {
|
if (reportRunEvery != null) {
|
||||||
baseDataValidator.reset().parameter("reportRunEvery").value(reportRunFrequencyCode).integerGreaterThanZero();
|
baseDataValidator.reset().parameter(REPORT_RUN_EVERY).value(reportRunFrequencyCode).integerGreaterThanZero();
|
||||||
}
|
}
|
||||||
|
|
||||||
throwExceptionIfValidationWarningsExist(dataValidationErrors);
|
throwExceptionIfValidationWarningsExist(dataValidationErrors);
|
||||||
@@ -101,42 +108,42 @@ public final class AdHocDataValidator {
|
|||||||
}
|
}
|
||||||
|
|
||||||
final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType();
|
final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType();
|
||||||
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParameters);
|
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, supportedParameters);
|
||||||
|
|
||||||
final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
|
final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
|
||||||
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("adhoc");
|
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("adhoc");
|
||||||
|
|
||||||
final JsonElement element = this.fromApiJsonHelper.parse(json);
|
final JsonElement element = this.fromApiJsonHelper.parse(json);
|
||||||
|
|
||||||
if (this.fromApiJsonHelper.parameterExists("name", element)) {
|
if (this.fromApiJsonHelper.parameterExists(NAME, element)) {
|
||||||
final String name = this.fromApiJsonHelper.extractStringNamed("name", element);
|
final String name = this.fromApiJsonHelper.extractStringNamed(NAME, element);
|
||||||
baseDataValidator.reset().parameter("name").value(name).notBlank().notExceedingLengthOf(100);
|
baseDataValidator.reset().parameter(NAME).value(name).notBlank().notExceedingLengthOf(100);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (this.fromApiJsonHelper.parameterExists("query", element)) {
|
if (this.fromApiJsonHelper.parameterExists(QUERY, element)) {
|
||||||
final String query = this.fromApiJsonHelper.extractStringNamed("query", element);
|
final String query = this.fromApiJsonHelper.extractStringNamed(QUERY, element);
|
||||||
baseDataValidator.reset().parameter("query").value(query).notBlank().notExceedingLengthOf(2000);
|
baseDataValidator.reset().parameter(QUERY).value(query).notBlank().notExceedingLengthOf(2000);
|
||||||
}
|
}
|
||||||
if (this.fromApiJsonHelper.parameterExists("tableName", element)) {
|
if (this.fromApiJsonHelper.parameterExists(TABLE_NAME, element)) {
|
||||||
final String tableName = this.fromApiJsonHelper.extractStringNamed("tableName", element);
|
final String tableName = this.fromApiJsonHelper.extractStringNamed(TABLE_NAME, element);
|
||||||
baseDataValidator.reset().parameter("tableName").value(tableName).notBlank().notExceedingLengthOf(100);
|
baseDataValidator.reset().parameter(TABLE_NAME).value(tableName).notBlank().notExceedingLengthOf(100);
|
||||||
}
|
}
|
||||||
if (this.fromApiJsonHelper.parameterExists("tableFields", element)) {
|
if (this.fromApiJsonHelper.parameterExists(TABLE_FIELDS, element)) {
|
||||||
final String tableField = this.fromApiJsonHelper.extractStringNamed("tableFields", element);
|
final String tableField = this.fromApiJsonHelper.extractStringNamed(TABLE_FIELDS, element);
|
||||||
baseDataValidator.reset().parameter("tableFields").value(tableField).notBlank().notExceedingLengthOf(2000);
|
baseDataValidator.reset().parameter(TABLE_FIELDS).value(tableField).notBlank().notExceedingLengthOf(2000);
|
||||||
}
|
}
|
||||||
if (this.fromApiJsonHelper.parameterExists("email", element)) {
|
if (this.fromApiJsonHelper.parameterExists(EMAIL, element)) {
|
||||||
final String email = this.fromApiJsonHelper.extractStringNamed("email", element);
|
final String email = this.fromApiJsonHelper.extractStringNamed(EMAIL, element);
|
||||||
baseDataValidator.reset().parameter("email").value(email).ignoreIfNull().notExceedingLengthOf(500);
|
baseDataValidator.reset().parameter(EMAIL).value(email).ignoreIfNull().notExceedingLengthOf(500);
|
||||||
}
|
}
|
||||||
if (this.fromApiJsonHelper.parameterExists("reportRunFrequency", element)) {
|
if (this.fromApiJsonHelper.parameterExists(REPORT_RUN_FREQUENCY, element)) {
|
||||||
final Long reportRunFrequencyCode = this.fromApiJsonHelper.extractLongNamed("reportRunFrequency", element);
|
final Long reportRunFrequencyCode = this.fromApiJsonHelper.extractLongNamed(REPORT_RUN_FREQUENCY, element);
|
||||||
baseDataValidator.reset().parameter("reportRunFrequency").value(reportRunFrequencyCode)
|
baseDataValidator.reset().parameter(REPORT_RUN_FREQUENCY).value(reportRunFrequencyCode)
|
||||||
.inMinMaxRange((int) ReportRunFrequency.DAILY.getValue(), (int) ReportRunFrequency.CUSTOM.getValue());
|
.inMinMaxRange((int) ReportRunFrequency.DAILY.getValue(), (int) ReportRunFrequency.CUSTOM.getValue());
|
||||||
}
|
}
|
||||||
if (this.fromApiJsonHelper.parameterExists("reportRunEvery", element)) {
|
if (this.fromApiJsonHelper.parameterExists(REPORT_RUN_EVERY, element)) {
|
||||||
final Long reportRunEvery = this.fromApiJsonHelper.extractLongNamed("reportRunEvery", element);
|
final Long reportRunEvery = this.fromApiJsonHelper.extractLongNamed(REPORT_RUN_EVERY, element);
|
||||||
baseDataValidator.reset().parameter("reportRunEvery").value(reportRunEvery).integerGreaterThanZero();
|
baseDataValidator.reset().parameter(REPORT_RUN_EVERY).value(reportRunEvery).integerGreaterThanZero();
|
||||||
}
|
}
|
||||||
/*
|
/*
|
||||||
* if (this.fromApiJsonHelper.parameterExists("isActive", element)) { final Integer isActive =
|
* if (this.fromApiJsonHelper.parameterExists("isActive", element)) { final Integer isActive =
|
||||||
|
|||||||
+35
-37
@@ -35,8 +35,9 @@ import org.springframework.stereotype.Component;
|
|||||||
@Component
|
@Component
|
||||||
public class CommandStrategyProvider {
|
public class CommandStrategyProvider {
|
||||||
|
|
||||||
|
public static final String CREATE_TRANSACTION_LOAN_COMMAND_STRATEGY = "createTransactionLoanCommandStrategy";
|
||||||
private final ApplicationContext applicationContext;
|
private final ApplicationContext applicationContext;
|
||||||
private final Map<CommandContext, String> commandStrategies = new ConcurrentHashMap<>();
|
private static final Map<CommandContext, String> commandStrategies = new ConcurrentHashMap<>();
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Constructs a CommandStrategyProvider with argument of ApplicationContext type. It also initialize
|
* Constructs a CommandStrategyProvider with argument of ApplicationContext type. It also initialize
|
||||||
@@ -63,13 +64,13 @@ public class CommandStrategyProvider {
|
|||||||
*/
|
*/
|
||||||
public CommandStrategy getCommandStrategy(final CommandContext commandContext) {
|
public CommandStrategy getCommandStrategy(final CommandContext commandContext) {
|
||||||
|
|
||||||
if (this.commandStrategies.containsKey(commandContext)) {
|
if (commandStrategies.containsKey(commandContext)) {
|
||||||
return (CommandStrategy) this.applicationContext.getBean(this.commandStrategies.get(commandContext));
|
return (CommandStrategy) this.applicationContext.getBean(commandStrategies.get(commandContext));
|
||||||
}
|
}
|
||||||
|
|
||||||
for (Map.Entry<CommandContext, String> entry : this.commandStrategies.entrySet()) {
|
for (Map.Entry<CommandContext, String> entry : commandStrategies.entrySet()) {
|
||||||
if (commandContext.matcher(entry.getKey())) {
|
if (commandContext.matcher(entry.getKey())) {
|
||||||
return (CommandStrategy) this.applicationContext.getBean(this.commandStrategies.get(entry.getKey()));
|
return (CommandStrategy) applicationContext.getBean(commandStrategies.get(entry.getKey()));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -80,48 +81,45 @@ public class CommandStrategyProvider {
|
|||||||
* Contains various available command strategies in {@link org.apache.fineract.batch.command.internal}. Any new
|
* Contains various available command strategies in {@link org.apache.fineract.batch.command.internal}. Any new
|
||||||
* command Strategy will have to be added within this function in order to initiate it within the constructor.
|
* command Strategy will have to be added within this function in order to initiate it within the constructor.
|
||||||
*/
|
*/
|
||||||
private void init() {
|
private static void init() {
|
||||||
this.commandStrategies.put(CommandContext.resource("clients").method("POST").build(), "createClientCommandStrategy");
|
commandStrategies.put(CommandContext.resource("clients").method("POST").build(), "createClientCommandStrategy");
|
||||||
this.commandStrategies.put(CommandContext.resource("clients\\/\\d+").method("PUT").build(), "updateClientCommandStrategy");
|
commandStrategies.put(CommandContext.resource("clients\\/\\d+").method("PUT").build(), "updateClientCommandStrategy");
|
||||||
this.commandStrategies.put(CommandContext.resource("loans").method("POST").build(), "applyLoanCommandStrategy");
|
commandStrategies.put(CommandContext.resource("loans").method("POST").build(), "applyLoanCommandStrategy");
|
||||||
this.commandStrategies.put(CommandContext.resource("loans\\/\\d+").method("GET").build(), "getLoanByIdCommandStrategy");
|
commandStrategies.put(CommandContext.resource("loans\\/\\d+").method("GET").build(), "getLoanByIdCommandStrategy");
|
||||||
this.commandStrategies.put(CommandContext.resource("loans/\\d+(\\?(\\w+(?:\\=[\\w,]+|&)+)+)").method("GET").build(),
|
commandStrategies.put(CommandContext.resource("loans/\\d+(\\?(\\w+(?:\\=[\\w,]+|&)+)+)").method("GET").build(),
|
||||||
"getLoanByIdCommandStrategy");
|
"getLoanByIdCommandStrategy");
|
||||||
this.commandStrategies.put(CommandContext.resource("savingsaccounts").method("POST").build(), "applySavingsCommandStrategy");
|
commandStrategies.put(CommandContext.resource("savingsaccounts").method("POST").build(), "applySavingsCommandStrategy");
|
||||||
this.commandStrategies.put(CommandContext.resource("loans\\/\\d+\\/charges").method("POST").build(), "createChargeCommandStrategy");
|
commandStrategies.put(CommandContext.resource("loans\\/\\d+\\/charges").method("POST").build(), "createChargeCommandStrategy");
|
||||||
this.commandStrategies.put(CommandContext.resource("loans\\/\\d+\\/charges").method("GET").build(),
|
commandStrategies.put(CommandContext.resource("loans\\/\\d+\\/charges").method("GET").build(), "collectChargesCommandStrategy");
|
||||||
"collectChargesCommandStrategy");
|
commandStrategies.put(CommandContext.resource("loans\\/\\d+\\/charges\\/\\d+").method("GET").build(),
|
||||||
this.commandStrategies.put(CommandContext.resource("loans\\/\\d+\\/charges\\/\\d+").method("GET").build(),
|
|
||||||
"getChargeByIdCommandStrategy");
|
"getChargeByIdCommandStrategy");
|
||||||
this.commandStrategies.put(CommandContext.resource("loans\\/\\d+\\/transactions\\?command=repayment").method("POST").build(),
|
commandStrategies.put(CommandContext.resource("loans\\/\\d+\\/transactions\\?command=repayment").method("POST").build(),
|
||||||
"createTransactionLoanCommandStrategy");
|
CREATE_TRANSACTION_LOAN_COMMAND_STRATEGY);
|
||||||
this.commandStrategies.put(
|
commandStrategies.put(CommandContext.resource("loans\\/\\d+\\/transactions\\?command=creditBalanceRefund").method("POST").build(),
|
||||||
CommandContext.resource("loans\\/\\d+\\/transactions\\?command=creditBalanceRefund").method("POST").build(),
|
CREATE_TRANSACTION_LOAN_COMMAND_STRATEGY);
|
||||||
"createTransactionLoanCommandStrategy");
|
commandStrategies.put(CommandContext.resource("loans\\/\\d+\\/transactions\\?command=goodwillCredit").method("POST").build(),
|
||||||
this.commandStrategies.put(CommandContext.resource("loans\\/\\d+\\/transactions\\?command=goodwillCredit").method("POST").build(),
|
CREATE_TRANSACTION_LOAN_COMMAND_STRATEGY);
|
||||||
"createTransactionLoanCommandStrategy");
|
commandStrategies.put(CommandContext.resource("loans\\/\\d+\\/transactions\\?command=merchantIssuedRefund").method("POST").build(),
|
||||||
this.commandStrategies.put(
|
CREATE_TRANSACTION_LOAN_COMMAND_STRATEGY);
|
||||||
CommandContext.resource("loans\\/\\d+\\/transactions\\?command=merchantIssuedRefund").method("POST").build(),
|
commandStrategies.put(CommandContext.resource("loans\\/\\d+\\/transactions\\?command=payoutRefund").method("POST").build(),
|
||||||
"createTransactionLoanCommandStrategy");
|
CREATE_TRANSACTION_LOAN_COMMAND_STRATEGY);
|
||||||
this.commandStrategies.put(CommandContext.resource("loans\\/\\d+\\/transactions\\?command=payoutRefund").method("POST").build(),
|
commandStrategies.put(CommandContext.resource("loans\\/\\d+\\/transactions\\/\\d+").method("POST").build(),
|
||||||
"createTransactionLoanCommandStrategy");
|
|
||||||
this.commandStrategies.put(CommandContext.resource("loans\\/\\d+\\/transactions\\/\\d+").method("POST").build(),
|
|
||||||
"adjustTransactionCommandStrategy");
|
"adjustTransactionCommandStrategy");
|
||||||
this.commandStrategies.put(CommandContext.resource("clients\\/\\d+\\?command=activate").method("POST").build(),
|
commandStrategies.put(CommandContext.resource("clients\\/\\d+\\?command=activate").method("POST").build(),
|
||||||
"activateClientCommandStrategy");
|
"activateClientCommandStrategy");
|
||||||
this.commandStrategies.put(CommandContext.resource("loans\\/\\d+\\?command=approve").method("POST").build(),
|
commandStrategies.put(CommandContext.resource("loans\\/\\d+\\?command=approve").method("POST").build(),
|
||||||
"approveLoanCommandStrategy");
|
"approveLoanCommandStrategy");
|
||||||
this.commandStrategies.put(CommandContext.resource("loans\\/\\d+\\?command=disburse").method("POST").build(),
|
commandStrategies.put(CommandContext.resource("loans\\/\\d+\\?command=disburse").method("POST").build(),
|
||||||
"disburseLoanCommandStrategy");
|
"disburseLoanCommandStrategy");
|
||||||
this.commandStrategies.put(CommandContext.resource("rescheduleloans").method("POST").build(),
|
commandStrategies.put(CommandContext.resource("rescheduleloans").method("POST").build(),
|
||||||
"createLoanRescheduleRequestCommandStrategy");
|
"createLoanRescheduleRequestCommandStrategy");
|
||||||
this.commandStrategies.put(CommandContext.resource("rescheduleloans\\/\\d+\\?command=approve").method("POST").build(),
|
commandStrategies.put(CommandContext.resource("rescheduleloans\\/\\d+\\?command=approve").method("POST").build(),
|
||||||
"approveLoanRescheduleCommandStrategy");
|
"approveLoanRescheduleCommandStrategy");
|
||||||
this.commandStrategies.put(CommandContext.resource("loans\\/\\d+\\/transactions\\/\\d+").method("GET").build(),
|
commandStrategies.put(CommandContext.resource("loans\\/\\d+\\/transactions\\/\\d+").method("GET").build(),
|
||||||
"getTransactionByIdCommandStrategy");
|
"getTransactionByIdCommandStrategy");
|
||||||
this.commandStrategies.put(CommandContext.resource("datatables\\/[a-zA-Z0-9_]*\\/\\d+").method("GET").build(),
|
commandStrategies.put(CommandContext.resource("datatables\\/[a-zA-Z0-9_]*\\/\\d+").method("GET").build(),
|
||||||
"getDatatableEntryByAppTableIdCommandStrategy");
|
"getDatatableEntryByAppTableIdCommandStrategy");
|
||||||
this.commandStrategies.put(
|
commandStrategies.put(
|
||||||
CommandContext.resource("datatables\\/[a-zA-Z0-9_]*\\/\\d+(\\?(\\w+(?:\\=[\\w,]+|&)+)+)").method("GET").build(),
|
CommandContext.resource("datatables\\/[a-zA-Z0-9_]*\\/\\d+(\\?(\\w+(?:\\=[\\w,]+|&)+)+)").method("GET").build(),
|
||||||
"getDatatableEntryByAppTableIdCommandStrategy");
|
"getDatatableEntryByAppTableIdCommandStrategy");
|
||||||
}
|
}
|
||||||
|
|||||||
+1
-1
@@ -26,7 +26,7 @@ import org.springframework.stereotype.Service;
|
|||||||
@Service
|
@Service
|
||||||
public class BusinessStepCategoryServiceImpl implements BusinessStepCategoryService {
|
public class BusinessStepCategoryServiceImpl implements BusinessStepCategoryService {
|
||||||
|
|
||||||
private final Map<BusinessStepCategory, Class<? extends COBBusinessStep>> businessSteps = Map.of(BusinessStepCategory.LOAN,
|
private static final Map<BusinessStepCategory, Class<? extends COBBusinessStep>> businessSteps = Map.of(BusinessStepCategory.LOAN,
|
||||||
LoanCOBBusinessStep.class);
|
LoanCOBBusinessStep.class);
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
|
|||||||
+3
-3
@@ -49,7 +49,7 @@ import org.springframework.stereotype.Component;
|
|||||||
@Tag(name = "Bulk Import", description = "")
|
@Tag(name = "Bulk Import", description = "")
|
||||||
public class BulkImportApiResource {
|
public class BulkImportApiResource {
|
||||||
|
|
||||||
private final String resourceNameForPermissions = "IMPORT";
|
private static final String RESOURCE_NAME_FOR_PERMISSION = "IMPORT";
|
||||||
|
|
||||||
private final PlatformSecurityContext context;
|
private final PlatformSecurityContext context;
|
||||||
private final BulkImportWorkbookService bulkImportWorkbookService;
|
private final BulkImportWorkbookService bulkImportWorkbookService;
|
||||||
@@ -70,7 +70,7 @@ public class BulkImportApiResource {
|
|||||||
@Produces({ MediaType.APPLICATION_JSON })
|
@Produces({ MediaType.APPLICATION_JSON })
|
||||||
public String retrieveImportDocuments(@Context final UriInfo uriInfo, @QueryParam("entityType") final String entityType) {
|
public String retrieveImportDocuments(@Context final UriInfo uriInfo, @QueryParam("entityType") final String entityType) {
|
||||||
|
|
||||||
this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions);
|
this.context.authenticatedUser().validateHasReadPermission(RESOURCE_NAME_FOR_PERMISSION);
|
||||||
Collection<ImportData> importData = new ArrayList<>();
|
Collection<ImportData> importData = new ArrayList<>();
|
||||||
if (entityType.equals(GlobalEntityType.CLIENT.getCode())) {
|
if (entityType.equals(GlobalEntityType.CLIENT.getCode())) {
|
||||||
final Collection<ImportData> importForClientEntity = this.bulkImportWorkbookService.getImports(GlobalEntityType.CLIENTS_ENTTTY);
|
final Collection<ImportData> importForClientEntity = this.bulkImportWorkbookService.getImports(GlobalEntityType.CLIENTS_ENTTTY);
|
||||||
@@ -95,7 +95,7 @@ public class BulkImportApiResource {
|
|||||||
@GET
|
@GET
|
||||||
@Path("getOutputTemplateLocation")
|
@Path("getOutputTemplateLocation")
|
||||||
public String retriveOutputTemplateLocation(@QueryParam("importDocumentId") final String importDocumentId) {
|
public String retriveOutputTemplateLocation(@QueryParam("importDocumentId") final String importDocumentId) {
|
||||||
this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions);
|
this.context.authenticatedUser().validateHasReadPermission(RESOURCE_NAME_FOR_PERMISSION);
|
||||||
final DocumentData documentData = this.bulkImportWorkbookService.getOutputTemplateLocation(importDocumentId);
|
final DocumentData documentData = this.bulkImportWorkbookService.getOutputTemplateLocation(importDocumentId);
|
||||||
return this.toApiJsonSerializer.serialize(documentData.fileLocation());
|
return this.toApiJsonSerializer.serialize(documentData.fileLocation());
|
||||||
}
|
}
|
||||||
|
|||||||
+40
-38
@@ -25,6 +25,7 @@ import java.time.LocalDate;
|
|||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.Collection;
|
import java.util.Collection;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.Objects;
|
||||||
import org.apache.fineract.commands.domain.CommandWrapper;
|
import org.apache.fineract.commands.domain.CommandWrapper;
|
||||||
import org.apache.fineract.commands.service.CommandWrapperBuilder;
|
import org.apache.fineract.commands.service.CommandWrapperBuilder;
|
||||||
import org.apache.fineract.commands.service.IdempotencyKeyGenerator;
|
import org.apache.fineract.commands.service.IdempotencyKeyGenerator;
|
||||||
@@ -56,12 +57,8 @@ import org.springframework.stereotype.Service;
|
|||||||
@Service
|
@Service
|
||||||
public class CenterImportHandler implements ImportHandler {
|
public class CenterImportHandler implements ImportHandler {
|
||||||
|
|
||||||
|
public static final String EMPTY_STR = "";
|
||||||
private static final Logger LOG = LoggerFactory.getLogger(CenterImportHandler.class);
|
private static final Logger LOG = LoggerFactory.getLogger(CenterImportHandler.class);
|
||||||
private List<CenterData> centers;
|
|
||||||
private List<CalendarData> meetings;
|
|
||||||
private List<String> statuses;
|
|
||||||
private Workbook workbook;
|
|
||||||
|
|
||||||
private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService;
|
private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService;
|
||||||
private final IdempotencyKeyGenerator idempotencyKeyGenerator;
|
private final IdempotencyKeyGenerator idempotencyKeyGenerator;
|
||||||
|
|
||||||
@@ -73,16 +70,16 @@ public class CenterImportHandler implements ImportHandler {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Count process(Workbook workbook, String locale, String dateFormat) {
|
public Count process(final Workbook workbook, final String locale, final String dateFormat) {
|
||||||
this.centers = new ArrayList<>();
|
List<CenterData> centers = new ArrayList<>();
|
||||||
this.meetings = new ArrayList<>();
|
List<CalendarData> meetings = new ArrayList<>();
|
||||||
this.statuses = new ArrayList<>();
|
List<String> statuses = new ArrayList<>();
|
||||||
this.workbook = workbook;
|
readExcelFile(workbook, centers, meetings, statuses, locale, dateFormat);
|
||||||
readExcelFile(locale, dateFormat);
|
return importEntity(workbook, centers, meetings, statuses, dateFormat);
|
||||||
return importEntity(dateFormat);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public void readExcelFile(final String locale, final String dateFormat) {
|
private void readExcelFile(final Workbook workbook, final List<CenterData> centers, final List<CalendarData> meetings,
|
||||||
|
final List<String> statuses, final String locale, final String dateFormat) {
|
||||||
|
|
||||||
Sheet centersSheet = workbook.getSheet(TemplatePopulateImportConstants.CENTER_SHEET_NAME);
|
Sheet centersSheet = workbook.getSheet(TemplatePopulateImportConstants.CENTER_SHEET_NAME);
|
||||||
Integer noOfEntries = ImportHandlerUtils.getNumberOfRows(centersSheet, TemplatePopulateImportConstants.FIRST_COLUMN_INDEX);
|
Integer noOfEntries = ImportHandlerUtils.getNumberOfRows(centersSheet, TemplatePopulateImportConstants.FIRST_COLUMN_INDEX);
|
||||||
@@ -90,13 +87,13 @@ public class CenterImportHandler implements ImportHandler {
|
|||||||
Row row;
|
Row row;
|
||||||
row = centersSheet.getRow(rowIndex);
|
row = centersSheet.getRow(rowIndex);
|
||||||
if (ImportHandlerUtils.isNotImported(row, CenterConstants.STATUS_COL)) {
|
if (ImportHandlerUtils.isNotImported(row, CenterConstants.STATUS_COL)) {
|
||||||
centers.add(readCenter(row, locale, dateFormat));
|
centers.add(readCenter(workbook, statuses, row, locale, dateFormat));
|
||||||
meetings.add(readMeeting(row, locale, dateFormat));
|
meetings.add(readMeeting(row, locale, dateFormat));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private CalendarData readMeeting(Row row, final String locale, final String dateFormat) {
|
private CalendarData readMeeting(final Row row, final String locale, final String dateFormat) {
|
||||||
LocalDate meetingStartDate = ImportHandlerUtils.readAsDate(CenterConstants.MEETING_START_DATE_COL, row);
|
LocalDate meetingStartDate = ImportHandlerUtils.readAsDate(CenterConstants.MEETING_START_DATE_COL, row);
|
||||||
Boolean isRepeating = ImportHandlerUtils.readAsBoolean(CenterConstants.IS_REPEATING_COL, row);
|
Boolean isRepeating = ImportHandlerUtils.readAsBoolean(CenterConstants.IS_REPEATING_COL, row);
|
||||||
String frequency = ImportHandlerUtils.readAsString(CenterConstants.FREQUENCY_COL, row);
|
String frequency = ImportHandlerUtils.readAsString(CenterConstants.FREQUENCY_COL, row);
|
||||||
@@ -117,7 +114,8 @@ public class CenterImportHandler implements ImportHandler {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private CenterData readCenter(Row row, final String locale, final String dateFormat) {
|
private CenterData readCenter(final Workbook workbook, final List<String> statuses, final Row row, final String locale,
|
||||||
|
final String dateFormat) {
|
||||||
String status = ImportHandlerUtils.readAsString(CenterConstants.STATUS_COL, row);
|
String status = ImportHandlerUtils.readAsString(CenterConstants.STATUS_COL, row);
|
||||||
String officeName = ImportHandlerUtils.readAsString(CenterConstants.OFFICE_NAME_COL, row);
|
String officeName = ImportHandlerUtils.readAsString(CenterConstants.OFFICE_NAME_COL, row);
|
||||||
Long officeId = ImportHandlerUtils.getIdByName(workbook.getSheet(TemplatePopulateImportConstants.OFFICE_SHEET_NAME), officeName);
|
Long officeId = ImportHandlerUtils.getIdByName(workbook.getSheet(TemplatePopulateImportConstants.OFFICE_SHEET_NAME), officeName);
|
||||||
@@ -127,20 +125,20 @@ public class CenterImportHandler implements ImportHandler {
|
|||||||
String externalId = ImportHandlerUtils.readAsString(CenterConstants.EXTERNAL_ID_COL, row);
|
String externalId = ImportHandlerUtils.readAsString(CenterConstants.EXTERNAL_ID_COL, row);
|
||||||
Boolean active = ImportHandlerUtils.readAsBoolean(CenterConstants.ACTIVE_COL, row);
|
Boolean active = ImportHandlerUtils.readAsBoolean(CenterConstants.ACTIVE_COL, row);
|
||||||
LocalDate submittedOn = ImportHandlerUtils.readAsDate(CenterConstants.SUBMITTED_ON_DATE_COL, row);
|
LocalDate submittedOn = ImportHandlerUtils.readAsDate(CenterConstants.SUBMITTED_ON_DATE_COL, row);
|
||||||
LocalDate activationDate = null;
|
LocalDate activationDate;
|
||||||
if (active) {
|
if (Boolean.TRUE.equals(active)) {
|
||||||
activationDate = ImportHandlerUtils.readAsDate(CenterConstants.ACTIVATION_DATE_COL, row);
|
activationDate = ImportHandlerUtils.readAsDate(CenterConstants.ACTIVATION_DATE_COL, row);
|
||||||
} else {
|
} else {
|
||||||
activationDate = submittedOn;
|
activationDate = submittedOn;
|
||||||
}
|
}
|
||||||
String centerName = ImportHandlerUtils.readAsString(CenterConstants.CENTER_NAME_COL, row);
|
String centerName = ImportHandlerUtils.readAsString(CenterConstants.CENTER_NAME_COL, row);
|
||||||
if (centerName == null || centerName.equals("")) {
|
if (centerName == null || centerName.equals(EMPTY_STR)) {
|
||||||
throw new IllegalArgumentException("Name is blank");
|
throw new IllegalArgumentException("Name is blank");
|
||||||
}
|
}
|
||||||
List<GroupGeneralData> groupMembers = new ArrayList<GroupGeneralData>();
|
List<GroupGeneralData> groupMembers = new ArrayList<>();
|
||||||
for (int cellNo = CenterConstants.GROUP_NAMES_STARTING_COL; cellNo < CenterConstants.GROUP_NAMES_ENDING_COL; cellNo++) {
|
for (int cellNo = CenterConstants.GROUP_NAMES_STARTING_COL; cellNo < CenterConstants.GROUP_NAMES_ENDING_COL; cellNo++) {
|
||||||
String groupName = ImportHandlerUtils.readAsString(cellNo, row);
|
String groupName = ImportHandlerUtils.readAsString(cellNo, row);
|
||||||
if (groupName == null || groupName.equals("")) {
|
if (groupName == null || groupName.equals(EMPTY_STR)) {
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
Long groupId = ImportHandlerUtils.getIdByName(workbook.getSheet(TemplatePopulateImportConstants.GROUP_SHEET_NAME), groupName);
|
Long groupId = ImportHandlerUtils.getIdByName(workbook.getSheet(TemplatePopulateImportConstants.GROUP_SHEET_NAME), groupName);
|
||||||
@@ -164,13 +162,14 @@ public class CenterImportHandler implements ImportHandler {
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
public Count importEntity(String dateFormat) {
|
private Count importEntity(final Workbook workbook, final List<CenterData> centers, final List<CalendarData> meetings,
|
||||||
|
final List<String> statuses, final String dateFormat) {
|
||||||
Sheet centerSheet = workbook.getSheet(TemplatePopulateImportConstants.CENTER_SHEET_NAME);
|
Sheet centerSheet = workbook.getSheet(TemplatePopulateImportConstants.CENTER_SHEET_NAME);
|
||||||
int progressLevel = 0;
|
int progressLevel = 0;
|
||||||
String centerId = "";
|
String centerId = EMPTY_STR;
|
||||||
int successCount = 0;
|
int successCount = 0;
|
||||||
int errorCount = 0;
|
int errorCount = 0;
|
||||||
String errorMessage = "";
|
String errorMessage;
|
||||||
for (int i = 0; i < centers.size(); i++) {
|
for (int i = 0; i < centers.size(); i++) {
|
||||||
Row row = centerSheet.getRow(centers.get(i).getRowIndex());
|
Row row = centerSheet.getRow(centers.get(i).getRowIndex());
|
||||||
Cell errorReportCell = row.createCell(CenterConstants.FAILURE_COL);
|
Cell errorReportCell = row.createCell(CenterConstants.FAILURE_COL);
|
||||||
@@ -181,16 +180,17 @@ public class CenterImportHandler implements ImportHandler {
|
|||||||
progressLevel = getProgressLevel(status);
|
progressLevel = getProgressLevel(status);
|
||||||
|
|
||||||
if (progressLevel == 0) {
|
if (progressLevel == 0) {
|
||||||
result = importCenter(i, dateFormat);
|
result = importCenter(centers, i, dateFormat);
|
||||||
centerId = result.getGroupId().toString();
|
centerId = result.getGroupId().toString();
|
||||||
progressLevel = 1;
|
progressLevel = 1;
|
||||||
} else {
|
} else {
|
||||||
centerId = ImportHandlerUtils.readAsInt(CenterConstants.CENTER_ID_COL, centerSheet.getRow(centers.get(i).getRowIndex()))
|
centerId = Objects.requireNonNull(
|
||||||
|
ImportHandlerUtils.readAsInt(CenterConstants.CENTER_ID_COL, centerSheet.getRow(centers.get(i).getRowIndex())))
|
||||||
.toString();
|
.toString();
|
||||||
}
|
}
|
||||||
|
|
||||||
if (meetings.get(i) != null) {
|
if (meetings.get(i) != null) {
|
||||||
progressLevel = importCenterMeeting(result, i, dateFormat);
|
progressLevel = importCenterMeeting(meetings, Objects.requireNonNull(result), i, dateFormat);
|
||||||
}
|
}
|
||||||
successCount++;
|
successCount++;
|
||||||
statusCell.setCellValue(TemplatePopulateImportConstants.STATUS_CELL_IMPORTED);
|
statusCell.setCellValue(TemplatePopulateImportConstants.STATUS_CELL_IMPORTED);
|
||||||
@@ -199,16 +199,16 @@ public class CenterImportHandler implements ImportHandler {
|
|||||||
errorCount++;
|
errorCount++;
|
||||||
LOG.error("Runtime Exception occured in importEntity function", ex);
|
LOG.error("Runtime Exception occured in importEntity function", ex);
|
||||||
errorMessage = ImportHandlerUtils.getErrorMessage(ex);
|
errorMessage = ImportHandlerUtils.getErrorMessage(ex);
|
||||||
writeCenterErrorMessage(centerId, errorMessage, progressLevel, statusCell, errorReportCell, row);
|
writeCenterErrorMessage(workbook, centerId, errorMessage, progressLevel, statusCell, errorReportCell, row);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
setReportHeaders(centerSheet);
|
setReportHeaders(centerSheet);
|
||||||
return Count.instance(successCount, errorCount);
|
return Count.instance(successCount, errorCount);
|
||||||
}
|
}
|
||||||
|
|
||||||
private void writeCenterErrorMessage(String centerId, String errorMessage, int progressLevel, Cell statusCell, Cell errorReportCell,
|
private void writeCenterErrorMessage(final Workbook workbook, final String centerId, final String errorMessage, final int progressLevel,
|
||||||
Row row) {
|
final Cell statusCell, final Cell errorReportCell, final Row row) {
|
||||||
String status = "";
|
String status = EMPTY_STR;
|
||||||
if (progressLevel == 0) {
|
if (progressLevel == 0) {
|
||||||
status = TemplatePopulateImportConstants.STATUS_CREATION_FAILED;
|
status = TemplatePopulateImportConstants.STATUS_CREATION_FAILED;
|
||||||
} else if (progressLevel == 1) {
|
} else if (progressLevel == 1) {
|
||||||
@@ -233,21 +233,22 @@ public class CenterImportHandler implements ImportHandler {
|
|||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
private CommandProcessingResult importCenter(int rowIndex, String dateFormat) {
|
private CommandProcessingResult importCenter(final List<CenterData> centers, final int rowIndex, final String dateFormat) {
|
||||||
GsonBuilder gsonBuilder = GoogleGsonSerializerHelper.createGsonBuilder();
|
GsonBuilder gsonBuilder = GoogleGsonSerializerHelper.createGsonBuilder();
|
||||||
gsonBuilder.registerTypeAdapter(LocalDate.class, new DateSerializer(dateFormat));
|
gsonBuilder.registerTypeAdapter(LocalDate.class, new DateSerializer(dateFormat));
|
||||||
Type groupCollectionType = new TypeToken<Collection<GroupGeneralData>>() {}.getType();
|
Type groupCollectionType = new TypeToken<Collection<GroupGeneralData>>() {
|
||||||
|
|
||||||
|
}.getType();
|
||||||
gsonBuilder.registerTypeAdapter(groupCollectionType, new GroupIdSerializer());
|
gsonBuilder.registerTypeAdapter(groupCollectionType, new GroupIdSerializer());
|
||||||
String payload = gsonBuilder.create().toJson(centers.get(rowIndex));
|
String payload = gsonBuilder.create().toJson(centers.get(rowIndex));
|
||||||
final CommandWrapper commandRequest = new CommandWrapperBuilder() //
|
final CommandWrapper commandRequest = new CommandWrapperBuilder() //
|
||||||
.createCenter() //
|
.createCenter() //
|
||||||
.withJson(payload) //
|
.withJson(payload) //
|
||||||
.build(); //
|
.build(); //
|
||||||
final CommandProcessingResult result = commandsSourceWritePlatformService.logCommandSource(commandRequest);
|
return commandsSourceWritePlatformService.logCommandSource(commandRequest);
|
||||||
return result;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private void setReportHeaders(Sheet sheet) {
|
private void setReportHeaders(final Sheet sheet) {
|
||||||
ImportHandlerUtils.writeString(CenterConstants.STATUS_COL, sheet.getRow(0),
|
ImportHandlerUtils.writeString(CenterConstants.STATUS_COL, sheet.getRow(0),
|
||||||
TemplatePopulateImportConstants.STATUS_COL_REPORT_HEADER);
|
TemplatePopulateImportConstants.STATUS_COL_REPORT_HEADER);
|
||||||
ImportHandlerUtils.writeString(CenterConstants.CENTER_ID_COL, sheet.getRow(0),
|
ImportHandlerUtils.writeString(CenterConstants.CENTER_ID_COL, sheet.getRow(0),
|
||||||
@@ -256,7 +257,8 @@ public class CenterImportHandler implements ImportHandler {
|
|||||||
TemplatePopulateImportConstants.FAILURE_COL_REPORT_HEADER);
|
TemplatePopulateImportConstants.FAILURE_COL_REPORT_HEADER);
|
||||||
}
|
}
|
||||||
|
|
||||||
private Integer importCenterMeeting(CommandProcessingResult result, int rowIndex, String dateFormat) {
|
private Integer importCenterMeeting(final List<CalendarData> meetings, final CommandProcessingResult result, final int rowIndex,
|
||||||
|
final String dateFormat) {
|
||||||
CalendarData calendarData = meetings.get(rowIndex);
|
CalendarData calendarData = meetings.get(rowIndex);
|
||||||
calendarData.setTitle("centers_" + result.getGroupId().toString() + "_CollectionMeeting");
|
calendarData.setTitle("centers_" + result.getGroupId().toString() + "_CollectionMeeting");
|
||||||
GsonBuilder gsonBuilder = GoogleGsonSerializerHelper.createGsonBuilder();
|
GsonBuilder gsonBuilder = GoogleGsonSerializerHelper.createGsonBuilder();
|
||||||
@@ -271,7 +273,7 @@ public class CenterImportHandler implements ImportHandler {
|
|||||||
.createCalendar(commandWrapper, TemplatePopulateImportConstants.CENTER_ENTITY_TYPE, result.getGroupId()) //
|
.createCalendar(commandWrapper, TemplatePopulateImportConstants.CENTER_ENTITY_TYPE, result.getGroupId()) //
|
||||||
.withJson(payload) //
|
.withJson(payload) //
|
||||||
.build(); //
|
.build(); //
|
||||||
final CommandProcessingResult meetingresult = commandsSourceWritePlatformService.logCommandSource(commandRequest);
|
commandsSourceWritePlatformService.logCommandSource(commandRequest);
|
||||||
return 2;
|
return 2;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+38
-44
@@ -23,11 +23,13 @@ import java.math.BigDecimal;
|
|||||||
import java.time.LocalDate;
|
import java.time.LocalDate;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.Objects;
|
||||||
import org.apache.fineract.accounting.glaccount.data.GLAccountData;
|
import org.apache.fineract.accounting.glaccount.data.GLAccountData;
|
||||||
import org.apache.fineract.accounting.glaccount.domain.GLAccount;
|
import org.apache.fineract.accounting.glaccount.domain.GLAccount;
|
||||||
import org.apache.fineract.accounting.glaccount.domain.GLAccountRepositoryWrapper;
|
import org.apache.fineract.accounting.glaccount.domain.GLAccountRepositoryWrapper;
|
||||||
import org.apache.fineract.accounting.glaccount.domain.GLAccountType;
|
import org.apache.fineract.accounting.glaccount.domain.GLAccountType;
|
||||||
import org.apache.fineract.accounting.glaccount.domain.GLAccountUsage;
|
import org.apache.fineract.accounting.glaccount.domain.GLAccountUsage;
|
||||||
|
import org.apache.fineract.accounting.glaccount.exception.GLAccountNotFoundException;
|
||||||
import org.apache.fineract.accounting.journalentry.data.CreditDebit;
|
import org.apache.fineract.accounting.journalentry.data.CreditDebit;
|
||||||
import org.apache.fineract.accounting.journalentry.data.JournalEntryData;
|
import org.apache.fineract.accounting.journalentry.data.JournalEntryData;
|
||||||
import org.apache.fineract.commands.domain.CommandWrapper;
|
import org.apache.fineract.commands.domain.CommandWrapper;
|
||||||
@@ -43,7 +45,6 @@ import org.apache.fineract.infrastructure.bulkimport.importhandler.helper.Curren
|
|||||||
import org.apache.fineract.infrastructure.bulkimport.importhandler.helper.DateSerializer;
|
import org.apache.fineract.infrastructure.bulkimport.importhandler.helper.DateSerializer;
|
||||||
import org.apache.fineract.infrastructure.bulkimport.importhandler.helper.EnumOptionDataIdSerializer;
|
import org.apache.fineract.infrastructure.bulkimport.importhandler.helper.EnumOptionDataIdSerializer;
|
||||||
import org.apache.fineract.infrastructure.codes.data.CodeValueData;
|
import org.apache.fineract.infrastructure.codes.data.CodeValueData;
|
||||||
import org.apache.fineract.infrastructure.core.data.CommandProcessingResult;
|
|
||||||
import org.apache.fineract.infrastructure.core.data.EnumOptionData;
|
import org.apache.fineract.infrastructure.core.data.EnumOptionData;
|
||||||
import org.apache.fineract.infrastructure.core.serialization.GoogleGsonSerializerHelper;
|
import org.apache.fineract.infrastructure.core.serialization.GoogleGsonSerializerHelper;
|
||||||
import org.apache.fineract.infrastructure.core.service.DateUtils;
|
import org.apache.fineract.infrastructure.core.service.DateUtils;
|
||||||
@@ -62,16 +63,6 @@ import org.springframework.stereotype.Service;
|
|||||||
public class ChartOfAccountsImportHandler implements ImportHandler {
|
public class ChartOfAccountsImportHandler implements ImportHandler {
|
||||||
|
|
||||||
private static final Logger LOG = LoggerFactory.getLogger(ChartOfAccountsImportHandler.class);
|
private static final Logger LOG = LoggerFactory.getLogger(ChartOfAccountsImportHandler.class);
|
||||||
private List<GLAccountData> glAccounts;
|
|
||||||
private Workbook workbook;
|
|
||||||
private LocalDate transactionDate;
|
|
||||||
|
|
||||||
// for opening bal
|
|
||||||
int flagForOpBal = 0;
|
|
||||||
private List<JournalEntryData> gltransaction;
|
|
||||||
List<CreditDebit> credits = new ArrayList<>();
|
|
||||||
List<CreditDebit> debits = new ArrayList<>();
|
|
||||||
String locale;
|
|
||||||
|
|
||||||
private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService;
|
private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService;
|
||||||
private final GLAccountRepositoryWrapper glAccountRepository;
|
private final GLAccountRepositoryWrapper glAccountRepository;
|
||||||
@@ -84,32 +75,38 @@ public class ChartOfAccountsImportHandler implements ImportHandler {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Count process(Workbook workbook, String locale, String dateFormat) {
|
public Count process(final Workbook workbook, final String locale, final String dateFormat) {
|
||||||
this.glAccounts = new ArrayList<>();
|
List<GLAccountData> glAccounts = new ArrayList<>();
|
||||||
this.workbook = workbook;
|
|
||||||
// for opening bal
|
// for opening bal
|
||||||
gltransaction = new ArrayList<>();
|
List<JournalEntryData> glTransactions = new ArrayList<>();
|
||||||
credits = new ArrayList<>();
|
List<CreditDebit> credits = new ArrayList<>();
|
||||||
debits = new ArrayList<>();
|
List<CreditDebit> debits = new ArrayList<>();
|
||||||
this.locale = locale;
|
|
||||||
|
|
||||||
readExcelFile();
|
boolean flagForOpBal = readExcelFile(workbook, glAccounts);
|
||||||
return importEntity(dateFormat);
|
return importEntity(workbook, glAccounts, glTransactions, credits, debits, flagForOpBal, locale, dateFormat);
|
||||||
}
|
}
|
||||||
|
|
||||||
private void readExcelFile() {
|
private boolean readExcelFile(final Workbook workbook, final List<GLAccountData> glAccounts) {
|
||||||
Sheet chartOfAccountsSheet = workbook.getSheet(TemplatePopulateImportConstants.CHART_OF_ACCOUNTS_SHEET_NAME);
|
Sheet chartOfAccountsSheet = workbook.getSheet(TemplatePopulateImportConstants.CHART_OF_ACCOUNTS_SHEET_NAME);
|
||||||
Integer noOfEntries = ImportHandlerUtils.getNumberOfRows(chartOfAccountsSheet, TemplatePopulateImportConstants.FIRST_COLUMN_INDEX);
|
Integer noOfEntries = ImportHandlerUtils.getNumberOfRows(chartOfAccountsSheet, TemplatePopulateImportConstants.FIRST_COLUMN_INDEX);
|
||||||
|
boolean flagForOpBal = false;
|
||||||
for (int rowIndex = 1; rowIndex <= noOfEntries; rowIndex++) {
|
for (int rowIndex = 1; rowIndex <= noOfEntries; rowIndex++) {
|
||||||
Row row;
|
Row row;
|
||||||
row = chartOfAccountsSheet.getRow(rowIndex);
|
row = chartOfAccountsSheet.getRow(rowIndex);
|
||||||
if (ImportHandlerUtils.isNotImported(row, ChartOfAcountsConstants.STATUS_COL)) {
|
if (ImportHandlerUtils.isNotImported(row, ChartOfAcountsConstants.STATUS_COL)) {
|
||||||
glAccounts.add(readGlAccounts(row));
|
glAccounts.add(readGlAccounts(row));
|
||||||
|
if (ImportHandlerUtils.readAsString(ChartOfAcountsConstants.OFFICE_COL, row) != null) {
|
||||||
|
flagForOpBal = Boolean.TRUE;
|
||||||
|
} else {
|
||||||
|
flagForOpBal = Boolean.FALSE;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return flagForOpBal;
|
||||||
}
|
}
|
||||||
|
|
||||||
private GLAccountData readGlAccounts(Row row) {
|
private GLAccountData readGlAccounts(final Row row) {
|
||||||
|
|
||||||
String accountType = ImportHandlerUtils.readAsString(ChartOfAcountsConstants.ACCOUNT_TYPE_COL, row);
|
String accountType = ImportHandlerUtils.readAsString(ChartOfAcountsConstants.ACCOUNT_TYPE_COL, row);
|
||||||
EnumOptionData accountTypeEnum = GLAccountType.fromString(accountType);
|
EnumOptionData accountTypeEnum = GLAccountType.fromString(accountType);
|
||||||
@@ -127,26 +124,23 @@ public class ChartOfAccountsImportHandler implements ImportHandler {
|
|||||||
Boolean manualEntriesAllowed = ImportHandlerUtils.readAsBoolean(ChartOfAcountsConstants.MANUAL_ENTRIES_ALLOWED_COL, row);
|
Boolean manualEntriesAllowed = ImportHandlerUtils.readAsBoolean(ChartOfAcountsConstants.MANUAL_ENTRIES_ALLOWED_COL, row);
|
||||||
Long parentId = null;
|
Long parentId = null;
|
||||||
if (ImportHandlerUtils.readAsString(ChartOfAcountsConstants.PARENT_ID_COL, row) != null) {
|
if (ImportHandlerUtils.readAsString(ChartOfAcountsConstants.PARENT_ID_COL, row) != null) {
|
||||||
parentId = Long.parseLong(ImportHandlerUtils.readAsString(ChartOfAcountsConstants.PARENT_ID_COL, row));
|
parentId = Long.parseLong(Objects.requireNonNull(ImportHandlerUtils.readAsString(ChartOfAcountsConstants.PARENT_ID_COL, row)));
|
||||||
}
|
}
|
||||||
String glCode = ImportHandlerUtils.readAsString(ChartOfAcountsConstants.GL_CODE_COL, row);
|
String glCode = ImportHandlerUtils.readAsString(ChartOfAcountsConstants.GL_CODE_COL, row);
|
||||||
Long tagId = null;
|
Long tagId = null;
|
||||||
CodeValueData tagIdCodeValueData = null;
|
CodeValueData tagIdCodeValueData = null;
|
||||||
if (ImportHandlerUtils.readAsString(ChartOfAcountsConstants.TAG_ID_COL, row) != null) {
|
if (ImportHandlerUtils.readAsString(ChartOfAcountsConstants.TAG_ID_COL, row) != null) {
|
||||||
tagId = Long.parseLong(ImportHandlerUtils.readAsString(ChartOfAcountsConstants.TAG_ID_COL, row));
|
tagId = Long.parseLong(Objects.requireNonNull(ImportHandlerUtils.readAsString(ChartOfAcountsConstants.TAG_ID_COL, row)));
|
||||||
tagIdCodeValueData = new CodeValueData().setId(tagId);
|
tagIdCodeValueData = new CodeValueData().setId(tagId);
|
||||||
}
|
}
|
||||||
String description = ImportHandlerUtils.readAsString(ChartOfAcountsConstants.DESCRIPTION_COL, row);
|
String description = ImportHandlerUtils.readAsString(ChartOfAcountsConstants.DESCRIPTION_COL, row);
|
||||||
if (ImportHandlerUtils.readAsString(ChartOfAcountsConstants.OFFICE_COL, row) != null) {
|
|
||||||
flagForOpBal = 1;
|
|
||||||
} else {
|
|
||||||
flagForOpBal = 0;
|
|
||||||
}
|
|
||||||
return GLAccountData.importInstance(accountName, parentId, glCode, manualEntriesAllowed, accountTypeEnum, usageEnum, description,
|
return GLAccountData.importInstance(accountName, parentId, glCode, manualEntriesAllowed, accountTypeEnum, usageEnum, description,
|
||||||
tagIdCodeValueData, row.getRowNum());
|
tagIdCodeValueData, row.getRowNum());
|
||||||
}
|
}
|
||||||
|
|
||||||
public Count importEntity(String dateFormat) {
|
private Count importEntity(final Workbook workbook, final List<GLAccountData> glAccounts, final List<JournalEntryData> glTransactions,
|
||||||
|
final List<CreditDebit> credits, final List<CreditDebit> debits, final boolean flagForOpBal, final String locale,
|
||||||
|
final String dateFormat) {
|
||||||
Sheet chartOfAccountsSheet = workbook.getSheet(TemplatePopulateImportConstants.CHART_OF_ACCOUNTS_SHEET_NAME);
|
Sheet chartOfAccountsSheet = workbook.getSheet(TemplatePopulateImportConstants.CHART_OF_ACCOUNTS_SHEET_NAME);
|
||||||
|
|
||||||
GsonBuilder gsonBuilder = GoogleGsonSerializerHelper.createGsonBuilder();
|
GsonBuilder gsonBuilder = GoogleGsonSerializerHelper.createGsonBuilder();
|
||||||
@@ -166,7 +160,7 @@ public class ChartOfAccountsImportHandler implements ImportHandler {
|
|||||||
.createGLAccount() //
|
.createGLAccount() //
|
||||||
.withJson(payload) //
|
.withJson(payload) //
|
||||||
.build(); //
|
.build(); //
|
||||||
final CommandProcessingResult result = commandsSourceWritePlatformService.logCommandSource(commandRequest);
|
commandsSourceWritePlatformService.logCommandSource(commandRequest);
|
||||||
successCount++;
|
successCount++;
|
||||||
Cell statusCell = chartOfAccountsSheet.getRow(glAccount.getRowIndex()).createCell(ChartOfAcountsConstants.STATUS_COL);
|
Cell statusCell = chartOfAccountsSheet.getRow(glAccount.getRowIndex()).createCell(ChartOfAcountsConstants.STATUS_COL);
|
||||||
statusCell.setCellValue(TemplatePopulateImportConstants.STATUS_CELL_IMPORTED);
|
statusCell.setCellValue(TemplatePopulateImportConstants.STATUS_CELL_IMPORTED);
|
||||||
@@ -179,16 +173,15 @@ public class ChartOfAccountsImportHandler implements ImportHandler {
|
|||||||
ChartOfAcountsConstants.STATUS_COL);
|
ChartOfAcountsConstants.STATUS_COL);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (flagForOpBal > 0) {
|
if (flagForOpBal) {
|
||||||
|
|
||||||
try {
|
try {
|
||||||
readExcelFileForOpBal(locale, dateFormat);
|
readExcelFileForOpBal(workbook, glTransactions, credits, debits, locale, dateFormat);
|
||||||
JournalEntryData transaction = gltransaction.get(gltransaction.size() - 1);
|
JournalEntryData transaction = glTransactions.get(glTransactions.size() - 1);
|
||||||
String payload = gsonBuilder.create().toJson(transaction);
|
String payload = gsonBuilder.create().toJson(transaction);
|
||||||
|
|
||||||
final CommandWrapper commandRequest = new CommandWrapperBuilder().defineOpeningBalanceForJournalEntry()
|
final CommandWrapper commandRequest = new CommandWrapperBuilder().defineOpeningBalanceForJournalEntry()
|
||||||
.withJson(payload).build();
|
.withJson(payload).build();
|
||||||
final CommandProcessingResult result = commandsSourceWritePlatformService.logCommandSource(commandRequest);
|
commandsSourceWritePlatformService.logCommandSource(commandRequest);
|
||||||
successCount++;
|
successCount++;
|
||||||
Cell statusCell = chartOfAccountsSheet.getRow(1).createCell(ChartOfAcountsConstants.STATUS_COL);
|
Cell statusCell = chartOfAccountsSheet.getRow(1).createCell(ChartOfAcountsConstants.STATUS_COL);
|
||||||
statusCell.setCellValue(TemplatePopulateImportConstants.STATUS_CELL_IMPORTED);
|
statusCell.setCellValue(TemplatePopulateImportConstants.STATUS_CELL_IMPORTED);
|
||||||
@@ -216,7 +209,8 @@ public class ChartOfAccountsImportHandler implements ImportHandler {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// for opening balance
|
// for opening balance
|
||||||
public void readExcelFileForOpBal(final String locale, final String dateFormat) {
|
private void readExcelFileForOpBal(final Workbook workbook, final List<JournalEntryData> glTransactions,
|
||||||
|
final List<CreditDebit> credits, final List<CreditDebit> debits, final String locale, final String dateFormat) {
|
||||||
|
|
||||||
Sheet chartOfAccountsSheet = workbook.getSheet(TemplatePopulateImportConstants.CHART_OF_ACCOUNTS_SHEET_NAME);
|
Sheet chartOfAccountsSheet = workbook.getSheet(TemplatePopulateImportConstants.CHART_OF_ACCOUNTS_SHEET_NAME);
|
||||||
Integer noOfEntries = ImportHandlerUtils.getNumberOfRows(chartOfAccountsSheet, TemplatePopulateImportConstants.FIRST_COLUMN_INDEX);
|
Integer noOfEntries = ImportHandlerUtils.getNumberOfRows(chartOfAccountsSheet, TemplatePopulateImportConstants.FIRST_COLUMN_INDEX);
|
||||||
@@ -225,18 +219,18 @@ public class ChartOfAccountsImportHandler implements ImportHandler {
|
|||||||
row = chartOfAccountsSheet.getRow(rowIndex);
|
row = chartOfAccountsSheet.getRow(rowIndex);
|
||||||
|
|
||||||
//
|
//
|
||||||
JournalEntryData journalEntry = null;
|
JournalEntryData journalEntry;
|
||||||
journalEntry = readAddJournalEntries(row, locale, dateFormat);
|
journalEntry = readAddJournalEntries(row, credits, debits, locale, dateFormat);
|
||||||
gltransaction.add(journalEntry);
|
glTransactions.add(journalEntry);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// for opening balance
|
// for opening balance
|
||||||
private JournalEntryData readAddJournalEntries(Row row, String locale, String dateFormat) {
|
private JournalEntryData readAddJournalEntries(final Row row, final List<CreditDebit> credits, final List<CreditDebit> debits,
|
||||||
transactionDate = DateUtils.getBusinessLocalDate();
|
final String locale, String dateFormat) {
|
||||||
|
LocalDate transactionDate = DateUtils.getBusinessLocalDate();
|
||||||
|
|
||||||
String officeName = ImportHandlerUtils.readAsString(ChartOfAcountsConstants.OFFICE_COL, row);
|
|
||||||
Long officeId = ImportHandlerUtils.readAsLong(ChartOfAcountsConstants.OFFICE_COL_ID, row);
|
Long officeId = ImportHandlerUtils.readAsLong(ChartOfAcountsConstants.OFFICE_COL_ID, row);
|
||||||
|
|
||||||
String currencyCode = ImportHandlerUtils.readAsString(ChartOfAcountsConstants.CURRENCY_CODE, row);
|
String currencyCode = ImportHandlerUtils.readAsString(ChartOfAcountsConstants.CURRENCY_CODE, row);
|
||||||
@@ -245,7 +239,7 @@ public class ChartOfAccountsImportHandler implements ImportHandler {
|
|||||||
GLAccount glAccount = this.glAccountRepository.findOneByGlCodeWithNotFoundDetection(glCode);
|
GLAccount glAccount = this.glAccountRepository.findOneByGlCodeWithNotFoundDetection(glCode);
|
||||||
Long glAccountIdToDebitedCredited = glAccount.getId();
|
Long glAccountIdToDebitedCredited = glAccount.getId();
|
||||||
if (glAccountIdToDebitedCredited == null) {
|
if (glAccountIdToDebitedCredited == null) {
|
||||||
throw new RuntimeException("Account does not exist");
|
throw new GLAccountNotFoundException("Account does not exist");
|
||||||
}
|
}
|
||||||
|
|
||||||
// String credit =
|
// String credit =
|
||||||
|
|||||||
+25
-27
@@ -22,9 +22,9 @@ import com.google.common.base.Splitter;
|
|||||||
import com.google.gson.GsonBuilder;
|
import com.google.gson.GsonBuilder;
|
||||||
import java.time.LocalDate;
|
import java.time.LocalDate;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.Arrays;
|
|
||||||
import java.util.Collection;
|
import java.util.Collection;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.Objects;
|
||||||
import org.apache.fineract.commands.domain.CommandWrapper;
|
import org.apache.fineract.commands.domain.CommandWrapper;
|
||||||
import org.apache.fineract.commands.service.CommandWrapperBuilder;
|
import org.apache.fineract.commands.service.CommandWrapperBuilder;
|
||||||
import org.apache.fineract.commands.service.PortfolioCommandSourceWritePlatformService;
|
import org.apache.fineract.commands.service.PortfolioCommandSourceWritePlatformService;
|
||||||
@@ -34,7 +34,6 @@ import org.apache.fineract.infrastructure.bulkimport.data.Count;
|
|||||||
import org.apache.fineract.infrastructure.bulkimport.importhandler.ImportHandler;
|
import org.apache.fineract.infrastructure.bulkimport.importhandler.ImportHandler;
|
||||||
import org.apache.fineract.infrastructure.bulkimport.importhandler.ImportHandlerUtils;
|
import org.apache.fineract.infrastructure.bulkimport.importhandler.ImportHandlerUtils;
|
||||||
import org.apache.fineract.infrastructure.bulkimport.importhandler.helper.DateSerializer;
|
import org.apache.fineract.infrastructure.bulkimport.importhandler.helper.DateSerializer;
|
||||||
import org.apache.fineract.infrastructure.core.data.CommandProcessingResult;
|
|
||||||
import org.apache.fineract.infrastructure.core.serialization.GoogleGsonSerializerHelper;
|
import org.apache.fineract.infrastructure.core.serialization.GoogleGsonSerializerHelper;
|
||||||
import org.apache.fineract.portfolio.address.data.AddressData;
|
import org.apache.fineract.portfolio.address.data.AddressData;
|
||||||
import org.apache.fineract.portfolio.client.data.ClientData;
|
import org.apache.fineract.portfolio.client.data.ClientData;
|
||||||
@@ -52,10 +51,8 @@ import org.springframework.stereotype.Service;
|
|||||||
@Service
|
@Service
|
||||||
public class ClientEntityImportHandler implements ImportHandler {
|
public class ClientEntityImportHandler implements ImportHandler {
|
||||||
|
|
||||||
|
public static final String SEPARATOR = "-";
|
||||||
private static final Logger LOG = LoggerFactory.getLogger(ClientEntityImportHandler.class);
|
private static final Logger LOG = LoggerFactory.getLogger(ClientEntityImportHandler.class);
|
||||||
private Workbook workbook;
|
|
||||||
private List<ClientData> clients;
|
|
||||||
|
|
||||||
private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService;
|
private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService;
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
@@ -64,26 +61,27 @@ public class ClientEntityImportHandler implements ImportHandler {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Count process(Workbook workbook, String locale, String dateFormat) {
|
public Count process(final Workbook workbook, final String locale, final String dateFormat) {
|
||||||
this.workbook = workbook;
|
|
||||||
this.clients = new ArrayList<>();
|
List<ClientData> clients = readExcelFile(workbook, locale, dateFormat);
|
||||||
readExcelFile(locale, dateFormat);
|
return importEntity(workbook, clients, dateFormat);
|
||||||
return importEntity(dateFormat);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public void readExcelFile(final String locale, final String dateFormat) {
|
private List<ClientData> readExcelFile(final Workbook workbook, final String locale, final String dateFormat) {
|
||||||
|
List<ClientData> clients = new ArrayList<>();
|
||||||
Sheet clientSheet = workbook.getSheet(TemplatePopulateImportConstants.CLIENT_ENTITY_SHEET_NAME);
|
Sheet clientSheet = workbook.getSheet(TemplatePopulateImportConstants.CLIENT_ENTITY_SHEET_NAME);
|
||||||
Integer noOfEntries = ImportHandlerUtils.getNumberOfRows(clientSheet, 0);
|
Integer noOfEntries = ImportHandlerUtils.getNumberOfRows(clientSheet, 0);
|
||||||
for (int rowIndex = 1; rowIndex <= noOfEntries; rowIndex++) {
|
for (int rowIndex = 1; rowIndex <= noOfEntries; rowIndex++) {
|
||||||
Row row;
|
Row row;
|
||||||
row = clientSheet.getRow(rowIndex);
|
row = clientSheet.getRow(rowIndex);
|
||||||
if (ImportHandlerUtils.isNotImported(row, ClientEntityConstants.STATUS_COL)) {
|
if (ImportHandlerUtils.isNotImported(row, ClientEntityConstants.STATUS_COL)) {
|
||||||
clients.add(readClient(row, locale, dateFormat));
|
clients.add(readClient(workbook, row, locale, dateFormat));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
return clients;
|
||||||
}
|
}
|
||||||
|
|
||||||
private ClientData readClient(Row row, final String locale, final String dateFormat) {
|
private ClientData readClient(final Workbook workbook, final Row row, final String locale, final String dateFormat) {
|
||||||
Long legalFormId = 2L;
|
Long legalFormId = 2L;
|
||||||
String name = ImportHandlerUtils.readAsString(ClientEntityConstants.NAME_COL, row);
|
String name = ImportHandlerUtils.readAsString(ClientEntityConstants.NAME_COL, row);
|
||||||
String officeName = ImportHandlerUtils.readAsString(ClientEntityConstants.OFFICE_NAME_COL, row);
|
String officeName = ImportHandlerUtils.readAsString(ClientEntityConstants.OFFICE_NAME_COL, row);
|
||||||
@@ -100,13 +98,13 @@ public class ClientEntityImportHandler implements ImportHandler {
|
|||||||
LocalDate incorporationTill = ImportHandlerUtils.readAsDate(ClientEntityConstants.INCOPORATION_VALID_TILL_COL, row);
|
LocalDate incorporationTill = ImportHandlerUtils.readAsDate(ClientEntityConstants.INCOPORATION_VALID_TILL_COL, row);
|
||||||
String mobileNo = null;
|
String mobileNo = null;
|
||||||
if (ImportHandlerUtils.readAsLong(ClientEntityConstants.MOBILE_NO_COL, row) != null) {
|
if (ImportHandlerUtils.readAsLong(ClientEntityConstants.MOBILE_NO_COL, row) != null) {
|
||||||
mobileNo = ImportHandlerUtils.readAsLong(ClientEntityConstants.MOBILE_NO_COL, row).toString();
|
mobileNo = Objects.requireNonNull(ImportHandlerUtils.readAsLong(ClientEntityConstants.MOBILE_NO_COL, row)).toString();
|
||||||
}
|
}
|
||||||
|
|
||||||
String clientType = ImportHandlerUtils.readAsString(ClientEntityConstants.CLIENT_TYPE_COL, row);
|
String clientType = ImportHandlerUtils.readAsString(ClientEntityConstants.CLIENT_TYPE_COL, row);
|
||||||
Long clientTypeId = null;
|
Long clientTypeId = null;
|
||||||
if (clientType != null) {
|
if (clientType != null) {
|
||||||
List<String> clientTypeAr = Splitter.on('-').splitToList(clientType);
|
List<String> clientTypeAr = Splitter.on(SEPARATOR).splitToList(clientType);
|
||||||
if (clientTypeAr.get(1) != null) {
|
if (clientTypeAr.get(1) != null) {
|
||||||
clientTypeId = Long.parseLong(clientTypeAr.get(1));
|
clientTypeId = Long.parseLong(clientTypeAr.get(1));
|
||||||
}
|
}
|
||||||
@@ -114,7 +112,7 @@ public class ClientEntityImportHandler implements ImportHandler {
|
|||||||
String clientClassification = ImportHandlerUtils.readAsString(ClientEntityConstants.CLIENT_CLASSIFICATION_COL, row);
|
String clientClassification = ImportHandlerUtils.readAsString(ClientEntityConstants.CLIENT_CLASSIFICATION_COL, row);
|
||||||
Long clientClassicationId = null;
|
Long clientClassicationId = null;
|
||||||
if (clientClassification != null) {
|
if (clientClassification != null) {
|
||||||
List<String> clientClassificationAr = Splitter.on('-').splitToList(clientClassification);
|
List<String> clientClassificationAr = Splitter.on(SEPARATOR).splitToList(clientClassification);
|
||||||
if (clientClassificationAr.get(1) != null) {
|
if (clientClassificationAr.get(1) != null) {
|
||||||
clientClassicationId = Long.parseLong(clientClassificationAr.get(1));
|
clientClassicationId = Long.parseLong(clientClassificationAr.get(1));
|
||||||
}
|
}
|
||||||
@@ -124,8 +122,8 @@ public class ClientEntityImportHandler implements ImportHandler {
|
|||||||
String mainBusinessLine = ImportHandlerUtils.readAsString(ClientEntityConstants.MAIN_BUSINESS_LINE, row);
|
String mainBusinessLine = ImportHandlerUtils.readAsString(ClientEntityConstants.MAIN_BUSINESS_LINE, row);
|
||||||
Long mainBusinessId = null;
|
Long mainBusinessId = null;
|
||||||
if (mainBusinessLine != null) {
|
if (mainBusinessLine != null) {
|
||||||
List<String> mainBusinessLineAr = Splitter.on('-')
|
List<String> mainBusinessLineAr = Splitter.on(SEPARATOR)
|
||||||
.splitToList(ImportHandlerUtils.readAsString(ClientEntityConstants.MAIN_BUSINESS_LINE, row));
|
.splitToList(Objects.requireNonNull(ImportHandlerUtils.readAsString(ClientEntityConstants.MAIN_BUSINESS_LINE, row)));
|
||||||
if (mainBusinessLineAr.get(1) != null) {
|
if (mainBusinessLineAr.get(1) != null) {
|
||||||
mainBusinessId = Long.parseLong(mainBusinessLineAr.get(1));
|
mainBusinessId = Long.parseLong(mainBusinessLineAr.get(1));
|
||||||
}
|
}
|
||||||
@@ -133,7 +131,7 @@ public class ClientEntityImportHandler implements ImportHandler {
|
|||||||
String constitution = ImportHandlerUtils.readAsString(ClientEntityConstants.CONSTITUTION_COL, row);
|
String constitution = ImportHandlerUtils.readAsString(ClientEntityConstants.CONSTITUTION_COL, row);
|
||||||
Long constitutionId = null;
|
Long constitutionId = null;
|
||||||
if (constitution != null) {
|
if (constitution != null) {
|
||||||
List<String> constitutionAr = Splitter.on('-').splitToList(constitution);
|
List<String> constitutionAr = Splitter.on(SEPARATOR).splitToList(constitution);
|
||||||
if (constitutionAr.get(1) != null) {
|
if (constitutionAr.get(1) != null) {
|
||||||
constitutionId = Long.parseLong(constitutionAr.get(1));
|
constitutionId = Long.parseLong(constitutionAr.get(1));
|
||||||
}
|
}
|
||||||
@@ -153,13 +151,13 @@ public class ClientEntityImportHandler implements ImportHandler {
|
|||||||
if (!active) {
|
if (!active) {
|
||||||
activationDate = submittedOn;
|
activationDate = submittedOn;
|
||||||
}
|
}
|
||||||
AddressData addressDataObj = null;
|
AddressData addressDataObj;
|
||||||
Collection<AddressData> addressList = null;
|
Collection<AddressData> addressList = null;
|
||||||
if (ImportHandlerUtils.readAsBoolean(ClientEntityConstants.ADDRESS_ENABLED, row)) {
|
if (ImportHandlerUtils.readAsBoolean(ClientEntityConstants.ADDRESS_ENABLED, row)) {
|
||||||
String addressType = ImportHandlerUtils.readAsString(ClientEntityConstants.ADDRESS_TYPE_COL, row);
|
String addressType = ImportHandlerUtils.readAsString(ClientEntityConstants.ADDRESS_TYPE_COL, row);
|
||||||
Long addressTypeId = null;
|
Long addressTypeId = null;
|
||||||
if (addressType != null) {
|
if (addressType != null) {
|
||||||
List<String> addressTypeAr = Splitter.on('-').splitToList(addressType);
|
List<String> addressTypeAr = Splitter.on(SEPARATOR).splitToList(addressType);
|
||||||
if (addressTypeAr.get(1) != null) {
|
if (addressTypeAr.get(1) != null) {
|
||||||
addressTypeId = Long.parseLong(addressTypeAr.get(1));
|
addressTypeId = Long.parseLong(addressTypeAr.get(1));
|
||||||
}
|
}
|
||||||
@@ -176,7 +174,7 @@ public class ClientEntityImportHandler implements ImportHandler {
|
|||||||
String stateProvince = ImportHandlerUtils.readAsString(ClientEntityConstants.STATE_PROVINCE_COL, row);
|
String stateProvince = ImportHandlerUtils.readAsString(ClientEntityConstants.STATE_PROVINCE_COL, row);
|
||||||
Long stateProvinceId = null;
|
Long stateProvinceId = null;
|
||||||
if (stateProvince != null) {
|
if (stateProvince != null) {
|
||||||
List<String> stateProvinceAr = Splitter.on('-').splitToList(stateProvince);
|
List<String> stateProvinceAr = Splitter.on(SEPARATOR).splitToList(stateProvince);
|
||||||
if (stateProvinceAr.get(1) != null) {
|
if (stateProvinceAr.get(1) != null) {
|
||||||
stateProvinceId = Long.parseLong(stateProvinceAr.get(1));
|
stateProvinceId = Long.parseLong(stateProvinceAr.get(1));
|
||||||
}
|
}
|
||||||
@@ -184,26 +182,26 @@ public class ClientEntityImportHandler implements ImportHandler {
|
|||||||
String country = ImportHandlerUtils.readAsString(ClientEntityConstants.COUNTRY_COL, row);
|
String country = ImportHandlerUtils.readAsString(ClientEntityConstants.COUNTRY_COL, row);
|
||||||
Long countryId = null;
|
Long countryId = null;
|
||||||
if (country != null) {
|
if (country != null) {
|
||||||
List<String> countryAr = Splitter.on('-').splitToList(country);
|
List<String> countryAr = Splitter.on(SEPARATOR).splitToList(country);
|
||||||
if (countryAr.get(1) != null) {
|
if (countryAr.get(1) != null) {
|
||||||
countryId = Long.parseLong(countryAr.get(1));
|
countryId = Long.parseLong(countryAr.get(1));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
addressDataObj = new AddressData(addressTypeId, street, addressLine1, addressLine2, addressLine3, city, postalCode,
|
addressDataObj = new AddressData(addressTypeId, street, addressLine1, addressLine2, addressLine3, city, postalCode,
|
||||||
isActiveAddress, stateProvinceId, countryId);
|
isActiveAddress, stateProvinceId, countryId);
|
||||||
addressList = new ArrayList<AddressData>(Arrays.asList(addressDataObj));
|
addressList = new ArrayList<>(List.of(addressDataObj));
|
||||||
}
|
}
|
||||||
return ClientData.importClientEntityInstance(legalFormId, row.getRowNum(), name, officeId, clientTypeId, clientClassicationId,
|
return ClientData.importClientEntityInstance(legalFormId, row.getRowNum(), name, officeId, clientTypeId, clientClassicationId,
|
||||||
staffId, active, activationDate, submittedOn, externalId, incorportionDate, mobileNo, clientNonPersonData, addressList,
|
staffId, active, activationDate, submittedOn, externalId, incorportionDate, mobileNo, clientNonPersonData, addressList,
|
||||||
locale, dateFormat);
|
locale, dateFormat);
|
||||||
}
|
}
|
||||||
|
|
||||||
public Count importEntity(String dateFormat) {
|
private Count importEntity(final Workbook workbook, final List<ClientData> clients, final String dateFormat) {
|
||||||
Sheet clientSheet = workbook.getSheet(TemplatePopulateImportConstants.CLIENT_ENTITY_SHEET_NAME);
|
Sheet clientSheet = workbook.getSheet(TemplatePopulateImportConstants.CLIENT_ENTITY_SHEET_NAME);
|
||||||
|
|
||||||
int successCount = 0;
|
int successCount = 0;
|
||||||
int errorCount = 0;
|
int errorCount = 0;
|
||||||
String errorMessage = "";
|
String errorMessage;
|
||||||
|
|
||||||
GsonBuilder gsonBuilder = GoogleGsonSerializerHelper.createGsonBuilder();
|
GsonBuilder gsonBuilder = GoogleGsonSerializerHelper.createGsonBuilder();
|
||||||
gsonBuilder.registerTypeAdapter(LocalDate.class, new DateSerializer(dateFormat));
|
gsonBuilder.registerTypeAdapter(LocalDate.class, new DateSerializer(dateFormat));
|
||||||
@@ -215,7 +213,7 @@ public class ClientEntityImportHandler implements ImportHandler {
|
|||||||
.createClient() //
|
.createClient() //
|
||||||
.withJson(payload) //
|
.withJson(payload) //
|
||||||
.build(); //
|
.build(); //
|
||||||
final CommandProcessingResult result = commandsSourceWritePlatformService.logCommandSource(commandRequest);
|
commandsSourceWritePlatformService.logCommandSource(commandRequest);
|
||||||
successCount++;
|
successCount++;
|
||||||
Cell statusCell = clientSheet.getRow(client.getRowIndex()).createCell(ClientEntityConstants.STATUS_COL);
|
Cell statusCell = clientSheet.getRow(client.getRowIndex()).createCell(ClientEntityConstants.STATUS_COL);
|
||||||
statusCell.setCellValue(TemplatePopulateImportConstants.STATUS_CELL_IMPORTED);
|
statusCell.setCellValue(TemplatePopulateImportConstants.STATUS_CELL_IMPORTED);
|
||||||
|
|||||||
+21
-22
@@ -22,9 +22,9 @@ import com.google.common.base.Splitter;
|
|||||||
import com.google.gson.GsonBuilder;
|
import com.google.gson.GsonBuilder;
|
||||||
import java.time.LocalDate;
|
import java.time.LocalDate;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.Arrays;
|
|
||||||
import java.util.Collection;
|
import java.util.Collection;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.Objects;
|
||||||
import org.apache.fineract.commands.domain.CommandWrapper;
|
import org.apache.fineract.commands.domain.CommandWrapper;
|
||||||
import org.apache.fineract.commands.service.CommandWrapperBuilder;
|
import org.apache.fineract.commands.service.CommandWrapperBuilder;
|
||||||
import org.apache.fineract.commands.service.PortfolioCommandSourceWritePlatformService;
|
import org.apache.fineract.commands.service.PortfolioCommandSourceWritePlatformService;
|
||||||
@@ -50,10 +50,8 @@ import org.springframework.stereotype.Service;
|
|||||||
@Service
|
@Service
|
||||||
public class ClientPersonImportHandler implements ImportHandler {
|
public class ClientPersonImportHandler implements ImportHandler {
|
||||||
|
|
||||||
|
public static final String SEPARATOR = "-";
|
||||||
private static final Logger LOG = LoggerFactory.getLogger(ClientPersonImportHandler.class);
|
private static final Logger LOG = LoggerFactory.getLogger(ClientPersonImportHandler.class);
|
||||||
private Workbook workbook;
|
|
||||||
private List<ClientData> clients;
|
|
||||||
|
|
||||||
private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService;
|
private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService;
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
@@ -62,26 +60,27 @@ public class ClientPersonImportHandler implements ImportHandler {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Count process(Workbook workbook, String locale, String dateFormat) {
|
public Count process(final Workbook workbook, final String locale, final String dateFormat) {
|
||||||
this.workbook = workbook;
|
|
||||||
this.clients = new ArrayList<>();
|
List<ClientData> clients = readExcelFile(workbook, locale, dateFormat);
|
||||||
readExcelFile(locale, dateFormat);
|
return importEntity(workbook, clients, dateFormat);
|
||||||
return importEntity(dateFormat);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public void readExcelFile(final String locale, final String dateFormat) {
|
public List<ClientData> readExcelFile(final Workbook workbook, final String locale, final String dateFormat) {
|
||||||
|
List<ClientData> clients = new ArrayList<>();
|
||||||
Sheet clientSheet = workbook.getSheet(TemplatePopulateImportConstants.CLIENT_PERSON_SHEET_NAME);
|
Sheet clientSheet = workbook.getSheet(TemplatePopulateImportConstants.CLIENT_PERSON_SHEET_NAME);
|
||||||
Integer noOfEntries = ImportHandlerUtils.getNumberOfRows(clientSheet, 0);
|
Integer noOfEntries = ImportHandlerUtils.getNumberOfRows(clientSheet, 0);
|
||||||
for (int rowIndex = 1; rowIndex <= noOfEntries; rowIndex++) {
|
for (int rowIndex = 1; rowIndex <= noOfEntries; rowIndex++) {
|
||||||
Row row;
|
Row row;
|
||||||
row = clientSheet.getRow(rowIndex);
|
row = clientSheet.getRow(rowIndex);
|
||||||
if (ImportHandlerUtils.isNotImported(row, ClientPersonConstants.STATUS_COL)) {
|
if (ImportHandlerUtils.isNotImported(row, ClientPersonConstants.STATUS_COL)) {
|
||||||
clients.add(readClient(row, locale, dateFormat));
|
clients.add(readClient(workbook, row, locale, dateFormat));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
return clients;
|
||||||
}
|
}
|
||||||
|
|
||||||
private ClientData readClient(Row row, final String locale, final String dateFormat) {
|
private ClientData readClient(final Workbook workbook, final Row row, final String locale, final String dateFormat) {
|
||||||
Long legalFormId = 1L;
|
Long legalFormId = 1L;
|
||||||
String firstName = ImportHandlerUtils.readAsString(ClientPersonConstants.FIRST_NAME_COL, row);
|
String firstName = ImportHandlerUtils.readAsString(ClientPersonConstants.FIRST_NAME_COL, row);
|
||||||
String lastName = ImportHandlerUtils.readAsString(ClientPersonConstants.LAST_NAME_COL, row);
|
String lastName = ImportHandlerUtils.readAsString(ClientPersonConstants.LAST_NAME_COL, row);
|
||||||
@@ -105,14 +104,14 @@ public class ClientPersonImportHandler implements ImportHandler {
|
|||||||
}
|
}
|
||||||
String mobileNo = null;
|
String mobileNo = null;
|
||||||
if (ImportHandlerUtils.readAsLong(ClientPersonConstants.MOBILE_NO_COL, row) != null) {
|
if (ImportHandlerUtils.readAsLong(ClientPersonConstants.MOBILE_NO_COL, row) != null) {
|
||||||
mobileNo = ImportHandlerUtils.readAsLong(ClientPersonConstants.MOBILE_NO_COL, row).toString();
|
mobileNo = Objects.requireNonNull(ImportHandlerUtils.readAsLong(ClientPersonConstants.MOBILE_NO_COL, row)).toString();
|
||||||
}
|
}
|
||||||
LocalDate dob = ImportHandlerUtils.readAsDate(ClientPersonConstants.DOB_COL, row);
|
LocalDate dob = ImportHandlerUtils.readAsDate(ClientPersonConstants.DOB_COL, row);
|
||||||
|
|
||||||
String clientType = ImportHandlerUtils.readAsString(ClientPersonConstants.CLIENT_TYPE_COL, row);
|
String clientType = ImportHandlerUtils.readAsString(ClientPersonConstants.CLIENT_TYPE_COL, row);
|
||||||
Long clientTypeId = null;
|
Long clientTypeId = null;
|
||||||
if (clientType != null) {
|
if (clientType != null) {
|
||||||
List<String> clientTypeAr = Splitter.on('-').splitToList(clientType);
|
List<String> clientTypeAr = Splitter.on(SEPARATOR).splitToList(clientType);
|
||||||
if (clientTypeAr.size() > 1 && clientTypeAr.get(1) != null) {
|
if (clientTypeAr.size() > 1 && clientTypeAr.get(1) != null) {
|
||||||
clientTypeId = Long.parseLong(clientTypeAr.get(1));
|
clientTypeId = Long.parseLong(clientTypeAr.get(1));
|
||||||
}
|
}
|
||||||
@@ -120,7 +119,7 @@ public class ClientPersonImportHandler implements ImportHandler {
|
|||||||
String gender = ImportHandlerUtils.readAsString(ClientPersonConstants.GENDER_COL, row);
|
String gender = ImportHandlerUtils.readAsString(ClientPersonConstants.GENDER_COL, row);
|
||||||
Long genderId = null;
|
Long genderId = null;
|
||||||
if (gender != null) {
|
if (gender != null) {
|
||||||
List<String> genderAr = Splitter.on('-').splitToList(gender);
|
List<String> genderAr = Splitter.on(SEPARATOR).splitToList(gender);
|
||||||
if (genderAr.size() > 1 && genderAr.get(1) != null) {
|
if (genderAr.size() > 1 && genderAr.get(1) != null) {
|
||||||
genderId = Long.parseLong(genderAr.get(1));
|
genderId = Long.parseLong(genderAr.get(1));
|
||||||
}
|
}
|
||||||
@@ -128,7 +127,7 @@ public class ClientPersonImportHandler implements ImportHandler {
|
|||||||
String clientClassification = ImportHandlerUtils.readAsString(ClientPersonConstants.CLIENT_CLASSIFICATION_COL, row);
|
String clientClassification = ImportHandlerUtils.readAsString(ClientPersonConstants.CLIENT_CLASSIFICATION_COL, row);
|
||||||
Long clientClassificationId = null;
|
Long clientClassificationId = null;
|
||||||
if (clientClassification != null) {
|
if (clientClassification != null) {
|
||||||
List<String> clientClassificationAr = Splitter.on('-').splitToList(clientClassification);
|
List<String> clientClassificationAr = Splitter.on(SEPARATOR).splitToList(clientClassification);
|
||||||
if (clientClassificationAr.size() > 1 && clientClassificationAr.get(1) != null) {
|
if (clientClassificationAr.size() > 1 && clientClassificationAr.get(1) != null) {
|
||||||
clientClassificationId = Long.parseLong(clientClassificationAr.get(1));
|
clientClassificationId = Long.parseLong(clientClassificationAr.get(1));
|
||||||
}
|
}
|
||||||
@@ -141,7 +140,7 @@ public class ClientPersonImportHandler implements ImportHandler {
|
|||||||
String addressType = ImportHandlerUtils.readAsString(ClientPersonConstants.ADDRESS_TYPE_COL, row);
|
String addressType = ImportHandlerUtils.readAsString(ClientPersonConstants.ADDRESS_TYPE_COL, row);
|
||||||
Long addressTypeId = null;
|
Long addressTypeId = null;
|
||||||
if (addressType != null) {
|
if (addressType != null) {
|
||||||
List<String> addressTypeAr = Splitter.on('-').splitToList(addressType);
|
List<String> addressTypeAr = Splitter.on(SEPARATOR).splitToList(addressType);
|
||||||
|
|
||||||
if (addressTypeAr.size() > 1 && addressTypeAr.get(1) != null) {
|
if (addressTypeAr.size() > 1 && addressTypeAr.get(1) != null) {
|
||||||
addressTypeId = Long.parseLong(addressTypeAr.get(1));
|
addressTypeId = Long.parseLong(addressTypeAr.get(1));
|
||||||
@@ -159,7 +158,7 @@ public class ClientPersonImportHandler implements ImportHandler {
|
|||||||
String stateProvince = ImportHandlerUtils.readAsString(ClientPersonConstants.STATE_PROVINCE_COL, row);
|
String stateProvince = ImportHandlerUtils.readAsString(ClientPersonConstants.STATE_PROVINCE_COL, row);
|
||||||
Long stateProvinceId = null;
|
Long stateProvinceId = null;
|
||||||
if (stateProvince != null) {
|
if (stateProvince != null) {
|
||||||
List<String> stateProvinceAr = Splitter.on('-').splitToList(stateProvince);
|
List<String> stateProvinceAr = Splitter.on(SEPARATOR).splitToList(stateProvince);
|
||||||
// Arkansas-AL <-- expected format of the cell
|
// Arkansas-AL <-- expected format of the cell
|
||||||
// but probably it's either an empty cell or it is missing a
|
// but probably it's either an empty cell or it is missing a
|
||||||
// hyphen
|
// hyphen
|
||||||
@@ -170,14 +169,14 @@ public class ClientPersonImportHandler implements ImportHandler {
|
|||||||
String country = ImportHandlerUtils.readAsString(ClientPersonConstants.COUNTRY_COL, row);
|
String country = ImportHandlerUtils.readAsString(ClientPersonConstants.COUNTRY_COL, row);
|
||||||
Long countryId = null;
|
Long countryId = null;
|
||||||
if (country != null) {
|
if (country != null) {
|
||||||
List<String> countryAr = Splitter.on('-').splitToList(country);
|
List<String> countryAr = Splitter.on(SEPARATOR).splitToList(country);
|
||||||
if (countryAr.size() > 1 && countryAr.get(1) != null) {
|
if (countryAr.size() > 1 && countryAr.get(1) != null) {
|
||||||
countryId = Long.parseLong(countryAr.get(1));
|
countryId = Long.parseLong(countryAr.get(1));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
addressDataObj = new AddressData(addressTypeId, street, addressLine1, addressLine2, addressLine3, city, postalCode,
|
addressDataObj = new AddressData(addressTypeId, street, addressLine1, addressLine2, addressLine3, city, postalCode,
|
||||||
isActiveAddress, stateProvinceId, countryId);
|
isActiveAddress, stateProvinceId, countryId);
|
||||||
addressList = new ArrayList<AddressData>(Arrays.asList(addressDataObj));
|
addressList = new ArrayList<>(List.of(addressDataObj));
|
||||||
}
|
}
|
||||||
return ClientData.importClientPersonInstance(legalFormId, row.getRowNum(), firstName, lastName, middleName, submittedOn,
|
return ClientData.importClientPersonInstance(legalFormId, row.getRowNum(), firstName, lastName, middleName, submittedOn,
|
||||||
activationDate, active, externalId, officeId, staffId, mobileNo, dob, clientTypeId, genderId, clientClassificationId,
|
activationDate, active, externalId, officeId, staffId, mobileNo, dob, clientTypeId, genderId, clientClassificationId,
|
||||||
@@ -185,11 +184,11 @@ public class ClientPersonImportHandler implements ImportHandler {
|
|||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public Count importEntity(String dateFormat) {
|
public Count importEntity(final Workbook workbook, final List<ClientData> clients, final String dateFormat) {
|
||||||
Sheet clientSheet = workbook.getSheet(TemplatePopulateImportConstants.CLIENT_PERSON_SHEET_NAME);
|
Sheet clientSheet = workbook.getSheet(TemplatePopulateImportConstants.CLIENT_PERSON_SHEET_NAME);
|
||||||
int successCount = 0;
|
int successCount = 0;
|
||||||
int errorCount = 0;
|
int errorCount = 0;
|
||||||
String errorMessage = "";
|
String errorMessage;
|
||||||
GsonBuilder gsonBuilder = GoogleGsonSerializerHelper.createGsonBuilder();
|
GsonBuilder gsonBuilder = GoogleGsonSerializerHelper.createGsonBuilder();
|
||||||
gsonBuilder.registerTypeAdapter(LocalDate.class, new DateSerializer(dateFormat));
|
gsonBuilder.registerTypeAdapter(LocalDate.class, new DateSerializer(dateFormat));
|
||||||
for (ClientData client : clients) {
|
for (ClientData client : clients) {
|
||||||
|
|||||||
+41
-41
@@ -58,14 +58,6 @@ import org.springframework.stereotype.Service;
|
|||||||
public class FixedDepositImportHandler implements ImportHandler {
|
public class FixedDepositImportHandler implements ImportHandler {
|
||||||
|
|
||||||
private static final Logger LOG = LoggerFactory.getLogger(FixedDepositImportHandler.class);
|
private static final Logger LOG = LoggerFactory.getLogger(FixedDepositImportHandler.class);
|
||||||
private Workbook workbook;
|
|
||||||
|
|
||||||
private List<FixedDepositAccountData> savings;
|
|
||||||
private List<SavingsApproval> approvalDates;
|
|
||||||
private List<SavingsActivation> activationDates;
|
|
||||||
private List<ClosingOfSavingsAccounts> closedOnDate;
|
|
||||||
private List<String> statuses;
|
|
||||||
|
|
||||||
private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService;
|
private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService;
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
@@ -74,25 +66,28 @@ public class FixedDepositImportHandler implements ImportHandler {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Count process(Workbook workbook, String locale, String dateFormat) {
|
public Count process(final Workbook workbook, final String locale, final String dateFormat) {
|
||||||
this.workbook = workbook;
|
|
||||||
savings = new ArrayList<>();
|
List<FixedDepositAccountData> savings = new ArrayList<>();
|
||||||
approvalDates = new ArrayList<>();
|
List<SavingsApproval> approvalDates = new ArrayList<>();
|
||||||
activationDates = new ArrayList<>();
|
List<SavingsActivation> activationDates = new ArrayList<>();
|
||||||
closedOnDate = new ArrayList<>();
|
List<ClosingOfSavingsAccounts> closedOnDates = new ArrayList<>();
|
||||||
statuses = new ArrayList<>();
|
List<String> statuses = new ArrayList<>();
|
||||||
readExcelFile(locale, dateFormat);
|
|
||||||
return importEntity(dateFormat);
|
readExcelFile(workbook, savings, approvalDates, activationDates, closedOnDates, statuses, locale, dateFormat);
|
||||||
|
return importEntity(workbook, savings, approvalDates, activationDates, closedOnDates, statuses, dateFormat);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void readExcelFile(final String locale, final String dateFormat) {
|
private void readExcelFile(final Workbook workbook, final List<FixedDepositAccountData> savings,
|
||||||
|
final List<SavingsApproval> approvalDates, final List<SavingsActivation> activationDates,
|
||||||
|
final List<ClosingOfSavingsAccounts> closedOnDate, final List<String> statuses, final String locale, final String dateFormat) {
|
||||||
Sheet savingsSheet = workbook.getSheet(TemplatePopulateImportConstants.FIXED_DEPOSIT_SHEET_NAME);
|
Sheet savingsSheet = workbook.getSheet(TemplatePopulateImportConstants.FIXED_DEPOSIT_SHEET_NAME);
|
||||||
Integer noOfEntries = ImportHandlerUtils.getNumberOfRows(savingsSheet, TemplatePopulateImportConstants.FIRST_COLUMN_INDEX);
|
Integer noOfEntries = ImportHandlerUtils.getNumberOfRows(savingsSheet, TemplatePopulateImportConstants.FIRST_COLUMN_INDEX);
|
||||||
for (int rowIndex = 1; rowIndex <= noOfEntries; rowIndex++) {
|
for (int rowIndex = 1; rowIndex <= noOfEntries; rowIndex++) {
|
||||||
Row row;
|
Row row;
|
||||||
row = savingsSheet.getRow(rowIndex);
|
row = savingsSheet.getRow(rowIndex);
|
||||||
if (ImportHandlerUtils.isNotImported(row, FixedDepositConstants.STATUS_COL)) {
|
if (ImportHandlerUtils.isNotImported(row, FixedDepositConstants.STATUS_COL)) {
|
||||||
savings.add(readSavings(row, locale, dateFormat));
|
savings.add(readSavings(workbook, statuses, row, locale, dateFormat));
|
||||||
approvalDates.add(readSavingsApproval(row, locale, dateFormat));
|
approvalDates.add(readSavingsApproval(row, locale, dateFormat));
|
||||||
activationDates.add(readSavingsActivation(row, locale, dateFormat));
|
activationDates.add(readSavingsActivation(row, locale, dateFormat));
|
||||||
closedOnDate.add(readSavingsClosed(row, locale, dateFormat));
|
closedOnDate.add(readSavingsClosed(row, locale, dateFormat));
|
||||||
@@ -131,7 +126,8 @@ public class FixedDepositImportHandler implements ImportHandler {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private FixedDepositAccountData readSavings(Row row, String locale, String dateFormat) {
|
private FixedDepositAccountData readSavings(final Workbook workbook, final List<String> statuses, final Row row, final String locale,
|
||||||
|
final String dateFormat) {
|
||||||
|
|
||||||
String productName = ImportHandlerUtils.readAsString(FixedDepositConstants.PRODUCT_COL, row);
|
String productName = ImportHandlerUtils.readAsString(FixedDepositConstants.PRODUCT_COL, row);
|
||||||
Long productId = ImportHandlerUtils.getIdByName(workbook.getSheet(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME), productName);
|
Long productId = ImportHandlerUtils.getIdByName(workbook.getSheet(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME), productName);
|
||||||
@@ -164,7 +160,7 @@ public class FixedDepositImportHandler implements ImportHandler {
|
|||||||
Long interestPostingPeriodTypeId = null;
|
Long interestPostingPeriodTypeId = null;
|
||||||
|
|
||||||
EnumOptionData interestPostingPeriodTypeEnum = null;
|
EnumOptionData interestPostingPeriodTypeEnum = null;
|
||||||
if (interestCompoundingPeriodType != null) {
|
if (interestPostingPeriodType != null) {
|
||||||
if (interestPostingPeriodType.equalsIgnoreCase(TemplatePopulateImportConstants.INTEREST_POSTING_PERIOD_MONTHLY)) {
|
if (interestPostingPeriodType.equalsIgnoreCase(TemplatePopulateImportConstants.INTEREST_POSTING_PERIOD_MONTHLY)) {
|
||||||
interestPostingPeriodTypeId = 4L;
|
interestPostingPeriodTypeId = 4L;
|
||||||
} else if (interestPostingPeriodType.equalsIgnoreCase(TemplatePopulateImportConstants.INTEREST_POSTING_PERIOD_QUARTERLY)) {
|
} else if (interestPostingPeriodType.equalsIgnoreCase(TemplatePopulateImportConstants.INTEREST_POSTING_PERIOD_QUARTERLY)) {
|
||||||
@@ -238,7 +234,7 @@ public class FixedDepositImportHandler implements ImportHandler {
|
|||||||
String externalId = ImportHandlerUtils.readAsString(FixedDepositConstants.EXTERNAL_ID_COL, row);
|
String externalId = ImportHandlerUtils.readAsString(FixedDepositConstants.EXTERNAL_ID_COL, row);
|
||||||
String clientName = ImportHandlerUtils.readAsString(FixedDepositConstants.CLIENT_NAME_COL, row);
|
String clientName = ImportHandlerUtils.readAsString(FixedDepositConstants.CLIENT_NAME_COL, row);
|
||||||
|
|
||||||
List<SavingsAccountChargeData> charges = new ArrayList<SavingsAccountChargeData>();
|
List<SavingsAccountChargeData> charges = new ArrayList<>();
|
||||||
|
|
||||||
String charge1 = ImportHandlerUtils.readAsString(FixedDepositConstants.CHARGE_ID_1, row);
|
String charge1 = ImportHandlerUtils.readAsString(FixedDepositConstants.CHARGE_ID_1, row);
|
||||||
String charge2 = ImportHandlerUtils.readAsString(FixedDepositConstants.CHARGE_ID_2, row);
|
String charge2 = ImportHandlerUtils.readAsString(FixedDepositConstants.CHARGE_ID_2, row);
|
||||||
@@ -273,7 +269,9 @@ public class FixedDepositImportHandler implements ImportHandler {
|
|||||||
depositPeriodFrequencyId, externalId, charges, row.getRowNum(), locale, dateFormat);
|
depositPeriodFrequencyId, externalId, charges, row.getRowNum(), locale, dateFormat);
|
||||||
}
|
}
|
||||||
|
|
||||||
public Count importEntity(String dateFormat) {
|
private Count importEntity(final Workbook workbook, final List<FixedDepositAccountData> savings,
|
||||||
|
final List<SavingsApproval> approvalDates, final List<SavingsActivation> activationDates,
|
||||||
|
final List<ClosingOfSavingsAccounts> closedOnDates, final List<String> statuses, String dateFormat) {
|
||||||
Sheet savingsSheet = workbook.getSheet(TemplatePopulateImportConstants.FIXED_DEPOSIT_SHEET_NAME);
|
Sheet savingsSheet = workbook.getSheet(TemplatePopulateImportConstants.FIXED_DEPOSIT_SHEET_NAME);
|
||||||
int successCount = 0;
|
int successCount = 0;
|
||||||
int errorCount = 0;
|
int errorCount = 0;
|
||||||
@@ -289,7 +287,7 @@ public class FixedDepositImportHandler implements ImportHandler {
|
|||||||
progressLevel = getProgressLevel(status);
|
progressLevel = getProgressLevel(status);
|
||||||
|
|
||||||
if (progressLevel == 0) {
|
if (progressLevel == 0) {
|
||||||
CommandProcessingResult result = importSavings(i, dateFormat);
|
CommandProcessingResult result = importSavings(savings, i, dateFormat);
|
||||||
savingsId = result.getSavingsId();
|
savingsId = result.getSavingsId();
|
||||||
progressLevel = 1;
|
progressLevel = 1;
|
||||||
} else {
|
} else {
|
||||||
@@ -298,15 +296,15 @@ public class FixedDepositImportHandler implements ImportHandler {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (progressLevel <= 1) {
|
if (progressLevel <= 1) {
|
||||||
progressLevel = importSavingsApproval(savingsId, i, dateFormat);
|
progressLevel = importSavingsApproval(approvalDates, savingsId, i, dateFormat);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (progressLevel <= 2) {
|
if (progressLevel <= 2) {
|
||||||
progressLevel = importSavingsActivation(savingsId, i, dateFormat);
|
progressLevel = importSavingsActivation(activationDates, savingsId, i, dateFormat);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (progressLevel <= 3) {
|
if (progressLevel <= 3) {
|
||||||
progressLevel = importSavingsClosing(savingsId, i, dateFormat);
|
progressLevel = importSavingsClosing(closedOnDates, savingsId, i, dateFormat);
|
||||||
}
|
}
|
||||||
|
|
||||||
successCount++;
|
successCount++;
|
||||||
@@ -316,7 +314,7 @@ public class FixedDepositImportHandler implements ImportHandler {
|
|||||||
errorCount++;
|
errorCount++;
|
||||||
LOG.error("Problem occurred in importEntity function", ex);
|
LOG.error("Problem occurred in importEntity function", ex);
|
||||||
errorMessage = ImportHandlerUtils.getErrorMessage(ex);
|
errorMessage = ImportHandlerUtils.getErrorMessage(ex);
|
||||||
writeFixedDepositErrorMessage(savingsId, errorMessage, progressLevel, statusCell, errorReportCell, row);
|
writeFixedDepositErrorMessage(workbook, savingsId, errorMessage, progressLevel, statusCell, errorReportCell, row);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -324,8 +322,8 @@ public class FixedDepositImportHandler implements ImportHandler {
|
|||||||
return Count.instance(successCount, errorCount);
|
return Count.instance(successCount, errorCount);
|
||||||
}
|
}
|
||||||
|
|
||||||
private void writeFixedDepositErrorMessage(Long savingsId, String errorMessage, int progressLevel, Cell statusCell,
|
private void writeFixedDepositErrorMessage(final Workbook workbook, final Long savingsId, final String errorMessage,
|
||||||
Cell errorReportCell, Row row) {
|
final int progressLevel, final Cell statusCell, Cell errorReportCell, Row row) {
|
||||||
String status = "";
|
String status = "";
|
||||||
if (progressLevel == 0) {
|
if (progressLevel == 0) {
|
||||||
status = TemplatePopulateImportConstants.STATUS_CREATION_FAILED;
|
status = TemplatePopulateImportConstants.STATUS_CREATION_FAILED;
|
||||||
@@ -343,21 +341,22 @@ public class FixedDepositImportHandler implements ImportHandler {
|
|||||||
errorReportCell.setCellValue(errorMessage);
|
errorReportCell.setCellValue(errorMessage);
|
||||||
}
|
}
|
||||||
|
|
||||||
private int importSavingsClosing(Long savingsId, int i, String dateFormat) {
|
private int importSavingsClosing(List<ClosingOfSavingsAccounts> closedOnDates, final Long savingsId, final int i,
|
||||||
if (closedOnDate.get(i) != null) {
|
final String dateFormat) {
|
||||||
|
if (closedOnDates.get(i) != null) {
|
||||||
GsonBuilder gsonBuilder = GoogleGsonSerializerHelper.createGsonBuilder();
|
GsonBuilder gsonBuilder = GoogleGsonSerializerHelper.createGsonBuilder();
|
||||||
gsonBuilder.registerTypeAdapter(LocalDate.class, new DateSerializer(dateFormat));
|
gsonBuilder.registerTypeAdapter(LocalDate.class, new DateSerializer(dateFormat));
|
||||||
String payload = gsonBuilder.create().toJson(closedOnDate.get(i));
|
String payload = gsonBuilder.create().toJson(closedOnDates.get(i));
|
||||||
final CommandWrapper commandRequest = new CommandWrapperBuilder() //
|
final CommandWrapper commandRequest = new CommandWrapperBuilder() //
|
||||||
.closeFixedDepositAccount(savingsId)//
|
.closeFixedDepositAccount(savingsId)//
|
||||||
.withJson(payload) //
|
.withJson(payload) //
|
||||||
.build(); //
|
.build(); //
|
||||||
final CommandProcessingResult result = commandsSourceWritePlatformService.logCommandSource(commandRequest);
|
commandsSourceWritePlatformService.logCommandSource(commandRequest);
|
||||||
}
|
}
|
||||||
return 4;
|
return 4;
|
||||||
}
|
}
|
||||||
|
|
||||||
private CommandProcessingResult importSavings(int i, String dateFormat) {
|
private CommandProcessingResult importSavings(List<FixedDepositAccountData> savings, final int i, final String dateFormat) {
|
||||||
GsonBuilder gsonBuilder = GoogleGsonSerializerHelper.createGsonBuilder();
|
GsonBuilder gsonBuilder = GoogleGsonSerializerHelper.createGsonBuilder();
|
||||||
gsonBuilder.registerTypeAdapter(LocalDate.class, new DateSerializer(dateFormat));
|
gsonBuilder.registerTypeAdapter(LocalDate.class, new DateSerializer(dateFormat));
|
||||||
gsonBuilder.registerTypeAdapter(EnumOptionData.class, new EnumOptionDataIdSerializer());
|
gsonBuilder.registerTypeAdapter(EnumOptionData.class, new EnumOptionDataIdSerializer());
|
||||||
@@ -377,11 +376,11 @@ public class FixedDepositImportHandler implements ImportHandler {
|
|||||||
.createFixedDepositAccount() //
|
.createFixedDepositAccount() //
|
||||||
.withJson(payload) //
|
.withJson(payload) //
|
||||||
.build(); //
|
.build(); //
|
||||||
final CommandProcessingResult result = commandsSourceWritePlatformService.logCommandSource(commandRequest);
|
return commandsSourceWritePlatformService.logCommandSource(commandRequest);
|
||||||
return result;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private int importSavingsApproval(Long savingsId, int i, String dateFormat) {
|
private int importSavingsApproval(final List<SavingsApproval> approvalDates, final Long savingsId, final int i,
|
||||||
|
final String dateFormat) {
|
||||||
if (approvalDates.get(i) != null) {
|
if (approvalDates.get(i) != null) {
|
||||||
GsonBuilder gsonBuilder = GoogleGsonSerializerHelper.createGsonBuilder();
|
GsonBuilder gsonBuilder = GoogleGsonSerializerHelper.createGsonBuilder();
|
||||||
gsonBuilder.registerTypeAdapter(LocalDate.class, new DateSerializer(dateFormat));
|
gsonBuilder.registerTypeAdapter(LocalDate.class, new DateSerializer(dateFormat));
|
||||||
@@ -390,12 +389,13 @@ public class FixedDepositImportHandler implements ImportHandler {
|
|||||||
.approveFixedDepositAccountApplication(savingsId)//
|
.approveFixedDepositAccountApplication(savingsId)//
|
||||||
.withJson(payload) //
|
.withJson(payload) //
|
||||||
.build(); //
|
.build(); //
|
||||||
final CommandProcessingResult result = commandsSourceWritePlatformService.logCommandSource(commandRequest);
|
commandsSourceWritePlatformService.logCommandSource(commandRequest);
|
||||||
}
|
}
|
||||||
return 2;
|
return 2;
|
||||||
}
|
}
|
||||||
|
|
||||||
private int importSavingsActivation(Long savingsId, int i, String dateFormat) {
|
private int importSavingsActivation(final List<SavingsActivation> activationDates, final Long savingsId, final int i,
|
||||||
|
final String dateFormat) {
|
||||||
if (activationDates.get(i) != null) {
|
if (activationDates.get(i) != null) {
|
||||||
GsonBuilder gsonBuilder = GoogleGsonSerializerHelper.createGsonBuilder();
|
GsonBuilder gsonBuilder = GoogleGsonSerializerHelper.createGsonBuilder();
|
||||||
gsonBuilder.registerTypeAdapter(LocalDate.class, new DateSerializer(dateFormat));
|
gsonBuilder.registerTypeAdapter(LocalDate.class, new DateSerializer(dateFormat));
|
||||||
@@ -404,7 +404,7 @@ public class FixedDepositImportHandler implements ImportHandler {
|
|||||||
.fixedDepositAccountActivation(savingsId)//
|
.fixedDepositAccountActivation(savingsId)//
|
||||||
.withJson(payload) //
|
.withJson(payload) //
|
||||||
.build(); //
|
.build(); //
|
||||||
final CommandProcessingResult result = commandsSourceWritePlatformService.logCommandSource(commandRequest);
|
commandsSourceWritePlatformService.logCommandSource(commandRequest);
|
||||||
}
|
}
|
||||||
return 3;
|
return 3;
|
||||||
}
|
}
|
||||||
|
|||||||
+29
-28
@@ -34,7 +34,6 @@ import org.apache.fineract.infrastructure.bulkimport.importhandler.ImportHandler
|
|||||||
import org.apache.fineract.infrastructure.bulkimport.importhandler.ImportHandlerUtils;
|
import org.apache.fineract.infrastructure.bulkimport.importhandler.ImportHandlerUtils;
|
||||||
import org.apache.fineract.infrastructure.bulkimport.importhandler.helper.DateSerializer;
|
import org.apache.fineract.infrastructure.bulkimport.importhandler.helper.DateSerializer;
|
||||||
import org.apache.fineract.infrastructure.bulkimport.importhandler.helper.SavingsAccountTransactionEnumValueSerialiser;
|
import org.apache.fineract.infrastructure.bulkimport.importhandler.helper.SavingsAccountTransactionEnumValueSerialiser;
|
||||||
import org.apache.fineract.infrastructure.core.data.CommandProcessingResult;
|
|
||||||
import org.apache.fineract.infrastructure.core.serialization.GoogleGsonSerializerHelper;
|
import org.apache.fineract.infrastructure.core.serialization.GoogleGsonSerializerHelper;
|
||||||
import org.apache.fineract.portfolio.savings.data.SavingsAccountTransactionData;
|
import org.apache.fineract.portfolio.savings.data.SavingsAccountTransactionData;
|
||||||
import org.apache.fineract.portfolio.savings.data.SavingsAccountTransactionEnumData;
|
import org.apache.fineract.portfolio.savings.data.SavingsAccountTransactionEnumData;
|
||||||
@@ -51,11 +50,12 @@ import org.springframework.stereotype.Service;
|
|||||||
@Service
|
@Service
|
||||||
public class FixedDepositTransactionImportHandler implements ImportHandler {
|
public class FixedDepositTransactionImportHandler implements ImportHandler {
|
||||||
|
|
||||||
|
public static final String TRANSACTION_TYPE = "transactionType";
|
||||||
|
public static final String REVERSED = "reversed";
|
||||||
|
public static final String INTERESTED_POSTED_AS_ON = "interestedPostedAsOn";
|
||||||
|
public static final String WITHDRAWAL = "Withdrawal";
|
||||||
|
public static final String DEPOSIT = "Deposit";
|
||||||
private static final Logger LOG = LoggerFactory.getLogger(FixedDepositTransactionImportHandler.class);
|
private static final Logger LOG = LoggerFactory.getLogger(FixedDepositTransactionImportHandler.class);
|
||||||
private Workbook workbook;
|
|
||||||
private List<SavingsAccountTransactionData> savingsTransactions;
|
|
||||||
private String savingsAccountId = "";
|
|
||||||
|
|
||||||
private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService;
|
private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService;
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
@@ -64,33 +64,34 @@ public class FixedDepositTransactionImportHandler implements ImportHandler {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Count process(Workbook workbook, String locale, String dateFormat) {
|
public Count process(final Workbook workbook, final String locale, final String dateFormat) {
|
||||||
this.workbook = workbook;
|
List<SavingsAccountTransactionData> savingsTransactions = readExcelFile(workbook, locale, dateFormat);
|
||||||
this.savingsTransactions = new ArrayList<>();
|
return importEntity(workbook, savingsTransactions, dateFormat);
|
||||||
readExcelFile(locale, dateFormat);
|
|
||||||
return importEntity(dateFormat);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public void readExcelFile(final String locale, final String dateFormat) {
|
public List<SavingsAccountTransactionData> readExcelFile(final Workbook workbook, final String locale, final String dateFormat) {
|
||||||
|
List<SavingsAccountTransactionData> savingsTransactions = new ArrayList<>();
|
||||||
Sheet savingsTransactionSheet = workbook.getSheet(TemplatePopulateImportConstants.FIXED_DEPOSIT_TRANSACTION_SHEET_NAME);
|
Sheet savingsTransactionSheet = workbook.getSheet(TemplatePopulateImportConstants.FIXED_DEPOSIT_TRANSACTION_SHEET_NAME);
|
||||||
Integer noOfEntries = ImportHandlerUtils.getNumberOfRows(savingsTransactionSheet, TransactionConstants.AMOUNT_COL);
|
Integer noOfEntries = ImportHandlerUtils.getNumberOfRows(savingsTransactionSheet, TransactionConstants.AMOUNT_COL);
|
||||||
|
Long savingsAccountId = null;
|
||||||
for (int rowIndex = 1; rowIndex <= noOfEntries; rowIndex++) {
|
for (int rowIndex = 1; rowIndex <= noOfEntries; rowIndex++) {
|
||||||
Row row;
|
Row row;
|
||||||
row = savingsTransactionSheet.getRow(rowIndex);
|
row = savingsTransactionSheet.getRow(rowIndex);
|
||||||
if (ImportHandlerUtils.isNotImported(row, TransactionConstants.STATUS_COL)) {
|
if (ImportHandlerUtils.isNotImported(row, TransactionConstants.STATUS_COL)) {
|
||||||
savingsTransactions.add(readSavingsTransaction(row, locale, dateFormat));
|
savingsTransactions.add(readSavingsTransaction(workbook, row, savingsAccountId, locale, dateFormat));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
return savingsTransactions;
|
||||||
}
|
}
|
||||||
|
|
||||||
private SavingsAccountTransactionData readSavingsTransaction(Row row, String locale, String dateFormat) {
|
private SavingsAccountTransactionData readSavingsTransaction(final Workbook workbook, final Row row, Long savingsAccountId,
|
||||||
String savingsAccountIdCheck = null;
|
final String locale, final String dateFormat) {
|
||||||
if (ImportHandlerUtils.readAsLong(TransactionConstants.SAVINGS_ACCOUNT_NO_COL, row) != null) {
|
|
||||||
savingsAccountIdCheck = ImportHandlerUtils.readAsLong(TransactionConstants.SAVINGS_ACCOUNT_NO_COL, row).toString();
|
Long newSavingsAccountId = ImportHandlerUtils.readAsLong(TransactionConstants.SAVINGS_ACCOUNT_NO_COL, row);
|
||||||
}
|
if (newSavingsAccountId != null) {
|
||||||
if (savingsAccountIdCheck != null) {
|
savingsAccountId = newSavingsAccountId;
|
||||||
savingsAccountId = savingsAccountIdCheck;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
String transactionType = ImportHandlerUtils.readAsString(TransactionConstants.TRANSACTION_TYPE_COL, row);
|
String transactionType = ImportHandlerUtils.readAsString(TransactionConstants.TRANSACTION_TYPE_COL, row);
|
||||||
SavingsAccountTransactionEnumData savingsAccountTransactionEnumData = new SavingsAccountTransactionEnumData(null, null,
|
SavingsAccountTransactionEnumData savingsAccountTransactionEnumData = new SavingsAccountTransactionEnumData(null, null,
|
||||||
transactionType);
|
transactionType);
|
||||||
@@ -110,12 +111,12 @@ public class FixedDepositTransactionImportHandler implements ImportHandler {
|
|||||||
String receiptNumber = ImportHandlerUtils.readAsString(TransactionConstants.RECEIPT_NO_COL, row);
|
String receiptNumber = ImportHandlerUtils.readAsString(TransactionConstants.RECEIPT_NO_COL, row);
|
||||||
String bankNumber = ImportHandlerUtils.readAsString(TransactionConstants.BANK_NO_COL, row);
|
String bankNumber = ImportHandlerUtils.readAsString(TransactionConstants.BANK_NO_COL, row);
|
||||||
return SavingsAccountTransactionData.importInstance(amount, transactionDate, paymentTypeId, accountNumber, checkNumber, routingCode,
|
return SavingsAccountTransactionData.importInstance(amount, transactionDate, paymentTypeId, accountNumber, checkNumber, routingCode,
|
||||||
receiptNumber, bankNumber, Long.parseLong(savingsAccountId), savingsAccountTransactionEnumData, row.getRowNum(), locale,
|
receiptNumber, bankNumber, savingsAccountId, savingsAccountTransactionEnumData, row.getRowNum(), locale, dateFormat);
|
||||||
dateFormat);
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public Count importEntity(String dateFormat) {
|
public Count importEntity(final Workbook workbook, final List<SavingsAccountTransactionData> savingsTransactions,
|
||||||
|
final String dateFormat) {
|
||||||
Sheet savingsTransactionSheet = workbook.getSheet(TemplatePopulateImportConstants.FIXED_DEPOSIT_TRANSACTION_SHEET_NAME);
|
Sheet savingsTransactionSheet = workbook.getSheet(TemplatePopulateImportConstants.FIXED_DEPOSIT_TRANSACTION_SHEET_NAME);
|
||||||
int successCount = 0;
|
int successCount = 0;
|
||||||
int errorCount = 0;
|
int errorCount = 0;
|
||||||
@@ -127,24 +128,24 @@ public class FixedDepositTransactionImportHandler implements ImportHandler {
|
|||||||
for (SavingsAccountTransactionData transaction : savingsTransactions) {
|
for (SavingsAccountTransactionData transaction : savingsTransactions) {
|
||||||
try {
|
try {
|
||||||
JsonObject savingsTransactionJsonob = gsonBuilder.create().toJsonTree(transaction).getAsJsonObject();
|
JsonObject savingsTransactionJsonob = gsonBuilder.create().toJsonTree(transaction).getAsJsonObject();
|
||||||
savingsTransactionJsonob.remove("transactionType");
|
savingsTransactionJsonob.remove(TRANSACTION_TYPE);
|
||||||
savingsTransactionJsonob.remove("reversed");
|
savingsTransactionJsonob.remove(REVERSED);
|
||||||
savingsTransactionJsonob.remove("interestedPostedAsOn");
|
savingsTransactionJsonob.remove(INTERESTED_POSTED_AS_ON);
|
||||||
String payload = savingsTransactionJsonob.toString();
|
String payload = savingsTransactionJsonob.toString();
|
||||||
CommandWrapper commandRequest = null;
|
CommandWrapper commandRequest = null;
|
||||||
if (transaction.getTransactionType().getValue().equals("Withdrawal")) {
|
if (transaction.getTransactionType().getValue().equals(WITHDRAWAL)) {
|
||||||
commandRequest = new CommandWrapperBuilder() //
|
commandRequest = new CommandWrapperBuilder() //
|
||||||
.fixedDepositAccountWithdrawal(transaction.getSavingsAccountId()) //
|
.fixedDepositAccountWithdrawal(transaction.getSavingsAccountId()) //
|
||||||
.withJson(payload) //
|
.withJson(payload) //
|
||||||
.build(); //
|
.build(); //
|
||||||
|
|
||||||
} else if (transaction.getTransactionType().getValue().equals("Deposit")) {
|
} else if (transaction.getTransactionType().getValue().equals(DEPOSIT)) {
|
||||||
commandRequest = new CommandWrapperBuilder() //
|
commandRequest = new CommandWrapperBuilder() //
|
||||||
.fixedDepositAccountDeposit(transaction.getSavingsAccountId()) //
|
.fixedDepositAccountDeposit(transaction.getSavingsAccountId()) //
|
||||||
.withJson(payload) //
|
.withJson(payload) //
|
||||||
.build();
|
.build();
|
||||||
}
|
}
|
||||||
final CommandProcessingResult result = commandsSourceWritePlatformService.logCommandSource(commandRequest);
|
commandsSourceWritePlatformService.logCommandSource(commandRequest);
|
||||||
successCount++;
|
successCount++;
|
||||||
Cell statusCell = savingsTransactionSheet.getRow(transaction.getRowIndex()).createCell(TransactionConstants.STATUS_COL);
|
Cell statusCell = savingsTransactionSheet.getRow(transaction.getRowIndex()).createCell(TransactionConstants.STATUS_COL);
|
||||||
statusCell.setCellValue(TemplatePopulateImportConstants.STATUS_CELL_IMPORTED);
|
statusCell.setCellValue(TemplatePopulateImportConstants.STATUS_CELL_IMPORTED);
|
||||||
|
|||||||
+29
-27
@@ -25,6 +25,7 @@ import java.time.LocalDate;
|
|||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.Collection;
|
import java.util.Collection;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.Objects;
|
||||||
import org.apache.fineract.commands.domain.CommandWrapper;
|
import org.apache.fineract.commands.domain.CommandWrapper;
|
||||||
import org.apache.fineract.commands.service.CommandWrapperBuilder;
|
import org.apache.fineract.commands.service.CommandWrapperBuilder;
|
||||||
import org.apache.fineract.commands.service.IdempotencyKeyGenerator;
|
import org.apache.fineract.commands.service.IdempotencyKeyGenerator;
|
||||||
@@ -57,10 +58,6 @@ import org.springframework.stereotype.Service;
|
|||||||
public class GroupImportHandler implements ImportHandler {
|
public class GroupImportHandler implements ImportHandler {
|
||||||
|
|
||||||
private static final Logger LOG = LoggerFactory.getLogger(GroupImportHandler.class);
|
private static final Logger LOG = LoggerFactory.getLogger(GroupImportHandler.class);
|
||||||
private List<GroupGeneralData> groups;
|
|
||||||
private List<CalendarData> meetings;
|
|
||||||
private Workbook workbook;
|
|
||||||
private List<String> statuses;
|
|
||||||
|
|
||||||
private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService;
|
private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService;
|
||||||
private final IdempotencyKeyGenerator idempotencyKeyGenerator;
|
private final IdempotencyKeyGenerator idempotencyKeyGenerator;
|
||||||
@@ -73,23 +70,24 @@ public class GroupImportHandler implements ImportHandler {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Count process(Workbook workbook, String locale, String dateFormat) {
|
public Count process(final Workbook workbook, final String locale, final String dateFormat) {
|
||||||
this.workbook = workbook;
|
|
||||||
groups = new ArrayList<>();
|
List<GroupGeneralData> groups = new ArrayList<>();
|
||||||
meetings = new ArrayList<>();
|
List<CalendarData> meetings = new ArrayList<>();
|
||||||
statuses = new ArrayList<>();
|
List<String> statuses = new ArrayList<>();
|
||||||
readExcelFile(locale, dateFormat);
|
readExcelFile(workbook, groups, meetings, statuses, locale, dateFormat);
|
||||||
return importEntity(dateFormat);
|
return importEntity(workbook, groups, meetings, statuses, dateFormat);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void readExcelFile(String locale, String dateFormat) {
|
private void readExcelFile(final Workbook workbook, final List<GroupGeneralData> groups, final List<CalendarData> meetings,
|
||||||
|
final List<String> statuses, final String locale, final String dateFormat) {
|
||||||
Sheet groupsSheet = workbook.getSheet(TemplatePopulateImportConstants.GROUP_SHEET_NAME);
|
Sheet groupsSheet = workbook.getSheet(TemplatePopulateImportConstants.GROUP_SHEET_NAME);
|
||||||
Integer noOfEntries = ImportHandlerUtils.getNumberOfRows(groupsSheet, TemplatePopulateImportConstants.FIRST_COLUMN_INDEX);
|
Integer noOfEntries = ImportHandlerUtils.getNumberOfRows(groupsSheet, TemplatePopulateImportConstants.FIRST_COLUMN_INDEX);
|
||||||
for (int rowIndex = 1; rowIndex <= noOfEntries; rowIndex++) {
|
for (int rowIndex = 1; rowIndex <= noOfEntries; rowIndex++) {
|
||||||
Row row;
|
Row row;
|
||||||
row = groupsSheet.getRow(rowIndex);
|
row = groupsSheet.getRow(rowIndex);
|
||||||
if (ImportHandlerUtils.isNotImported(row, GroupConstants.STATUS_COL)) {
|
if (ImportHandlerUtils.isNotImported(row, GroupConstants.STATUS_COL)) {
|
||||||
groups.add(readGroup(row, locale, dateFormat));
|
groups.add(readGroup(workbook, row, statuses, locale, dateFormat));
|
||||||
meetings.add(readMeeting(row, locale, dateFormat));
|
meetings.add(readMeeting(row, locale, dateFormat));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -116,7 +114,8 @@ public class GroupImportHandler implements ImportHandler {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private GroupGeneralData readGroup(Row row, String locale, String dateFormat) {
|
private GroupGeneralData readGroup(final Workbook workbook, final Row row, final List<String> statuses, final String locale,
|
||||||
|
final String dateFormat) {
|
||||||
String status = ImportHandlerUtils.readAsString(GroupConstants.STATUS_COL, row);
|
String status = ImportHandlerUtils.readAsString(GroupConstants.STATUS_COL, row);
|
||||||
String officeName = ImportHandlerUtils.readAsString(GroupConstants.OFFICE_NAME_COL, row);
|
String officeName = ImportHandlerUtils.readAsString(GroupConstants.OFFICE_NAME_COL, row);
|
||||||
Long officeId = ImportHandlerUtils.getIdByName(workbook.getSheet(TemplatePopulateImportConstants.OFFICE_SHEET_NAME), officeName);
|
Long officeId = ImportHandlerUtils.getIdByName(workbook.getSheet(TemplatePopulateImportConstants.OFFICE_SHEET_NAME), officeName);
|
||||||
@@ -167,7 +166,8 @@ public class GroupImportHandler implements ImportHandler {
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
public Count importEntity(String dateFormat) {
|
private Count importEntity(final Workbook workbook, final List<GroupGeneralData> groups, final List<CalendarData> meetings,
|
||||||
|
final List<String> statuses, final String dateFormat) {
|
||||||
Sheet groupSheet = workbook.getSheet(TemplatePopulateImportConstants.GROUP_SHEET_NAME);
|
Sheet groupSheet = workbook.getSheet(TemplatePopulateImportConstants.GROUP_SHEET_NAME);
|
||||||
int successCount = 0;
|
int successCount = 0;
|
||||||
int errorCount = 0;
|
int errorCount = 0;
|
||||||
@@ -184,16 +184,17 @@ public class GroupImportHandler implements ImportHandler {
|
|||||||
progressLevel = getProgressLevel(status);
|
progressLevel = getProgressLevel(status);
|
||||||
|
|
||||||
if (progressLevel == 0) {
|
if (progressLevel == 0) {
|
||||||
result = importGroup(i, dateFormat);
|
result = importGroup(groups, i, dateFormat);
|
||||||
groupId = result.getGroupId().toString();
|
groupId = result.getGroupId().toString();
|
||||||
progressLevel = 1;
|
progressLevel = 1;
|
||||||
} else {
|
} else {
|
||||||
groupId = ImportHandlerUtils.readAsInt(GroupConstants.GROUP_ID_COL, groupSheet.getRow(groups.get(i).getRowIndex()))
|
groupId = Objects.requireNonNull(
|
||||||
|
ImportHandlerUtils.readAsInt(GroupConstants.GROUP_ID_COL, groupSheet.getRow(groups.get(i).getRowIndex())))
|
||||||
.toString();
|
.toString();
|
||||||
}
|
}
|
||||||
|
|
||||||
if (meetings.get(i) != null && groups.get(i).getCenterId() == null) {
|
if (meetings.get(i) != null && groups.get(i).getCenterId() == null) {
|
||||||
progressLevel = importGroupMeeting(result, i, dateFormat);
|
progressLevel = importGroupMeeting(meetings, Objects.requireNonNull(result), i, dateFormat);
|
||||||
}
|
}
|
||||||
|
|
||||||
statusCell.setCellValue(TemplatePopulateImportConstants.STATUS_CELL_IMPORTED);
|
statusCell.setCellValue(TemplatePopulateImportConstants.STATUS_CELL_IMPORTED);
|
||||||
@@ -202,15 +203,15 @@ public class GroupImportHandler implements ImportHandler {
|
|||||||
errorCount++;
|
errorCount++;
|
||||||
LOG.error("Problem occurred in importEntity function", ex);
|
LOG.error("Problem occurred in importEntity function", ex);
|
||||||
errorMessage = ImportHandlerUtils.getErrorMessage(ex);
|
errorMessage = ImportHandlerUtils.getErrorMessage(ex);
|
||||||
writeGroupErrorMessage(groupId, errorMessage, progressLevel, statusCell, errorReportCell, row);
|
writeGroupErrorMessage(workbook, groupId, errorMessage, progressLevel, statusCell, errorReportCell, row);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
setReportHeaders(groupSheet);
|
setReportHeaders(groupSheet);
|
||||||
return Count.instance(successCount, errorCount);
|
return Count.instance(successCount, errorCount);
|
||||||
}
|
}
|
||||||
|
|
||||||
private void writeGroupErrorMessage(String groupId, String errorMessage, int progressLevel, Cell statusCell, Cell errorReportCell,
|
private void writeGroupErrorMessage(final Workbook workbook, final String groupId, final String errorMessage, final int progressLevel,
|
||||||
Row row) {
|
final Cell statusCell, final Cell errorReportCell, final Row row) {
|
||||||
String status = "";
|
String status = "";
|
||||||
if (progressLevel == 0) {
|
if (progressLevel == 0) {
|
||||||
status = TemplatePopulateImportConstants.STATUS_CREATION_FAILED;
|
status = TemplatePopulateImportConstants.STATUS_CREATION_FAILED;
|
||||||
@@ -235,7 +236,7 @@ public class GroupImportHandler implements ImportHandler {
|
|||||||
TemplatePopulateImportConstants.FAILURE_COL_REPORT_HEADER);
|
TemplatePopulateImportConstants.FAILURE_COL_REPORT_HEADER);
|
||||||
}
|
}
|
||||||
|
|
||||||
private Integer importGroupMeeting(CommandProcessingResult result, int rowIndex, String dateFormat) {
|
private Integer importGroupMeeting(final List<CalendarData> meetings, CommandProcessingResult result, int rowIndex, String dateFormat) {
|
||||||
CalendarData calendarData = meetings.get(rowIndex);
|
CalendarData calendarData = meetings.get(rowIndex);
|
||||||
calendarData.setTitle("group_" + result.getGroupId().toString() + "_CollectionMeeting");
|
calendarData.setTitle("group_" + result.getGroupId().toString() + "_CollectionMeeting");
|
||||||
GsonBuilder gsonBuilder = GoogleGsonSerializerHelper.createGsonBuilder();
|
GsonBuilder gsonBuilder = GoogleGsonSerializerHelper.createGsonBuilder();
|
||||||
@@ -250,22 +251,23 @@ public class GroupImportHandler implements ImportHandler {
|
|||||||
.createCalendar(commandWrapper, TemplatePopulateImportConstants.CENTER_ENTITY_TYPE, result.getGroupId()) //
|
.createCalendar(commandWrapper, TemplatePopulateImportConstants.CENTER_ENTITY_TYPE, result.getGroupId()) //
|
||||||
.withJson(payload) //
|
.withJson(payload) //
|
||||||
.build(); //
|
.build(); //
|
||||||
final CommandProcessingResult meetingresult = commandsSourceWritePlatformService.logCommandSource(commandRequest);
|
commandsSourceWritePlatformService.logCommandSource(commandRequest);
|
||||||
return 2;
|
return 2;
|
||||||
}
|
}
|
||||||
|
|
||||||
private CommandProcessingResult importGroup(int rowIndex, String dateFormat) {
|
private CommandProcessingResult importGroup(final List<GroupGeneralData> groups, final int rowIndex, final String dateFormat) {
|
||||||
GsonBuilder gsonBuilder = GoogleGsonSerializerHelper.createGsonBuilder();
|
GsonBuilder gsonBuilder = GoogleGsonSerializerHelper.createGsonBuilder();
|
||||||
gsonBuilder.registerTypeAdapter(LocalDate.class, new DateSerializer(dateFormat));
|
gsonBuilder.registerTypeAdapter(LocalDate.class, new DateSerializer(dateFormat));
|
||||||
Type clientCollectionType = new TypeToken<Collection<ClientData>>() {}.getType();
|
Type clientCollectionType = new TypeToken<Collection<ClientData>>() {
|
||||||
|
|
||||||
|
}.getType();
|
||||||
gsonBuilder.registerTypeAdapter(clientCollectionType, new ClientIdSerializer());
|
gsonBuilder.registerTypeAdapter(clientCollectionType, new ClientIdSerializer());
|
||||||
String payload = gsonBuilder.create().toJson(groups.get(rowIndex));
|
String payload = gsonBuilder.create().toJson(groups.get(rowIndex));
|
||||||
final CommandWrapper commandRequest = new CommandWrapperBuilder() //
|
final CommandWrapper commandRequest = new CommandWrapperBuilder() //
|
||||||
.createGroup() //
|
.createGroup() //
|
||||||
.withJson(payload) //
|
.withJson(payload) //
|
||||||
.build(); //
|
.build(); //
|
||||||
final CommandProcessingResult result = commandsSourceWritePlatformService.logCommandSource(commandRequest);
|
return commandsSourceWritePlatformService.logCommandSource(commandRequest);
|
||||||
return result;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private int getProgressLevel(String status) {
|
private int getProgressLevel(String status) {
|
||||||
|
|||||||
+15
-18
@@ -34,7 +34,6 @@ import org.apache.fineract.infrastructure.bulkimport.data.Count;
|
|||||||
import org.apache.fineract.infrastructure.bulkimport.importhandler.ImportHandler;
|
import org.apache.fineract.infrastructure.bulkimport.importhandler.ImportHandler;
|
||||||
import org.apache.fineract.infrastructure.bulkimport.importhandler.ImportHandlerUtils;
|
import org.apache.fineract.infrastructure.bulkimport.importhandler.ImportHandlerUtils;
|
||||||
import org.apache.fineract.infrastructure.bulkimport.importhandler.helper.DateSerializer;
|
import org.apache.fineract.infrastructure.bulkimport.importhandler.helper.DateSerializer;
|
||||||
import org.apache.fineract.infrastructure.core.data.CommandProcessingResult;
|
|
||||||
import org.apache.fineract.infrastructure.core.serialization.GoogleGsonSerializerHelper;
|
import org.apache.fineract.infrastructure.core.serialization.GoogleGsonSerializerHelper;
|
||||||
import org.apache.fineract.portfolio.loanaccount.guarantor.data.GuarantorData;
|
import org.apache.fineract.portfolio.loanaccount.guarantor.data.GuarantorData;
|
||||||
import org.apache.poi.ss.usermodel.Cell;
|
import org.apache.poi.ss.usermodel.Cell;
|
||||||
@@ -50,11 +49,8 @@ import org.springframework.stereotype.Service;
|
|||||||
@Service
|
@Service
|
||||||
public class GuarantorImportHandler implements ImportHandler {
|
public class GuarantorImportHandler implements ImportHandler {
|
||||||
|
|
||||||
|
public static final String SEPARATOR = "-";
|
||||||
private static final Logger LOG = LoggerFactory.getLogger(GuarantorImportHandler.class);
|
private static final Logger LOG = LoggerFactory.getLogger(GuarantorImportHandler.class);
|
||||||
private Workbook workbook;
|
|
||||||
private List<GuarantorData> guarantors;
|
|
||||||
private Long loanAccountId;
|
|
||||||
|
|
||||||
private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService;
|
private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService;
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
@@ -63,30 +59,31 @@ public class GuarantorImportHandler implements ImportHandler {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Count process(Workbook workbook, String locale, String dateFormat) {
|
public Count process(final Workbook workbook, final String locale, final String dateFormat) {
|
||||||
this.workbook = workbook;
|
List<GuarantorData> guarantors = readExcelFile(workbook, locale, dateFormat);
|
||||||
this.guarantors = new ArrayList<>();
|
return importEntity(workbook, guarantors, dateFormat);
|
||||||
readExcelFile(locale, dateFormat);
|
|
||||||
return importEntity(dateFormat);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public void readExcelFile(final String locale, final String dateFormat) {
|
private List<GuarantorData> readExcelFile(final Workbook workbook, final String locale, final String dateFormat) {
|
||||||
|
List<GuarantorData> guarantors = new ArrayList<>();
|
||||||
Sheet addGuarantorSheet = workbook.getSheet(TemplatePopulateImportConstants.GUARANTOR_SHEET_NAME);
|
Sheet addGuarantorSheet = workbook.getSheet(TemplatePopulateImportConstants.GUARANTOR_SHEET_NAME);
|
||||||
Integer noOfEntries = ImportHandlerUtils.getNumberOfRows(addGuarantorSheet, GuarantorConstants.LOAN_ACCOUNT_NO_COL);
|
Integer noOfEntries = ImportHandlerUtils.getNumberOfRows(addGuarantorSheet, GuarantorConstants.LOAN_ACCOUNT_NO_COL);
|
||||||
|
Long loanAccountId = null;
|
||||||
for (int rowIndex = 1; rowIndex <= noOfEntries; rowIndex++) {
|
for (int rowIndex = 1; rowIndex <= noOfEntries; rowIndex++) {
|
||||||
Row row;
|
Row row;
|
||||||
row = addGuarantorSheet.getRow(rowIndex);
|
row = addGuarantorSheet.getRow(rowIndex);
|
||||||
if (ImportHandlerUtils.isNotImported(row, GuarantorConstants.STATUS_COL)) {
|
if (ImportHandlerUtils.isNotImported(row, GuarantorConstants.STATUS_COL)) {
|
||||||
guarantors.add(readGuarantor(row, locale, dateFormat));
|
guarantors.add(readGuarantor(workbook, row, loanAccountId, locale, dateFormat));
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
return guarantors;
|
||||||
}
|
}
|
||||||
|
|
||||||
private GuarantorData readGuarantor(Row row, String locale, String dateFormat) {
|
private GuarantorData readGuarantor(final Workbook workbook, final Row row, Long loanAccountId, final String locale,
|
||||||
|
final String dateFormat) {
|
||||||
String loanaccountInfo = ImportHandlerUtils.readAsString(GuarantorConstants.LOAN_ACCOUNT_NO_COL, row);
|
String loanaccountInfo = ImportHandlerUtils.readAsString(GuarantorConstants.LOAN_ACCOUNT_NO_COL, row);
|
||||||
if (loanaccountInfo != null) {
|
if (loanaccountInfo != null) {
|
||||||
List<String> loanAccountAr = Splitter.on('-').splitToList(loanaccountInfo);
|
List<String> loanAccountAr = Splitter.on(SEPARATOR).splitToList(loanaccountInfo);
|
||||||
loanAccountId = Long.parseLong(loanAccountAr.get(0));
|
loanAccountId = Long.parseLong(loanAccountAr.get(0));
|
||||||
}
|
}
|
||||||
String guarantorType = ImportHandlerUtils.readAsString(GuarantorConstants.GUARANTO_TYPE_COL, row);
|
String guarantorType = ImportHandlerUtils.readAsString(GuarantorConstants.GUARANTO_TYPE_COL, row);
|
||||||
@@ -104,7 +101,7 @@ public class GuarantorImportHandler implements ImportHandler {
|
|||||||
String clientRelationshipTypeInfo = ImportHandlerUtils.readAsString(GuarantorConstants.CLIENT_RELATIONSHIP_TYPE_COL, row);
|
String clientRelationshipTypeInfo = ImportHandlerUtils.readAsString(GuarantorConstants.CLIENT_RELATIONSHIP_TYPE_COL, row);
|
||||||
Integer clientRelationshipTypeId = null;
|
Integer clientRelationshipTypeId = null;
|
||||||
if (clientRelationshipTypeInfo != null) {
|
if (clientRelationshipTypeInfo != null) {
|
||||||
List<String> clientRelationshipTypeAr = Splitter.on('-').splitToList(clientRelationshipTypeInfo);
|
List<String> clientRelationshipTypeAr = Splitter.on(SEPARATOR).splitToList(clientRelationshipTypeInfo);
|
||||||
clientRelationshipTypeId = Integer.parseInt(clientRelationshipTypeAr.get(1));
|
clientRelationshipTypeId = Integer.parseInt(clientRelationshipTypeAr.get(1));
|
||||||
}
|
}
|
||||||
String firstname = ImportHandlerUtils.readAsString(GuarantorConstants.FIRST_NAME_COL, row);
|
String firstname = ImportHandlerUtils.readAsString(GuarantorConstants.FIRST_NAME_COL, row);
|
||||||
@@ -121,7 +118,7 @@ public class GuarantorImportHandler implements ImportHandler {
|
|||||||
addressLine2, city, dob, zip, savingsId, amount, row.getRowNum(), loanAccountId, locale, dateFormat);
|
addressLine2, city, dob, zip, savingsId, amount, row.getRowNum(), loanAccountId, locale, dateFormat);
|
||||||
}
|
}
|
||||||
|
|
||||||
public Count importEntity(String dateFormat) {
|
private Count importEntity(final Workbook workbook, final List<GuarantorData> guarantors, final String dateFormat) {
|
||||||
Sheet addGuarantorSheet = workbook.getSheet(TemplatePopulateImportConstants.GUARANTOR_SHEET_NAME);
|
Sheet addGuarantorSheet = workbook.getSheet(TemplatePopulateImportConstants.GUARANTOR_SHEET_NAME);
|
||||||
int successCount = 0;
|
int successCount = 0;
|
||||||
int errorCount = 0;
|
int errorCount = 0;
|
||||||
@@ -137,7 +134,7 @@ public class GuarantorImportHandler implements ImportHandler {
|
|||||||
.createGuarantor(guarantor.getAccountId()) //
|
.createGuarantor(guarantor.getAccountId()) //
|
||||||
.withJson(payload) //
|
.withJson(payload) //
|
||||||
.build(); //
|
.build(); //
|
||||||
final CommandProcessingResult result = commandsSourceWritePlatformService.logCommandSource(commandRequest);
|
commandsSourceWritePlatformService.logCommandSource(commandRequest);
|
||||||
successCount++;
|
successCount++;
|
||||||
Cell statusCell = addGuarantorSheet.getRow(guarantor.getRowIndex()).createCell(GuarantorConstants.STATUS_COL);
|
Cell statusCell = addGuarantorSheet.getRow(guarantor.getRowIndex()).createCell(GuarantorConstants.STATUS_COL);
|
||||||
statusCell.setCellValue(TemplatePopulateImportConstants.STATUS_CELL_IMPORTED);
|
statusCell.setCellValue(TemplatePopulateImportConstants.STATUS_CELL_IMPORTED);
|
||||||
|
|||||||
+20
-28
@@ -35,7 +35,6 @@ import org.apache.fineract.infrastructure.bulkimport.importhandler.ImportHandler
|
|||||||
import org.apache.fineract.infrastructure.bulkimport.importhandler.ImportHandlerUtils;
|
import org.apache.fineract.infrastructure.bulkimport.importhandler.ImportHandlerUtils;
|
||||||
import org.apache.fineract.infrastructure.bulkimport.importhandler.helper.CurrencyDateCodeSerializer;
|
import org.apache.fineract.infrastructure.bulkimport.importhandler.helper.CurrencyDateCodeSerializer;
|
||||||
import org.apache.fineract.infrastructure.bulkimport.importhandler.helper.DateSerializer;
|
import org.apache.fineract.infrastructure.bulkimport.importhandler.helper.DateSerializer;
|
||||||
import org.apache.fineract.infrastructure.core.data.CommandProcessingResult;
|
|
||||||
import org.apache.fineract.infrastructure.core.serialization.GoogleGsonSerializerHelper;
|
import org.apache.fineract.infrastructure.core.serialization.GoogleGsonSerializerHelper;
|
||||||
import org.apache.fineract.organisation.monetary.data.CurrencyData;
|
import org.apache.fineract.organisation.monetary.data.CurrencyData;
|
||||||
import org.apache.poi.ss.usermodel.Cell;
|
import org.apache.poi.ss.usermodel.Cell;
|
||||||
@@ -52,12 +51,6 @@ import org.springframework.stereotype.Service;
|
|||||||
public class JournalEntriesImportHandler implements ImportHandler {
|
public class JournalEntriesImportHandler implements ImportHandler {
|
||||||
|
|
||||||
private static final Logger LOG = LoggerFactory.getLogger(JournalEntriesImportHandler.class);
|
private static final Logger LOG = LoggerFactory.getLogger(JournalEntriesImportHandler.class);
|
||||||
private Workbook workbook;
|
|
||||||
private List<JournalEntryData> gltransaction;
|
|
||||||
private LocalDate transactionDate;
|
|
||||||
|
|
||||||
List<CreditDebit> credits = new ArrayList<>();
|
|
||||||
List<CreditDebit> debits = new ArrayList<>();
|
|
||||||
|
|
||||||
private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService;
|
private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService;
|
||||||
|
|
||||||
@@ -67,17 +60,18 @@ public class JournalEntriesImportHandler implements ImportHandler {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Count process(Workbook workbook, String locale, String dateFormat) {
|
public Count process(final Workbook workbook, final String locale, final String dateFormat) {
|
||||||
this.workbook = workbook;
|
|
||||||
gltransaction = new ArrayList<>();
|
List<JournalEntryData> glTransactions = readExcelFile(workbook, locale, dateFormat);
|
||||||
readExcelFile(locale, dateFormat);
|
return importEntity(workbook, glTransactions, dateFormat);
|
||||||
return importEntity(dateFormat);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public void readExcelFile(final String locale, final String dateFormat) {
|
private List<JournalEntryData> readExcelFile(final Workbook workbook, final String locale, final String dateFormat) {
|
||||||
|
List<JournalEntryData> glTransactions = new ArrayList<>();
|
||||||
String currentTransactionId = null;
|
String currentTransactionId = null;
|
||||||
String prevTransactionId = null;
|
String prevTransactionId = null;
|
||||||
JournalEntryData journalEntry = null;
|
JournalEntryData journalEntry = null;
|
||||||
|
LocalDate transactionDate = null;
|
||||||
|
|
||||||
Sheet addJournalEntriesSheet = workbook.getSheet(TemplatePopulateImportConstants.JOURNAL_ENTRY_SHEET_NAME);
|
Sheet addJournalEntriesSheet = workbook.getSheet(TemplatePopulateImportConstants.JOURNAL_ENTRY_SHEET_NAME);
|
||||||
Integer noOfEntries = ImportHandlerUtils.getNumberOfRows(addJournalEntriesSheet, 4);
|
Integer noOfEntries = ImportHandlerUtils.getNumberOfRows(addJournalEntriesSheet, 4);
|
||||||
@@ -120,22 +114,20 @@ public class JournalEntriesImportHandler implements ImportHandler {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
|
|
||||||
if (journalEntry != null) {
|
if (journalEntry != null) {
|
||||||
gltransaction.add(journalEntry);
|
glTransactions.add(journalEntry);
|
||||||
journalEntry = null;
|
|
||||||
}
|
}
|
||||||
|
journalEntry = readAddJournalEntries(workbook, row, transactionDate, locale, dateFormat);
|
||||||
journalEntry = readAddJournalEntries(row, locale, dateFormat);
|
|
||||||
|
|
||||||
}
|
}
|
||||||
prevTransactionId = currentTransactionId;
|
prevTransactionId = currentTransactionId;
|
||||||
}
|
}
|
||||||
// Adding last JE
|
// Adding last JE
|
||||||
gltransaction.add(journalEntry);
|
glTransactions.add(journalEntry);
|
||||||
|
return glTransactions;
|
||||||
}
|
}
|
||||||
|
|
||||||
private JournalEntryData readAddJournalEntries(Row row, String locale, String dateFormat) {
|
private JournalEntryData readAddJournalEntries(final Workbook workbook, final Row row, LocalDate transactionDate, final String locale,
|
||||||
|
final String dateFormat) {
|
||||||
LocalDate transactionDateCheck = ImportHandlerUtils.readAsDate(JournalEntryConstants.TRANSACION_ON_DATE_COL, row);
|
LocalDate transactionDateCheck = ImportHandlerUtils.readAsDate(JournalEntryConstants.TRANSACION_ON_DATE_COL, row);
|
||||||
if (transactionDateCheck != null) {
|
if (transactionDateCheck != null) {
|
||||||
transactionDate = transactionDateCheck;
|
transactionDate = transactionDateCheck;
|
||||||
@@ -147,8 +139,8 @@ public class JournalEntriesImportHandler implements ImportHandler {
|
|||||||
Long paymentTypeId = ImportHandlerUtils.getIdByName(workbook.getSheet(TemplatePopulateImportConstants.EXTRAS_SHEET_NAME),
|
Long paymentTypeId = ImportHandlerUtils.getIdByName(workbook.getSheet(TemplatePopulateImportConstants.EXTRAS_SHEET_NAME),
|
||||||
paymentType);
|
paymentType);
|
||||||
String currencyName = ImportHandlerUtils.readAsString(JournalEntryConstants.CURRENCY_NAME_COL, row);
|
String currencyName = ImportHandlerUtils.readAsString(JournalEntryConstants.CURRENCY_NAME_COL, row);
|
||||||
String currencyCode = ImportHandlerUtils
|
String currencyCode = ImportHandlerUtils.getCodeByName(workbook.getSheet(TemplatePopulateImportConstants.EXTRAS_SHEET_NAME),
|
||||||
.getCodeByName(workbook.getSheet(TemplatePopulateImportConstants.EXTRAS_SHEET_NAME), currencyName).toString();
|
currencyName);
|
||||||
String glAccountNameCredit = ImportHandlerUtils.readAsString(JournalEntryConstants.GL_ACCOUNT_ID_CREDIT_COL, row);
|
String glAccountNameCredit = ImportHandlerUtils.readAsString(JournalEntryConstants.GL_ACCOUNT_ID_CREDIT_COL, row);
|
||||||
Long glAccountIdCredit = ImportHandlerUtils.getIdByName(workbook.getSheet(TemplatePopulateImportConstants.GL_ACCOUNTS_SHEET_NAME),
|
Long glAccountIdCredit = ImportHandlerUtils.getIdByName(workbook.getSheet(TemplatePopulateImportConstants.GL_ACCOUNTS_SHEET_NAME),
|
||||||
glAccountNameCredit);
|
glAccountNameCredit);
|
||||||
@@ -156,8 +148,8 @@ public class JournalEntriesImportHandler implements ImportHandler {
|
|||||||
Long glAccountIdDebit = ImportHandlerUtils.getIdByName(workbook.getSheet(TemplatePopulateImportConstants.GL_ACCOUNTS_SHEET_NAME),
|
Long glAccountIdDebit = ImportHandlerUtils.getIdByName(workbook.getSheet(TemplatePopulateImportConstants.GL_ACCOUNTS_SHEET_NAME),
|
||||||
glAccountNameDebit);
|
glAccountNameDebit);
|
||||||
|
|
||||||
credits = new ArrayList<>();
|
List<CreditDebit> credits = new ArrayList<>();
|
||||||
debits = new ArrayList<>();
|
List<CreditDebit> debits = new ArrayList<>();
|
||||||
|
|
||||||
// String credit =
|
// String credit =
|
||||||
// readAsString(JournalEntryConstants.GL_ACCOUNT_ID_CREDIT_COL, row);
|
// readAsString(JournalEntryConstants.GL_ACCOUNT_ID_CREDIT_COL, row);
|
||||||
@@ -193,7 +185,7 @@ public class JournalEntriesImportHandler implements ImportHandler {
|
|||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public Count importEntity(String dateFormat) {
|
private Count importEntity(final Workbook workbook, final List<JournalEntryData> glTransactions, String dateFormat) {
|
||||||
Sheet addJournalEntriesSheet = workbook.getSheet(TemplatePopulateImportConstants.JOURNAL_ENTRY_SHEET_NAME);
|
Sheet addJournalEntriesSheet = workbook.getSheet(TemplatePopulateImportConstants.JOURNAL_ENTRY_SHEET_NAME);
|
||||||
int successCount = 0;
|
int successCount = 0;
|
||||||
int errorCount = 0;
|
int errorCount = 0;
|
||||||
@@ -202,14 +194,14 @@ public class JournalEntriesImportHandler implements ImportHandler {
|
|||||||
gsonBuilder.registerTypeAdapter(LocalDate.class, new DateSerializer(dateFormat));
|
gsonBuilder.registerTypeAdapter(LocalDate.class, new DateSerializer(dateFormat));
|
||||||
gsonBuilder.registerTypeAdapter(CurrencyData.class, new CurrencyDateCodeSerializer());
|
gsonBuilder.registerTypeAdapter(CurrencyData.class, new CurrencyDateCodeSerializer());
|
||||||
|
|
||||||
for (JournalEntryData transaction : gltransaction) {
|
for (JournalEntryData transaction : glTransactions) {
|
||||||
try {
|
try {
|
||||||
String payload = gsonBuilder.create().toJson(transaction);
|
String payload = gsonBuilder.create().toJson(transaction);
|
||||||
final CommandWrapper commandRequest = new CommandWrapperBuilder() //
|
final CommandWrapper commandRequest = new CommandWrapperBuilder() //
|
||||||
.createJournalEntry() //
|
.createJournalEntry() //
|
||||||
.withJson(payload) //
|
.withJson(payload) //
|
||||||
.build(); //
|
.build(); //
|
||||||
final CommandProcessingResult result = commandsSourceWritePlatformService.logCommandSource(commandRequest);
|
commandsSourceWritePlatformService.logCommandSource(commandRequest);
|
||||||
successCount++;
|
successCount++;
|
||||||
Cell statusCell = addJournalEntriesSheet.getRow(transaction.getRowIndex()).createCell(JournalEntryConstants.STATUS_COL);
|
Cell statusCell = addJournalEntriesSheet.getRow(transaction.getRowIndex()).createCell(JournalEntryConstants.STATUS_COL);
|
||||||
statusCell.setCellValue(TemplatePopulateImportConstants.STATUS_CELL_IMPORTED);
|
statusCell.setCellValue(TemplatePopulateImportConstants.STATUS_CELL_IMPORTED);
|
||||||
|
|||||||
+48
-47
@@ -27,6 +27,7 @@ import java.time.LocalDate;
|
|||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Locale;
|
import java.util.Locale;
|
||||||
|
import java.util.Objects;
|
||||||
import org.apache.fineract.commands.domain.CommandWrapper;
|
import org.apache.fineract.commands.domain.CommandWrapper;
|
||||||
import org.apache.fineract.commands.service.CommandWrapperBuilder;
|
import org.apache.fineract.commands.service.CommandWrapperBuilder;
|
||||||
import org.apache.fineract.commands.service.PortfolioCommandSourceWritePlatformService;
|
import org.apache.fineract.commands.service.PortfolioCommandSourceWritePlatformService;
|
||||||
@@ -61,14 +62,8 @@ import org.springframework.stereotype.Service;
|
|||||||
@Service
|
@Service
|
||||||
public class LoanImportHandler implements ImportHandler {
|
public class LoanImportHandler implements ImportHandler {
|
||||||
|
|
||||||
|
public static final String EMPTY_STR = "";
|
||||||
private static final Logger LOG = LoggerFactory.getLogger(LoanImportHandler.class);
|
private static final Logger LOG = LoggerFactory.getLogger(LoanImportHandler.class);
|
||||||
private Workbook workbook;
|
|
||||||
private List<LoanAccountData> loans;
|
|
||||||
private List<LoanApprovalData> approvalDates;
|
|
||||||
private List<LoanTransactionData> loanRepayments;
|
|
||||||
private List<DisbursementData> disbursalDates;
|
|
||||||
private List<String> statuses;
|
|
||||||
|
|
||||||
private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService;
|
private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService;
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
@@ -77,34 +72,35 @@ public class LoanImportHandler implements ImportHandler {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Count process(Workbook workbook, String locale, String dateFormat) {
|
public Count process(final Workbook workbook, final String locale, final String dateFormat) {
|
||||||
this.workbook = workbook;
|
List<LoanAccountData> loans = new ArrayList<>();
|
||||||
this.loans = new ArrayList<>();
|
List<LoanApprovalData> approvalDates = new ArrayList<>();
|
||||||
this.approvalDates = new ArrayList<>();
|
List<LoanTransactionData> loanRepayments = new ArrayList<>();
|
||||||
this.loanRepayments = new ArrayList<>();
|
List<DisbursementData> disbursalDates = new ArrayList<>();
|
||||||
this.disbursalDates = new ArrayList<>();
|
List<String> statuses = new ArrayList<>();
|
||||||
this.statuses = new ArrayList<>();
|
readExcelFile(workbook, loans, approvalDates, loanRepayments, disbursalDates, statuses, locale, dateFormat);
|
||||||
readExcelFile(locale, dateFormat);
|
return importEntity(workbook, loans, approvalDates, loanRepayments, disbursalDates, statuses, dateFormat);
|
||||||
return importEntity(dateFormat);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public void readExcelFile(final String locale, final String dateFormat) {
|
private void readExcelFile(final Workbook workbook, final List<LoanAccountData> loans, final List<LoanApprovalData> approvalDates,
|
||||||
|
final List<LoanTransactionData> loanRepayments, final List<DisbursementData> disbursalDates, List<String> statuses,
|
||||||
|
final String locale, final String dateFormat) {
|
||||||
Sheet loanSheet = workbook.getSheet(TemplatePopulateImportConstants.LOANS_SHEET_NAME);
|
Sheet loanSheet = workbook.getSheet(TemplatePopulateImportConstants.LOANS_SHEET_NAME);
|
||||||
Integer noOfEntries = ImportHandlerUtils.getNumberOfRows(loanSheet, TemplatePopulateImportConstants.FIRST_COLUMN_INDEX);
|
Integer noOfEntries = ImportHandlerUtils.getNumberOfRows(loanSheet, TemplatePopulateImportConstants.FIRST_COLUMN_INDEX);
|
||||||
for (int rowIndex = 1; rowIndex <= noOfEntries; rowIndex++) {
|
for (int rowIndex = 1; rowIndex <= noOfEntries; rowIndex++) {
|
||||||
Row row;
|
Row row;
|
||||||
row = loanSheet.getRow(rowIndex);
|
row = loanSheet.getRow(rowIndex);
|
||||||
if (ImportHandlerUtils.isNotImported(row, LoanConstants.STATUS_COL)) {
|
if (ImportHandlerUtils.isNotImported(row, LoanConstants.STATUS_COL)) {
|
||||||
loans.add(readLoan(row, locale, dateFormat));
|
loans.add(readLoan(workbook, row, statuses, locale, dateFormat));
|
||||||
approvalDates.add(readLoanApproval(row, locale, dateFormat));
|
approvalDates.add(readLoanApproval(row, locale, dateFormat));
|
||||||
disbursalDates.add(readDisbursalData(row, locale, dateFormat));
|
disbursalDates.add(readDisbursalData(row, locale, dateFormat));
|
||||||
loanRepayments.add(readLoanRepayment(row, locale, dateFormat));
|
loanRepayments.add(readLoanRepayment(workbook, row, locale, dateFormat));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private LoanTransactionData readLoanRepayment(Row row, String locale, String dateFormat) {
|
private LoanTransactionData readLoanRepayment(final Workbook workbook, final Row row, final String locale, final String dateFormat) {
|
||||||
BigDecimal repaymentAmount = null;
|
BigDecimal repaymentAmount = null;
|
||||||
if (ImportHandlerUtils.readAsDouble(LoanConstants.TOTAL_AMOUNT_REPAID_COL, row) != null) {
|
if (ImportHandlerUtils.readAsDouble(LoanConstants.TOTAL_AMOUNT_REPAID_COL, row) != null) {
|
||||||
repaymentAmount = BigDecimal.valueOf(ImportHandlerUtils.readAsDouble(LoanConstants.TOTAL_AMOUNT_REPAID_COL, row));
|
repaymentAmount = BigDecimal.valueOf(ImportHandlerUtils.readAsDouble(LoanConstants.TOTAL_AMOUNT_REPAID_COL, row));
|
||||||
@@ -121,11 +117,11 @@ public class LoanImportHandler implements ImportHandler {
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
private DisbursementData readDisbursalData(Row row, String locale, String dateFormat) {
|
private DisbursementData readDisbursalData(final Row row, final String locale, final String dateFormat) {
|
||||||
LocalDate disbursedDate = ImportHandlerUtils.readAsDate(LoanConstants.DISBURSED_DATE_COL, row);
|
LocalDate disbursedDate = ImportHandlerUtils.readAsDate(LoanConstants.DISBURSED_DATE_COL, row);
|
||||||
String linkAccountId = null;
|
String linkAccountId = null;
|
||||||
if (ImportHandlerUtils.readAsLong(LoanConstants.LINK_ACCOUNT_ID, row) != null) {
|
if (ImportHandlerUtils.readAsLong(LoanConstants.LINK_ACCOUNT_ID, row) != null) {
|
||||||
linkAccountId = ImportHandlerUtils.readAsLong(LoanConstants.LINK_ACCOUNT_ID, row).toString();
|
linkAccountId = Objects.requireNonNull(ImportHandlerUtils.readAsLong(LoanConstants.LINK_ACCOUNT_ID, row)).toString();
|
||||||
}
|
}
|
||||||
|
|
||||||
if (disbursedDate != null) {
|
if (disbursedDate != null) {
|
||||||
@@ -134,7 +130,7 @@ public class LoanImportHandler implements ImportHandler {
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
private LoanApprovalData readLoanApproval(Row row, String locale, String dateFormat) {
|
private LoanApprovalData readLoanApproval(final Row row, final String locale, final String dateFormat) {
|
||||||
LocalDate approvedDate = ImportHandlerUtils.readAsDate(LoanConstants.APPROVED_DATE_COL, row);
|
LocalDate approvedDate = ImportHandlerUtils.readAsDate(LoanConstants.APPROVED_DATE_COL, row);
|
||||||
if (approvedDate != null) {
|
if (approvedDate != null) {
|
||||||
return LoanApprovalData.importInstance(approvedDate, row.getRowNum(), locale, dateFormat);
|
return LoanApprovalData.importInstance(approvedDate, row.getRowNum(), locale, dateFormat);
|
||||||
@@ -143,7 +139,8 @@ public class LoanImportHandler implements ImportHandler {
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
private LoanAccountData readLoan(Row row, String locale, String dateFormat) {
|
private LoanAccountData readLoan(final Workbook workbook, final Row row, final List<String> statuses, final String locale,
|
||||||
|
final String dateFormat) {
|
||||||
String externalId = ImportHandlerUtils.readAsString(LoanConstants.EXTERNAL_ID_COL, row);
|
String externalId = ImportHandlerUtils.readAsString(LoanConstants.EXTERNAL_ID_COL, row);
|
||||||
String status = ImportHandlerUtils.readAsString(LoanConstants.STATUS_COL, row);
|
String status = ImportHandlerUtils.readAsString(LoanConstants.STATUS_COL, row);
|
||||||
String productName = ImportHandlerUtils.readAsString(LoanConstants.PRODUCT_COL, row);
|
String productName = ImportHandlerUtils.readAsString(LoanConstants.PRODUCT_COL, row);
|
||||||
@@ -167,7 +164,7 @@ public class LoanImportHandler implements ImportHandler {
|
|||||||
Integer numberOfRepayments = ImportHandlerUtils.readAsInt(LoanConstants.NO_OF_REPAYMENTS_COL, row);
|
Integer numberOfRepayments = ImportHandlerUtils.readAsInt(LoanConstants.NO_OF_REPAYMENTS_COL, row);
|
||||||
Integer repaidEvery = ImportHandlerUtils.readAsInt(LoanConstants.REPAID_EVERY_COL, row);
|
Integer repaidEvery = ImportHandlerUtils.readAsInt(LoanConstants.REPAID_EVERY_COL, row);
|
||||||
String repaidEveryFrequency = ImportHandlerUtils.readAsString(LoanConstants.REPAID_EVERY_FREQUENCY_COL, row);
|
String repaidEveryFrequency = ImportHandlerUtils.readAsString(LoanConstants.REPAID_EVERY_FREQUENCY_COL, row);
|
||||||
String repaidEveryFrequencyId = "";
|
String repaidEveryFrequencyId = EMPTY_STR;
|
||||||
EnumOptionData repaidEveryFrequencyEnums = null;
|
EnumOptionData repaidEveryFrequencyEnums = null;
|
||||||
if (repaidEveryFrequency != null) {
|
if (repaidEveryFrequency != null) {
|
||||||
if (repaidEveryFrequency.equalsIgnoreCase("Days")) {
|
if (repaidEveryFrequency.equalsIgnoreCase("Days")) {
|
||||||
@@ -185,7 +182,7 @@ public class LoanImportHandler implements ImportHandler {
|
|||||||
String loanTermFrequencyType = ImportHandlerUtils.readAsString(LoanConstants.LOAN_TERM_FREQUENCY_COL, row);
|
String loanTermFrequencyType = ImportHandlerUtils.readAsString(LoanConstants.LOAN_TERM_FREQUENCY_COL, row);
|
||||||
EnumOptionData loanTermFrequencyEnum = null;
|
EnumOptionData loanTermFrequencyEnum = null;
|
||||||
if (loanTermFrequencyType != null) {
|
if (loanTermFrequencyType != null) {
|
||||||
String loanTermFrequencyId = "";
|
String loanTermFrequencyId = EMPTY_STR;
|
||||||
if (loanTermFrequencyType.equalsIgnoreCase("Days")) {
|
if (loanTermFrequencyType.equalsIgnoreCase("Days")) {
|
||||||
loanTermFrequencyId = "0";
|
loanTermFrequencyId = "0";
|
||||||
} else if (loanTermFrequencyType.equalsIgnoreCase("Weeks")) {
|
} else if (loanTermFrequencyType.equalsIgnoreCase("Weeks")) {
|
||||||
@@ -200,7 +197,7 @@ public class LoanImportHandler implements ImportHandler {
|
|||||||
nominalInterestRate = BigDecimal.valueOf(ImportHandlerUtils.readAsDouble(LoanConstants.NOMINAL_INTEREST_RATE_COL, row));
|
nominalInterestRate = BigDecimal.valueOf(ImportHandlerUtils.readAsDouble(LoanConstants.NOMINAL_INTEREST_RATE_COL, row));
|
||||||
}
|
}
|
||||||
String amortization = ImportHandlerUtils.readAsString(LoanConstants.AMORTIZATION_COL, row);
|
String amortization = ImportHandlerUtils.readAsString(LoanConstants.AMORTIZATION_COL, row);
|
||||||
String amortizationId = "";
|
String amortizationId = EMPTY_STR;
|
||||||
EnumOptionData amortizationEnumOption = null;
|
EnumOptionData amortizationEnumOption = null;
|
||||||
if (amortization != null) {
|
if (amortization != null) {
|
||||||
if (amortization.equalsIgnoreCase("Equal principal payments")) {
|
if (amortization.equalsIgnoreCase("Equal principal payments")) {
|
||||||
@@ -211,7 +208,7 @@ public class LoanImportHandler implements ImportHandler {
|
|||||||
amortizationEnumOption = new EnumOptionData(null, null, amortizationId);
|
amortizationEnumOption = new EnumOptionData(null, null, amortizationId);
|
||||||
}
|
}
|
||||||
String interestMethod = ImportHandlerUtils.readAsString(LoanConstants.INTEREST_METHOD_COL, row);
|
String interestMethod = ImportHandlerUtils.readAsString(LoanConstants.INTEREST_METHOD_COL, row);
|
||||||
String interestMethodId = "";
|
String interestMethodId = EMPTY_STR;
|
||||||
EnumOptionData interestMethodEnum = null;
|
EnumOptionData interestMethodEnum = null;
|
||||||
if (interestMethod != null) {
|
if (interestMethod != null) {
|
||||||
if (interestMethod.equalsIgnoreCase("Flat")) {
|
if (interestMethod.equalsIgnoreCase("Flat")) {
|
||||||
@@ -222,7 +219,7 @@ public class LoanImportHandler implements ImportHandler {
|
|||||||
interestMethodEnum = new EnumOptionData(null, null, interestMethodId);
|
interestMethodEnum = new EnumOptionData(null, null, interestMethodId);
|
||||||
}
|
}
|
||||||
String interestCalculationPeriod = ImportHandlerUtils.readAsString(LoanConstants.INTEREST_CALCULATION_PERIOD_COL, row);
|
String interestCalculationPeriod = ImportHandlerUtils.readAsString(LoanConstants.INTEREST_CALCULATION_PERIOD_COL, row);
|
||||||
String interestCalculationPeriodId = "";
|
String interestCalculationPeriodId = EMPTY_STR;
|
||||||
EnumOptionData interestCalculationPeriodEnum = null;
|
EnumOptionData interestCalculationPeriodEnum = null;
|
||||||
if (interestCalculationPeriod != null) {
|
if (interestCalculationPeriod != null) {
|
||||||
if (interestCalculationPeriod.equalsIgnoreCase("Daily")) {
|
if (interestCalculationPeriod.equalsIgnoreCase("Daily")) {
|
||||||
@@ -385,25 +382,27 @@ public class LoanImportHandler implements ImportHandler {
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
public Count importEntity(String dateFormat) {
|
private Count importEntity(final Workbook workbook, final List<LoanAccountData> loans, final List<LoanApprovalData> approvalDates,
|
||||||
|
final List<LoanTransactionData> loanRepayments, final List<DisbursementData> disbursalDates, final List<String> statuses,
|
||||||
|
final String dateFormat) {
|
||||||
Sheet loanSheet = workbook.getSheet(TemplatePopulateImportConstants.LOANS_SHEET_NAME);
|
Sheet loanSheet = workbook.getSheet(TemplatePopulateImportConstants.LOANS_SHEET_NAME);
|
||||||
int successCount = 0;
|
int successCount = 0;
|
||||||
int errorCount = 0;
|
int errorCount = 0;
|
||||||
int progressLevel = 0;
|
int progressLevel = 0;
|
||||||
String loanId;
|
String loanId;
|
||||||
String errorMessage = "";
|
String errorMessage;
|
||||||
for (int i = 0; i < loans.size(); i++) {
|
for (int i = 0; i < loans.size(); i++) {
|
||||||
Row row = loanSheet.getRow(loans.get(i).getRowIndex());
|
Row row = loanSheet.getRow(loans.get(i).getRowIndex());
|
||||||
Cell errorReportCell = row.createCell(LoanConstants.FAILURE_REPORT_COL);
|
Cell errorReportCell = row.createCell(LoanConstants.FAILURE_REPORT_COL);
|
||||||
Cell statusCell = row.createCell(LoanConstants.STATUS_COL);
|
Cell statusCell = row.createCell(LoanConstants.STATUS_COL);
|
||||||
CommandProcessingResult result = null;
|
CommandProcessingResult result = null;
|
||||||
loanId = "";
|
loanId = EMPTY_STR;
|
||||||
try {
|
try {
|
||||||
String status = statuses.get(i);
|
String status = statuses.get(i);
|
||||||
progressLevel = getProgressLevel(status);
|
progressLevel = getProgressLevel(status);
|
||||||
|
|
||||||
if (progressLevel == 0 && loans.get(i) != null) {
|
if (progressLevel == 0 && loans.get(i) != null) {
|
||||||
result = importLoan(i, dateFormat);
|
result = importLoan(loans, i, dateFormat);
|
||||||
loanId = result.getLoanId().toString();
|
loanId = result.getLoanId().toString();
|
||||||
progressLevel = 1;
|
progressLevel = 1;
|
||||||
} else {
|
} else {
|
||||||
@@ -411,15 +410,15 @@ public class LoanImportHandler implements ImportHandler {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (progressLevel <= 1 && approvalDates.get(i) != null) {
|
if (progressLevel <= 1 && approvalDates.get(i) != null) {
|
||||||
progressLevel = importLoanApproval(result, i, dateFormat);
|
progressLevel = importLoanApproval(approvalDates, result, i, dateFormat);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (progressLevel <= 2 && disbursalDates.get(i) != null) {
|
if (progressLevel <= 2 && disbursalDates.get(i) != null) {
|
||||||
progressLevel = importDisbursalData(result, i, dateFormat);
|
progressLevel = importDisbursalData(approvalDates, disbursalDates, result, i, dateFormat);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (loanRepayments.get(i) != null) {
|
if (loanRepayments.get(i) != null) {
|
||||||
progressLevel = importLoanRepayment(result, i, dateFormat);
|
progressLevel = importLoanRepayment(loanRepayments, result, i, dateFormat);
|
||||||
}
|
}
|
||||||
|
|
||||||
successCount++;
|
successCount++;
|
||||||
@@ -429,7 +428,7 @@ public class LoanImportHandler implements ImportHandler {
|
|||||||
errorCount++;
|
errorCount++;
|
||||||
LOG.error("Problem occurred in importEntity function", ex);
|
LOG.error("Problem occurred in importEntity function", ex);
|
||||||
errorMessage = ImportHandlerUtils.getErrorMessage(ex);
|
errorMessage = ImportHandlerUtils.getErrorMessage(ex);
|
||||||
writeLoanErrorMessage(loanId, errorMessage, progressLevel, statusCell, errorReportCell, row);
|
writeLoanErrorMessage(workbook, loanId, errorMessage, progressLevel, statusCell, errorReportCell, row);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -437,9 +436,9 @@ public class LoanImportHandler implements ImportHandler {
|
|||||||
return Count.instance(successCount, errorCount);
|
return Count.instance(successCount, errorCount);
|
||||||
}
|
}
|
||||||
|
|
||||||
private void writeLoanErrorMessage(String loanId, String errorMessage, int progressLevel, Cell statusCell, Cell errorReportCell,
|
private void writeLoanErrorMessage(final Workbook workbook, final String loanId, final String errorMessage, final int progressLevel,
|
||||||
Row row) {
|
final Cell statusCell, final Cell errorReportCell, final Row row) {
|
||||||
String status = "";
|
String status = EMPTY_STR;
|
||||||
if (progressLevel == 0) {
|
if (progressLevel == 0) {
|
||||||
status = TemplatePopulateImportConstants.STATUS_CREATION_FAILED;
|
status = TemplatePopulateImportConstants.STATUS_CREATION_FAILED;
|
||||||
} else if (progressLevel == 1) {
|
} else if (progressLevel == 1) {
|
||||||
@@ -466,7 +465,8 @@ public class LoanImportHandler implements ImportHandler {
|
|||||||
ImportHandlerUtils.writeString(LoanConstants.FAILURE_REPORT_COL, rowHeader, "Report");
|
ImportHandlerUtils.writeString(LoanConstants.FAILURE_REPORT_COL, rowHeader, "Report");
|
||||||
}
|
}
|
||||||
|
|
||||||
private Integer importLoanRepayment(CommandProcessingResult result, int rowIndex, String dateFormat) {
|
private Integer importLoanRepayment(final List<LoanTransactionData> loanRepayments, final CommandProcessingResult result,
|
||||||
|
final int rowIndex, final String dateFormat) {
|
||||||
GsonBuilder gsonBuilder = GoogleGsonSerializerHelper.createGsonBuilder();
|
GsonBuilder gsonBuilder = GoogleGsonSerializerHelper.createGsonBuilder();
|
||||||
gsonBuilder.registerTypeAdapter(LocalDate.class, new DateSerializer(dateFormat));
|
gsonBuilder.registerTypeAdapter(LocalDate.class, new DateSerializer(dateFormat));
|
||||||
JsonObject loanRepaymentJsonob = gsonBuilder.create().toJsonTree(loanRepayments.get(rowIndex)).getAsJsonObject();
|
JsonObject loanRepaymentJsonob = gsonBuilder.create().toJsonTree(loanRepayments.get(rowIndex)).getAsJsonObject();
|
||||||
@@ -482,14 +482,15 @@ public class LoanImportHandler implements ImportHandler {
|
|||||||
return 4;
|
return 4;
|
||||||
}
|
}
|
||||||
|
|
||||||
private Integer importDisbursalData(CommandProcessingResult result, int rowIndex, String dateFormat) {
|
private Integer importDisbursalData(final List<LoanApprovalData> approvalDates, final List<DisbursementData> disbursalDates,
|
||||||
|
final CommandProcessingResult result, final int rowIndex, final String dateFormat) {
|
||||||
if (approvalDates.get(rowIndex) != null && disbursalDates.get(rowIndex) != null) {
|
if (approvalDates.get(rowIndex) != null && disbursalDates.get(rowIndex) != null) {
|
||||||
|
|
||||||
DisbursementData disbusalData = disbursalDates.get(rowIndex);
|
DisbursementData disbusalData = disbursalDates.get(rowIndex);
|
||||||
String linkAccountId = disbusalData.getLinkAccountId();
|
String linkAccountId = disbusalData.getLinkAccountId();
|
||||||
GsonBuilder gsonBuilder = GoogleGsonSerializerHelper.createGsonBuilder();
|
GsonBuilder gsonBuilder = GoogleGsonSerializerHelper.createGsonBuilder();
|
||||||
gsonBuilder.registerTypeAdapter(LocalDate.class, new DateSerializer(dateFormat));
|
gsonBuilder.registerTypeAdapter(LocalDate.class, new DateSerializer(dateFormat));
|
||||||
if (linkAccountId != null && !"".equals(linkAccountId)) {
|
if (linkAccountId != null && !EMPTY_STR.equals(linkAccountId)) {
|
||||||
String payload = gsonBuilder.create().toJson(disbusalData);
|
String payload = gsonBuilder.create().toJson(disbusalData);
|
||||||
final CommandWrapper commandRequest = new CommandWrapperBuilder() //
|
final CommandWrapper commandRequest = new CommandWrapperBuilder() //
|
||||||
.disburseLoanToSavingsApplication(result.getLoanId()) //
|
.disburseLoanToSavingsApplication(result.getLoanId()) //
|
||||||
@@ -509,7 +510,8 @@ public class LoanImportHandler implements ImportHandler {
|
|||||||
return 3;
|
return 3;
|
||||||
}
|
}
|
||||||
|
|
||||||
private Integer importLoanApproval(CommandProcessingResult result, int rowIndex, String dateFormat) {
|
private Integer importLoanApproval(final List<LoanApprovalData> approvalDates, final CommandProcessingResult result, final int rowIndex,
|
||||||
|
final String dateFormat) {
|
||||||
if (approvalDates.get(rowIndex) != null) {
|
if (approvalDates.get(rowIndex) != null) {
|
||||||
GsonBuilder gsonBuilder = GoogleGsonSerializerHelper.createGsonBuilder();
|
GsonBuilder gsonBuilder = GoogleGsonSerializerHelper.createGsonBuilder();
|
||||||
gsonBuilder.registerTypeAdapter(LocalDate.class, new DateSerializer(dateFormat));
|
gsonBuilder.registerTypeAdapter(LocalDate.class, new DateSerializer(dateFormat));
|
||||||
@@ -524,7 +526,7 @@ public class LoanImportHandler implements ImportHandler {
|
|||||||
return 2;
|
return 2;
|
||||||
}
|
}
|
||||||
|
|
||||||
private CommandProcessingResult importLoan(int rowIndex, String dateFormat) {
|
private CommandProcessingResult importLoan(final List<LoanAccountData> loans, final int rowIndex, final String dateFormat) {
|
||||||
GsonBuilder gsonBuilder = GoogleGsonSerializerHelper.createGsonBuilder();
|
GsonBuilder gsonBuilder = GoogleGsonSerializerHelper.createGsonBuilder();
|
||||||
gsonBuilder.registerTypeAdapter(LocalDate.class, new DateSerializer(dateFormat));
|
gsonBuilder.registerTypeAdapter(LocalDate.class, new DateSerializer(dateFormat));
|
||||||
gsonBuilder.registerTypeAdapter(EnumOptionData.class, new EnumOptionDataValueSerializer());
|
gsonBuilder.registerTypeAdapter(EnumOptionData.class, new EnumOptionDataValueSerializer());
|
||||||
@@ -550,8 +552,7 @@ public class LoanImportHandler implements ImportHandler {
|
|||||||
.createLoanApplication() //
|
.createLoanApplication() //
|
||||||
.withJson(payload) //
|
.withJson(payload) //
|
||||||
.build(); //
|
.build(); //
|
||||||
final CommandProcessingResult result = commandsSourceWritePlatformService.logCommandSource(commandRequest);
|
return commandsSourceWritePlatformService.logCommandSource(commandRequest);
|
||||||
return result;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private int getProgressLevel(String status) {
|
private int getProgressLevel(String status) {
|
||||||
|
|||||||
+17
-15
@@ -50,10 +50,9 @@ import org.springframework.stereotype.Service;
|
|||||||
@Service
|
@Service
|
||||||
public class LoanRepaymentImportHandler implements ImportHandler {
|
public class LoanRepaymentImportHandler implements ImportHandler {
|
||||||
|
|
||||||
|
public static final String SEPARATOR = "-";
|
||||||
|
public static final String EMPTY_STR = "";
|
||||||
private static final Logger LOG = LoggerFactory.getLogger(LoanRepaymentImportHandler.class);
|
private static final Logger LOG = LoggerFactory.getLogger(LoanRepaymentImportHandler.class);
|
||||||
private Workbook workbook;
|
|
||||||
private List<LoanTransactionData> loanRepayments;
|
|
||||||
private Long loanAccountId;
|
|
||||||
private final LoanReadPlatformService loanReadPlatformService;
|
private final LoanReadPlatformService loanReadPlatformService;
|
||||||
|
|
||||||
private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService;
|
private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService;
|
||||||
@@ -66,29 +65,32 @@ public class LoanRepaymentImportHandler implements ImportHandler {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Count process(Workbook workbook, String locale, String dateFormat) {
|
public Count process(final Workbook workbook, final String locale, final String dateFormat) {
|
||||||
this.workbook = workbook;
|
|
||||||
this.loanRepayments = new ArrayList<>();
|
List<LoanTransactionData> loanRepayments = readExcelFile(workbook, locale, dateFormat);
|
||||||
readExcelFile(locale, dateFormat);
|
return importEntity(workbook, loanRepayments, dateFormat);
|
||||||
return importEntity(dateFormat);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public void readExcelFile(String locale, String dateFormat) {
|
private List<LoanTransactionData> readExcelFile(final Workbook workbook, final String locale, final String dateFormat) {
|
||||||
|
List<LoanTransactionData> loanRepayments = new ArrayList<>();
|
||||||
Sheet loanRepaymentSheet = workbook.getSheet(TemplatePopulateImportConstants.LOAN_REPAYMENT_SHEET_NAME);
|
Sheet loanRepaymentSheet = workbook.getSheet(TemplatePopulateImportConstants.LOAN_REPAYMENT_SHEET_NAME);
|
||||||
Integer noOfEntries = ImportHandlerUtils.getNumberOfRows(loanRepaymentSheet, LoanRepaymentConstants.AMOUNT_COL);
|
Integer noOfEntries = ImportHandlerUtils.getNumberOfRows(loanRepaymentSheet, LoanRepaymentConstants.AMOUNT_COL);
|
||||||
|
Long loanAccountId = null;
|
||||||
for (int rowIndex = 1; rowIndex <= noOfEntries; rowIndex++) {
|
for (int rowIndex = 1; rowIndex <= noOfEntries; rowIndex++) {
|
||||||
Row row;
|
Row row;
|
||||||
row = loanRepaymentSheet.getRow(rowIndex);
|
row = loanRepaymentSheet.getRow(rowIndex);
|
||||||
if (ImportHandlerUtils.isNotImported(row, LoanRepaymentConstants.STATUS_COL)) {
|
if (ImportHandlerUtils.isNotImported(row, LoanRepaymentConstants.STATUS_COL)) {
|
||||||
loanRepayments.add(readLoanRepayment(row, locale, dateFormat));
|
loanRepayments.add(readLoanRepayment(workbook, loanAccountId, row, locale, dateFormat));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
return loanRepayments;
|
||||||
}
|
}
|
||||||
|
|
||||||
private LoanTransactionData readLoanRepayment(Row row, String locale, String dateFormat) {
|
private LoanTransactionData readLoanRepayment(final Workbook workbook, Long loanAccountId, final Row row, final String locale,
|
||||||
|
final String dateFormat) {
|
||||||
String loanaccountInfo = ImportHandlerUtils.readAsString(LoanRepaymentConstants.LOAN_ACCOUNT_NO_COL, row);
|
String loanaccountInfo = ImportHandlerUtils.readAsString(LoanRepaymentConstants.LOAN_ACCOUNT_NO_COL, row);
|
||||||
if (loanaccountInfo != null) {
|
if (loanaccountInfo != null) {
|
||||||
List<String> loanAccountAr = Splitter.on('-').splitToList(loanaccountInfo);
|
List<String> loanAccountAr = Splitter.on(SEPARATOR).splitToList(loanaccountInfo);
|
||||||
loanAccountId = this.loanReadPlatformService.retrieveLoanIdByAccountNumber(loanAccountAr.get(0));
|
loanAccountId = this.loanReadPlatformService.retrieveLoanIdByAccountNumber(loanAccountAr.get(0));
|
||||||
}
|
}
|
||||||
BigDecimal repaymentAmount = null;
|
BigDecimal repaymentAmount = null;
|
||||||
@@ -105,14 +107,14 @@ public class LoanRepaymentImportHandler implements ImportHandler {
|
|||||||
Integer receiptNumber = ImportHandlerUtils.readAsInt(LoanRepaymentConstants.RECEIPT_NO_COL, row);
|
Integer receiptNumber = ImportHandlerUtils.readAsInt(LoanRepaymentConstants.RECEIPT_NO_COL, row);
|
||||||
Integer bankNumber = ImportHandlerUtils.readAsInt(LoanRepaymentConstants.BANK_NO_COL, row);
|
Integer bankNumber = ImportHandlerUtils.readAsInt(LoanRepaymentConstants.BANK_NO_COL, row);
|
||||||
return LoanTransactionData.importInstance(repaymentAmount, repaymentDate, repaymentTypeId, accountNumber, checkNumber, routingCode,
|
return LoanTransactionData.importInstance(repaymentAmount, repaymentDate, repaymentTypeId, accountNumber, checkNumber, routingCode,
|
||||||
receiptNumber, bankNumber, loanAccountId, "", row.getRowNum(), locale, dateFormat);
|
receiptNumber, bankNumber, loanAccountId, EMPTY_STR, row.getRowNum(), locale, dateFormat);
|
||||||
}
|
}
|
||||||
|
|
||||||
public Count importEntity(String dateFormat) {
|
private Count importEntity(final Workbook workbook, final List<LoanTransactionData> loanRepayments, final String dateFormat) {
|
||||||
Sheet loanRepaymentSheet = workbook.getSheet(TemplatePopulateImportConstants.LOAN_REPAYMENT_SHEET_NAME);
|
Sheet loanRepaymentSheet = workbook.getSheet(TemplatePopulateImportConstants.LOAN_REPAYMENT_SHEET_NAME);
|
||||||
int successCount = 0;
|
int successCount = 0;
|
||||||
int errorCount = 0;
|
int errorCount = 0;
|
||||||
String errorMessage = "";
|
String errorMessage;
|
||||||
GsonBuilder gsonBuilder = GoogleGsonSerializerHelper.createGsonBuilder();
|
GsonBuilder gsonBuilder = GoogleGsonSerializerHelper.createGsonBuilder();
|
||||||
gsonBuilder.registerTypeAdapter(LocalDate.class, new DateSerializer(dateFormat));
|
gsonBuilder.registerTypeAdapter(LocalDate.class, new DateSerializer(dateFormat));
|
||||||
|
|
||||||
|
|||||||
+8
-15
@@ -31,7 +31,6 @@ import org.apache.fineract.infrastructure.bulkimport.data.Count;
|
|||||||
import org.apache.fineract.infrastructure.bulkimport.importhandler.ImportHandler;
|
import org.apache.fineract.infrastructure.bulkimport.importhandler.ImportHandler;
|
||||||
import org.apache.fineract.infrastructure.bulkimport.importhandler.ImportHandlerUtils;
|
import org.apache.fineract.infrastructure.bulkimport.importhandler.ImportHandlerUtils;
|
||||||
import org.apache.fineract.infrastructure.bulkimport.importhandler.helper.DateSerializer;
|
import org.apache.fineract.infrastructure.bulkimport.importhandler.helper.DateSerializer;
|
||||||
import org.apache.fineract.infrastructure.core.data.CommandProcessingResult;
|
|
||||||
import org.apache.fineract.infrastructure.core.serialization.GoogleGsonSerializerHelper;
|
import org.apache.fineract.infrastructure.core.serialization.GoogleGsonSerializerHelper;
|
||||||
import org.apache.fineract.organisation.office.data.OfficeData;
|
import org.apache.fineract.organisation.office.data.OfficeData;
|
||||||
import org.apache.poi.ss.usermodel.Cell;
|
import org.apache.poi.ss.usermodel.Cell;
|
||||||
@@ -48,8 +47,6 @@ import org.springframework.stereotype.Service;
|
|||||||
public class OfficeImportHandler implements ImportHandler {
|
public class OfficeImportHandler implements ImportHandler {
|
||||||
|
|
||||||
private static final Logger LOG = LoggerFactory.getLogger(OfficeImportHandler.class);
|
private static final Logger LOG = LoggerFactory.getLogger(OfficeImportHandler.class);
|
||||||
private List<OfficeData> offices;
|
|
||||||
private Workbook workbook;
|
|
||||||
private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService;
|
private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService;
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
@@ -59,13 +56,12 @@ public class OfficeImportHandler implements ImportHandler {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Count process(final Workbook workbook, final String locale, final String dateFormat) {
|
public Count process(final Workbook workbook, final String locale, final String dateFormat) {
|
||||||
this.offices = new ArrayList<>();
|
List<OfficeData> offices = readExcelFile(workbook, locale, dateFormat);
|
||||||
this.workbook = workbook;
|
return importEntity(workbook, offices, dateFormat);
|
||||||
readExcelFile(locale, dateFormat);
|
|
||||||
return importEntity(dateFormat);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public void readExcelFile(final String locale, final String dateFormat) {
|
private List<OfficeData> readExcelFile(final Workbook workbook, final String locale, final String dateFormat) {
|
||||||
|
List<OfficeData> offices = new ArrayList<>();
|
||||||
Sheet officeSheet = workbook.getSheet(TemplatePopulateImportConstants.OFFICE_SHEET_NAME);
|
Sheet officeSheet = workbook.getSheet(TemplatePopulateImportConstants.OFFICE_SHEET_NAME);
|
||||||
Integer noOfEntries = ImportHandlerUtils.getNumberOfRows(officeSheet, 0);
|
Integer noOfEntries = ImportHandlerUtils.getNumberOfRows(officeSheet, 0);
|
||||||
for (int rowIndex = 1; rowIndex <= noOfEntries; rowIndex++) {
|
for (int rowIndex = 1; rowIndex <= noOfEntries; rowIndex++) {
|
||||||
@@ -75,6 +71,7 @@ public class OfficeImportHandler implements ImportHandler {
|
|||||||
offices.add(readOffice(row, locale, dateFormat));
|
offices.add(readOffice(row, locale, dateFormat));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
return offices;
|
||||||
}
|
}
|
||||||
|
|
||||||
private OfficeData readOffice(Row row, final String locale, final String dateFormat) {
|
private OfficeData readOffice(Row row, final String locale, final String dateFormat) {
|
||||||
@@ -87,14 +84,14 @@ public class OfficeImportHandler implements ImportHandler {
|
|||||||
return office;
|
return office;
|
||||||
}
|
}
|
||||||
|
|
||||||
public Count importEntity(String dateFormat) {
|
private Count importEntity(final Workbook workbook, final List<OfficeData> offices, final String dateFormat) {
|
||||||
Sheet officeSheet = workbook.getSheet(TemplatePopulateImportConstants.OFFICE_SHEET_NAME);
|
Sheet officeSheet = workbook.getSheet(TemplatePopulateImportConstants.OFFICE_SHEET_NAME);
|
||||||
GsonBuilder gsonBuilder = GoogleGsonSerializerHelper.createGsonBuilder();
|
GsonBuilder gsonBuilder = GoogleGsonSerializerHelper.createGsonBuilder();
|
||||||
gsonBuilder.registerTypeAdapter(LocalDate.class, new DateSerializer(dateFormat));
|
gsonBuilder.registerTypeAdapter(LocalDate.class, new DateSerializer(dateFormat));
|
||||||
|
|
||||||
int successCount = 0;
|
int successCount = 0;
|
||||||
int errorCount = 0;
|
int errorCount = 0;
|
||||||
String errorMessage = "";
|
String errorMessage;
|
||||||
for (OfficeData office : offices) {
|
for (OfficeData office : offices) {
|
||||||
try {
|
try {
|
||||||
String payload = gsonBuilder.create().toJson(office);
|
String payload = gsonBuilder.create().toJson(office);
|
||||||
@@ -102,7 +99,7 @@ public class OfficeImportHandler implements ImportHandler {
|
|||||||
.createOffice() //
|
.createOffice() //
|
||||||
.withJson(payload) //
|
.withJson(payload) //
|
||||||
.build(); //
|
.build(); //
|
||||||
final CommandProcessingResult result = commandsSourceWritePlatformService.logCommandSource(commandRequest);
|
commandsSourceWritePlatformService.logCommandSource(commandRequest);
|
||||||
successCount++;
|
successCount++;
|
||||||
Cell statusCell = officeSheet.getRow(office.getRowIndex()).createCell(OfficeConstants.STATUS_COL);
|
Cell statusCell = officeSheet.getRow(office.getRowIndex()).createCell(OfficeConstants.STATUS_COL);
|
||||||
statusCell.setCellValue(TemplatePopulateImportConstants.STATUS_CELL_IMPORTED);
|
statusCell.setCellValue(TemplatePopulateImportConstants.STATUS_CELL_IMPORTED);
|
||||||
@@ -119,8 +116,4 @@ public class OfficeImportHandler implements ImportHandler {
|
|||||||
TemplatePopulateImportConstants.STATUS_COL_REPORT_HEADER);
|
TemplatePopulateImportConstants.STATUS_COL_REPORT_HEADER);
|
||||||
return Count.instance(successCount, errorCount);
|
return Count.instance(successCount, errorCount);
|
||||||
}
|
}
|
||||||
|
|
||||||
public List<OfficeData> getOffices() {
|
|
||||||
return offices;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
+49
-47
@@ -54,40 +54,38 @@ import org.springframework.stereotype.Service;
|
|||||||
@Service
|
@Service
|
||||||
public class RecurringDepositImportHandler implements ImportHandler {
|
public class RecurringDepositImportHandler implements ImportHandler {
|
||||||
|
|
||||||
|
public static final String WEEKS = "Weeks";
|
||||||
|
public static final String DAYS = "Days";
|
||||||
|
public static final String MONTHS = "Months";
|
||||||
|
public static final String YEARS = "Years";
|
||||||
private static final Logger LOG = LoggerFactory.getLogger(RecurringDepositImportHandler.class);
|
private static final Logger LOG = LoggerFactory.getLogger(RecurringDepositImportHandler.class);
|
||||||
private Workbook workbook;
|
|
||||||
private List<RecurringDepositAccountData> savings;
|
|
||||||
private List<SavingsApproval> approvalDates;
|
|
||||||
private List<SavingsActivation> activationDates;
|
|
||||||
private List<String> statuses;
|
|
||||||
|
|
||||||
private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService;
|
private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService;
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
public RecurringDepositImportHandler(final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService) {
|
public RecurringDepositImportHandler(final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService) {
|
||||||
this.commandsSourceWritePlatformService = commandsSourceWritePlatformService;
|
this.commandsSourceWritePlatformService = commandsSourceWritePlatformService;
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Count process(Workbook workbook, String locale, String dateFormat) {
|
public Count process(final Workbook workbook, final String locale, final String dateFormat) {
|
||||||
this.workbook = workbook;
|
List<RecurringDepositAccountData> savings = new ArrayList<>();
|
||||||
savings = new ArrayList<>();
|
List<SavingsApproval> approvalDates = new ArrayList<>();
|
||||||
approvalDates = new ArrayList<>();
|
List<SavingsActivation> activationDates = new ArrayList<>();
|
||||||
activationDates = new ArrayList<>();
|
List<String> statuses = new ArrayList<>();
|
||||||
statuses = new ArrayList<>();
|
readExcelFile(workbook, savings, approvalDates, activationDates, statuses, locale, dateFormat);
|
||||||
readExcelFile(locale, dateFormat);
|
return importEntity(workbook, savings, approvalDates, activationDates, statuses, dateFormat);
|
||||||
return importEntity(dateFormat);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public void readExcelFile(String locale, String dateFormat) {
|
private void readExcelFile(final Workbook workbook, final List<RecurringDepositAccountData> savings,
|
||||||
|
final List<SavingsApproval> approvalDates, final List<SavingsActivation> activationDates, final List<String> statuses,
|
||||||
|
final String locale, final String dateFormat) {
|
||||||
Sheet savingsSheet = workbook.getSheet(TemplatePopulateImportConstants.RECURRING_DEPOSIT_SHEET_NAME);
|
Sheet savingsSheet = workbook.getSheet(TemplatePopulateImportConstants.RECURRING_DEPOSIT_SHEET_NAME);
|
||||||
Integer noOfEntries = ImportHandlerUtils.getNumberOfRows(savingsSheet, TemplatePopulateImportConstants.ROWHEADER_INDEX);
|
Integer noOfEntries = ImportHandlerUtils.getNumberOfRows(savingsSheet, TemplatePopulateImportConstants.ROWHEADER_INDEX);
|
||||||
for (int rowIndex = 1; rowIndex <= noOfEntries; rowIndex++) {
|
for (int rowIndex = 1; rowIndex <= noOfEntries; rowIndex++) {
|
||||||
Row row;
|
Row row;
|
||||||
row = savingsSheet.getRow(rowIndex);
|
row = savingsSheet.getRow(rowIndex);
|
||||||
if (ImportHandlerUtils.isNotImported(row, RecurringDepositConstants.STATUS_COL)) {
|
if (ImportHandlerUtils.isNotImported(row, RecurringDepositConstants.STATUS_COL)) {
|
||||||
savings.add(readSavings(row, locale, dateFormat));
|
savings.add(readSavings(workbook, row, statuses, locale, dateFormat));
|
||||||
approvalDates.add(readSavingsApproval(row, locale, dateFormat));
|
approvalDates.add(readSavingsApproval(row, locale, dateFormat));
|
||||||
activationDates.add(readSavingsActivation(row, locale, dateFormat));
|
activationDates.add(readSavingsActivation(row, locale, dateFormat));
|
||||||
}
|
}
|
||||||
@@ -95,7 +93,7 @@ public class RecurringDepositImportHandler implements ImportHandler {
|
|||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private SavingsActivation readSavingsActivation(Row row, String locale, String dateFormat) {
|
private SavingsActivation readSavingsActivation(final Row row, final String locale, final String dateFormat) {
|
||||||
LocalDate activationDate = ImportHandlerUtils.readAsDate(RecurringDepositConstants.ACTIVATION_DATE_COL, row);
|
LocalDate activationDate = ImportHandlerUtils.readAsDate(RecurringDepositConstants.ACTIVATION_DATE_COL, row);
|
||||||
if (activationDate != null) {
|
if (activationDate != null) {
|
||||||
return SavingsActivation.importInstance(activationDate, row.getRowNum(), locale, dateFormat);
|
return SavingsActivation.importInstance(activationDate, row.getRowNum(), locale, dateFormat);
|
||||||
@@ -104,7 +102,7 @@ public class RecurringDepositImportHandler implements ImportHandler {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private SavingsApproval readSavingsApproval(Row row, String locale, String dateFormat) {
|
private SavingsApproval readSavingsApproval(final Row row, final String locale, final String dateFormat) {
|
||||||
LocalDate approvalDate = ImportHandlerUtils.readAsDate(RecurringDepositConstants.APPROVED_DATE_COL, row);
|
LocalDate approvalDate = ImportHandlerUtils.readAsDate(RecurringDepositConstants.APPROVED_DATE_COL, row);
|
||||||
if (approvalDate != null) {
|
if (approvalDate != null) {
|
||||||
return SavingsApproval.importInstance(approvalDate, row.getRowNum(), locale, dateFormat);
|
return SavingsApproval.importInstance(approvalDate, row.getRowNum(), locale, dateFormat);
|
||||||
@@ -113,7 +111,8 @@ public class RecurringDepositImportHandler implements ImportHandler {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private RecurringDepositAccountData readSavings(Row row, String locale, String dateFormat) {
|
private RecurringDepositAccountData readSavings(final Workbook workbook, final Row row, final List<String> statuses,
|
||||||
|
final String locale, final String dateFormat) {
|
||||||
|
|
||||||
String productName = ImportHandlerUtils.readAsString(RecurringDepositConstants.PRODUCT_COL, row);
|
String productName = ImportHandlerUtils.readAsString(RecurringDepositConstants.PRODUCT_COL, row);
|
||||||
Long productId = ImportHandlerUtils.getIdByName(workbook.getSheet(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME), productName);
|
Long productId = ImportHandlerUtils.getIdByName(workbook.getSheet(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME), productName);
|
||||||
@@ -183,13 +182,13 @@ public class RecurringDepositImportHandler implements ImportHandler {
|
|||||||
Long lockinPeriodFrequencyTypeId = null;
|
Long lockinPeriodFrequencyTypeId = null;
|
||||||
EnumOptionData lockinPeriodFrequencyTypeEnum = null;
|
EnumOptionData lockinPeriodFrequencyTypeEnum = null;
|
||||||
if (lockinPeriodFrequencyType != null) {
|
if (lockinPeriodFrequencyType != null) {
|
||||||
if (lockinPeriodFrequencyType.equalsIgnoreCase("Days")) {
|
if (lockinPeriodFrequencyType.equalsIgnoreCase(DAYS)) {
|
||||||
lockinPeriodFrequencyTypeId = 0L;
|
lockinPeriodFrequencyTypeId = 0L;
|
||||||
} else if (lockinPeriodFrequencyType.equalsIgnoreCase("Weeks")) {
|
} else if (lockinPeriodFrequencyType.equalsIgnoreCase(WEEKS)) {
|
||||||
lockinPeriodFrequencyTypeId = 1L;
|
lockinPeriodFrequencyTypeId = 1L;
|
||||||
} else if (lockinPeriodFrequencyType.equalsIgnoreCase("Months")) {
|
} else if (lockinPeriodFrequencyType.equalsIgnoreCase(MONTHS)) {
|
||||||
lockinPeriodFrequencyTypeId = 2L;
|
lockinPeriodFrequencyTypeId = 2L;
|
||||||
} else if (lockinPeriodFrequencyType.equalsIgnoreCase("Years")) {
|
} else if (lockinPeriodFrequencyType.equalsIgnoreCase(YEARS)) {
|
||||||
lockinPeriodFrequencyTypeId = 3L;
|
lockinPeriodFrequencyTypeId = 3L;
|
||||||
}
|
}
|
||||||
lockinPeriodFrequencyTypeEnum = new EnumOptionData(lockinPeriodFrequencyTypeId, null, null);
|
lockinPeriodFrequencyTypeEnum = new EnumOptionData(lockinPeriodFrequencyTypeId, null, null);
|
||||||
@@ -203,13 +202,13 @@ public class RecurringDepositImportHandler implements ImportHandler {
|
|||||||
String depositPeriodFrequency = ImportHandlerUtils.readAsString(RecurringDepositConstants.DEPOSIT_PERIOD_FREQUENCY_COL, row);
|
String depositPeriodFrequency = ImportHandlerUtils.readAsString(RecurringDepositConstants.DEPOSIT_PERIOD_FREQUENCY_COL, row);
|
||||||
Long depositPeriodFrequencyId = null;
|
Long depositPeriodFrequencyId = null;
|
||||||
if (depositPeriodFrequency != null) {
|
if (depositPeriodFrequency != null) {
|
||||||
if (depositPeriodFrequency.equalsIgnoreCase("Days")) {
|
if (depositPeriodFrequency.equalsIgnoreCase(DAYS)) {
|
||||||
depositPeriodFrequencyId = 0L;
|
depositPeriodFrequencyId = 0L;
|
||||||
} else if (depositPeriodFrequency.equalsIgnoreCase("Weeks")) {
|
} else if (depositPeriodFrequency.equalsIgnoreCase(WEEKS)) {
|
||||||
depositPeriodFrequencyId = 1L;
|
depositPeriodFrequencyId = 1L;
|
||||||
} else if (depositPeriodFrequency.equalsIgnoreCase("Months")) {
|
} else if (depositPeriodFrequency.equalsIgnoreCase(MONTHS)) {
|
||||||
depositPeriodFrequencyId = 2L;
|
depositPeriodFrequencyId = 2L;
|
||||||
} else if (depositPeriodFrequency.equalsIgnoreCase("Years")) {
|
} else if (depositPeriodFrequency.equalsIgnoreCase(YEARS)) {
|
||||||
depositPeriodFrequencyId = 3L;
|
depositPeriodFrequencyId = 3L;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -218,13 +217,13 @@ public class RecurringDepositImportHandler implements ImportHandler {
|
|||||||
Long recurringFrequencyTypeId = null;
|
Long recurringFrequencyTypeId = null;
|
||||||
EnumOptionData recurringFrequencyTypeEnum = null;
|
EnumOptionData recurringFrequencyTypeEnum = null;
|
||||||
if (recurringFrequencyType != null) {
|
if (recurringFrequencyType != null) {
|
||||||
if (recurringFrequencyType.equalsIgnoreCase("Days")) {
|
if (recurringFrequencyType.equalsIgnoreCase(DAYS)) {
|
||||||
recurringFrequencyTypeId = 0L;
|
recurringFrequencyTypeId = 0L;
|
||||||
} else if (recurringFrequencyType.equalsIgnoreCase("Weeks")) {
|
} else if (recurringFrequencyType.equalsIgnoreCase(WEEKS)) {
|
||||||
recurringFrequencyTypeId = 1L;
|
recurringFrequencyTypeId = 1L;
|
||||||
} else if (recurringFrequencyType.equalsIgnoreCase("Months")) {
|
} else if (recurringFrequencyType.equalsIgnoreCase(MONTHS)) {
|
||||||
recurringFrequencyTypeId = 2L;
|
recurringFrequencyTypeId = 2L;
|
||||||
} else if (recurringFrequencyType.equalsIgnoreCase("Years")) {
|
} else if (recurringFrequencyType.equalsIgnoreCase(YEARS)) {
|
||||||
recurringFrequencyTypeId = 3L;
|
recurringFrequencyTypeId = 3L;
|
||||||
}
|
}
|
||||||
recurringFrequencyTypeEnum = new EnumOptionData(recurringFrequencyTypeId, null, null);
|
recurringFrequencyTypeEnum = new EnumOptionData(recurringFrequencyTypeId, null, null);
|
||||||
@@ -272,7 +271,9 @@ public class RecurringDepositImportHandler implements ImportHandler {
|
|||||||
isMandatoryDeposit, allowWithdrawal, adjustAdvancePayments, externalId, charges, row.getRowNum(), locale, dateFormat);
|
isMandatoryDeposit, allowWithdrawal, adjustAdvancePayments, externalId, charges, row.getRowNum(), locale, dateFormat);
|
||||||
}
|
}
|
||||||
|
|
||||||
public Count importEntity(String dateFormat) {
|
private Count importEntity(final Workbook workbook, final List<RecurringDepositAccountData> savings,
|
||||||
|
final List<SavingsApproval> approvalDates, final List<SavingsActivation> activationDates, final List<String> statuses,
|
||||||
|
final String dateFormat) {
|
||||||
Sheet savingsSheet = workbook.getSheet(TemplatePopulateImportConstants.RECURRING_DEPOSIT_SHEET_NAME);
|
Sheet savingsSheet = workbook.getSheet(TemplatePopulateImportConstants.RECURRING_DEPOSIT_SHEET_NAME);
|
||||||
int successCount = 0;
|
int successCount = 0;
|
||||||
int errorCount = 0;
|
int errorCount = 0;
|
||||||
@@ -288,7 +289,7 @@ public class RecurringDepositImportHandler implements ImportHandler {
|
|||||||
progressLevel = getProgressLevel(status);
|
progressLevel = getProgressLevel(status);
|
||||||
|
|
||||||
if (progressLevel == 0) {
|
if (progressLevel == 0) {
|
||||||
CommandProcessingResult result = importSavings(i, dateFormat);
|
CommandProcessingResult result = importSavings(savings, i, dateFormat);
|
||||||
savingsId = result.getSavingsId();
|
savingsId = result.getSavingsId();
|
||||||
progressLevel = 1;
|
progressLevel = 1;
|
||||||
} else {
|
} else {
|
||||||
@@ -297,11 +298,11 @@ public class RecurringDepositImportHandler implements ImportHandler {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (progressLevel <= 1) {
|
if (progressLevel <= 1) {
|
||||||
progressLevel = importSavingsApproval(savingsId, i, dateFormat);
|
progressLevel = importSavingsApproval(approvalDates, savingsId, i, dateFormat);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (progressLevel <= 2) {
|
if (progressLevel <= 2) {
|
||||||
progressLevel = importSavingsActivation(savingsId, i, dateFormat);
|
progressLevel = importSavingsActivation(activationDates, savingsId, i, dateFormat);
|
||||||
}
|
}
|
||||||
successCount++;
|
successCount++;
|
||||||
statusCell.setCellValue(TemplatePopulateImportConstants.STATUS_CELL_IMPORTED);
|
statusCell.setCellValue(TemplatePopulateImportConstants.STATUS_CELL_IMPORTED);
|
||||||
@@ -310,15 +311,15 @@ public class RecurringDepositImportHandler implements ImportHandler {
|
|||||||
errorCount++;
|
errorCount++;
|
||||||
LOG.error("Problem occurred in importEntity function", ex);
|
LOG.error("Problem occurred in importEntity function", ex);
|
||||||
errorMessage = ImportHandlerUtils.getErrorMessage(ex);
|
errorMessage = ImportHandlerUtils.getErrorMessage(ex);
|
||||||
writeRecurringDepositErrorMessage(savingsId, errorMessage, progressLevel, statusCell, errorReportCell, row);
|
writeRecurringDepositErrorMessage(workbook, savingsId, errorMessage, progressLevel, statusCell, errorReportCell, row);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
setReportHeaders(savingsSheet);
|
setReportHeaders(savingsSheet);
|
||||||
return Count.instance(successCount, errorCount);
|
return Count.instance(successCount, errorCount);
|
||||||
}
|
}
|
||||||
|
|
||||||
private void writeRecurringDepositErrorMessage(Long savingsId, String errorMessage, int progressLevel, Cell statusCell,
|
private void writeRecurringDepositErrorMessage(final Workbook workbook, final Long savingsId, final String errorMessage,
|
||||||
Cell errorReportCell, Row row) {
|
final int progressLevel, final Cell statusCell, final Cell errorReportCell, final Row row) {
|
||||||
String status = "";
|
String status = "";
|
||||||
if (progressLevel == 0) {
|
if (progressLevel == 0) {
|
||||||
status = TemplatePopulateImportConstants.STATUS_CREATION_FAILED;
|
status = TemplatePopulateImportConstants.STATUS_CREATION_FAILED;
|
||||||
@@ -337,7 +338,7 @@ public class RecurringDepositImportHandler implements ImportHandler {
|
|||||||
errorReportCell.setCellValue(errorMessage);
|
errorReportCell.setCellValue(errorMessage);
|
||||||
}
|
}
|
||||||
|
|
||||||
private void setReportHeaders(Sheet savingsSheet) {
|
private void setReportHeaders(final Sheet savingsSheet) {
|
||||||
savingsSheet.setColumnWidth(RecurringDepositConstants.STATUS_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
|
savingsSheet.setColumnWidth(RecurringDepositConstants.STATUS_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
|
||||||
Row rowHeader = savingsSheet.getRow(TemplatePopulateImportConstants.ROWHEADER_INDEX);
|
Row rowHeader = savingsSheet.getRow(TemplatePopulateImportConstants.ROWHEADER_INDEX);
|
||||||
ImportHandlerUtils.writeString(RecurringDepositConstants.STATUS_COL, rowHeader, "Status");
|
ImportHandlerUtils.writeString(RecurringDepositConstants.STATUS_COL, rowHeader, "Status");
|
||||||
@@ -345,7 +346,8 @@ public class RecurringDepositImportHandler implements ImportHandler {
|
|||||||
ImportHandlerUtils.writeString(RecurringDepositConstants.FAILURE_REPORT_COL, rowHeader, "Report");
|
ImportHandlerUtils.writeString(RecurringDepositConstants.FAILURE_REPORT_COL, rowHeader, "Report");
|
||||||
}
|
}
|
||||||
|
|
||||||
private int importSavingsActivation(Long savingsId, int i, String dateFormat) {
|
private int importSavingsActivation(final List<SavingsActivation> activationDates, final Long savingsId, final int i,
|
||||||
|
final String dateFormat) {
|
||||||
if (activationDates.get(i) != null) {
|
if (activationDates.get(i) != null) {
|
||||||
GsonBuilder gsonBuilder = GoogleGsonSerializerHelper.createGsonBuilder();
|
GsonBuilder gsonBuilder = GoogleGsonSerializerHelper.createGsonBuilder();
|
||||||
gsonBuilder.registerTypeAdapter(LocalDate.class, new DateSerializer(dateFormat));
|
gsonBuilder.registerTypeAdapter(LocalDate.class, new DateSerializer(dateFormat));
|
||||||
@@ -354,12 +356,13 @@ public class RecurringDepositImportHandler implements ImportHandler {
|
|||||||
.recurringDepositAccountActivation(savingsId)//
|
.recurringDepositAccountActivation(savingsId)//
|
||||||
.withJson(payload) //
|
.withJson(payload) //
|
||||||
.build(); //
|
.build(); //
|
||||||
final CommandProcessingResult result = commandsSourceWritePlatformService.logCommandSource(commandRequest);
|
commandsSourceWritePlatformService.logCommandSource(commandRequest);
|
||||||
}
|
}
|
||||||
return 3;
|
return 3;
|
||||||
}
|
}
|
||||||
|
|
||||||
private int importSavingsApproval(Long savingsId, int i, String dateFormat) {
|
private int importSavingsApproval(final List<SavingsApproval> approvalDates, final Long savingsId, final int i,
|
||||||
|
final String dateFormat) {
|
||||||
if (approvalDates.get(i) != null) {
|
if (approvalDates.get(i) != null) {
|
||||||
GsonBuilder gsonBuilder = GoogleGsonSerializerHelper.createGsonBuilder();
|
GsonBuilder gsonBuilder = GoogleGsonSerializerHelper.createGsonBuilder();
|
||||||
gsonBuilder.registerTypeAdapter(LocalDate.class, new DateSerializer(dateFormat));
|
gsonBuilder.registerTypeAdapter(LocalDate.class, new DateSerializer(dateFormat));
|
||||||
@@ -368,12 +371,12 @@ public class RecurringDepositImportHandler implements ImportHandler {
|
|||||||
.approveRecurringDepositAccountApplication(savingsId)//
|
.approveRecurringDepositAccountApplication(savingsId)//
|
||||||
.withJson(payload) //
|
.withJson(payload) //
|
||||||
.build(); //
|
.build(); //
|
||||||
final CommandProcessingResult result = commandsSourceWritePlatformService.logCommandSource(commandRequest);
|
commandsSourceWritePlatformService.logCommandSource(commandRequest);
|
||||||
}
|
}
|
||||||
return 2;
|
return 2;
|
||||||
}
|
}
|
||||||
|
|
||||||
private CommandProcessingResult importSavings(int i, String dateFormat) {
|
private CommandProcessingResult importSavings(final List<RecurringDepositAccountData> savings, final int i, final String dateFormat) {
|
||||||
GsonBuilder gsonBuilder = GoogleGsonSerializerHelper.createGsonBuilder();
|
GsonBuilder gsonBuilder = GoogleGsonSerializerHelper.createGsonBuilder();
|
||||||
gsonBuilder.registerTypeAdapter(LocalDate.class, new DateSerializer(dateFormat));
|
gsonBuilder.registerTypeAdapter(LocalDate.class, new DateSerializer(dateFormat));
|
||||||
gsonBuilder.registerTypeAdapter(EnumOptionData.class, new EnumOptionDataIdSerializer());
|
gsonBuilder.registerTypeAdapter(EnumOptionData.class, new EnumOptionDataIdSerializer());
|
||||||
@@ -384,8 +387,7 @@ public class RecurringDepositImportHandler implements ImportHandler {
|
|||||||
.createRecurringDepositAccount() //
|
.createRecurringDepositAccount() //
|
||||||
.withJson(payload) //
|
.withJson(payload) //
|
||||||
.build(); //
|
.build(); //
|
||||||
final CommandProcessingResult result = commandsSourceWritePlatformService.logCommandSource(commandRequest);
|
return commandsSourceWritePlatformService.logCommandSource(commandRequest);
|
||||||
return result;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private int getProgressLevel(String status) {
|
private int getProgressLevel(String status) {
|
||||||
|
|||||||
+18
-22
@@ -34,7 +34,6 @@ import org.apache.fineract.infrastructure.bulkimport.importhandler.ImportHandler
|
|||||||
import org.apache.fineract.infrastructure.bulkimport.importhandler.ImportHandlerUtils;
|
import org.apache.fineract.infrastructure.bulkimport.importhandler.ImportHandlerUtils;
|
||||||
import org.apache.fineract.infrastructure.bulkimport.importhandler.helper.DateSerializer;
|
import org.apache.fineract.infrastructure.bulkimport.importhandler.helper.DateSerializer;
|
||||||
import org.apache.fineract.infrastructure.bulkimport.importhandler.helper.SavingsAccountTransactionEnumValueSerialiser;
|
import org.apache.fineract.infrastructure.bulkimport.importhandler.helper.SavingsAccountTransactionEnumValueSerialiser;
|
||||||
import org.apache.fineract.infrastructure.core.data.CommandProcessingResult;
|
|
||||||
import org.apache.fineract.infrastructure.core.exception.AbstractPlatformDomainRuleException;
|
import org.apache.fineract.infrastructure.core.exception.AbstractPlatformDomainRuleException;
|
||||||
import org.apache.fineract.infrastructure.core.serialization.GoogleGsonSerializerHelper;
|
import org.apache.fineract.infrastructure.core.serialization.GoogleGsonSerializerHelper;
|
||||||
import org.apache.fineract.portfolio.savings.data.SavingsAccountTransactionData;
|
import org.apache.fineract.portfolio.savings.data.SavingsAccountTransactionData;
|
||||||
@@ -53,9 +52,6 @@ import org.springframework.stereotype.Service;
|
|||||||
public class RecurringDepositTransactionImportHandler implements ImportHandler {
|
public class RecurringDepositTransactionImportHandler implements ImportHandler {
|
||||||
|
|
||||||
private static final Logger LOG = LoggerFactory.getLogger(RecurringDepositTransactionImportHandler.class);
|
private static final Logger LOG = LoggerFactory.getLogger(RecurringDepositTransactionImportHandler.class);
|
||||||
private Workbook workbook;
|
|
||||||
private List<SavingsAccountTransactionData> savingsTransactions;
|
|
||||||
private String savingsAccountId = "";
|
|
||||||
|
|
||||||
private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService;
|
private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService;
|
||||||
|
|
||||||
@@ -65,32 +61,32 @@ public class RecurringDepositTransactionImportHandler implements ImportHandler {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Count process(Workbook workbook, String locale, String dateFormat) {
|
public Count process(final Workbook workbook, final String locale, final String dateFormat) {
|
||||||
this.workbook = workbook;
|
List<SavingsAccountTransactionData> savingsTransactions = readExcelFile(workbook, locale, dateFormat);
|
||||||
this.savingsTransactions = new ArrayList<>();
|
return importEntity(workbook, savingsTransactions, dateFormat);
|
||||||
readExcelFile(locale, dateFormat);
|
|
||||||
return importEntity(dateFormat);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public void readExcelFile(String locale, String dateFormat) {
|
public List<SavingsAccountTransactionData> readExcelFile(final Workbook workbook, final String locale, final String dateFormat) {
|
||||||
|
List<SavingsAccountTransactionData> savingsTransactions = new ArrayList<>();
|
||||||
Sheet savingsTransactionSheet = workbook.getSheet(TemplatePopulateImportConstants.SAVINGS_TRANSACTION_SHEET_NAME);
|
Sheet savingsTransactionSheet = workbook.getSheet(TemplatePopulateImportConstants.SAVINGS_TRANSACTION_SHEET_NAME);
|
||||||
Integer noOfEntries = ImportHandlerUtils.getNumberOfRows(savingsTransactionSheet, TransactionConstants.AMOUNT_COL);
|
Integer noOfEntries = ImportHandlerUtils.getNumberOfRows(savingsTransactionSheet, TransactionConstants.AMOUNT_COL);
|
||||||
|
Long savingsAccountId = null;
|
||||||
for (int rowIndex = 1; rowIndex <= noOfEntries; rowIndex++) {
|
for (int rowIndex = 1; rowIndex <= noOfEntries; rowIndex++) {
|
||||||
Row row;
|
Row row;
|
||||||
row = savingsTransactionSheet.getRow(rowIndex);
|
row = savingsTransactionSheet.getRow(rowIndex);
|
||||||
if (ImportHandlerUtils.isNotImported(row, TransactionConstants.STATUS_COL)) {
|
if (ImportHandlerUtils.isNotImported(row, TransactionConstants.STATUS_COL)) {
|
||||||
savingsTransactions.add(readSavingsTransaction(row, locale, dateFormat));
|
savingsTransactions.add(readSavingsTransaction(workbook, row, savingsAccountId, locale, dateFormat));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
return savingsTransactions;
|
||||||
}
|
}
|
||||||
|
|
||||||
private SavingsAccountTransactionData readSavingsTransaction(Row row, String locale, String dateFormat) {
|
private SavingsAccountTransactionData readSavingsTransaction(final Workbook workbook, final Row row, Long savingsAccountId,
|
||||||
String savingsAccountIdCheck = null;
|
final String locale, final String dateFormat) {
|
||||||
if (ImportHandlerUtils.readAsLong(TransactionConstants.SAVINGS_ACCOUNT_NO_COL, row) != null) {
|
Long internalSavingsAccountId = ImportHandlerUtils.readAsLong(TransactionConstants.SAVINGS_ACCOUNT_NO_COL, row);
|
||||||
savingsAccountIdCheck = ImportHandlerUtils.readAsLong(TransactionConstants.SAVINGS_ACCOUNT_NO_COL, row).toString();
|
|
||||||
}
|
if (internalSavingsAccountId != null) {
|
||||||
if (savingsAccountIdCheck != null) {
|
savingsAccountId = internalSavingsAccountId;
|
||||||
savingsAccountId = savingsAccountIdCheck;
|
|
||||||
}
|
}
|
||||||
String transactionType = ImportHandlerUtils.readAsString(TransactionConstants.TRANSACTION_TYPE_COL, row);
|
String transactionType = ImportHandlerUtils.readAsString(TransactionConstants.TRANSACTION_TYPE_COL, row);
|
||||||
SavingsAccountTransactionEnumData savingsAccountTransactionEnumData = new SavingsAccountTransactionEnumData(null, null,
|
SavingsAccountTransactionEnumData savingsAccountTransactionEnumData = new SavingsAccountTransactionEnumData(null, null,
|
||||||
@@ -111,12 +107,12 @@ public class RecurringDepositTransactionImportHandler implements ImportHandler {
|
|||||||
String receiptNumber = ImportHandlerUtils.readAsString(TransactionConstants.RECEIPT_NO_COL, row);
|
String receiptNumber = ImportHandlerUtils.readAsString(TransactionConstants.RECEIPT_NO_COL, row);
|
||||||
String bankNumber = ImportHandlerUtils.readAsString(TransactionConstants.BANK_NO_COL, row);
|
String bankNumber = ImportHandlerUtils.readAsString(TransactionConstants.BANK_NO_COL, row);
|
||||||
return SavingsAccountTransactionData.importInstance(amount, transactionDate, paymentTypeId, accountNumber, checkNumber, routingCode,
|
return SavingsAccountTransactionData.importInstance(amount, transactionDate, paymentTypeId, accountNumber, checkNumber, routingCode,
|
||||||
receiptNumber, bankNumber, Long.parseLong(savingsAccountId), savingsAccountTransactionEnumData, row.getRowNum(), locale,
|
receiptNumber, bankNumber, savingsAccountId, savingsAccountTransactionEnumData, row.getRowNum(), locale, dateFormat);
|
||||||
dateFormat);
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public Count importEntity(String dateFormat) {
|
public Count importEntity(final Workbook workbook, final List<SavingsAccountTransactionData> savingsTransactions,
|
||||||
|
final String dateFormat) {
|
||||||
Sheet savingsTransactionSheet = workbook.getSheet(TemplatePopulateImportConstants.SAVINGS_TRANSACTION_SHEET_NAME);
|
Sheet savingsTransactionSheet = workbook.getSheet(TemplatePopulateImportConstants.SAVINGS_TRANSACTION_SHEET_NAME);
|
||||||
int successCount = 0;
|
int successCount = 0;
|
||||||
int errorCount = 0;
|
int errorCount = 0;
|
||||||
@@ -145,7 +141,7 @@ public class RecurringDepositTransactionImportHandler implements ImportHandler {
|
|||||||
.withJson(payload) //
|
.withJson(payload) //
|
||||||
.build();
|
.build();
|
||||||
}
|
}
|
||||||
final CommandProcessingResult result = commandsSourceWritePlatformService.logCommandSource(commandRequest);
|
commandsSourceWritePlatformService.logCommandSource(commandRequest);
|
||||||
successCount++;
|
successCount++;
|
||||||
Cell statusCell = savingsTransactionSheet.getRow(transaction.getRowIndex()).createCell(TransactionConstants.STATUS_COL);
|
Cell statusCell = savingsTransactionSheet.getRow(transaction.getRowIndex()).createCell(TransactionConstants.STATUS_COL);
|
||||||
statusCell.setCellValue(TemplatePopulateImportConstants.STATUS_CELL_IMPORTED);
|
statusCell.setCellValue(TemplatePopulateImportConstants.STATUS_CELL_IMPORTED);
|
||||||
|
|||||||
+43
-40
@@ -55,13 +55,13 @@ import org.springframework.stereotype.Service;
|
|||||||
@Service
|
@Service
|
||||||
public class SavingsImportHandler implements ImportHandler {
|
public class SavingsImportHandler implements ImportHandler {
|
||||||
|
|
||||||
|
public static final String DAILY = "Daily";
|
||||||
|
public static final String MONTHLY = "Monthly";
|
||||||
|
public static final String QUARTERLY = "Quarterly";
|
||||||
|
public static final String SEMI_ANNUAL = "Semi-Annual";
|
||||||
|
public static final String ANNUALLY = "Annually";
|
||||||
|
public static final String BI_ANNUAL = "BiAnnual";
|
||||||
private static final Logger LOG = LoggerFactory.getLogger(SavingsImportHandler.class);
|
private static final Logger LOG = LoggerFactory.getLogger(SavingsImportHandler.class);
|
||||||
private Workbook workbook;
|
|
||||||
private List<SavingsAccountData> savings;
|
|
||||||
private List<SavingsApproval> approvalDates;
|
|
||||||
private List<SavingsActivation> activationDates;
|
|
||||||
private List<String> statuses;
|
|
||||||
|
|
||||||
private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService;
|
private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService;
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
@@ -70,24 +70,24 @@ public class SavingsImportHandler implements ImportHandler {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Count process(Workbook workbook, String locale, String dateFormat) {
|
public Count process(final Workbook workbook, final String locale, final String dateFormat) {
|
||||||
this.workbook = workbook;
|
List<SavingsAccountData> savings = new ArrayList<>();
|
||||||
this.savings = new ArrayList<>();
|
List<SavingsApproval> approvalDates = new ArrayList<>();
|
||||||
this.approvalDates = new ArrayList<>();
|
List<SavingsActivation> activationDates = new ArrayList<>();
|
||||||
this.activationDates = new ArrayList<>();
|
List<String> statuses = new ArrayList<>();
|
||||||
this.statuses = new ArrayList<>();
|
readExcelFile(workbook, savings, approvalDates, activationDates, statuses, locale, dateFormat);
|
||||||
readExcelFile(locale, dateFormat);
|
return importEntity(workbook, savings, approvalDates, activationDates, statuses, dateFormat);
|
||||||
return importEntity(dateFormat);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public void readExcelFile(String locale, String dateFormat) {
|
public void readExcelFile(final Workbook workbook, final List<SavingsAccountData> savings, final List<SavingsApproval> approvalDates,
|
||||||
|
final List<SavingsActivation> activationDates, final List<String> statuses, final String locale, final String dateFormat) {
|
||||||
Sheet savingsSheet = workbook.getSheet(TemplatePopulateImportConstants.SAVINGS_ACCOUNTS_SHEET_NAME);
|
Sheet savingsSheet = workbook.getSheet(TemplatePopulateImportConstants.SAVINGS_ACCOUNTS_SHEET_NAME);
|
||||||
Integer noOfEntries = ImportHandlerUtils.getNumberOfRows(savingsSheet, TemplatePopulateImportConstants.FIRST_COLUMN_INDEX);
|
Integer noOfEntries = ImportHandlerUtils.getNumberOfRows(savingsSheet, TemplatePopulateImportConstants.FIRST_COLUMN_INDEX);
|
||||||
for (int rowIndex = 1; rowIndex <= noOfEntries; rowIndex++) {
|
for (int rowIndex = 1; rowIndex <= noOfEntries; rowIndex++) {
|
||||||
Row row;
|
Row row;
|
||||||
row = savingsSheet.getRow(rowIndex);
|
row = savingsSheet.getRow(rowIndex);
|
||||||
if (ImportHandlerUtils.isNotImported(row, SavingsConstants.STATUS_COL)) {
|
if (ImportHandlerUtils.isNotImported(row, SavingsConstants.STATUS_COL)) {
|
||||||
savings.add(readSavings(row, locale, dateFormat));
|
savings.add(readSavings(workbook, row, statuses, locale, dateFormat));
|
||||||
approvalDates.add(readSavingsApproval(row, locale, dateFormat));
|
approvalDates.add(readSavingsApproval(row, locale, dateFormat));
|
||||||
activationDates.add(readSavingsActivation(row, locale, dateFormat));
|
activationDates.add(readSavingsActivation(row, locale, dateFormat));
|
||||||
}
|
}
|
||||||
@@ -112,7 +112,8 @@ public class SavingsImportHandler implements ImportHandler {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private SavingsAccountData readSavings(Row row, String locale, String dateFormat) {
|
private SavingsAccountData readSavings(final Workbook workbook, final Row row, final List<String> statuses, final String locale,
|
||||||
|
final String dateFormat) {
|
||||||
String productName = ImportHandlerUtils.readAsString(SavingsConstants.PRODUCT_COL, row);
|
String productName = ImportHandlerUtils.readAsString(SavingsConstants.PRODUCT_COL, row);
|
||||||
Long productId = ImportHandlerUtils.getIdByName(workbook.getSheet(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME), productName);
|
Long productId = ImportHandlerUtils.getIdByName(workbook.getSheet(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME), productName);
|
||||||
String fieldOfficerName = ImportHandlerUtils.readAsString(SavingsConstants.FIELD_OFFICER_NAME_COL, row);
|
String fieldOfficerName = ImportHandlerUtils.readAsString(SavingsConstants.FIELD_OFFICER_NAME_COL, row);
|
||||||
@@ -129,15 +130,15 @@ public class SavingsImportHandler implements ImportHandler {
|
|||||||
Long interestCompoundingPeriodTypeId = null;
|
Long interestCompoundingPeriodTypeId = null;
|
||||||
EnumOptionData interestCompoundingPeriodTypeEnum = null;
|
EnumOptionData interestCompoundingPeriodTypeEnum = null;
|
||||||
if (interestCompoundingPeriodType != null) {
|
if (interestCompoundingPeriodType != null) {
|
||||||
if (interestCompoundingPeriodType.equalsIgnoreCase("Daily")) {
|
if (interestCompoundingPeriodType.equalsIgnoreCase(DAILY)) {
|
||||||
interestCompoundingPeriodTypeId = 1L;
|
interestCompoundingPeriodTypeId = 1L;
|
||||||
} else if (interestCompoundingPeriodType.equalsIgnoreCase("Monthly")) {
|
} else if (interestCompoundingPeriodType.equalsIgnoreCase(MONTHLY)) {
|
||||||
interestCompoundingPeriodTypeId = 4L;
|
interestCompoundingPeriodTypeId = 4L;
|
||||||
} else if (interestCompoundingPeriodType.equalsIgnoreCase("Quarterly")) {
|
} else if (interestCompoundingPeriodType.equalsIgnoreCase(QUARTERLY)) {
|
||||||
interestCompoundingPeriodTypeId = 5L;
|
interestCompoundingPeriodTypeId = 5L;
|
||||||
} else if (interestCompoundingPeriodType.equalsIgnoreCase("Semi-Annual")) {
|
} else if (interestCompoundingPeriodType.equalsIgnoreCase(SEMI_ANNUAL)) {
|
||||||
interestCompoundingPeriodTypeId = 6L;
|
interestCompoundingPeriodTypeId = 6L;
|
||||||
} else if (interestCompoundingPeriodType.equalsIgnoreCase("Annually")) {
|
} else if (interestCompoundingPeriodType.equalsIgnoreCase(ANNUALLY)) {
|
||||||
interestCompoundingPeriodTypeId = 7L;
|
interestCompoundingPeriodTypeId = 7L;
|
||||||
}
|
}
|
||||||
interestCompoundingPeriodTypeEnum = new EnumOptionData(interestCompoundingPeriodTypeId, null, null);
|
interestCompoundingPeriodTypeEnum = new EnumOptionData(interestCompoundingPeriodTypeId, null, null);
|
||||||
@@ -146,13 +147,13 @@ public class SavingsImportHandler implements ImportHandler {
|
|||||||
Long interestPostingPeriodTypeId = null;
|
Long interestPostingPeriodTypeId = null;
|
||||||
EnumOptionData interestPostingPeriodTypeEnum = null;
|
EnumOptionData interestPostingPeriodTypeEnum = null;
|
||||||
if (interestPostingPeriodType != null) {
|
if (interestPostingPeriodType != null) {
|
||||||
if (interestPostingPeriodType.equalsIgnoreCase("Monthly")) {
|
if (interestPostingPeriodType.equalsIgnoreCase(MONTHLY)) {
|
||||||
interestPostingPeriodTypeId = 4L;
|
interestPostingPeriodTypeId = 4L;
|
||||||
} else if (interestPostingPeriodType.equalsIgnoreCase("Quarterly")) {
|
} else if (interestPostingPeriodType.equalsIgnoreCase(QUARTERLY)) {
|
||||||
interestPostingPeriodTypeId = 5L;
|
interestPostingPeriodTypeId = 5L;
|
||||||
} else if (interestPostingPeriodType.equalsIgnoreCase("Annually")) {
|
} else if (interestPostingPeriodType.equalsIgnoreCase(ANNUALLY)) {
|
||||||
interestPostingPeriodTypeId = 7L;
|
interestPostingPeriodTypeId = 7L;
|
||||||
} else if (interestPostingPeriodType.equalsIgnoreCase("BiAnnual")) {
|
} else if (interestPostingPeriodType.equalsIgnoreCase(BI_ANNUAL)) {
|
||||||
interestPostingPeriodTypeId = 6L;
|
interestPostingPeriodTypeId = 6L;
|
||||||
}
|
}
|
||||||
interestPostingPeriodTypeEnum = new EnumOptionData(interestPostingPeriodTypeId, null, null);
|
interestPostingPeriodTypeEnum = new EnumOptionData(interestPostingPeriodTypeId, null, null);
|
||||||
@@ -264,7 +265,8 @@ public class SavingsImportHandler implements ImportHandler {
|
|||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public Count importEntity(String dateFormat) {
|
public Count importEntity(final Workbook workbook, final List<SavingsAccountData> savings, final List<SavingsApproval> approvalDates,
|
||||||
|
final List<SavingsActivation> activationDates, final List<String> statuses, final String dateFormat) {
|
||||||
Sheet savingsSheet = workbook.getSheet(TemplatePopulateImportConstants.SAVINGS_ACCOUNTS_SHEET_NAME);
|
Sheet savingsSheet = workbook.getSheet(TemplatePopulateImportConstants.SAVINGS_ACCOUNTS_SHEET_NAME);
|
||||||
int successCount = 0;
|
int successCount = 0;
|
||||||
int errorCount = 0;
|
int errorCount = 0;
|
||||||
@@ -280,7 +282,7 @@ public class SavingsImportHandler implements ImportHandler {
|
|||||||
progressLevel = getProgressLevel(status);
|
progressLevel = getProgressLevel(status);
|
||||||
|
|
||||||
if (progressLevel == 0) {
|
if (progressLevel == 0) {
|
||||||
CommandProcessingResult result = importSavings(i, dateFormat);
|
CommandProcessingResult result = importSavings(savings, i, dateFormat);
|
||||||
savingsId = result.getSavingsId();
|
savingsId = result.getSavingsId();
|
||||||
progressLevel = 1;
|
progressLevel = 1;
|
||||||
} else {
|
} else {
|
||||||
@@ -289,11 +291,11 @@ public class SavingsImportHandler implements ImportHandler {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (progressLevel <= 1) {
|
if (progressLevel <= 1) {
|
||||||
progressLevel = importSavingsApproval(savingsId, i, dateFormat);
|
progressLevel = importSavingsApproval(approvalDates, savingsId, i, dateFormat);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (progressLevel <= 2) {
|
if (progressLevel <= 2) {
|
||||||
progressLevel = importSavingsActivation(savingsId, i, dateFormat);
|
progressLevel = importSavingsActivation(activationDates, savingsId, i, dateFormat);
|
||||||
}
|
}
|
||||||
successCount++;
|
successCount++;
|
||||||
statusCell.setCellValue(TemplatePopulateImportConstants.STATUS_CELL_IMPORTED);
|
statusCell.setCellValue(TemplatePopulateImportConstants.STATUS_CELL_IMPORTED);
|
||||||
@@ -302,15 +304,15 @@ public class SavingsImportHandler implements ImportHandler {
|
|||||||
errorCount++;
|
errorCount++;
|
||||||
LOG.error("Problem occurred in importEntity function", ex);
|
LOG.error("Problem occurred in importEntity function", ex);
|
||||||
errorMessage = ImportHandlerUtils.getErrorMessage(ex);
|
errorMessage = ImportHandlerUtils.getErrorMessage(ex);
|
||||||
writeSavingsErrorMessage(savingsId, errorMessage, progressLevel, statusCell, errorReportCell, row);
|
writeSavingsErrorMessage(workbook, savingsId, errorMessage, progressLevel, statusCell, errorReportCell, row);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
setReportHeaders(savingsSheet);
|
setReportHeaders(savingsSheet);
|
||||||
return Count.instance(successCount, errorCount);
|
return Count.instance(successCount, errorCount);
|
||||||
}
|
}
|
||||||
|
|
||||||
private void writeSavingsErrorMessage(Long savingsId, String errorMessage, int progressLevel, Cell statusCell, Cell errorReportCell,
|
private void writeSavingsErrorMessage(final Workbook workbook, final Long savingsId, final String errorMessage, final int progressLevel,
|
||||||
Row row) {
|
final Cell statusCell, final Cell errorReportCell, final Row row) {
|
||||||
String status = "";
|
String status = "";
|
||||||
|
|
||||||
if (progressLevel == 0) {
|
if (progressLevel == 0) {
|
||||||
@@ -340,7 +342,8 @@ public class SavingsImportHandler implements ImportHandler {
|
|||||||
TemplatePopulateImportConstants.FAILURE_COL_REPORT_HEADER);
|
TemplatePopulateImportConstants.FAILURE_COL_REPORT_HEADER);
|
||||||
}
|
}
|
||||||
|
|
||||||
private int importSavingsActivation(Long savingsId, int i, String dateFormat) {
|
private int importSavingsActivation(final List<SavingsActivation> activationDates, final Long savingsId, final int i,
|
||||||
|
final String dateFormat) {
|
||||||
if (activationDates.get(i) != null) {
|
if (activationDates.get(i) != null) {
|
||||||
GsonBuilder gsonBuilder = GoogleGsonSerializerHelper.createGsonBuilder();
|
GsonBuilder gsonBuilder = GoogleGsonSerializerHelper.createGsonBuilder();
|
||||||
gsonBuilder.registerTypeAdapter(LocalDate.class, new DateSerializer(dateFormat));
|
gsonBuilder.registerTypeAdapter(LocalDate.class, new DateSerializer(dateFormat));
|
||||||
@@ -349,12 +352,13 @@ public class SavingsImportHandler implements ImportHandler {
|
|||||||
.savingsAccountActivation(savingsId)//
|
.savingsAccountActivation(savingsId)//
|
||||||
.withJson(payload) //
|
.withJson(payload) //
|
||||||
.build(); //
|
.build(); //
|
||||||
final CommandProcessingResult result = commandsSourceWritePlatformService.logCommandSource(commandRequest);
|
commandsSourceWritePlatformService.logCommandSource(commandRequest);
|
||||||
}
|
}
|
||||||
return 3;
|
return 3;
|
||||||
}
|
}
|
||||||
|
|
||||||
private int importSavingsApproval(Long savingsId, int i, String dateFormat) {
|
private int importSavingsApproval(final List<SavingsApproval> approvalDates, final Long savingsId, final int i,
|
||||||
|
final String dateFormat) {
|
||||||
if (approvalDates.get(i) != null) {
|
if (approvalDates.get(i) != null) {
|
||||||
GsonBuilder gsonBuilder = GoogleGsonSerializerHelper.createGsonBuilder();
|
GsonBuilder gsonBuilder = GoogleGsonSerializerHelper.createGsonBuilder();
|
||||||
gsonBuilder.registerTypeAdapter(LocalDate.class, new DateSerializer(dateFormat));
|
gsonBuilder.registerTypeAdapter(LocalDate.class, new DateSerializer(dateFormat));
|
||||||
@@ -363,12 +367,12 @@ public class SavingsImportHandler implements ImportHandler {
|
|||||||
.approveSavingsAccountApplication(savingsId)//
|
.approveSavingsAccountApplication(savingsId)//
|
||||||
.withJson(payload) //
|
.withJson(payload) //
|
||||||
.build(); //
|
.build(); //
|
||||||
final CommandProcessingResult result = commandsSourceWritePlatformService.logCommandSource(commandRequest);
|
commandsSourceWritePlatformService.logCommandSource(commandRequest);
|
||||||
}
|
}
|
||||||
return 2;
|
return 2;
|
||||||
}
|
}
|
||||||
|
|
||||||
private CommandProcessingResult importSavings(int i, String dateFormat) {
|
private CommandProcessingResult importSavings(final List<SavingsAccountData> savings, final int i, final String dateFormat) {
|
||||||
GsonBuilder gsonBuilder = GoogleGsonSerializerHelper.createGsonBuilder();
|
GsonBuilder gsonBuilder = GoogleGsonSerializerHelper.createGsonBuilder();
|
||||||
gsonBuilder.registerTypeAdapter(LocalDate.class, new DateSerializer(dateFormat));
|
gsonBuilder.registerTypeAdapter(LocalDate.class, new DateSerializer(dateFormat));
|
||||||
gsonBuilder.registerTypeAdapter(EnumOptionData.class, new EnumOptionDataIdSerializer());
|
gsonBuilder.registerTypeAdapter(EnumOptionData.class, new EnumOptionDataIdSerializer());
|
||||||
@@ -379,8 +383,7 @@ public class SavingsImportHandler implements ImportHandler {
|
|||||||
.createSavingsAccount() //
|
.createSavingsAccount() //
|
||||||
.withJson(payload) //
|
.withJson(payload) //
|
||||||
.build(); //
|
.build(); //
|
||||||
final CommandProcessingResult result = commandsSourceWritePlatformService.logCommandSource(commandRequest);
|
return commandsSourceWritePlatformService.logCommandSource(commandRequest);
|
||||||
return result;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private int getProgressLevel(String status) {
|
private int getProgressLevel(String status) {
|
||||||
|
|||||||
+26
-26
@@ -34,7 +34,6 @@ import org.apache.fineract.infrastructure.bulkimport.importhandler.ImportHandler
|
|||||||
import org.apache.fineract.infrastructure.bulkimport.importhandler.ImportHandlerUtils;
|
import org.apache.fineract.infrastructure.bulkimport.importhandler.ImportHandlerUtils;
|
||||||
import org.apache.fineract.infrastructure.bulkimport.importhandler.helper.DateSerializer;
|
import org.apache.fineract.infrastructure.bulkimport.importhandler.helper.DateSerializer;
|
||||||
import org.apache.fineract.infrastructure.bulkimport.importhandler.helper.SavingsAccountTransactionEnumValueSerialiser;
|
import org.apache.fineract.infrastructure.bulkimport.importhandler.helper.SavingsAccountTransactionEnumValueSerialiser;
|
||||||
import org.apache.fineract.infrastructure.core.data.CommandProcessingResult;
|
|
||||||
import org.apache.fineract.infrastructure.core.serialization.GoogleGsonSerializerHelper;
|
import org.apache.fineract.infrastructure.core.serialization.GoogleGsonSerializerHelper;
|
||||||
import org.apache.fineract.portfolio.savings.data.SavingsAccountTransactionData;
|
import org.apache.fineract.portfolio.savings.data.SavingsAccountTransactionData;
|
||||||
import org.apache.fineract.portfolio.savings.data.SavingsAccountTransactionEnumData;
|
import org.apache.fineract.portfolio.savings.data.SavingsAccountTransactionEnumData;
|
||||||
@@ -51,11 +50,12 @@ import org.springframework.stereotype.Service;
|
|||||||
@Service
|
@Service
|
||||||
public class SavingsTransactionImportHandler implements ImportHandler {
|
public class SavingsTransactionImportHandler implements ImportHandler {
|
||||||
|
|
||||||
|
public static final String TRANSACTION_TYPE = "transactionType";
|
||||||
|
public static final String REVERSED = "reversed";
|
||||||
|
public static final String INTERESTED_POSTED_AS_ON = "interestedPostedAsOn";
|
||||||
|
public static final String WITHDRAWAL = "Withdrawal";
|
||||||
|
public static final String DEPOSIT = "Deposit";
|
||||||
private static final Logger LOG = LoggerFactory.getLogger(SavingsTransactionImportHandler.class);
|
private static final Logger LOG = LoggerFactory.getLogger(SavingsTransactionImportHandler.class);
|
||||||
private Workbook workbook;
|
|
||||||
private List<SavingsAccountTransactionData> savingsTransactions;
|
|
||||||
private String savingsAccountId = "";
|
|
||||||
|
|
||||||
private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService;
|
private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService;
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
@@ -64,30 +64,30 @@ public class SavingsTransactionImportHandler implements ImportHandler {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Count process(Workbook workbook, String locale, String dateFormat) {
|
public Count process(final Workbook workbook, final String locale, final String dateFormat) {
|
||||||
this.workbook = workbook;
|
List<SavingsAccountTransactionData> savingsTransactions = readExcelFile(workbook, locale, dateFormat);
|
||||||
this.savingsTransactions = new ArrayList<>();
|
return importEntity(workbook, savingsTransactions, dateFormat);
|
||||||
readExcelFile(locale, dateFormat);
|
|
||||||
return importEntity(dateFormat);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public void readExcelFile(String locale, String dateFormat) {
|
private List<SavingsAccountTransactionData> readExcelFile(final Workbook workbook, final String locale, final String dateFormat) {
|
||||||
|
List<SavingsAccountTransactionData> savingsTransactions = new ArrayList<>();
|
||||||
Sheet savingsTransactionSheet = workbook.getSheet(TemplatePopulateImportConstants.SAVINGS_TRANSACTION_SHEET_NAME);
|
Sheet savingsTransactionSheet = workbook.getSheet(TemplatePopulateImportConstants.SAVINGS_TRANSACTION_SHEET_NAME);
|
||||||
Integer noOfEntries = ImportHandlerUtils.getNumberOfRows(savingsTransactionSheet, TransactionConstants.AMOUNT_COL);
|
Integer noOfEntries = ImportHandlerUtils.getNumberOfRows(savingsTransactionSheet, TransactionConstants.AMOUNT_COL);
|
||||||
|
Long savingsAccountId = null;
|
||||||
for (int rowIndex = 1; rowIndex <= noOfEntries; rowIndex++) {
|
for (int rowIndex = 1; rowIndex <= noOfEntries; rowIndex++) {
|
||||||
Row row;
|
Row row;
|
||||||
row = savingsTransactionSheet.getRow(rowIndex);
|
row = savingsTransactionSheet.getRow(rowIndex);
|
||||||
if (ImportHandlerUtils.isNotImported(row, TransactionConstants.STATUS_COL)) {
|
if (ImportHandlerUtils.isNotImported(row, TransactionConstants.STATUS_COL)) {
|
||||||
savingsTransactions.add(readSavingsTransaction(row, locale, dateFormat));
|
savingsTransactions.add(readSavingsTransaction(workbook, row, savingsAccountId, locale, dateFormat));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
return savingsTransactions;
|
||||||
}
|
}
|
||||||
|
|
||||||
private SavingsAccountTransactionData readSavingsTransaction(Row row, String locale, String dateFormat) {
|
private SavingsAccountTransactionData readSavingsTransaction(final Workbook workbook, final Row row, Long savingsAccountId,
|
||||||
String savingsAccountIdCheck = null;
|
final String locale, final String dateFormat) {
|
||||||
if (ImportHandlerUtils.readAsLong(TransactionConstants.SAVINGS_ACCOUNT_NO_COL, row) != null) {
|
Long savingsAccountIdCheck = ImportHandlerUtils.readAsLong(TransactionConstants.SAVINGS_ACCOUNT_NO_COL, row);
|
||||||
savingsAccountIdCheck = ImportHandlerUtils.readAsLong(TransactionConstants.SAVINGS_ACCOUNT_NO_COL, row).toString();
|
|
||||||
}
|
|
||||||
if (savingsAccountIdCheck != null) {
|
if (savingsAccountIdCheck != null) {
|
||||||
savingsAccountId = savingsAccountIdCheck;
|
savingsAccountId = savingsAccountIdCheck;
|
||||||
}
|
}
|
||||||
@@ -110,12 +110,12 @@ public class SavingsTransactionImportHandler implements ImportHandler {
|
|||||||
String receiptNumber = ImportHandlerUtils.readAsString(TransactionConstants.RECEIPT_NO_COL, row);
|
String receiptNumber = ImportHandlerUtils.readAsString(TransactionConstants.RECEIPT_NO_COL, row);
|
||||||
String bankNumber = ImportHandlerUtils.readAsString(TransactionConstants.BANK_NO_COL, row);
|
String bankNumber = ImportHandlerUtils.readAsString(TransactionConstants.BANK_NO_COL, row);
|
||||||
return SavingsAccountTransactionData.importInstance(amount, transactionDate, paymentTypeId, accountNumber, checkNumber, routingCode,
|
return SavingsAccountTransactionData.importInstance(amount, transactionDate, paymentTypeId, accountNumber, checkNumber, routingCode,
|
||||||
receiptNumber, bankNumber, Long.parseLong(savingsAccountId), savingsAccountTransactionEnumData, row.getRowNum(), locale,
|
receiptNumber, bankNumber, savingsAccountId, savingsAccountTransactionEnumData, row.getRowNum(), locale, dateFormat);
|
||||||
dateFormat);
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public Count importEntity(String dateFormat) {
|
private Count importEntity(final Workbook workbook, final List<SavingsAccountTransactionData> savingsTransactions,
|
||||||
|
final String dateFormat) {
|
||||||
Sheet savingsTransactionSheet = workbook.getSheet(TemplatePopulateImportConstants.SAVINGS_TRANSACTION_SHEET_NAME);
|
Sheet savingsTransactionSheet = workbook.getSheet(TemplatePopulateImportConstants.SAVINGS_TRANSACTION_SHEET_NAME);
|
||||||
int successCount = 0;
|
int successCount = 0;
|
||||||
int errorCount = 0;
|
int errorCount = 0;
|
||||||
@@ -127,24 +127,24 @@ public class SavingsTransactionImportHandler implements ImportHandler {
|
|||||||
for (SavingsAccountTransactionData transaction : savingsTransactions) {
|
for (SavingsAccountTransactionData transaction : savingsTransactions) {
|
||||||
try {
|
try {
|
||||||
JsonObject savingsTransactionJsonob = gsonBuilder.create().toJsonTree(transaction).getAsJsonObject();
|
JsonObject savingsTransactionJsonob = gsonBuilder.create().toJsonTree(transaction).getAsJsonObject();
|
||||||
savingsTransactionJsonob.remove("transactionType");
|
savingsTransactionJsonob.remove(TRANSACTION_TYPE);
|
||||||
savingsTransactionJsonob.remove("reversed");
|
savingsTransactionJsonob.remove(REVERSED);
|
||||||
savingsTransactionJsonob.remove("interestedPostedAsOn");
|
savingsTransactionJsonob.remove(INTERESTED_POSTED_AS_ON);
|
||||||
String payload = savingsTransactionJsonob.toString();
|
String payload = savingsTransactionJsonob.toString();
|
||||||
CommandWrapper commandRequest = null;
|
CommandWrapper commandRequest = null;
|
||||||
if (transaction.getTransactionType().getValue().equals("Withdrawal")) {
|
if (transaction.getTransactionType().getValue().equals(WITHDRAWAL)) {
|
||||||
commandRequest = new CommandWrapperBuilder() //
|
commandRequest = new CommandWrapperBuilder() //
|
||||||
.savingsAccountWithdrawal(transaction.getSavingsAccountId()) //
|
.savingsAccountWithdrawal(transaction.getSavingsAccountId()) //
|
||||||
.withJson(payload) //
|
.withJson(payload) //
|
||||||
.build(); //
|
.build(); //
|
||||||
|
|
||||||
} else if (transaction.getTransactionType().getValue().equals("Deposit")) {
|
} else if (transaction.getTransactionType().getValue().equals(DEPOSIT)) {
|
||||||
commandRequest = new CommandWrapperBuilder() //
|
commandRequest = new CommandWrapperBuilder() //
|
||||||
.savingsAccountDeposit(transaction.getSavingsAccountId()) //
|
.savingsAccountDeposit(transaction.getSavingsAccountId()) //
|
||||||
.withJson(payload) //
|
.withJson(payload) //
|
||||||
.build();
|
.build();
|
||||||
}
|
}
|
||||||
final CommandProcessingResult result = commandsSourceWritePlatformService.logCommandSource(commandRequest);
|
commandsSourceWritePlatformService.logCommandSource(commandRequest);
|
||||||
successCount++;
|
successCount++;
|
||||||
Cell statusCell = savingsTransactionSheet.getRow(transaction.getRowIndex()).createCell(TransactionConstants.STATUS_COL);
|
Cell statusCell = savingsTransactionSheet.getRow(transaction.getRowIndex()).createCell(TransactionConstants.STATUS_COL);
|
||||||
statusCell.setCellValue(TemplatePopulateImportConstants.STATUS_CELL_IMPORTED);
|
statusCell.setCellValue(TemplatePopulateImportConstants.STATUS_CELL_IMPORTED);
|
||||||
|
|||||||
+18
-19
@@ -32,7 +32,6 @@ import org.apache.fineract.infrastructure.bulkimport.data.Count;
|
|||||||
import org.apache.fineract.infrastructure.bulkimport.importhandler.ImportHandler;
|
import org.apache.fineract.infrastructure.bulkimport.importhandler.ImportHandler;
|
||||||
import org.apache.fineract.infrastructure.bulkimport.importhandler.ImportHandlerUtils;
|
import org.apache.fineract.infrastructure.bulkimport.importhandler.ImportHandlerUtils;
|
||||||
import org.apache.fineract.infrastructure.bulkimport.importhandler.helper.DateSerializer;
|
import org.apache.fineract.infrastructure.bulkimport.importhandler.helper.DateSerializer;
|
||||||
import org.apache.fineract.infrastructure.core.data.CommandProcessingResult;
|
|
||||||
import org.apache.fineract.infrastructure.core.serialization.GoogleGsonSerializerHelper;
|
import org.apache.fineract.infrastructure.core.serialization.GoogleGsonSerializerHelper;
|
||||||
import org.apache.fineract.portfolio.shareaccounts.data.ShareAccountChargeData;
|
import org.apache.fineract.portfolio.shareaccounts.data.ShareAccountChargeData;
|
||||||
import org.apache.fineract.portfolio.shareaccounts.data.ShareAccountData;
|
import org.apache.fineract.portfolio.shareaccounts.data.ShareAccountData;
|
||||||
@@ -49,11 +48,10 @@ import org.springframework.stereotype.Service;
|
|||||||
@Service
|
@Service
|
||||||
public class SharedAccountImportHandler implements ImportHandler {
|
public class SharedAccountImportHandler implements ImportHandler {
|
||||||
|
|
||||||
|
public static final String ZERO = "0";
|
||||||
|
public static final String SHARE = "share";
|
||||||
|
public static final String EMPTY_STR = "";
|
||||||
private static final Logger LOG = LoggerFactory.getLogger(SharedAccountImportHandler.class);
|
private static final Logger LOG = LoggerFactory.getLogger(SharedAccountImportHandler.class);
|
||||||
private Workbook workbook;
|
|
||||||
private List<ShareAccountData> shareAccountDataList;
|
|
||||||
private List<String> statuses;
|
|
||||||
|
|
||||||
private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService;
|
private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService;
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
@@ -62,27 +60,28 @@ public class SharedAccountImportHandler implements ImportHandler {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Count process(Workbook workbook, String locale, String dateFormat) {
|
public Count process(final Workbook workbook, final String locale, final String dateFormat) {
|
||||||
this.workbook = workbook;
|
List<ShareAccountData> shareAccountDataList = new ArrayList<>();
|
||||||
this.shareAccountDataList = new ArrayList<>();
|
List<String> statuses = new ArrayList<>();
|
||||||
statuses = new ArrayList<String>();
|
readExcelFile(workbook, shareAccountDataList, statuses, locale, dateFormat);
|
||||||
readExcelFile(locale, dateFormat);
|
return importEntity(workbook, shareAccountDataList, dateFormat);
|
||||||
return importEntity(dateFormat);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public void readExcelFile(String locale, String dateFormat) {
|
private void readExcelFile(final Workbook workbook, final List<ShareAccountData> shareAccountDataList, final List<String> statuses,
|
||||||
|
final String locale, String dateFormat) {
|
||||||
Sheet sharedAccountsSheet = workbook.getSheet(TemplatePopulateImportConstants.SHARED_ACCOUNTS_SHEET_NAME);
|
Sheet sharedAccountsSheet = workbook.getSheet(TemplatePopulateImportConstants.SHARED_ACCOUNTS_SHEET_NAME);
|
||||||
Integer noOfEntries = ImportHandlerUtils.getNumberOfRows(sharedAccountsSheet, TemplatePopulateImportConstants.FIRST_COLUMN_INDEX);
|
Integer noOfEntries = ImportHandlerUtils.getNumberOfRows(sharedAccountsSheet, TemplatePopulateImportConstants.FIRST_COLUMN_INDEX);
|
||||||
for (int rowIndex = 1; rowIndex <= noOfEntries; rowIndex++) {
|
for (int rowIndex = 1; rowIndex <= noOfEntries; rowIndex++) {
|
||||||
Row row;
|
Row row;
|
||||||
row = sharedAccountsSheet.getRow(rowIndex);
|
row = sharedAccountsSheet.getRow(rowIndex);
|
||||||
if (ImportHandlerUtils.isNotImported(row, SharedAccountsConstants.STATUS_COL)) {
|
if (ImportHandlerUtils.isNotImported(row, SharedAccountsConstants.STATUS_COL)) {
|
||||||
shareAccountDataList.add(readSharedAccount(row, locale, dateFormat));
|
shareAccountDataList.add(readSharedAccount(workbook, row, statuses, locale, dateFormat));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private ShareAccountData readSharedAccount(Row row, String locale, String dateFormat) {
|
private ShareAccountData readSharedAccount(final Workbook workbook, final Row row, final List<String> statuses, final String locale,
|
||||||
|
final String dateFormat) {
|
||||||
String clientName = ImportHandlerUtils.readAsString(SharedAccountsConstants.CLIENT_NAME_COL, row);
|
String clientName = ImportHandlerUtils.readAsString(SharedAccountsConstants.CLIENT_NAME_COL, row);
|
||||||
Long clientId = ImportHandlerUtils.getIdByName(workbook.getSheet(TemplatePopulateImportConstants.CLIENT_SHEET_NAME), clientName);
|
Long clientId = ImportHandlerUtils.getIdByName(workbook.getSheet(TemplatePopulateImportConstants.CLIENT_SHEET_NAME), clientName);
|
||||||
|
|
||||||
@@ -127,7 +126,7 @@ public class SharedAccountImportHandler implements ImportHandler {
|
|||||||
List<ShareAccountChargeData> charges = new ArrayList<>();
|
List<ShareAccountChargeData> charges = new ArrayList<>();
|
||||||
for (int cellNo = SharedAccountsConstants.CHARGES_NAME_1_COL; cellNo < SharedAccountsConstants.CHARGES_NAME_3_COL; cellNo += 2) {
|
for (int cellNo = SharedAccountsConstants.CHARGES_NAME_1_COL; cellNo < SharedAccountsConstants.CHARGES_NAME_3_COL; cellNo += 2) {
|
||||||
String chargeName = ImportHandlerUtils.readAsString(cellNo, row);
|
String chargeName = ImportHandlerUtils.readAsString(cellNo, row);
|
||||||
if (chargeName == null || chargeName.equals("0")) {
|
if (chargeName == null || chargeName.equals(ZERO)) {
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
Long chargeId = ImportHandlerUtils.getIdByName(workbook.getSheet(TemplatePopulateImportConstants.SHARED_PRODUCTS_SHEET_NAME),
|
Long chargeId = ImportHandlerUtils.getIdByName(workbook.getSheet(TemplatePopulateImportConstants.SHARED_PRODUCTS_SHEET_NAME),
|
||||||
@@ -149,11 +148,11 @@ public class SharedAccountImportHandler implements ImportHandler {
|
|||||||
defaultSavingsAccountId, row.getRowNum(), locale, dateFormat);
|
defaultSavingsAccountId, row.getRowNum(), locale, dateFormat);
|
||||||
}
|
}
|
||||||
|
|
||||||
public Count importEntity(String dateFormat) {
|
private Count importEntity(final Workbook workbook, final List<ShareAccountData> shareAccountDataList, final String dateFormat) {
|
||||||
Sheet sharedAccountsSheet = workbook.getSheet(TemplatePopulateImportConstants.SHARED_ACCOUNTS_SHEET_NAME);
|
Sheet sharedAccountsSheet = workbook.getSheet(TemplatePopulateImportConstants.SHARED_ACCOUNTS_SHEET_NAME);
|
||||||
int successCount = 0;
|
int successCount = 0;
|
||||||
int errorCount = 0;
|
int errorCount = 0;
|
||||||
String errorMessage = "";
|
String errorMessage;
|
||||||
GsonBuilder gsonBuilder = GoogleGsonSerializerHelper.createGsonBuilder();
|
GsonBuilder gsonBuilder = GoogleGsonSerializerHelper.createGsonBuilder();
|
||||||
gsonBuilder.registerTypeAdapter(LocalDate.class, new DateSerializer(dateFormat));
|
gsonBuilder.registerTypeAdapter(LocalDate.class, new DateSerializer(dateFormat));
|
||||||
|
|
||||||
@@ -161,10 +160,10 @@ public class SharedAccountImportHandler implements ImportHandler {
|
|||||||
try {
|
try {
|
||||||
String payload = gsonBuilder.create().toJson(shareAccountData);
|
String payload = gsonBuilder.create().toJson(shareAccountData);
|
||||||
final CommandWrapper commandRequest = new CommandWrapperBuilder() //
|
final CommandWrapper commandRequest = new CommandWrapperBuilder() //
|
||||||
.createAccount("share")//
|
.createAccount(SHARE)//
|
||||||
.withJson(payload) //
|
.withJson(payload) //
|
||||||
.build(); //
|
.build(); //
|
||||||
final CommandProcessingResult result = commandsSourceWritePlatformService.logCommandSource(commandRequest);
|
commandsSourceWritePlatformService.logCommandSource(commandRequest);
|
||||||
successCount++;
|
successCount++;
|
||||||
Cell statusCell = sharedAccountsSheet.getRow(shareAccountData.getRowIndex()).createCell(SharedAccountsConstants.STATUS_COL);
|
Cell statusCell = sharedAccountsSheet.getRow(shareAccountData.getRowIndex()).createCell(SharedAccountsConstants.STATUS_COL);
|
||||||
statusCell.setCellValue(TemplatePopulateImportConstants.STATUS_CELL_IMPORTED);
|
statusCell.setCellValue(TemplatePopulateImportConstants.STATUS_CELL_IMPORTED);
|
||||||
|
|||||||
+11
-15
@@ -31,7 +31,6 @@ import org.apache.fineract.infrastructure.bulkimport.data.Count;
|
|||||||
import org.apache.fineract.infrastructure.bulkimport.importhandler.ImportHandler;
|
import org.apache.fineract.infrastructure.bulkimport.importhandler.ImportHandler;
|
||||||
import org.apache.fineract.infrastructure.bulkimport.importhandler.ImportHandlerUtils;
|
import org.apache.fineract.infrastructure.bulkimport.importhandler.ImportHandlerUtils;
|
||||||
import org.apache.fineract.infrastructure.bulkimport.importhandler.helper.DateSerializer;
|
import org.apache.fineract.infrastructure.bulkimport.importhandler.helper.DateSerializer;
|
||||||
import org.apache.fineract.infrastructure.core.data.CommandProcessingResult;
|
|
||||||
import org.apache.fineract.infrastructure.core.serialization.GoogleGsonSerializerHelper;
|
import org.apache.fineract.infrastructure.core.serialization.GoogleGsonSerializerHelper;
|
||||||
import org.apache.fineract.organisation.staff.data.StaffData;
|
import org.apache.fineract.organisation.staff.data.StaffData;
|
||||||
import org.apache.poi.ss.usermodel.Cell;
|
import org.apache.poi.ss.usermodel.Cell;
|
||||||
@@ -48,8 +47,6 @@ import org.springframework.stereotype.Service;
|
|||||||
public class StaffImportHandler implements ImportHandler {
|
public class StaffImportHandler implements ImportHandler {
|
||||||
|
|
||||||
private static final Logger LOG = LoggerFactory.getLogger(StaffImportHandler.class);
|
private static final Logger LOG = LoggerFactory.getLogger(StaffImportHandler.class);
|
||||||
private List<StaffData> staffList;
|
|
||||||
private Workbook workbook;
|
|
||||||
|
|
||||||
private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService;
|
private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService;
|
||||||
|
|
||||||
@@ -59,27 +56,26 @@ public class StaffImportHandler implements ImportHandler {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Count process(Workbook workbook, String locale, String dateFormat) {
|
public Count process(final Workbook workbook, final String locale, final String dateFormat) {
|
||||||
this.workbook = workbook;
|
List<StaffData> staffList = readExcelFile(workbook, locale, dateFormat);
|
||||||
this.staffList = new ArrayList<>();
|
return importEntity(workbook, staffList, dateFormat);
|
||||||
readExcelFile(locale, dateFormat);
|
|
||||||
return importEntity(dateFormat);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public void readExcelFile(String locale, String dateFormat) {
|
private List<StaffData> readExcelFile(final Workbook workbook, final String locale, final String dateFormat) {
|
||||||
|
List<StaffData> staffList = new ArrayList<>();
|
||||||
Sheet staffSheet = workbook.getSheet(TemplatePopulateImportConstants.EMPLOYEE_SHEET_NAME);
|
Sheet staffSheet = workbook.getSheet(TemplatePopulateImportConstants.EMPLOYEE_SHEET_NAME);
|
||||||
Integer noOfEntries = ImportHandlerUtils.getNumberOfRows(staffSheet, TemplatePopulateImportConstants.FIRST_COLUMN_INDEX);
|
Integer noOfEntries = ImportHandlerUtils.getNumberOfRows(staffSheet, TemplatePopulateImportConstants.FIRST_COLUMN_INDEX);
|
||||||
for (int rowIndex = 1; rowIndex <= noOfEntries; rowIndex++) {
|
for (int rowIndex = 1; rowIndex <= noOfEntries; rowIndex++) {
|
||||||
Row row;
|
Row row;
|
||||||
row = staffSheet.getRow(rowIndex);
|
row = staffSheet.getRow(rowIndex);
|
||||||
if (ImportHandlerUtils.isNotImported(row, StaffConstants.STATUS_COL)) {
|
if (ImportHandlerUtils.isNotImported(row, StaffConstants.STATUS_COL)) {
|
||||||
staffList.add(readStaff(row, locale, dateFormat));
|
staffList.add(readStaff(workbook, row, locale, dateFormat));
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
return staffList;
|
||||||
}
|
}
|
||||||
|
|
||||||
private StaffData readStaff(Row row, String locale, String dateFormat) {
|
private StaffData readStaff(final Workbook workbook, final Row row, final String locale, final String dateFormat) {
|
||||||
String officeName = ImportHandlerUtils.readAsString(StaffConstants.OFFICE_NAME_COL, row);
|
String officeName = ImportHandlerUtils.readAsString(StaffConstants.OFFICE_NAME_COL, row);
|
||||||
Long officeId = ImportHandlerUtils.getIdByName(workbook.getSheet(TemplatePopulateImportConstants.OFFICE_SHEET_NAME), officeName);
|
Long officeId = ImportHandlerUtils.getIdByName(workbook.getSheet(TemplatePopulateImportConstants.OFFICE_SHEET_NAME), officeName);
|
||||||
String firstName = ImportHandlerUtils.readAsString(StaffConstants.FIRST_NAME_COL, row);
|
String firstName = ImportHandlerUtils.readAsString(StaffConstants.FIRST_NAME_COL, row);
|
||||||
@@ -97,11 +93,11 @@ public class StaffImportHandler implements ImportHandler {
|
|||||||
row.getRowNum(), locale, dateFormat);
|
row.getRowNum(), locale, dateFormat);
|
||||||
}
|
}
|
||||||
|
|
||||||
public Count importEntity(String dateFormat) {
|
private Count importEntity(final Workbook workbook, final List<StaffData> staffList, final String dateFormat) {
|
||||||
Sheet staffSheet = workbook.getSheet(TemplatePopulateImportConstants.EMPLOYEE_SHEET_NAME);
|
Sheet staffSheet = workbook.getSheet(TemplatePopulateImportConstants.EMPLOYEE_SHEET_NAME);
|
||||||
int successCount = 0;
|
int successCount = 0;
|
||||||
int errorCount = 0;
|
int errorCount = 0;
|
||||||
String errorMessage = "";
|
String errorMessage;
|
||||||
GsonBuilder gsonBuilder = GoogleGsonSerializerHelper.createGsonBuilder();
|
GsonBuilder gsonBuilder = GoogleGsonSerializerHelper.createGsonBuilder();
|
||||||
gsonBuilder.registerTypeAdapter(LocalDate.class, new DateSerializer(dateFormat));
|
gsonBuilder.registerTypeAdapter(LocalDate.class, new DateSerializer(dateFormat));
|
||||||
for (StaffData staff : staffList) {
|
for (StaffData staff : staffList) {
|
||||||
@@ -111,7 +107,7 @@ public class StaffImportHandler implements ImportHandler {
|
|||||||
.createStaff()//
|
.createStaff()//
|
||||||
.withJson(payload) //
|
.withJson(payload) //
|
||||||
.build(); //
|
.build(); //
|
||||||
final CommandProcessingResult result = commandsSourceWritePlatformService.logCommandSource(commandRequest);
|
commandsSourceWritePlatformService.logCommandSource(commandRequest);
|
||||||
successCount++;
|
successCount++;
|
||||||
Cell statusCell = staffSheet.getRow(staff.getRowIndex()).createCell(StaffConstants.STATUS_COL);
|
Cell statusCell = staffSheet.getRow(staff.getRowIndex()).createCell(StaffConstants.STATUS_COL);
|
||||||
statusCell.setCellValue(TemplatePopulateImportConstants.STATUS_CELL_IMPORTED);
|
statusCell.setCellValue(TemplatePopulateImportConstants.STATUS_CELL_IMPORTED);
|
||||||
|
|||||||
+12
-16
@@ -30,7 +30,6 @@ import org.apache.fineract.infrastructure.bulkimport.constants.UserConstants;
|
|||||||
import org.apache.fineract.infrastructure.bulkimport.data.Count;
|
import org.apache.fineract.infrastructure.bulkimport.data.Count;
|
||||||
import org.apache.fineract.infrastructure.bulkimport.importhandler.ImportHandler;
|
import org.apache.fineract.infrastructure.bulkimport.importhandler.ImportHandler;
|
||||||
import org.apache.fineract.infrastructure.bulkimport.importhandler.ImportHandlerUtils;
|
import org.apache.fineract.infrastructure.bulkimport.importhandler.ImportHandlerUtils;
|
||||||
import org.apache.fineract.infrastructure.core.data.CommandProcessingResult;
|
|
||||||
import org.apache.fineract.infrastructure.core.serialization.GoogleGsonSerializerHelper;
|
import org.apache.fineract.infrastructure.core.serialization.GoogleGsonSerializerHelper;
|
||||||
import org.apache.fineract.useradministration.data.AppUserData;
|
import org.apache.fineract.useradministration.data.AppUserData;
|
||||||
import org.apache.poi.ss.usermodel.Cell;
|
import org.apache.poi.ss.usermodel.Cell;
|
||||||
@@ -47,9 +46,6 @@ import org.springframework.stereotype.Service;
|
|||||||
public class UserImportHandler implements ImportHandler {
|
public class UserImportHandler implements ImportHandler {
|
||||||
|
|
||||||
private static final Logger LOG = LoggerFactory.getLogger(UserImportHandler.class);
|
private static final Logger LOG = LoggerFactory.getLogger(UserImportHandler.class);
|
||||||
private Workbook workbook;
|
|
||||||
private List<AppUserData> users;
|
|
||||||
private List<String> statuses;
|
|
||||||
|
|
||||||
private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService;
|
private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService;
|
||||||
|
|
||||||
@@ -59,27 +55,27 @@ public class UserImportHandler implements ImportHandler {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Count process(Workbook workbook, String locale, String dateFormat) {
|
public Count process(final Workbook workbook, final String locale, final String dateFormat) {
|
||||||
this.workbook = workbook;
|
List<String> statuses = new ArrayList<>();
|
||||||
users = new ArrayList<>();
|
List<AppUserData> users = readExcelFile(workbook, statuses);
|
||||||
statuses = new ArrayList<>();
|
return importEntity(workbook, users);
|
||||||
readExcelFile();
|
|
||||||
return importEntity(dateFormat);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public void readExcelFile() {
|
private List<AppUserData> readExcelFile(final Workbook workbook, final List<String> statuses) {
|
||||||
|
List<AppUserData> users = new ArrayList<>();
|
||||||
Sheet usersSheet = workbook.getSheet(TemplatePopulateImportConstants.USER_SHEET_NAME);
|
Sheet usersSheet = workbook.getSheet(TemplatePopulateImportConstants.USER_SHEET_NAME);
|
||||||
Integer noOfEntries = ImportHandlerUtils.getNumberOfRows(usersSheet, TemplatePopulateImportConstants.FIRST_COLUMN_INDEX);
|
Integer noOfEntries = ImportHandlerUtils.getNumberOfRows(usersSheet, TemplatePopulateImportConstants.FIRST_COLUMN_INDEX);
|
||||||
for (int rowIndex = 1; rowIndex <= noOfEntries; rowIndex++) {
|
for (int rowIndex = 1; rowIndex <= noOfEntries; rowIndex++) {
|
||||||
Row row;
|
Row row;
|
||||||
row = usersSheet.getRow(rowIndex);
|
row = usersSheet.getRow(rowIndex);
|
||||||
if (ImportHandlerUtils.isNotImported(row, UserConstants.STATUS_COL)) {
|
if (ImportHandlerUtils.isNotImported(row, UserConstants.STATUS_COL)) {
|
||||||
users.add(readUsers(row));
|
users.add(readUsers(workbook, row, statuses));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
return users;
|
||||||
}
|
}
|
||||||
|
|
||||||
private AppUserData readUsers(Row row) {
|
private AppUserData readUsers(final Workbook workbook, final Row row, final List<String> statuses) {
|
||||||
String officeName = ImportHandlerUtils.readAsString(UserConstants.OFFICE_NAME_COL, row);
|
String officeName = ImportHandlerUtils.readAsString(UserConstants.OFFICE_NAME_COL, row);
|
||||||
Long officeId = ImportHandlerUtils.getIdByName(workbook.getSheet(TemplatePopulateImportConstants.OFFICE_SHEET_NAME), officeName);
|
Long officeId = ImportHandlerUtils.getIdByName(workbook.getSheet(TemplatePopulateImportConstants.OFFICE_SHEET_NAME), officeName);
|
||||||
String staffName = ImportHandlerUtils.readAsString(UserConstants.STAFF_NAME_COL, row);
|
String staffName = ImportHandlerUtils.readAsString(UserConstants.STAFF_NAME_COL, row);
|
||||||
@@ -109,11 +105,11 @@ public class UserImportHandler implements ImportHandler {
|
|||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public Count importEntity(String dateFormat) {
|
private Count importEntity(final Workbook workbook, final List<AppUserData> users) {
|
||||||
Sheet userSheet = workbook.getSheet(TemplatePopulateImportConstants.USER_SHEET_NAME);
|
Sheet userSheet = workbook.getSheet(TemplatePopulateImportConstants.USER_SHEET_NAME);
|
||||||
int successCount = 0;
|
int successCount = 0;
|
||||||
int errorCount = 0;
|
int errorCount = 0;
|
||||||
String errorMessage = "";
|
String errorMessage;
|
||||||
GsonBuilder gsonBuilder = GoogleGsonSerializerHelper.createGsonBuilder();
|
GsonBuilder gsonBuilder = GoogleGsonSerializerHelper.createGsonBuilder();
|
||||||
for (AppUserData user : users) {
|
for (AppUserData user : users) {
|
||||||
try {
|
try {
|
||||||
@@ -123,7 +119,7 @@ public class UserImportHandler implements ImportHandler {
|
|||||||
.createUser() //
|
.createUser() //
|
||||||
.withJson(payload) //
|
.withJson(payload) //
|
||||||
.build(); //
|
.build(); //
|
||||||
final CommandProcessingResult result = commandsSourceWritePlatformService.logCommandSource(commandRequest);
|
commandsSourceWritePlatformService.logCommandSource(commandRequest);
|
||||||
successCount++;
|
successCount++;
|
||||||
Cell statusCell = userSheet.getRow(user.getRowIndex()).createCell(UserConstants.STATUS_COL);
|
Cell statusCell = userSheet.getRow(user.getRowIndex()).createCell(UserConstants.STATUS_COL);
|
||||||
statusCell.setCellValue(TemplatePopulateImportConstants.STATUS_CELL_IMPORTED);
|
statusCell.setCellValue(TemplatePopulateImportConstants.STATUS_CELL_IMPORTED);
|
||||||
|
|||||||
Vendored
+4
-4
@@ -27,9 +27,9 @@ import io.swagger.v3.oas.annotations.parameters.RequestBody;
|
|||||||
import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
||||||
import io.swagger.v3.oas.annotations.responses.ApiResponses;
|
import io.swagger.v3.oas.annotations.responses.ApiResponses;
|
||||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||||
import java.util.Arrays;
|
|
||||||
import java.util.Collection;
|
import java.util.Collection;
|
||||||
import java.util.HashSet;
|
import java.util.HashSet;
|
||||||
|
import java.util.List;
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
import javax.ws.rs.Consumes;
|
import javax.ws.rs.Consumes;
|
||||||
import javax.ws.rs.GET;
|
import javax.ws.rs.GET;
|
||||||
@@ -64,8 +64,8 @@ import org.springframework.stereotype.Component;
|
|||||||
+ "By default caching is set to No Caching. Switching between caches results in the cache been clear e.g. from Single node to No cache and back again would clear down the single node cache.")
|
+ "By default caching is set to No Caching. Switching between caches results in the cache been clear e.g. from Single node to No cache and back again would clear down the single node cache.")
|
||||||
public class CacheApiResource {
|
public class CacheApiResource {
|
||||||
|
|
||||||
private static final Set<String> RESPONSE_DATA_PARAMETERS = new HashSet<>(Arrays.asList("id"));
|
private static final Set<String> RESPONSE_DATA_PARAMETERS = new HashSet<>(List.of("id"));
|
||||||
private final String resourceNameForPermissions = "CACHE";
|
private static final String RESOURCE_NAME_FOR_PERMISSIONS = "CACHE";
|
||||||
|
|
||||||
private final PlatformSecurityContext context;
|
private final PlatformSecurityContext context;
|
||||||
private final DefaultToApiJsonSerializer<CacheData> toApiJsonSerializer;
|
private final DefaultToApiJsonSerializer<CacheData> toApiJsonSerializer;
|
||||||
@@ -92,7 +92,7 @@ public class CacheApiResource {
|
|||||||
@ApiResponse(responseCode = "200", description = "OK", content = @Content(array = @ArraySchema(schema = @Schema(implementation = CacheApiResourceSwagger.GetCachesResponse.class)))) })
|
@ApiResponse(responseCode = "200", description = "OK", content = @Content(array = @ArraySchema(schema = @Schema(implementation = CacheApiResourceSwagger.GetCachesResponse.class)))) })
|
||||||
public String retrieveAll(@Context final UriInfo uriInfo) {
|
public String retrieveAll(@Context final UriInfo uriInfo) {
|
||||||
|
|
||||||
this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions);
|
this.context.authenticatedUser().validateHasReadPermission(RESOURCE_NAME_FOR_PERMISSIONS);
|
||||||
|
|
||||||
final Collection<CacheData> codes = this.cacheService.retrieveAll();
|
final Collection<CacheData> codes = this.cacheService.retrieveAll();
|
||||||
|
|
||||||
|
|||||||
+2
-4
@@ -49,9 +49,8 @@ import org.springframework.stereotype.Component;
|
|||||||
@Scope("singleton")
|
@Scope("singleton")
|
||||||
public class EmailConfigurationApiResource {
|
public class EmailConfigurationApiResource {
|
||||||
|
|
||||||
private final String resourceNameForPermissions = "EMAIL_CONFIGURATION";
|
private static final String RESOURCE_NAME_FOR_PERMISSIONS = "EMAIL_CONFIGURATION";
|
||||||
private final PlatformSecurityContext context;
|
private final PlatformSecurityContext context;
|
||||||
private final EmailReadPlatformService readPlatformService;
|
|
||||||
private final DefaultToApiJsonSerializer<EmailConfigurationData> toApiJsonSerializer;
|
private final DefaultToApiJsonSerializer<EmailConfigurationData> toApiJsonSerializer;
|
||||||
private final ApiRequestParameterHelper apiRequestParameterHelper;
|
private final ApiRequestParameterHelper apiRequestParameterHelper;
|
||||||
private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService;
|
private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService;
|
||||||
@@ -64,7 +63,6 @@ public class EmailConfigurationApiResource {
|
|||||||
final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService,
|
final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService,
|
||||||
final EmailConfigurationReadPlatformService emailConfigurationReadPlatformService) {
|
final EmailConfigurationReadPlatformService emailConfigurationReadPlatformService) {
|
||||||
this.context = context;
|
this.context = context;
|
||||||
this.readPlatformService = readPlatformService;
|
|
||||||
this.toApiJsonSerializer = toApiJsonSerializer;
|
this.toApiJsonSerializer = toApiJsonSerializer;
|
||||||
this.apiRequestParameterHelper = apiRequestParameterHelper;
|
this.apiRequestParameterHelper = apiRequestParameterHelper;
|
||||||
this.commandsSourceWritePlatformService = commandsSourceWritePlatformService;
|
this.commandsSourceWritePlatformService = commandsSourceWritePlatformService;
|
||||||
@@ -73,7 +71,7 @@ public class EmailConfigurationApiResource {
|
|||||||
|
|
||||||
@GET
|
@GET
|
||||||
public String retrieveAll(@Context final UriInfo uriInfo) {
|
public String retrieveAll(@Context final UriInfo uriInfo) {
|
||||||
this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions);
|
this.context.authenticatedUser().validateHasReadPermission(RESOURCE_NAME_FOR_PERMISSIONS);
|
||||||
|
|
||||||
final Collection<EmailConfigurationData> configuration = this.emailConfigurationReadPlatformService.retrieveAll();
|
final Collection<EmailConfigurationData> configuration = this.emailConfigurationReadPlatformService.retrieveAll();
|
||||||
|
|
||||||
|
|||||||
+3
-3
@@ -73,7 +73,7 @@ public class CodeValuesApiResource {
|
|||||||
Arrays.asList(CodevalueJSONinputParams.CODEVALUE_ID.getValue(), CodevalueJSONinputParams.NAME.getValue(),
|
Arrays.asList(CodevalueJSONinputParams.CODEVALUE_ID.getValue(), CodevalueJSONinputParams.NAME.getValue(),
|
||||||
CodevalueJSONinputParams.POSITION.getValue(), CodevalueJSONinputParams.IS_MANDATORY.getValue(),
|
CodevalueJSONinputParams.POSITION.getValue(), CodevalueJSONinputParams.IS_MANDATORY.getValue(),
|
||||||
CodevalueJSONinputParams.DESCRIPTION.getValue()));
|
CodevalueJSONinputParams.DESCRIPTION.getValue()));
|
||||||
private final String resourceNameForPermissions = "CODEVALUE";
|
private static final String RESOURCE_NAME_FOR_PERMISSIONS = "CODEVALUE";
|
||||||
|
|
||||||
private final PlatformSecurityContext context;
|
private final PlatformSecurityContext context;
|
||||||
private final CodeValueReadPlatformService readPlatformService;
|
private final CodeValueReadPlatformService readPlatformService;
|
||||||
@@ -102,7 +102,7 @@ public class CodeValuesApiResource {
|
|||||||
public String retrieveAllCodeValues(@Context final UriInfo uriInfo,
|
public String retrieveAllCodeValues(@Context final UriInfo uriInfo,
|
||||||
@PathParam("codeId") @Parameter(description = "codeId") final Long codeId) {
|
@PathParam("codeId") @Parameter(description = "codeId") final Long codeId) {
|
||||||
|
|
||||||
this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions);
|
this.context.authenticatedUser().validateHasReadPermission(RESOURCE_NAME_FOR_PERMISSIONS);
|
||||||
|
|
||||||
final Collection<CodeValueData> codeValues = this.readPlatformService.retrieveAllCodeValues(codeId);
|
final Collection<CodeValueData> codeValues = this.readPlatformService.retrieveAllCodeValues(codeId);
|
||||||
|
|
||||||
@@ -122,7 +122,7 @@ public class CodeValuesApiResource {
|
|||||||
@PathParam("codeValueId") @Parameter(description = "codeValueId") final Long codeValueId,
|
@PathParam("codeValueId") @Parameter(description = "codeValueId") final Long codeValueId,
|
||||||
@PathParam("codeId") @Parameter(description = "codeId") final Long codeId) {
|
@PathParam("codeId") @Parameter(description = "codeId") final Long codeId) {
|
||||||
|
|
||||||
this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions);
|
this.context.authenticatedUser().validateHasReadPermission(RESOURCE_NAME_FOR_PERMISSIONS);
|
||||||
|
|
||||||
final CodeValueData codeValue = this.readPlatformService.retrieveCodeValue(codeValueId);
|
final CodeValueData codeValue = this.readPlatformService.retrieveCodeValue(codeValueId);
|
||||||
|
|
||||||
|
|||||||
+2
-2
@@ -68,7 +68,7 @@ public class CodesApiResource {
|
|||||||
* The set of parameters that are supported in response for {@link CodeData}
|
* The set of parameters that are supported in response for {@link CodeData}
|
||||||
*/
|
*/
|
||||||
private static final Set<String> RESPONSE_DATA_PARAMETERS = new HashSet<>(Arrays.asList("id", "name", "systemDefined"));
|
private static final Set<String> RESPONSE_DATA_PARAMETERS = new HashSet<>(Arrays.asList("id", "name", "systemDefined"));
|
||||||
private final String resourceNameForPermissions = "CODE";
|
private static final String RESOURCE_NAME_FOR_PERMISSIONS = "CODE";
|
||||||
|
|
||||||
private final PlatformSecurityContext context;
|
private final PlatformSecurityContext context;
|
||||||
private final CodeReadPlatformService readPlatformService;
|
private final CodeReadPlatformService readPlatformService;
|
||||||
@@ -95,7 +95,7 @@ public class CodesApiResource {
|
|||||||
@ApiResponse(responseCode = "200", description = "OK", content = @Content(array = @ArraySchema(schema = @Schema(implementation = CodesApiResourceSwagger.GetCodesResponse.class)))) })
|
@ApiResponse(responseCode = "200", description = "OK", content = @Content(array = @ArraySchema(schema = @Schema(implementation = CodesApiResourceSwagger.GetCodesResponse.class)))) })
|
||||||
public String retrieveCodes(@Context final UriInfo uriInfo) {
|
public String retrieveCodes(@Context final UriInfo uriInfo) {
|
||||||
|
|
||||||
this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions);
|
this.context.authenticatedUser().validateHasReadPermission(RESOURCE_NAME_FOR_PERMISSIONS);
|
||||||
|
|
||||||
final Collection<CodeData> codes = this.readPlatformService.retrieveAllCodes();
|
final Collection<CodeData> codes = this.readPlatformService.retrieveAllCodes();
|
||||||
|
|
||||||
|
|||||||
+3
-4
@@ -22,7 +22,6 @@ import com.google.gson.JsonElement;
|
|||||||
import com.google.gson.reflect.TypeToken;
|
import com.google.gson.reflect.TypeToken;
|
||||||
import java.lang.reflect.Type;
|
import java.lang.reflect.Type;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.Arrays;
|
|
||||||
import java.util.HashSet;
|
import java.util.HashSet;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
@@ -45,7 +44,7 @@ public final class CodeCommandFromApiJsonDeserializer {
|
|||||||
/**
|
/**
|
||||||
* The parameters supported for this command.
|
* The parameters supported for this command.
|
||||||
*/
|
*/
|
||||||
private final Set<String> supportedParameters = new HashSet<>(Arrays.asList("name"));
|
private static final Set<String> SUPPORTED_PARAMETERS = new HashSet<>(List.of("name"));
|
||||||
private final FromJsonHelper fromApiJsonHelper;
|
private final FromJsonHelper fromApiJsonHelper;
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
@@ -59,7 +58,7 @@ public final class CodeCommandFromApiJsonDeserializer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType();
|
final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType();
|
||||||
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParameters);
|
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, SUPPORTED_PARAMETERS);
|
||||||
|
|
||||||
final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
|
final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
|
||||||
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("code");
|
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("code");
|
||||||
@@ -78,7 +77,7 @@ public final class CodeCommandFromApiJsonDeserializer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType();
|
final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType();
|
||||||
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParameters);
|
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, SUPPORTED_PARAMETERS);
|
||||||
|
|
||||||
final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
|
final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
|
||||||
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("code");
|
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("code");
|
||||||
|
|||||||
+3
-3
@@ -44,7 +44,7 @@ public final class CodeValueCommandFromApiJsonDeserializer {
|
|||||||
/**
|
/**
|
||||||
* The parameters supported for this command.
|
* The parameters supported for this command.
|
||||||
*/
|
*/
|
||||||
private final Set<String> supportedParameters = CodevalueJSONinputParams.getAllValues();
|
private static final Set<String> SUPPORTED_PARAMETERS = CodevalueJSONinputParams.getAllValues();
|
||||||
private final FromJsonHelper fromApiJsonHelper;
|
private final FromJsonHelper fromApiJsonHelper;
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
@@ -58,7 +58,7 @@ public final class CodeValueCommandFromApiJsonDeserializer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType();
|
final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType();
|
||||||
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParameters);
|
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, SUPPORTED_PARAMETERS);
|
||||||
|
|
||||||
final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
|
final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
|
||||||
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("code.value");
|
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("code.value");
|
||||||
@@ -93,7 +93,7 @@ public final class CodeValueCommandFromApiJsonDeserializer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType();
|
final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType();
|
||||||
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParameters);
|
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, SUPPORTED_PARAMETERS);
|
||||||
|
|
||||||
final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
|
final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
|
||||||
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("code.value");
|
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("code.value");
|
||||||
|
|||||||
+4
-4
@@ -71,7 +71,7 @@ public class GlobalConfigurationApiResource {
|
|||||||
|
|
||||||
private static final Set<String> RESPONSE_DATA_PARAMETERS = new HashSet<>(Arrays.asList("globalConfiguration"));
|
private static final Set<String> RESPONSE_DATA_PARAMETERS = new HashSet<>(Arrays.asList("globalConfiguration"));
|
||||||
|
|
||||||
private final String resourceNameForPermissions = "CONFIGURATION";
|
private static final String RESOURCE_NAME_FOR_PERMISSIONS = "CONFIGURATION";
|
||||||
|
|
||||||
private final PlatformSecurityContext context;
|
private final PlatformSecurityContext context;
|
||||||
private final ConfigurationReadPlatformService readPlatformService;
|
private final ConfigurationReadPlatformService readPlatformService;
|
||||||
@@ -106,7 +106,7 @@ public class GlobalConfigurationApiResource {
|
|||||||
public String retrieveConfiguration(@Context final UriInfo uriInfo,
|
public String retrieveConfiguration(@Context final UriInfo uriInfo,
|
||||||
@DefaultValue("false") @QueryParam("survey") @Parameter(description = "survey") final boolean survey) {
|
@DefaultValue("false") @QueryParam("survey") @Parameter(description = "survey") final boolean survey) {
|
||||||
|
|
||||||
this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions);
|
this.context.authenticatedUser().validateHasReadPermission(RESOURCE_NAME_FOR_PERMISSIONS);
|
||||||
|
|
||||||
final GlobalConfigurationData configurationData = this.readPlatformService.retrieveGlobalConfiguration(survey);
|
final GlobalConfigurationData configurationData = this.readPlatformService.retrieveGlobalConfiguration(survey);
|
||||||
|
|
||||||
@@ -125,7 +125,7 @@ public class GlobalConfigurationApiResource {
|
|||||||
public String retrieveOne(@PathParam("configId") @Parameter(description = "configId") final Long configId,
|
public String retrieveOne(@PathParam("configId") @Parameter(description = "configId") final Long configId,
|
||||||
@Context final UriInfo uriInfo) {
|
@Context final UriInfo uriInfo) {
|
||||||
|
|
||||||
this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions);
|
this.context.authenticatedUser().validateHasReadPermission(RESOURCE_NAME_FOR_PERMISSIONS);
|
||||||
|
|
||||||
final GlobalConfigurationPropertyData configurationData = this.readPlatformService.retrieveGlobalConfiguration(configId);
|
final GlobalConfigurationPropertyData configurationData = this.readPlatformService.retrieveGlobalConfiguration(configId);
|
||||||
|
|
||||||
@@ -143,7 +143,7 @@ public class GlobalConfigurationApiResource {
|
|||||||
@ApiResponse(responseCode = "200", description = "OK", content = @Content(schema = @Schema(implementation = GlobalConfigurationPropertyData.class))) })
|
@ApiResponse(responseCode = "200", description = "OK", content = @Content(schema = @Schema(implementation = GlobalConfigurationPropertyData.class))) })
|
||||||
public String retrieveOneByName(@PathParam("name") @Parameter(description = "name") final String name, @Context final UriInfo uriInfo) {
|
public String retrieveOneByName(@PathParam("name") @Parameter(description = "name") final String name, @Context final UriInfo uriInfo) {
|
||||||
|
|
||||||
this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions);
|
this.context.authenticatedUser().validateHasReadPermission(RESOURCE_NAME_FOR_PERMISSIONS);
|
||||||
|
|
||||||
final GlobalConfigurationPropertyData configurationData = this.readPlatformService.retrieveGlobalConfiguration(name);
|
final GlobalConfigurationPropertyData configurationData = this.readPlatformService.retrieveGlobalConfiguration(name);
|
||||||
|
|
||||||
|
|||||||
+16
-26
@@ -36,10 +36,10 @@ import org.springframework.stereotype.Component;
|
|||||||
@Component
|
@Component
|
||||||
public class ExternalServicesPropertiesCommandFromApiJsonDeserializer {
|
public class ExternalServicesPropertiesCommandFromApiJsonDeserializer {
|
||||||
|
|
||||||
private final Set<String> s3SupportedParameters = S3JSONinputParams.getAllValues();
|
private static final Set<String> S3_SUPPORTED_PARAMETERS = S3JSONinputParams.getAllValues();
|
||||||
private final Set<String> smtpSupportedParameters = SMTPJSONinputParams.getAllValues();
|
private static final Set<String> SMTP_SUPPORTED_PARAMETERS = SMTPJSONinputParams.getAllValues();
|
||||||
private final Set<String> smsSupportedParameters = SMSJSONinputParams.getAllValues();
|
private static final Set<String> SMS_SUPPORTED_PARAMETERS = SMSJSONinputParams.getAllValues();
|
||||||
private final Set<String> notificationSupportedParameters = NotificationJSONinputParams.getAllValues();
|
private static final Set<String> NOTIFICATION_SUPPORTED_PARAMETERS = NotificationJSONinputParams.getAllValues();
|
||||||
private final FromJsonHelper fromApiJsonHelper;
|
private final FromJsonHelper fromApiJsonHelper;
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
@@ -52,34 +52,24 @@ public class ExternalServicesPropertiesCommandFromApiJsonDeserializer {
|
|||||||
throw new InvalidJsonException();
|
throw new InvalidJsonException();
|
||||||
}
|
}
|
||||||
|
|
||||||
final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType();
|
final Type typeOfMap = new TypeToken<Map<String, Object>>() {
|
||||||
|
|
||||||
|
}.getType();
|
||||||
switch (externalServiceName) {
|
switch (externalServiceName) {
|
||||||
case "S3":
|
case "S3" -> this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, S3_SUPPORTED_PARAMETERS);
|
||||||
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.s3SupportedParameters);
|
case "SMTP" -> this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, SMTP_SUPPORTED_PARAMETERS);
|
||||||
break;
|
case "SMS" -> this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, SMS_SUPPORTED_PARAMETERS);
|
||||||
|
case "NOTIFICATION" -> this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, NOTIFICATION_SUPPORTED_PARAMETERS);
|
||||||
case "SMTP":
|
default -> throw new ExternalServiceConfigurationNotFoundException(externalServiceName);
|
||||||
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.smtpSupportedParameters);
|
|
||||||
break;
|
|
||||||
|
|
||||||
case "SMS":
|
|
||||||
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.smsSupportedParameters);
|
|
||||||
break;
|
|
||||||
|
|
||||||
case "NOTIFICATION":
|
|
||||||
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.notificationSupportedParameters);
|
|
||||||
break;
|
|
||||||
|
|
||||||
default:
|
|
||||||
throw new ExternalServiceConfigurationNotFoundException(externalServiceName);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public Set<String> getNameKeys(final String json) {
|
public Set<String> getNameKeys(final String json) {
|
||||||
final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType();
|
final Type typeOfMap = new TypeToken<Map<String, Object>>() {
|
||||||
|
|
||||||
|
}.getType();
|
||||||
Map<String, String> jsonMap = this.fromApiJsonHelper.extractDataMap(typeOfMap, json);
|
Map<String, String> jsonMap = this.fromApiJsonHelper.extractDataMap(typeOfMap, json);
|
||||||
Set<String> keyNames = jsonMap.keySet();
|
return jsonMap.keySet();
|
||||||
return keyNames;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+3
-3
@@ -20,8 +20,8 @@ package org.apache.fineract.infrastructure.configuration.serialization;
|
|||||||
|
|
||||||
import com.google.gson.reflect.TypeToken;
|
import com.google.gson.reflect.TypeToken;
|
||||||
import java.lang.reflect.Type;
|
import java.lang.reflect.Type;
|
||||||
import java.util.Arrays;
|
|
||||||
import java.util.HashSet;
|
import java.util.HashSet;
|
||||||
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
import org.apache.commons.lang3.StringUtils;
|
import org.apache.commons.lang3.StringUtils;
|
||||||
@@ -43,7 +43,7 @@ public final class GlobalConfigurationCommandFromApiJsonDeserializer
|
|||||||
/**
|
/**
|
||||||
* The parameters supported for this command.
|
* The parameters supported for this command.
|
||||||
*/
|
*/
|
||||||
private final Set<String> supportedParameters = new HashSet<>(Arrays.asList("globalConfiguration"));
|
private static final Set<String> SUPPORTED_PARAMETERS = new HashSet<>(List.of("globalConfiguration"));
|
||||||
private final FromJsonHelper fromApiJsonHelper;
|
private final FromJsonHelper fromApiJsonHelper;
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
@@ -59,7 +59,7 @@ public final class GlobalConfigurationCommandFromApiJsonDeserializer
|
|||||||
}
|
}
|
||||||
|
|
||||||
final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType();
|
final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType();
|
||||||
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParameters);
|
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, SUPPORTED_PARAMETERS);
|
||||||
|
|
||||||
return this.fromApiJsonHelper.fromJson(json, UpdateGlobalConfigurationCommand.class);
|
return this.fromApiJsonHelper.fromJson(json, UpdateGlobalConfigurationCommand.class);
|
||||||
}
|
}
|
||||||
|
|||||||
+3
-3
@@ -29,14 +29,14 @@ import org.springframework.stereotype.Component;
|
|||||||
@Component
|
@Component
|
||||||
public class PaginationParametersDataValidator {
|
public class PaginationParametersDataValidator {
|
||||||
|
|
||||||
private final Set<String> sortOrderValues = new HashSet<>(Arrays.asList("ASC", "DESC"));
|
private static final Set<String> sortOrderValues = new HashSet<>(Arrays.asList("ASC", "DESC"));
|
||||||
|
|
||||||
public void validateParameterValues(PaginationParameters parameters, final Set<String> supportedOrdeByValues,
|
public void validateParameterValues(PaginationParameters parameters, final Set<String> supportedOrdeByValues,
|
||||||
final String resourceName) {
|
final String resourceName) {
|
||||||
final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
|
final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
|
||||||
if (parameters.isOrderByRequested() && !supportedOrdeByValues.contains(parameters.getOrderBy())) {
|
if (parameters.isOrderByRequested() && !supportedOrdeByValues.contains(parameters.getOrderBy())) {
|
||||||
final String defaultUserMessage = "The orderBy value '" + parameters.getOrderBy()
|
final String defaultUserMessage = "The orderBy value '" + parameters.getOrderBy()
|
||||||
+ "' is not supported. The supported orderBy values are " + supportedOrdeByValues.toString();
|
+ "' is not supported. The supported orderBy values are " + supportedOrdeByValues;
|
||||||
final ApiParameterError error = ApiParameterError.parameterError(
|
final ApiParameterError error = ApiParameterError.parameterError(
|
||||||
"validation.msg." + resourceName + ".orderBy.value.is.not.supported", defaultUserMessage, "orderBy",
|
"validation.msg." + resourceName + ".orderBy.value.is.not.supported", defaultUserMessage, "orderBy",
|
||||||
parameters.getOrderBy(), supportedOrdeByValues.toString());
|
parameters.getOrderBy(), supportedOrdeByValues.toString());
|
||||||
@@ -45,7 +45,7 @@ public class PaginationParametersDataValidator {
|
|||||||
|
|
||||||
if (parameters.isSortOrderProvided() && !sortOrderValues.contains(parameters.getSortOrder().toUpperCase())) {
|
if (parameters.isSortOrderProvided() && !sortOrderValues.contains(parameters.getSortOrder().toUpperCase())) {
|
||||||
final String defaultUserMessage = "The sortOrder value '" + parameters.getSortOrder()
|
final String defaultUserMessage = "The sortOrder value '" + parameters.getSortOrder()
|
||||||
+ "' is not supported. The supported sortOrder values are " + sortOrderValues.toString();
|
+ "' is not supported. The supported sortOrder values are " + sortOrderValues;
|
||||||
final ApiParameterError error = ApiParameterError.parameterError(
|
final ApiParameterError error = ApiParameterError.parameterError(
|
||||||
"validation.msg." + resourceName + ".sortOrder.value.is.not.supported", defaultUserMessage, "sortOrder",
|
"validation.msg." + resourceName + ".sortOrder.value.is.not.supported", defaultUserMessage, "sortOrder",
|
||||||
parameters.getSortOrder(), sortOrderValues.toString());
|
parameters.getSortOrder(), sortOrderValues.toString());
|
||||||
|
|||||||
+125
-89
@@ -40,25 +40,57 @@ import org.springframework.stereotype.Component;
|
|||||||
@Component
|
@Component
|
||||||
public class DatatableCommandFromApiJsonDeserializer {
|
public class DatatableCommandFromApiJsonDeserializer {
|
||||||
|
|
||||||
|
public static final String DATATABLE_NAME = "datatableName";
|
||||||
|
public static final String ENTITY_SUB_TYPE = "entitySubType";
|
||||||
|
public static final String APPTABLE_NAME = "apptableName";
|
||||||
|
public static final String MULTI_ROW = "multiRow";
|
||||||
|
public static final String COLUMNS = "columns";
|
||||||
|
public static final String NAME = "name";
|
||||||
|
public static final String TYPE = "type";
|
||||||
|
public static final String LENGTH = "length";
|
||||||
|
public static final String MANDATORY = "mandatory";
|
||||||
|
public static final String CODE = "code";
|
||||||
|
public static final String CHANGE_COLUMNS = "changeColumns";
|
||||||
|
public static final String ADD_COLUMNS = "addColumns";
|
||||||
|
public static final String DROP_COLUMNS = "dropColumns";
|
||||||
|
public static final String AFTER = "after";
|
||||||
|
public static final String NEW_CODE = "newCode";
|
||||||
|
public static final String M_LOAN = "m_loan";
|
||||||
|
public static final String M_SAVINGS_ACCOUNT = "m_savings_account";
|
||||||
|
public static final String M_CLIENT = "m_client";
|
||||||
|
public static final String M_GROUP = "m_group";
|
||||||
|
public static final String M_CENTER = "m_center";
|
||||||
|
public static final String M_OFFICE = "m_office";
|
||||||
|
public static final String M_SAVINGS_PRODUCT = "m_savings_product";
|
||||||
|
public static final String M_PRODUCT_LOAN = "m_product_loan";
|
||||||
|
public static final String NEW_NAME = "newName";
|
||||||
|
public static final String STRING = "string";
|
||||||
|
public static final String NUMBER = "number";
|
||||||
|
public static final String BOOLEAN = "boolean";
|
||||||
|
public static final String DECIMAL = "decimal";
|
||||||
|
public static final String DATE = "date";
|
||||||
|
public static final String DATETIME = "datetime";
|
||||||
|
public static final String TEXT = "text";
|
||||||
|
public static final String DROPDOWN = "dropdown";
|
||||||
private static final String DATATABLE_NAME_REGEX_PATTERN = "^[a-zA-Z][a-zA-Z0-9\\-_\\s]{0,48}[a-zA-Z0-9]$";
|
private static final String DATATABLE_NAME_REGEX_PATTERN = "^[a-zA-Z][a-zA-Z0-9\\-_\\s]{0,48}[a-zA-Z0-9]$";
|
||||||
private static final String DATATABLE_COLUMN_NAME_REGEX_PATTERN = "^[a-zA-Z][a-zA-Z0-9\\-_\\s]{0,}[a-zA-Z0-9]$";
|
private static final String DATATABLE_COLUMN_NAME_REGEX_PATTERN = "^[a-zA-Z][a-zA-Z0-9\\-_\\s]{0,}[a-zA-Z0-9]$";
|
||||||
/**
|
/**
|
||||||
* The parameters supported for this command.
|
* The parameters supported for this command.
|
||||||
*/
|
*/
|
||||||
private final Set<String> supportedParametersForCreate = new HashSet<>(
|
private static final Set<String> SUPPORTED_PARAMETERS_FOR_CREATE = new HashSet<>(
|
||||||
Arrays.asList("datatableName", "entitySubType", "apptableName", "multiRow", "columns"));
|
Arrays.asList(DATATABLE_NAME, ENTITY_SUB_TYPE, APPTABLE_NAME, MULTI_ROW, COLUMNS));
|
||||||
private final Set<String> supportedParametersForCreateColumns = new HashSet<>(
|
private static final Set<String> SUPPORTED_PARAMETERS_FOR_CREATE_COLUMNS = new HashSet<>(
|
||||||
Arrays.asList("name", "type", "length", "mandatory", "code"));
|
Arrays.asList(NAME, TYPE, LENGTH, MANDATORY, CODE));
|
||||||
private final Set<String> supportedParametersForUpdate = new HashSet<>(
|
private static final Set<String> SUPPORTED_PARAMETERS_FOR_UPDATE = new HashSet<>(
|
||||||
Arrays.asList("apptableName", "entitySubType", "changeColumns", "addColumns", "dropColumns"));
|
Arrays.asList(APPTABLE_NAME, ENTITY_SUB_TYPE, CHANGE_COLUMNS, ADD_COLUMNS, DROP_COLUMNS));
|
||||||
private final Set<String> supportedParametersForAddColumns = new HashSet<>(
|
private static final Set<String> SUPPORTED_PARAMETERS_FOR_ADD_COLUMNS = new HashSet<>(
|
||||||
Arrays.asList("name", "type", "length", "mandatory", "after", "code"));
|
Arrays.asList(NAME, TYPE, LENGTH, MANDATORY, AFTER, CODE));
|
||||||
private final Set<String> supportedParametersForChangeColumns = new HashSet<>(
|
private static final Set<String> SUPPORTED_PARAMETERS_FOR_CHANGE_COLUMNS = new HashSet<>(
|
||||||
Arrays.asList("name", "newName", "length", "mandatory", "after", "code", "newCode"));
|
Arrays.asList(NAME, NEW_NAME, LENGTH, MANDATORY, AFTER, CODE, NEW_CODE));
|
||||||
private final Set<String> supportedParametersForDropColumns = new HashSet<>(Arrays.asList("name"));
|
private static final Set<String> SUPPORTED_PARAMETERS_FOR_DROP_COLUMNS = new HashSet<>(List.of(NAME));
|
||||||
private final Object[] supportedColumnTypes = { "string", "number", "boolean", "decimal", "date", "datetime", "text", "dropdown" };
|
private static final Object[] SUPPORTED_COLUMN_TYPES = { STRING, NUMBER, BOOLEAN, DECIMAL, DATE, DATETIME, TEXT, DROPDOWN };
|
||||||
private final Object[] supportedApptableNames = { "m_loan", "m_savings_account", "m_client", "m_group", "m_center", "m_office",
|
private static final Object[] SUPPORTED_APPTABLE_NAMES = { M_LOAN, M_SAVINGS_ACCOUNT, M_CLIENT, M_GROUP, M_CENTER, M_OFFICE,
|
||||||
"m_savings_product", "m_product_loan" };
|
M_SAVINGS_PRODUCT, M_PRODUCT_LOAN };
|
||||||
|
|
||||||
private final FromJsonHelper fromApiJsonHelper;
|
private final FromJsonHelper fromApiJsonHelper;
|
||||||
|
|
||||||
@@ -68,37 +100,37 @@ public class DatatableCommandFromApiJsonDeserializer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private void validateType(final DataValidatorBuilder baseDataValidator, final JsonElement column) {
|
private void validateType(final DataValidatorBuilder baseDataValidator, final JsonElement column) {
|
||||||
final String type = this.fromApiJsonHelper.extractStringNamed("type", column);
|
final String type = this.fromApiJsonHelper.extractStringNamed(TYPE, column);
|
||||||
baseDataValidator.reset().parameter("type").value(type).notBlank().isOneOfTheseStringValues(this.supportedColumnTypes);
|
baseDataValidator.reset().parameter(TYPE).value(type).notBlank().isOneOfTheseStringValues(SUPPORTED_COLUMN_TYPES);
|
||||||
|
|
||||||
if (type != null && type.equalsIgnoreCase("String")) {
|
if (type != null && type.equalsIgnoreCase("String")) {
|
||||||
if (this.fromApiJsonHelper.parameterExists("length", column)) {
|
if (this.fromApiJsonHelper.parameterExists(LENGTH, column)) {
|
||||||
final String lengthStr = this.fromApiJsonHelper.extractStringNamed("length", column);
|
final String lengthStr = this.fromApiJsonHelper.extractStringNamed(LENGTH, column);
|
||||||
if (lengthStr != null && !StringUtils.isWhitespace(lengthStr) && StringUtils.isNumeric(lengthStr)
|
if (lengthStr != null && !StringUtils.isWhitespace(lengthStr) && StringUtils.isNumeric(lengthStr)
|
||||||
&& StringUtils.isNotBlank(lengthStr)) {
|
&& StringUtils.isNotBlank(lengthStr)) {
|
||||||
final Integer length = Integer.parseInt(lengthStr);
|
final Integer length = Integer.parseInt(lengthStr);
|
||||||
baseDataValidator.reset().parameter("length").value(length).positiveAmount();
|
baseDataValidator.reset().parameter(LENGTH).value(length).positiveAmount();
|
||||||
} else if (StringUtils.isBlank(lengthStr) || StringUtils.isWhitespace(lengthStr)) {
|
} else if (StringUtils.isBlank(lengthStr) || StringUtils.isWhitespace(lengthStr)) {
|
||||||
baseDataValidator.reset().parameter("length").failWithCode("must.be.provided.when.type.is.String");
|
baseDataValidator.reset().parameter(LENGTH).failWithCode("must.be.provided.when.type.is.String");
|
||||||
} else if (!StringUtils.isNumeric(lengthStr)) {
|
} else if (!StringUtils.isNumeric(lengthStr)) {
|
||||||
baseDataValidator.reset().parameter("length").failWithCode("not.greater.than.zero");
|
baseDataValidator.reset().parameter(LENGTH).failWithCode("not.greater.than.zero");
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
baseDataValidator.reset().parameter("length").failWithCode("must.be.provided.when.type.is.String");
|
baseDataValidator.reset().parameter(LENGTH).failWithCode("must.be.provided.when.type.is.String");
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
baseDataValidator.reset().parameter("length").mustBeBlankWhenParameterProvidedIs("type", type);
|
baseDataValidator.reset().parameter(LENGTH).mustBeBlankWhenParameterProvidedIs(TYPE, type);
|
||||||
}
|
}
|
||||||
|
|
||||||
final String code = this.fromApiJsonHelper.extractStringNamed("code", column);
|
final String code = this.fromApiJsonHelper.extractStringNamed(CODE, column);
|
||||||
if (type != null && type.equalsIgnoreCase("Dropdown")) {
|
if (type != null && type.equalsIgnoreCase(DROPDOWN)) {
|
||||||
if (code != null) {
|
if (code != null) {
|
||||||
baseDataValidator.reset().parameter("code").value(code).notBlank().matchesRegularExpression(DATATABLE_NAME_REGEX_PATTERN);
|
baseDataValidator.reset().parameter(CODE).value(code).notBlank().matchesRegularExpression(DATATABLE_NAME_REGEX_PATTERN);
|
||||||
} else {
|
} else {
|
||||||
baseDataValidator.reset().parameter("code").value(code).cantBeBlankWhenParameterProvidedIs("type", type);
|
baseDataValidator.reset().parameter(CODE).value(code).cantBeBlankWhenParameterProvidedIs(TYPE, type);
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
baseDataValidator.reset().parameter("code").value(code).mustBeBlankWhenParameterProvided("type", type);
|
baseDataValidator.reset().parameter(CODE).value(code).mustBeBlankWhenParameterProvided(TYPE, type);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -107,46 +139,48 @@ public class DatatableCommandFromApiJsonDeserializer {
|
|||||||
throw new InvalidJsonException();
|
throw new InvalidJsonException();
|
||||||
}
|
}
|
||||||
|
|
||||||
final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType();
|
final Type typeOfMap = new TypeToken<Map<String, Object>>() {
|
||||||
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParametersForCreate);
|
|
||||||
|
}.getType();
|
||||||
|
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, SUPPORTED_PARAMETERS_FOR_CREATE);
|
||||||
|
|
||||||
final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
|
final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
|
||||||
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("datatable");
|
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("datatable");
|
||||||
|
|
||||||
final JsonElement element = this.fromApiJsonHelper.parse(json);
|
final JsonElement element = this.fromApiJsonHelper.parse(json);
|
||||||
|
|
||||||
final String datatableName = this.fromApiJsonHelper.extractStringNamed("datatableName", element);
|
final String datatableName = this.fromApiJsonHelper.extractStringNamed(DATATABLE_NAME, element);
|
||||||
baseDataValidator.reset().parameter("datatableName").value(datatableName).notBlank().notExceedingLengthOf(50)
|
baseDataValidator.reset().parameter(DATATABLE_NAME).value(datatableName).notBlank().notExceedingLengthOf(50)
|
||||||
.matchesRegularExpression(DATATABLE_NAME_REGEX_PATTERN);
|
.matchesRegularExpression(DATATABLE_NAME_REGEX_PATTERN);
|
||||||
|
|
||||||
final String apptableName = this.fromApiJsonHelper.extractStringNamed("apptableName", element);
|
final String apptableName = this.fromApiJsonHelper.extractStringNamed(APPTABLE_NAME, element);
|
||||||
baseDataValidator.reset().parameter("apptableName").value(apptableName).notBlank().notExceedingLengthOf(50)
|
baseDataValidator.reset().parameter(APPTABLE_NAME).value(apptableName).notBlank().notExceedingLengthOf(50)
|
||||||
.isOneOfTheseValues(this.supportedApptableNames);
|
.isOneOfTheseValues(SUPPORTED_APPTABLE_NAMES);
|
||||||
|
|
||||||
if ("m_client".equals(apptableName)) {
|
if (M_CLIENT.equals(apptableName)) {
|
||||||
String entitySubType = this.fromApiJsonHelper.extractStringNamed("entitySubType", element);
|
String entitySubType = this.fromApiJsonHelper.extractStringNamed(ENTITY_SUB_TYPE, element);
|
||||||
baseDataValidator.reset().parameter("entitySubType").value(entitySubType).notBlank(); // Person or Entity
|
baseDataValidator.reset().parameter(ENTITY_SUB_TYPE).value(entitySubType).notBlank(); // Person or Entity
|
||||||
}
|
}
|
||||||
final String fkColumnName = (apptableName != null) ? apptableName.substring(2) + "_id" : "";
|
final String fkColumnName = (apptableName != null) ? apptableName.substring(2) + "_id" : "";
|
||||||
|
|
||||||
final Boolean multiRow = this.fromApiJsonHelper.extractBooleanNamed("multiRow", element);
|
final Boolean multiRow = this.fromApiJsonHelper.extractBooleanNamed(MULTI_ROW, element);
|
||||||
baseDataValidator.reset().parameter("multiRow").value(multiRow).ignoreIfNull().notBlank().isOneOfTheseValues(true, false);
|
baseDataValidator.reset().parameter(MULTI_ROW).value(multiRow).ignoreIfNull().notBlank().isOneOfTheseValues(true, false);
|
||||||
|
|
||||||
final JsonArray columns = this.fromApiJsonHelper.extractJsonArrayNamed("columns", element);
|
final JsonArray columns = this.fromApiJsonHelper.extractJsonArrayNamed(COLUMNS, element);
|
||||||
baseDataValidator.reset().parameter("columns").value(columns).notNull().jsonArrayNotEmpty();
|
baseDataValidator.reset().parameter(COLUMNS).value(columns).notNull().jsonArrayNotEmpty();
|
||||||
|
|
||||||
if (columns != null) {
|
if (columns != null) {
|
||||||
for (final JsonElement column : columns) {
|
for (final JsonElement column : columns) {
|
||||||
this.fromApiJsonHelper.checkForUnsupportedParameters(column.getAsJsonObject(), this.supportedParametersForCreateColumns);
|
this.fromApiJsonHelper.checkForUnsupportedParameters(column.getAsJsonObject(), SUPPORTED_PARAMETERS_FOR_CREATE_COLUMNS);
|
||||||
|
|
||||||
final String name = this.fromApiJsonHelper.extractStringNamed("name", column);
|
final String name = this.fromApiJsonHelper.extractStringNamed(NAME, column);
|
||||||
baseDataValidator.reset().parameter("name").value(name).notBlank().isNotOneOfTheseValues("id", fkColumnName)
|
baseDataValidator.reset().parameter(NAME).value(name).notBlank().isNotOneOfTheseValues("id", fkColumnName)
|
||||||
.matchesRegularExpression(DATATABLE_COLUMN_NAME_REGEX_PATTERN);
|
.matchesRegularExpression(DATATABLE_COLUMN_NAME_REGEX_PATTERN);
|
||||||
|
|
||||||
validateType(baseDataValidator, column);
|
validateType(baseDataValidator, column);
|
||||||
|
|
||||||
final Boolean mandatory = this.fromApiJsonHelper.extractBooleanNamed("mandatory", column);
|
final Boolean mandatory = this.fromApiJsonHelper.extractBooleanNamed(MANDATORY, column);
|
||||||
baseDataValidator.reset().parameter("mandatory").value(mandatory).ignoreIfNull().notBlank().isOneOfTheseValues(true, false);
|
baseDataValidator.reset().parameter(MANDATORY).value(mandatory).ignoreIfNull().notBlank().isOneOfTheseValues(true, false);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -166,99 +200,101 @@ public class DatatableCommandFromApiJsonDeserializer {
|
|||||||
"Provided JSON request body does not have any parameters.");
|
"Provided JSON request body does not have any parameters.");
|
||||||
}
|
}
|
||||||
|
|
||||||
final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType();
|
final Type typeOfMap = new TypeToken<Map<String, Object>>() {
|
||||||
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParametersForUpdate);
|
|
||||||
|
}.getType();
|
||||||
|
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, SUPPORTED_PARAMETERS_FOR_UPDATE);
|
||||||
|
|
||||||
final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
|
final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
|
||||||
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("datatable");
|
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("datatable");
|
||||||
|
|
||||||
final JsonElement element = this.fromApiJsonHelper.parse(json);
|
final JsonElement element = this.fromApiJsonHelper.parse(json);
|
||||||
final String apptableName = this.fromApiJsonHelper.extractStringNamed("apptableName", element);
|
final String apptableName = this.fromApiJsonHelper.extractStringNamed(APPTABLE_NAME, element);
|
||||||
baseDataValidator.reset().parameter("apptableName").value(apptableName).ignoreIfNull().notBlank()
|
baseDataValidator.reset().parameter(APPTABLE_NAME).value(apptableName).ignoreIfNull().notBlank()
|
||||||
.isOneOfTheseValues(this.supportedApptableNames);
|
.isOneOfTheseValues(SUPPORTED_APPTABLE_NAMES);
|
||||||
|
|
||||||
if ("m_client".equals(apptableName)) {
|
if (M_CLIENT.equals(apptableName)) {
|
||||||
String entitySubType = this.fromApiJsonHelper.extractStringNamed("entitySubType", element);
|
String entitySubType = this.fromApiJsonHelper.extractStringNamed(ENTITY_SUB_TYPE, element);
|
||||||
baseDataValidator.reset().parameter("entitySubType").value(entitySubType).notBlank(); // Person or Entity
|
baseDataValidator.reset().parameter(ENTITY_SUB_TYPE).value(entitySubType).notBlank(); // Person or Entity
|
||||||
}
|
}
|
||||||
|
|
||||||
final String fkColumnName = (apptableName != null) ? apptableName.substring(2) + "_id" : "";
|
final String fkColumnName = (apptableName != null) ? apptableName.substring(2) + "_id" : "";
|
||||||
|
|
||||||
final JsonArray changeColumns = this.fromApiJsonHelper.extractJsonArrayNamed("changeColumns", element);
|
final JsonArray changeColumns = this.fromApiJsonHelper.extractJsonArrayNamed(CHANGE_COLUMNS, element);
|
||||||
baseDataValidator.reset().parameter("changeColumns").value(changeColumns).ignoreIfNull().jsonArrayNotEmpty();
|
baseDataValidator.reset().parameter(CHANGE_COLUMNS).value(changeColumns).ignoreIfNull().jsonArrayNotEmpty();
|
||||||
|
|
||||||
if (changeColumns != null) {
|
if (changeColumns != null) {
|
||||||
for (final JsonElement column : changeColumns) {
|
for (final JsonElement column : changeColumns) {
|
||||||
this.fromApiJsonHelper.checkForUnsupportedParameters(column.getAsJsonObject(), this.supportedParametersForChangeColumns);
|
this.fromApiJsonHelper.checkForUnsupportedParameters(column.getAsJsonObject(), SUPPORTED_PARAMETERS_FOR_CHANGE_COLUMNS);
|
||||||
|
|
||||||
final String name = this.fromApiJsonHelper.extractStringNamed("name", column);
|
final String name = this.fromApiJsonHelper.extractStringNamed(NAME, column);
|
||||||
baseDataValidator.reset().parameter("name").value(name).notBlank().isNotOneOfTheseValues("id", fkColumnName)
|
baseDataValidator.reset().parameter(NAME).value(name).notBlank().isNotOneOfTheseValues("id", fkColumnName)
|
||||||
.matchesRegularExpression(DATATABLE_COLUMN_NAME_REGEX_PATTERN);
|
.matchesRegularExpression(DATATABLE_COLUMN_NAME_REGEX_PATTERN);
|
||||||
|
|
||||||
final String newName = this.fromApiJsonHelper.extractStringNamed("newName", column);
|
final String newName = this.fromApiJsonHelper.extractStringNamed(NEW_NAME, column);
|
||||||
baseDataValidator.reset().parameter("newName").value(newName).ignoreIfNull().notBlank().notExceedingLengthOf(50)
|
baseDataValidator.reset().parameter(NEW_NAME).value(newName).ignoreIfNull().notBlank().notExceedingLengthOf(50)
|
||||||
.isNotOneOfTheseValues("id", fkColumnName).matchesRegularExpression(DATATABLE_COLUMN_NAME_REGEX_PATTERN);
|
.isNotOneOfTheseValues("id", fkColumnName).matchesRegularExpression(DATATABLE_COLUMN_NAME_REGEX_PATTERN);
|
||||||
|
|
||||||
if (this.fromApiJsonHelper.parameterExists("length", column)) {
|
if (this.fromApiJsonHelper.parameterExists(LENGTH, column)) {
|
||||||
final String lengthStr = this.fromApiJsonHelper.extractStringNamed("length", column);
|
final String lengthStr = this.fromApiJsonHelper.extractStringNamed(LENGTH, column);
|
||||||
if (StringUtils.isWhitespace(lengthStr) || !StringUtils.isNumeric(lengthStr) || StringUtils.isBlank(lengthStr)) {
|
if (StringUtils.isWhitespace(lengthStr) || !StringUtils.isNumeric(lengthStr) || StringUtils.isBlank(lengthStr)) {
|
||||||
baseDataValidator.reset().parameter("length").failWithCode("not.greater.than.zero");
|
baseDataValidator.reset().parameter(LENGTH).failWithCode("not.greater.than.zero");
|
||||||
} else {
|
} else {
|
||||||
final Integer length = Integer.parseInt(lengthStr);
|
final Integer length = Integer.parseInt(lengthStr);
|
||||||
baseDataValidator.reset().parameter("length").value(length).ignoreIfNull().notBlank().positiveAmount();
|
baseDataValidator.reset().parameter(LENGTH).value(length).ignoreIfNull().notBlank().positiveAmount();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
final String code = this.fromApiJsonHelper.extractStringNamed("code", column);
|
final String code = this.fromApiJsonHelper.extractStringNamed(CODE, column);
|
||||||
baseDataValidator.reset().parameter("code").value(code).ignoreIfNull().notBlank().notExceedingLengthOf(100)
|
baseDataValidator.reset().parameter(CODE).value(code).ignoreIfNull().notBlank().notExceedingLengthOf(100)
|
||||||
.matchesRegularExpression(DATATABLE_COLUMN_NAME_REGEX_PATTERN);
|
.matchesRegularExpression(DATATABLE_COLUMN_NAME_REGEX_PATTERN);
|
||||||
|
|
||||||
final String newCode = this.fromApiJsonHelper.extractStringNamed("newCode", column);
|
final String newCode = this.fromApiJsonHelper.extractStringNamed(NEW_CODE, column);
|
||||||
baseDataValidator.reset().parameter("newCode").value(newCode).ignoreIfNull().notBlank().notExceedingLengthOf(100)
|
baseDataValidator.reset().parameter(NEW_CODE).value(newCode).ignoreIfNull().notBlank().notExceedingLengthOf(100)
|
||||||
.matchesRegularExpression(DATATABLE_COLUMN_NAME_REGEX_PATTERN);
|
.matchesRegularExpression(DATATABLE_COLUMN_NAME_REGEX_PATTERN);
|
||||||
|
|
||||||
if (StringUtils.isBlank(code) && StringUtils.isNotBlank(newCode)) {
|
if (StringUtils.isBlank(code) && StringUtils.isNotBlank(newCode)) {
|
||||||
baseDataValidator.reset().parameter("code").value(code).cantBeBlankWhenParameterProvidedIs("newCode", newCode);
|
baseDataValidator.reset().parameter(CODE).value(code).cantBeBlankWhenParameterProvidedIs(NEW_CODE, newCode);
|
||||||
}
|
}
|
||||||
|
|
||||||
final Boolean mandatory = this.fromApiJsonHelper.extractBooleanNamed("mandatory", column);
|
final Boolean mandatory = this.fromApiJsonHelper.extractBooleanNamed(MANDATORY, column);
|
||||||
baseDataValidator.reset().parameter("mandatory").value(mandatory).ignoreIfNull().notBlank().isOneOfTheseValues(true, false);
|
baseDataValidator.reset().parameter(MANDATORY).value(mandatory).ignoreIfNull().notBlank().isOneOfTheseValues(true, false);
|
||||||
|
|
||||||
final Boolean after = this.fromApiJsonHelper.extractBooleanNamed("after", column);
|
final Boolean after = this.fromApiJsonHelper.extractBooleanNamed(AFTER, column);
|
||||||
baseDataValidator.reset().parameter("after").value(after).ignoreIfNull().notBlank().isOneOfTheseValues(true, false);
|
baseDataValidator.reset().parameter(AFTER).value(after).ignoreIfNull().notBlank().isOneOfTheseValues(true, false);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
final JsonArray addColumns = this.fromApiJsonHelper.extractJsonArrayNamed("addColumns", element);
|
final JsonArray addColumns = this.fromApiJsonHelper.extractJsonArrayNamed(ADD_COLUMNS, element);
|
||||||
baseDataValidator.reset().parameter("addColumns").value(addColumns).ignoreIfNull().jsonArrayNotEmpty();
|
baseDataValidator.reset().parameter(ADD_COLUMNS).value(addColumns).ignoreIfNull().jsonArrayNotEmpty();
|
||||||
|
|
||||||
if (addColumns != null) {
|
if (addColumns != null) {
|
||||||
for (final JsonElement column : addColumns) {
|
for (final JsonElement column : addColumns) {
|
||||||
this.fromApiJsonHelper.checkForUnsupportedParameters(column.getAsJsonObject(), this.supportedParametersForAddColumns);
|
this.fromApiJsonHelper.checkForUnsupportedParameters(column.getAsJsonObject(), SUPPORTED_PARAMETERS_FOR_ADD_COLUMNS);
|
||||||
|
|
||||||
final String name = this.fromApiJsonHelper.extractStringNamed("name", column);
|
final String name = this.fromApiJsonHelper.extractStringNamed(NAME, column);
|
||||||
baseDataValidator.reset().parameter("name").value(name).notBlank().isNotOneOfTheseValues("id", fkColumnName)
|
baseDataValidator.reset().parameter(NAME).value(name).notBlank().isNotOneOfTheseValues("id", fkColumnName)
|
||||||
.matchesRegularExpression(DATATABLE_COLUMN_NAME_REGEX_PATTERN);
|
.matchesRegularExpression(DATATABLE_COLUMN_NAME_REGEX_PATTERN);
|
||||||
|
|
||||||
validateType(baseDataValidator, column);
|
validateType(baseDataValidator, column);
|
||||||
|
|
||||||
final Boolean mandatory = this.fromApiJsonHelper.extractBooleanNamed("mandatory", column);
|
final Boolean mandatory = this.fromApiJsonHelper.extractBooleanNamed(MANDATORY, column);
|
||||||
baseDataValidator.reset().parameter("mandatory").value(mandatory).ignoreIfNull().notBlank().isOneOfTheseValues(true, false);
|
baseDataValidator.reset().parameter(MANDATORY).value(mandatory).ignoreIfNull().notBlank().isOneOfTheseValues(true, false);
|
||||||
|
|
||||||
final Boolean after = this.fromApiJsonHelper.extractBooleanNamed("after", column);
|
final Boolean after = this.fromApiJsonHelper.extractBooleanNamed(AFTER, column);
|
||||||
baseDataValidator.reset().parameter("after").value(after).ignoreIfNull().notBlank().isOneOfTheseValues(true, false);
|
baseDataValidator.reset().parameter(AFTER).value(after).ignoreIfNull().notBlank().isOneOfTheseValues(true, false);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
final JsonArray dropColumns = this.fromApiJsonHelper.extractJsonArrayNamed("dropColumns", element);
|
final JsonArray dropColumns = this.fromApiJsonHelper.extractJsonArrayNamed(DROP_COLUMNS, element);
|
||||||
baseDataValidator.reset().parameter("dropColumns").value(dropColumns).ignoreIfNull().jsonArrayNotEmpty();
|
baseDataValidator.reset().parameter(DROP_COLUMNS).value(dropColumns).ignoreIfNull().jsonArrayNotEmpty();
|
||||||
|
|
||||||
if (dropColumns != null) {
|
if (dropColumns != null) {
|
||||||
for (final JsonElement column : dropColumns) {
|
for (final JsonElement column : dropColumns) {
|
||||||
this.fromApiJsonHelper.checkForUnsupportedParameters(column.getAsJsonObject(), this.supportedParametersForDropColumns);
|
this.fromApiJsonHelper.checkForUnsupportedParameters(column.getAsJsonObject(), SUPPORTED_PARAMETERS_FOR_DROP_COLUMNS);
|
||||||
|
|
||||||
final String name = this.fromApiJsonHelper.extractStringNamed("name", column);
|
final String name = this.fromApiJsonHelper.extractStringNamed(NAME, column);
|
||||||
baseDataValidator.reset().parameter("name").value(name).notBlank().isNotOneOfTheseValues("id", fkColumnName)
|
baseDataValidator.reset().parameter(NAME).value(name).notBlank().isNotOneOfTheseValues("id", fkColumnName)
|
||||||
.matchesRegularExpression(DATATABLE_COLUMN_NAME_REGEX_PATTERN);
|
.matchesRegularExpression(DATATABLE_COLUMN_NAME_REGEX_PATTERN);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+8
-8
@@ -36,7 +36,7 @@ import org.springframework.stereotype.Service;
|
|||||||
@Service
|
@Service
|
||||||
public class TomcatJdbcDataSourcePerTenantService implements RoutingDataSourceService {
|
public class TomcatJdbcDataSourcePerTenantService implements RoutingDataSourceService {
|
||||||
|
|
||||||
private final Map<Long, DataSource> tenantToDataSourceMap = new HashMap<>(1);
|
private static final Map<Long, DataSource> TENANT_TO_DATA_SOURCE_MAP = new HashMap<>(1);
|
||||||
private final DataSource tenantDataSource;
|
private final DataSource tenantDataSource;
|
||||||
|
|
||||||
private final DataSourcePerTenantServiceFactory dataSourcePerTenantServiceFactory;
|
private final DataSourcePerTenantServiceFactory dataSourcePerTenantServiceFactory;
|
||||||
@@ -51,25 +51,25 @@ public class TomcatJdbcDataSourcePerTenantService implements RoutingDataSourceSe
|
|||||||
@Override
|
@Override
|
||||||
public DataSource retrieveDataSource() {
|
public DataSource retrieveDataSource() {
|
||||||
// default to tenant database datasource
|
// default to tenant database datasource
|
||||||
DataSource tenantDataSource = this.tenantDataSource;
|
DataSource actualDataSource = this.tenantDataSource;
|
||||||
|
|
||||||
final FineractPlatformTenant tenant = ThreadLocalContextUtil.getTenant();
|
final FineractPlatformTenant tenant = ThreadLocalContextUtil.getTenant();
|
||||||
if (tenant != null) {
|
if (tenant != null) {
|
||||||
final FineractPlatformTenantConnection tenantConnection = tenant.getConnection();
|
final FineractPlatformTenantConnection tenantConnection = tenant.getConnection();
|
||||||
|
|
||||||
synchronized (this.tenantToDataSourceMap) {
|
synchronized (TENANT_TO_DATA_SOURCE_MAP) {
|
||||||
// if tenantConnection information available switch to the
|
// if tenantConnection information available switch to the
|
||||||
// appropriate datasource for that tenant.
|
// appropriate datasource for that tenant.
|
||||||
DataSource possibleDS = this.tenantToDataSourceMap.get(tenantConnection.getConnectionId());
|
DataSource possibleDS = TENANT_TO_DATA_SOURCE_MAP.get(tenantConnection.getConnectionId());
|
||||||
if (possibleDS != null) {
|
if (possibleDS != null) {
|
||||||
tenantDataSource = possibleDS;
|
actualDataSource = possibleDS;
|
||||||
} else {
|
} else {
|
||||||
tenantDataSource = dataSourcePerTenantServiceFactory.createNewDataSourceFor(tenantConnection);
|
actualDataSource = dataSourcePerTenantServiceFactory.createNewDataSourceFor(tenantConnection);
|
||||||
this.tenantToDataSourceMap.put(tenantConnection.getConnectionId(), tenantDataSource);
|
TENANT_TO_DATA_SOURCE_MAP.put(tenantConnection.getConnectionId(), actualDataSource);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return tenantDataSource;
|
return actualDataSource;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+5
-4
@@ -28,10 +28,11 @@ import org.springframework.stereotype.Component;
|
|||||||
@Component
|
@Component
|
||||||
public class DatabaseTypeResolver implements InitializingBean {
|
public class DatabaseTypeResolver implements InitializingBean {
|
||||||
|
|
||||||
private final Map<String, DatabaseType> driverMapping = Map.of("org.mariadb.jdbc.Driver", DatabaseType.MYSQL, "com.mysql.jdbc.Driver",
|
private static final Map<String, DatabaseType> DRIVER_MAPPING = Map.of("org.mariadb.jdbc.Driver", DatabaseType.MYSQL,
|
||||||
DatabaseType.MYSQL, "com.mysql.cj.jdbc.Driver", DatabaseType.MYSQL, "org.postgresql.Driver", DatabaseType.POSTGRESQL);
|
"com.mysql.jdbc.Driver", DatabaseType.MYSQL, "com.mysql.cj.jdbc.Driver", DatabaseType.MYSQL, "org.postgresql.Driver",
|
||||||
|
DatabaseType.POSTGRESQL);
|
||||||
|
|
||||||
private final AtomicReference<DatabaseType> currentDatabaseType = new AtomicReference<>();
|
private static final AtomicReference<DatabaseType> currentDatabaseType = new AtomicReference<>();
|
||||||
private final HikariConfig hikariConfig;
|
private final HikariConfig hikariConfig;
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
@@ -45,7 +46,7 @@ public class DatabaseTypeResolver implements InitializingBean {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private DatabaseType determineDatabaseType(String driverClassName) {
|
private DatabaseType determineDatabaseType(String driverClassName) {
|
||||||
DatabaseType databaseType = driverMapping.get(driverClassName);
|
DatabaseType databaseType = DRIVER_MAPPING.get(driverClassName);
|
||||||
if (databaseType == null) {
|
if (databaseType == null) {
|
||||||
throw new IllegalArgumentException("The driver's class is not supported " + driverClassName);
|
throw new IllegalArgumentException("The driver's class is not supported " + driverClassName);
|
||||||
}
|
}
|
||||||
|
|||||||
+3
-2
@@ -27,7 +27,8 @@ import org.springframework.stereotype.Component;
|
|||||||
@Component
|
@Component
|
||||||
public class DatabaseAwareMigrationContextProvider {
|
public class DatabaseAwareMigrationContextProvider {
|
||||||
|
|
||||||
private final Map<DatabaseType, String> contextMapping = Map.of(DatabaseType.MYSQL, "mysql", DatabaseType.POSTGRESQL, "postgresql");
|
private static final Map<DatabaseType, String> CONTEXT_MAPPING = Map.of(DatabaseType.MYSQL, "mysql", DatabaseType.POSTGRESQL,
|
||||||
|
"postgresql");
|
||||||
|
|
||||||
private final DatabaseTypeResolver databaseTypeResolver;
|
private final DatabaseTypeResolver databaseTypeResolver;
|
||||||
|
|
||||||
@@ -38,7 +39,7 @@ public class DatabaseAwareMigrationContextProvider {
|
|||||||
|
|
||||||
public String provide() {
|
public String provide() {
|
||||||
DatabaseType databaseType = databaseTypeResolver.databaseType();
|
DatabaseType databaseType = databaseTypeResolver.databaseType();
|
||||||
String context = contextMapping.get(databaseType);
|
String context = CONTEXT_MAPPING.get(databaseType);
|
||||||
if (context == null) {
|
if (context == null) {
|
||||||
throw new IllegalStateException("Database is not supported");
|
throw new IllegalStateException("Database is not supported");
|
||||||
}
|
}
|
||||||
|
|||||||
+13
-13
@@ -60,9 +60,9 @@ import org.springframework.stereotype.Component;
|
|||||||
@Tag(name = "Credit Bureau Configuration", description = "")
|
@Tag(name = "Credit Bureau Configuration", description = "")
|
||||||
public class CreditBureauConfigurationAPI {
|
public class CreditBureauConfigurationAPI {
|
||||||
|
|
||||||
private final Set<String> responseDataParameters = new HashSet<>(
|
private static final Set<String> RESPONSE_DATA_PARAMETERS = new HashSet<>(
|
||||||
Arrays.asList("creditBureauId", "alias", "country", "creditBureauProductId", "startDate", "endDate", "isActive"));
|
Arrays.asList("creditBureauId", "alias", "country", "creditBureauProductId", "startDate", "endDate", "isActive"));
|
||||||
private final String resourceNameForPermissions = "CreditBureau";
|
private static final String RESOURCE_NAME_FOR_PERMISSIONS = "CreditBureau";
|
||||||
private final PlatformSecurityContext context;
|
private final PlatformSecurityContext context;
|
||||||
private final CreditBureauReadPlatformService readPlatformService;
|
private final CreditBureauReadPlatformService readPlatformService;
|
||||||
private final DefaultToApiJsonSerializer<CreditBureauData> toApiJsonSerializer;
|
private final DefaultToApiJsonSerializer<CreditBureauData> toApiJsonSerializer;
|
||||||
@@ -105,12 +105,12 @@ public class CreditBureauConfigurationAPI {
|
|||||||
@Consumes({ MediaType.APPLICATION_JSON })
|
@Consumes({ MediaType.APPLICATION_JSON })
|
||||||
@Produces({ MediaType.APPLICATION_JSON })
|
@Produces({ MediaType.APPLICATION_JSON })
|
||||||
public String getCreditBureau(@Context final UriInfo uriInfo) {
|
public String getCreditBureau(@Context final UriInfo uriInfo) {
|
||||||
this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions);
|
this.context.authenticatedUser().validateHasReadPermission(RESOURCE_NAME_FOR_PERMISSIONS);
|
||||||
|
|
||||||
final Collection<CreditBureauData> creditBureau = this.readPlatformService.retrieveCreditBureau();
|
final Collection<CreditBureauData> creditBureau = this.readPlatformService.retrieveCreditBureau();
|
||||||
|
|
||||||
final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters());
|
final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters());
|
||||||
return this.toApiJsonSerializer.serialize(settings, creditBureau, this.responseDataParameters);
|
return this.toApiJsonSerializer.serialize(settings, creditBureau, RESPONSE_DATA_PARAMETERS);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -119,14 +119,14 @@ public class CreditBureauConfigurationAPI {
|
|||||||
@Consumes({ MediaType.APPLICATION_JSON })
|
@Consumes({ MediaType.APPLICATION_JSON })
|
||||||
@Produces({ MediaType.APPLICATION_JSON })
|
@Produces({ MediaType.APPLICATION_JSON })
|
||||||
public String getCreditBureauLoanProductMapping(@Context final UriInfo uriInfo) {
|
public String getCreditBureauLoanProductMapping(@Context final UriInfo uriInfo) {
|
||||||
this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions);
|
this.context.authenticatedUser().validateHasReadPermission(RESOURCE_NAME_FOR_PERMISSIONS);
|
||||||
|
|
||||||
final Collection<CreditBureauLoanProductMappingData> creditBureauLoanProductMapping = this.readPlatformServiceCreditBureauLoanProduct
|
final Collection<CreditBureauLoanProductMappingData> creditBureauLoanProductMapping = this.readPlatformServiceCreditBureauLoanProduct
|
||||||
.readCreditBureauLoanProductMapping();
|
.readCreditBureauLoanProductMapping();
|
||||||
|
|
||||||
final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters());
|
final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters());
|
||||||
return this.toApiJsonSerializerCreditBureauLoanProduct.serialize(settings, creditBureauLoanProductMapping,
|
return this.toApiJsonSerializerCreditBureauLoanProduct.serialize(settings, creditBureauLoanProductMapping,
|
||||||
this.responseDataParameters);
|
RESPONSE_DATA_PARAMETERS);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -135,13 +135,13 @@ public class CreditBureauConfigurationAPI {
|
|||||||
@Consumes({ MediaType.APPLICATION_JSON })
|
@Consumes({ MediaType.APPLICATION_JSON })
|
||||||
@Produces({ MediaType.APPLICATION_JSON })
|
@Produces({ MediaType.APPLICATION_JSON })
|
||||||
public String getOrganisationCreditBureau(@Context final UriInfo uriInfo) {
|
public String getOrganisationCreditBureau(@Context final UriInfo uriInfo) {
|
||||||
this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions);
|
this.context.authenticatedUser().validateHasReadPermission(RESOURCE_NAME_FOR_PERMISSIONS);
|
||||||
|
|
||||||
final Collection<OrganisationCreditBureauData> organisationCreditBureau = this.readPlatformServiceOrganisationCreditBureau
|
final Collection<OrganisationCreditBureauData> organisationCreditBureau = this.readPlatformServiceOrganisationCreditBureau
|
||||||
.retrieveOrgCreditBureau();
|
.retrieveOrgCreditBureau();
|
||||||
|
|
||||||
final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters());
|
final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters());
|
||||||
return this.toApiJsonSerializerOrganisationCreditBureau.serialize(settings, organisationCreditBureau, this.responseDataParameters);
|
return this.toApiJsonSerializerOrganisationCreditBureau.serialize(settings, organisationCreditBureau, RESPONSE_DATA_PARAMETERS);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -152,7 +152,7 @@ public class CreditBureauConfigurationAPI {
|
|||||||
public String getConfiguration(@PathParam("organisationCreditBureauId") final Long organisationCreditBureauId,
|
public String getConfiguration(@PathParam("organisationCreditBureauId") final Long organisationCreditBureauId,
|
||||||
@Context final UriInfo uriInfo) {
|
@Context final UriInfo uriInfo) {
|
||||||
|
|
||||||
this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions);
|
this.context.authenticatedUser().validateHasReadPermission(RESOURCE_NAME_FOR_PERMISSIONS);
|
||||||
|
|
||||||
final Collection<CreditBureauConfigurationData> configurationData = this.creditBureauConfiguration
|
final Collection<CreditBureauConfigurationData> configurationData = this.creditBureauConfiguration
|
||||||
.readConfigurationByOrganisationCreditBureauId(organisationCreditBureauId);
|
.readConfigurationByOrganisationCreditBureauId(organisationCreditBureauId);
|
||||||
@@ -165,14 +165,14 @@ public class CreditBureauConfigurationAPI {
|
|||||||
@Consumes({ MediaType.APPLICATION_JSON })
|
@Consumes({ MediaType.APPLICATION_JSON })
|
||||||
@Produces({ MediaType.APPLICATION_JSON })
|
@Produces({ MediaType.APPLICATION_JSON })
|
||||||
public String fetchLoanProducts(@Context final UriInfo uriInfo) {
|
public String fetchLoanProducts(@Context final UriInfo uriInfo) {
|
||||||
this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions);
|
this.context.authenticatedUser().validateHasReadPermission(RESOURCE_NAME_FOR_PERMISSIONS);
|
||||||
|
|
||||||
final Collection<CreditBureauLoanProductMappingData> creditBureauLoanProductMapping = this.readPlatformServiceCreditBureauLoanProduct
|
final Collection<CreditBureauLoanProductMappingData> creditBureauLoanProductMapping = this.readPlatformServiceCreditBureauLoanProduct
|
||||||
.fetchLoanProducts();
|
.fetchLoanProducts();
|
||||||
|
|
||||||
final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters());
|
final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters());
|
||||||
return this.toApiJsonSerializerCreditBureauLoanProduct.serialize(settings, creditBureauLoanProductMapping,
|
return this.toApiJsonSerializerCreditBureauLoanProduct.serialize(settings, creditBureauLoanProductMapping,
|
||||||
this.responseDataParameters);
|
RESPONSE_DATA_PARAMETERS);
|
||||||
}
|
}
|
||||||
|
|
||||||
@GET
|
@GET
|
||||||
@@ -180,14 +180,14 @@ public class CreditBureauConfigurationAPI {
|
|||||||
@Consumes({ MediaType.APPLICATION_JSON })
|
@Consumes({ MediaType.APPLICATION_JSON })
|
||||||
@Produces({ MediaType.APPLICATION_JSON })
|
@Produces({ MediaType.APPLICATION_JSON })
|
||||||
public String fetchMappingByLoanProductId(@Context final UriInfo uriInfo, @PathParam("loanProductId") final Long loanProductId) {
|
public String fetchMappingByLoanProductId(@Context final UriInfo uriInfo, @PathParam("loanProductId") final Long loanProductId) {
|
||||||
this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions);
|
this.context.authenticatedUser().validateHasReadPermission(RESOURCE_NAME_FOR_PERMISSIONS);
|
||||||
|
|
||||||
final CreditBureauLoanProductMappingData creditBureauLoanProductMapping = this.readPlatformServiceCreditBureauLoanProduct
|
final CreditBureauLoanProductMappingData creditBureauLoanProductMapping = this.readPlatformServiceCreditBureauLoanProduct
|
||||||
.readMappingByLoanId(loanProductId);
|
.readMappingByLoanId(loanProductId);
|
||||||
|
|
||||||
final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters());
|
final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters());
|
||||||
return this.toApiJsonSerializerCreditBureauLoanProduct.serialize(settings, creditBureauLoanProductMapping,
|
return this.toApiJsonSerializerCreditBureauLoanProduct.serialize(settings, creditBureauLoanProductMapping,
|
||||||
this.responseDataParameters);
|
RESPONSE_DATA_PARAMETERS);
|
||||||
}
|
}
|
||||||
|
|
||||||
@PUT
|
@PUT
|
||||||
|
|||||||
+17
-14
@@ -39,7 +39,10 @@ import org.springframework.stereotype.Component;
|
|||||||
@Component
|
@Component
|
||||||
public class CreditBureauCommandFromApiJsonDeserializer {
|
public class CreditBureauCommandFromApiJsonDeserializer {
|
||||||
|
|
||||||
private final Set<String> supportedParameters = new HashSet<>(Arrays.asList("alias", "isActive", "creditBureauId"));
|
public static final String ALIAS = "alias";
|
||||||
|
public static final String IS_ACTIVE = "isActive";
|
||||||
|
public static final String CREDIT_BUREAU_ID = "creditBureauId";
|
||||||
|
private static final Set<String> SUPPORTED_PARAMETERS = new HashSet<>(Arrays.asList(ALIAS, IS_ACTIVE, CREDIT_BUREAU_ID));
|
||||||
|
|
||||||
private final FromJsonHelper fromApiJsonHelper;
|
private final FromJsonHelper fromApiJsonHelper;
|
||||||
|
|
||||||
@@ -54,7 +57,7 @@ public class CreditBureauCommandFromApiJsonDeserializer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType();
|
final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType();
|
||||||
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParameters);
|
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, SUPPORTED_PARAMETERS);
|
||||||
|
|
||||||
final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
|
final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
|
||||||
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("CreditBureau");
|
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("CreditBureau");
|
||||||
@@ -63,13 +66,13 @@ public class CreditBureauCommandFromApiJsonDeserializer {
|
|||||||
|
|
||||||
baseDataValidator.reset().value(creditBureauId).notBlank().integerGreaterThanZero();
|
baseDataValidator.reset().value(creditBureauId).notBlank().integerGreaterThanZero();
|
||||||
|
|
||||||
final String alias = this.fromApiJsonHelper.extractStringNamed("alias", element);
|
final String alias = this.fromApiJsonHelper.extractStringNamed(ALIAS, element);
|
||||||
baseDataValidator.reset().parameter("alias").value(alias).notNull().notBlank().notExceedingLengthOf(100);
|
baseDataValidator.reset().parameter(ALIAS).value(alias).notNull().notBlank().notExceedingLengthOf(100);
|
||||||
|
|
||||||
final String is_activeParameter = "isActive";
|
final String is_activeParameter = IS_ACTIVE;
|
||||||
if (this.fromApiJsonHelper.parameterExists(is_activeParameter, element)) {
|
if (this.fromApiJsonHelper.parameterExists(is_activeParameter, element)) {
|
||||||
final boolean isActive = this.fromApiJsonHelper.extractBooleanNamed("isActive", element);
|
final boolean isActive = this.fromApiJsonHelper.extractBooleanNamed(IS_ACTIVE, element);
|
||||||
baseDataValidator.reset().parameter("isActive").value(isActive).notNull().notBlank().trueOrFalseRequired(isActive);
|
baseDataValidator.reset().parameter(IS_ACTIVE).value(isActive).notNull().notBlank().trueOrFalseRequired(isActive);
|
||||||
}
|
}
|
||||||
|
|
||||||
throwExceptionIfValidationWarningsExist(dataValidationErrors);
|
throwExceptionIfValidationWarningsExist(dataValidationErrors);
|
||||||
@@ -81,23 +84,23 @@ public class CreditBureauCommandFromApiJsonDeserializer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType();
|
final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType();
|
||||||
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParameters);
|
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, SUPPORTED_PARAMETERS);
|
||||||
|
|
||||||
final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
|
final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
|
||||||
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("CreditBureau");
|
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("CreditBureau");
|
||||||
|
|
||||||
final JsonElement element = this.fromApiJsonHelper.parse(json);
|
final JsonElement element = this.fromApiJsonHelper.parse(json);
|
||||||
|
|
||||||
final String creditBureauIdParameter = "creditBureauId";
|
final String creditBureauIdParameter = CREDIT_BUREAU_ID;
|
||||||
if (this.fromApiJsonHelper.parameterExists(creditBureauIdParameter, element)) {
|
if (this.fromApiJsonHelper.parameterExists(creditBureauIdParameter, element)) {
|
||||||
final Long creditBureauId = this.fromApiJsonHelper.extractLongNamed("creditBureauId", element);
|
final Long creditBureauId = this.fromApiJsonHelper.extractLongNamed(CREDIT_BUREAU_ID, element);
|
||||||
baseDataValidator.reset().parameter("creditBureauId").value(creditBureauId).notNull().notBlank().longGreaterThanZero();
|
baseDataValidator.reset().parameter(CREDIT_BUREAU_ID).value(creditBureauId).notNull().notBlank().longGreaterThanZero();
|
||||||
}
|
}
|
||||||
|
|
||||||
final String is_activeParameter = "isActive";
|
final String is_activeParameter = IS_ACTIVE;
|
||||||
if (this.fromApiJsonHelper.parameterExists(is_activeParameter, element)) {
|
if (this.fromApiJsonHelper.parameterExists(is_activeParameter, element)) {
|
||||||
final boolean isActive = this.fromApiJsonHelper.extractBooleanNamed("isActive", element);
|
final boolean isActive = this.fromApiJsonHelper.extractBooleanNamed(IS_ACTIVE, element);
|
||||||
baseDataValidator.reset().parameter("isActive").value(isActive).notNull().notBlank().trueOrFalseRequired(isActive);
|
baseDataValidator.reset().parameter(IS_ACTIVE).value(isActive).notNull().notBlank().trueOrFalseRequired(isActive);
|
||||||
}
|
}
|
||||||
|
|
||||||
throwExceptionIfValidationWarningsExist(dataValidationErrors);
|
throwExceptionIfValidationWarningsExist(dataValidationErrors);
|
||||||
|
|||||||
+19
-16
@@ -39,7 +39,10 @@ import org.springframework.stereotype.Component;
|
|||||||
@Component
|
@Component
|
||||||
public final class CreditBureauConfigurationCommandFromApiJsonDeserializer {
|
public final class CreditBureauConfigurationCommandFromApiJsonDeserializer {
|
||||||
|
|
||||||
private final Set<String> supportedParameters = new HashSet<>(Arrays.asList("configkey", "value", "description"));
|
public static final String CONFIGKEY = "configkey";
|
||||||
|
public static final String VALUE = "value";
|
||||||
|
public static final String DESCRIPTION = "description";
|
||||||
|
private static final Set<String> SUPPORTED_PARAMETERS = new HashSet<>(Arrays.asList(CONFIGKEY, VALUE, DESCRIPTION));
|
||||||
private final FromJsonHelper fromApiJsonHelper;
|
private final FromJsonHelper fromApiJsonHelper;
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
@@ -53,7 +56,7 @@ public final class CreditBureauConfigurationCommandFromApiJsonDeserializer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType();
|
final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType();
|
||||||
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParameters);
|
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, SUPPORTED_PARAMETERS);
|
||||||
|
|
||||||
final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
|
final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
|
||||||
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors)
|
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors)
|
||||||
@@ -63,16 +66,16 @@ public final class CreditBureauConfigurationCommandFromApiJsonDeserializer {
|
|||||||
|
|
||||||
baseDataValidator.reset().value(creditBureauId).notBlank().integerGreaterThanZero();
|
baseDataValidator.reset().value(creditBureauId).notBlank().integerGreaterThanZero();
|
||||||
|
|
||||||
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParameters);
|
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, SUPPORTED_PARAMETERS);
|
||||||
|
|
||||||
final String configkey = this.fromApiJsonHelper.extractStringNamed("configkey", element);
|
final String configkey = this.fromApiJsonHelper.extractStringNamed(CONFIGKEY, element);
|
||||||
baseDataValidator.reset().parameter("configkey").value(configkey).notBlank().notExceedingLengthOf(100);
|
baseDataValidator.reset().parameter(CONFIGKEY).value(configkey).notBlank().notExceedingLengthOf(100);
|
||||||
|
|
||||||
final String value = this.fromApiJsonHelper.extractStringNamed("value", element);
|
final String value = this.fromApiJsonHelper.extractStringNamed(VALUE, element);
|
||||||
baseDataValidator.reset().parameter("value").value(value).notBlank().notExceedingLengthOf(100);
|
baseDataValidator.reset().parameter(VALUE).value(value).notBlank().notExceedingLengthOf(100);
|
||||||
|
|
||||||
final String description = this.fromApiJsonHelper.extractStringNamed("description", element);
|
final String description = this.fromApiJsonHelper.extractStringNamed(DESCRIPTION, element);
|
||||||
baseDataValidator.reset().parameter("description").value(description).notBlank().notExceedingLengthOf(100);
|
baseDataValidator.reset().parameter(DESCRIPTION).value(description).notBlank().notExceedingLengthOf(100);
|
||||||
|
|
||||||
throwExceptionIfValidationWarningsExist(dataValidationErrors);
|
throwExceptionIfValidationWarningsExist(dataValidationErrors);
|
||||||
}
|
}
|
||||||
@@ -83,21 +86,21 @@ public final class CreditBureauConfigurationCommandFromApiJsonDeserializer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType();
|
final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType();
|
||||||
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParameters);
|
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, SUPPORTED_PARAMETERS);
|
||||||
|
|
||||||
final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
|
final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
|
||||||
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("config");
|
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("config");
|
||||||
|
|
||||||
final JsonElement element = this.fromApiJsonHelper.parse(json);
|
final JsonElement element = this.fromApiJsonHelper.parse(json);
|
||||||
|
|
||||||
if (this.fromApiJsonHelper.parameterExists("value", element)) {
|
if (this.fromApiJsonHelper.parameterExists(VALUE, element)) {
|
||||||
final String value = this.fromApiJsonHelper.extractStringNamed("value", element);
|
final String value = this.fromApiJsonHelper.extractStringNamed(VALUE, element);
|
||||||
baseDataValidator.reset().parameter("value").value(value).notBlank().notExceedingLengthOf(100);
|
baseDataValidator.reset().parameter(VALUE).value(value).notBlank().notExceedingLengthOf(100);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (this.fromApiJsonHelper.parameterExists("description", element)) {
|
if (this.fromApiJsonHelper.parameterExists(DESCRIPTION, element)) {
|
||||||
final String description = this.fromApiJsonHelper.extractStringNamed("description", element);
|
final String description = this.fromApiJsonHelper.extractStringNamed(DESCRIPTION, element);
|
||||||
baseDataValidator.reset().parameter("description").value(description).notBlank().notExceedingLengthOf(100);
|
baseDataValidator.reset().parameter(DESCRIPTION).value(description).notBlank().notExceedingLengthOf(100);
|
||||||
}
|
}
|
||||||
|
|
||||||
throwExceptionIfValidationWarningsExist(dataValidationErrors);
|
throwExceptionIfValidationWarningsExist(dataValidationErrors);
|
||||||
|
|||||||
+38
-31
@@ -39,8 +39,15 @@ import org.springframework.stereotype.Component;
|
|||||||
@Component
|
@Component
|
||||||
public class CreditBureauLoanProductCommandFromApiJsonDeserializer {
|
public class CreditBureauLoanProductCommandFromApiJsonDeserializer {
|
||||||
|
|
||||||
private final Set<String> supportedParameters = new HashSet<>(Arrays.asList("loanProductId", "isCreditcheckMandatory",
|
public static final String LOAN_PRODUCT_ID = "loanProductId";
|
||||||
"skipCreditcheckInFailure", "stalePeriod", "isActive", "locale", "creditbureauLoanProductMappingId"));
|
public static final String IS_CREDITCHECK_MANDATORY = "isCreditcheckMandatory";
|
||||||
|
public static final String SKIP_CREDITCHECK_IN_FAILURE = "skipCreditcheckInFailure";
|
||||||
|
public static final String STALE_PERIOD = "stalePeriod";
|
||||||
|
public static final String IS_ACTIVE = "isActive";
|
||||||
|
public static final String LOCALE = "locale";
|
||||||
|
public static final String CREDITBUREAU_LOAN_PRODUCT_MAPPING_ID = "creditbureauLoanProductMappingId";
|
||||||
|
private static final Set<String> SUPPORTED_PARAMETERS = new HashSet<>(Arrays.asList(LOAN_PRODUCT_ID, IS_CREDITCHECK_MANDATORY,
|
||||||
|
SKIP_CREDITCHECK_IN_FAILURE, STALE_PERIOD, IS_ACTIVE, LOCALE, CREDITBUREAU_LOAN_PRODUCT_MAPPING_ID));
|
||||||
|
|
||||||
private final FromJsonHelper fromApiJsonHelper;
|
private final FromJsonHelper fromApiJsonHelper;
|
||||||
|
|
||||||
@@ -55,7 +62,7 @@ public class CreditBureauLoanProductCommandFromApiJsonDeserializer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType();
|
final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType();
|
||||||
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParameters);
|
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, SUPPORTED_PARAMETERS);
|
||||||
|
|
||||||
final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
|
final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
|
||||||
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors)
|
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors)
|
||||||
@@ -65,45 +72,45 @@ public class CreditBureauLoanProductCommandFromApiJsonDeserializer {
|
|||||||
|
|
||||||
baseDataValidator.reset().value(cb_id).notBlank().integerGreaterThanZero();
|
baseDataValidator.reset().value(cb_id).notBlank().integerGreaterThanZero();
|
||||||
|
|
||||||
final long loanProductId = this.fromApiJsonHelper.extractLongNamed("loanProductId", element);
|
final long loanProductId = this.fromApiJsonHelper.extractLongNamed(LOAN_PRODUCT_ID, element);
|
||||||
baseDataValidator.reset().parameter("loanProductId").value(loanProductId).notBlank().integerGreaterThanZero();
|
baseDataValidator.reset().parameter(LOAN_PRODUCT_ID).value(loanProductId).notBlank().integerGreaterThanZero();
|
||||||
|
|
||||||
if (this.fromApiJsonHelper.extractBooleanNamed("isCreditcheckMandatory", element) != null) {
|
if (this.fromApiJsonHelper.extractBooleanNamed(IS_CREDITCHECK_MANDATORY, element) != null) {
|
||||||
final boolean isCreditcheckMandatory = this.fromApiJsonHelper.extractBooleanNamed("isCreditcheckMandatory", element);
|
final boolean isCreditcheckMandatory = this.fromApiJsonHelper.extractBooleanNamed(IS_CREDITCHECK_MANDATORY, element);
|
||||||
baseDataValidator.reset().parameter("isCreditcheckMandatory").value(isCreditcheckMandatory).notBlank()
|
baseDataValidator.reset().parameter(IS_CREDITCHECK_MANDATORY).value(isCreditcheckMandatory).notBlank()
|
||||||
.trueOrFalseRequired(isCreditcheckMandatory);
|
.trueOrFalseRequired(isCreditcheckMandatory);
|
||||||
} else {
|
} else {
|
||||||
baseDataValidator.reset().parameter("isCreditcheckMandatory")
|
baseDataValidator.reset().parameter(IS_CREDITCHECK_MANDATORY)
|
||||||
.value(this.fromApiJsonHelper.extractBooleanNamed("isCreditcheckMandatory", element)).notBlank()
|
.value(this.fromApiJsonHelper.extractBooleanNamed(IS_CREDITCHECK_MANDATORY, element)).notBlank()
|
||||||
.trueOrFalseRequired(this.fromApiJsonHelper.extractBooleanNamed("isCreditcheckMandatory", element));
|
.trueOrFalseRequired(this.fromApiJsonHelper.extractBooleanNamed(IS_CREDITCHECK_MANDATORY, element));
|
||||||
}
|
}
|
||||||
|
|
||||||
if (this.fromApiJsonHelper.extractBooleanNamed("skipCreditcheckInFailure", element) != null) {
|
if (this.fromApiJsonHelper.extractBooleanNamed(SKIP_CREDITCHECK_IN_FAILURE, element) != null) {
|
||||||
final boolean skipCreditcheckInFailure = this.fromApiJsonHelper.extractBooleanNamed("skipCreditcheckInFailure", element);
|
final boolean skipCreditcheckInFailure = this.fromApiJsonHelper.extractBooleanNamed(SKIP_CREDITCHECK_IN_FAILURE, element);
|
||||||
baseDataValidator.reset().parameter("skipCreditcheckInFailure").value(skipCreditcheckInFailure).notBlank()
|
baseDataValidator.reset().parameter(SKIP_CREDITCHECK_IN_FAILURE).value(skipCreditcheckInFailure).notBlank()
|
||||||
.trueOrFalseRequired(skipCreditcheckInFailure);
|
.trueOrFalseRequired(skipCreditcheckInFailure);
|
||||||
|
|
||||||
} else {
|
} else {
|
||||||
baseDataValidator.reset().parameter("skipCreditcheckInFailure")
|
baseDataValidator.reset().parameter(SKIP_CREDITCHECK_IN_FAILURE)
|
||||||
.value(this.fromApiJsonHelper.extractBooleanNamed("skipCreditcheckInFailure", element)).notBlank()
|
.value(this.fromApiJsonHelper.extractBooleanNamed(SKIP_CREDITCHECK_IN_FAILURE, element)).notBlank()
|
||||||
.trueOrFalseRequired(this.fromApiJsonHelper.extractBooleanNamed("skipCreditcheckInFailure", element));
|
.trueOrFalseRequired(this.fromApiJsonHelper.extractBooleanNamed(SKIP_CREDITCHECK_IN_FAILURE, element));
|
||||||
}
|
}
|
||||||
|
|
||||||
if (this.fromApiJsonHelper.extractLongNamed("stalePeriod", element) != null) {
|
if (this.fromApiJsonHelper.extractLongNamed(STALE_PERIOD, element) != null) {
|
||||||
final long stalePeriod = this.fromApiJsonHelper.extractLongNamed("stalePeriod", element);
|
final long stalePeriod = this.fromApiJsonHelper.extractLongNamed(STALE_PERIOD, element);
|
||||||
baseDataValidator.reset().parameter("stalePeriod").value(stalePeriod).notBlank().integerGreaterThanZero();
|
baseDataValidator.reset().parameter(STALE_PERIOD).value(stalePeriod).notBlank().integerGreaterThanZero();
|
||||||
} else {
|
} else {
|
||||||
baseDataValidator.reset().parameter("stalePeriod").value(this.fromApiJsonHelper.extractLongNamed("stalePeriod", element))
|
baseDataValidator.reset().parameter(STALE_PERIOD).value(this.fromApiJsonHelper.extractLongNamed(STALE_PERIOD, element))
|
||||||
.notBlank().integerGreaterThanZero();
|
.notBlank().integerGreaterThanZero();
|
||||||
}
|
}
|
||||||
|
|
||||||
if (this.fromApiJsonHelper.extractBooleanNamed("isActive", element) != null) {
|
if (this.fromApiJsonHelper.extractBooleanNamed(IS_ACTIVE, element) != null) {
|
||||||
Boolean isActive = this.fromApiJsonHelper.extractBooleanNamed("isActive", element);
|
Boolean isActive = this.fromApiJsonHelper.extractBooleanNamed(IS_ACTIVE, element);
|
||||||
if (isActive == null) {
|
if (isActive == null) {
|
||||||
isActive = false;
|
isActive = false;
|
||||||
} else {
|
} else {
|
||||||
|
|
||||||
baseDataValidator.reset().parameter("isActive").value(isActive).notBlank().trueOrFalseRequired(isActive);
|
baseDataValidator.reset().parameter(IS_ACTIVE).value(isActive).notBlank().trueOrFalseRequired(isActive);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -117,7 +124,7 @@ public class CreditBureauLoanProductCommandFromApiJsonDeserializer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType();
|
final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType();
|
||||||
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParameters);
|
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, SUPPORTED_PARAMETERS);
|
||||||
|
|
||||||
final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
|
final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
|
||||||
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors)
|
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors)
|
||||||
@@ -125,18 +132,18 @@ public class CreditBureauLoanProductCommandFromApiJsonDeserializer {
|
|||||||
|
|
||||||
final JsonElement element = this.fromApiJsonHelper.parse(json);
|
final JsonElement element = this.fromApiJsonHelper.parse(json);
|
||||||
|
|
||||||
final String creditbureauLoanProductMappingIdParameter = "creditbureauLoanProductMappingId";
|
final String creditbureauLoanProductMappingIdParameter = CREDITBUREAU_LOAN_PRODUCT_MAPPING_ID;
|
||||||
if (this.fromApiJsonHelper.parameterExists(creditbureauLoanProductMappingIdParameter, element)) {
|
if (this.fromApiJsonHelper.parameterExists(creditbureauLoanProductMappingIdParameter, element)) {
|
||||||
final Long creditbureauLoanProductMappingId = this.fromApiJsonHelper.extractLongNamed("creditbureauLoanProductMappingId",
|
final Long creditbureauLoanProductMappingId = this.fromApiJsonHelper.extractLongNamed(CREDITBUREAU_LOAN_PRODUCT_MAPPING_ID,
|
||||||
element);
|
element);
|
||||||
baseDataValidator.reset().parameter("creditbureauLoanProductMappingId").value(creditbureauLoanProductMappingId).notNull()
|
baseDataValidator.reset().parameter(CREDITBUREAU_LOAN_PRODUCT_MAPPING_ID).value(creditbureauLoanProductMappingId).notNull()
|
||||||
.notBlank().longGreaterThanZero();
|
.notBlank().longGreaterThanZero();
|
||||||
}
|
}
|
||||||
|
|
||||||
final String is_activeParameter = "isActive";
|
final String is_activeParameter = IS_ACTIVE;
|
||||||
if (this.fromApiJsonHelper.parameterExists(is_activeParameter, element)) {
|
if (this.fromApiJsonHelper.parameterExists(is_activeParameter, element)) {
|
||||||
final boolean isActive = this.fromApiJsonHelper.extractBooleanNamed("isActive", element);
|
final boolean isActive = this.fromApiJsonHelper.extractBooleanNamed(IS_ACTIVE, element);
|
||||||
baseDataValidator.reset().parameter("isActive").value(isActive).notNull().notBlank().trueOrFalseRequired(isActive);
|
baseDataValidator.reset().parameter(IS_ACTIVE).value(isActive).notNull().notBlank().trueOrFalseRequired(isActive);
|
||||||
}
|
}
|
||||||
|
|
||||||
throwExceptionIfValidationWarningsExist(dataValidationErrors);
|
throwExceptionIfValidationWarningsExist(dataValidationErrors);
|
||||||
|
|||||||
+41
-33
@@ -34,21 +34,25 @@ import org.apache.fineract.infrastructure.core.data.DataValidatorBuilder;
|
|||||||
import org.apache.fineract.infrastructure.core.exception.InvalidJsonException;
|
import org.apache.fineract.infrastructure.core.exception.InvalidJsonException;
|
||||||
import org.apache.fineract.infrastructure.core.exception.PlatformApiDataValidationException;
|
import org.apache.fineract.infrastructure.core.exception.PlatformApiDataValidationException;
|
||||||
import org.apache.fineract.infrastructure.core.serialization.FromJsonHelper;
|
import org.apache.fineract.infrastructure.core.serialization.FromJsonHelper;
|
||||||
import org.slf4j.Logger;
|
|
||||||
import org.slf4j.LoggerFactory;
|
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
import org.springframework.stereotype.Component;
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
@Component
|
@Component
|
||||||
public class CreditBureauTokenCommandFromApiJsonDeserializer {
|
public class CreditBureauTokenCommandFromApiJsonDeserializer {
|
||||||
|
|
||||||
private static final Logger LOG = LoggerFactory.getLogger(CreditBureauTokenCommandFromApiJsonDeserializer.class);
|
public static final String ACCESS_TOKEN = "access_token";
|
||||||
|
public static final String TOKEN_TYPE = "token_type";
|
||||||
private final Set<String> supportedParameters = new HashSet<>(
|
public static final String EXPIRES_IN = "expires_in";
|
||||||
Arrays.asList("access_token", "token_type", "expires_in", "userName", ".issued", ".expires"));
|
public static final String USER_NAME = "userName";
|
||||||
|
public static final String ISSUED = ".issued";
|
||||||
private final Set<String> supportedTokenConfigParameters = new HashSet<>(
|
public static final String EXPIRES = ".expires";
|
||||||
Arrays.asList("userName", "password", "subscriptionId", "subscriptionKey"));
|
public static final String PASSWORD = "password";
|
||||||
|
public static final String SUBSCRIPTION_ID = "subscriptionId";
|
||||||
|
public static final String SUBSCRIPTION_KEY = "subscriptionKey";
|
||||||
|
private static final Set<String> SUPPORTED_PARAMETERS = new HashSet<>(
|
||||||
|
Arrays.asList(ACCESS_TOKEN, TOKEN_TYPE, EXPIRES_IN, USER_NAME, ISSUED, EXPIRES));
|
||||||
|
private static final Set<String> SUPPORTED_TOKEN_CONFIG_PARAMETERS = new HashSet<>(
|
||||||
|
Arrays.asList(USER_NAME, PASSWORD, SUBSCRIPTION_ID, SUBSCRIPTION_KEY));
|
||||||
private final FromJsonHelper fromApiJsonHelper;
|
private final FromJsonHelper fromApiJsonHelper;
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
@@ -61,31 +65,33 @@ public class CreditBureauTokenCommandFromApiJsonDeserializer {
|
|||||||
throw new InvalidJsonException();
|
throw new InvalidJsonException();
|
||||||
}
|
}
|
||||||
|
|
||||||
final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType();
|
final Type typeOfMap = new TypeToken<Map<String, Object>>() {
|
||||||
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParameters);
|
|
||||||
|
}.getType();
|
||||||
|
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, SUPPORTED_PARAMETERS);
|
||||||
|
|
||||||
final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
|
final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
|
||||||
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("tokens");
|
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("tokens");
|
||||||
|
|
||||||
final JsonElement element = this.fromApiJsonHelper.parse(json);
|
final JsonElement element = this.fromApiJsonHelper.parse(json);
|
||||||
|
|
||||||
final String access_token = this.fromApiJsonHelper.extractStringNamed("access_token", element);
|
final String access_token = this.fromApiJsonHelper.extractStringNamed(ACCESS_TOKEN, element);
|
||||||
baseDataValidator.reset().parameter("access_token").value(access_token).notBlank().notExceedingLengthOf(1000);
|
baseDataValidator.reset().parameter(ACCESS_TOKEN).value(access_token).notBlank().notExceedingLengthOf(1000);
|
||||||
|
|
||||||
final String token_type = this.fromApiJsonHelper.extractStringNamed("token_type", element);
|
final String token_type = this.fromApiJsonHelper.extractStringNamed(TOKEN_TYPE, element);
|
||||||
baseDataValidator.reset().parameter("token_type").value(token_type).notBlank().notExceedingLengthOf(100);
|
baseDataValidator.reset().parameter(TOKEN_TYPE).value(token_type).notBlank().notExceedingLengthOf(100);
|
||||||
|
|
||||||
final String expires_in = this.fromApiJsonHelper.extractStringNamed("expires_in", element);
|
final String expires_in = this.fromApiJsonHelper.extractStringNamed(EXPIRES_IN, element);
|
||||||
baseDataValidator.reset().parameter("expires_in").value(expires_in).notBlank().notExceedingLengthOf(100);
|
baseDataValidator.reset().parameter(EXPIRES_IN).value(expires_in).notBlank().notExceedingLengthOf(100);
|
||||||
|
|
||||||
final String userName = this.fromApiJsonHelper.extractStringNamed("userName", element);
|
final String userName = this.fromApiJsonHelper.extractStringNamed(USER_NAME, element);
|
||||||
baseDataValidator.reset().parameter("userName").value(userName).notBlank().notExceedingLengthOf(100);
|
baseDataValidator.reset().parameter(USER_NAME).value(userName).notBlank().notExceedingLengthOf(100);
|
||||||
|
|
||||||
final String issued = this.fromApiJsonHelper.extractStringNamed(".issued", element);
|
final String issued = this.fromApiJsonHelper.extractStringNamed(ISSUED, element);
|
||||||
baseDataValidator.reset().parameter(".issued").value(issued).notBlank().notExceedingLengthOf(100);
|
baseDataValidator.reset().parameter(ISSUED).value(issued).notBlank().notExceedingLengthOf(100);
|
||||||
|
|
||||||
final String expires = this.fromApiJsonHelper.extractStringNamed(".expires", element);
|
final String expires = this.fromApiJsonHelper.extractStringNamed(EXPIRES, element);
|
||||||
baseDataValidator.reset().parameter(".expires").value(expires).notBlank().notExceedingLengthOf(100);
|
baseDataValidator.reset().parameter(EXPIRES).value(expires).notBlank().notExceedingLengthOf(100);
|
||||||
|
|
||||||
throwExceptionIfValidationWarningsExist(dataValidationErrors);
|
throwExceptionIfValidationWarningsExist(dataValidationErrors);
|
||||||
}
|
}
|
||||||
@@ -95,25 +101,27 @@ public class CreditBureauTokenCommandFromApiJsonDeserializer {
|
|||||||
throw new InvalidJsonException();
|
throw new InvalidJsonException();
|
||||||
}
|
}
|
||||||
|
|
||||||
final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType();
|
final Type typeOfMap = new TypeToken<Map<String, Object>>() {
|
||||||
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedTokenConfigParameters);
|
|
||||||
|
}.getType();
|
||||||
|
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, SUPPORTED_TOKEN_CONFIG_PARAMETERS);
|
||||||
|
|
||||||
final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
|
final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
|
||||||
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("configdata");
|
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("configdata");
|
||||||
|
|
||||||
final JsonElement element = this.fromApiJsonHelper.parse(json);
|
final JsonElement element = this.fromApiJsonHelper.parse(json);
|
||||||
|
|
||||||
final String userName = this.fromApiJsonHelper.extractStringNamed("userName", element);
|
final String userName = this.fromApiJsonHelper.extractStringNamed(USER_NAME, element);
|
||||||
baseDataValidator.reset().parameter("userName").value(userName).notBlank().notExceedingLengthOf(1000);
|
baseDataValidator.reset().parameter(USER_NAME).value(userName).notBlank().notExceedingLengthOf(1000);
|
||||||
|
|
||||||
final String password = this.fromApiJsonHelper.extractStringNamed("password", element);
|
final String password = this.fromApiJsonHelper.extractStringNamed(PASSWORD, element);
|
||||||
baseDataValidator.reset().parameter("password").value(password).notBlank().notExceedingLengthOf(100);
|
baseDataValidator.reset().parameter(PASSWORD).value(password).notBlank().notExceedingLengthOf(100);
|
||||||
|
|
||||||
final String subscriptionId = this.fromApiJsonHelper.extractStringNamed("subscriptionId", element);
|
final String subscriptionId = this.fromApiJsonHelper.extractStringNamed(SUBSCRIPTION_ID, element);
|
||||||
baseDataValidator.reset().parameter("subscriptionId").value(subscriptionId).notBlank().notExceedingLengthOf(100);
|
baseDataValidator.reset().parameter(SUBSCRIPTION_ID).value(subscriptionId).notBlank().notExceedingLengthOf(100);
|
||||||
|
|
||||||
final String subscriptionKey = this.fromApiJsonHelper.extractStringNamed("subscriptionKey", element);
|
final String subscriptionKey = this.fromApiJsonHelper.extractStringNamed(SUBSCRIPTION_KEY, element);
|
||||||
baseDataValidator.reset().parameter("subscriptionKey").value(subscriptionKey).notBlank().notExceedingLengthOf(100);
|
baseDataValidator.reset().parameter(SUBSCRIPTION_KEY).value(subscriptionKey).notBlank().notExceedingLengthOf(100);
|
||||||
|
|
||||||
throwExceptionIfValidationWarningsExist(dataValidationErrors);
|
throwExceptionIfValidationWarningsExist(dataValidationErrors);
|
||||||
}
|
}
|
||||||
|
|||||||
+23
-33
@@ -34,17 +34,12 @@ import org.apache.fineract.infrastructure.core.data.CommandProcessingResultBuild
|
|||||||
import org.apache.fineract.infrastructure.core.data.DataValidatorBuilder;
|
import org.apache.fineract.infrastructure.core.data.DataValidatorBuilder;
|
||||||
import org.apache.fineract.infrastructure.core.exception.PlatformApiDataValidationException;
|
import org.apache.fineract.infrastructure.core.exception.PlatformApiDataValidationException;
|
||||||
import org.apache.fineract.infrastructure.core.exception.PlatformDataIntegrityException;
|
import org.apache.fineract.infrastructure.core.exception.PlatformDataIntegrityException;
|
||||||
import org.apache.fineract.infrastructure.core.serialization.FromJsonHelper;
|
|
||||||
import org.apache.fineract.infrastructure.creditbureau.data.CreditBureauConfigurations;
|
import org.apache.fineract.infrastructure.creditbureau.data.CreditBureauConfigurations;
|
||||||
import org.apache.fineract.infrastructure.creditbureau.data.CreditBureauReportData;
|
import org.apache.fineract.infrastructure.creditbureau.data.CreditBureauReportData;
|
||||||
import org.apache.fineract.infrastructure.creditbureau.domain.CreditBureau;
|
import org.apache.fineract.infrastructure.creditbureau.domain.CreditBureau;
|
||||||
import org.apache.fineract.infrastructure.creditbureau.domain.CreditBureauConfigurationRepositoryWrapper;
|
|
||||||
import org.apache.fineract.infrastructure.creditbureau.domain.CreditBureauLoanProductMappingRepository;
|
|
||||||
import org.apache.fineract.infrastructure.creditbureau.domain.CreditBureauRepository;
|
import org.apache.fineract.infrastructure.creditbureau.domain.CreditBureauRepository;
|
||||||
import org.apache.fineract.infrastructure.creditbureau.domain.CreditReport;
|
import org.apache.fineract.infrastructure.creditbureau.domain.CreditReport;
|
||||||
import org.apache.fineract.infrastructure.creditbureau.domain.CreditReportRepository;
|
import org.apache.fineract.infrastructure.creditbureau.domain.CreditReportRepository;
|
||||||
import org.apache.fineract.infrastructure.creditbureau.domain.TokenRepositoryWrapper;
|
|
||||||
import org.apache.fineract.infrastructure.creditbureau.serialization.CreditBureauTokenCommandFromApiJsonDeserializer;
|
|
||||||
import org.apache.fineract.infrastructure.security.service.PlatformSecurityContext;
|
import org.apache.fineract.infrastructure.security.service.PlatformSecurityContext;
|
||||||
import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
|
import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
@@ -56,36 +51,29 @@ import org.springframework.transaction.annotation.Transactional;
|
|||||||
@Service
|
@Service
|
||||||
public class CreditReportWritePlatformServiceImpl implements CreditReportWritePlatformService {
|
public class CreditReportWritePlatformServiceImpl implements CreditReportWritePlatformService {
|
||||||
|
|
||||||
|
public static final String CREDIT_BUREAU_INTEGRATION = "creditBureauIntegration";
|
||||||
|
public static final String CREDIT_BUREAU_HAS_NOT_BEEN_INTEGRATED = "creditBureau.has.not.been.Integrated";
|
||||||
private final PlatformSecurityContext context;
|
private final PlatformSecurityContext context;
|
||||||
private final CreditBureauConfigurationRepositoryWrapper configDataRepository;
|
|
||||||
private final CreditBureauRepository creditBureauRepository;
|
private final CreditBureauRepository creditBureauRepository;
|
||||||
private final CreditReportRepository creditReportRepository;
|
private final CreditReportRepository creditReportRepository;
|
||||||
private final ThitsaWorksCreditBureauIntegrationWritePlatformService thitsaWorksCreditBureauIntegrationWritePlatformService;
|
private final ThitsaWorksCreditBureauIntegrationWritePlatformService thitsaWorksCreditBureauIntegrationWritePlatformService;
|
||||||
private final ThitsaWorksCreditBureauIntegrationWritePlatformServiceImpl thitsaWorksCreditBureauIntegrationWritePlatformServiceImpl;
|
|
||||||
private final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
|
|
||||||
private final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors)
|
|
||||||
.resource("creditBureauIntegration");
|
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
public CreditReportWritePlatformServiceImpl(final PlatformSecurityContext context, final FromJsonHelper fromApiJsonHelper,
|
public CreditReportWritePlatformServiceImpl(final PlatformSecurityContext context, final CreditBureauRepository creditBureauRepository,
|
||||||
final TokenRepositoryWrapper tokenRepository, final CreditBureauConfigurationRepositoryWrapper configDataRepository,
|
final CreditReportRepository creditReportRepository,
|
||||||
final CreditBureauTokenCommandFromApiJsonDeserializer fromApiJsonDeserializer,
|
final ThitsaWorksCreditBureauIntegrationWritePlatformService thitsaWorksCreditBureauIntegrationWritePlatformService) {
|
||||||
final CreditBureauLoanProductMappingRepository loanProductMappingRepository,
|
|
||||||
final CreditBureauRepository creditBureauRepository, final CreditReportRepository creditReportRepository,
|
|
||||||
final ThitsaWorksCreditBureauIntegrationWritePlatformService thitsaWorksCreditBureauIntegrationWritePlatformService,
|
|
||||||
final ThitsaWorksCreditBureauIntegrationWritePlatformServiceImpl thitsaWorksCreditBureauIntegrationWritePlatformServiceImpl) {
|
|
||||||
this.context = context;
|
this.context = context;
|
||||||
this.configDataRepository = configDataRepository;
|
|
||||||
this.creditBureauRepository = creditBureauRepository;
|
this.creditBureauRepository = creditBureauRepository;
|
||||||
this.creditReportRepository = creditReportRepository;
|
this.creditReportRepository = creditReportRepository;
|
||||||
this.thitsaWorksCreditBureauIntegrationWritePlatformService = thitsaWorksCreditBureauIntegrationWritePlatformService;
|
this.thitsaWorksCreditBureauIntegrationWritePlatformService = thitsaWorksCreditBureauIntegrationWritePlatformService;
|
||||||
this.thitsaWorksCreditBureauIntegrationWritePlatformServiceImpl = thitsaWorksCreditBureauIntegrationWritePlatformServiceImpl;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@Transactional
|
@Transactional
|
||||||
public CommandProcessingResult getCreditReport(JsonCommand command) {
|
public CommandProcessingResult getCreditReport(JsonCommand command) {
|
||||||
|
List<ApiParameterError> dataValidationErrors = new ArrayList<>();
|
||||||
|
DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource(CREDIT_BUREAU_INTEGRATION);
|
||||||
try {
|
try {
|
||||||
Long creditBureauID = command.longValueOfParameterNamed("creditBureauID");
|
Long creditBureauID = command.longValueOfParameterNamed("creditBureauID");
|
||||||
|
|
||||||
@@ -103,16 +91,16 @@ public class CreditReportWritePlatformServiceImpl implements CreditReportWritePl
|
|||||||
return new CommandProcessingResultBuilder().withCreditReport(reportMap).build();
|
return new CommandProcessingResultBuilder().withCreditReport(reportMap).build();
|
||||||
}
|
}
|
||||||
|
|
||||||
baseDataValidator.reset().failWithCode("creditBureau.has.not.been.Integrated");
|
baseDataValidator.reset().failWithCode(CREDIT_BUREAU_HAS_NOT_BEEN_INTEGRATED);
|
||||||
throw new PlatformApiDataValidationException("creditBureau.has.not.been.Integrated", "creditBureau.has.not.been.Integrated",
|
throw new PlatformApiDataValidationException(CREDIT_BUREAU_HAS_NOT_BEEN_INTEGRATED, CREDIT_BUREAU_HAS_NOT_BEEN_INTEGRATED,
|
||||||
dataValidationErrors);
|
dataValidationErrors);
|
||||||
|
|
||||||
} catch (final JpaSystemException | DataIntegrityViolationException dve) {
|
} catch (final JpaSystemException | DataIntegrityViolationException dve) {
|
||||||
handleTokenDataIntegrityIssues(command, dve.getMostSpecificCause(), dve);
|
handleTokenDataIntegrityIssues(dve.getMostSpecificCause());
|
||||||
return CommandProcessingResult.empty();
|
return CommandProcessingResult.empty();
|
||||||
} catch (final PersistenceException ee) {
|
} catch (final PersistenceException ee) {
|
||||||
Throwable throwable = ExceptionUtils.getRootCause(ee.getCause());
|
Throwable throwable = ExceptionUtils.getRootCause(ee.getCause());
|
||||||
handleTokenDataIntegrityIssues(command, throwable, ee);
|
handleTokenDataIntegrityIssues(throwable);
|
||||||
return CommandProcessingResult.empty();
|
return CommandProcessingResult.empty();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -121,7 +109,8 @@ public class CreditReportWritePlatformServiceImpl implements CreditReportWritePl
|
|||||||
@Override
|
@Override
|
||||||
@Transactional
|
@Transactional
|
||||||
public String addCreditReport(Long bureauId, File creditReport, FormDataContentDisposition fileDetail) {
|
public String addCreditReport(Long bureauId, File creditReport, FormDataContentDisposition fileDetail) {
|
||||||
|
List<ApiParameterError> dataValidationErrors = new ArrayList<>();
|
||||||
|
DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource(CREDIT_BUREAU_INTEGRATION);
|
||||||
String creditBureauName = getCreditBureauName(bureauId);
|
String creditBureauName = getCreditBureauName(bureauId);
|
||||||
String responseMessage = null;
|
String responseMessage = null;
|
||||||
|
|
||||||
@@ -130,8 +119,8 @@ public class CreditReportWritePlatformServiceImpl implements CreditReportWritePl
|
|||||||
fileDetail);
|
fileDetail);
|
||||||
} else {
|
} else {
|
||||||
|
|
||||||
baseDataValidator.reset().failWithCode("creditBureau.has.not.been.Integrated");
|
baseDataValidator.reset().failWithCode(CREDIT_BUREAU_HAS_NOT_BEEN_INTEGRATED);
|
||||||
throw new PlatformApiDataValidationException("creditBureau.has.not.been.Integrated", "creditBureau.has.not.been.Integrated",
|
throw new PlatformApiDataValidationException(CREDIT_BUREAU_HAS_NOT_BEEN_INTEGRATED, CREDIT_BUREAU_HAS_NOT_BEEN_INTEGRATED,
|
||||||
dataValidationErrors);
|
dataValidationErrors);
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -141,7 +130,8 @@ public class CreditReportWritePlatformServiceImpl implements CreditReportWritePl
|
|||||||
}
|
}
|
||||||
|
|
||||||
private String getCreditBureauName(Long creditBureauID) {
|
private String getCreditBureauName(Long creditBureauID) {
|
||||||
|
List<ApiParameterError> dataValidationErrors = new ArrayList<>();
|
||||||
|
DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource(CREDIT_BUREAU_INTEGRATION);
|
||||||
if (creditBureauID != null) {
|
if (creditBureauID != null) {
|
||||||
Optional<CreditBureau> creditBureau = this.creditBureauRepository.findById(creditBureauID);
|
Optional<CreditBureau> creditBureau = this.creditBureauRepository.findById(creditBureauID);
|
||||||
|
|
||||||
@@ -150,8 +140,8 @@ public class CreditReportWritePlatformServiceImpl implements CreditReportWritePl
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
baseDataValidator.reset().failWithCode("creditBureau.has.not.been.Integrated");
|
baseDataValidator.reset().failWithCode(CREDIT_BUREAU_HAS_NOT_BEEN_INTEGRATED);
|
||||||
throw new PlatformApiDataValidationException("creditBureau.has.not.been.Integrated", "creditBureau.has.not.been.Integrated",
|
throw new PlatformApiDataValidationException(CREDIT_BUREAU_HAS_NOT_BEEN_INTEGRATED, CREDIT_BUREAU_HAS_NOT_BEEN_INTEGRATED,
|
||||||
dataValidationErrors);
|
dataValidationErrors);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -186,11 +176,11 @@ public class CreditReportWritePlatformServiceImpl implements CreditReportWritePl
|
|||||||
|
|
||||||
return new CommandProcessingResultBuilder().withEntityId(creditReport.getId()).build();
|
return new CommandProcessingResultBuilder().withEntityId(creditReport.getId()).build();
|
||||||
} catch (final JpaSystemException | DataIntegrityViolationException dve) {
|
} catch (final JpaSystemException | DataIntegrityViolationException dve) {
|
||||||
handleTokenDataIntegrityIssues(command, dve.getMostSpecificCause(), dve);
|
handleTokenDataIntegrityIssues(dve.getMostSpecificCause());
|
||||||
return CommandProcessingResult.empty();
|
return CommandProcessingResult.empty();
|
||||||
} catch (final PersistenceException ee) {
|
} catch (final PersistenceException ee) {
|
||||||
Throwable throwable = ExceptionUtils.getRootCause(ee.getCause());
|
Throwable throwable = ExceptionUtils.getRootCause(ee.getCause());
|
||||||
handleTokenDataIntegrityIssues(command, throwable, ee);
|
handleTokenDataIntegrityIssues(throwable);
|
||||||
return CommandProcessingResult.empty();
|
return CommandProcessingResult.empty();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -219,7 +209,7 @@ public class CreditReportWritePlatformServiceImpl implements CreditReportWritePl
|
|||||||
return new CommandProcessingResultBuilder().withEntityId(creditReport.getId()).build();
|
return new CommandProcessingResultBuilder().withEntityId(creditReport.getId()).build();
|
||||||
}
|
}
|
||||||
|
|
||||||
private void handleTokenDataIntegrityIssues(final JsonCommand command, final Throwable realCause, final Exception dve) {
|
private void handleTokenDataIntegrityIssues(final Throwable realCause) {
|
||||||
|
|
||||||
throw new PlatformDataIntegrityException("error.msg.cund.unknown.data.integrity.issue",
|
throw new PlatformDataIntegrityException("error.msg.cund.unknown.data.integrity.issue",
|
||||||
"Unknown data integrity issue with resource: " + realCause.getMessage());
|
"Unknown data integrity issue with resource: " + realCause.getMessage());
|
||||||
|
|||||||
+24
-32
@@ -49,10 +49,8 @@ import org.apache.fineract.infrastructure.core.service.DateUtils;
|
|||||||
import org.apache.fineract.infrastructure.creditbureau.data.CreditBureauConfigurations;
|
import org.apache.fineract.infrastructure.creditbureau.data.CreditBureauConfigurations;
|
||||||
import org.apache.fineract.infrastructure.creditbureau.data.CreditBureauReportData;
|
import org.apache.fineract.infrastructure.creditbureau.data.CreditBureauReportData;
|
||||||
import org.apache.fineract.infrastructure.creditbureau.domain.CreditBureauConfiguration;
|
import org.apache.fineract.infrastructure.creditbureau.domain.CreditBureauConfiguration;
|
||||||
import org.apache.fineract.infrastructure.creditbureau.domain.CreditBureauConfigurationRepository;
|
|
||||||
import org.apache.fineract.infrastructure.creditbureau.domain.CreditBureauConfigurationRepositoryWrapper;
|
import org.apache.fineract.infrastructure.creditbureau.domain.CreditBureauConfigurationRepositoryWrapper;
|
||||||
import org.apache.fineract.infrastructure.creditbureau.domain.CreditBureauToken;
|
import org.apache.fineract.infrastructure.creditbureau.domain.CreditBureauToken;
|
||||||
import org.apache.fineract.infrastructure.creditbureau.domain.CreditReportRepository;
|
|
||||||
import org.apache.fineract.infrastructure.creditbureau.domain.TokenRepositoryWrapper;
|
import org.apache.fineract.infrastructure.creditbureau.domain.TokenRepositoryWrapper;
|
||||||
import org.apache.fineract.infrastructure.creditbureau.serialization.CreditBureauTokenCommandFromApiJsonDeserializer;
|
import org.apache.fineract.infrastructure.creditbureau.serialization.CreditBureauTokenCommandFromApiJsonDeserializer;
|
||||||
import org.apache.fineract.infrastructure.security.service.PlatformSecurityContext;
|
import org.apache.fineract.infrastructure.security.service.PlatformSecurityContext;
|
||||||
@@ -68,22 +66,18 @@ import org.springframework.transaction.annotation.Transactional;
|
|||||||
@Service
|
@Service
|
||||||
public class ThitsaWorksCreditBureauIntegrationWritePlatformServiceImpl implements ThitsaWorksCreditBureauIntegrationWritePlatformService {
|
public class ThitsaWorksCreditBureauIntegrationWritePlatformServiceImpl implements ThitsaWorksCreditBureauIntegrationWritePlatformService {
|
||||||
|
|
||||||
|
private static final Logger LOG = LoggerFactory.getLogger(ThitsaWorksCreditBureauIntegrationWritePlatformServiceImpl.class);
|
||||||
private final PlatformSecurityContext context;
|
private final PlatformSecurityContext context;
|
||||||
private final FromJsonHelper fromApiJsonHelper;
|
private final FromJsonHelper fromApiJsonHelper;
|
||||||
private final TokenRepositoryWrapper tokenRepositoryWrapper;
|
private final TokenRepositoryWrapper tokenRepositoryWrapper;
|
||||||
private final CreditBureauConfigurationRepositoryWrapper configDataRepository;
|
private final CreditBureauConfigurationRepositoryWrapper configDataRepository;
|
||||||
private final CreditBureauTokenCommandFromApiJsonDeserializer fromApiJsonDeserializer;
|
private final CreditBureauTokenCommandFromApiJsonDeserializer fromApiJsonDeserializer;
|
||||||
private final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
|
|
||||||
private final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors)
|
|
||||||
.resource("ThitsaWorksCreditBureauIntegration");
|
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
public ThitsaWorksCreditBureauIntegrationWritePlatformServiceImpl(final PlatformSecurityContext context,
|
public ThitsaWorksCreditBureauIntegrationWritePlatformServiceImpl(final PlatformSecurityContext context,
|
||||||
final FromJsonHelper fromApiJsonHelper, final TokenRepositoryWrapper tokenRepositoryWrapper,
|
final FromJsonHelper fromApiJsonHelper, final TokenRepositoryWrapper tokenRepositoryWrapper,
|
||||||
final CreditBureauConfigurationRepositoryWrapper configDataRepository,
|
final CreditBureauConfigurationRepositoryWrapper configDataRepository,
|
||||||
final CreditBureauConfigurationRepository configurationDataRepository,
|
final CreditBureauTokenCommandFromApiJsonDeserializer fromApiJsonDeserializer) {
|
||||||
final CreditBureauTokenCommandFromApiJsonDeserializer fromApiJsonDeserializer,
|
|
||||||
final CreditReportRepository creditReportRepository) {
|
|
||||||
this.context = context;
|
this.context = context;
|
||||||
this.tokenRepositoryWrapper = tokenRepositoryWrapper;
|
this.tokenRepositoryWrapper = tokenRepositoryWrapper;
|
||||||
this.configDataRepository = configDataRepository;
|
this.configDataRepository = configDataRepository;
|
||||||
@@ -91,8 +85,6 @@ public class ThitsaWorksCreditBureauIntegrationWritePlatformServiceImpl implemen
|
|||||||
this.fromApiJsonDeserializer = fromApiJsonDeserializer;
|
this.fromApiJsonDeserializer = fromApiJsonDeserializer;
|
||||||
}
|
}
|
||||||
|
|
||||||
private static final Logger LOG = LoggerFactory.getLogger(ThitsaWorksCreditBureauIntegrationWritePlatformServiceImpl.class);
|
|
||||||
|
|
||||||
@Transactional
|
@Transactional
|
||||||
@Override
|
@Override
|
||||||
@SuppressWarnings("deprecation")
|
@SuppressWarnings("deprecation")
|
||||||
@@ -171,8 +163,8 @@ public class ThitsaWorksCreditBureauIntegrationWritePlatformServiceImpl implemen
|
|||||||
|
|
||||||
if (process.equals("UploadCreditReport")) { // to show the Response on frontEnd
|
if (process.equals("UploadCreditReport")) { // to show the Response on frontEnd
|
||||||
JsonObject reportObject = JsonParser.parseString(reponseMessage).getAsJsonObject();
|
JsonObject reportObject = JsonParser.parseString(reponseMessage).getAsJsonObject();
|
||||||
String ResponseMessageJson = reportObject.get("ResponseMessage").getAsString();
|
String responseMessageJson = reportObject.get("ResponseMessage").getAsString();
|
||||||
this.handleAPIIntegrityIssues(ResponseMessageJson);
|
this.handleAPIIntegrityIssues(responseMessageJson);
|
||||||
}
|
}
|
||||||
|
|
||||||
return reponseMessage;
|
return reponseMessage;
|
||||||
@@ -249,7 +241,7 @@ public class ThitsaWorksCreditBureauIntegrationWritePlatformServiceImpl implemen
|
|||||||
JsonElement element = reportObject.get("Data");
|
JsonElement element = reportObject.get("Data");
|
||||||
|
|
||||||
if (!(element instanceof JsonNull)) { // NOTE : "element instanceof JsonNull" is for handling empty values (and
|
if (!(element instanceof JsonNull)) { // NOTE : "element instanceof JsonNull" is for handling empty values (and
|
||||||
// assigning null) while fetching data from results
|
// assigning null) while fetching data from results
|
||||||
jsonData = (JsonObject) element;
|
jsonData = (JsonObject) element;
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -265,9 +257,9 @@ public class ThitsaWorksCreditBureauIntegrationWritePlatformServiceImpl implemen
|
|||||||
borrowerInfo = gson.toJson(borrowerInfos);
|
borrowerInfo = gson.toJson(borrowerInfos);
|
||||||
}
|
}
|
||||||
|
|
||||||
String Name = borrowerInfos.get("Name").toString();
|
String name = borrowerInfos.get("Name").toString();
|
||||||
String Gender = borrowerInfos.get("Gender").toString();
|
String gender = borrowerInfos.get("Gender").toString();
|
||||||
String Address = borrowerInfos.get("Address").toString();
|
String address = borrowerInfos.get("Address").toString();
|
||||||
|
|
||||||
String creditScore = "CreditScore";
|
String creditScore = "CreditScore";
|
||||||
creditScore = getJsonObjectToString(creditScore, element, jsonData);
|
creditScore = getJsonObjectToString(creditScore, element, jsonData);
|
||||||
@@ -288,7 +280,7 @@ public class ThitsaWorksCreditBureauIntegrationWritePlatformServiceImpl implemen
|
|||||||
writeoffLoanStringArray = convertArrayintoStringArray(writeOffLoansArray);
|
writeoffLoanStringArray = convertArrayintoStringArray(writeOffLoansArray);
|
||||||
}
|
}
|
||||||
|
|
||||||
return CreditBureauReportData.instance(Name, Gender, Address, creditScore, borrowerInfo, activeLoanStringArray,
|
return CreditBureauReportData.instance(name, gender, address, creditScore, borrowerInfo, activeLoanStringArray,
|
||||||
writeoffLoanStringArray);
|
writeoffLoanStringArray);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -311,10 +303,8 @@ public class ThitsaWorksCreditBureauIntegrationWritePlatformServiceImpl implemen
|
|||||||
|
|
||||||
String process = "UploadCreditReport";
|
String process = "UploadCreditReport";
|
||||||
|
|
||||||
String responseMessage = this.okHttpConnectionMethod(userName, password, subscriptionKey, subscriptionId, url, token, creditReport,
|
return this.okHttpConnectionMethod(userName, password, subscriptionKey, subscriptionId, url, token, creditReport, fileDetail, 0L,
|
||||||
fileDetail, 0L, null, process);
|
null, process);
|
||||||
|
|
||||||
return responseMessage;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private String[] convertArrayintoStringArray(JsonArray jsonResult) {
|
private String[] convertArrayintoStringArray(JsonArray jsonResult) {
|
||||||
@@ -338,8 +328,8 @@ public class ThitsaWorksCreditBureauIntegrationWritePlatformServiceImpl implemen
|
|||||||
JsonElement element = reportObject.get("Data");
|
JsonElement element = reportObject.get("Data");
|
||||||
|
|
||||||
if (element.isJsonNull()) {
|
if (element.isJsonNull()) {
|
||||||
String ResponseMessage = reportObject.get("ResponseMessage").getAsString();
|
String responseMessage = reportObject.get("ResponseMessage").getAsString();
|
||||||
handleAPIIntegrityIssues(ResponseMessage);
|
handleAPIIntegrityIssues(responseMessage);
|
||||||
}
|
}
|
||||||
|
|
||||||
// to fetch the Unique ID from Result
|
// to fetch the Unique ID from Result
|
||||||
@@ -354,16 +344,16 @@ public class ThitsaWorksCreditBureauIntegrationWritePlatformServiceImpl implemen
|
|||||||
JsonObject jobject = dataArray.get(0).getAsJsonObject();
|
JsonObject jobject = dataArray.get(0).getAsJsonObject();
|
||||||
|
|
||||||
String uniqueIdString = jobject.get("UniqueID").toString();
|
String uniqueIdString = jobject.get("UniqueID").toString();
|
||||||
String TrimUniqueId = uniqueIdString.substring(1, uniqueIdString.length() - 1);
|
String trimUniqueId = uniqueIdString.substring(1, uniqueIdString.length() - 1);
|
||||||
|
|
||||||
uniqueID = Long.parseLong(TrimUniqueId);
|
uniqueID = Long.parseLong(trimUniqueId);
|
||||||
|
|
||||||
} else if (dataArray.size() == 0) {
|
} else if (dataArray.size() == 0) {
|
||||||
String ResponseMessage = reportObject.get("ResponseMessage").getAsString();
|
String responseMessage = reportObject.get("ResponseMessage").getAsString();
|
||||||
handleAPIIntegrityIssues(ResponseMessage);
|
handleAPIIntegrityIssues(responseMessage);
|
||||||
} else {
|
} else {
|
||||||
String nrc = null;
|
String nrc;
|
||||||
List<String> arrlist = new ArrayList<String>();
|
List<String> arrlist = new ArrayList<>();
|
||||||
|
|
||||||
for (int i = 0; i < dataArray.size(); ++i) {
|
for (int i = 0; i < dataArray.size(); ++i) {
|
||||||
JsonObject data = dataArray.get(i).getAsJsonObject();
|
JsonObject data = dataArray.get(i).getAsJsonObject();
|
||||||
@@ -377,8 +367,8 @@ public class ThitsaWorksCreditBureauIntegrationWritePlatformServiceImpl implemen
|
|||||||
}
|
}
|
||||||
|
|
||||||
} catch (IndexOutOfBoundsException e) {
|
} catch (IndexOutOfBoundsException e) {
|
||||||
String ResponseMessage = jsonObject.get("ResponseMessage").getAsString();
|
String responseMessage = jsonObject.get("ResponseMessage").getAsString();
|
||||||
handleAPIIntegrityIssues(ResponseMessage);
|
handleAPIIntegrityIssues(responseMessage);
|
||||||
}
|
}
|
||||||
return uniqueID;
|
return uniqueID;
|
||||||
}
|
}
|
||||||
@@ -471,7 +461,9 @@ public class ThitsaWorksCreditBureauIntegrationWritePlatformServiceImpl implemen
|
|||||||
}
|
}
|
||||||
|
|
||||||
public String getCreditBureauConfiguration(Integer creditBureauId, String configurationParameterName) {
|
public String getCreditBureauConfiguration(Integer creditBureauId, String configurationParameterName) {
|
||||||
|
List<ApiParameterError> dataValidationErrors = new ArrayList<>();
|
||||||
|
DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors)
|
||||||
|
.resource("ThitsaWorksCreditBureauIntegration");
|
||||||
String creditBureauConfigurationValue = null;
|
String creditBureauConfigurationValue = null;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
|||||||
+9
-9
@@ -63,10 +63,10 @@ import org.springframework.stereotype.Component;
|
|||||||
@Tag(name = "Reports", description = "Non-core reports can be added, updated and deleted.")
|
@Tag(name = "Reports", description = "Non-core reports can be added, updated and deleted.")
|
||||||
public class ReportsApiResource {
|
public class ReportsApiResource {
|
||||||
|
|
||||||
private final Set<String> responseDataParameters = new HashSet<>(Arrays.asList("id", "reportName", "reportType", "reportSubType",
|
private static final Set<String> RESPONSE_DATA_PARAMETERS = new HashSet<>(Arrays.asList("id", "reportName", "reportType",
|
||||||
"reportCategory", "description", "reportSql", "coreReport", "useReport", "reportParameters"));
|
"reportSubType", "reportCategory", "description", "reportSql", "coreReport", "useReport", "reportParameters"));
|
||||||
|
|
||||||
private final String resourceNameForPermissions = "REPORT";
|
private static final String RESOURCE_NAME_FOR_PERMISSIONS = "REPORT";
|
||||||
private final PlatformSecurityContext context;
|
private final PlatformSecurityContext context;
|
||||||
private final ToApiJsonSerializer<ReportData> toApiJsonSerializer;
|
private final ToApiJsonSerializer<ReportData> toApiJsonSerializer;
|
||||||
private final ReadReportingService readReportingService;
|
private final ReadReportingService readReportingService;
|
||||||
@@ -95,12 +95,12 @@ public class ReportsApiResource {
|
|||||||
@ApiResponse(responseCode = "200", description = "OK", content = @Content(array = @ArraySchema(schema = @Schema(implementation = ReportsApiResourceSwagger.GetReportsResponse.class))))
|
@ApiResponse(responseCode = "200", description = "OK", content = @Content(array = @ArraySchema(schema = @Schema(implementation = ReportsApiResourceSwagger.GetReportsResponse.class))))
|
||||||
public String retrieveReportList(@Context final UriInfo uriInfo) {
|
public String retrieveReportList(@Context final UriInfo uriInfo) {
|
||||||
|
|
||||||
this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions);
|
this.context.authenticatedUser().validateHasReadPermission(RESOURCE_NAME_FOR_PERMISSIONS);
|
||||||
|
|
||||||
final Collection<ReportData> result = this.readReportingService.retrieveReportList();
|
final Collection<ReportData> result = this.readReportingService.retrieveReportList();
|
||||||
|
|
||||||
final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters());
|
final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters());
|
||||||
return this.toApiJsonSerializer.serialize(settings, result, this.responseDataParameters);
|
return this.toApiJsonSerializer.serialize(settings, result, RESPONSE_DATA_PARAMETERS);
|
||||||
}
|
}
|
||||||
|
|
||||||
@GET
|
@GET
|
||||||
@@ -113,7 +113,7 @@ public class ReportsApiResource {
|
|||||||
@ApiResponse(responseCode = "200", description = "OK", content = @Content(schema = @Schema(implementation = ReportsApiResourceSwagger.GetReportsResponse.class))) })
|
@ApiResponse(responseCode = "200", description = "OK", content = @Content(schema = @Schema(implementation = ReportsApiResourceSwagger.GetReportsResponse.class))) })
|
||||||
public String retrieveReport(@PathParam("id") @Parameter(description = "id") final Long id, @Context final UriInfo uriInfo) {
|
public String retrieveReport(@PathParam("id") @Parameter(description = "id") final Long id, @Context final UriInfo uriInfo) {
|
||||||
|
|
||||||
this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions);
|
this.context.authenticatedUser().validateHasReadPermission(RESOURCE_NAME_FOR_PERMISSIONS);
|
||||||
|
|
||||||
final ReportData result = this.readReportingService.retrieveReport(id);
|
final ReportData result = this.readReportingService.retrieveReport(id);
|
||||||
|
|
||||||
@@ -123,7 +123,7 @@ public class ReportsApiResource {
|
|||||||
result.appendedTemplate(this.readReportingService.getAllowedParameters(),
|
result.appendedTemplate(this.readReportingService.getAllowedParameters(),
|
||||||
this.reportingProcessServiceProvider.findAllReportingTypes());
|
this.reportingProcessServiceProvider.findAllReportingTypes());
|
||||||
}
|
}
|
||||||
return this.toApiJsonSerializer.serialize(settings, result, this.responseDataParameters);
|
return this.toApiJsonSerializer.serialize(settings, result, RESPONSE_DATA_PARAMETERS);
|
||||||
}
|
}
|
||||||
|
|
||||||
@GET
|
@GET
|
||||||
@@ -136,14 +136,14 @@ public class ReportsApiResource {
|
|||||||
@ApiResponse(responseCode = "200", description = "OK", content = @Content(schema = @Schema(implementation = ReportsApiResourceSwagger.GetReportsTemplateResponse.class))) })
|
@ApiResponse(responseCode = "200", description = "OK", content = @Content(schema = @Schema(implementation = ReportsApiResourceSwagger.GetReportsTemplateResponse.class))) })
|
||||||
public String retrieveOfficeTemplate(@Context final UriInfo uriInfo) {
|
public String retrieveOfficeTemplate(@Context final UriInfo uriInfo) {
|
||||||
|
|
||||||
this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions);
|
this.context.authenticatedUser().validateHasReadPermission(RESOURCE_NAME_FOR_PERMISSIONS);
|
||||||
|
|
||||||
final ReportData result = new ReportData();
|
final ReportData result = new ReportData();
|
||||||
result.appendedTemplate(this.readReportingService.getAllowedParameters(),
|
result.appendedTemplate(this.readReportingService.getAllowedParameters(),
|
||||||
this.reportingProcessServiceProvider.findAllReportingTypes());
|
this.reportingProcessServiceProvider.findAllReportingTypes());
|
||||||
|
|
||||||
final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters());
|
final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters());
|
||||||
return this.toApiJsonSerializer.serialize(settings, result, this.responseDataParameters);
|
return this.toApiJsonSerializer.serialize(settings, result, RESPONSE_DATA_PARAMETERS);
|
||||||
}
|
}
|
||||||
|
|
||||||
@POST
|
@POST
|
||||||
|
|||||||
+2
-2
@@ -39,7 +39,7 @@ import org.springframework.stereotype.Component;
|
|||||||
public class DataTableValidator {
|
public class DataTableValidator {
|
||||||
|
|
||||||
private final FromJsonHelper fromApiJsonHelper;
|
private final FromJsonHelper fromApiJsonHelper;
|
||||||
private final Set<String> registerParams = new HashSet<>(
|
private static final Set<String> SUPPORTED_PARAMETERS = new HashSet<>(
|
||||||
Arrays.asList(DataTableApiConstant.categoryParamName, DataTableApiConstant.localParamName));
|
Arrays.asList(DataTableApiConstant.categoryParamName, DataTableApiConstant.localParamName));
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
@@ -50,7 +50,7 @@ public class DataTableValidator {
|
|||||||
public void validateDataTableRegistration(final String json) {
|
public void validateDataTableRegistration(final String json) {
|
||||||
|
|
||||||
final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType();
|
final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType();
|
||||||
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, registerParams);
|
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, SUPPORTED_PARAMETERS);
|
||||||
|
|
||||||
final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
|
final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
|
||||||
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors)
|
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors)
|
||||||
|
|||||||
+2
-2
@@ -36,7 +36,7 @@ public final class ReportCommandFromApiJsonDeserializer {
|
|||||||
/**
|
/**
|
||||||
* The parameters supported for this command.
|
* The parameters supported for this command.
|
||||||
*/
|
*/
|
||||||
private final Set<String> supportedParameters = new HashSet<>(Arrays.asList("reportName", "reportType", "reportSubType",
|
private static final Set<String> SUPPORTED_PARAMETERS = new HashSet<>(Arrays.asList("reportName", "reportType", "reportSubType",
|
||||||
"reportCategory", "description", "reportSql", "useReport", "reportParameters"));
|
"reportCategory", "description", "reportSql", "useReport", "reportParameters"));
|
||||||
|
|
||||||
private final FromJsonHelper fromApiJsonHelper;
|
private final FromJsonHelper fromApiJsonHelper;
|
||||||
@@ -53,6 +53,6 @@ public final class ReportCommandFromApiJsonDeserializer {
|
|||||||
|
|
||||||
final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType();
|
final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType();
|
||||||
|
|
||||||
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParameters);
|
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, SUPPORTED_PARAMETERS);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+25
-18
@@ -40,12 +40,17 @@ import org.springframework.stereotype.Component;
|
|||||||
@Component
|
@Component
|
||||||
public final class EntityDatatableChecksDataValidator {
|
public final class EntityDatatableChecksDataValidator {
|
||||||
|
|
||||||
|
public static final String ENTITY = "entity";
|
||||||
|
public static final String DATATABLE_NAME = "datatableName";
|
||||||
|
public static final String STATUS = "status";
|
||||||
|
public static final String SYSTEM_DEFINED = "systemDefined";
|
||||||
|
public static final String PRODUCT_ID = "productId";
|
||||||
|
public static final String ENTITY_DATATABLE_CHECKS = "entityDatatableChecks";
|
||||||
/**
|
/**
|
||||||
* The parameters supported for this command.
|
* The parameters supported for this command.
|
||||||
*/
|
*/
|
||||||
private final Set<String> supportedParameters = new HashSet<>(
|
private static final Set<String> SUPPORTED_PARAMETERS = new HashSet<>(
|
||||||
Arrays.asList("entity", "datatableName", "status", "systemDefined", "productId"));
|
Arrays.asList(ENTITY, DATATABLE_NAME, STATUS, SYSTEM_DEFINED, PRODUCT_ID));
|
||||||
|
|
||||||
private final FromJsonHelper fromApiJsonHelper;
|
private final FromJsonHelper fromApiJsonHelper;
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
@@ -58,33 +63,35 @@ public final class EntityDatatableChecksDataValidator {
|
|||||||
throw new InvalidJsonException();
|
throw new InvalidJsonException();
|
||||||
}
|
}
|
||||||
|
|
||||||
final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType();
|
final Type typeOfMap = new TypeToken<Map<String, Object>>() {
|
||||||
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParameters);
|
|
||||||
|
}.getType();
|
||||||
|
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, SUPPORTED_PARAMETERS);
|
||||||
|
|
||||||
final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
|
final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
|
||||||
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("entityDatatableChecks");
|
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource(ENTITY_DATATABLE_CHECKS);
|
||||||
|
|
||||||
final JsonElement element = this.fromApiJsonHelper.parse(json);
|
final JsonElement element = this.fromApiJsonHelper.parse(json);
|
||||||
|
|
||||||
final String entity = this.fromApiJsonHelper.extractStringNamed("entity", element);
|
final String entity = this.fromApiJsonHelper.extractStringNamed(ENTITY, element);
|
||||||
baseDataValidator.reset().parameter("entity").value(entity).notBlank().isOneOfTheseStringValues(EntityTables.getEntitiesList());
|
baseDataValidator.reset().parameter(ENTITY).value(entity).notBlank().isOneOfTheseStringValues(EntityTables.getEntitiesList());
|
||||||
|
|
||||||
final Integer status = this.fromApiJsonHelper.extractIntegerSansLocaleNamed("status", element);
|
final Integer status = this.fromApiJsonHelper.extractIntegerSansLocaleNamed(STATUS, element);
|
||||||
final Object[] entityTablesStatuses = EntityTables.getStatus(entity).toArray();
|
final Object[] entityTablesStatuses = EntityTables.getStatus(entity).toArray();
|
||||||
|
|
||||||
baseDataValidator.reset().parameter("status").value(status).isOneOfTheseValues(entityTablesStatuses);
|
baseDataValidator.reset().parameter(STATUS).value(status).isOneOfTheseValues(entityTablesStatuses);
|
||||||
|
|
||||||
final String datatableName = this.fromApiJsonHelper.extractStringNamed("datatableName", element);
|
final String datatableName = this.fromApiJsonHelper.extractStringNamed(DATATABLE_NAME, element);
|
||||||
baseDataValidator.reset().parameter("datatableName").value(datatableName).notBlank();
|
baseDataValidator.reset().parameter(DATATABLE_NAME).value(datatableName).notBlank();
|
||||||
|
|
||||||
if (this.fromApiJsonHelper.parameterExists("systemDefined", element)) {
|
if (this.fromApiJsonHelper.parameterExists(SYSTEM_DEFINED, element)) {
|
||||||
final String systemDefined = this.fromApiJsonHelper.extractStringNamed("systemDefined", element);
|
final String systemDefined = this.fromApiJsonHelper.extractStringNamed(SYSTEM_DEFINED, element);
|
||||||
baseDataValidator.reset().parameter("systemDefined").value(systemDefined).validateForBooleanValue();
|
baseDataValidator.reset().parameter(SYSTEM_DEFINED).value(systemDefined).validateForBooleanValue();
|
||||||
}
|
}
|
||||||
|
|
||||||
if (this.fromApiJsonHelper.parameterExists("productId", element)) {
|
if (this.fromApiJsonHelper.parameterExists(PRODUCT_ID, element)) {
|
||||||
final long productId = this.fromApiJsonHelper.extractLongNamed("productId", element);
|
final long productId = this.fromApiJsonHelper.extractLongNamed(PRODUCT_ID, element);
|
||||||
baseDataValidator.reset().parameter("productId").value(productId).integerZeroOrGreater();
|
baseDataValidator.reset().parameter(PRODUCT_ID).value(productId).integerZeroOrGreater();
|
||||||
}
|
}
|
||||||
|
|
||||||
throwExceptionIfValidationWarningsExist(dataValidationErrors);
|
throwExceptionIfValidationWarningsExist(dataValidationErrors);
|
||||||
|
|||||||
+7
-7
@@ -71,10 +71,10 @@ import org.springframework.stereotype.Component;
|
|||||||
+ "Groups: URL Pattern as groups")
|
+ "Groups: URL Pattern as groups")
|
||||||
public class DocumentManagementApiResource {
|
public class DocumentManagementApiResource {
|
||||||
|
|
||||||
private final Set<String> responseDataParameters = new HashSet<>(
|
private static final Set<String> RESPONSE_DATA_PARAMETERS = new HashSet<>(
|
||||||
Arrays.asList("id", "parentEntityType", "parentEntityId", "name", "fileName", "size", "type", "description"));
|
Arrays.asList("id", "parentEntityType", "parentEntityId", "name", "fileName", "size", "type", "description"));
|
||||||
|
|
||||||
private final String systemEntityType = "DOCUMENT";
|
private static final String SYSTEM_ENTITY_TYPE = "DOCUMENT";
|
||||||
|
|
||||||
private final PlatformSecurityContext context;
|
private final PlatformSecurityContext context;
|
||||||
private final DocumentReadPlatformService documentReadPlatformService;
|
private final DocumentReadPlatformService documentReadPlatformService;
|
||||||
@@ -107,12 +107,12 @@ public class DocumentManagementApiResource {
|
|||||||
@PathParam("entityType") @Parameter(description = "entityType") final String entityType,
|
@PathParam("entityType") @Parameter(description = "entityType") final String entityType,
|
||||||
@PathParam("entityId") @Parameter(description = "entityId") final Long entityId) {
|
@PathParam("entityId") @Parameter(description = "entityId") final Long entityId) {
|
||||||
|
|
||||||
this.context.authenticatedUser().validateHasReadPermission(this.systemEntityType);
|
this.context.authenticatedUser().validateHasReadPermission(SYSTEM_ENTITY_TYPE);
|
||||||
|
|
||||||
final Collection<DocumentData> documentDatas = this.documentReadPlatformService.retrieveAllDocuments(entityType, entityId);
|
final Collection<DocumentData> documentDatas = this.documentReadPlatformService.retrieveAllDocuments(entityType, entityId);
|
||||||
|
|
||||||
final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters());
|
final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters());
|
||||||
return this.toApiJsonSerializer.serialize(settings, documentDatas, this.responseDataParameters);
|
return this.toApiJsonSerializer.serialize(settings, documentDatas, RESPONSE_DATA_PARAMETERS);
|
||||||
}
|
}
|
||||||
|
|
||||||
@POST
|
@POST
|
||||||
@@ -202,12 +202,12 @@ public class DocumentManagementApiResource {
|
|||||||
@PathParam("entityId") @Parameter(description = "entityId") final Long entityId,
|
@PathParam("entityId") @Parameter(description = "entityId") final Long entityId,
|
||||||
@PathParam("documentId") @Parameter(description = "documentId") final Long documentId, @Context final UriInfo uriInfo) {
|
@PathParam("documentId") @Parameter(description = "documentId") final Long documentId, @Context final UriInfo uriInfo) {
|
||||||
|
|
||||||
this.context.authenticatedUser().validateHasReadPermission(this.systemEntityType);
|
this.context.authenticatedUser().validateHasReadPermission(SYSTEM_ENTITY_TYPE);
|
||||||
|
|
||||||
final DocumentData documentData = this.documentReadPlatformService.retrieveDocument(entityType, entityId, documentId);
|
final DocumentData documentData = this.documentReadPlatformService.retrieveDocument(entityType, entityId, documentId);
|
||||||
|
|
||||||
final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters());
|
final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters());
|
||||||
return this.toApiJsonSerializer.serialize(settings, documentData, this.responseDataParameters);
|
return this.toApiJsonSerializer.serialize(settings, documentData, RESPONSE_DATA_PARAMETERS);
|
||||||
}
|
}
|
||||||
|
|
||||||
@GET
|
@GET
|
||||||
@@ -221,7 +221,7 @@ public class DocumentManagementApiResource {
|
|||||||
@PathParam("entityId") @Parameter(description = "entityId") final Long entityId,
|
@PathParam("entityId") @Parameter(description = "entityId") final Long entityId,
|
||||||
@PathParam("documentId") @Parameter(description = "documentId") final Long documentId) {
|
@PathParam("documentId") @Parameter(description = "documentId") final Long documentId) {
|
||||||
|
|
||||||
this.context.authenticatedUser().validateHasReadPermission(this.systemEntityType);
|
this.context.authenticatedUser().validateHasReadPermission(SYSTEM_ENTITY_TYPE);
|
||||||
final FileData fileData = this.documentReadPlatformService.retrieveFileData(entityType, entityId, documentId);
|
final FileData fileData = this.documentReadPlatformService.retrieveFileData(entityType, entityId, documentId);
|
||||||
return ContentResources.fileDataToResponse(fileData, "attachment");
|
return ContentResources.fileDataToResponse(fileData, "attachment");
|
||||||
}
|
}
|
||||||
|
|||||||
+4
-9
@@ -23,21 +23,16 @@ import static org.apache.fineract.infrastructure.hooks.api.HookApiConstants.http
|
|||||||
import static org.apache.fineract.infrastructure.hooks.api.HookApiConstants.smsTemplateName;
|
import static org.apache.fineract.infrastructure.hooks.api.HookApiConstants.smsTemplateName;
|
||||||
import static org.apache.fineract.infrastructure.hooks.api.HookApiConstants.webTemplateName;
|
import static org.apache.fineract.infrastructure.hooks.api.HookApiConstants.webTemplateName;
|
||||||
|
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
import org.apache.fineract.infrastructure.hooks.domain.Hook;
|
import org.apache.fineract.infrastructure.hooks.domain.Hook;
|
||||||
import org.springframework.beans.BeansException;
|
|
||||||
import org.springframework.context.ApplicationContext;
|
import org.springframework.context.ApplicationContext;
|
||||||
import org.springframework.context.ApplicationContextAware;
|
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
@Service
|
@Service
|
||||||
public class HookProcessorProvider implements ApplicationContextAware {
|
@RequiredArgsConstructor
|
||||||
|
public class HookProcessorProvider {
|
||||||
|
|
||||||
private ApplicationContext applicationContext;
|
private final ApplicationContext applicationContext;
|
||||||
|
|
||||||
@Override
|
|
||||||
public void setApplicationContext(final ApplicationContext applicationContext) throws BeansException {
|
|
||||||
this.applicationContext = applicationContext;
|
|
||||||
}
|
|
||||||
|
|
||||||
public HookProcessor getProcessor(final Hook hook) {
|
public HookProcessor getProcessor(final Hook hook) {
|
||||||
HookProcessor processor;
|
HookProcessor processor;
|
||||||
|
|||||||
+3
-7
@@ -20,8 +20,6 @@ package org.apache.fineract.infrastructure.hooks.processor;
|
|||||||
|
|
||||||
import static org.apache.fineract.infrastructure.hooks.api.HookApiConstants.apiKeyName;
|
import static org.apache.fineract.infrastructure.hooks.api.HookApiConstants.apiKeyName;
|
||||||
|
|
||||||
import com.fasterxml.jackson.core.JsonParseException;
|
|
||||||
import com.fasterxml.jackson.databind.JsonMappingException;
|
|
||||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
import com.google.gson.Gson;
|
import com.google.gson.Gson;
|
||||||
import com.google.gson.JsonObject;
|
import com.google.gson.JsonObject;
|
||||||
@@ -80,11 +78,11 @@ public class TwilioHookProcessor implements HookProcessor {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (apiKey != null && !apiKey.equals("")) {
|
if (apiKey != null && !apiKey.equals("")) {
|
||||||
JsonObject json = null;
|
JsonObject json;
|
||||||
if (hook.getUgdTemplate() != null) {
|
if (hook.getUgdTemplate() != null) {
|
||||||
entityName = "sms";
|
entityName = "sms";
|
||||||
actionName = "send";
|
actionName = "send";
|
||||||
json = processUgdTemplate(payload, hook, context.getAuthTokenContext());
|
json = processUgdTemplate(payload, hook);
|
||||||
if (json == null) {
|
if (json == null) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -96,8 +94,7 @@ public class TwilioHookProcessor implements HookProcessor {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private JsonObject processUgdTemplate(final String payload, final Hook hook, final String authToken)
|
private JsonObject processUgdTemplate(final String payload, final Hook hook) throws IOException {
|
||||||
throws JsonParseException, JsonMappingException, IOException {
|
|
||||||
JsonObject json = null;
|
JsonObject json = null;
|
||||||
@SuppressWarnings("unchecked")
|
@SuppressWarnings("unchecked")
|
||||||
final HashMap<String, Object> map = new ObjectMapper().readValue(payload, HashMap.class);
|
final HashMap<String, Object> map = new ObjectMapper().readValue(payload, HashMap.class);
|
||||||
@@ -107,7 +104,6 @@ public class TwilioHookProcessor implements HookProcessor {
|
|||||||
final Client client = this.clientRepositoryWrapper.findOneWithNotFoundDetection(clientId);
|
final Client client = this.clientRepositoryWrapper.findOneWithNotFoundDetection(clientId);
|
||||||
final String mobileNo = client.mobileNo();
|
final String mobileNo = client.mobileNo();
|
||||||
if (mobileNo != null && !mobileNo.isEmpty()) {
|
if (mobileNo != null && !mobileNo.isEmpty()) {
|
||||||
this.templateMergeService.setAuthToken(authToken);
|
|
||||||
final String compiledMessage = this.templateMergeService.compile(hook.getUgdTemplate(), map).replace("<p>", "")
|
final String compiledMessage = this.templateMergeService.compile(hook.getUgdTemplate(), map).replace("<p>", "")
|
||||||
.replace("</p>", "");
|
.replace("</p>", "");
|
||||||
final Map<String, String> jsonMap = new HashMap<>();
|
final Map<String, String> jsonMap = new HashMap<>();
|
||||||
|
|||||||
+16
-15
@@ -45,6 +45,7 @@ import org.springframework.batch.core.Job;
|
|||||||
import org.springframework.batch.core.configuration.JobLocator;
|
import org.springframework.batch.core.configuration.JobLocator;
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
import org.springframework.context.ApplicationListener;
|
import org.springframework.context.ApplicationListener;
|
||||||
|
import org.springframework.context.annotation.Lazy;
|
||||||
import org.springframework.context.event.ContextClosedEvent;
|
import org.springframework.context.event.ContextClosedEvent;
|
||||||
import org.springframework.scheduling.quartz.CronTriggerFactoryBean;
|
import org.springframework.scheduling.quartz.CronTriggerFactoryBean;
|
||||||
import org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean;
|
import org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean;
|
||||||
@@ -68,10 +69,11 @@ public class JobRegisterServiceImpl implements JobRegisterService, ApplicationLi
|
|||||||
@Autowired
|
@Autowired
|
||||||
private SchedulerTriggerListener globalSchedulerTriggerListener;
|
private SchedulerTriggerListener globalSchedulerTriggerListener;
|
||||||
|
|
||||||
private final HashMap<String, Scheduler> schedulers = new HashMap<>(4);
|
private static final HashMap<String, Scheduler> SCHEDULERS = new HashMap<>(4);
|
||||||
|
|
||||||
// This cannot be injected as Autowired due to circular dependency
|
@Autowired
|
||||||
private SchedulerStopListener schedulerStopListener = new SchedulerStopListener(this);
|
@Lazy
|
||||||
|
private SchedulerStopListener schedulerStopListener;
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
private FineractProperties fineractProperties;
|
private FineractProperties fineractProperties;
|
||||||
@@ -93,14 +95,14 @@ public class JobRegisterServiceImpl implements JobRegisterService, ApplicationLi
|
|||||||
jobDataMap.put(SchedulerServiceConstants.TRIGGER_TYPE_REFERENCE, triggerType);
|
jobDataMap.put(SchedulerServiceConstants.TRIGGER_TYPE_REFERENCE, triggerType);
|
||||||
jobDataMap.put(SchedulerServiceConstants.TENANT_IDENTIFIER, ThreadLocalContextUtil.getTenant().getTenantIdentifier());
|
jobDataMap.put(SchedulerServiceConstants.TENANT_IDENTIFIER, ThreadLocalContextUtil.getTenant().getTenantIdentifier());
|
||||||
final String schedulerName = getSchedulerName(scheduledJobDetail);
|
final String schedulerName = getSchedulerName(scheduledJobDetail);
|
||||||
final Scheduler scheduler = this.schedulers.get(schedulerName);
|
final Scheduler scheduler = SCHEDULERS.get(schedulerName);
|
||||||
final JobDetail jobDetail = createJobDetail(scheduledJobDetail);
|
final JobDetail jobDetail = createJobDetail(scheduledJobDetail);
|
||||||
JobKey jobKey = jobDetail.getKey();
|
JobKey jobKey = jobDetail.getKey();
|
||||||
if (scheduler == null || !scheduler.checkExists(jobKey)) {
|
if (scheduler == null || !scheduler.checkExists(jobKey)) {
|
||||||
final String tempSchedulerName = "temp" + scheduledJobDetail.getId();
|
final String tempSchedulerName = "temp" + scheduledJobDetail.getId();
|
||||||
final Scheduler tempScheduler = createScheduler(tempSchedulerName, 1, schedulerJobListener, schedulerStopListener);
|
final Scheduler tempScheduler = createScheduler(tempSchedulerName, 1, schedulerJobListener, schedulerStopListener);
|
||||||
jobDataMap.put(SchedulerServiceConstants.SCHEDULER_NAME, tempSchedulerName);
|
jobDataMap.put(SchedulerServiceConstants.SCHEDULER_NAME, tempSchedulerName);
|
||||||
schedulers.put(tempSchedulerName, tempScheduler);
|
SCHEDULERS.put(tempSchedulerName, tempScheduler);
|
||||||
tempScheduler.addJob(jobDetail, true);
|
tempScheduler.addJob(jobDetail, true);
|
||||||
tempScheduler.triggerJob(jobKey, jobDataMap);
|
tempScheduler.triggerJob(jobKey, jobDataMap);
|
||||||
} else {
|
} else {
|
||||||
@@ -120,13 +122,13 @@ public class JobRegisterServiceImpl implements JobRegisterService, ApplicationLi
|
|||||||
final String jobIdentity = scheduledJobDetail.getJobKey();
|
final String jobIdentity = scheduledJobDetail.getJobKey();
|
||||||
final JobKey jobKey = constructJobKey(jobIdentity);
|
final JobKey jobKey = constructJobKey(jobIdentity);
|
||||||
final String schedulername = getSchedulerName(scheduledJobDetail);
|
final String schedulername = getSchedulerName(scheduledJobDetail);
|
||||||
final Scheduler scheduler = this.schedulers.get(schedulername);
|
final Scheduler scheduler = SCHEDULERS.get(schedulername);
|
||||||
if (scheduler != null) {
|
if (scheduler != null) {
|
||||||
scheduler.deleteJob(jobKey);
|
scheduler.deleteJob(jobKey);
|
||||||
}
|
}
|
||||||
scheduleJob(scheduledJobDetail);
|
scheduleJob(scheduledJobDetail);
|
||||||
this.schedularWritePlatformService.saveOrUpdate(scheduledJobDetail);
|
this.schedularWritePlatformService.saveOrUpdate(scheduledJobDetail);
|
||||||
} catch (final Throwable throwable) {
|
} catch (final Exception throwable) {
|
||||||
final String stackTrace = getStackTraceAsString(throwable);
|
final String stackTrace = getStackTraceAsString(throwable);
|
||||||
scheduledJobDetail.setErrorLog(stackTrace);
|
scheduledJobDetail.setErrorLog(stackTrace);
|
||||||
this.schedularWritePlatformService.saveOrUpdate(scheduledJobDetail);
|
this.schedularWritePlatformService.saveOrUpdate(scheduledJobDetail);
|
||||||
@@ -158,7 +160,7 @@ public class JobRegisterServiceImpl implements JobRegisterService, ApplicationLi
|
|||||||
jobDetail.setMismatchedJob(false);
|
jobDetail.setMismatchedJob(false);
|
||||||
}
|
}
|
||||||
final String schedulerName = getSchedulerName(jobDetail);
|
final String schedulerName = getSchedulerName(jobDetail);
|
||||||
final Scheduler scheduler = this.schedulers.get(schedulerName);
|
final Scheduler scheduler = SCHEDULERS.get(schedulerName);
|
||||||
if (scheduler != null) {
|
if (scheduler != null) {
|
||||||
final String key = jobDetail.getJobKey();
|
final String key = jobDetail.getJobKey();
|
||||||
final JobKey jobKey = constructJobKey(key);
|
final JobKey jobKey = constructJobKey(key);
|
||||||
@@ -244,7 +246,7 @@ public class JobRegisterServiceImpl implements JobRegisterService, ApplicationLi
|
|||||||
scheduler.scheduleJob(jobDetail, trigger);
|
scheduler.scheduleJob(jobDetail, trigger);
|
||||||
scheduledJobDetails.setNextRunTime(trigger.getNextFireTime());
|
scheduledJobDetails.setNextRunTime(trigger.getNextFireTime());
|
||||||
scheduledJobDetails.setErrorLog(null);
|
scheduledJobDetails.setErrorLog(null);
|
||||||
} catch (final Throwable throwable) {
|
} catch (final Exception throwable) {
|
||||||
scheduledJobDetails.setNextRunTime(null);
|
scheduledJobDetails.setNextRunTime(null);
|
||||||
final String stackTrace = getStackTraceAsString(throwable);
|
final String stackTrace = getStackTraceAsString(throwable);
|
||||||
scheduledJobDetails.setErrorLog(stackTrace);
|
scheduledJobDetails.setErrorLog(stackTrace);
|
||||||
@@ -255,7 +257,7 @@ public class JobRegisterServiceImpl implements JobRegisterService, ApplicationLi
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void stopAllSchedulers() {
|
public void stopAllSchedulers() {
|
||||||
for (Scheduler scheduler : this.schedulers.values()) {
|
for (Scheduler scheduler : SCHEDULERS.values()) {
|
||||||
try {
|
try {
|
||||||
scheduler.shutdown();
|
scheduler.shutdown();
|
||||||
} catch (final SchedulerException e) {
|
} catch (final SchedulerException e) {
|
||||||
@@ -266,21 +268,21 @@ public class JobRegisterServiceImpl implements JobRegisterService, ApplicationLi
|
|||||||
|
|
||||||
private Scheduler getScheduler(final ScheduledJobDetail scheduledJobDetail) throws Exception {
|
private Scheduler getScheduler(final ScheduledJobDetail scheduledJobDetail) throws Exception {
|
||||||
final String schedulername = getSchedulerName(scheduledJobDetail);
|
final String schedulername = getSchedulerName(scheduledJobDetail);
|
||||||
Scheduler scheduler = this.schedulers.get(schedulername);
|
Scheduler scheduler = SCHEDULERS.get(schedulername);
|
||||||
if (scheduler == null) {
|
if (scheduler == null) {
|
||||||
int noOfThreads = SchedulerServiceConstants.DEFAULT_THREAD_COUNT;
|
int noOfThreads = SchedulerServiceConstants.DEFAULT_THREAD_COUNT;
|
||||||
if (scheduledJobDetail.getSchedulerGroup() > 0) {
|
if (scheduledJobDetail.getSchedulerGroup() > 0) {
|
||||||
noOfThreads = SchedulerServiceConstants.GROUP_THREAD_COUNT;
|
noOfThreads = SchedulerServiceConstants.GROUP_THREAD_COUNT;
|
||||||
}
|
}
|
||||||
scheduler = createScheduler(schedulername, noOfThreads, schedulerJobListener);
|
scheduler = createScheduler(schedulername, noOfThreads, schedulerJobListener);
|
||||||
this.schedulers.put(schedulername, scheduler);
|
SCHEDULERS.put(schedulername, scheduler);
|
||||||
}
|
}
|
||||||
return scheduler;
|
return scheduler;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void stopScheduler(final String name) {
|
public void stopScheduler(final String name) {
|
||||||
final Scheduler scheduler = this.schedulers.remove(name);
|
final Scheduler scheduler = SCHEDULERS.remove(name);
|
||||||
try {
|
try {
|
||||||
scheduler.shutdown();
|
scheduler.shutdown();
|
||||||
} catch (final SchedulerException e) {
|
} catch (final SchedulerException e) {
|
||||||
@@ -363,7 +365,6 @@ public class JobRegisterServiceImpl implements JobRegisterService, ApplicationLi
|
|||||||
|
|
||||||
private JobKey constructJobKey(final String Key) {
|
private JobKey constructJobKey(final String Key) {
|
||||||
final List<String> keyParams = Splitter.onPattern(SchedulerServiceConstants.JOB_KEY_SEPERATOR).splitToList(Key);
|
final List<String> keyParams = Splitter.onPattern(SchedulerServiceConstants.JOB_KEY_SEPERATOR).splitToList(Key);
|
||||||
final JobKey jobKey = new JobKey(keyParams.get(0), keyParams.get(1));
|
return new JobKey(keyParams.get(0), keyParams.get(1));
|
||||||
return jobKey;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+5
-7
@@ -18,13 +18,17 @@
|
|||||||
*/
|
*/
|
||||||
package org.apache.fineract.infrastructure.jobs.service;
|
package org.apache.fineract.infrastructure.jobs.service;
|
||||||
|
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
import org.quartz.JobExecutionContext;
|
import org.quartz.JobExecutionContext;
|
||||||
import org.quartz.JobExecutionException;
|
import org.quartz.JobExecutionException;
|
||||||
import org.quartz.JobListener;
|
import org.quartz.JobListener;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Global job Listener class to Stop the temporary scheduler once job execution completes
|
* Global job Listener class to Stop the temporary scheduler once job execution completes
|
||||||
*/
|
*/
|
||||||
|
@Component
|
||||||
|
@RequiredArgsConstructor
|
||||||
public class SchedulerStopListener implements JobListener {
|
public class SchedulerStopListener implements JobListener {
|
||||||
|
|
||||||
private static final String name = "Singlr Trigger Global Listener";
|
private static final String name = "Singlr Trigger Global Listener";
|
||||||
@@ -60,13 +64,7 @@ public class SchedulerStopListener implements JobListener {
|
|||||||
public void jobWasExecuted(final JobExecutionContext context, @SuppressWarnings("unused") final JobExecutionException jobException) {
|
public void jobWasExecuted(final JobExecutionContext context, @SuppressWarnings("unused") final JobExecutionException jobException) {
|
||||||
final String schedulerName = context.getTrigger().getJobDataMap().getString(SchedulerServiceConstants.SCHEDULER_NAME);
|
final String schedulerName = context.getTrigger().getJobDataMap().getString(SchedulerServiceConstants.SCHEDULER_NAME);
|
||||||
if (schedulerName != null) {
|
if (schedulerName != null) {
|
||||||
final Thread newThread = new Thread(new Runnable() {
|
final Thread newThread = new Thread(() -> SchedulerStopListener.this.jobRegisterService.stopScheduler(schedulerName));
|
||||||
|
|
||||||
@Override
|
|
||||||
public void run() {
|
|
||||||
SchedulerStopListener.this.jobRegisterService.stopScheduler(schedulerName);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
newThread.start();
|
newThread.start();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+26
-27
@@ -38,7 +38,6 @@ public class ReportMailingJobEmailServiceImpl implements ReportMailingJobEmailSe
|
|||||||
|
|
||||||
private static final Logger LOG = LoggerFactory.getLogger(ReportMailingJobEmailServiceImpl.class);
|
private static final Logger LOG = LoggerFactory.getLogger(ReportMailingJobEmailServiceImpl.class);
|
||||||
private final ReportMailingJobConfigurationReadPlatformService reportMailingJobConfigurationReadPlatformService;
|
private final ReportMailingJobConfigurationReadPlatformService reportMailingJobConfigurationReadPlatformService;
|
||||||
private Collection<ReportMailingJobConfigurationData> reportMailingJobConfigurationDataCollection;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* ReportMailingJobEmailServiceImpl constructor
|
* ReportMailingJobEmailServiceImpl constructor
|
||||||
@@ -52,17 +51,18 @@ public class ReportMailingJobEmailServiceImpl implements ReportMailingJobEmailSe
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void sendEmailWithAttachment(ReportMailingJobEmailData reportMailingJobEmailData) {
|
public void sendEmailWithAttachment(ReportMailingJobEmailData reportMailingJobEmailData) {
|
||||||
|
Collection<ReportMailingJobConfigurationData> reportMailingJobConfigurationDataCollection;
|
||||||
try {
|
try {
|
||||||
// get all ReportMailingJobConfiguration objects from the database
|
// get all ReportMailingJobConfiguration objects from the database
|
||||||
this.reportMailingJobConfigurationDataCollection = this.reportMailingJobConfigurationReadPlatformService
|
reportMailingJobConfigurationDataCollection = this.reportMailingJobConfigurationReadPlatformService
|
||||||
.retrieveAllReportMailingJobConfigurations();
|
.retrieveAllReportMailingJobConfigurations();
|
||||||
|
|
||||||
JavaMailSenderImpl javaMailSenderImpl = new JavaMailSenderImpl();
|
JavaMailSenderImpl javaMailSenderImpl = new JavaMailSenderImpl();
|
||||||
javaMailSenderImpl.setHost(this.getGmailSmtpServer());
|
javaMailSenderImpl.setHost(this.getGmailSmtpServer(reportMailingJobConfigurationDataCollection));
|
||||||
javaMailSenderImpl.setPort(this.getGmailSmtpPort());
|
javaMailSenderImpl.setPort(this.getGmailSmtpPort(reportMailingJobConfigurationDataCollection));
|
||||||
javaMailSenderImpl.setUsername(this.getGmailSmtpUsername());
|
javaMailSenderImpl.setUsername(this.getGmailSmtpUsername(reportMailingJobConfigurationDataCollection));
|
||||||
javaMailSenderImpl.setPassword(this.getGmailSmtpPassword());
|
javaMailSenderImpl.setPassword(this.getGmailSmtpPassword(reportMailingJobConfigurationDataCollection));
|
||||||
javaMailSenderImpl.setJavaMailProperties(this.getJavaMailProperties());
|
javaMailSenderImpl.setJavaMailProperties(this.getJavaMailProperties(reportMailingJobConfigurationDataCollection));
|
||||||
|
|
||||||
MimeMessage mimeMessage = javaMailSenderImpl.createMimeMessage();
|
MimeMessage mimeMessage = javaMailSenderImpl.createMimeMessage();
|
||||||
|
|
||||||
@@ -79,9 +79,7 @@ public class ReportMailingJobEmailServiceImpl implements ReportMailingJobEmailSe
|
|||||||
}
|
}
|
||||||
|
|
||||||
javaMailSenderImpl.send(mimeMessage);
|
javaMailSenderImpl.send(mimeMessage);
|
||||||
}
|
} catch (MessagingException e) {
|
||||||
|
|
||||||
catch (MessagingException e) {
|
|
||||||
// handle the exception
|
// handle the exception
|
||||||
LOG.error("Problem occurred in sendEmailWithAttachment function", e);
|
LOG.error("Problem occurred in sendEmailWithAttachment function", e);
|
||||||
}
|
}
|
||||||
@@ -90,12 +88,12 @@ public class ReportMailingJobEmailServiceImpl implements ReportMailingJobEmailSe
|
|||||||
/**
|
/**
|
||||||
* @return Properties object containing JavaMail properties
|
* @return Properties object containing JavaMail properties
|
||||||
**/
|
**/
|
||||||
private Properties getJavaMailProperties() {
|
private Properties getJavaMailProperties(Collection<ReportMailingJobConfigurationData> reportMailingJobConfigurationDataCollection) {
|
||||||
Properties properties = new Properties();
|
Properties properties = new Properties();
|
||||||
|
|
||||||
properties.setProperty("mail.smtp.auth", "true");
|
properties.setProperty("mail.smtp.auth", "true");
|
||||||
properties.setProperty("mail.smtp.starttls.enable", "true");
|
properties.setProperty("mail.smtp.starttls.enable", "true");
|
||||||
properties.setProperty("mail.smtp.ssl.trust", this.getGmailSmtpServer());
|
properties.setProperty("mail.smtp.ssl.trust", this.getGmailSmtpServer(reportMailingJobConfigurationDataCollection));
|
||||||
|
|
||||||
return properties;
|
return properties;
|
||||||
}
|
}
|
||||||
@@ -107,11 +105,12 @@ public class ReportMailingJobEmailServiceImpl implements ReportMailingJobEmailSe
|
|||||||
* -- the value of the name property
|
* -- the value of the name property
|
||||||
* @return ReportMailingJobConfigurationData object
|
* @return ReportMailingJobConfigurationData object
|
||||||
**/
|
**/
|
||||||
private ReportMailingJobConfigurationData getReportMailingJobConfigurationData(final String name) {
|
private ReportMailingJobConfigurationData getReportMailingJobConfigurationData(
|
||||||
|
final Collection<ReportMailingJobConfigurationData> reportMailingJobConfigurationDataCollection, final String name) {
|
||||||
ReportMailingJobConfigurationData reportMailingJobConfigurationData = null;
|
ReportMailingJobConfigurationData reportMailingJobConfigurationData = null;
|
||||||
|
|
||||||
if (this.reportMailingJobConfigurationDataCollection != null && !this.reportMailingJobConfigurationDataCollection.isEmpty()) {
|
if (reportMailingJobConfigurationDataCollection != null && !reportMailingJobConfigurationDataCollection.isEmpty()) {
|
||||||
for (ReportMailingJobConfigurationData reportMailingJobConfigurationDataObject : this.reportMailingJobConfigurationDataCollection) {
|
for (ReportMailingJobConfigurationData reportMailingJobConfigurationDataObject : reportMailingJobConfigurationDataCollection) {
|
||||||
String configurationName = reportMailingJobConfigurationDataObject.getName();
|
String configurationName = reportMailingJobConfigurationDataObject.getName();
|
||||||
|
|
||||||
if (!StringUtils.isEmpty(configurationName) && configurationName.equals(name)) {
|
if (!StringUtils.isEmpty(configurationName) && configurationName.equals(name)) {
|
||||||
@@ -127,9 +126,9 @@ public class ReportMailingJobEmailServiceImpl implements ReportMailingJobEmailSe
|
|||||||
/**
|
/**
|
||||||
* @return Gmail smtp server name
|
* @return Gmail smtp server name
|
||||||
**/
|
**/
|
||||||
private String getGmailSmtpServer() {
|
private String getGmailSmtpServer(Collection<ReportMailingJobConfigurationData> reportMailingJobConfigurationDataCollection) {
|
||||||
final ReportMailingJobConfigurationData reportMailingJobConfigurationData = this
|
final ReportMailingJobConfigurationData reportMailingJobConfigurationData = this.getReportMailingJobConfigurationData(
|
||||||
.getReportMailingJobConfigurationData(ReportMailingJobConstants.GMAIL_SMTP_SERVER);
|
reportMailingJobConfigurationDataCollection, ReportMailingJobConstants.GMAIL_SMTP_SERVER);
|
||||||
|
|
||||||
return (reportMailingJobConfigurationData != null) ? reportMailingJobConfigurationData.getValue() : null;
|
return (reportMailingJobConfigurationData != null) ? reportMailingJobConfigurationData.getValue() : null;
|
||||||
}
|
}
|
||||||
@@ -137,9 +136,9 @@ public class ReportMailingJobEmailServiceImpl implements ReportMailingJobEmailSe
|
|||||||
/**
|
/**
|
||||||
* @return Gmail smtp server port number
|
* @return Gmail smtp server port number
|
||||||
**/
|
**/
|
||||||
private Integer getGmailSmtpPort() {
|
private Integer getGmailSmtpPort(Collection<ReportMailingJobConfigurationData> reportMailingJobConfigurationDataCollection) {
|
||||||
final ReportMailingJobConfigurationData reportMailingJobConfigurationData = this
|
final ReportMailingJobConfigurationData reportMailingJobConfigurationData = this.getReportMailingJobConfigurationData(
|
||||||
.getReportMailingJobConfigurationData(ReportMailingJobConstants.GMAIL_SMTP_PORT);
|
reportMailingJobConfigurationDataCollection, ReportMailingJobConstants.GMAIL_SMTP_PORT);
|
||||||
final String portNumber = (reportMailingJobConfigurationData != null) ? reportMailingJobConfigurationData.getValue() : null;
|
final String portNumber = (reportMailingJobConfigurationData != null) ? reportMailingJobConfigurationData.getValue() : null;
|
||||||
|
|
||||||
return (portNumber != null) ? Integer.parseInt(portNumber) : null;
|
return (portNumber != null) ? Integer.parseInt(portNumber) : null;
|
||||||
@@ -148,9 +147,9 @@ public class ReportMailingJobEmailServiceImpl implements ReportMailingJobEmailSe
|
|||||||
/**
|
/**
|
||||||
* @return Gmail smtp username
|
* @return Gmail smtp username
|
||||||
**/
|
**/
|
||||||
private String getGmailSmtpUsername() {
|
private String getGmailSmtpUsername(Collection<ReportMailingJobConfigurationData> reportMailingJobConfigurationDataCollection) {
|
||||||
final ReportMailingJobConfigurationData reportMailingJobConfigurationData = this
|
final ReportMailingJobConfigurationData reportMailingJobConfigurationData = this.getReportMailingJobConfigurationData(
|
||||||
.getReportMailingJobConfigurationData(ReportMailingJobConstants.GMAIL_SMTP_USERNAME);
|
reportMailingJobConfigurationDataCollection, ReportMailingJobConstants.GMAIL_SMTP_USERNAME);
|
||||||
|
|
||||||
return (reportMailingJobConfigurationData != null) ? reportMailingJobConfigurationData.getValue() : null;
|
return (reportMailingJobConfigurationData != null) ? reportMailingJobConfigurationData.getValue() : null;
|
||||||
}
|
}
|
||||||
@@ -158,9 +157,9 @@ public class ReportMailingJobEmailServiceImpl implements ReportMailingJobEmailSe
|
|||||||
/**
|
/**
|
||||||
* @return Gmail smtp password
|
* @return Gmail smtp password
|
||||||
**/
|
**/
|
||||||
private String getGmailSmtpPassword() {
|
private String getGmailSmtpPassword(Collection<ReportMailingJobConfigurationData> reportMailingJobConfigurationDataCollection) {
|
||||||
final ReportMailingJobConfigurationData reportMailingJobConfigurationData = this
|
final ReportMailingJobConfigurationData reportMailingJobConfigurationData = this.getReportMailingJobConfigurationData(
|
||||||
.getReportMailingJobConfigurationData(ReportMailingJobConstants.GMAIL_SMTP_PASSWORD);
|
reportMailingJobConfigurationDataCollection, ReportMailingJobConstants.GMAIL_SMTP_PASSWORD);
|
||||||
|
|
||||||
return (reportMailingJobConfigurationData != null) ? reportMailingJobConfigurationData.getValue() : null;
|
return (reportMailingJobConfigurationData != null) ? reportMailingJobConfigurationData.getValue() : null;
|
||||||
}
|
}
|
||||||
|
|||||||
+2
-2
@@ -45,7 +45,7 @@ import org.springframework.stereotype.Component;
|
|||||||
@ConditionalOnProperty("fineract.security.2fa.enabled")
|
@ConditionalOnProperty("fineract.security.2fa.enabled")
|
||||||
public class TwoFactorConfigurationApiResource {
|
public class TwoFactorConfigurationApiResource {
|
||||||
|
|
||||||
private final String resourceNameForPermissions = "TWOFACTOR_CONFIG";
|
private static final String RESOURCE_NAME_FOR_PERMISSIONS = "TWOFACTOR_CONFIG";
|
||||||
|
|
||||||
private final PlatformSecurityContext context;
|
private final PlatformSecurityContext context;
|
||||||
private final TwoFactorConfigurationService configurationService;
|
private final TwoFactorConfigurationService configurationService;
|
||||||
@@ -64,7 +64,7 @@ public class TwoFactorConfigurationApiResource {
|
|||||||
|
|
||||||
@GET
|
@GET
|
||||||
public String retrieveAll() {
|
public String retrieveAll() {
|
||||||
this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions);
|
this.context.authenticatedUser().validateHasReadPermission(RESOURCE_NAME_FOR_PERMISSIONS);
|
||||||
Map<String, Object> configurationMap = configurationService.retrieveAll();
|
Map<String, Object> configurationMap = configurationService.retrieveAll();
|
||||||
return toApiJsonSerializer.serialize(configurationMap);
|
return toApiJsonSerializer.serialize(configurationMap);
|
||||||
}
|
}
|
||||||
|
|||||||
+4
-4
@@ -30,21 +30,21 @@ import org.springframework.util.Assert;
|
|||||||
@SuppressWarnings({ "MemberName" })
|
@SuppressWarnings({ "MemberName" })
|
||||||
public class OTPRequestRepository {
|
public class OTPRequestRepository {
|
||||||
|
|
||||||
private final ConcurrentHashMap<Long, OTPRequest> OTPrequests = new ConcurrentHashMap<>();
|
private static final ConcurrentHashMap<Long, OTPRequest> OTT_REQUESTS = new ConcurrentHashMap<>();
|
||||||
|
|
||||||
public OTPRequest getOTPRequestForUser(AppUser user) {
|
public OTPRequest getOTPRequestForUser(AppUser user) {
|
||||||
Assert.notNull(user, "User must not be null");
|
Assert.notNull(user, "User must not be null");
|
||||||
|
|
||||||
return this.OTPrequests.get(user.getId());
|
return OTT_REQUESTS.get(user.getId());
|
||||||
}
|
}
|
||||||
|
|
||||||
public void addOTPRequest(AppUser user, OTPRequest request) {
|
public void addOTPRequest(AppUser user, OTPRequest request) {
|
||||||
Assert.notNull(user, "User must not be null");
|
Assert.notNull(user, "User must not be null");
|
||||||
Assert.notNull(request, "Request must not be null");
|
Assert.notNull(request, "Request must not be null");
|
||||||
this.OTPrequests.put(user.getId(), request);
|
OTT_REQUESTS.put(user.getId(), request);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void deleteOTPRequestForUser(AppUser user) {
|
public void deleteOTPRequestForUser(AppUser user) {
|
||||||
this.OTPrequests.remove(user.getId());
|
OTT_REQUESTS.remove(user.getId());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+2
-2
@@ -47,7 +47,7 @@ import org.springframework.stereotype.Component;
|
|||||||
@Tag(name = "Mix Taxonomy", description = "")
|
@Tag(name = "Mix Taxonomy", description = "")
|
||||||
public class MixTaxonomyApiResource {
|
public class MixTaxonomyApiResource {
|
||||||
|
|
||||||
private final Set<String> responseDataParameters = new HashSet<>(
|
private static final Set<String> RESPONSE_DATA_PARAMETERS = new HashSet<>(
|
||||||
Arrays.asList("taxonomyId", "name", "namespace", "dimension", "description"));
|
Arrays.asList("taxonomyId", "name", "namespace", "dimension", "description"));
|
||||||
|
|
||||||
private final PlatformSecurityContext context;
|
private final PlatformSecurityContext context;
|
||||||
@@ -75,6 +75,6 @@ public class MixTaxonomyApiResource {
|
|||||||
final List<MixTaxonomyData> taxonomyDatas = this.readTaxonomyService.retrieveAll();
|
final List<MixTaxonomyData> taxonomyDatas = this.readTaxonomyService.retrieveAll();
|
||||||
final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters());
|
final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters());
|
||||||
|
|
||||||
return this.toApiJsonSerializer.serialize(settings, taxonomyDatas, this.responseDataParameters);
|
return this.toApiJsonSerializer.serialize(settings, taxonomyDatas, RESPONSE_DATA_PARAMETERS);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+2
-2
@@ -51,7 +51,7 @@ import org.springframework.stereotype.Component;
|
|||||||
@Tag(name = "Mix Mapping", description = "")
|
@Tag(name = "Mix Mapping", description = "")
|
||||||
public class MixTaxonomyMappingApiResource {
|
public class MixTaxonomyMappingApiResource {
|
||||||
|
|
||||||
private final Set<String> responseDataParameters = new HashSet<>(Arrays.asList("identifier", "config"));
|
private static final Set<String> RESPONSE_DATA_PARAMETERS = new HashSet<>(Arrays.asList("identifier", "config"));
|
||||||
|
|
||||||
private final PlatformSecurityContext context;
|
private final PlatformSecurityContext context;
|
||||||
private final ToApiJsonSerializer<MixTaxonomyMappingData> toApiJsonSerializer;
|
private final ToApiJsonSerializer<MixTaxonomyMappingData> toApiJsonSerializer;
|
||||||
@@ -80,7 +80,7 @@ public class MixTaxonomyMappingApiResource {
|
|||||||
this.context.authenticatedUser();
|
this.context.authenticatedUser();
|
||||||
final MixTaxonomyMappingData mappingData = this.readTaxonomyMappingService.retrieveTaxonomyMapping();
|
final MixTaxonomyMappingData mappingData = this.readTaxonomyMappingService.retrieveTaxonomyMapping();
|
||||||
final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters());
|
final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters());
|
||||||
return this.toApiJsonSerializer.serialize(settings, mappingData, this.responseDataParameters);
|
return this.toApiJsonSerializer.serialize(settings, mappingData, RESPONSE_DATA_PARAMETERS);
|
||||||
}
|
}
|
||||||
|
|
||||||
@PUT
|
@PUT
|
||||||
|
|||||||
@@ -44,13 +44,6 @@ public class XBRLBuilder {
|
|||||||
private static final String UNITID_PURE = "Unit1";
|
private static final String UNITID_PURE = "Unit1";
|
||||||
private static final String UNITID_CUR = "Unit2";
|
private static final String UNITID_CUR = "Unit2";
|
||||||
|
|
||||||
private Element root;
|
|
||||||
private HashMap<ContextData, String> contextMap;
|
|
||||||
Date startDate;
|
|
||||||
Date endDate;
|
|
||||||
private Integer instantScenarioCounter = 1;
|
|
||||||
private Integer durationScenarioCounter = 1;
|
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
private NamespaceReadPlatformService readNamespaceService;
|
private NamespaceReadPlatformService readNamespaceService;
|
||||||
|
|
||||||
@@ -59,38 +52,37 @@ public class XBRLBuilder {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public String build(final Map<MixTaxonomyData, BigDecimal> map, final Date startDate, final Date endDate, final String currency) {
|
public String build(final Map<MixTaxonomyData, BigDecimal> map, final Date startDate, final Date endDate, final String currency) {
|
||||||
this.instantScenarioCounter = 1;
|
Integer instantScenarioCounter = 0;
|
||||||
this.durationScenarioCounter = 1;
|
Integer durationScenarioCounter = 0;
|
||||||
this.contextMap = new HashMap<>();
|
Map<ContextData, String> contextMap = new HashMap<>();
|
||||||
final Document doc = DocumentHelper.createDocument();
|
final Document doc = DocumentHelper.createDocument();
|
||||||
this.root = doc.addElement("xbrl");
|
Element root = doc.addElement("xbrl");
|
||||||
|
|
||||||
this.root.addElement("schemaRef").addNamespace("link",
|
root.addElement("schemaRef").addNamespace("link",
|
||||||
"http://www.themix.org/sites/default/files/Taxonomy2010/dct/dc-all_2010-08-31.xsd");
|
"http://www.themix.org/sites/default/files/Taxonomy2010/dct/dc-all_2010-08-31.xsd");
|
||||||
|
|
||||||
this.startDate = startDate;
|
|
||||||
this.endDate = endDate;
|
|
||||||
|
|
||||||
for (final Map.Entry<MixTaxonomyData, BigDecimal> entry : map.entrySet()) {
|
for (final Map.Entry<MixTaxonomyData, BigDecimal> entry : map.entrySet()) {
|
||||||
final MixTaxonomyData taxonomy = entry.getKey();
|
final MixTaxonomyData taxonomy = entry.getKey();
|
||||||
final BigDecimal value = entry.getValue();
|
final BigDecimal value = entry.getValue();
|
||||||
addTaxonomy(this.root, taxonomy, value);
|
addTaxonomy(root, taxonomy, value, startDate, endDate, instantScenarioCounter, durationScenarioCounter, contextMap);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
addContexts();
|
addContexts(root, startDate, endDate, contextMap);
|
||||||
addCurrencyUnit(currency);
|
addCurrencyUnit(root, currency);
|
||||||
addNumberUnit();
|
addNumberUnit(root);
|
||||||
|
|
||||||
doc.setXMLEncoding("UTF-8");
|
doc.setXMLEncoding("UTF-8");
|
||||||
|
|
||||||
return doc.asXML();
|
return doc.asXML();
|
||||||
}
|
}
|
||||||
|
|
||||||
Element addTaxonomy(final Element rootElement, final MixTaxonomyData taxonomy, final BigDecimal value) {
|
private Element addTaxonomy(final Element rootElement, final MixTaxonomyData taxonomy, final BigDecimal value, final Date startDate,
|
||||||
|
final Date endDate, Integer instantScenarioCounter, Integer durationScenarioCounter,
|
||||||
|
final Map<ContextData, String> contextMap) {
|
||||||
|
|
||||||
// throw an error is start / endate is null
|
// throw an error is start / endate is null
|
||||||
if (this.startDate == null || this.endDate == null) {
|
if (startDate == null || endDate == null) {
|
||||||
throw new XBRLMappingInvalidException("start date and end date should not be null");
|
throw new XBRLMappingInvalidException("start date and end date should not be null");
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -100,7 +92,7 @@ public class XBRLBuilder {
|
|||||||
final NamespaceData ns = this.readNamespaceService.retrieveNamespaceByPrefix(prefix);
|
final NamespaceData ns = this.readNamespaceService.retrieveNamespaceByPrefix(prefix);
|
||||||
if (ns != null) {
|
if (ns != null) {
|
||||||
|
|
||||||
this.root.addNamespace(prefix, ns.getUrl());
|
rootElement.addNamespace(prefix, ns.getUrl());
|
||||||
}
|
}
|
||||||
qname = prefix + ":" + taxonomy.getName();
|
qname = prefix + ":" + taxonomy.getName();
|
||||||
|
|
||||||
@@ -127,18 +119,19 @@ public class XBRLBuilder {
|
|||||||
: 1);
|
: 1);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!this.contextMap.containsKey(context)) {
|
if (!contextMap.containsKey(context)) {
|
||||||
|
|
||||||
final String startDateStr = timeFormat.format(this.startDate);
|
final String startDateStr = timeFormat.format(startDate);
|
||||||
final String endDateStr = timeFormat.format(this.endDate);
|
final String endDateStr = timeFormat.format(endDate);
|
||||||
|
instantScenarioCounter += 1;
|
||||||
|
durationScenarioCounter += 1;
|
||||||
|
final String contextRefID = context.getPeriodType() == 0 ? "As_Of_" + endDateStr + instantScenarioCounter
|
||||||
|
: "Duration_" + startDateStr + "_To_" + endDateStr + durationScenarioCounter;
|
||||||
|
|
||||||
final String contextRefID = context.getPeriodType() == 0 ? "As_Of_" + endDateStr + this.instantScenarioCounter++
|
contextMap.put(context, contextRefID);
|
||||||
: "Duration_" + startDateStr + "_To_" + endDateStr + this.durationScenarioCounter++;
|
|
||||||
|
|
||||||
this.contextMap.put(context, contextRefID);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
xmlElement.addAttribute("contextRef", this.contextMap.get(context));
|
xmlElement.addAttribute("contextRef", contextMap.get(context));
|
||||||
xmlElement.addAttribute("unitRef", getUnitRef(taxonomy));
|
xmlElement.addAttribute("unitRef", getUnitRef(taxonomy));
|
||||||
xmlElement.addAttribute("decimals", getNumberOfDecimalPlaces(value).toString());
|
xmlElement.addAttribute("decimals", getNumberOfDecimalPlaces(value).toString());
|
||||||
|
|
||||||
@@ -155,8 +148,8 @@ public class XBRLBuilder {
|
|||||||
/**
|
/**
|
||||||
* Adds the generic number unit
|
* Adds the generic number unit
|
||||||
*/
|
*/
|
||||||
void addNumberUnit() {
|
private void addNumberUnit(final Element root) {
|
||||||
final Element numerUnit = this.root.addElement("unit");
|
final Element numerUnit = root.addElement("unit");
|
||||||
numerUnit.addAttribute("id", UNITID_PURE);
|
numerUnit.addAttribute("id", UNITID_PURE);
|
||||||
final Element measure = numerUnit.addElement("measure");
|
final Element measure = numerUnit.addElement("measure");
|
||||||
measure.addText("xbrli:pure");
|
measure.addText("xbrli:pure");
|
||||||
@@ -168,29 +161,29 @@ public class XBRLBuilder {
|
|||||||
*
|
*
|
||||||
* @param currencyCode
|
* @param currencyCode
|
||||||
*/
|
*/
|
||||||
public void addCurrencyUnit(final String currencyCode) {
|
private void addCurrencyUnit(final Element root, final String currencyCode) {
|
||||||
final Element currencyUnitElement = this.root.addElement("unit");
|
final Element currencyUnitElement = root.addElement("unit");
|
||||||
currencyUnitElement.addAttribute("id", UNITID_CUR);
|
currencyUnitElement.addAttribute("id", UNITID_CUR);
|
||||||
final Element measure = currencyUnitElement.addElement("measure");
|
final Element measure = currencyUnitElement.addElement("measure");
|
||||||
measure.addText("iso4217:" + currencyCode);
|
measure.addText("iso4217:" + currencyCode);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public void addContexts() {
|
private void addContexts(final Element root, final Date startDate, final Date endDate, final Map<ContextData, String> contextMap) {
|
||||||
final SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
|
final SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
|
||||||
for (final Map.Entry<ContextData, String> entry : this.contextMap.entrySet()) {
|
for (final Map.Entry<ContextData, String> entry : contextMap.entrySet()) {
|
||||||
final ContextData context = entry.getKey();
|
final ContextData context = entry.getKey();
|
||||||
final Element contextElement = this.root.addElement("context");
|
final Element contextElement = root.addElement("context");
|
||||||
contextElement.addAttribute("id", entry.getValue());
|
contextElement.addAttribute("id", entry.getValue());
|
||||||
contextElement.addElement("entity").addElement("identifier").addAttribute("scheme", SCHEME_URL).addText(IDENTIFIER);
|
contextElement.addElement("entity").addElement("identifier").addAttribute("scheme", SCHEME_URL).addText(IDENTIFIER);
|
||||||
|
|
||||||
final Element periodElement = contextElement.addElement("period");
|
final Element periodElement = contextElement.addElement("period");
|
||||||
|
|
||||||
if (context.getPeriodType() == 0) {
|
if (context.getPeriodType() == 0) {
|
||||||
periodElement.addElement("instant").addText(format.format(this.endDate));
|
periodElement.addElement("instant").addText(format.format(endDate));
|
||||||
} else {
|
} else {
|
||||||
periodElement.addElement("startDate").addText(format.format(this.startDate));
|
periodElement.addElement("startDate").addText(format.format(startDate));
|
||||||
periodElement.addElement("endDate").addText(format.format(this.endDate));
|
periodElement.addElement("endDate").addText(format.format(endDate));
|
||||||
}
|
}
|
||||||
|
|
||||||
final String dimension = context.getDimension();
|
final String dimension = context.getDimension();
|
||||||
|
|||||||
+20
-22
@@ -23,6 +23,7 @@ import java.math.BigDecimal;
|
|||||||
import java.sql.Date;
|
import java.sql.Date;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.regex.Matcher;
|
import java.util.regex.Matcher;
|
||||||
import java.util.regex.Pattern;
|
import java.util.regex.Pattern;
|
||||||
@@ -49,7 +50,6 @@ public class XBRLResultServiceImpl implements XBRLResultService {
|
|||||||
private final MixTaxonomyMappingReadPlatformService readTaxonomyMappingService;
|
private final MixTaxonomyMappingReadPlatformService readTaxonomyMappingService;
|
||||||
private final MixTaxonomyReadPlatformService readTaxonomyService;
|
private final MixTaxonomyReadPlatformService readTaxonomyService;
|
||||||
private final JdbcTemplate jdbcTemplate;
|
private final JdbcTemplate jdbcTemplate;
|
||||||
private HashMap<String, BigDecimal> accountBalanceMap;
|
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
public XBRLResultServiceImpl(final JdbcTemplate jdbcTemplate, final MixTaxonomyMappingReadPlatformService readTaxonomyMappingService,
|
public XBRLResultServiceImpl(final JdbcTemplate jdbcTemplate, final MixTaxonomyMappingReadPlatformService readTaxonomyMappingService,
|
||||||
@@ -85,13 +85,11 @@ public class XBRLResultServiceImpl implements XBRLResultService {
|
|||||||
}
|
}
|
||||||
// <taxonomyId, value>
|
// <taxonomyId, value>
|
||||||
final HashMap<MixTaxonomyData, BigDecimal> resultMap = new HashMap<>();
|
final HashMap<MixTaxonomyData, BigDecimal> resultMap = new HashMap<>();
|
||||||
setupBalanceMap(getAccountSql(startDate, endDate));
|
Map<String, BigDecimal> accountBalanceMap = setupBalanceMap(getAccountSql(startDate, endDate));
|
||||||
for (final Map.Entry<String, String> entry : configMap.entrySet()) {
|
for (final Map.Entry<String, String> entry : configMap.entrySet()) {
|
||||||
final BigDecimal value = processMappingString(entry.getValue());
|
final BigDecimal value = processMappingString(accountBalanceMap, entry.getValue());
|
||||||
if (value != null) {
|
final MixTaxonomyData taxonomy = this.readTaxonomyService.retrieveOne(Long.parseLong(entry.getKey()));
|
||||||
final MixTaxonomyData taxonomy = this.readTaxonomyService.retrieveOne(Long.parseLong(entry.getKey()));
|
resultMap.put(taxonomy, value);
|
||||||
resultMap.put(taxonomy, value);
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
}
|
||||||
return resultMap;
|
return resultMap;
|
||||||
@@ -100,7 +98,7 @@ public class XBRLResultServiceImpl implements XBRLResultService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private String getAccountSql(final Date startDate, final Date endDate) {
|
private String getAccountSql(final Date startDate, final Date endDate) {
|
||||||
final String sql = "select debits.glcode as 'glcode', debits.name as 'name', coalesce(debits.debitamount,0)-coalesce(credits.creditamount,0)) as 'balance' "
|
return "select debits.glcode as 'glcode', debits.name as 'name', coalesce(debits.debitamount,0)-coalesce(credits.creditamount,0)) as 'balance' "
|
||||||
+ "from (select acc_gl_account.gl_code as 'glcode',name,sum(amount) as 'debitamount' "
|
+ "from (select acc_gl_account.gl_code as 'glcode',name,sum(amount) as 'debitamount' "
|
||||||
+ "from acc_gl_journal_entry,acc_gl_account " + "where acc_gl_account.id = acc_gl_journal_entry.account_id "
|
+ "from acc_gl_journal_entry,acc_gl_account " + "where acc_gl_account.id = acc_gl_journal_entry.account_id "
|
||||||
+ "and acc_gl_journal_entry.type_enum=2 " + "and acc_gl_journal_entry.entry_date <= " + endDate
|
+ "and acc_gl_journal_entry.type_enum=2 " + "and acc_gl_journal_entry.entry_date <= " + endDate
|
||||||
@@ -134,30 +132,30 @@ public class XBRLResultServiceImpl implements XBRLResultService {
|
|||||||
// ${branch}=1) "
|
// ${branch}=1) "
|
||||||
// +
|
// +
|
||||||
+ " group by name, glcode " + "order by glcode) credits " + "on debits.glcode=credits.glcode;";
|
+ " group by name, glcode " + "order by glcode) credits " + "on debits.glcode=credits.glcode;";
|
||||||
return sql;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private void setupBalanceMap(final String sql) {
|
private Map<String, BigDecimal> setupBalanceMap(final String sql) {
|
||||||
if (this.accountBalanceMap == null) {
|
Map<String, BigDecimal> accountBalanceMap = new HashMap<>();
|
||||||
this.accountBalanceMap = new HashMap<>();
|
|
||||||
final SqlRowSet rs = this.jdbcTemplate.queryForRowSet(sql);
|
final SqlRowSet rs = this.jdbcTemplate.queryForRowSet(sql);
|
||||||
while (rs.next()) {
|
while (rs.next()) {
|
||||||
this.accountBalanceMap.put(rs.getString("glcode"), rs.getBigDecimal("balance"));
|
accountBalanceMap.put(rs.getString("glcode"), rs.getBigDecimal("balance"));
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return accountBalanceMap;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Calculate Taxonomy value from expression
|
// Calculate Taxonomy value from expression
|
||||||
private BigDecimal processMappingString(String mappingString) {
|
private BigDecimal processMappingString(Map<String, BigDecimal> accountBalanceMap, String mappingString) {
|
||||||
final ArrayList<String> glCodes = getGLCodes(mappingString);
|
final List<String> glCodes = getGLCodes(mappingString);
|
||||||
for (final String glcode : glCodes) {
|
for (final String glcode : glCodes) {
|
||||||
|
|
||||||
final BigDecimal balance = this.accountBalanceMap.get(glcode);
|
final BigDecimal balance = accountBalanceMap.get(glcode);
|
||||||
mappingString = mappingString.replaceAll("\\{" + glcode + "\\}", balance != null ? balance.toString() : "0");
|
mappingString = mappingString.replaceAll("\\{" + glcode + "\\}", balance != null ? balance.toString() : "0");
|
||||||
}
|
}
|
||||||
|
|
||||||
// evaluate the expression
|
// evaluate the expression
|
||||||
Float eval = 0f;
|
float eval = 0f;
|
||||||
try {
|
try {
|
||||||
final Number value = (Number) SCRIPT_ENGINE.eval(mappingString);
|
final Number value = (Number) SCRIPT_ENGINE.eval(mappingString);
|
||||||
if (value != null) {
|
if (value != null) {
|
||||||
@@ -168,10 +166,10 @@ public class XBRLResultServiceImpl implements XBRLResultService {
|
|||||||
throw new IllegalArgumentException(e.getMessage(), e);
|
throw new IllegalArgumentException(e.getMessage(), e);
|
||||||
}
|
}
|
||||||
|
|
||||||
return new BigDecimal(eval);
|
return BigDecimal.valueOf(eval);
|
||||||
}
|
}
|
||||||
|
|
||||||
public ArrayList<String> getGLCodes(final String template) {
|
public List<String> getGLCodes(final String template) {
|
||||||
|
|
||||||
final ArrayList<String> placeholders = new ArrayList<>();
|
final ArrayList<String> placeholders = new ArrayList<>();
|
||||||
|
|
||||||
|
|||||||
+4
-4
@@ -58,9 +58,9 @@ import org.springframework.stereotype.Component;
|
|||||||
@Tag(name = "Currency", description = "Application related configuration around viewing/updating the currencies permitted for use within the MFI.")
|
@Tag(name = "Currency", description = "Application related configuration around viewing/updating the currencies permitted for use within the MFI.")
|
||||||
public class CurrenciesApiResource {
|
public class CurrenciesApiResource {
|
||||||
|
|
||||||
private final Set<String> responseDataParameters = new HashSet<>(Arrays.asList("selectedCurrencyOptions", "currencyOptions"));
|
private static final Set<String> RESPONSE_DATA_PARAMETERS = new HashSet<>(Arrays.asList("selectedCurrencyOptions", "currencyOptions"));
|
||||||
|
|
||||||
private final String resourceNameForPermissions = "CURRENCY";
|
private static final String RESOURCE_NAME_FOR_PERMISSIONS = "CURRENCY";
|
||||||
|
|
||||||
private final PlatformSecurityContext context;
|
private final PlatformSecurityContext context;
|
||||||
private final OrganisationCurrencyReadPlatformService readPlatformService;
|
private final OrganisationCurrencyReadPlatformService readPlatformService;
|
||||||
@@ -89,12 +89,12 @@ public class CurrenciesApiResource {
|
|||||||
@ApiResponse(responseCode = "200", description = "OK", content = @Content(schema = @Schema(implementation = CurrenciesApiResourceSwagger.GetCurrenciesResponse.class))) })
|
@ApiResponse(responseCode = "200", description = "OK", content = @Content(schema = @Schema(implementation = CurrenciesApiResourceSwagger.GetCurrenciesResponse.class))) })
|
||||||
public String retrieveCurrencies(@Context final UriInfo uriInfo) {
|
public String retrieveCurrencies(@Context final UriInfo uriInfo) {
|
||||||
|
|
||||||
this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions);
|
this.context.authenticatedUser().validateHasReadPermission(RESOURCE_NAME_FOR_PERMISSIONS);
|
||||||
|
|
||||||
final ApplicationCurrencyConfigurationData configurationData = this.readPlatformService.retrieveCurrencyConfiguration();
|
final ApplicationCurrencyConfigurationData configurationData = this.readPlatformService.retrieveCurrencyConfiguration();
|
||||||
|
|
||||||
final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters());
|
final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters());
|
||||||
return this.toApiJsonSerializer.serialize(settings, configurationData, this.responseDataParameters);
|
return this.toApiJsonSerializer.serialize(settings, configurationData, RESPONSE_DATA_PARAMETERS);
|
||||||
}
|
}
|
||||||
|
|
||||||
@PUT
|
@PUT
|
||||||
|
|||||||
+6
-6
@@ -22,7 +22,6 @@ import com.google.gson.JsonElement;
|
|||||||
import com.google.gson.reflect.TypeToken;
|
import com.google.gson.reflect.TypeToken;
|
||||||
import java.lang.reflect.Type;
|
import java.lang.reflect.Type;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.Arrays;
|
|
||||||
import java.util.HashSet;
|
import java.util.HashSet;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
@@ -39,10 +38,11 @@ import org.springframework.stereotype.Component;
|
|||||||
@Component
|
@Component
|
||||||
public final class CurrencyCommandFromApiJsonDeserializer {
|
public final class CurrencyCommandFromApiJsonDeserializer {
|
||||||
|
|
||||||
|
public static final String CURRENCIES = "currencies";
|
||||||
/**
|
/**
|
||||||
* The parameters supported for this command.
|
* The parameters supported for this command.
|
||||||
*/
|
*/
|
||||||
private final Set<String> supportedParameters = new HashSet<>(Arrays.asList("currencies"));
|
private static final Set<String> SUPPORTED_PARAMETERS = new HashSet<>(List.of(CURRENCIES));
|
||||||
|
|
||||||
private final FromJsonHelper fromApiJsonHelper;
|
private final FromJsonHelper fromApiJsonHelper;
|
||||||
|
|
||||||
@@ -58,14 +58,14 @@ public final class CurrencyCommandFromApiJsonDeserializer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType();
|
final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType();
|
||||||
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParameters);
|
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, SUPPORTED_PARAMETERS);
|
||||||
|
|
||||||
final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
|
final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
|
||||||
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("currencies");
|
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource(CURRENCIES);
|
||||||
|
|
||||||
final JsonElement element = this.fromApiJsonHelper.parse(json);
|
final JsonElement element = this.fromApiJsonHelper.parse(json);
|
||||||
final String[] currencies = this.fromApiJsonHelper.extractArrayNamed("currencies", element);
|
final String[] currencies = this.fromApiJsonHelper.extractArrayNamed(CURRENCIES, element);
|
||||||
baseDataValidator.reset().parameter("currencies").value(currencies).arrayNotEmpty();
|
baseDataValidator.reset().parameter(CURRENCIES).value(currencies).arrayNotEmpty();
|
||||||
|
|
||||||
throwExceptionIfValidationWarningsExist(dataValidationErrors);
|
throwExceptionIfValidationWarningsExist(dataValidationErrors);
|
||||||
}
|
}
|
||||||
|
|||||||
+3
-3
@@ -56,7 +56,7 @@ public class OfficeTransactionsApiResource {
|
|||||||
Arrays.asList("id", "transactionDate", "fromOfficeId", "fromOfficeName", "toOfficeId", "toOfficeIdName", "currencyCode",
|
Arrays.asList("id", "transactionDate", "fromOfficeId", "fromOfficeName", "toOfficeId", "toOfficeIdName", "currencyCode",
|
||||||
"digitsAfterDecimal", "inMultiplesOf", "transactionAmount", "description", "allowedOffices", "currencyOptions"));
|
"digitsAfterDecimal", "inMultiplesOf", "transactionAmount", "description", "allowedOffices", "currencyOptions"));
|
||||||
|
|
||||||
private final String resourceNameForReadPermissions = "OFFICE";
|
private static final String RESOURCE_NAME_FOR_READ_PERMISSIONS = "OFFICE";
|
||||||
|
|
||||||
private final PlatformSecurityContext context;
|
private final PlatformSecurityContext context;
|
||||||
private final OfficeReadPlatformService readPlatformService;
|
private final OfficeReadPlatformService readPlatformService;
|
||||||
@@ -81,7 +81,7 @@ public class OfficeTransactionsApiResource {
|
|||||||
@Produces({ MediaType.APPLICATION_JSON })
|
@Produces({ MediaType.APPLICATION_JSON })
|
||||||
public String retrieveOfficeTransactions(@Context final UriInfo uriInfo) {
|
public String retrieveOfficeTransactions(@Context final UriInfo uriInfo) {
|
||||||
|
|
||||||
this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForReadPermissions);
|
this.context.authenticatedUser().validateHasReadPermission(RESOURCE_NAME_FOR_READ_PERMISSIONS);
|
||||||
|
|
||||||
final Collection<OfficeTransactionData> officeTransactions = this.readPlatformService.retrieveAllOfficeTransactions();
|
final Collection<OfficeTransactionData> officeTransactions = this.readPlatformService.retrieveAllOfficeTransactions();
|
||||||
|
|
||||||
@@ -95,7 +95,7 @@ public class OfficeTransactionsApiResource {
|
|||||||
@Produces({ MediaType.APPLICATION_JSON })
|
@Produces({ MediaType.APPLICATION_JSON })
|
||||||
public String newOfficeTransactionDetails(@Context final UriInfo uriInfo) {
|
public String newOfficeTransactionDetails(@Context final UriInfo uriInfo) {
|
||||||
|
|
||||||
this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForReadPermissions);
|
this.context.authenticatedUser().validateHasReadPermission(RESOURCE_NAME_FOR_READ_PERMISSIONS);
|
||||||
|
|
||||||
final OfficeTransactionData officeTransactionData = this.readPlatformService.retrieveNewOfficeTransactionDetails();
|
final OfficeTransactionData officeTransactionData = this.readPlatformService.retrieveNewOfficeTransactionDetails();
|
||||||
|
|
||||||
|
|||||||
+10
-10
@@ -28,9 +28,9 @@ import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
|||||||
import io.swagger.v3.oas.annotations.responses.ApiResponses;
|
import io.swagger.v3.oas.annotations.responses.ApiResponses;
|
||||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||||
import java.io.InputStream;
|
import java.io.InputStream;
|
||||||
import java.util.Arrays;
|
|
||||||
import java.util.Collection;
|
import java.util.Collection;
|
||||||
import java.util.HashSet;
|
import java.util.HashSet;
|
||||||
|
import java.util.List;
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
import javax.ws.rs.Consumes;
|
import javax.ws.rs.Consumes;
|
||||||
import javax.ws.rs.DefaultValue;
|
import javax.ws.rs.DefaultValue;
|
||||||
@@ -75,10 +75,10 @@ public class OfficesApiResource {
|
|||||||
/**
|
/**
|
||||||
* The set of parameters that are supported in response for {@link OfficeData}.
|
* The set of parameters that are supported in response for {@link OfficeData}.
|
||||||
*/
|
*/
|
||||||
private final Set<String> responseDataParameters = new HashSet<>(Arrays.asList("id", "name", "nameDecorated", "externalId",
|
private static final Set<String> RESPONSE_DATA_PARAMETERS = new HashSet<>(
|
||||||
"openingDate", "hierarchy", "parentId", "parentName", "allowedParents"));
|
List.of("id", "name", "nameDecorated", "externalId", "openingDate", "hierarchy", "parentId", "parentName", "allowedParents"));
|
||||||
|
|
||||||
private final String resourceNameForPermissions = "OFFICE";
|
private static final String RESOURCE_NAME_FOR_PERMISSIONS = "OFFICE";
|
||||||
|
|
||||||
private final PlatformSecurityContext context;
|
private final PlatformSecurityContext context;
|
||||||
private final OfficeReadPlatformService readPlatformService;
|
private final OfficeReadPlatformService readPlatformService;
|
||||||
@@ -115,14 +115,14 @@ public class OfficesApiResource {
|
|||||||
@QueryParam("orderBy") @Parameter(description = "orderBy") final String orderBy,
|
@QueryParam("orderBy") @Parameter(description = "orderBy") final String orderBy,
|
||||||
@QueryParam("sortOrder") @Parameter(description = "sortOrder") final String sortOrder) {
|
@QueryParam("sortOrder") @Parameter(description = "sortOrder") final String sortOrder) {
|
||||||
|
|
||||||
this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions);
|
this.context.authenticatedUser().validateHasReadPermission(RESOURCE_NAME_FOR_PERMISSIONS);
|
||||||
|
|
||||||
final SearchParameters searchParameters = SearchParameters.forOffices(orderBy, sortOrder);
|
final SearchParameters searchParameters = SearchParameters.forOffices(orderBy, sortOrder);
|
||||||
|
|
||||||
final Collection<OfficeData> offices = this.readPlatformService.retrieveAllOffices(onlyManualEntries, searchParameters);
|
final Collection<OfficeData> offices = this.readPlatformService.retrieveAllOffices(onlyManualEntries, searchParameters);
|
||||||
|
|
||||||
final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters());
|
final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters());
|
||||||
return this.toApiJsonSerializer.serialize(settings, offices, this.responseDataParameters);
|
return this.toApiJsonSerializer.serialize(settings, offices, RESPONSE_DATA_PARAMETERS);
|
||||||
}
|
}
|
||||||
|
|
||||||
@GET
|
@GET
|
||||||
@@ -135,7 +135,7 @@ public class OfficesApiResource {
|
|||||||
@ApiResponse(responseCode = "200", description = "OK", content = @Content(schema = @Schema(implementation = OfficesApiResourceSwagger.GetOfficesTemplateResponse.class))) })
|
@ApiResponse(responseCode = "200", description = "OK", content = @Content(schema = @Schema(implementation = OfficesApiResourceSwagger.GetOfficesTemplateResponse.class))) })
|
||||||
public String retrieveOfficeTemplate(@Context final UriInfo uriInfo) {
|
public String retrieveOfficeTemplate(@Context final UriInfo uriInfo) {
|
||||||
|
|
||||||
this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions);
|
this.context.authenticatedUser().validateHasReadPermission(RESOURCE_NAME_FOR_PERMISSIONS);
|
||||||
|
|
||||||
OfficeData office = this.readPlatformService.retrieveNewOfficeTemplate();
|
OfficeData office = this.readPlatformService.retrieveNewOfficeTemplate();
|
||||||
|
|
||||||
@@ -143,7 +143,7 @@ public class OfficesApiResource {
|
|||||||
office = OfficeData.appendedTemplate(office, allowedParents);
|
office = OfficeData.appendedTemplate(office, allowedParents);
|
||||||
|
|
||||||
final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters());
|
final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters());
|
||||||
return this.toApiJsonSerializer.serialize(settings, office, this.responseDataParameters);
|
return this.toApiJsonSerializer.serialize(settings, office, RESPONSE_DATA_PARAMETERS);
|
||||||
}
|
}
|
||||||
|
|
||||||
@POST
|
@POST
|
||||||
@@ -176,7 +176,7 @@ public class OfficesApiResource {
|
|||||||
public String retreiveOffice(@PathParam("officeId") @Parameter(description = "officeId") final Long officeId,
|
public String retreiveOffice(@PathParam("officeId") @Parameter(description = "officeId") final Long officeId,
|
||||||
@Context final UriInfo uriInfo) {
|
@Context final UriInfo uriInfo) {
|
||||||
|
|
||||||
this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions);
|
this.context.authenticatedUser().validateHasReadPermission(RESOURCE_NAME_FOR_PERMISSIONS);
|
||||||
|
|
||||||
final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters());
|
final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters());
|
||||||
|
|
||||||
@@ -186,7 +186,7 @@ public class OfficesApiResource {
|
|||||||
office = OfficeData.appendedTemplate(office, allowedParents);
|
office = OfficeData.appendedTemplate(office, allowedParents);
|
||||||
}
|
}
|
||||||
|
|
||||||
return this.toApiJsonSerializer.serialize(settings, office, this.responseDataParameters);
|
return this.toApiJsonSerializer.serialize(settings, office, RESPONSE_DATA_PARAMETERS);
|
||||||
}
|
}
|
||||||
|
|
||||||
@PUT
|
@PUT
|
||||||
|
|||||||
+32
-26
@@ -43,11 +43,17 @@ import org.springframework.stereotype.Component;
|
|||||||
@Component
|
@Component
|
||||||
public final class OfficeCommandFromApiJsonDeserializer {
|
public final class OfficeCommandFromApiJsonDeserializer {
|
||||||
|
|
||||||
|
public static final String PARENT_ID = "parentId";
|
||||||
|
public static final String NAME = "name";
|
||||||
|
public static final String OPENING_DATE = "openingDate";
|
||||||
|
public static final String EXTERNAL_ID = "externalId";
|
||||||
|
public static final String LOCALE = "locale";
|
||||||
|
public static final String DATE_FORMAT = "dateFormat";
|
||||||
/**
|
/**
|
||||||
* The parameters supported for this command.
|
* The parameters supported for this command.
|
||||||
*/
|
*/
|
||||||
private final Set<String> supportedParameters = new HashSet<>(
|
private static final Set<String> SUPPORTED_PARAMETERS = new HashSet<>(
|
||||||
Arrays.asList("name", "parentId", "openingDate", "externalId", "locale", "dateFormat"));
|
Arrays.asList(NAME, PARENT_ID, OPENING_DATE, EXTERNAL_ID, LOCALE, DATE_FORMAT));
|
||||||
|
|
||||||
private final FromJsonHelper fromApiJsonHelper;
|
private final FromJsonHelper fromApiJsonHelper;
|
||||||
|
|
||||||
@@ -62,27 +68,27 @@ public final class OfficeCommandFromApiJsonDeserializer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType();
|
final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType();
|
||||||
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParameters);
|
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, SUPPORTED_PARAMETERS);
|
||||||
|
|
||||||
final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
|
final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
|
||||||
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("office");
|
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("office");
|
||||||
|
|
||||||
final JsonElement element = this.fromApiJsonHelper.parse(json);
|
final JsonElement element = this.fromApiJsonHelper.parse(json);
|
||||||
|
|
||||||
final String name = this.fromApiJsonHelper.extractStringNamed("name", element);
|
final String name = this.fromApiJsonHelper.extractStringNamed(NAME, element);
|
||||||
baseDataValidator.reset().parameter("name").value(name).notBlank().notExceedingLengthOf(100);
|
baseDataValidator.reset().parameter(NAME).value(name).notBlank().notExceedingLengthOf(100);
|
||||||
|
|
||||||
final LocalDate openingDate = this.fromApiJsonHelper.extractLocalDateNamed("openingDate", element);
|
final LocalDate openingDate = this.fromApiJsonHelper.extractLocalDateNamed(OPENING_DATE, element);
|
||||||
baseDataValidator.reset().parameter("openingDate").value(openingDate).notNull();
|
baseDataValidator.reset().parameter(OPENING_DATE).value(openingDate).notNull();
|
||||||
|
|
||||||
if (this.fromApiJsonHelper.parameterExists("externalId", element)) {
|
if (this.fromApiJsonHelper.parameterExists(EXTERNAL_ID, element)) {
|
||||||
final String externalId = this.fromApiJsonHelper.extractStringNamed("externalId", element);
|
final String externalId = this.fromApiJsonHelper.extractStringNamed(EXTERNAL_ID, element);
|
||||||
baseDataValidator.reset().parameter("externalId").value(externalId).notExceedingLengthOf(100);
|
baseDataValidator.reset().parameter(EXTERNAL_ID).value(externalId).notExceedingLengthOf(100);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (this.fromApiJsonHelper.parameterExists("parentId", element)) {
|
if (this.fromApiJsonHelper.parameterExists(PARENT_ID, element)) {
|
||||||
final Long parentId = this.fromApiJsonHelper.extractLongNamed("parentId", element);
|
final Long parentId = this.fromApiJsonHelper.extractLongNamed(PARENT_ID, element);
|
||||||
baseDataValidator.reset().parameter("parentId").value(parentId).notNull().integerGreaterThanZero();
|
baseDataValidator.reset().parameter(PARENT_ID).value(parentId).notNull().integerGreaterThanZero();
|
||||||
}
|
}
|
||||||
|
|
||||||
throwExceptionIfValidationWarningsExist(dataValidationErrors);
|
throwExceptionIfValidationWarningsExist(dataValidationErrors);
|
||||||
@@ -101,31 +107,31 @@ public final class OfficeCommandFromApiJsonDeserializer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType();
|
final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType();
|
||||||
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParameters);
|
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, SUPPORTED_PARAMETERS);
|
||||||
|
|
||||||
final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
|
final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
|
||||||
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("office");
|
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("office");
|
||||||
|
|
||||||
final JsonElement element = this.fromApiJsonHelper.parse(json);
|
final JsonElement element = this.fromApiJsonHelper.parse(json);
|
||||||
|
|
||||||
if (this.fromApiJsonHelper.parameterExists("name", element)) {
|
if (this.fromApiJsonHelper.parameterExists(NAME, element)) {
|
||||||
final String name = this.fromApiJsonHelper.extractStringNamed("name", element);
|
final String name = this.fromApiJsonHelper.extractStringNamed(NAME, element);
|
||||||
baseDataValidator.reset().parameter("name").value(name).notBlank().notExceedingLengthOf(100);
|
baseDataValidator.reset().parameter(NAME).value(name).notBlank().notExceedingLengthOf(100);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (this.fromApiJsonHelper.parameterExists("openingDate", element)) {
|
if (this.fromApiJsonHelper.parameterExists(OPENING_DATE, element)) {
|
||||||
final LocalDate openingDate = this.fromApiJsonHelper.extractLocalDateNamed("openingDate", element);
|
final LocalDate openingDate = this.fromApiJsonHelper.extractLocalDateNamed(OPENING_DATE, element);
|
||||||
baseDataValidator.reset().parameter("openingDate").value(openingDate).notNull();
|
baseDataValidator.reset().parameter(OPENING_DATE).value(openingDate).notNull();
|
||||||
}
|
}
|
||||||
|
|
||||||
if (this.fromApiJsonHelper.parameterExists("externalId", element)) {
|
if (this.fromApiJsonHelper.parameterExists(EXTERNAL_ID, element)) {
|
||||||
final String externalId = this.fromApiJsonHelper.extractStringNamed("externalId", element);
|
final String externalId = this.fromApiJsonHelper.extractStringNamed(EXTERNAL_ID, element);
|
||||||
baseDataValidator.reset().parameter("externalId").value(externalId).notExceedingLengthOf(100);
|
baseDataValidator.reset().parameter(EXTERNAL_ID).value(externalId).notExceedingLengthOf(100);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (this.fromApiJsonHelper.parameterExists("parentId", element)) {
|
if (this.fromApiJsonHelper.parameterExists(PARENT_ID, element)) {
|
||||||
final Long parentId = this.fromApiJsonHelper.extractLongNamed("parentId", element);
|
final Long parentId = this.fromApiJsonHelper.extractLongNamed(PARENT_ID, element);
|
||||||
baseDataValidator.reset().parameter("parentId").value(parentId).notNull().integerGreaterThanZero();
|
baseDataValidator.reset().parameter(PARENT_ID).value(parentId).notNull().integerGreaterThanZero();
|
||||||
}
|
}
|
||||||
|
|
||||||
throwExceptionIfValidationWarningsExist(dataValidationErrors);
|
throwExceptionIfValidationWarningsExist(dataValidationErrors);
|
||||||
|
|||||||
+28
-18
@@ -41,11 +41,19 @@ import org.springframework.stereotype.Component;
|
|||||||
@Component
|
@Component
|
||||||
public final class OfficeTransactionCommandFromApiJsonDeserializer {
|
public final class OfficeTransactionCommandFromApiJsonDeserializer {
|
||||||
|
|
||||||
|
public static final String FROM_OFFICE_ID = "fromOfficeId";
|
||||||
|
public static final String TO_OFFICE_ID = "toOfficeId";
|
||||||
|
public static final String TRANSACTION_DATE = "transactionDate";
|
||||||
|
public static final String CURRENCY_CODE = "currencyCode";
|
||||||
|
public static final String TRANSACTION_AMOUNT = "transactionAmount";
|
||||||
|
public static final String DESCRIPTION = "description";
|
||||||
|
public static final String LOCALE = "locale";
|
||||||
|
public static final String DATE_FORMAT = "dateFormat";
|
||||||
/**
|
/**
|
||||||
* The parameters supported for this command.
|
* The parameters supported for this command.
|
||||||
*/
|
*/
|
||||||
private final Set<String> supportedParameters = new HashSet<>(Arrays.asList("fromOfficeId", "toOfficeId", "transactionDate",
|
private static final Set<String> SUPPORTED_PARAMETERS = new HashSet<>(Arrays.asList(FROM_OFFICE_ID, TO_OFFICE_ID, TRANSACTION_DATE,
|
||||||
"currencyCode", "transactionAmount", "description", "locale", "dateFormat"));
|
CURRENCY_CODE, TRANSACTION_AMOUNT, DESCRIPTION, LOCALE, DATE_FORMAT));
|
||||||
|
|
||||||
private final FromJsonHelper fromApiJsonHelper;
|
private final FromJsonHelper fromApiJsonHelper;
|
||||||
|
|
||||||
@@ -59,38 +67,40 @@ public final class OfficeTransactionCommandFromApiJsonDeserializer {
|
|||||||
throw new InvalidJsonException();
|
throw new InvalidJsonException();
|
||||||
}
|
}
|
||||||
|
|
||||||
final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType();
|
final Type typeOfMap = new TypeToken<Map<String, Object>>() {
|
||||||
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParameters);
|
|
||||||
|
}.getType();
|
||||||
|
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, SUPPORTED_PARAMETERS);
|
||||||
|
|
||||||
final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
|
final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
|
||||||
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("officeTransaction");
|
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("officeTransaction");
|
||||||
|
|
||||||
final JsonElement element = this.fromApiJsonHelper.parse(json);
|
final JsonElement element = this.fromApiJsonHelper.parse(json);
|
||||||
final Long fromOfficeId = this.fromApiJsonHelper.extractLongNamed("fromOfficeId", element);
|
final Long fromOfficeId = this.fromApiJsonHelper.extractLongNamed(FROM_OFFICE_ID, element);
|
||||||
baseDataValidator.reset().parameter("fromOfficeId").value(fromOfficeId).ignoreIfNull().integerGreaterThanZero();
|
baseDataValidator.reset().parameter(FROM_OFFICE_ID).value(fromOfficeId).ignoreIfNull().integerGreaterThanZero();
|
||||||
|
|
||||||
final Long toOfficeId = this.fromApiJsonHelper.extractLongNamed("toOfficeId", element);
|
final Long toOfficeId = this.fromApiJsonHelper.extractLongNamed(TO_OFFICE_ID, element);
|
||||||
baseDataValidator.reset().parameter("toOfficeId").value(toOfficeId).ignoreIfNull().integerGreaterThanZero();
|
baseDataValidator.reset().parameter(TO_OFFICE_ID).value(toOfficeId).ignoreIfNull().integerGreaterThanZero();
|
||||||
|
|
||||||
if (fromOfficeId == null && toOfficeId == null) {
|
if (fromOfficeId == null && toOfficeId == null) {
|
||||||
baseDataValidator.reset().parameter("toOfficeId").value(toOfficeId).notNull();
|
baseDataValidator.reset().parameter(TO_OFFICE_ID).value(toOfficeId).notNull();
|
||||||
}
|
}
|
||||||
|
|
||||||
if (fromOfficeId != null && toOfficeId != null) {
|
if (fromOfficeId != null && toOfficeId != null) {
|
||||||
baseDataValidator.reset().parameter("fromOfficeId").value(fromOfficeId).notSameAsParameter("toOfficeId", toOfficeId);
|
baseDataValidator.reset().parameter(FROM_OFFICE_ID).value(fromOfficeId).notSameAsParameter(TO_OFFICE_ID, toOfficeId);
|
||||||
}
|
}
|
||||||
|
|
||||||
final LocalDate transactionDate = this.fromApiJsonHelper.extractLocalDateNamed("transactionDate", element);
|
final LocalDate transactionDate = this.fromApiJsonHelper.extractLocalDateNamed(TRANSACTION_DATE, element);
|
||||||
baseDataValidator.reset().parameter("transactionDate").value(transactionDate).notNull();
|
baseDataValidator.reset().parameter(TRANSACTION_DATE).value(transactionDate).notNull();
|
||||||
|
|
||||||
final String currencyCode = this.fromApiJsonHelper.extractStringNamed("currencyCode", element);
|
final String currencyCode = this.fromApiJsonHelper.extractStringNamed(CURRENCY_CODE, element);
|
||||||
baseDataValidator.reset().parameter("currencyCode").value(currencyCode).notBlank().notExceedingLengthOf(3);
|
baseDataValidator.reset().parameter(CURRENCY_CODE).value(currencyCode).notBlank().notExceedingLengthOf(3);
|
||||||
|
|
||||||
final BigDecimal transactionAmount = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed("transactionAmount", element);
|
final BigDecimal transactionAmount = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed(TRANSACTION_AMOUNT, element);
|
||||||
baseDataValidator.reset().parameter("transactionAmount").value(transactionAmount).notNull().positiveAmount();
|
baseDataValidator.reset().parameter(TRANSACTION_AMOUNT).value(transactionAmount).notNull().positiveAmount();
|
||||||
|
|
||||||
final String description = this.fromApiJsonHelper.extractStringNamed("description", element);
|
final String description = this.fromApiJsonHelper.extractStringNamed(DESCRIPTION, element);
|
||||||
baseDataValidator.reset().parameter("description").value(description).notExceedingLengthOf(100);
|
baseDataValidator.reset().parameter(DESCRIPTION).value(description).notExceedingLengthOf(100);
|
||||||
|
|
||||||
throwExceptionIfValidationWarningsExist(dataValidationErrors);
|
throwExceptionIfValidationWarningsExist(dataValidationErrors);
|
||||||
}
|
}
|
||||||
|
|||||||
+19
-13
@@ -39,11 +39,13 @@ import org.springframework.stereotype.Component;
|
|||||||
@Component
|
@Component
|
||||||
public class ProvisioningCategoryDefinitionJsonDeserializer {
|
public class ProvisioningCategoryDefinitionJsonDeserializer {
|
||||||
|
|
||||||
|
public static final String CATEGORYNAME = "categoryname";
|
||||||
|
public static final String CATEGORYDESCRIPTION = "categorydescription";
|
||||||
|
public static final String PROVISIONINGCATEGORIES = "provisioningcategories";
|
||||||
/**
|
/**
|
||||||
* The parameters supported for this command.
|
* The parameters supported for this command.
|
||||||
*/
|
*/
|
||||||
private final Set<String> supportedParameters = new HashSet<>(Arrays.asList("categoryname", "categorydescription"));
|
private static final Set<String> SUPPORTED_PARAMETERS = new HashSet<>(Arrays.asList(CATEGORYNAME, CATEGORYDESCRIPTION));
|
||||||
|
|
||||||
private final FromJsonHelper fromApiJsonHelper;
|
private final FromJsonHelper fromApiJsonHelper;
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
@@ -55,15 +57,17 @@ public class ProvisioningCategoryDefinitionJsonDeserializer {
|
|||||||
if (StringUtils.isBlank(json)) {
|
if (StringUtils.isBlank(json)) {
|
||||||
throw new InvalidJsonException();
|
throw new InvalidJsonException();
|
||||||
}
|
}
|
||||||
final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType();
|
final Type typeOfMap = new TypeToken<Map<String, Object>>() {
|
||||||
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParameters);
|
|
||||||
|
}.getType();
|
||||||
|
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, SUPPORTED_PARAMETERS);
|
||||||
|
|
||||||
final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
|
final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
|
||||||
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("provisioningcategories");
|
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource(PROVISIONINGCATEGORIES);
|
||||||
final JsonElement element = this.fromApiJsonHelper.parse(json);
|
final JsonElement element = this.fromApiJsonHelper.parse(json);
|
||||||
|
|
||||||
final String name = this.fromApiJsonHelper.extractStringNamed("categoryname", element);
|
final String name = this.fromApiJsonHelper.extractStringNamed(CATEGORYNAME, element);
|
||||||
baseDataValidator.reset().parameter("categoryname").value(name).notBlank().notExceedingLengthOf(100);
|
baseDataValidator.reset().parameter(CATEGORYNAME).value(name).notBlank().notExceedingLengthOf(100);
|
||||||
if (!dataValidationErrors.isEmpty()) {
|
if (!dataValidationErrors.isEmpty()) {
|
||||||
throw new PlatformApiDataValidationException(dataValidationErrors);
|
throw new PlatformApiDataValidationException(dataValidationErrors);
|
||||||
}
|
}
|
||||||
@@ -73,16 +77,18 @@ public class ProvisioningCategoryDefinitionJsonDeserializer {
|
|||||||
if (StringUtils.isBlank(json)) {
|
if (StringUtils.isBlank(json)) {
|
||||||
throw new InvalidJsonException();
|
throw new InvalidJsonException();
|
||||||
}
|
}
|
||||||
final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType();
|
final Type typeOfMap = new TypeToken<Map<String, Object>>() {
|
||||||
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParameters);
|
|
||||||
|
}.getType();
|
||||||
|
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, SUPPORTED_PARAMETERS);
|
||||||
|
|
||||||
final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
|
final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
|
||||||
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("provisioningcategories");
|
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource(PROVISIONINGCATEGORIES);
|
||||||
final JsonElement element = this.fromApiJsonHelper.parse(json);
|
final JsonElement element = this.fromApiJsonHelper.parse(json);
|
||||||
|
|
||||||
if (this.fromApiJsonHelper.parameterExists("categoryname", element)) {
|
if (this.fromApiJsonHelper.parameterExists(CATEGORYNAME, element)) {
|
||||||
final String categoryName = this.fromApiJsonHelper.extractStringNamed("categoryname", element);
|
final String categoryName = this.fromApiJsonHelper.extractStringNamed(CATEGORYNAME, element);
|
||||||
baseDataValidator.reset().parameter("categoryname").value(categoryName).notBlank().notExceedingLengthOf(100);
|
baseDataValidator.reset().parameter(CATEGORYNAME).value(categoryName).notBlank().notExceedingLengthOf(100);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!dataValidationErrors.isEmpty()) {
|
if (!dataValidationErrors.isEmpty()) {
|
||||||
|
|||||||
+7
-7
@@ -76,10 +76,10 @@ public class StaffApiResource {
|
|||||||
/**
|
/**
|
||||||
* The set of parameters that are supported in response for {@link StaffData}.
|
* The set of parameters that are supported in response for {@link StaffData}.
|
||||||
*/
|
*/
|
||||||
private final Set<String> responseDataParameters = new HashSet<>(Arrays.asList("id", "firstname", "lastname", "displayName", "officeId",
|
private static final Set<String> RESPONSE_DATA_PARAMETERS = new HashSet<>(Arrays.asList("id", "firstname", "lastname", "displayName",
|
||||||
"officeName", "isLoanOfficer", "externalId", "mobileNo", "allowedOffices", "isActive", "joiningDate"));
|
"officeId", "officeName", "isLoanOfficer", "externalId", "mobileNo", "allowedOffices", "isActive", "joiningDate"));
|
||||||
|
|
||||||
private final String resourceNameForPermissions = "STAFF";
|
private static final String RESOURCE_NAME_FOR_PERMISSIONS = "STAFF";
|
||||||
|
|
||||||
private final PlatformSecurityContext context;
|
private final PlatformSecurityContext context;
|
||||||
private final StaffReadPlatformService readPlatformService;
|
private final StaffReadPlatformService readPlatformService;
|
||||||
@@ -123,7 +123,7 @@ public class StaffApiResource {
|
|||||||
@DefaultValue("false") @QueryParam("loanOfficersOnly") @Parameter(description = "loanOfficersOnly") final boolean loanOfficersOnly,
|
@DefaultValue("false") @QueryParam("loanOfficersOnly") @Parameter(description = "loanOfficersOnly") final boolean loanOfficersOnly,
|
||||||
@DefaultValue("active") @QueryParam("status") @Parameter(description = "status") final String status) {
|
@DefaultValue("active") @QueryParam("status") @Parameter(description = "status") final String status) {
|
||||||
|
|
||||||
this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions);
|
this.context.authenticatedUser().validateHasReadPermission(RESOURCE_NAME_FOR_PERMISSIONS);
|
||||||
|
|
||||||
final Collection<StaffData> staff;
|
final Collection<StaffData> staff;
|
||||||
if (staffInOfficeHierarchy) {
|
if (staffInOfficeHierarchy) {
|
||||||
@@ -133,7 +133,7 @@ public class StaffApiResource {
|
|||||||
}
|
}
|
||||||
|
|
||||||
final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters());
|
final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters());
|
||||||
return this.toApiJsonSerializer.serialize(settings, staff, this.responseDataParameters);
|
return this.toApiJsonSerializer.serialize(settings, staff, RESPONSE_DATA_PARAMETERS);
|
||||||
}
|
}
|
||||||
|
|
||||||
@POST
|
@POST
|
||||||
@@ -164,7 +164,7 @@ public class StaffApiResource {
|
|||||||
public String retrieveOne(@PathParam("staffId") @Parameter(description = "staffId") final Long staffId,
|
public String retrieveOne(@PathParam("staffId") @Parameter(description = "staffId") final Long staffId,
|
||||||
@Context final UriInfo uriInfo) {
|
@Context final UriInfo uriInfo) {
|
||||||
|
|
||||||
this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions);
|
this.context.authenticatedUser().validateHasReadPermission(RESOURCE_NAME_FOR_PERMISSIONS);
|
||||||
|
|
||||||
final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters());
|
final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters());
|
||||||
|
|
||||||
@@ -173,7 +173,7 @@ public class StaffApiResource {
|
|||||||
final Collection<OfficeData> allowedOffices = this.officeReadPlatformService.retrieveAllOfficesForDropdown();
|
final Collection<OfficeData> allowedOffices = this.officeReadPlatformService.retrieveAllOfficesForDropdown();
|
||||||
staff = StaffData.templateData(staff, allowedOffices);
|
staff = StaffData.templateData(staff, allowedOffices);
|
||||||
}
|
}
|
||||||
return this.toApiJsonSerializer.serialize(settings, staff, this.responseDataParameters);
|
return this.toApiJsonSerializer.serialize(settings, staff, RESPONSE_DATA_PARAMETERS);
|
||||||
}
|
}
|
||||||
|
|
||||||
@PUT
|
@PUT
|
||||||
|
|||||||
+74
-59
@@ -42,11 +42,22 @@ import org.springframework.stereotype.Component;
|
|||||||
@Component
|
@Component
|
||||||
public final class StaffCommandFromApiJsonDeserializer {
|
public final class StaffCommandFromApiJsonDeserializer {
|
||||||
|
|
||||||
|
public static final String FIRSTNAME = "firstname";
|
||||||
|
public static final String LASTNAME = "lastname";
|
||||||
|
public static final String OFFICE_ID = "officeId";
|
||||||
|
public static final String EXTERNAL_ID = "externalId";
|
||||||
|
public static final String MOBILE_NO = "mobileNo";
|
||||||
|
public static final String IS_LOAN_OFFICER = "isLoanOfficer";
|
||||||
|
public static final String IS_ACTIVE = "isActive";
|
||||||
|
public static final String JOINING_DATE = "joiningDate";
|
||||||
|
public static final String DATE_FORMAT = "dateFormat";
|
||||||
|
public static final String LOCALE = "locale";
|
||||||
|
public static final String FORCE_STATUS = "forceStatus";
|
||||||
/**
|
/**
|
||||||
* The parameters supported for this command.
|
* The parameters supported for this command.
|
||||||
*/
|
*/
|
||||||
private final Set<String> supportedParameters = new HashSet<>(Arrays.asList("firstname", "lastname", "officeId", "externalId",
|
private static final Set<String> SUPPORTED_PARAMETERS = new HashSet<>(Arrays.asList(FIRSTNAME, LASTNAME, OFFICE_ID, EXTERNAL_ID,
|
||||||
"mobileNo", "isLoanOfficer", "isActive", "joiningDate", "dateFormat", "locale", "forceStatus"));
|
MOBILE_NO, IS_LOAN_OFFICER, IS_ACTIVE, JOINING_DATE, DATE_FORMAT, LOCALE, FORCE_STATUS));
|
||||||
|
|
||||||
private final FromJsonHelper fromApiJsonHelper;
|
private final FromJsonHelper fromApiJsonHelper;
|
||||||
|
|
||||||
@@ -64,22 +75,24 @@ public final class StaffCommandFromApiJsonDeserializer {
|
|||||||
throw new InvalidJsonException();
|
throw new InvalidJsonException();
|
||||||
}
|
}
|
||||||
|
|
||||||
final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType();
|
final Type typeOfMap = new TypeToken<Map<String, Object>>() {
|
||||||
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParameters);
|
|
||||||
|
}.getType();
|
||||||
|
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, SUPPORTED_PARAMETERS);
|
||||||
|
|
||||||
final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
|
final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
|
||||||
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("staff");
|
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("staff");
|
||||||
|
|
||||||
final JsonElement element = this.fromApiJsonHelper.parse(json);
|
final JsonElement element = this.fromApiJsonHelper.parse(json);
|
||||||
|
|
||||||
final Long officeId = this.fromApiJsonHelper.extractLongNamed("officeId", element);
|
final Long officeId = this.fromApiJsonHelper.extractLongNamed(OFFICE_ID, element);
|
||||||
baseDataValidator.reset().parameter("officeId").value(officeId).notNull().integerGreaterThanZero();
|
baseDataValidator.reset().parameter(OFFICE_ID).value(officeId).notNull().integerGreaterThanZero();
|
||||||
|
|
||||||
final String firstname = this.fromApiJsonHelper.extractStringNamed("firstname", element);
|
final String firstname = this.fromApiJsonHelper.extractStringNamed(FIRSTNAME, element);
|
||||||
baseDataValidator.reset().parameter("firstname").value(firstname).notBlank().notExceedingLengthOf(50);
|
baseDataValidator.reset().parameter(FIRSTNAME).value(firstname).notBlank().notExceedingLengthOf(50);
|
||||||
|
|
||||||
final String lastname = this.fromApiJsonHelper.extractStringNamed("lastname", element);
|
final String lastname = this.fromApiJsonHelper.extractStringNamed(LASTNAME, element);
|
||||||
baseDataValidator.reset().parameter("lastname").value(lastname).notBlank().notExceedingLengthOf(50);
|
baseDataValidator.reset().parameter(LASTNAME).value(lastname).notBlank().notExceedingLengthOf(50);
|
||||||
|
|
||||||
if (this.fromApiJsonHelper.parameterExists(ClientApiConstants.mobileNoParamName, element)) {
|
if (this.fromApiJsonHelper.parameterExists(ClientApiConstants.mobileNoParamName, element)) {
|
||||||
final String mobileNo = this.fromApiJsonHelper.extractStringNamed(ClientApiConstants.mobileNoParamName, element);
|
final String mobileNo = this.fromApiJsonHelper.extractStringNamed(ClientApiConstants.mobileNoParamName, element);
|
||||||
@@ -87,32 +100,32 @@ public final class StaffCommandFromApiJsonDeserializer {
|
|||||||
.notExceedingLengthOf(50);
|
.notExceedingLengthOf(50);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (this.fromApiJsonHelper.parameterExists("isLoanOfficer", element)) {
|
if (this.fromApiJsonHelper.parameterExists(IS_LOAN_OFFICER, element)) {
|
||||||
final String loanOfficerFlag = this.fromApiJsonHelper.extractStringNamed("isLoanOfficer", element);
|
final String loanOfficerFlag = this.fromApiJsonHelper.extractStringNamed(IS_LOAN_OFFICER, element);
|
||||||
baseDataValidator.reset().parameter("isLoanOfficer").trueOrFalseRequired(loanOfficerFlag);
|
baseDataValidator.reset().parameter(IS_LOAN_OFFICER).trueOrFalseRequired(loanOfficerFlag);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (this.fromApiJsonHelper.parameterExists("isActive", element)) {
|
if (this.fromApiJsonHelper.parameterExists(IS_ACTIVE, element)) {
|
||||||
final String activeFlag = this.fromApiJsonHelper.extractStringNamed("isActive", element);
|
final String activeFlag = this.fromApiJsonHelper.extractStringNamed(IS_ACTIVE, element);
|
||||||
baseDataValidator.reset().parameter("isActive").trueOrFalseRequired(activeFlag);
|
baseDataValidator.reset().parameter(IS_ACTIVE).trueOrFalseRequired(activeFlag);
|
||||||
}
|
}
|
||||||
|
|
||||||
final LocalDate joiningDate = this.fromApiJsonHelper.extractLocalDateNamed("joiningDate", element);
|
final LocalDate joiningDate = this.fromApiJsonHelper.extractLocalDateNamed(JOINING_DATE, element);
|
||||||
baseDataValidator.reset().parameter("joiningDate").value(joiningDate).notNull();
|
baseDataValidator.reset().parameter(JOINING_DATE).value(joiningDate).notNull();
|
||||||
|
|
||||||
if (this.fromApiJsonHelper.parameterExists("dateFormat", element)) {
|
if (this.fromApiJsonHelper.parameterExists(DATE_FORMAT, element)) {
|
||||||
final String dateFormat = this.fromApiJsonHelper.extractStringNamed("dateFormat", element);
|
final String dateFormat = this.fromApiJsonHelper.extractStringNamed(DATE_FORMAT, element);
|
||||||
baseDataValidator.reset().parameter("dateFormat").value(dateFormat).notBlank();
|
baseDataValidator.reset().parameter(DATE_FORMAT).value(dateFormat).notBlank();
|
||||||
}
|
}
|
||||||
|
|
||||||
if (this.fromApiJsonHelper.parameterExists("locale", element)) {
|
if (this.fromApiJsonHelper.parameterExists(LOCALE, element)) {
|
||||||
final String locale = this.fromApiJsonHelper.extractStringNamed("locale", element);
|
final String locale = this.fromApiJsonHelper.extractStringNamed(LOCALE, element);
|
||||||
baseDataValidator.reset().parameter("locale").value(locale).notBlank();
|
baseDataValidator.reset().parameter(LOCALE).value(locale).notBlank();
|
||||||
}
|
}
|
||||||
|
|
||||||
if (this.fromApiJsonHelper.parameterExists("externalId", element)) {
|
if (this.fromApiJsonHelper.parameterExists(EXTERNAL_ID, element)) {
|
||||||
final String externalId = this.fromApiJsonHelper.extractStringNamed("externalId", element);
|
final String externalId = this.fromApiJsonHelper.extractStringNamed(EXTERNAL_ID, element);
|
||||||
baseDataValidator.reset().parameter("externalId").value(externalId).notBlank().notExceedingLengthOf(100);
|
baseDataValidator.reset().parameter(EXTERNAL_ID).value(externalId).notBlank().notExceedingLengthOf(100);
|
||||||
}
|
}
|
||||||
|
|
||||||
throwExceptionIfValidationWarningsExist(dataValidationErrors);
|
throwExceptionIfValidationWarningsExist(dataValidationErrors);
|
||||||
@@ -127,26 +140,28 @@ public final class StaffCommandFromApiJsonDeserializer {
|
|||||||
throw new InvalidJsonException();
|
throw new InvalidJsonException();
|
||||||
}
|
}
|
||||||
|
|
||||||
final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType();
|
final Type typeOfMap = new TypeToken<Map<String, Object>>() {
|
||||||
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParameters);
|
|
||||||
|
}.getType();
|
||||||
|
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, SUPPORTED_PARAMETERS);
|
||||||
|
|
||||||
final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
|
final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
|
||||||
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("staff");
|
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("staff");
|
||||||
|
|
||||||
final JsonElement element = this.fromApiJsonHelper.parse(json);
|
final JsonElement element = this.fromApiJsonHelper.parse(json);
|
||||||
if (this.fromApiJsonHelper.parameterExists("officeId", element)) {
|
if (this.fromApiJsonHelper.parameterExists(OFFICE_ID, element)) {
|
||||||
final Long officeId = this.fromApiJsonHelper.extractLongNamed("officeId", element);
|
final Long officeId = this.fromApiJsonHelper.extractLongNamed(OFFICE_ID, element);
|
||||||
baseDataValidator.reset().parameter("officeId").value(officeId).notNull().integerGreaterThanZero();
|
baseDataValidator.reset().parameter(OFFICE_ID).value(officeId).notNull().integerGreaterThanZero();
|
||||||
}
|
}
|
||||||
|
|
||||||
if (this.fromApiJsonHelper.parameterExists("firstname", element)) {
|
if (this.fromApiJsonHelper.parameterExists(FIRSTNAME, element)) {
|
||||||
final String firstname = this.fromApiJsonHelper.extractStringNamed("firstname", element);
|
final String firstname = this.fromApiJsonHelper.extractStringNamed(FIRSTNAME, element);
|
||||||
baseDataValidator.reset().parameter("firstname").value(firstname).notBlank().notExceedingLengthOf(50);
|
baseDataValidator.reset().parameter(FIRSTNAME).value(firstname).notBlank().notExceedingLengthOf(50);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (this.fromApiJsonHelper.parameterExists("lastname", element)) {
|
if (this.fromApiJsonHelper.parameterExists(LASTNAME, element)) {
|
||||||
final String lastname = this.fromApiJsonHelper.extractStringNamed("lastname", element);
|
final String lastname = this.fromApiJsonHelper.extractStringNamed(LASTNAME, element);
|
||||||
baseDataValidator.reset().parameter("lastname").value(lastname).notBlank().notExceedingLengthOf(50);
|
baseDataValidator.reset().parameter(LASTNAME).value(lastname).notBlank().notExceedingLengthOf(50);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (this.fromApiJsonHelper.parameterExists(ClientApiConstants.mobileNoParamName, element)) {
|
if (this.fromApiJsonHelper.parameterExists(ClientApiConstants.mobileNoParamName, element)) {
|
||||||
@@ -154,21 +169,21 @@ public final class StaffCommandFromApiJsonDeserializer {
|
|||||||
baseDataValidator.reset().parameter(ClientApiConstants.mobileNoParamName).value(mobileNo).notExceedingLengthOf(50);
|
baseDataValidator.reset().parameter(ClientApiConstants.mobileNoParamName).value(mobileNo).notExceedingLengthOf(50);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (this.fromApiJsonHelper.parameterExists("isLoanOfficer", element)) {
|
if (this.fromApiJsonHelper.parameterExists(IS_LOAN_OFFICER, element)) {
|
||||||
final String loanOfficerFlag = this.fromApiJsonHelper.extractStringNamed("isLoanOfficer", element);
|
final String loanOfficerFlag = this.fromApiJsonHelper.extractStringNamed(IS_LOAN_OFFICER, element);
|
||||||
baseDataValidator.reset().parameter("isLoanOfficer").trueOrFalseRequired(loanOfficerFlag);
|
baseDataValidator.reset().parameter(IS_LOAN_OFFICER).trueOrFalseRequired(loanOfficerFlag);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (this.fromApiJsonHelper.parameterExists("isActive", element)) {
|
if (this.fromApiJsonHelper.parameterExists(IS_ACTIVE, element)) {
|
||||||
final String activeFlagStr = this.fromApiJsonHelper.extractStringNamed("isActive", element);
|
final String activeFlagStr = this.fromApiJsonHelper.extractStringNamed(IS_ACTIVE, element);
|
||||||
baseDataValidator.reset().parameter("isActive").trueOrFalseRequired(activeFlagStr);
|
baseDataValidator.reset().parameter(IS_ACTIVE).trueOrFalseRequired(activeFlagStr);
|
||||||
|
|
||||||
final Boolean activeFlag = this.fromApiJsonHelper.extractBooleanNamed("isActive", element);
|
final Boolean activeFlag = this.fromApiJsonHelper.extractBooleanNamed(IS_ACTIVE, element);
|
||||||
|
|
||||||
// Need to add here check to see if any clients, group, account and
|
// Need to add here check to see if any clients, group, account and
|
||||||
// loans are assigned to this staff if staff is being set to
|
// loans are assigned to this staff if staff is being set to
|
||||||
// inactive --LJB
|
// inactive --LJB
|
||||||
final Boolean forceStatus = this.fromApiJsonHelper.extractBooleanNamed("forceStatus", element);
|
final Boolean forceStatus = this.fromApiJsonHelper.extractBooleanNamed(FORCE_STATUS, element);
|
||||||
if ((!activeFlag && forceStatus == null) || (!activeFlag && forceStatus)) {
|
if ((!activeFlag && forceStatus == null) || (!activeFlag && forceStatus)) {
|
||||||
Object[] result = staffReadPlatformService.hasAssociatedItems(staffId);
|
Object[] result = staffReadPlatformService.hasAssociatedItems(staffId);
|
||||||
|
|
||||||
@@ -177,27 +192,27 @@ public final class StaffCommandFromApiJsonDeserializer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
baseDataValidator.reset().parameter("isActive").value(activeFlag).notNull();
|
baseDataValidator.reset().parameter(IS_ACTIVE).value(activeFlag).notNull();
|
||||||
}
|
}
|
||||||
|
|
||||||
if (this.fromApiJsonHelper.parameterExists("joiningDate", element)) {
|
if (this.fromApiJsonHelper.parameterExists(JOINING_DATE, element)) {
|
||||||
final LocalDate joiningDate = this.fromApiJsonHelper.extractLocalDateNamed("joiningDate", element);
|
final LocalDate joiningDate = this.fromApiJsonHelper.extractLocalDateNamed(JOINING_DATE, element);
|
||||||
baseDataValidator.reset().parameter("joiningDate").value(joiningDate).notNull();
|
baseDataValidator.reset().parameter(JOINING_DATE).value(joiningDate).notNull();
|
||||||
}
|
}
|
||||||
|
|
||||||
if (this.fromApiJsonHelper.parameterExists("dateFormat", element)) {
|
if (this.fromApiJsonHelper.parameterExists(DATE_FORMAT, element)) {
|
||||||
final String dateFormat = this.fromApiJsonHelper.extractStringNamed("dateFormat", element);
|
final String dateFormat = this.fromApiJsonHelper.extractStringNamed(DATE_FORMAT, element);
|
||||||
baseDataValidator.reset().parameter("dateFormat").value(dateFormat).notBlank();
|
baseDataValidator.reset().parameter(DATE_FORMAT).value(dateFormat).notBlank();
|
||||||
}
|
}
|
||||||
|
|
||||||
if (this.fromApiJsonHelper.parameterExists("locale", element)) {
|
if (this.fromApiJsonHelper.parameterExists(LOCALE, element)) {
|
||||||
final String locale = this.fromApiJsonHelper.extractStringNamed("locale", element);
|
final String locale = this.fromApiJsonHelper.extractStringNamed(LOCALE, element);
|
||||||
baseDataValidator.reset().parameter("locale").value(locale).notBlank();
|
baseDataValidator.reset().parameter(LOCALE).value(locale).notBlank();
|
||||||
}
|
}
|
||||||
|
|
||||||
if (this.fromApiJsonHelper.parameterExists("externalId", element)) {
|
if (this.fromApiJsonHelper.parameterExists(EXTERNAL_ID, element)) {
|
||||||
final String externalId = this.fromApiJsonHelper.extractStringNamed("externalId", element);
|
final String externalId = this.fromApiJsonHelper.extractStringNamed(EXTERNAL_ID, element);
|
||||||
baseDataValidator.reset().parameter("externalId").value(externalId).notBlank().notExceedingLengthOf(100);
|
baseDataValidator.reset().parameter(EXTERNAL_ID).value(externalId).notBlank().notExceedingLengthOf(100);
|
||||||
}
|
}
|
||||||
|
|
||||||
throwExceptionIfValidationWarningsExist(dataValidationErrors);
|
throwExceptionIfValidationWarningsExist(dataValidationErrors);
|
||||||
|
|||||||
+12
-16
@@ -28,7 +28,6 @@ import java.util.Map;
|
|||||||
import org.apache.fineract.infrastructure.core.domain.JdbcSupport;
|
import org.apache.fineract.infrastructure.core.domain.JdbcSupport;
|
||||||
import org.apache.fineract.infrastructure.core.exception.UnrecognizedQueryParamException;
|
import org.apache.fineract.infrastructure.core.exception.UnrecognizedQueryParamException;
|
||||||
import org.apache.fineract.infrastructure.security.service.PlatformSecurityContext;
|
import org.apache.fineract.infrastructure.security.service.PlatformSecurityContext;
|
||||||
import org.apache.fineract.infrastructure.security.utils.ColumnValidator;
|
|
||||||
import org.apache.fineract.infrastructure.security.utils.SQLBuilder;
|
import org.apache.fineract.infrastructure.security.utils.SQLBuilder;
|
||||||
import org.apache.fineract.organisation.staff.data.StaffData;
|
import org.apache.fineract.organisation.staff.data.StaffData;
|
||||||
import org.apache.fineract.organisation.staff.exception.StaffNotFoundException;
|
import org.apache.fineract.organisation.staff.exception.StaffNotFoundException;
|
||||||
@@ -46,16 +45,13 @@ public class StaffReadPlatformServiceImpl implements StaffReadPlatformService {
|
|||||||
|
|
||||||
private final JdbcTemplate jdbcTemplate;
|
private final JdbcTemplate jdbcTemplate;
|
||||||
private final PlatformSecurityContext context;
|
private final PlatformSecurityContext context;
|
||||||
private final StaffLookupMapper lookupMapper = new StaffLookupMapper();
|
private static final StaffLookupMapper LOOKUP_MAPPER = new StaffLookupMapper();
|
||||||
private final StaffInOfficeHierarchyMapper staffInOfficeHierarchyMapper = new StaffInOfficeHierarchyMapper();
|
private static final StaffInOfficeHierarchyMapper STAFF_IN_OFFICE_HIERARCHY_MAPPER = new StaffInOfficeHierarchyMapper();
|
||||||
private final ColumnValidator columnValidator;
|
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
public StaffReadPlatformServiceImpl(final PlatformSecurityContext context, final JdbcTemplate jdbcTemplate,
|
public StaffReadPlatformServiceImpl(final PlatformSecurityContext context, final JdbcTemplate jdbcTemplate) {
|
||||||
final ColumnValidator columnValidator) {
|
|
||||||
this.context = context;
|
this.context = context;
|
||||||
this.jdbcTemplate = jdbcTemplate;
|
this.jdbcTemplate = jdbcTemplate;
|
||||||
this.columnValidator = columnValidator;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private static final class StaffMapper implements RowMapper<StaffData> {
|
private static final class StaffMapper implements RowMapper<StaffData> {
|
||||||
@@ -174,9 +170,9 @@ public class StaffReadPlatformServiceImpl implements StaffReadPlatformService {
|
|||||||
|
|
||||||
final Long defaultOfficeId = defaultToUsersOfficeIfNull(officeId);
|
final Long defaultOfficeId = defaultToUsersOfficeIfNull(officeId);
|
||||||
|
|
||||||
final String sql = "select " + this.lookupMapper.schema() + " where s.office_id = ? and s.is_active=true and o.hierarchy like ? ";
|
final String sql = "select " + LOOKUP_MAPPER.schema() + " where s.office_id = ? and s.is_active=true and o.hierarchy like ? ";
|
||||||
|
|
||||||
return this.jdbcTemplate.query(sql, this.lookupMapper, new Object[] { defaultOfficeId, hierarchy }); // NOSONAR
|
return this.jdbcTemplate.query(sql, LOOKUP_MAPPER, defaultOfficeId, hierarchy); // NOSONAR
|
||||||
}
|
}
|
||||||
|
|
||||||
private Long defaultToUsersOfficeIfNull(final Long officeId) {
|
private Long defaultToUsersOfficeIfNull(final Long officeId) {
|
||||||
@@ -199,7 +195,7 @@ public class StaffReadPlatformServiceImpl implements StaffReadPlatformService {
|
|||||||
final StaffMapper rm = new StaffMapper();
|
final StaffMapper rm = new StaffMapper();
|
||||||
final String sql = "select " + rm.schema() + " where s.id = ? and o.hierarchy like ? ";
|
final String sql = "select " + rm.schema() + " where s.id = ? and o.hierarchy like ? ";
|
||||||
|
|
||||||
return this.jdbcTemplate.queryForObject(sql, rm, new Object[] { staffId, hierarchy }); // NOSONAR
|
return this.jdbcTemplate.queryForObject(sql, rm, staffId, hierarchy); // NOSONAR
|
||||||
} catch (final EmptyResultDataAccessException e) {
|
} catch (final EmptyResultDataAccessException e) {
|
||||||
throw new StaffNotFoundException(staffId, e);
|
throw new StaffNotFoundException(staffId, e);
|
||||||
}
|
}
|
||||||
@@ -246,7 +242,7 @@ public class StaffReadPlatformServiceImpl implements StaffReadPlatformService {
|
|||||||
extraCriteria.addCriteria(" s.is_active =", false);
|
extraCriteria.addCriteria(" s.is_active =", false);
|
||||||
} else {
|
} else {
|
||||||
if (!status.equalsIgnoreCase("all")) {
|
if (!status.equalsIgnoreCase("all")) {
|
||||||
throw new UnrecognizedQueryParamException("status", status, new Object[] { "all", "active", "inactive" });
|
throw new UnrecognizedQueryParamException("status", status, "all", "active", "inactive");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -257,14 +253,14 @@ public class StaffReadPlatformServiceImpl implements StaffReadPlatformService {
|
|||||||
@Override
|
@Override
|
||||||
public Collection<StaffData> retrieveAllStaffInOfficeAndItsParentOfficeHierarchy(final Long officeId, final boolean loanOfficersOnly) {
|
public Collection<StaffData> retrieveAllStaffInOfficeAndItsParentOfficeHierarchy(final Long officeId, final boolean loanOfficersOnly) {
|
||||||
|
|
||||||
String sql = "select " + this.staffInOfficeHierarchyMapper.schema(loanOfficersOnly);
|
String sql = "select " + STAFF_IN_OFFICE_HIERARCHY_MAPPER.schema(loanOfficersOnly);
|
||||||
sql = sql + " order by s.lastname";
|
sql = sql + " order by s.lastname";
|
||||||
return this.jdbcTemplate.query(sql, this.staffInOfficeHierarchyMapper, new Object[] { officeId }); // NOSONAR
|
return this.jdbcTemplate.query(sql, STAFF_IN_OFFICE_HIERARCHY_MAPPER, officeId); // NOSONAR
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Object[] hasAssociatedItems(final Long staffId) {
|
public Object[] hasAssociatedItems(final Long staffId) {
|
||||||
ArrayList<String> params = new ArrayList<String>();
|
ArrayList<String> params = new ArrayList<>();
|
||||||
|
|
||||||
String sql = "select c.display_name as client, g.display_name as grp,l.loan_officer_id as loan, s.field_officer_id as sav"
|
String sql = "select c.display_name as client, g.display_name as grp,l.loan_officer_id as loan, s.field_officer_id as sav"
|
||||||
+ " from m_staff staff " + " left outer join m_client c on staff.id = c.staff_id AND c.status_enum < ? "
|
+ " from m_staff staff " + " left outer join m_client c on staff.id = c.staff_id AND c.status_enum < ? "
|
||||||
@@ -273,8 +269,8 @@ public class StaffReadPlatformServiceImpl implements StaffReadPlatformService {
|
|||||||
+ " left outer join m_savings_account s on c.staff_id = s.field_officer_id and s.status_enum < ? "
|
+ " left outer join m_savings_account s on c.staff_id = s.field_officer_id and s.status_enum < ? "
|
||||||
+ " where staff.id = ? " + " group by staff.id, client, grp, loan, sav";
|
+ " where staff.id = ? " + " group by staff.id, client, grp, loan, sav";
|
||||||
|
|
||||||
List<Map<String, Object>> result = this.jdbcTemplate.queryForList(sql, new Object[] { ClientStatus.CLOSED.getValue(),
|
List<Map<String, Object>> result = this.jdbcTemplate.queryForList(sql, ClientStatus.CLOSED.getValue(),
|
||||||
LoanStatus.WITHDRAWN_BY_CLIENT.getValue(), SavingsAccountStatusType.WITHDRAWN_BY_APPLICANT.getValue(), staffId });
|
LoanStatus.WITHDRAWN_BY_CLIENT.getValue(), SavingsAccountStatusType.WITHDRAWN_BY_APPLICANT.getValue(), staffId);
|
||||||
if (result != null) {
|
if (result != null) {
|
||||||
for (Map<String, Object> map : result) {
|
for (Map<String, Object> map : result) {
|
||||||
if (map.get("client") != null) {
|
if (map.get("client") != null) {
|
||||||
|
|||||||
+77
-53
@@ -46,13 +46,33 @@ import org.springframework.stereotype.Component;
|
|||||||
@Component
|
@Component
|
||||||
public final class TellerCommandFromApiJsonDeserializer {
|
public final class TellerCommandFromApiJsonDeserializer {
|
||||||
|
|
||||||
|
public static final String OFFICE_ID = "officeId";
|
||||||
|
public static final String NAME = "name";
|
||||||
|
public static final String DESCRIPTION = "description";
|
||||||
|
public static final String START_DATE = "startDate";
|
||||||
|
public static final String END_DATE = "endDate";
|
||||||
|
public static final String STATUS = "status";
|
||||||
|
public static final String DATE_FORMAT = "dateFormat";
|
||||||
|
public static final String LOCALE = "locale";
|
||||||
|
public static final String IS_FULL_DAY = "isFullDay";
|
||||||
|
public static final String STAFF_ID = "staffId";
|
||||||
|
public static final String ENTITY_TYPE = "entityType";
|
||||||
|
public static final String ENTITY_ID = "entityId";
|
||||||
|
public static final String CURRENCY_CODE = "currencyCode";
|
||||||
|
public static final String HOUR_START_TIME = "hourStartTime";
|
||||||
|
public static final String MIN_START_TIME = "minStartTime";
|
||||||
|
public static final String HOUR_END_TIME = "hourEndTime";
|
||||||
|
public static final String MIN_END_TIME = "minEndTime";
|
||||||
|
public static final String TXN_AMOUNT = "txnAmount";
|
||||||
|
public static final String TXN_DATE = "txnDate";
|
||||||
|
public static final String TXN_NOTE = "txnNote";
|
||||||
|
public static final String TELLER = "teller";
|
||||||
/**
|
/**
|
||||||
* The parameters supported for this command.
|
* The parameters supported for this command.
|
||||||
*/
|
*/
|
||||||
private final Set<String> supportedParameters = new HashSet<>(Arrays.asList("officeId", "name", "description", "startDate", "endDate",
|
private static final Set<String> SUPPORTED_PARAMETERS = new HashSet<>(Arrays.asList(OFFICE_ID, NAME, DESCRIPTION, START_DATE, END_DATE,
|
||||||
"status", "dateFormat", "locale", "isFullDay", "staffId", "hourStartTime", "minStartTime", "hourEndTime", "minEndTime",
|
STATUS, DATE_FORMAT, LOCALE, IS_FULL_DAY, STAFF_ID, HOUR_START_TIME, MIN_START_TIME, HOUR_END_TIME, MIN_END_TIME, TXN_AMOUNT,
|
||||||
"txnAmount", "txnDate", "txnNote", "entityType", "entityId", "currencyCode"));
|
TXN_DATE, TXN_NOTE, ENTITY_TYPE, ENTITY_ID, CURRENCY_CODE));
|
||||||
|
|
||||||
private final FromJsonHelper fromApiJsonHelper;
|
private final FromJsonHelper fromApiJsonHelper;
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
@@ -65,36 +85,36 @@ public final class TellerCommandFromApiJsonDeserializer {
|
|||||||
throw new InvalidJsonException();
|
throw new InvalidJsonException();
|
||||||
}
|
}
|
||||||
|
|
||||||
final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType();
|
final Type typeOfMap = new TypeToken<Map<String, Object>>() {
|
||||||
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParameters);
|
|
||||||
|
}.getType();
|
||||||
|
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, SUPPORTED_PARAMETERS);
|
||||||
|
|
||||||
final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
|
final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
|
||||||
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("teller");
|
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource(TELLER);
|
||||||
|
|
||||||
final JsonElement element = this.fromApiJsonHelper.parse(json);
|
final JsonElement element = this.fromApiJsonHelper.parse(json);
|
||||||
|
|
||||||
final Long officeId = this.fromApiJsonHelper.extractLongNamed("officeId", element);
|
final Long officeId = this.fromApiJsonHelper.extractLongNamed(OFFICE_ID, element);
|
||||||
baseDataValidator.reset().parameter("officeId").value(officeId).notNull().integerGreaterThanZero();
|
baseDataValidator.reset().parameter(OFFICE_ID).value(officeId).notNull().integerGreaterThanZero();
|
||||||
|
|
||||||
final String name = this.fromApiJsonHelper.extractStringNamed("name", element);
|
final String name = this.fromApiJsonHelper.extractStringNamed(NAME, element);
|
||||||
baseDataValidator.reset().parameter("name").value(name).notBlank().notExceedingLengthOf(50);
|
baseDataValidator.reset().parameter(NAME).value(name).notBlank().notExceedingLengthOf(50);
|
||||||
|
|
||||||
final String description = this.fromApiJsonHelper.extractStringNamed("description", element);
|
final String description = this.fromApiJsonHelper.extractStringNamed(DESCRIPTION, element);
|
||||||
baseDataValidator.reset().parameter("description").value(description).notExceedingLengthOf(100);
|
baseDataValidator.reset().parameter(DESCRIPTION).value(description).notExceedingLengthOf(100);
|
||||||
|
|
||||||
final LocalDate startDate = this.fromApiJsonHelper.extractLocalDateNamed("startDate", element);
|
final LocalDate startDate = this.fromApiJsonHelper.extractLocalDateNamed(START_DATE, element);
|
||||||
baseDataValidator.reset().parameter("startDate").value(startDate).notNull();
|
baseDataValidator.reset().parameter(START_DATE).value(startDate).notNull();
|
||||||
|
|
||||||
final LocalDate endDate = this.fromApiJsonHelper.extractLocalDateNamed("endDate", element);
|
final LocalDate endDate = this.fromApiJsonHelper.extractLocalDateNamed(END_DATE, element);
|
||||||
baseDataValidator.reset().parameter("endDate").value(endDate).ignoreIfNull();
|
baseDataValidator.reset().parameter(END_DATE).value(endDate).ignoreIfNull();
|
||||||
|
|
||||||
final String status = this.fromApiJsonHelper.extractStringNamed("status", element);
|
final String status = this.fromApiJsonHelper.extractStringNamed(STATUS, element);
|
||||||
baseDataValidator.reset().parameter("status").value(status).notBlank().notExceedingLengthOf(50);
|
baseDataValidator.reset().parameter(STATUS).value(status).notBlank().notExceedingLengthOf(50);
|
||||||
|
|
||||||
if (endDate != null) {
|
if (endDate != null && endDate.isBefore(startDate)) {
|
||||||
if (endDate.isBefore(startDate)) {
|
throw new InvalidDateInputException(startDate.toString(), endDate.toString());
|
||||||
throw new InvalidDateInputException(startDate.toString(), endDate.toString());
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
throwExceptionIfValidationWarningsExist(dataValidationErrors);
|
throwExceptionIfValidationWarningsExist(dataValidationErrors);
|
||||||
}
|
}
|
||||||
@@ -111,38 +131,40 @@ public final class TellerCommandFromApiJsonDeserializer {
|
|||||||
throw new InvalidJsonException();
|
throw new InvalidJsonException();
|
||||||
}
|
}
|
||||||
|
|
||||||
final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType();
|
final Type typeOfMap = new TypeToken<Map<String, Object>>() {
|
||||||
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParameters);
|
|
||||||
|
}.getType();
|
||||||
|
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, SUPPORTED_PARAMETERS);
|
||||||
|
|
||||||
final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
|
final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
|
||||||
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("teller");
|
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource(TELLER);
|
||||||
|
|
||||||
final JsonElement element = this.fromApiJsonHelper.parse(json);
|
final JsonElement element = this.fromApiJsonHelper.parse(json);
|
||||||
|
|
||||||
final Long staffId = this.fromApiJsonHelper.extractLongNamed("staffId", element);
|
final Long staffId = this.fromApiJsonHelper.extractLongNamed(STAFF_ID, element);
|
||||||
baseDataValidator.reset().parameter("staffId").value(staffId).notNull().integerGreaterThanZero();
|
baseDataValidator.reset().parameter(STAFF_ID).value(staffId).notNull().integerGreaterThanZero();
|
||||||
|
|
||||||
final String description = this.fromApiJsonHelper.extractStringNamed("description", element);
|
final String description = this.fromApiJsonHelper.extractStringNamed(DESCRIPTION, element);
|
||||||
baseDataValidator.reset().parameter("description").value(description).notExceedingLengthOf(100);
|
baseDataValidator.reset().parameter(DESCRIPTION).value(description).notExceedingLengthOf(100);
|
||||||
|
|
||||||
final LocalDate startDate = this.fromApiJsonHelper.extractLocalDateNamed("startDate", element);
|
final LocalDate startDate = this.fromApiJsonHelper.extractLocalDateNamed(START_DATE, element);
|
||||||
baseDataValidator.reset().parameter("startDate").value(startDate).notNull();
|
baseDataValidator.reset().parameter(START_DATE).value(startDate).notNull();
|
||||||
|
|
||||||
final LocalDate endDate = this.fromApiJsonHelper.extractLocalDateNamed("endDate", element);
|
final LocalDate endDate = this.fromApiJsonHelper.extractLocalDateNamed(END_DATE, element);
|
||||||
baseDataValidator.reset().parameter("endDate").value(endDate).notNull();
|
baseDataValidator.reset().parameter(END_DATE).value(endDate).notNull();
|
||||||
|
|
||||||
final Boolean isFullDay = this.fromApiJsonHelper.extractBooleanNamed("isFullDay", element);
|
final Boolean isFullDay = this.fromApiJsonHelper.extractBooleanNamed(IS_FULL_DAY, element);
|
||||||
baseDataValidator.reset().parameter("isFullDay").value(isFullDay).notNull();
|
baseDataValidator.reset().parameter(IS_FULL_DAY).value(isFullDay).notNull();
|
||||||
|
|
||||||
if (!isFullDay) {
|
if (!isFullDay) {
|
||||||
final String hourStartTime = this.fromApiJsonHelper.extractStringNamed("hourStartTime", element);
|
final String hourStartTime = this.fromApiJsonHelper.extractStringNamed(HOUR_START_TIME, element);
|
||||||
baseDataValidator.reset().parameter("startTime").value(hourStartTime).notBlank();
|
baseDataValidator.reset().parameter("startTime").value(hourStartTime).notBlank();
|
||||||
final String minStartTime = this.fromApiJsonHelper.extractStringNamed("minStartTime", element);
|
final String minStartTime = this.fromApiJsonHelper.extractStringNamed(MIN_START_TIME, element);
|
||||||
baseDataValidator.reset().parameter("startTime").value(minStartTime).notBlank();
|
baseDataValidator.reset().parameter("startTime").value(minStartTime).notBlank();
|
||||||
final String hourEndTime = this.fromApiJsonHelper.extractStringNamed("hourEndTime", element);
|
final String hourEndTime = this.fromApiJsonHelper.extractStringNamed(HOUR_END_TIME, element);
|
||||||
baseDataValidator.reset().parameter("hourEndTime").value(hourEndTime).notBlank();
|
baseDataValidator.reset().parameter(HOUR_END_TIME).value(hourEndTime).notBlank();
|
||||||
final String minEndTime = this.fromApiJsonHelper.extractStringNamed("minEndTime", element);
|
final String minEndTime = this.fromApiJsonHelper.extractStringNamed(MIN_END_TIME, element);
|
||||||
baseDataValidator.reset().parameter("minEndTime").value(minEndTime).notBlank();
|
baseDataValidator.reset().parameter(MIN_END_TIME).value(minEndTime).notBlank();
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -154,24 +176,26 @@ public final class TellerCommandFromApiJsonDeserializer {
|
|||||||
throw new InvalidJsonException();
|
throw new InvalidJsonException();
|
||||||
}
|
}
|
||||||
|
|
||||||
final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType();
|
final Type typeOfMap = new TypeToken<Map<String, Object>>() {
|
||||||
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParameters);
|
|
||||||
|
}.getType();
|
||||||
|
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, SUPPORTED_PARAMETERS);
|
||||||
|
|
||||||
final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
|
final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
|
||||||
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("teller");
|
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource(TELLER);
|
||||||
|
|
||||||
final JsonElement element = this.fromApiJsonHelper.parse(json);
|
final JsonElement element = this.fromApiJsonHelper.parse(json);
|
||||||
|
|
||||||
final BigDecimal txnAmount = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed("txnAmount", element);
|
final BigDecimal txnAmount = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed(TXN_AMOUNT, element);
|
||||||
baseDataValidator.reset().parameter("txnAmount").value(txnAmount).notNull();
|
baseDataValidator.reset().parameter(TXN_AMOUNT).value(txnAmount).notNull();
|
||||||
|
|
||||||
final LocalDate txnDate = this.fromApiJsonHelper.extractLocalDateNamed("txnDate", element);
|
final LocalDate txnDate = this.fromApiJsonHelper.extractLocalDateNamed(TXN_DATE, element);
|
||||||
baseDataValidator.reset().parameter("txnDate").value(txnDate).notNull();
|
baseDataValidator.reset().parameter(TXN_DATE).value(txnDate).notNull();
|
||||||
|
|
||||||
final String txnNote = this.fromApiJsonHelper.extractStringNamed("txnNote", element);
|
final String txnNote = this.fromApiJsonHelper.extractStringNamed(TXN_NOTE, element);
|
||||||
baseDataValidator.reset().parameter("txnNote").value(txnNote).notExceedingLengthOf(200);
|
baseDataValidator.reset().parameter(TXN_NOTE).value(txnNote).notExceedingLengthOf(200);
|
||||||
|
|
||||||
final String currencyCode = this.fromApiJsonHelper.extractStringNamed("currencyCode", element);
|
final String currencyCode = this.fromApiJsonHelper.extractStringNamed(CURRENCY_CODE, element);
|
||||||
baseDataValidator.reset().parameter("currencyCode").value(currencyCode).notExceedingLengthOf(3);
|
baseDataValidator.reset().parameter(CURRENCY_CODE).value(currencyCode).notExceedingLengthOf(3);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+121
-130
@@ -26,7 +26,6 @@ import java.time.format.DateTimeFormatter;
|
|||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.Arrays;
|
import java.util.Arrays;
|
||||||
import java.util.Collection;
|
import java.util.Collection;
|
||||||
import java.util.List;
|
|
||||||
import org.apache.fineract.infrastructure.core.data.EnumOptionData;
|
import org.apache.fineract.infrastructure.core.data.EnumOptionData;
|
||||||
import org.apache.fineract.infrastructure.core.domain.JdbcSupport;
|
import org.apache.fineract.infrastructure.core.domain.JdbcSupport;
|
||||||
import org.apache.fineract.infrastructure.core.service.DateUtils;
|
import org.apache.fineract.infrastructure.core.service.DateUtils;
|
||||||
@@ -56,19 +55,17 @@ import org.springframework.util.CollectionUtils;
|
|||||||
@Service
|
@Service
|
||||||
public class AccountTransfersReadPlatformServiceImpl implements AccountTransfersReadPlatformService {
|
public class AccountTransfersReadPlatformServiceImpl implements AccountTransfersReadPlatformService {
|
||||||
|
|
||||||
|
private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");
|
||||||
private final JdbcTemplate jdbcTemplate;
|
private final JdbcTemplate jdbcTemplate;
|
||||||
private final ClientReadPlatformService clientReadPlatformService;
|
private final ClientReadPlatformService clientReadPlatformService;
|
||||||
private final OfficeReadPlatformService officeReadPlatformService;
|
private final OfficeReadPlatformService officeReadPlatformService;
|
||||||
private final PortfolioAccountReadPlatformService portfolioAccountReadPlatformService;
|
private final PortfolioAccountReadPlatformService portfolioAccountReadPlatformService;
|
||||||
private final ColumnValidator columnValidator;
|
private final ColumnValidator columnValidator;
|
||||||
private final DatabaseSpecificSQLGenerator sqlGenerator;
|
private final DatabaseSpecificSQLGenerator sqlGenerator;
|
||||||
|
|
||||||
// mapper
|
// mapper
|
||||||
private final AccountTransfersMapper accountTransfersMapper;
|
private final AccountTransfersMapper accountTransfersMapper;
|
||||||
|
|
||||||
// pagination
|
// pagination
|
||||||
private final PaginationHelper paginationHelper;
|
private final PaginationHelper paginationHelper;
|
||||||
private final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
|
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
public AccountTransfersReadPlatformServiceImpl(final JdbcTemplate jdbcTemplate,
|
public AccountTransfersReadPlatformServiceImpl(final JdbcTemplate jdbcTemplate,
|
||||||
@@ -260,137 +257,14 @@ public class AccountTransfersReadPlatformServiceImpl implements AccountTransfers
|
|||||||
public Collection<Long> fetchPostInterestTransactionIds(final Long accountId) {
|
public Collection<Long> fetchPostInterestTransactionIds(final Long accountId) {
|
||||||
final String sql = "select att.from_savings_transaction_id from m_account_transfer_transaction att inner join m_account_transfer_details atd on atd.id = att.account_transfer_details_id where atd.from_savings_account_id=? and att.is_reversed = false and atd.transfer_type = ?";
|
final String sql = "select att.from_savings_transaction_id from m_account_transfer_transaction att inner join m_account_transfer_details atd on atd.id = att.account_transfer_details_id where atd.from_savings_account_id=? and att.is_reversed = false and atd.transfer_type = ?";
|
||||||
|
|
||||||
final List<Long> transactionId = this.jdbcTemplate.queryForList(sql, Long.class, accountId,
|
return this.jdbcTemplate.queryForList(sql, Long.class, accountId, AccountTransferType.INTEREST_TRANSFER.getValue());
|
||||||
AccountTransferType.INTEREST_TRANSFER.getValue());
|
|
||||||
|
|
||||||
return transactionId;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Collection<Long> fetchPostInterestTransactionIdsWithPivotDate(final Long accountId, final LocalDate pivotDate) {
|
public Collection<Long> fetchPostInterestTransactionIdsWithPivotDate(final Long accountId, final LocalDate pivotDate) {
|
||||||
final String sql = "select att.from_savings_transaction_id from m_account_transfer_transaction att inner join m_account_transfer_details atd on atd.id = att.account_transfer_details_id where atd.from_savings_account_id=? and att.is_reversed = false and atd.transfer_type = ? and att.transaction_date >= ?";
|
final String sql = "select att.from_savings_transaction_id from m_account_transfer_transaction att inner join m_account_transfer_details atd on atd.id = att.account_transfer_details_id where atd.from_savings_account_id=? and att.is_reversed = false and atd.transfer_type = ? and att.transaction_date >= ?";
|
||||||
|
|
||||||
final List<Long> transactionIds = this.jdbcTemplate.queryForList(sql, Long.class, accountId,
|
return this.jdbcTemplate.queryForList(sql, Long.class, accountId, AccountTransferType.INTEREST_TRANSFER.getValue(), pivotDate);
|
||||||
AccountTransferType.INTEREST_TRANSFER.getValue(), pivotDate);
|
|
||||||
|
|
||||||
return transactionIds;
|
|
||||||
}
|
|
||||||
|
|
||||||
private static final class AccountTransfersMapper implements RowMapper<AccountTransferData> {
|
|
||||||
|
|
||||||
private final String schemaSql;
|
|
||||||
|
|
||||||
AccountTransfersMapper() {
|
|
||||||
final StringBuilder sqlBuilder = new StringBuilder(400);
|
|
||||||
sqlBuilder.append("att.id as id, att.is_reversed as isReversed,");
|
|
||||||
sqlBuilder.append("att.transaction_date as transferDate, att.amount as transferAmount,");
|
|
||||||
sqlBuilder.append("att.description as transferDescription,");
|
|
||||||
sqlBuilder.append("att.currency_code as currencyCode, att.currency_digits as currencyDigits,");
|
|
||||||
sqlBuilder.append("att.currency_multiplesof as inMultiplesOf, ");
|
|
||||||
sqlBuilder.append("curr.name as currencyName, curr.internationalized_name_code as currencyNameCode, ");
|
|
||||||
sqlBuilder.append("curr.display_symbol as currencyDisplaySymbol, ");
|
|
||||||
sqlBuilder.append("fromoff.id as fromOfficeId, fromoff.name as fromOfficeName,");
|
|
||||||
sqlBuilder.append("tooff.id as toOfficeId, tooff.name as toOfficeName,");
|
|
||||||
sqlBuilder.append("fromclient.id as fromClientId, fromclient.display_name as fromClientName,");
|
|
||||||
sqlBuilder.append("toclient.id as toClientId, toclient.display_name as toClientName,");
|
|
||||||
sqlBuilder.append("fromsavacc.id as fromSavingsAccountId, fromsavacc.account_no as fromSavingsAccountNo,");
|
|
||||||
sqlBuilder.append("fromloanacc.id as fromLoanAccountId, fromloanacc.account_no as fromLoanAccountNo,");
|
|
||||||
sqlBuilder.append("tosavacc.id as toSavingsAccountId, tosavacc.account_no as toSavingsAccountNo,");
|
|
||||||
sqlBuilder.append("toloanacc.id as toLoanAccountId, toloanacc.account_no as toLoanAccountNo,");
|
|
||||||
sqlBuilder.append("fromsavtran.id as fromSavingsAccountTransactionId,");
|
|
||||||
sqlBuilder.append("fromsavtran.transaction_type_enum as fromSavingsAccountTransactionType,");
|
|
||||||
sqlBuilder.append("tosavtran.id as toSavingsAccountTransactionId,");
|
|
||||||
sqlBuilder.append("tosavtran.transaction_type_enum as toSavingsAccountTransactionType");
|
|
||||||
sqlBuilder.append(" FROM m_account_transfer_transaction att ");
|
|
||||||
sqlBuilder.append("left join m_account_transfer_details atd on atd.id = att.account_transfer_details_id ");
|
|
||||||
sqlBuilder.append("join m_currency curr on curr.code = att.currency_code ");
|
|
||||||
sqlBuilder.append("join m_office fromoff on fromoff.id = atd.from_office_id ");
|
|
||||||
sqlBuilder.append("join m_office tooff on tooff.id = atd.to_office_id ");
|
|
||||||
sqlBuilder.append("join m_client fromclient on fromclient.id = atd.from_client_id ");
|
|
||||||
sqlBuilder.append("join m_client toclient on toclient.id = atd.to_client_id ");
|
|
||||||
sqlBuilder.append("left join m_savings_account fromsavacc on fromsavacc.id = atd.from_savings_account_id ");
|
|
||||||
sqlBuilder.append("left join m_loan fromloanacc on fromloanacc.id = atd.from_loan_account_id ");
|
|
||||||
sqlBuilder.append("left join m_savings_account tosavacc on tosavacc.id = atd.to_savings_account_id ");
|
|
||||||
sqlBuilder.append("left join m_loan toloanacc on toloanacc.id = atd.to_loan_account_id ");
|
|
||||||
sqlBuilder.append("left join m_savings_account_transaction fromsavtran on fromsavtran.id = att.from_savings_transaction_id ");
|
|
||||||
sqlBuilder.append("left join m_savings_account_transaction tosavtran on tosavtran.id = att.to_savings_transaction_id ");
|
|
||||||
sqlBuilder.append("left join m_loan_transaction fromloantran on fromloantran.id = att.from_savings_transaction_id ");
|
|
||||||
sqlBuilder.append("left join m_loan_transaction toloantran on toloantran.id = att.to_savings_transaction_id ");
|
|
||||||
|
|
||||||
this.schemaSql = sqlBuilder.toString();
|
|
||||||
}
|
|
||||||
|
|
||||||
public String schema() {
|
|
||||||
return this.schemaSql;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public AccountTransferData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) throws SQLException {
|
|
||||||
|
|
||||||
final Long id = rs.getLong("id");
|
|
||||||
final boolean reversed = rs.getBoolean("isReversed");
|
|
||||||
|
|
||||||
final LocalDate transferDate = JdbcSupport.getLocalDate(rs, "transferDate");
|
|
||||||
final BigDecimal transferAmount = JdbcSupport.getBigDecimalDefaultToZeroIfNull(rs, "transferAmount");
|
|
||||||
final String transferDescription = rs.getString("transferDescription");
|
|
||||||
|
|
||||||
final String currencyCode = rs.getString("currencyCode");
|
|
||||||
final String currencyName = rs.getString("currencyName");
|
|
||||||
final String currencyNameCode = rs.getString("currencyNameCode");
|
|
||||||
final String currencyDisplaySymbol = rs.getString("currencyDisplaySymbol");
|
|
||||||
final Integer currencyDigits = JdbcSupport.getInteger(rs, "currencyDigits");
|
|
||||||
final Integer inMultiplesOf = JdbcSupport.getInteger(rs, "inMultiplesOf");
|
|
||||||
final CurrencyData currency = new CurrencyData(currencyCode, currencyName, currencyDigits, inMultiplesOf, currencyDisplaySymbol,
|
|
||||||
currencyNameCode);
|
|
||||||
|
|
||||||
final Long fromOfficeId = JdbcSupport.getLong(rs, "fromOfficeId");
|
|
||||||
final String fromOfficeName = rs.getString("fromOfficeName");
|
|
||||||
final OfficeData fromOffice = OfficeData.dropdown(fromOfficeId, fromOfficeName, null);
|
|
||||||
|
|
||||||
final Long toOfficeId = JdbcSupport.getLong(rs, "toOfficeId");
|
|
||||||
final String toOfficeName = rs.getString("toOfficeName");
|
|
||||||
final OfficeData toOffice = OfficeData.dropdown(toOfficeId, toOfficeName, null);
|
|
||||||
|
|
||||||
final Long fromClientId = JdbcSupport.getLong(rs, "fromClientId");
|
|
||||||
final String fromClientName = rs.getString("fromClientName");
|
|
||||||
final ClientData fromClient = ClientData.lookup(fromClientId, fromClientName, fromOfficeId, fromOfficeName);
|
|
||||||
|
|
||||||
final Long toClientId = JdbcSupport.getLong(rs, "toClientId");
|
|
||||||
final String toClientName = rs.getString("toClientName");
|
|
||||||
final ClientData toClient = ClientData.lookup(toClientId, toClientName, toOfficeId, toOfficeName);
|
|
||||||
|
|
||||||
final Long fromSavingsAccountId = JdbcSupport.getLong(rs, "fromSavingsAccountId");
|
|
||||||
final String fromSavingsAccountNo = rs.getString("fromSavingsAccountNo");
|
|
||||||
final Long fromLoanAccountId = JdbcSupport.getLong(rs, "fromLoanAccountId");
|
|
||||||
final String fromLoanAccountNo = rs.getString("fromLoanAccountNo");
|
|
||||||
PortfolioAccountData fromAccount = null;
|
|
||||||
EnumOptionData fromAccountType = null;
|
|
||||||
if (fromSavingsAccountId != null) {
|
|
||||||
fromAccount = PortfolioAccountData.lookup(fromSavingsAccountId, fromSavingsAccountNo);
|
|
||||||
fromAccountType = AccountTransferEnumerations.accountType(PortfolioAccountType.SAVINGS);
|
|
||||||
} else if (fromLoanAccountId != null) {
|
|
||||||
fromAccount = PortfolioAccountData.lookup(fromLoanAccountId, fromLoanAccountNo);
|
|
||||||
fromAccountType = AccountTransferEnumerations.accountType(PortfolioAccountType.LOAN);
|
|
||||||
}
|
|
||||||
|
|
||||||
PortfolioAccountData toAccount = null;
|
|
||||||
EnumOptionData toAccountType = null;
|
|
||||||
final Long toSavingsAccountId = JdbcSupport.getLong(rs, "toSavingsAccountId");
|
|
||||||
final String toSavingsAccountNo = rs.getString("toSavingsAccountNo");
|
|
||||||
final Long toLoanAccountId = JdbcSupport.getLong(rs, "toLoanAccountId");
|
|
||||||
final String toLoanAccountNo = rs.getString("toLoanAccountNo");
|
|
||||||
|
|
||||||
if (toSavingsAccountId != null) {
|
|
||||||
toAccount = PortfolioAccountData.lookup(toSavingsAccountId, toSavingsAccountNo);
|
|
||||||
toAccountType = AccountTransferEnumerations.accountType(PortfolioAccountType.SAVINGS);
|
|
||||||
} else if (toLoanAccountId != null) {
|
|
||||||
toAccount = PortfolioAccountData.lookup(toLoanAccountId, toLoanAccountNo);
|
|
||||||
toAccountType = AccountTransferEnumerations.accountType(PortfolioAccountType.LOAN);
|
|
||||||
}
|
|
||||||
|
|
||||||
return AccountTransferData.instance(id, reversed, transferDate, currency, transferAmount, transferDescription, fromOffice,
|
|
||||||
toOffice, fromClient, toClient, fromAccountType, fromAccount, toAccountType, toAccount);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@@ -561,8 +435,125 @@ public class AccountTransfersReadPlatformServiceImpl implements AccountTransfers
|
|||||||
sqlBuilder.append(" and trans.transaction_date = ? ");
|
sqlBuilder.append(" and trans.transaction_date = ? ");
|
||||||
sqlBuilder.append(" and IF(1=?, det.from_loan_account_id = ?, det.from_savings_account_id = ?) ");
|
sqlBuilder.append(" and IF(1=?, det.from_loan_account_id = ?, det.from_savings_account_id = ?) ");
|
||||||
|
|
||||||
return this.jdbcTemplate.queryForObject(sqlBuilder.toString(), BigDecimal.class, this.formatter.format(transactionDate),
|
return this.jdbcTemplate.queryForObject(sqlBuilder.toString(), BigDecimal.class, DATE_TIME_FORMATTER.format(transactionDate),
|
||||||
accountType, accountId, accountId);
|
accountType, accountId, accountId);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static final class AccountTransfersMapper implements RowMapper<AccountTransferData> {
|
||||||
|
|
||||||
|
private final String schemaSql;
|
||||||
|
|
||||||
|
AccountTransfersMapper() {
|
||||||
|
final StringBuilder sqlBuilder = new StringBuilder(400);
|
||||||
|
sqlBuilder.append("att.id as id, att.is_reversed as isReversed,");
|
||||||
|
sqlBuilder.append("att.transaction_date as transferDate, att.amount as transferAmount,");
|
||||||
|
sqlBuilder.append("att.description as transferDescription,");
|
||||||
|
sqlBuilder.append("att.currency_code as currencyCode, att.currency_digits as currencyDigits,");
|
||||||
|
sqlBuilder.append("att.currency_multiplesof as inMultiplesOf, ");
|
||||||
|
sqlBuilder.append("curr.name as currencyName, curr.internationalized_name_code as currencyNameCode, ");
|
||||||
|
sqlBuilder.append("curr.display_symbol as currencyDisplaySymbol, ");
|
||||||
|
sqlBuilder.append("fromoff.id as fromOfficeId, fromoff.name as fromOfficeName,");
|
||||||
|
sqlBuilder.append("tooff.id as toOfficeId, tooff.name as toOfficeName,");
|
||||||
|
sqlBuilder.append("fromclient.id as fromClientId, fromclient.display_name as fromClientName,");
|
||||||
|
sqlBuilder.append("toclient.id as toClientId, toclient.display_name as toClientName,");
|
||||||
|
sqlBuilder.append("fromsavacc.id as fromSavingsAccountId, fromsavacc.account_no as fromSavingsAccountNo,");
|
||||||
|
sqlBuilder.append("fromloanacc.id as fromLoanAccountId, fromloanacc.account_no as fromLoanAccountNo,");
|
||||||
|
sqlBuilder.append("tosavacc.id as toSavingsAccountId, tosavacc.account_no as toSavingsAccountNo,");
|
||||||
|
sqlBuilder.append("toloanacc.id as toLoanAccountId, toloanacc.account_no as toLoanAccountNo,");
|
||||||
|
sqlBuilder.append("fromsavtran.id as fromSavingsAccountTransactionId,");
|
||||||
|
sqlBuilder.append("fromsavtran.transaction_type_enum as fromSavingsAccountTransactionType,");
|
||||||
|
sqlBuilder.append("tosavtran.id as toSavingsAccountTransactionId,");
|
||||||
|
sqlBuilder.append("tosavtran.transaction_type_enum as toSavingsAccountTransactionType");
|
||||||
|
sqlBuilder.append(" FROM m_account_transfer_transaction att ");
|
||||||
|
sqlBuilder.append("left join m_account_transfer_details atd on atd.id = att.account_transfer_details_id ");
|
||||||
|
sqlBuilder.append("join m_currency curr on curr.code = att.currency_code ");
|
||||||
|
sqlBuilder.append("join m_office fromoff on fromoff.id = atd.from_office_id ");
|
||||||
|
sqlBuilder.append("join m_office tooff on tooff.id = atd.to_office_id ");
|
||||||
|
sqlBuilder.append("join m_client fromclient on fromclient.id = atd.from_client_id ");
|
||||||
|
sqlBuilder.append("join m_client toclient on toclient.id = atd.to_client_id ");
|
||||||
|
sqlBuilder.append("left join m_savings_account fromsavacc on fromsavacc.id = atd.from_savings_account_id ");
|
||||||
|
sqlBuilder.append("left join m_loan fromloanacc on fromloanacc.id = atd.from_loan_account_id ");
|
||||||
|
sqlBuilder.append("left join m_savings_account tosavacc on tosavacc.id = atd.to_savings_account_id ");
|
||||||
|
sqlBuilder.append("left join m_loan toloanacc on toloanacc.id = atd.to_loan_account_id ");
|
||||||
|
sqlBuilder.append("left join m_savings_account_transaction fromsavtran on fromsavtran.id = att.from_savings_transaction_id ");
|
||||||
|
sqlBuilder.append("left join m_savings_account_transaction tosavtran on tosavtran.id = att.to_savings_transaction_id ");
|
||||||
|
sqlBuilder.append("left join m_loan_transaction fromloantran on fromloantran.id = att.from_savings_transaction_id ");
|
||||||
|
sqlBuilder.append("left join m_loan_transaction toloantran on toloantran.id = att.to_savings_transaction_id ");
|
||||||
|
|
||||||
|
this.schemaSql = sqlBuilder.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
public String schema() {
|
||||||
|
return this.schemaSql;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public AccountTransferData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) throws SQLException {
|
||||||
|
|
||||||
|
final Long id = rs.getLong("id");
|
||||||
|
final boolean reversed = rs.getBoolean("isReversed");
|
||||||
|
|
||||||
|
final LocalDate transferDate = JdbcSupport.getLocalDate(rs, "transferDate");
|
||||||
|
final BigDecimal transferAmount = JdbcSupport.getBigDecimalDefaultToZeroIfNull(rs, "transferAmount");
|
||||||
|
final String transferDescription = rs.getString("transferDescription");
|
||||||
|
|
||||||
|
final String currencyCode = rs.getString("currencyCode");
|
||||||
|
final String currencyName = rs.getString("currencyName");
|
||||||
|
final String currencyNameCode = rs.getString("currencyNameCode");
|
||||||
|
final String currencyDisplaySymbol = rs.getString("currencyDisplaySymbol");
|
||||||
|
final Integer currencyDigits = JdbcSupport.getInteger(rs, "currencyDigits");
|
||||||
|
final Integer inMultiplesOf = JdbcSupport.getInteger(rs, "inMultiplesOf");
|
||||||
|
final CurrencyData currency = new CurrencyData(currencyCode, currencyName, currencyDigits, inMultiplesOf, currencyDisplaySymbol,
|
||||||
|
currencyNameCode);
|
||||||
|
|
||||||
|
final Long fromOfficeId = JdbcSupport.getLong(rs, "fromOfficeId");
|
||||||
|
final String fromOfficeName = rs.getString("fromOfficeName");
|
||||||
|
final OfficeData fromOffice = OfficeData.dropdown(fromOfficeId, fromOfficeName, null);
|
||||||
|
|
||||||
|
final Long toOfficeId = JdbcSupport.getLong(rs, "toOfficeId");
|
||||||
|
final String toOfficeName = rs.getString("toOfficeName");
|
||||||
|
final OfficeData toOffice = OfficeData.dropdown(toOfficeId, toOfficeName, null);
|
||||||
|
|
||||||
|
final Long fromClientId = JdbcSupport.getLong(rs, "fromClientId");
|
||||||
|
final String fromClientName = rs.getString("fromClientName");
|
||||||
|
final ClientData fromClient = ClientData.lookup(fromClientId, fromClientName, fromOfficeId, fromOfficeName);
|
||||||
|
|
||||||
|
final Long toClientId = JdbcSupport.getLong(rs, "toClientId");
|
||||||
|
final String toClientName = rs.getString("toClientName");
|
||||||
|
final ClientData toClient = ClientData.lookup(toClientId, toClientName, toOfficeId, toOfficeName);
|
||||||
|
|
||||||
|
final Long fromSavingsAccountId = JdbcSupport.getLong(rs, "fromSavingsAccountId");
|
||||||
|
final String fromSavingsAccountNo = rs.getString("fromSavingsAccountNo");
|
||||||
|
final Long fromLoanAccountId = JdbcSupport.getLong(rs, "fromLoanAccountId");
|
||||||
|
final String fromLoanAccountNo = rs.getString("fromLoanAccountNo");
|
||||||
|
PortfolioAccountData fromAccount = null;
|
||||||
|
EnumOptionData fromAccountType = null;
|
||||||
|
if (fromSavingsAccountId != null) {
|
||||||
|
fromAccount = PortfolioAccountData.lookup(fromSavingsAccountId, fromSavingsAccountNo);
|
||||||
|
fromAccountType = AccountTransferEnumerations.accountType(PortfolioAccountType.SAVINGS);
|
||||||
|
} else if (fromLoanAccountId != null) {
|
||||||
|
fromAccount = PortfolioAccountData.lookup(fromLoanAccountId, fromLoanAccountNo);
|
||||||
|
fromAccountType = AccountTransferEnumerations.accountType(PortfolioAccountType.LOAN);
|
||||||
|
}
|
||||||
|
|
||||||
|
PortfolioAccountData toAccount = null;
|
||||||
|
EnumOptionData toAccountType = null;
|
||||||
|
final Long toSavingsAccountId = JdbcSupport.getLong(rs, "toSavingsAccountId");
|
||||||
|
final String toSavingsAccountNo = rs.getString("toSavingsAccountNo");
|
||||||
|
final Long toLoanAccountId = JdbcSupport.getLong(rs, "toLoanAccountId");
|
||||||
|
final String toLoanAccountNo = rs.getString("toLoanAccountNo");
|
||||||
|
|
||||||
|
if (toSavingsAccountId != null) {
|
||||||
|
toAccount = PortfolioAccountData.lookup(toSavingsAccountId, toSavingsAccountNo);
|
||||||
|
toAccountType = AccountTransferEnumerations.accountType(PortfolioAccountType.SAVINGS);
|
||||||
|
} else if (toLoanAccountId != null) {
|
||||||
|
toAccount = PortfolioAccountData.lookup(toLoanAccountId, toLoanAccountNo);
|
||||||
|
toAccountType = AccountTransferEnumerations.accountType(PortfolioAccountType.LOAN);
|
||||||
|
}
|
||||||
|
|
||||||
|
return AccountTransferData.instance(id, reversed, transferDate, currency, transferAmount, transferDescription, fromOffice,
|
||||||
|
toOffice, fromClient, toClient, fromAccountType, fromAccount, toAccountType, toAccount);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
+5
-13
@@ -38,12 +38,10 @@ import javax.ws.rs.Produces;
|
|||||||
import javax.ws.rs.core.Context;
|
import javax.ws.rs.core.Context;
|
||||||
import javax.ws.rs.core.MediaType;
|
import javax.ws.rs.core.MediaType;
|
||||||
import javax.ws.rs.core.UriInfo;
|
import javax.ws.rs.core.UriInfo;
|
||||||
import org.apache.fineract.commands.service.PortfolioCommandSourceWritePlatformService;
|
|
||||||
import org.apache.fineract.infrastructure.core.api.ApiRequestParameterHelper;
|
import org.apache.fineract.infrastructure.core.api.ApiRequestParameterHelper;
|
||||||
import org.apache.fineract.infrastructure.core.serialization.ApiRequestJsonSerializationSettings;
|
import org.apache.fineract.infrastructure.core.serialization.ApiRequestJsonSerializationSettings;
|
||||||
import org.apache.fineract.infrastructure.core.serialization.DefaultToApiJsonSerializer;
|
import org.apache.fineract.infrastructure.core.serialization.DefaultToApiJsonSerializer;
|
||||||
import org.apache.fineract.infrastructure.security.service.PlatformSecurityContext;
|
import org.apache.fineract.infrastructure.security.service.PlatformSecurityContext;
|
||||||
import org.apache.fineract.portfolio.address.data.AddressData;
|
|
||||||
import org.apache.fineract.portfolio.address.data.FieldConfigurationData;
|
import org.apache.fineract.portfolio.address.data.FieldConfigurationData;
|
||||||
import org.apache.fineract.portfolio.address.service.FieldConfigurationReadPlatformService;
|
import org.apache.fineract.portfolio.address.service.FieldConfigurationReadPlatformService;
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
@@ -58,30 +56,24 @@ import org.springframework.stereotype.Component;
|
|||||||
+ "add regular expression for validation")
|
+ "add regular expression for validation")
|
||||||
public class EntityFieldConfigurationApiResources {
|
public class EntityFieldConfigurationApiResources {
|
||||||
|
|
||||||
private final Set<String> responseDataParameters = new HashSet<>(
|
private static final Set<String> RESPONSE_DATA_PARAMETERS = new HashSet<>(
|
||||||
Arrays.asList("clientAddressId", "client_id", "address_id", "address_type_id", "isActive", "fieldConfigurationId", "entity",
|
Arrays.asList("clientAddressId", "client_id", "address_id", "address_type_id", "isActive", "fieldConfigurationId", "entity",
|
||||||
"table", "field", "is_enabled", "is_mandatory", "validation_regex"));
|
"table", "field", "is_enabled", "is_mandatory", "validation_regex"));
|
||||||
private final String resourceNameForPermissions = "Address";
|
private static final String RESOURCE_NAME_FOR_PERMISSIONS = "Address";
|
||||||
private final PlatformSecurityContext context;
|
private final PlatformSecurityContext context;
|
||||||
private final DefaultToApiJsonSerializer<AddressData> toApiJsonSerializer;
|
|
||||||
private final FieldConfigurationReadPlatformService readPlatformServicefld;
|
private final FieldConfigurationReadPlatformService readPlatformServicefld;
|
||||||
private final DefaultToApiJsonSerializer<FieldConfigurationData> toApiJsonSerializerfld;
|
private final DefaultToApiJsonSerializer<FieldConfigurationData> toApiJsonSerializerfld;
|
||||||
private final ApiRequestParameterHelper apiRequestParameterHelper;
|
private final ApiRequestParameterHelper apiRequestParameterHelper;
|
||||||
private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService;
|
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
public EntityFieldConfigurationApiResources(final PlatformSecurityContext context,
|
public EntityFieldConfigurationApiResources(final PlatformSecurityContext context,
|
||||||
final DefaultToApiJsonSerializer<AddressData> toApiJsonSerializer,
|
|
||||||
final FieldConfigurationReadPlatformService readPlatformServicefld,
|
final FieldConfigurationReadPlatformService readPlatformServicefld,
|
||||||
final DefaultToApiJsonSerializer<FieldConfigurationData> toApiJsonSerializerfld,
|
final DefaultToApiJsonSerializer<FieldConfigurationData> toApiJsonSerializerfld,
|
||||||
final ApiRequestParameterHelper apiRequestParameterHelper,
|
final ApiRequestParameterHelper apiRequestParameterHelper) {
|
||||||
final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService) {
|
|
||||||
this.context = context;
|
this.context = context;
|
||||||
this.toApiJsonSerializer = toApiJsonSerializer;
|
|
||||||
this.readPlatformServicefld = readPlatformServicefld;
|
this.readPlatformServicefld = readPlatformServicefld;
|
||||||
this.toApiJsonSerializerfld = toApiJsonSerializerfld;
|
this.toApiJsonSerializerfld = toApiJsonSerializerfld;
|
||||||
this.apiRequestParameterHelper = apiRequestParameterHelper;
|
this.apiRequestParameterHelper = apiRequestParameterHelper;
|
||||||
this.commandsSourceWritePlatformService = commandsSourceWritePlatformService;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@GET
|
@GET
|
||||||
@@ -92,12 +84,12 @@ public class EntityFieldConfigurationApiResources {
|
|||||||
@ApiResponse(responseCode = "200", description = "OK", content = @Content(array = @ArraySchema(schema = @Schema(implementation = EntityFieldConfigurationApiResourcesSwagger.GetFieldConfigurationEntityResponse.class)))) })
|
@ApiResponse(responseCode = "200", description = "OK", content = @Content(array = @ArraySchema(schema = @Schema(implementation = EntityFieldConfigurationApiResourcesSwagger.GetFieldConfigurationEntityResponse.class)))) })
|
||||||
public String getAddresses(@PathParam("entity") @Parameter(description = "entity") final String entityname,
|
public String getAddresses(@PathParam("entity") @Parameter(description = "entity") final String entityname,
|
||||||
@Context final UriInfo uriInfo) {
|
@Context final UriInfo uriInfo) {
|
||||||
this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions);
|
this.context.authenticatedUser().validateHasReadPermission(RESOURCE_NAME_FOR_PERMISSIONS);
|
||||||
|
|
||||||
final Collection<FieldConfigurationData> fldconfig = this.readPlatformServicefld.retrieveFieldConfiguration(entityname);
|
final Collection<FieldConfigurationData> fldconfig = this.readPlatformServicefld.retrieveFieldConfiguration(entityname);
|
||||||
|
|
||||||
final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters());
|
final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters());
|
||||||
return this.toApiJsonSerializerfld.serialize(settings, fldconfig, this.responseDataParameters);
|
return this.toApiJsonSerializerfld.serialize(settings, fldconfig, RESPONSE_DATA_PARAMETERS);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+16
-17
@@ -69,12 +69,13 @@ public class CalendarsApiResource {
|
|||||||
/**
|
/**
|
||||||
* The set of parameters that are supported in response for {@link Calendar}
|
* The set of parameters that are supported in response for {@link Calendar}
|
||||||
*/
|
*/
|
||||||
private final Set<String> responseDataParameters = new HashSet<>(Arrays.asList("id", "entityId", "entityType", "title", "description",
|
private static final Set<String> RESPONSE_DATA_PARAMETERS = new HashSet<>(
|
||||||
"location", "startDate", "endDate", "duration", "type", "repeating", "recurrence", "frequency", "interval", "repeatsOnDay",
|
Arrays.asList("id", "entityId", "entityType", "title", "description", "location", "startDate", "endDate", "duration", "type",
|
||||||
"remindBy", "firstReminder", "secondReminder", "humanReadable", "createdDate", "lastUpdatedDate", "createdByUserId",
|
"repeating", "recurrence", "frequency", "interval", "repeatsOnDay", "remindBy", "firstReminder", "secondReminder",
|
||||||
"createdByUsername", "lastUpdatedByUserId", "lastUpdatedByUsername", "recurringDates", "nextTenRecurringDates",
|
"humanReadable", "createdDate", "lastUpdatedDate", "createdByUserId", "createdByUsername", "lastUpdatedByUserId",
|
||||||
"entityTypeOptions", "calendarTypeOptions", "remindByOptions", "frequencyOptions", "repeatsOnDayOptions"));
|
"lastUpdatedByUsername", "recurringDates", "nextTenRecurringDates", "entityTypeOptions", "calendarTypeOptions",
|
||||||
private final String resourceNameForPermissions = "CALENDAR";
|
"remindByOptions", "frequencyOptions", "repeatsOnDayOptions"));
|
||||||
|
private static final String RESOURCE_NAME_FOR_PERMISSIONS = "CALENDAR";
|
||||||
|
|
||||||
private final PlatformSecurityContext context;
|
private final PlatformSecurityContext context;
|
||||||
private final CalendarReadPlatformService readPlatformService;
|
private final CalendarReadPlatformService readPlatformService;
|
||||||
@@ -103,7 +104,7 @@ public class CalendarsApiResource {
|
|||||||
public String retrieveCalendar(@PathParam("calendarId") final Long calendarId, @PathParam("entityType") final String entityType,
|
public String retrieveCalendar(@PathParam("calendarId") final Long calendarId, @PathParam("entityType") final String entityType,
|
||||||
@PathParam("entityId") final Long entityId, @Context final UriInfo uriInfo) {
|
@PathParam("entityId") final Long entityId, @Context final UriInfo uriInfo) {
|
||||||
|
|
||||||
this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions);
|
this.context.authenticatedUser().validateHasReadPermission(RESOURCE_NAME_FOR_PERMISSIONS);
|
||||||
final Integer entityTypeId = CalendarEntityType.valueOf(entityType.toUpperCase()).getValue();
|
final Integer entityTypeId = CalendarEntityType.valueOf(entityType.toUpperCase()).getValue();
|
||||||
CalendarData calendarData = this.readPlatformService.retrieveCalendar(calendarId, entityId, entityTypeId);
|
CalendarData calendarData = this.readPlatformService.retrieveCalendar(calendarId, entityId, entityTypeId);
|
||||||
|
|
||||||
@@ -119,7 +120,7 @@ public class CalendarsApiResource {
|
|||||||
if (settings.isTemplate()) {
|
if (settings.isTemplate()) {
|
||||||
calendarData = handleTemplate(calendarData);
|
calendarData = handleTemplate(calendarData);
|
||||||
}
|
}
|
||||||
return this.toApiJsonSerializer.serialize(settings, calendarData, this.responseDataParameters);
|
return this.toApiJsonSerializer.serialize(settings, calendarData, RESPONSE_DATA_PARAMETERS);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -135,7 +136,7 @@ public class CalendarsApiResource {
|
|||||||
public String retrieveCalendarsByEntity(@PathParam("entityType") final String entityType, @PathParam("entityId") final Long entityId,
|
public String retrieveCalendarsByEntity(@PathParam("entityType") final String entityType, @PathParam("entityId") final Long entityId,
|
||||||
@Context final UriInfo uriInfo, @DefaultValue("all") @QueryParam("calendarType") final String calendarType) {
|
@Context final UriInfo uriInfo, @DefaultValue("all") @QueryParam("calendarType") final String calendarType) {
|
||||||
|
|
||||||
this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions);
|
this.context.authenticatedUser().validateHasReadPermission(RESOURCE_NAME_FOR_PERMISSIONS);
|
||||||
|
|
||||||
final Set<String> associationParameters = ApiParameterHelper.extractAssociationsForResponseIfProvided(uriInfo.getQueryParameters());
|
final Set<String> associationParameters = ApiParameterHelper.extractAssociationsForResponseIfProvided(uriInfo.getQueryParameters());
|
||||||
|
|
||||||
@@ -143,11 +144,9 @@ public class CalendarsApiResource {
|
|||||||
|
|
||||||
final List<Integer> calendarTypeOptions = CalendarUtils.createIntegerListFromQueryParameter(calendarType);
|
final List<Integer> calendarTypeOptions = CalendarUtils.createIntegerListFromQueryParameter(calendarType);
|
||||||
|
|
||||||
if (!associationParameters.isEmpty()) {
|
if (!associationParameters.isEmpty() && associationParameters.contains("parentCalendars")) {
|
||||||
if (associationParameters.contains("parentCalendars")) {
|
calendarsData.addAll(this.readPlatformService.retrieveParentCalendarsByEntity(entityId,
|
||||||
calendarsData.addAll(this.readPlatformService.retrieveParentCalendarsByEntity(entityId,
|
CalendarEntityType.valueOf(entityType.toUpperCase()).getValue(), calendarTypeOptions));
|
||||||
CalendarEntityType.valueOf(entityType.toUpperCase()).getValue(), calendarTypeOptions));
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
calendarsData.addAll(this.readPlatformService.retrieveCalendarsByEntity(entityId,
|
calendarsData.addAll(this.readPlatformService.retrieveCalendarsByEntity(entityId,
|
||||||
@@ -157,7 +156,7 @@ public class CalendarsApiResource {
|
|||||||
calendarsData = this.readPlatformService.updateWithRecurringDates(calendarsData);
|
calendarsData = this.readPlatformService.updateWithRecurringDates(calendarsData);
|
||||||
|
|
||||||
final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters());
|
final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters());
|
||||||
return this.toApiJsonSerializer.serialize(settings, calendarsData, this.responseDataParameters);
|
return this.toApiJsonSerializer.serialize(settings, calendarsData, RESPONSE_DATA_PARAMETERS);
|
||||||
}
|
}
|
||||||
|
|
||||||
@GET
|
@GET
|
||||||
@@ -167,13 +166,13 @@ public class CalendarsApiResource {
|
|||||||
public String retrieveNewCalendarDetails(@Context final UriInfo uriInfo, @PathParam("entityType") final String entityType,
|
public String retrieveNewCalendarDetails(@Context final UriInfo uriInfo, @PathParam("entityType") final String entityType,
|
||||||
@PathParam("entityId") final Long entityId) {
|
@PathParam("entityId") final Long entityId) {
|
||||||
|
|
||||||
this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions);
|
this.context.authenticatedUser().validateHasReadPermission(RESOURCE_NAME_FOR_PERMISSIONS);
|
||||||
|
|
||||||
CalendarData calendarData = this.readPlatformService.retrieveNewCalendarDetails();
|
CalendarData calendarData = this.readPlatformService.retrieveNewCalendarDetails();
|
||||||
calendarData = handleTemplate(calendarData);
|
calendarData = handleTemplate(calendarData);
|
||||||
|
|
||||||
final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters());
|
final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters());
|
||||||
return this.toApiJsonSerializer.serialize(settings, calendarData, this.responseDataParameters);
|
return this.toApiJsonSerializer.serialize(settings, calendarData, RESPONSE_DATA_PARAMETERS);
|
||||||
}
|
}
|
||||||
|
|
||||||
@POST
|
@POST
|
||||||
|
|||||||
+4
-4
@@ -50,7 +50,7 @@ public class CalendarCommandFromApiJsonDeserializer extends AbstractFromApiJsonD
|
|||||||
/**
|
/**
|
||||||
* The parameters supported for this command.
|
* The parameters supported for this command.
|
||||||
*/
|
*/
|
||||||
private final Set<String> supportedParameters = CalendarSupportedParameters.getAllValues();
|
private static final Set<String> SUPPORTED_PARAMETERS = CalendarSupportedParameters.getAllValues();
|
||||||
|
|
||||||
private final FromJsonHelper fromApiJsonHelper;
|
private final FromJsonHelper fromApiJsonHelper;
|
||||||
|
|
||||||
@@ -66,7 +66,7 @@ public class CalendarCommandFromApiJsonDeserializer extends AbstractFromApiJsonD
|
|||||||
}
|
}
|
||||||
|
|
||||||
final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType();
|
final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType();
|
||||||
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParameters);
|
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, SUPPORTED_PARAMETERS);
|
||||||
|
|
||||||
final JsonElement element = this.fromApiJsonHelper.parse(json);
|
final JsonElement element = this.fromApiJsonHelper.parse(json);
|
||||||
final String title = this.fromApiJsonHelper.extractStringNamed(CalendarSupportedParameters.TITLE.getValue(), element);
|
final String title = this.fromApiJsonHelper.extractStringNamed(CalendarSupportedParameters.TITLE.getValue(), element);
|
||||||
@@ -100,7 +100,7 @@ public class CalendarCommandFromApiJsonDeserializer extends AbstractFromApiJsonD
|
|||||||
}
|
}
|
||||||
|
|
||||||
final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType();
|
final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType();
|
||||||
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParameters);
|
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, SUPPORTED_PARAMETERS);
|
||||||
final JsonElement element = this.fromApiJsonHelper.parse(json);
|
final JsonElement element = this.fromApiJsonHelper.parse(json);
|
||||||
|
|
||||||
final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
|
final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
|
||||||
@@ -221,7 +221,7 @@ public class CalendarCommandFromApiJsonDeserializer extends AbstractFromApiJsonD
|
|||||||
}
|
}
|
||||||
|
|
||||||
final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType();
|
final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType();
|
||||||
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParameters);
|
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, SUPPORTED_PARAMETERS);
|
||||||
final JsonElement element = this.fromApiJsonHelper.parse(json);
|
final JsonElement element = this.fromApiJsonHelper.parse(json);
|
||||||
|
|
||||||
final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
|
final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
|
||||||
|
|||||||
+12
-12
@@ -64,13 +64,13 @@ import org.springframework.stereotype.Component;
|
|||||||
+ "At present we support defining charges for use with Client accounts and both loan and saving products.")
|
+ "At present we support defining charges for use with Client accounts and both loan and saving products.")
|
||||||
public class ChargesApiResource {
|
public class ChargesApiResource {
|
||||||
|
|
||||||
private final Set<String> chargesDataParameters = new HashSet<>(Arrays.asList("id", "name", "amount", "currency", "penalty", "active",
|
private static final Set<String> CHARGES_DATA_PARAMETERS = new HashSet<>(Arrays.asList("id", "name", "amount", "currency", "penalty",
|
||||||
"chargeAppliesTo", "chargeTimeType", "chargeCalculationType", "chargeCalculationTypeOptions", "chargeAppliesToOptions",
|
"active", "chargeAppliesTo", "chargeTimeType", "chargeCalculationType", "chargeCalculationTypeOptions",
|
||||||
"chargeTimeTypeOptions", "currencyOptions", "loanChargeCalculationTypeOptions", "loanChargeTimeTypeOptions",
|
"chargeAppliesToOptions", "chargeTimeTypeOptions", "currencyOptions", "loanChargeCalculationTypeOptions",
|
||||||
"savingsChargeCalculationTypeOptions", "savingsChargeTimeTypeOptions", "incomeAccount", "clientChargeCalculationTypeOptions",
|
"loanChargeTimeTypeOptions", "savingsChargeCalculationTypeOptions", "savingsChargeTimeTypeOptions", "incomeAccount",
|
||||||
"clientChargeTimeTypeOptions"));
|
"clientChargeCalculationTypeOptions", "clientChargeTimeTypeOptions"));
|
||||||
|
|
||||||
private final String resourceNameForPermissions = "CHARGE";
|
private static final String RESOURCE_NAME_FOR_PERMISSIONS = "CHARGE";
|
||||||
|
|
||||||
private final PlatformSecurityContext context;
|
private final PlatformSecurityContext context;
|
||||||
private final ChargeReadPlatformService readPlatformService;
|
private final ChargeReadPlatformService readPlatformService;
|
||||||
@@ -98,12 +98,12 @@ public class ChargesApiResource {
|
|||||||
@ApiResponse(responseCode = "200", description = "OK", content = @Content(array = @ArraySchema(schema = @Schema(implementation = ChargesApiResourceSwagger.GetChargesResponse.class)))) })
|
@ApiResponse(responseCode = "200", description = "OK", content = @Content(array = @ArraySchema(schema = @Schema(implementation = ChargesApiResourceSwagger.GetChargesResponse.class)))) })
|
||||||
public String retrieveAllCharges(@Context final UriInfo uriInfo) {
|
public String retrieveAllCharges(@Context final UriInfo uriInfo) {
|
||||||
|
|
||||||
this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions);
|
this.context.authenticatedUser().validateHasReadPermission(RESOURCE_NAME_FOR_PERMISSIONS);
|
||||||
|
|
||||||
final Collection<ChargeData> charges = this.readPlatformService.retrieveAllCharges();
|
final Collection<ChargeData> charges = this.readPlatformService.retrieveAllCharges();
|
||||||
|
|
||||||
final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters());
|
final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters());
|
||||||
return this.toApiJsonSerializer.serialize(settings, charges, this.chargesDataParameters);
|
return this.toApiJsonSerializer.serialize(settings, charges, CHARGES_DATA_PARAMETERS);
|
||||||
}
|
}
|
||||||
|
|
||||||
@GET
|
@GET
|
||||||
@@ -117,7 +117,7 @@ public class ChargesApiResource {
|
|||||||
public String retrieveCharge(@PathParam("chargeId") @Parameter(description = "chargeId") final Long chargeId,
|
public String retrieveCharge(@PathParam("chargeId") @Parameter(description = "chargeId") final Long chargeId,
|
||||||
@Context final UriInfo uriInfo) {
|
@Context final UriInfo uriInfo) {
|
||||||
|
|
||||||
this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions);
|
this.context.authenticatedUser().validateHasReadPermission(RESOURCE_NAME_FOR_PERMISSIONS);
|
||||||
|
|
||||||
final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters());
|
final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters());
|
||||||
|
|
||||||
@@ -127,7 +127,7 @@ public class ChargesApiResource {
|
|||||||
charge = ChargeData.withTemplate(charge, templateData);
|
charge = ChargeData.withTemplate(charge, templateData);
|
||||||
}
|
}
|
||||||
|
|
||||||
return this.toApiJsonSerializer.serialize(settings, charge, this.chargesDataParameters);
|
return this.toApiJsonSerializer.serialize(settings, charge, CHARGES_DATA_PARAMETERS);
|
||||||
}
|
}
|
||||||
|
|
||||||
@GET
|
@GET
|
||||||
@@ -140,12 +140,12 @@ public class ChargesApiResource {
|
|||||||
@ApiResponse(responseCode = "200", description = "OK", content = @Content(schema = @Schema(implementation = ChargesApiResourceSwagger.GetChargesTemplateResponse.class))) })
|
@ApiResponse(responseCode = "200", description = "OK", content = @Content(schema = @Schema(implementation = ChargesApiResourceSwagger.GetChargesTemplateResponse.class))) })
|
||||||
public String retrieveNewChargeDetails(@Context final UriInfo uriInfo) {
|
public String retrieveNewChargeDetails(@Context final UriInfo uriInfo) {
|
||||||
|
|
||||||
this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions);
|
this.context.authenticatedUser().validateHasReadPermission(RESOURCE_NAME_FOR_PERMISSIONS);
|
||||||
|
|
||||||
final ChargeData charge = this.readPlatformService.retrieveNewChargeDetails();
|
final ChargeData charge = this.readPlatformService.retrieveNewChargeDetails();
|
||||||
|
|
||||||
final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters());
|
final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters());
|
||||||
return this.toApiJsonSerializer.serialize(settings, charge, this.chargesDataParameters);
|
return this.toApiJsonSerializer.serialize(settings, charge, CHARGES_DATA_PARAMETERS);
|
||||||
}
|
}
|
||||||
|
|
||||||
@POST
|
@POST
|
||||||
|
|||||||
+186
-159
@@ -48,15 +48,39 @@ import org.springframework.stereotype.Component;
|
|||||||
@Component
|
@Component
|
||||||
public final class ChargeDefinitionCommandFromApiJsonDeserializer {
|
public final class ChargeDefinitionCommandFromApiJsonDeserializer {
|
||||||
|
|
||||||
|
public static final String NAME = "name";
|
||||||
|
public static final String AMOUNT = "amount";
|
||||||
|
public static final String LOCALE = "locale";
|
||||||
|
public static final String CURRENCY_CODE = "currencyCode";
|
||||||
|
public static final String PENALTY = "penalty";
|
||||||
|
public static final String CHARGE_CALCULATION_TYPE_OPTIONS = "chargeCalculationTypeOptions";
|
||||||
|
public static final String CHARGE_CALCULATION_TYPE = "chargeCalculationType";
|
||||||
|
public static final String CHARGE_TIME_TYPE = "chargeTimeType";
|
||||||
|
public static final String CHARGE_APPLIES_TO = "chargeAppliesTo";
|
||||||
|
public static final String CURRENCY_OPTIONS = "currencyOptions";
|
||||||
|
public static final String ACTIVE = "active";
|
||||||
|
public static final String CHARGE_PAYMENT_MODE = "chargePaymentMode";
|
||||||
|
public static final String FEE_ON_MONTH_DAY = "feeOnMonthDay";
|
||||||
|
public static final String FEE_INTERVAL = "feeInterval";
|
||||||
|
public static final String MONTH_DAY_FORMAT = "monthDayFormat";
|
||||||
|
public static final String MIN_CAP = "minCap";
|
||||||
|
public static final String MAX_CAP = "maxCap";
|
||||||
|
public static final String FEE_FREQUENCY = "feeFrequency";
|
||||||
|
public static final String ENABLE_FREE_WITHDRAWAL_CHARGE = "enableFreeWithdrawalCharge";
|
||||||
|
public static final String FREE_WITHDRAWAL_FREQUENCY = "freeWithdrawalFrequency";
|
||||||
|
public static final String RESTART_COUNT_FREQUENCY = "restartCountFrequency";
|
||||||
|
public static final String COUNT_FREQUENCY_TYPE = "countFrequencyType";
|
||||||
|
public static final String ENABLE_PAYMENT_TYPE = "enablePaymentType";
|
||||||
|
public static final String PAYMENT_TYPE_ID = "paymentTypeId";
|
||||||
|
public static final String CHARGE = "charge";
|
||||||
/**
|
/**
|
||||||
* The parameters supported for this command.
|
* The parameters supported for this command.
|
||||||
*/
|
*/
|
||||||
private final Set<String> supportedParameters = new HashSet<>(Arrays.asList("name", "amount", "locale", "currencyCode",
|
private static final Set<String> SUPPORTED_PARAMETERS = new HashSet<>(Arrays.asList(NAME, AMOUNT, LOCALE, CURRENCY_CODE,
|
||||||
"currencyOptions", "chargeAppliesTo", "chargeTimeType", "chargeCalculationType", "chargeCalculationTypeOptions", "penalty",
|
CURRENCY_OPTIONS, CHARGE_APPLIES_TO, CHARGE_TIME_TYPE, CHARGE_CALCULATION_TYPE, CHARGE_CALCULATION_TYPE_OPTIONS, PENALTY,
|
||||||
"active", "chargePaymentMode", "feeOnMonthDay", "feeInterval", "monthDayFormat", "minCap", "maxCap", "feeFrequency",
|
ACTIVE, CHARGE_PAYMENT_MODE, FEE_ON_MONTH_DAY, FEE_INTERVAL, MONTH_DAY_FORMAT, MIN_CAP, MAX_CAP, FEE_FREQUENCY,
|
||||||
"enableFreeWithdrawalCharge", "freeWithdrawalFrequency", "restartCountFrequency", "countFrequencyType", "paymentTypeId",
|
ENABLE_FREE_WITHDRAWAL_CHARGE, FREE_WITHDRAWAL_FREQUENCY, RESTART_COUNT_FREQUENCY, COUNT_FREQUENCY_TYPE, PAYMENT_TYPE_ID,
|
||||||
"enablePaymentType", ChargesApiConstants.glAccountIdParamName, ChargesApiConstants.taxGroupIdParamName));
|
ENABLE_PAYMENT_TYPE, ChargesApiConstants.glAccountIdParamName, ChargesApiConstants.taxGroupIdParamName));
|
||||||
|
|
||||||
private final FromJsonHelper fromApiJsonHelper;
|
private final FromJsonHelper fromApiJsonHelper;
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
@@ -69,86 +93,88 @@ public final class ChargeDefinitionCommandFromApiJsonDeserializer {
|
|||||||
throw new InvalidJsonException();
|
throw new InvalidJsonException();
|
||||||
}
|
}
|
||||||
|
|
||||||
final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType();
|
final Type typeOfMap = new TypeToken<Map<String, Object>>() {
|
||||||
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParameters);
|
|
||||||
|
}.getType();
|
||||||
|
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, SUPPORTED_PARAMETERS);
|
||||||
|
|
||||||
final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
|
final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
|
||||||
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("charge");
|
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource(CHARGE);
|
||||||
|
|
||||||
final JsonElement element = this.fromApiJsonHelper.parse(json);
|
final JsonElement element = this.fromApiJsonHelper.parse(json);
|
||||||
|
|
||||||
final Integer chargeAppliesTo = this.fromApiJsonHelper.extractIntegerSansLocaleNamed("chargeAppliesTo", element);
|
final Integer chargeAppliesTo = this.fromApiJsonHelper.extractIntegerSansLocaleNamed(CHARGE_APPLIES_TO, element);
|
||||||
baseDataValidator.reset().parameter("chargeAppliesTo").value(chargeAppliesTo).notNull();
|
baseDataValidator.reset().parameter(CHARGE_APPLIES_TO).value(chargeAppliesTo).notNull();
|
||||||
if (chargeAppliesTo != null) {
|
if (chargeAppliesTo != null) {
|
||||||
baseDataValidator.reset().parameter("chargeAppliesTo").value(chargeAppliesTo).isOneOfTheseValues(ChargeAppliesTo.validValues());
|
baseDataValidator.reset().parameter(CHARGE_APPLIES_TO).value(chargeAppliesTo).isOneOfTheseValues(ChargeAppliesTo.validValues());
|
||||||
}
|
}
|
||||||
|
|
||||||
final Integer chargeCalculationType = this.fromApiJsonHelper.extractIntegerSansLocaleNamed("chargeCalculationType", element);
|
final Integer chargeCalculationType = this.fromApiJsonHelper.extractIntegerSansLocaleNamed(CHARGE_CALCULATION_TYPE, element);
|
||||||
baseDataValidator.reset().parameter("chargeCalculationType").value(chargeCalculationType).notNull();
|
baseDataValidator.reset().parameter(CHARGE_CALCULATION_TYPE).value(chargeCalculationType).notNull();
|
||||||
|
|
||||||
final Integer feeInterval = this.fromApiJsonHelper.extractIntegerNamed("feeInterval", element, Locale.getDefault());
|
final Integer feeInterval = this.fromApiJsonHelper.extractIntegerNamed(FEE_INTERVAL, element, Locale.getDefault());
|
||||||
baseDataValidator.reset().parameter("feeInterval").value(feeInterval).integerGreaterThanZero();
|
baseDataValidator.reset().parameter(FEE_INTERVAL).value(feeInterval).integerGreaterThanZero();
|
||||||
|
|
||||||
final Integer feeFrequency = this.fromApiJsonHelper.extractIntegerNamed("feeFrequency", element, Locale.getDefault());
|
final Integer feeFrequency = this.fromApiJsonHelper.extractIntegerNamed(FEE_FREQUENCY, element, Locale.getDefault());
|
||||||
baseDataValidator.reset().parameter("feeFrequency").value(feeFrequency).inMinMaxRange(0, 3);
|
baseDataValidator.reset().parameter(FEE_FREQUENCY).value(feeFrequency).inMinMaxRange(0, 3);
|
||||||
|
|
||||||
if (this.fromApiJsonHelper.parameterExists("enableFreeWithdrawalCharge", element)) {
|
if (this.fromApiJsonHelper.parameterExists(ENABLE_FREE_WITHDRAWAL_CHARGE, element)) {
|
||||||
|
|
||||||
final Boolean enableFreeWithdrawalCharge = this.fromApiJsonHelper.extractBooleanNamed("enableFreeWithdrawalCharge", element);
|
final Boolean enableFreeWithdrawalCharge = this.fromApiJsonHelper.extractBooleanNamed(ENABLE_FREE_WITHDRAWAL_CHARGE, element);
|
||||||
baseDataValidator.reset().parameter("enableFreeWithdrawalCharge").value(enableFreeWithdrawalCharge).notNull();
|
baseDataValidator.reset().parameter(ENABLE_FREE_WITHDRAWAL_CHARGE).value(enableFreeWithdrawalCharge).notNull();
|
||||||
|
|
||||||
if (enableFreeWithdrawalCharge) {
|
if (enableFreeWithdrawalCharge) {
|
||||||
|
|
||||||
final Integer freeWithdrawalFrequency = this.fromApiJsonHelper.extractIntegerNamed("freeWithdrawalFrequency", element,
|
final Integer freeWithdrawalFrequency = this.fromApiJsonHelper.extractIntegerNamed(FREE_WITHDRAWAL_FREQUENCY, element,
|
||||||
Locale.getDefault());
|
Locale.getDefault());
|
||||||
baseDataValidator.reset().parameter("freeWithdrawalFrequency").value(freeWithdrawalFrequency).integerGreaterThanZero();
|
baseDataValidator.reset().parameter(FREE_WITHDRAWAL_FREQUENCY).value(freeWithdrawalFrequency).integerGreaterThanZero();
|
||||||
|
|
||||||
final Integer restartCountFrequency = this.fromApiJsonHelper.extractIntegerNamed("restartCountFrequency", element,
|
final Integer restartCountFrequency = this.fromApiJsonHelper.extractIntegerNamed(RESTART_COUNT_FREQUENCY, element,
|
||||||
Locale.getDefault());
|
Locale.getDefault());
|
||||||
baseDataValidator.reset().parameter("restartCountFrequency").value(restartCountFrequency).integerGreaterThanZero();
|
baseDataValidator.reset().parameter(RESTART_COUNT_FREQUENCY).value(restartCountFrequency).integerGreaterThanZero();
|
||||||
|
|
||||||
final Integer countFrequencyType = this.fromApiJsonHelper.extractIntegerNamed("countFrequencyType", element,
|
final Integer countFrequencyType = this.fromApiJsonHelper.extractIntegerNamed(COUNT_FREQUENCY_TYPE, element,
|
||||||
Locale.getDefault());
|
Locale.getDefault());
|
||||||
baseDataValidator.reset().parameter("countFrequencyType").value(countFrequencyType);
|
baseDataValidator.reset().parameter(COUNT_FREQUENCY_TYPE).value(countFrequencyType);
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (this.fromApiJsonHelper.parameterExists("enablePaymentType", element)) {
|
if (this.fromApiJsonHelper.parameterExists(ENABLE_PAYMENT_TYPE, element)) {
|
||||||
|
|
||||||
final boolean enablePaymentType = this.fromApiJsonHelper.extractBooleanNamed("enablePaymentType", element);
|
final boolean enablePaymentType = this.fromApiJsonHelper.extractBooleanNamed(ENABLE_PAYMENT_TYPE, element);
|
||||||
baseDataValidator.reset().parameter("enablePaymentType").value(enablePaymentType).notNull();
|
baseDataValidator.reset().parameter(ENABLE_PAYMENT_TYPE).value(enablePaymentType).notNull();
|
||||||
|
|
||||||
if (enablePaymentType) {
|
if (enablePaymentType) {
|
||||||
final Integer paymentTypeId = this.fromApiJsonHelper.extractIntegerNamed("paymentTypeId", element, Locale.getDefault());
|
final Integer paymentTypeId = this.fromApiJsonHelper.extractIntegerNamed(PAYMENT_TYPE_ID, element, Locale.getDefault());
|
||||||
baseDataValidator.reset().parameter("paymentTypeId").value(paymentTypeId).integerGreaterThanZero();
|
baseDataValidator.reset().parameter(PAYMENT_TYPE_ID).value(paymentTypeId).integerGreaterThanZero();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (feeFrequency != null) {
|
if (feeFrequency != null) {
|
||||||
baseDataValidator.reset().parameter("feeInterval").value(feeInterval).notNull();
|
baseDataValidator.reset().parameter(FEE_INTERVAL).value(feeInterval).notNull();
|
||||||
}
|
}
|
||||||
|
|
||||||
final ChargeAppliesTo appliesTo = ChargeAppliesTo.fromInt(chargeAppliesTo);
|
final ChargeAppliesTo appliesTo = ChargeAppliesTo.fromInt(chargeAppliesTo);
|
||||||
if (appliesTo.isLoanCharge()) {
|
if (appliesTo.isLoanCharge()) {
|
||||||
// loan applicable validation
|
// loan applicable validation
|
||||||
final Integer chargeTimeType = this.fromApiJsonHelper.extractIntegerSansLocaleNamed("chargeTimeType", element);
|
final Integer chargeTimeType = this.fromApiJsonHelper.extractIntegerSansLocaleNamed(CHARGE_TIME_TYPE, element);
|
||||||
baseDataValidator.reset().parameter("chargeTimeType").value(chargeTimeType).notNull();
|
baseDataValidator.reset().parameter(CHARGE_TIME_TYPE).value(chargeTimeType).notNull();
|
||||||
if (chargeTimeType != null) {
|
if (chargeTimeType != null) {
|
||||||
baseDataValidator.reset().parameter("chargeTimeType").value(chargeTimeType)
|
baseDataValidator.reset().parameter(CHARGE_TIME_TYPE).value(chargeTimeType)
|
||||||
.isOneOfTheseValues(ChargeTimeType.validLoanValues());
|
.isOneOfTheseValues(ChargeTimeType.validLoanValues());
|
||||||
}
|
}
|
||||||
|
|
||||||
final Integer chargePaymentMode = this.fromApiJsonHelper.extractIntegerSansLocaleNamed("chargePaymentMode", element);
|
final Integer chargePaymentMode = this.fromApiJsonHelper.extractIntegerSansLocaleNamed(CHARGE_PAYMENT_MODE, element);
|
||||||
baseDataValidator.reset().parameter("chargePaymentMode").value(chargePaymentMode).notNull()
|
baseDataValidator.reset().parameter(CHARGE_PAYMENT_MODE).value(chargePaymentMode).notNull()
|
||||||
.isOneOfTheseValues(ChargePaymentMode.validValues());
|
.isOneOfTheseValues(ChargePaymentMode.validValues());
|
||||||
if (chargePaymentMode != null) {
|
if (chargePaymentMode != null) {
|
||||||
baseDataValidator.reset().parameter("chargePaymentMode").value(chargePaymentMode)
|
baseDataValidator.reset().parameter(CHARGE_PAYMENT_MODE).value(chargePaymentMode)
|
||||||
.isOneOfTheseValues(ChargePaymentMode.validValues());
|
.isOneOfTheseValues(ChargePaymentMode.validValues());
|
||||||
}
|
}
|
||||||
|
|
||||||
if (chargeCalculationType != null) {
|
if (chargeCalculationType != null) {
|
||||||
baseDataValidator.reset().parameter("chargeCalculationType").value(chargeCalculationType)
|
baseDataValidator.reset().parameter(CHARGE_CALCULATION_TYPE).value(chargeCalculationType)
|
||||||
.isOneOfTheseValues(ChargeCalculationType.validValuesForLoan());
|
.isOneOfTheseValues(ChargeCalculationType.validValuesForLoan());
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -158,49 +184,49 @@ public final class ChargeDefinitionCommandFromApiJsonDeserializer {
|
|||||||
|
|
||||||
} else if (appliesTo.isSavingsCharge()) {
|
} else if (appliesTo.isSavingsCharge()) {
|
||||||
// savings applicable validation
|
// savings applicable validation
|
||||||
final Integer chargeTimeType = this.fromApiJsonHelper.extractIntegerSansLocaleNamed("chargeTimeType", element);
|
final Integer chargeTimeType = this.fromApiJsonHelper.extractIntegerSansLocaleNamed(CHARGE_TIME_TYPE, element);
|
||||||
baseDataValidator.reset().parameter("chargeTimeType").value(chargeTimeType).notNull();
|
baseDataValidator.reset().parameter(CHARGE_TIME_TYPE).value(chargeTimeType).notNull();
|
||||||
if (chargeTimeType != null) {
|
if (chargeTimeType != null) {
|
||||||
baseDataValidator.reset().parameter("chargeTimeType").value(chargeTimeType)
|
baseDataValidator.reset().parameter(CHARGE_TIME_TYPE).value(chargeTimeType)
|
||||||
.isOneOfTheseValues(ChargeTimeType.validSavingsValues());
|
.isOneOfTheseValues(ChargeTimeType.validSavingsValues());
|
||||||
}
|
}
|
||||||
|
|
||||||
final ChargeTimeType ctt = ChargeTimeType.fromInt(chargeTimeType);
|
final ChargeTimeType ctt = ChargeTimeType.fromInt(chargeTimeType);
|
||||||
|
|
||||||
if (ctt.isWeeklyFee()) {
|
if (ctt.isWeeklyFee()) {
|
||||||
final String monthDay = this.fromApiJsonHelper.extractStringNamed("feeOnMonthDay", element);
|
final String monthDay = this.fromApiJsonHelper.extractStringNamed(FEE_ON_MONTH_DAY, element);
|
||||||
baseDataValidator.reset().parameter("feeOnMonthDay").value(monthDay).mustBeBlankWhenParameterProvidedIs("chargeTimeType",
|
baseDataValidator.reset().parameter(FEE_ON_MONTH_DAY).value(monthDay).mustBeBlankWhenParameterProvidedIs(CHARGE_TIME_TYPE,
|
||||||
chargeTimeType);
|
chargeTimeType);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (ctt.isMonthlyFee()) {
|
if (ctt.isMonthlyFee()) {
|
||||||
final MonthDay monthDay = this.fromApiJsonHelper.extractMonthDayNamed("feeOnMonthDay", element);
|
final MonthDay monthDay = this.fromApiJsonHelper.extractMonthDayNamed(FEE_ON_MONTH_DAY, element);
|
||||||
baseDataValidator.reset().parameter("feeOnMonthDay").value(monthDay).notNull();
|
baseDataValidator.reset().parameter(FEE_ON_MONTH_DAY).value(monthDay).notNull();
|
||||||
|
|
||||||
baseDataValidator.reset().parameter("feeInterval").value(feeInterval).notNull().inMinMaxRange(1, 12);
|
baseDataValidator.reset().parameter(FEE_INTERVAL).value(feeInterval).notNull().inMinMaxRange(1, 12);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (ctt.isAnnualFee()) {
|
if (ctt.isAnnualFee()) {
|
||||||
final MonthDay monthDay = this.fromApiJsonHelper.extractMonthDayNamed("feeOnMonthDay", element);
|
final MonthDay monthDay = this.fromApiJsonHelper.extractMonthDayNamed(FEE_ON_MONTH_DAY, element);
|
||||||
baseDataValidator.reset().parameter("feeOnMonthDay").value(monthDay).notNull();
|
baseDataValidator.reset().parameter(FEE_ON_MONTH_DAY).value(monthDay).notNull();
|
||||||
}
|
}
|
||||||
|
|
||||||
if (chargeCalculationType != null) {
|
if (chargeCalculationType != null) {
|
||||||
baseDataValidator.reset().parameter("chargeCalculationType").value(chargeCalculationType)
|
baseDataValidator.reset().parameter(CHARGE_CALCULATION_TYPE).value(chargeCalculationType)
|
||||||
.isOneOfTheseValues(ChargeCalculationType.validValuesForSavings());
|
.isOneOfTheseValues(ChargeCalculationType.validValuesForSavings());
|
||||||
}
|
}
|
||||||
|
|
||||||
} else if (appliesTo.isClientCharge()) {
|
} else if (appliesTo.isClientCharge()) {
|
||||||
// client applicable validation
|
// client applicable validation
|
||||||
final Integer chargeTimeType = this.fromApiJsonHelper.extractIntegerSansLocaleNamed("chargeTimeType", element);
|
final Integer chargeTimeType = this.fromApiJsonHelper.extractIntegerSansLocaleNamed(CHARGE_TIME_TYPE, element);
|
||||||
baseDataValidator.reset().parameter("chargeTimeType").value(chargeTimeType).notNull();
|
baseDataValidator.reset().parameter(CHARGE_TIME_TYPE).value(chargeTimeType).notNull();
|
||||||
if (chargeTimeType != null) {
|
if (chargeTimeType != null) {
|
||||||
baseDataValidator.reset().parameter("chargeTimeType").value(chargeTimeType)
|
baseDataValidator.reset().parameter(CHARGE_TIME_TYPE).value(chargeTimeType)
|
||||||
.isOneOfTheseValues(ChargeTimeType.validClientValues());
|
.isOneOfTheseValues(ChargeTimeType.validClientValues());
|
||||||
}
|
}
|
||||||
|
|
||||||
if (chargeCalculationType != null) {
|
if (chargeCalculationType != null) {
|
||||||
baseDataValidator.reset().parameter("chargeCalculationType").value(chargeCalculationType)
|
baseDataValidator.reset().parameter(CHARGE_CALCULATION_TYPE).value(chargeCalculationType)
|
||||||
.isOneOfTheseValues(ChargeCalculationType.validValuesForClients());
|
.isOneOfTheseValues(ChargeCalculationType.validValuesForClients());
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -212,52 +238,51 @@ public final class ChargeDefinitionCommandFromApiJsonDeserializer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
} else if (appliesTo.isSharesCharge()) {
|
} else if (appliesTo.isSharesCharge()) {
|
||||||
final Integer chargeTimeType = this.fromApiJsonHelper.extractIntegerSansLocaleNamed("chargeTimeType", element);
|
final Integer chargeTimeType = this.fromApiJsonHelper.extractIntegerSansLocaleNamed(CHARGE_TIME_TYPE, element);
|
||||||
baseDataValidator.reset().parameter("chargeTimeType").value(chargeTimeType).notNull();
|
baseDataValidator.reset().parameter(CHARGE_TIME_TYPE).value(chargeTimeType).notNull();
|
||||||
if (chargeTimeType != null) {
|
if (chargeTimeType != null) {
|
||||||
baseDataValidator.reset().parameter("chargeTimeType").value(chargeTimeType)
|
baseDataValidator.reset().parameter(CHARGE_TIME_TYPE).value(chargeTimeType)
|
||||||
.isOneOfTheseValues(ChargeTimeType.validShareValues());
|
.isOneOfTheseValues(ChargeTimeType.validShareValues());
|
||||||
}
|
}
|
||||||
|
|
||||||
if (chargeCalculationType != null) {
|
if (chargeCalculationType != null) {
|
||||||
baseDataValidator.reset().parameter("chargeCalculationType").value(chargeCalculationType)
|
baseDataValidator.reset().parameter(CHARGE_CALCULATION_TYPE).value(chargeCalculationType)
|
||||||
.isOneOfTheseValues(ChargeCalculationType.validValuesForShares());
|
.isOneOfTheseValues(ChargeCalculationType.validValuesForShares());
|
||||||
}
|
}
|
||||||
|
|
||||||
if (chargeTimeType != null && chargeTimeType.equals(ChargeTimeType.SHAREACCOUNT_ACTIVATION.getValue())) {
|
if (chargeTimeType != null && chargeTimeType.equals(ChargeTimeType.SHAREACCOUNT_ACTIVATION.getValue())
|
||||||
if (chargeCalculationType != null) {
|
&& chargeCalculationType != null) {
|
||||||
baseDataValidator.reset().parameter("chargeCalculationType").value(chargeCalculationType)
|
baseDataValidator.reset().parameter(CHARGE_CALCULATION_TYPE).value(chargeCalculationType)
|
||||||
.isOneOfTheseValues(ChargeCalculationType.validValuesForShareAccountActivation());
|
.isOneOfTheseValues(ChargeCalculationType.validValuesForShareAccountActivation());
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
final String name = this.fromApiJsonHelper.extractStringNamed("name", element);
|
final String name = this.fromApiJsonHelper.extractStringNamed(NAME, element);
|
||||||
baseDataValidator.reset().parameter("name").value(name).notBlank().notExceedingLengthOf(100);
|
baseDataValidator.reset().parameter(NAME).value(name).notBlank().notExceedingLengthOf(100);
|
||||||
|
|
||||||
final String currencyCode = this.fromApiJsonHelper.extractStringNamed("currencyCode", element);
|
final String currencyCode = this.fromApiJsonHelper.extractStringNamed(CURRENCY_CODE, element);
|
||||||
baseDataValidator.reset().parameter("currencyCode").value(currencyCode).notBlank().notExceedingLengthOf(3);
|
baseDataValidator.reset().parameter(CURRENCY_CODE).value(currencyCode).notBlank().notExceedingLengthOf(3);
|
||||||
|
|
||||||
final BigDecimal amount = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed("amount", element.getAsJsonObject());
|
final BigDecimal amount = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed(AMOUNT, element.getAsJsonObject());
|
||||||
baseDataValidator.reset().parameter("amount").value(amount).notNull().positiveAmount();
|
baseDataValidator.reset().parameter(AMOUNT).value(amount).notNull().positiveAmount();
|
||||||
|
|
||||||
if (this.fromApiJsonHelper.parameterExists("penalty", element)) {
|
if (this.fromApiJsonHelper.parameterExists(PENALTY, element)) {
|
||||||
final Boolean penalty = this.fromApiJsonHelper.extractBooleanNamed("penalty", element);
|
final Boolean penalty = this.fromApiJsonHelper.extractBooleanNamed(PENALTY, element);
|
||||||
baseDataValidator.reset().parameter("penalty").value(penalty).notNull();
|
baseDataValidator.reset().parameter(PENALTY).value(penalty).notNull();
|
||||||
}
|
}
|
||||||
|
|
||||||
if (this.fromApiJsonHelper.parameterExists("active", element)) {
|
if (this.fromApiJsonHelper.parameterExists(ACTIVE, element)) {
|
||||||
final Boolean active = this.fromApiJsonHelper.extractBooleanNamed("active", element);
|
final Boolean active = this.fromApiJsonHelper.extractBooleanNamed(ACTIVE, element);
|
||||||
baseDataValidator.reset().parameter("active").value(active).notNull();
|
baseDataValidator.reset().parameter(ACTIVE).value(active).notNull();
|
||||||
}
|
}
|
||||||
|
|
||||||
if (this.fromApiJsonHelper.parameterExists("minCap", element)) {
|
if (this.fromApiJsonHelper.parameterExists(MIN_CAP, element)) {
|
||||||
final BigDecimal minCap = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed("minCap", element.getAsJsonObject());
|
final BigDecimal minCap = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed(MIN_CAP, element.getAsJsonObject());
|
||||||
baseDataValidator.reset().parameter("minCap").value(minCap).notNull().positiveAmount();
|
baseDataValidator.reset().parameter(MIN_CAP).value(minCap).notNull().positiveAmount();
|
||||||
}
|
}
|
||||||
if (this.fromApiJsonHelper.parameterExists("maxCap", element)) {
|
if (this.fromApiJsonHelper.parameterExists(MAX_CAP, element)) {
|
||||||
final BigDecimal maxCap = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed("maxCap", element.getAsJsonObject());
|
final BigDecimal maxCap = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed(MAX_CAP, element.getAsJsonObject());
|
||||||
baseDataValidator.reset().parameter("maxCap").value(maxCap).notNull().positiveAmount();
|
baseDataValidator.reset().parameter(MAX_CAP).value(maxCap).notNull().positiveAmount();
|
||||||
}
|
}
|
||||||
|
|
||||||
if (this.fromApiJsonHelper.parameterExists(ChargesApiConstants.taxGroupIdParamName, element)) {
|
if (this.fromApiJsonHelper.parameterExists(ChargesApiConstants.taxGroupIdParamName, element)) {
|
||||||
@@ -273,92 +298,94 @@ public final class ChargeDefinitionCommandFromApiJsonDeserializer {
|
|||||||
throw new InvalidJsonException();
|
throw new InvalidJsonException();
|
||||||
}
|
}
|
||||||
|
|
||||||
final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType();
|
final Type typeOfMap = new TypeToken<Map<String, Object>>() {
|
||||||
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParameters);
|
|
||||||
|
}.getType();
|
||||||
|
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, SUPPORTED_PARAMETERS);
|
||||||
|
|
||||||
final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
|
final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
|
||||||
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("charge");
|
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource(CHARGE);
|
||||||
|
|
||||||
final JsonElement element = this.fromApiJsonHelper.parse(json);
|
final JsonElement element = this.fromApiJsonHelper.parse(json);
|
||||||
|
|
||||||
if (this.fromApiJsonHelper.parameterExists("name", element)) {
|
if (this.fromApiJsonHelper.parameterExists(NAME, element)) {
|
||||||
final String name = this.fromApiJsonHelper.extractStringNamed("name", element);
|
final String name = this.fromApiJsonHelper.extractStringNamed(NAME, element);
|
||||||
baseDataValidator.reset().parameter("name").value(name).notBlank().notExceedingLengthOf(100);
|
baseDataValidator.reset().parameter(NAME).value(name).notBlank().notExceedingLengthOf(100);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (this.fromApiJsonHelper.parameterExists("currencyCode", element)) {
|
if (this.fromApiJsonHelper.parameterExists(CURRENCY_CODE, element)) {
|
||||||
final String currencyCode = this.fromApiJsonHelper.extractStringNamed("currencyCode", element);
|
final String currencyCode = this.fromApiJsonHelper.extractStringNamed(CURRENCY_CODE, element);
|
||||||
baseDataValidator.reset().parameter("currencyCode").value(currencyCode).notBlank().notExceedingLengthOf(3);
|
baseDataValidator.reset().parameter(CURRENCY_CODE).value(currencyCode).notBlank().notExceedingLengthOf(3);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (this.fromApiJsonHelper.parameterExists("amount", element)) {
|
if (this.fromApiJsonHelper.parameterExists(AMOUNT, element)) {
|
||||||
final BigDecimal amount = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed("amount", element.getAsJsonObject());
|
final BigDecimal amount = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed(AMOUNT, element.getAsJsonObject());
|
||||||
baseDataValidator.reset().parameter("amount").value(amount).notNull().positiveAmount();
|
baseDataValidator.reset().parameter(AMOUNT).value(amount).notNull().positiveAmount();
|
||||||
}
|
}
|
||||||
|
|
||||||
if (this.fromApiJsonHelper.parameterExists("minCap", element)) {
|
if (this.fromApiJsonHelper.parameterExists(MIN_CAP, element)) {
|
||||||
final BigDecimal minCap = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed("minCap", element.getAsJsonObject());
|
final BigDecimal minCap = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed(MIN_CAP, element.getAsJsonObject());
|
||||||
baseDataValidator.reset().parameter("minCap").value(minCap).notNull().positiveAmount();
|
baseDataValidator.reset().parameter(MIN_CAP).value(minCap).notNull().positiveAmount();
|
||||||
}
|
}
|
||||||
|
|
||||||
if (this.fromApiJsonHelper.parameterExists("maxCap", element)) {
|
if (this.fromApiJsonHelper.parameterExists(MAX_CAP, element)) {
|
||||||
final BigDecimal maxCap = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed("maxCap", element.getAsJsonObject());
|
final BigDecimal maxCap = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed(MAX_CAP, element.getAsJsonObject());
|
||||||
baseDataValidator.reset().parameter("maxCap").value(maxCap).notNull().positiveAmount();
|
baseDataValidator.reset().parameter(MAX_CAP).value(maxCap).notNull().positiveAmount();
|
||||||
}
|
}
|
||||||
|
|
||||||
if (this.fromApiJsonHelper.parameterExists("chargeAppliesTo", element)) {
|
if (this.fromApiJsonHelper.parameterExists(CHARGE_APPLIES_TO, element)) {
|
||||||
final Integer chargeAppliesTo = this.fromApiJsonHelper.extractIntegerSansLocaleNamed("chargeAppliesTo", element);
|
final Integer chargeAppliesTo = this.fromApiJsonHelper.extractIntegerSansLocaleNamed(CHARGE_APPLIES_TO, element);
|
||||||
baseDataValidator.reset().parameter("chargeAppliesTo").value(chargeAppliesTo).notNull()
|
baseDataValidator.reset().parameter(CHARGE_APPLIES_TO).value(chargeAppliesTo).notNull()
|
||||||
.isOneOfTheseValues(ChargeAppliesTo.validValues());
|
.isOneOfTheseValues(ChargeAppliesTo.validValues());
|
||||||
}
|
}
|
||||||
|
|
||||||
Boolean enableFreeWithdrawalCharge = false;
|
Boolean enableFreeWithdrawalCharge = false;
|
||||||
if (this.fromApiJsonHelper.parameterExists("enableFreeWithdrawalCharge", element)) {
|
if (this.fromApiJsonHelper.parameterExists(ENABLE_FREE_WITHDRAWAL_CHARGE, element)) {
|
||||||
enableFreeWithdrawalCharge = this.fromApiJsonHelper.extractBooleanNamed("enableFreeWithdrawalCharge", element);
|
enableFreeWithdrawalCharge = this.fromApiJsonHelper.extractBooleanNamed(ENABLE_FREE_WITHDRAWAL_CHARGE, element);
|
||||||
baseDataValidator.reset().parameter("enableFreeWithdrawalCharge").value(enableFreeWithdrawalCharge).notNull();
|
baseDataValidator.reset().parameter(ENABLE_FREE_WITHDRAWAL_CHARGE).value(enableFreeWithdrawalCharge).notNull();
|
||||||
|
|
||||||
if (enableFreeWithdrawalCharge) {
|
if (enableFreeWithdrawalCharge) {
|
||||||
|
|
||||||
final Integer freeWithdrawalFrequency = this.fromApiJsonHelper.extractIntegerNamed("freeWithdrawalFrequency", element,
|
final Integer freeWithdrawalFrequency = this.fromApiJsonHelper.extractIntegerNamed(FREE_WITHDRAWAL_FREQUENCY, element,
|
||||||
Locale.getDefault());
|
Locale.getDefault());
|
||||||
baseDataValidator.reset().parameter("freeWithdrawalFrequency").value(freeWithdrawalFrequency).integerGreaterThanZero();
|
baseDataValidator.reset().parameter(FREE_WITHDRAWAL_FREQUENCY).value(freeWithdrawalFrequency).integerGreaterThanZero();
|
||||||
|
|
||||||
final Integer restartCountFrequency = this.fromApiJsonHelper.extractIntegerNamed("restartCountFrequency", element,
|
final Integer restartCountFrequency = this.fromApiJsonHelper.extractIntegerNamed(RESTART_COUNT_FREQUENCY, element,
|
||||||
Locale.getDefault());
|
Locale.getDefault());
|
||||||
baseDataValidator.reset().parameter("restartCountFrequency").value(restartCountFrequency).integerGreaterThanZero();
|
baseDataValidator.reset().parameter(RESTART_COUNT_FREQUENCY).value(restartCountFrequency).integerGreaterThanZero();
|
||||||
|
|
||||||
final Integer countFrequencyType = this.fromApiJsonHelper.extractIntegerNamed("countFrequencyType", element,
|
final Integer countFrequencyType = this.fromApiJsonHelper.extractIntegerNamed(COUNT_FREQUENCY_TYPE, element,
|
||||||
Locale.getDefault());
|
Locale.getDefault());
|
||||||
baseDataValidator.reset().parameter("countFrequencyType").value(countFrequencyType);
|
baseDataValidator.reset().parameter(COUNT_FREQUENCY_TYPE).value(countFrequencyType);
|
||||||
}
|
}
|
||||||
|
|
||||||
Boolean enablePaymentType = false;
|
Boolean enablePaymentType = false;
|
||||||
if (this.fromApiJsonHelper.parameterExists("enablePaymentType", element)) {
|
if (this.fromApiJsonHelper.parameterExists(ENABLE_PAYMENT_TYPE, element)) {
|
||||||
enablePaymentType = this.fromApiJsonHelper.extractBooleanNamed("enablePaymentType", element);
|
enablePaymentType = this.fromApiJsonHelper.extractBooleanNamed(ENABLE_PAYMENT_TYPE, element);
|
||||||
baseDataValidator.reset().parameter("enablePaymentType").value(enablePaymentType).notNull();
|
baseDataValidator.reset().parameter(ENABLE_PAYMENT_TYPE).value(enablePaymentType).notNull();
|
||||||
|
|
||||||
if (enablePaymentType) {
|
if (enablePaymentType) {
|
||||||
final Integer paymentTypeId = this.fromApiJsonHelper.extractIntegerNamed("paymentTypeId", element, Locale.getDefault());
|
final Integer paymentTypeId = this.fromApiJsonHelper.extractIntegerNamed(PAYMENT_TYPE_ID, element, Locale.getDefault());
|
||||||
baseDataValidator.reset().parameter("paymentTypeId").value(paymentTypeId).integerGreaterThanZero();
|
baseDataValidator.reset().parameter(PAYMENT_TYPE_ID).value(paymentTypeId).integerGreaterThanZero();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (this.fromApiJsonHelper.parameterExists("chargeAppliesTo", element)) {
|
if (this.fromApiJsonHelper.parameterExists(CHARGE_APPLIES_TO, element)) {
|
||||||
final Integer chargeAppliesTo = this.fromApiJsonHelper.extractIntegerSansLocaleNamed("chargeAppliesTo", element);
|
final Integer chargeAppliesTo = this.fromApiJsonHelper.extractIntegerSansLocaleNamed(CHARGE_APPLIES_TO, element);
|
||||||
baseDataValidator.reset().parameter("chargeAppliesTo").value(chargeAppliesTo).notNull()
|
baseDataValidator.reset().parameter(CHARGE_APPLIES_TO).value(chargeAppliesTo).notNull()
|
||||||
.isOneOfTheseValues(ChargeAppliesTo.validValues());
|
.isOneOfTheseValues(ChargeAppliesTo.validValues());
|
||||||
}
|
}
|
||||||
|
|
||||||
if (this.fromApiJsonHelper.parameterExists("chargeAppliesTo", element)) {
|
if (this.fromApiJsonHelper.parameterExists(CHARGE_APPLIES_TO, element)) {
|
||||||
final Integer chargeAppliesTo = this.fromApiJsonHelper.extractIntegerSansLocaleNamed("chargeAppliesTo", element);
|
final Integer chargeAppliesTo = this.fromApiJsonHelper.extractIntegerSansLocaleNamed(CHARGE_APPLIES_TO, element);
|
||||||
baseDataValidator.reset().parameter("chargeAppliesTo").value(chargeAppliesTo).notNull()
|
baseDataValidator.reset().parameter(CHARGE_APPLIES_TO).value(chargeAppliesTo).notNull()
|
||||||
.isOneOfTheseValues(ChargeAppliesTo.validValues());
|
.isOneOfTheseValues(ChargeAppliesTo.validValues());
|
||||||
}
|
}
|
||||||
|
|
||||||
if (this.fromApiJsonHelper.parameterExists("chargeTimeType", element)) {
|
if (this.fromApiJsonHelper.parameterExists(CHARGE_TIME_TYPE, element)) {
|
||||||
|
|
||||||
final Integer chargeTimeType = this.fromApiJsonHelper.extractIntegerSansLocaleNamed("chargeTimeType", element);
|
final Integer chargeTimeType = this.fromApiJsonHelper.extractIntegerSansLocaleNamed(CHARGE_TIME_TYPE, element);
|
||||||
|
|
||||||
final Collection<Object> validLoanValues = Arrays.asList(ChargeTimeType.validLoanValues());
|
final Collection<Object> validLoanValues = Arrays.asList(ChargeTimeType.validLoanValues());
|
||||||
final Collection<Object> validSavingsValues = Arrays.asList(ChargeTimeType.validSavingsValues());
|
final Collection<Object> validSavingsValues = Arrays.asList(ChargeTimeType.validSavingsValues());
|
||||||
@@ -368,51 +395,51 @@ public final class ChargeDefinitionCommandFromApiJsonDeserializer {
|
|||||||
allValidValues.addAll(validSavingsValues);
|
allValidValues.addAll(validSavingsValues);
|
||||||
allValidValues.addAll(validClientValues);
|
allValidValues.addAll(validClientValues);
|
||||||
allValidValues.addAll(validShareValues);
|
allValidValues.addAll(validShareValues);
|
||||||
baseDataValidator.reset().parameter("chargeTimeType").value(chargeTimeType).notNull()
|
baseDataValidator.reset().parameter(CHARGE_TIME_TYPE).value(chargeTimeType).notNull()
|
||||||
.isOneOfTheseValues(allValidValues.toArray(new Object[allValidValues.size()]));
|
.isOneOfTheseValues(allValidValues.toArray(new Object[allValidValues.size()]));
|
||||||
}
|
}
|
||||||
|
|
||||||
if (this.fromApiJsonHelper.parameterExists("feeOnMonthDay", element)) {
|
if (this.fromApiJsonHelper.parameterExists(FEE_ON_MONTH_DAY, element)) {
|
||||||
final MonthDay monthDay = this.fromApiJsonHelper.extractMonthDayNamed("feeOnMonthDay", element);
|
final MonthDay monthDay = this.fromApiJsonHelper.extractMonthDayNamed(FEE_ON_MONTH_DAY, element);
|
||||||
baseDataValidator.reset().parameter("feeOnMonthDay").value(monthDay).notNull();
|
baseDataValidator.reset().parameter(FEE_ON_MONTH_DAY).value(monthDay).notNull();
|
||||||
}
|
}
|
||||||
|
|
||||||
if (this.fromApiJsonHelper.parameterExists("feeInterval", element)) {
|
if (this.fromApiJsonHelper.parameterExists(FEE_INTERVAL, element)) {
|
||||||
final Integer feeInterval = this.fromApiJsonHelper.extractIntegerNamed("feeInterval", element, Locale.getDefault());
|
final Integer feeInterval = this.fromApiJsonHelper.extractIntegerNamed(FEE_INTERVAL, element, Locale.getDefault());
|
||||||
baseDataValidator.reset().parameter("feeInterval").value(feeInterval).integerGreaterThanZero();
|
baseDataValidator.reset().parameter(FEE_INTERVAL).value(feeInterval).integerGreaterThanZero();
|
||||||
}
|
}
|
||||||
|
|
||||||
if (this.fromApiJsonHelper.parameterExists("chargeCalculationType", element)) {
|
if (this.fromApiJsonHelper.parameterExists(CHARGE_CALCULATION_TYPE, element)) {
|
||||||
final Integer chargeCalculationType = this.fromApiJsonHelper.extractIntegerNamed("chargeCalculationType", element,
|
final Integer chargeCalculationType = this.fromApiJsonHelper.extractIntegerNamed(CHARGE_CALCULATION_TYPE, element,
|
||||||
Locale.getDefault());
|
Locale.getDefault());
|
||||||
baseDataValidator.reset().parameter("chargeCalculationType").value(chargeCalculationType).notNull().inMinMaxRange(1, 5);
|
baseDataValidator.reset().parameter(CHARGE_CALCULATION_TYPE).value(chargeCalculationType).notNull().inMinMaxRange(1, 5);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (this.fromApiJsonHelper.parameterExists("chargePaymentMode", element)) {
|
if (this.fromApiJsonHelper.parameterExists(CHARGE_PAYMENT_MODE, element)) {
|
||||||
final Integer chargePaymentMode = this.fromApiJsonHelper.extractIntegerNamed("chargePaymentMode", element, Locale.getDefault());
|
final Integer chargePaymentMode = this.fromApiJsonHelper.extractIntegerNamed(CHARGE_PAYMENT_MODE, element, Locale.getDefault());
|
||||||
baseDataValidator.reset().parameter("chargePaymentMode").value(chargePaymentMode).notNull().inMinMaxRange(0, 1);
|
baseDataValidator.reset().parameter(CHARGE_PAYMENT_MODE).value(chargePaymentMode).notNull().inMinMaxRange(0, 1);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (this.fromApiJsonHelper.parameterExists("penalty", element)) {
|
if (this.fromApiJsonHelper.parameterExists(PENALTY, element)) {
|
||||||
final Boolean penalty = this.fromApiJsonHelper.extractBooleanNamed("penalty", element);
|
final Boolean penalty = this.fromApiJsonHelper.extractBooleanNamed(PENALTY, element);
|
||||||
baseDataValidator.reset().parameter("penalty").value(penalty).notNull();
|
baseDataValidator.reset().parameter(PENALTY).value(penalty).notNull();
|
||||||
}
|
}
|
||||||
|
|
||||||
if (this.fromApiJsonHelper.parameterExists("active", element)) {
|
if (this.fromApiJsonHelper.parameterExists(ACTIVE, element)) {
|
||||||
final Boolean active = this.fromApiJsonHelper.extractBooleanNamed("active", element);
|
final Boolean active = this.fromApiJsonHelper.extractBooleanNamed(ACTIVE, element);
|
||||||
baseDataValidator.reset().parameter("active").value(active).notNull();
|
baseDataValidator.reset().parameter(ACTIVE).value(active).notNull();
|
||||||
}
|
}
|
||||||
if (this.fromApiJsonHelper.parameterExists("minCap", element)) {
|
if (this.fromApiJsonHelper.parameterExists(MIN_CAP, element)) {
|
||||||
final BigDecimal minCap = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed("minCap", element.getAsJsonObject());
|
final BigDecimal minCap = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed(MIN_CAP, element.getAsJsonObject());
|
||||||
baseDataValidator.reset().parameter("minCap").value(minCap).notNull().positiveAmount();
|
baseDataValidator.reset().parameter(MIN_CAP).value(minCap).notNull().positiveAmount();
|
||||||
}
|
}
|
||||||
if (this.fromApiJsonHelper.parameterExists("maxCap", element)) {
|
if (this.fromApiJsonHelper.parameterExists(MAX_CAP, element)) {
|
||||||
final BigDecimal maxCap = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed("maxCap", element.getAsJsonObject());
|
final BigDecimal maxCap = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed(MAX_CAP, element.getAsJsonObject());
|
||||||
baseDataValidator.reset().parameter("maxCap").value(maxCap).notNull().positiveAmount();
|
baseDataValidator.reset().parameter(MAX_CAP).value(maxCap).notNull().positiveAmount();
|
||||||
}
|
}
|
||||||
if (this.fromApiJsonHelper.parameterExists("feeFrequency", element)) {
|
if (this.fromApiJsonHelper.parameterExists(FEE_FREQUENCY, element)) {
|
||||||
final Integer feeFrequency = this.fromApiJsonHelper.extractIntegerNamed("feeFrequency", element, Locale.getDefault());
|
final Integer feeFrequency = this.fromApiJsonHelper.extractIntegerNamed(FEE_FREQUENCY, element, Locale.getDefault());
|
||||||
baseDataValidator.reset().parameter("feeFrequency").value(feeFrequency).inMinMaxRange(0, 3);
|
baseDataValidator.reset().parameter(FEE_FREQUENCY).value(feeFrequency).inMinMaxRange(0, 3);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (this.fromApiJsonHelper.parameterExists(ChargesApiConstants.glAccountIdParamName, element)) {
|
if (this.fromApiJsonHelper.parameterExists(ChargesApiConstants.glAccountIdParamName, element)) {
|
||||||
@@ -429,25 +456,25 @@ public final class ChargeDefinitionCommandFromApiJsonDeserializer {
|
|||||||
throwExceptionIfValidationWarningsExist(dataValidationErrors);
|
throwExceptionIfValidationWarningsExist(dataValidationErrors);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void validateChargeTimeNCalculationType(Integer chargeTimeType, Integer ChargeCalculationType) {
|
public void validateChargeTimeNCalculationType(Integer chargeTimeType, Integer chargeCalculationType) {
|
||||||
final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
|
final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
|
||||||
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("charge");
|
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource(CHARGE);
|
||||||
performChargeTimeNCalculationTypeValidation(baseDataValidator, chargeTimeType, ChargeCalculationType);
|
performChargeTimeNCalculationTypeValidation(baseDataValidator, chargeTimeType, chargeCalculationType);
|
||||||
throwExceptionIfValidationWarningsExist(dataValidationErrors);
|
throwExceptionIfValidationWarningsExist(dataValidationErrors);
|
||||||
}
|
}
|
||||||
|
|
||||||
private void performChargeTimeNCalculationTypeValidation(DataValidatorBuilder baseDataValidator, final Integer chargeTimeType,
|
private void performChargeTimeNCalculationTypeValidation(DataValidatorBuilder baseDataValidator, final Integer chargeTimeType,
|
||||||
final Integer chargeCalculationType) {
|
final Integer chargeCalculationType) {
|
||||||
if (chargeTimeType.equals(ChargeTimeType.SHAREACCOUNT_ACTIVATION.getValue())) {
|
if (chargeTimeType.equals(ChargeTimeType.SHAREACCOUNT_ACTIVATION.getValue())) {
|
||||||
baseDataValidator.reset().parameter("chargeCalculationType").value(chargeCalculationType)
|
baseDataValidator.reset().parameter(CHARGE_CALCULATION_TYPE).value(chargeCalculationType)
|
||||||
.isOneOfTheseValues(ChargeCalculationType.validValuesForShareAccountActivation());
|
.isOneOfTheseValues(ChargeCalculationType.validValuesForShareAccountActivation());
|
||||||
}
|
}
|
||||||
|
|
||||||
if (chargeTimeType.equals(ChargeTimeType.TRANCHE_DISBURSEMENT.getValue())) {
|
if (chargeTimeType.equals(ChargeTimeType.TRANCHE_DISBURSEMENT.getValue())) {
|
||||||
baseDataValidator.reset().parameter("chargeCalculationType").value(chargeCalculationType)
|
baseDataValidator.reset().parameter(CHARGE_CALCULATION_TYPE).value(chargeCalculationType)
|
||||||
.isOneOfTheseValues(ChargeCalculationType.validValuesForTrancheDisbursement());
|
.isOneOfTheseValues(ChargeCalculationType.validValuesForTrancheDisbursement());
|
||||||
} else {
|
} else {
|
||||||
baseDataValidator.reset().parameter("chargeCalculationType").value(chargeCalculationType)
|
baseDataValidator.reset().parameter(CHARGE_CALCULATION_TYPE).value(chargeCalculationType)
|
||||||
.isNotOneOfTheseValues(ChargeCalculationType.PERCENT_OF_DISBURSEMENT_AMOUNT.getValue());
|
.isNotOneOfTheseValues(ChargeCalculationType.PERCENT_OF_DISBURSEMENT_AMOUNT.getValue());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+10
-9
@@ -62,11 +62,12 @@ import org.springframework.stereotype.Component;
|
|||||||
@Tag(name = "Clients Address", description = "Address module is an optional module and can be configured into the system by using GlobalConfiguration setting: enable-address. In order to activate Address module, we need to enable the configuration, enable-address by setting its value to true.")
|
@Tag(name = "Clients Address", description = "Address module is an optional module and can be configured into the system by using GlobalConfiguration setting: enable-address. In order to activate Address module, we need to enable the configuration, enable-address by setting its value to true.")
|
||||||
public class ClientAddressApiResources {
|
public class ClientAddressApiResources {
|
||||||
|
|
||||||
private final Set<String> responseDataParameters = new HashSet<>(Arrays.asList("addressId", "street", "addressLine1", "addressLine2",
|
private static final Set<String> RESPONSE_DATA_PARAMETERS = new HashSet<>(
|
||||||
"addressLine3", "townVillage", "city", "countyDistrict", "stateProvinceId", "countryId", "postalCode", "latitude", "longitude",
|
Arrays.asList("addressId", "street", "addressLine1", "addressLine2", "addressLine3", "townVillage", "city", "countyDistrict",
|
||||||
"createdBy", "createdOn", "updatedBy", "updatedOn", "clientAddressId", "client_id", "address_id", "address_type_id", "isActive",
|
"stateProvinceId", "countryId", "postalCode", "latitude", "longitude", "createdBy", "createdOn", "updatedBy",
|
||||||
"fieldConfigurationId", "entity", "table", "field", "is_enabled", "is_mandatory", "validation_regex"));
|
"updatedOn", "clientAddressId", "client_id", "address_id", "address_type_id", "isActive", "fieldConfigurationId",
|
||||||
private final String resourceNameForPermissions = "Address";
|
"entity", "table", "field", "is_enabled", "is_mandatory", "validation_regex"));
|
||||||
|
private static final String RESOURCE_NAME_FOR_PERMISSIONS = "Address";
|
||||||
private final PlatformSecurityContext context;
|
private final PlatformSecurityContext context;
|
||||||
private final AddressReadPlatformServiceImpl readPlatformService;
|
private final AddressReadPlatformServiceImpl readPlatformService;
|
||||||
private final DefaultToApiJsonSerializer<AddressData> toApiJsonSerializer;
|
private final DefaultToApiJsonSerializer<AddressData> toApiJsonSerializer;
|
||||||
@@ -89,12 +90,12 @@ public class ClientAddressApiResources {
|
|||||||
@Consumes({ MediaType.APPLICATION_JSON })
|
@Consumes({ MediaType.APPLICATION_JSON })
|
||||||
@Produces({ MediaType.APPLICATION_JSON })
|
@Produces({ MediaType.APPLICATION_JSON })
|
||||||
public String getAddressesTemplate(@Context final UriInfo uriInfo) {
|
public String getAddressesTemplate(@Context final UriInfo uriInfo) {
|
||||||
this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions);
|
this.context.authenticatedUser().validateHasReadPermission(RESOURCE_NAME_FOR_PERMISSIONS);
|
||||||
|
|
||||||
final AddressData template = this.readPlatformService.retrieveTemplate();
|
final AddressData template = this.readPlatformService.retrieveTemplate();
|
||||||
|
|
||||||
final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters());
|
final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters());
|
||||||
return this.toApiJsonSerializer.serialize(settings, template, this.responseDataParameters);
|
return this.toApiJsonSerializer.serialize(settings, template, RESPONSE_DATA_PARAMETERS);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -131,7 +132,7 @@ public class ClientAddressApiResources {
|
|||||||
@PathParam("clientid") @Parameter(description = "clientId") final long clientid, @Context final UriInfo uriInfo) {
|
@PathParam("clientid") @Parameter(description = "clientId") final long clientid, @Context final UriInfo uriInfo) {
|
||||||
Collection<AddressData> address;
|
Collection<AddressData> address;
|
||||||
|
|
||||||
this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions);
|
this.context.authenticatedUser().validateHasReadPermission(RESOURCE_NAME_FOR_PERMISSIONS);
|
||||||
|
|
||||||
// TODO: This is quite a confusing implementation with all these checks
|
// TODO: This is quite a confusing implementation with all these checks
|
||||||
// These have to be considered as filtering criterias instead
|
// These have to be considered as filtering criterias instead
|
||||||
@@ -146,7 +147,7 @@ public class ClientAddressApiResources {
|
|||||||
}
|
}
|
||||||
|
|
||||||
final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters());
|
final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters());
|
||||||
return this.toApiJsonSerializer.serialize(settings, address, this.responseDataParameters);
|
return this.toApiJsonSerializer.serialize(settings, address, RESPONSE_DATA_PARAMETERS);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+9
-9
@@ -56,9 +56,9 @@ import org.springframework.stereotype.Component;
|
|||||||
@Tag(name = "Client Family Member", description = "")
|
@Tag(name = "Client Family Member", description = "")
|
||||||
public class ClientFamilyMembersApiResources {
|
public class ClientFamilyMembersApiResources {
|
||||||
|
|
||||||
private final Set<String> responseDataParameters = new HashSet<>(Arrays.asList("id", "clientId", "firstName", "middleName", "lastName",
|
private static final Set<String> RESPONSE_DATA_PARAMETERS = new HashSet<>(Arrays.asList("id", "clientId", "firstName", "middleName",
|
||||||
"qualification", "relationship", "maritalStatus", "gender", "dateOfBirth", "profession", "clientFamilyMemberId"));
|
"lastName", "qualification", "relationship", "maritalStatus", "gender", "dateOfBirth", "profession", "clientFamilyMemberId"));
|
||||||
private final String resourceNameForPermissions = "FamilyMembers";
|
private static final String RESOURCE_NAME_FOR_PERMISSIONS = "FamilyMembers";
|
||||||
private final PlatformSecurityContext context;
|
private final PlatformSecurityContext context;
|
||||||
private final ClientFamilyMembersReadPlatformService readPlatformService;
|
private final ClientFamilyMembersReadPlatformService readPlatformService;
|
||||||
private final ToApiJsonSerializer<ClientFamilyMembersData> toApiJsonSerializer;
|
private final ToApiJsonSerializer<ClientFamilyMembersData> toApiJsonSerializer;
|
||||||
@@ -86,12 +86,12 @@ public class ClientFamilyMembersApiResources {
|
|||||||
public String getFamilyMember(@Context final UriInfo uriInfo, @PathParam("familyMemberId") final Long familyMemberId,
|
public String getFamilyMember(@Context final UriInfo uriInfo, @PathParam("familyMemberId") final Long familyMemberId,
|
||||||
@PathParam("clientId") @Parameter(description = "clientId") final Long clientId) {
|
@PathParam("clientId") @Parameter(description = "clientId") final Long clientId) {
|
||||||
|
|
||||||
this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions);
|
this.context.authenticatedUser().validateHasReadPermission(RESOURCE_NAME_FOR_PERMISSIONS);
|
||||||
|
|
||||||
final ClientFamilyMembersData familyMembers = this.readPlatformService.getClientFamilyMember(familyMemberId);
|
final ClientFamilyMembersData familyMembers = this.readPlatformService.getClientFamilyMember(familyMemberId);
|
||||||
|
|
||||||
final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters());
|
final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters());
|
||||||
return this.toApiJsonSerializer.serialize(settings, familyMembers, this.responseDataParameters);
|
return this.toApiJsonSerializer.serialize(settings, familyMembers, RESPONSE_DATA_PARAMETERS);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -100,12 +100,12 @@ public class ClientFamilyMembersApiResources {
|
|||||||
@Produces({ MediaType.APPLICATION_JSON })
|
@Produces({ MediaType.APPLICATION_JSON })
|
||||||
public String getFamilyMembers(@Context final UriInfo uriInfo, @PathParam("clientId") final long clientId) {
|
public String getFamilyMembers(@Context final UriInfo uriInfo, @PathParam("clientId") final long clientId) {
|
||||||
|
|
||||||
this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions);
|
this.context.authenticatedUser().validateHasReadPermission(RESOURCE_NAME_FOR_PERMISSIONS);
|
||||||
|
|
||||||
final Collection<ClientFamilyMembersData> familyMembers = this.readPlatformService.getClientFamilyMembers(clientId);
|
final Collection<ClientFamilyMembersData> familyMembers = this.readPlatformService.getClientFamilyMembers(clientId);
|
||||||
|
|
||||||
final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters());
|
final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters());
|
||||||
return this.toApiJsonSerializer.serialize(settings, familyMembers, this.responseDataParameters);
|
return this.toApiJsonSerializer.serialize(settings, familyMembers, RESPONSE_DATA_PARAMETERS);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -115,12 +115,12 @@ public class ClientFamilyMembersApiResources {
|
|||||||
@Produces({ MediaType.APPLICATION_JSON })
|
@Produces({ MediaType.APPLICATION_JSON })
|
||||||
public String getTemplate(@Context final UriInfo uriInfo, @PathParam("clientId") final long clientId) {
|
public String getTemplate(@Context final UriInfo uriInfo, @PathParam("clientId") final long clientId) {
|
||||||
|
|
||||||
this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions);
|
this.context.authenticatedUser().validateHasReadPermission(RESOURCE_NAME_FOR_PERMISSIONS);
|
||||||
|
|
||||||
final ClientFamilyMembersData options = this.readPlatformService.retrieveTemplate();
|
final ClientFamilyMembersData options = this.readPlatformService.retrieveTemplate();
|
||||||
|
|
||||||
final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters());
|
final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters());
|
||||||
return this.toApiJsonSerializer.serialize(settings, options, this.responseDataParameters);
|
return this.toApiJsonSerializer.serialize(settings, options, RESPONSE_DATA_PARAMETERS);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+4
-4
@@ -71,7 +71,7 @@ public class ClientIdentifiersApiResource {
|
|||||||
private static final Set<String> CLIENT_IDENTIFIER_DATA_PARAMETERS = new HashSet<>(
|
private static final Set<String> CLIENT_IDENTIFIER_DATA_PARAMETERS = new HashSet<>(
|
||||||
Arrays.asList("id", "clientId", "documentType", "documentKey", "description", "allowedDocumentTypes"));
|
Arrays.asList("id", "clientId", "documentType", "documentKey", "description", "allowedDocumentTypes"));
|
||||||
|
|
||||||
private final String resourceNameForPermissions = "CLIENTIDENTIFIER";
|
private static final String RESOURCE_NAME_FOR_PERMISSIONS = "CLIENTIDENTIFIER";
|
||||||
|
|
||||||
private final PlatformSecurityContext context;
|
private final PlatformSecurityContext context;
|
||||||
private final ClientReadPlatformService clientReadPlatformService;
|
private final ClientReadPlatformService clientReadPlatformService;
|
||||||
@@ -107,7 +107,7 @@ public class ClientIdentifiersApiResource {
|
|||||||
public String retrieveAllClientIdentifiers(@Context final UriInfo uriInfo,
|
public String retrieveAllClientIdentifiers(@Context final UriInfo uriInfo,
|
||||||
@PathParam("clientId") @Parameter(description = "clientId") final Long clientId) {
|
@PathParam("clientId") @Parameter(description = "clientId") final Long clientId) {
|
||||||
|
|
||||||
this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions);
|
this.context.authenticatedUser().validateHasReadPermission(RESOURCE_NAME_FOR_PERMISSIONS);
|
||||||
|
|
||||||
final Collection<ClientIdentifierData> clientIdentifiers = this.clientIdentifierReadPlatformService
|
final Collection<ClientIdentifierData> clientIdentifiers = this.clientIdentifierReadPlatformService
|
||||||
.retrieveClientIdentifiers(clientId);
|
.retrieveClientIdentifiers(clientId);
|
||||||
@@ -127,7 +127,7 @@ public class ClientIdentifiersApiResource {
|
|||||||
public String newClientIdentifierDetails(@Context final UriInfo uriInfo,
|
public String newClientIdentifierDetails(@Context final UriInfo uriInfo,
|
||||||
@PathParam("clientId") @Parameter(description = "clientId") final Long clientId) {
|
@PathParam("clientId") @Parameter(description = "clientId") final Long clientId) {
|
||||||
|
|
||||||
this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions);
|
this.context.authenticatedUser().validateHasReadPermission(RESOURCE_NAME_FOR_PERMISSIONS);
|
||||||
|
|
||||||
final Collection<CodeValueData> codeValues = this.codeValueReadPlatformService.retrieveCodeValuesByCode("Customer Identifier");
|
final Collection<CodeValueData> codeValues = this.codeValueReadPlatformService.retrieveCodeValuesByCode("Customer Identifier");
|
||||||
final ClientIdentifierData clientIdentifierData = ClientIdentifierData.template(codeValues);
|
final ClientIdentifierData clientIdentifierData = ClientIdentifierData.template(codeValues);
|
||||||
@@ -178,7 +178,7 @@ public class ClientIdentifiersApiResource {
|
|||||||
@PathParam("identifierId") @Parameter(description = "identifierId") final Long clientIdentifierId,
|
@PathParam("identifierId") @Parameter(description = "identifierId") final Long clientIdentifierId,
|
||||||
@Context final UriInfo uriInfo) {
|
@Context final UriInfo uriInfo) {
|
||||||
|
|
||||||
this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions);
|
this.context.authenticatedUser().validateHasReadPermission(RESOURCE_NAME_FOR_PERMISSIONS);
|
||||||
|
|
||||||
final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters());
|
final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters());
|
||||||
|
|
||||||
|
|||||||
+107
-82
@@ -42,10 +42,29 @@ import org.springframework.stereotype.Component;
|
|||||||
@Component
|
@Component
|
||||||
public final class ClientFamilyMemberCommandFromApiJsonDeserializer {
|
public final class ClientFamilyMemberCommandFromApiJsonDeserializer {
|
||||||
|
|
||||||
|
public static final String ID = "id";
|
||||||
|
public static final String CLIENT_ID = "clientId";
|
||||||
|
public static final String FIRST_NAME = "firstName";
|
||||||
|
public static final String MIDDLE_NAME = "middleName";
|
||||||
|
public static final String LAST_NAME = "lastName";
|
||||||
|
public static final String QUALIFICATION = "qualification";
|
||||||
|
public static final String MOBILE_NUMBER = "mobileNumber";
|
||||||
|
public static final String AGE = "age";
|
||||||
|
public static final String IS_DEPENDENT = "isDependent";
|
||||||
|
public static final String RELATIONSHIP_ID = "relationshipId";
|
||||||
|
public static final String MARITAL_STATUS_ID = "maritalStatusId";
|
||||||
|
public static final String GENDER_ID = "genderId";
|
||||||
|
public static final String DATE_OF_BIRTH = "dateOfBirth";
|
||||||
|
public static final String PROFESSION_ID = "professionId";
|
||||||
|
public static final String LOCALE = "locale";
|
||||||
|
public static final String DATE_FORMAT = "dateFormat";
|
||||||
|
public static final String FAMILY_MEMBERS = "familyMembers";
|
||||||
|
private static final Set<String> SUPPORTED_PARAMETERS = new HashSet<>(
|
||||||
|
Arrays.asList(ID, CLIENT_ID, FIRST_NAME, MIDDLE_NAME, LAST_NAME, QUALIFICATION, MOBILE_NUMBER, AGE, IS_DEPENDENT,
|
||||||
|
RELATIONSHIP_ID, MARITAL_STATUS_ID, GENDER_ID, DATE_OF_BIRTH, PROFESSION_ID, LOCALE, DATE_FORMAT, FAMILY_MEMBERS));
|
||||||
|
public static final String FAMILY_MEMBERS1 = "FamilyMembers";
|
||||||
|
public static final String RELATION_SHIP_ID = "relationShipId";
|
||||||
private final FromJsonHelper fromApiJsonHelper;
|
private final FromJsonHelper fromApiJsonHelper;
|
||||||
private final Set<String> supportedParameters = new HashSet<>(Arrays.asList("id", "clientId", "firstName", "middleName", "lastName",
|
|
||||||
"qualification", "mobileNumber", "age", "isDependent", "relationshipId", "maritalStatusId", "genderId", "dateOfBirth",
|
|
||||||
"professionId", "locale", "dateFormat", "familyMembers"));
|
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
public ClientFamilyMemberCommandFromApiJsonDeserializer(final FromJsonHelper fromApiJsonHelper) {
|
public ClientFamilyMemberCommandFromApiJsonDeserializer(final FromJsonHelper fromApiJsonHelper) {
|
||||||
@@ -58,18 +77,20 @@ public final class ClientFamilyMemberCommandFromApiJsonDeserializer {
|
|||||||
throw new InvalidJsonException();
|
throw new InvalidJsonException();
|
||||||
}
|
}
|
||||||
|
|
||||||
final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType();
|
final Type typeOfMap = new TypeToken<Map<String, Object>>() {
|
||||||
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParameters);
|
|
||||||
|
}.getType();
|
||||||
|
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, SUPPORTED_PARAMETERS);
|
||||||
final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
|
final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
|
||||||
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("FamilyMembers");
|
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource(FAMILY_MEMBERS1);
|
||||||
|
|
||||||
final JsonElement element = this.fromApiJsonHelper.parse(json);
|
final JsonElement element = this.fromApiJsonHelper.parse(json);
|
||||||
|
|
||||||
if (this.fromApiJsonHelper.extractArrayNamed("familyMembers", element) != null) {
|
if (this.fromApiJsonHelper.extractArrayNamed(FAMILY_MEMBERS, element) != null) {
|
||||||
final JsonArray familyMembers = this.fromApiJsonHelper.extractJsonArrayNamed("familyMembers", element);
|
final JsonArray familyMembers = this.fromApiJsonHelper.extractJsonArrayNamed(FAMILY_MEMBERS, element);
|
||||||
baseDataValidator.reset().value(familyMembers).arrayNotEmpty();
|
baseDataValidator.reset().value(familyMembers).arrayNotEmpty();
|
||||||
} else {
|
} else {
|
||||||
baseDataValidator.reset().value(this.fromApiJsonHelper.extractJsonArrayNamed("familyMembers", element)).arrayNotEmpty();
|
baseDataValidator.reset().value(this.fromApiJsonHelper.extractJsonArrayNamed(FAMILY_MEMBERS, element)).arrayNotEmpty();
|
||||||
}
|
}
|
||||||
|
|
||||||
validateForCreate(1, json);
|
validateForCreate(1, json);
|
||||||
@@ -82,85 +103,87 @@ public final class ClientFamilyMemberCommandFromApiJsonDeserializer {
|
|||||||
throw new InvalidJsonException();
|
throw new InvalidJsonException();
|
||||||
}
|
}
|
||||||
|
|
||||||
final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType();
|
final Type typeOfMap = new TypeToken<Map<String, Object>>() {
|
||||||
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParameters);
|
|
||||||
|
}.getType();
|
||||||
|
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, SUPPORTED_PARAMETERS);
|
||||||
|
|
||||||
final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
|
final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
|
||||||
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("FamilyMembers");
|
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource(FAMILY_MEMBERS1);
|
||||||
|
|
||||||
final JsonElement element = this.fromApiJsonHelper.parse(json);
|
final JsonElement element = this.fromApiJsonHelper.parse(json);
|
||||||
|
|
||||||
baseDataValidator.reset().value(clientId).notBlank().integerGreaterThanZero();
|
baseDataValidator.reset().value(clientId).notBlank().integerGreaterThanZero();
|
||||||
|
|
||||||
if (this.fromApiJsonHelper.extractStringNamed("firstName", element) != null) {
|
if (this.fromApiJsonHelper.extractStringNamed(FIRST_NAME, element) != null) {
|
||||||
final String firstName = this.fromApiJsonHelper.extractStringNamed("firstName", element);
|
final String firstName = this.fromApiJsonHelper.extractStringNamed(FIRST_NAME, element);
|
||||||
baseDataValidator.reset().parameter("firstName").value(firstName).notNull().notBlank().notExceedingLengthOf(100);
|
baseDataValidator.reset().parameter(FIRST_NAME).value(firstName).notNull().notBlank().notExceedingLengthOf(100);
|
||||||
} else {
|
} else {
|
||||||
baseDataValidator.reset().parameter("firstName").value(this.fromApiJsonHelper.extractStringNamed("firstName", element))
|
baseDataValidator.reset().parameter(FIRST_NAME).value(this.fromApiJsonHelper.extractStringNamed(FIRST_NAME, element)).notNull()
|
||||||
.notNull().notBlank().notExceedingLengthOf(100);
|
.notBlank().notExceedingLengthOf(100);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (this.fromApiJsonHelper.extractStringNamed("lastName", element) != null) {
|
if (this.fromApiJsonHelper.extractStringNamed(LAST_NAME, element) != null) {
|
||||||
final String lastName = this.fromApiJsonHelper.extractStringNamed("lastName", element);
|
final String lastName = this.fromApiJsonHelper.extractStringNamed(LAST_NAME, element);
|
||||||
baseDataValidator.reset().parameter("lastName").value(lastName).notNull().notBlank().notExceedingLengthOf(100);
|
baseDataValidator.reset().parameter(LAST_NAME).value(lastName).notNull().notBlank().notExceedingLengthOf(100);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (this.fromApiJsonHelper.extractStringNamed("middleName", element) != null) {
|
if (this.fromApiJsonHelper.extractStringNamed(MIDDLE_NAME, element) != null) {
|
||||||
final String middleName = this.fromApiJsonHelper.extractStringNamed("middleName", element);
|
final String middleName = this.fromApiJsonHelper.extractStringNamed(MIDDLE_NAME, element);
|
||||||
baseDataValidator.reset().parameter("middleName").value(middleName).notNull().notBlank().notExceedingLengthOf(100);
|
baseDataValidator.reset().parameter(MIDDLE_NAME).value(middleName).notNull().notBlank().notExceedingLengthOf(100);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (this.fromApiJsonHelper.extractStringNamed("qualification", element) != null) {
|
if (this.fromApiJsonHelper.extractStringNamed(QUALIFICATION, element) != null) {
|
||||||
final String qualification = this.fromApiJsonHelper.extractStringNamed("qualification", element);
|
final String qualification = this.fromApiJsonHelper.extractStringNamed(QUALIFICATION, element);
|
||||||
baseDataValidator.reset().parameter("qualification").value(qualification).notNull().notBlank().notExceedingLengthOf(100);
|
baseDataValidator.reset().parameter(QUALIFICATION).value(qualification).notNull().notBlank().notExceedingLengthOf(100);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (this.fromApiJsonHelper.extractStringNamed("mobileNumber", element) != null) {
|
if (this.fromApiJsonHelper.extractStringNamed(MOBILE_NUMBER, element) != null) {
|
||||||
final String mobileNumber = this.fromApiJsonHelper.extractStringNamed("mobileNumber", element);
|
final String mobileNumber = this.fromApiJsonHelper.extractStringNamed(MOBILE_NUMBER, element);
|
||||||
baseDataValidator.reset().parameter("mobileNumber").value(mobileNumber).notNull().notBlank().notExceedingLengthOf(100);
|
baseDataValidator.reset().parameter(MOBILE_NUMBER).value(mobileNumber).notNull().notBlank().notExceedingLengthOf(100);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (this.fromApiJsonHelper.extractBooleanNamed("isDependent", element) != null) {
|
if (this.fromApiJsonHelper.extractBooleanNamed(IS_DEPENDENT, element) != null) {
|
||||||
final Boolean isDependent = this.fromApiJsonHelper.extractBooleanNamed("isDependent", element);
|
final Boolean isDependent = this.fromApiJsonHelper.extractBooleanNamed(IS_DEPENDENT, element);
|
||||||
baseDataValidator.reset().parameter("isDependent").value(isDependent).notNull().notBlank().notExceedingLengthOf(100);
|
baseDataValidator.reset().parameter(IS_DEPENDENT).value(isDependent).notNull().notBlank().notExceedingLengthOf(100);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (this.fromApiJsonHelper.extractLongNamed("relationShipId", element) != null) {
|
if (this.fromApiJsonHelper.extractLongNamed(RELATION_SHIP_ID, element) != null) {
|
||||||
final long relationShipId = this.fromApiJsonHelper.extractLongNamed("relationShipId", element);
|
final long relationShipId = this.fromApiJsonHelper.extractLongNamed(RELATION_SHIP_ID, element);
|
||||||
baseDataValidator.reset().parameter("relationShipId").value(relationShipId).notBlank().longGreaterThanZero();
|
baseDataValidator.reset().parameter(RELATION_SHIP_ID).value(relationShipId).notBlank().longGreaterThanZero();
|
||||||
|
|
||||||
} else {
|
} else {
|
||||||
baseDataValidator.reset().parameter("relationShipId").value(this.fromApiJsonHelper.extractLongNamed("relationShipId", element))
|
baseDataValidator.reset().parameter(RELATION_SHIP_ID).value(this.fromApiJsonHelper.extractLongNamed(RELATION_SHIP_ID, element))
|
||||||
.notBlank().longGreaterThanZero();
|
.notBlank().longGreaterThanZero();
|
||||||
}
|
}
|
||||||
|
|
||||||
if (this.fromApiJsonHelper.extractLongNamed("maritalStatusId", element) != null) {
|
if (this.fromApiJsonHelper.extractLongNamed(MARITAL_STATUS_ID, element) != null) {
|
||||||
final long maritalStatusId = this.fromApiJsonHelper.extractLongNamed("maritalStatusId", element);
|
final long maritalStatusId = this.fromApiJsonHelper.extractLongNamed(MARITAL_STATUS_ID, element);
|
||||||
baseDataValidator.reset().parameter("maritalStatusId").value(maritalStatusId).notBlank().longGreaterThanZero();
|
baseDataValidator.reset().parameter(MARITAL_STATUS_ID).value(maritalStatusId).notBlank().longGreaterThanZero();
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (this.fromApiJsonHelper.extractLongNamed("genderId", element) != null) {
|
if (this.fromApiJsonHelper.extractLongNamed(GENDER_ID, element) != null) {
|
||||||
final long genderId = this.fromApiJsonHelper.extractLongNamed("genderId", element);
|
final long genderId = this.fromApiJsonHelper.extractLongNamed(GENDER_ID, element);
|
||||||
baseDataValidator.reset().parameter("genderId").value(genderId).notBlank().longGreaterThanZero();
|
baseDataValidator.reset().parameter(GENDER_ID).value(genderId).notBlank().longGreaterThanZero();
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (this.fromApiJsonHelper.extractLongNamed("age", element) != null) {
|
if (this.fromApiJsonHelper.extractLongNamed(AGE, element) != null) {
|
||||||
final long age = this.fromApiJsonHelper.extractLongNamed("age", element);
|
final long age = this.fromApiJsonHelper.extractLongNamed(AGE, element);
|
||||||
baseDataValidator.reset().parameter("age").value(age).notBlank().longGreaterThanZero();
|
baseDataValidator.reset().parameter(AGE).value(age).notBlank().longGreaterThanZero();
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (this.fromApiJsonHelper.extractLongNamed("professionId", element) != null) {
|
if (this.fromApiJsonHelper.extractLongNamed(PROFESSION_ID, element) != null) {
|
||||||
final long professionId = this.fromApiJsonHelper.extractLongNamed("professionId", element);
|
final long professionId = this.fromApiJsonHelper.extractLongNamed(PROFESSION_ID, element);
|
||||||
baseDataValidator.reset().parameter("professionId").value(professionId).notBlank().longGreaterThanZero();
|
baseDataValidator.reset().parameter(PROFESSION_ID).value(professionId).notBlank().longGreaterThanZero();
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (this.fromApiJsonHelper.extractLocalDateNamed("dateOfBirth", element) != null) {
|
if (this.fromApiJsonHelper.extractLocalDateNamed(DATE_OF_BIRTH, element) != null) {
|
||||||
final LocalDate dateOfBirth = this.fromApiJsonHelper.extractLocalDateNamed("dateOfBirth", element);
|
final LocalDate dateOfBirth = this.fromApiJsonHelper.extractLocalDateNamed(DATE_OF_BIRTH, element);
|
||||||
baseDataValidator.reset().parameter("dateOfBirth").value(dateOfBirth).value(dateOfBirth).notNull()
|
baseDataValidator.reset().parameter(DATE_OF_BIRTH).value(dateOfBirth).value(dateOfBirth).notNull()
|
||||||
.validateDateBefore(DateUtils.getBusinessLocalDate());
|
.validateDateBefore(DateUtils.getBusinessLocalDate());
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -173,63 +196,65 @@ public final class ClientFamilyMemberCommandFromApiJsonDeserializer {
|
|||||||
throw new InvalidJsonException();
|
throw new InvalidJsonException();
|
||||||
}
|
}
|
||||||
|
|
||||||
final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType();
|
final Type typeOfMap = new TypeToken<Map<String, Object>>() {
|
||||||
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParameters);
|
|
||||||
|
}.getType();
|
||||||
|
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, SUPPORTED_PARAMETERS);
|
||||||
|
|
||||||
final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
|
final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
|
||||||
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("FamilyMembers");
|
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource(FAMILY_MEMBERS1);
|
||||||
|
|
||||||
final JsonElement element = this.fromApiJsonHelper.parse(json);
|
final JsonElement element = this.fromApiJsonHelper.parse(json);
|
||||||
|
|
||||||
baseDataValidator.reset().value(familyMemberId).notBlank().integerGreaterThanZero();
|
baseDataValidator.reset().value(familyMemberId).notBlank().integerGreaterThanZero();
|
||||||
|
|
||||||
if (this.fromApiJsonHelper.extractStringNamed("firstName", element) != null) {
|
if (this.fromApiJsonHelper.extractStringNamed(FIRST_NAME, element) != null) {
|
||||||
final String firstName = this.fromApiJsonHelper.extractStringNamed("firstName", element);
|
final String firstName = this.fromApiJsonHelper.extractStringNamed(FIRST_NAME, element);
|
||||||
baseDataValidator.reset().parameter("firstName").value(firstName).notNull().notBlank().notExceedingLengthOf(100);
|
baseDataValidator.reset().parameter(FIRST_NAME).value(firstName).notNull().notBlank().notExceedingLengthOf(100);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (this.fromApiJsonHelper.extractStringNamed("lastName", element) != null) {
|
if (this.fromApiJsonHelper.extractStringNamed(LAST_NAME, element) != null) {
|
||||||
final String lastName = this.fromApiJsonHelper.extractStringNamed("lastName", element);
|
final String lastName = this.fromApiJsonHelper.extractStringNamed(LAST_NAME, element);
|
||||||
baseDataValidator.reset().parameter("lastName").value(lastName).notNull().notBlank().notExceedingLengthOf(100);
|
baseDataValidator.reset().parameter(LAST_NAME).value(lastName).notNull().notBlank().notExceedingLengthOf(100);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (this.fromApiJsonHelper.extractStringNamed("middleName", element) != null) {
|
if (this.fromApiJsonHelper.extractStringNamed(MIDDLE_NAME, element) != null) {
|
||||||
final String middleName = this.fromApiJsonHelper.extractStringNamed("middleName", element);
|
final String middleName = this.fromApiJsonHelper.extractStringNamed(MIDDLE_NAME, element);
|
||||||
baseDataValidator.reset().parameter("middleName").value(middleName).notNull().notBlank().notExceedingLengthOf(100);
|
baseDataValidator.reset().parameter(MIDDLE_NAME).value(middleName).notNull().notBlank().notExceedingLengthOf(100);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (this.fromApiJsonHelper.extractStringNamed("qualification", element) != null) {
|
if (this.fromApiJsonHelper.extractStringNamed(QUALIFICATION, element) != null) {
|
||||||
final String qualification = this.fromApiJsonHelper.extractStringNamed("qualification", element);
|
final String qualification = this.fromApiJsonHelper.extractStringNamed(QUALIFICATION, element);
|
||||||
baseDataValidator.reset().parameter("qualification").value(qualification).notNull().notBlank().notExceedingLengthOf(100);
|
baseDataValidator.reset().parameter(QUALIFICATION).value(qualification).notNull().notBlank().notExceedingLengthOf(100);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (this.fromApiJsonHelper.extractLongNamed("relationShipId", element) != null) {
|
if (this.fromApiJsonHelper.extractLongNamed(RELATION_SHIP_ID, element) != null) {
|
||||||
final long relationShipId = this.fromApiJsonHelper.extractLongNamed("relationShipId", element);
|
final long relationShipId = this.fromApiJsonHelper.extractLongNamed(RELATION_SHIP_ID, element);
|
||||||
baseDataValidator.reset().parameter("relationShipId").value(relationShipId).notBlank().longGreaterThanZero();
|
baseDataValidator.reset().parameter(RELATION_SHIP_ID).value(relationShipId).notBlank().longGreaterThanZero();
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (this.fromApiJsonHelper.extractLongNamed("maritalStatusId", element) != null) {
|
if (this.fromApiJsonHelper.extractLongNamed(MARITAL_STATUS_ID, element) != null) {
|
||||||
final long maritalStatusId = this.fromApiJsonHelper.extractLongNamed("maritalStatusId", element);
|
final long maritalStatusId = this.fromApiJsonHelper.extractLongNamed(MARITAL_STATUS_ID, element);
|
||||||
baseDataValidator.reset().parameter("maritalStatusId").value(maritalStatusId).notBlank().longGreaterThanZero();
|
baseDataValidator.reset().parameter(MARITAL_STATUS_ID).value(maritalStatusId).notBlank().longGreaterThanZero();
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (this.fromApiJsonHelper.extractLongNamed("genderId", element) != null) {
|
if (this.fromApiJsonHelper.extractLongNamed(GENDER_ID, element) != null) {
|
||||||
final long genderId = this.fromApiJsonHelper.extractLongNamed("genderId", element);
|
final long genderId = this.fromApiJsonHelper.extractLongNamed(GENDER_ID, element);
|
||||||
baseDataValidator.reset().parameter("genderId").value(genderId).longGreaterThanZero();
|
baseDataValidator.reset().parameter(GENDER_ID).value(genderId).longGreaterThanZero();
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (this.fromApiJsonHelper.extractLongNamed("professionId", element) != null) {
|
if (this.fromApiJsonHelper.extractLongNamed(PROFESSION_ID, element) != null) {
|
||||||
final long professionId = this.fromApiJsonHelper.extractLongNamed("professionId", element);
|
final long professionId = this.fromApiJsonHelper.extractLongNamed(PROFESSION_ID, element);
|
||||||
baseDataValidator.reset().parameter("professionId").value(professionId).longGreaterThanZero();
|
baseDataValidator.reset().parameter(PROFESSION_ID).value(professionId).longGreaterThanZero();
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (this.fromApiJsonHelper.extractLocalDateNamed("dateOfBirth", element) != null) {
|
if (this.fromApiJsonHelper.extractLocalDateNamed(DATE_OF_BIRTH, element) != null) {
|
||||||
final LocalDate dateOfBirth = this.fromApiJsonHelper.extractLocalDateNamed("dateOfBirth", element);
|
final LocalDate dateOfBirth = this.fromApiJsonHelper.extractLocalDateNamed(DATE_OF_BIRTH, element);
|
||||||
baseDataValidator.reset().parameter("dateOfBirth").value(dateOfBirth).validateDateBefore(DateUtils.getBusinessLocalDate());
|
baseDataValidator.reset().parameter(DATE_OF_BIRTH).value(dateOfBirth).validateDateBefore(DateUtils.getBusinessLocalDate());
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -238,7 +263,7 @@ public final class ClientFamilyMemberCommandFromApiJsonDeserializer {
|
|||||||
public void validateForDelete(final long familyMemberId) {
|
public void validateForDelete(final long familyMemberId) {
|
||||||
|
|
||||||
final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
|
final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
|
||||||
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("FamilyMembers");
|
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource(FAMILY_MEMBERS1);
|
||||||
|
|
||||||
// final JsonElement element = this.fromApiJsonHelper.parse(json);
|
// final JsonElement element = this.fromApiJsonHelper.parse(json);
|
||||||
|
|
||||||
|
|||||||
+15
-8
@@ -40,11 +40,16 @@ import org.springframework.stereotype.Component;
|
|||||||
@Component
|
@Component
|
||||||
public final class ClientIdentifierCommandFromApiJsonDeserializer extends AbstractFromApiJsonDeserializer<ClientIdentifierCommand> {
|
public final class ClientIdentifierCommandFromApiJsonDeserializer extends AbstractFromApiJsonDeserializer<ClientIdentifierCommand> {
|
||||||
|
|
||||||
|
public static final String DOCUMENT_TYPE_ID = "documentTypeId";
|
||||||
|
public static final String DOCUMENT_KEY = "documentKey";
|
||||||
|
public static final String STATUS = "status";
|
||||||
|
public static final String DESCRIPTION = "description";
|
||||||
|
public static final String DOCUMENT_DESCRIPTION = "documentDescription";
|
||||||
/**
|
/**
|
||||||
* The parameters supported for this command.
|
* The parameters supported for this command.
|
||||||
*/
|
*/
|
||||||
private final Set<String> supportedParameters = new HashSet<>(Arrays.asList("documentTypeId", "documentKey", "status", "description"));
|
private static final Set<String> SUPPORTED_PARAMETERS = new HashSet<>(
|
||||||
|
Arrays.asList(DOCUMENT_TYPE_ID, DOCUMENT_KEY, STATUS, DESCRIPTION));
|
||||||
private final FromJsonHelper fromApiJsonHelper;
|
private final FromJsonHelper fromApiJsonHelper;
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
@@ -59,14 +64,16 @@ public final class ClientIdentifierCommandFromApiJsonDeserializer extends Abstra
|
|||||||
throw new InvalidJsonException();
|
throw new InvalidJsonException();
|
||||||
}
|
}
|
||||||
|
|
||||||
final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType();
|
final Type typeOfMap = new TypeToken<Map<String, Object>>() {
|
||||||
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParameters);
|
|
||||||
|
}.getType();
|
||||||
|
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, SUPPORTED_PARAMETERS);
|
||||||
|
|
||||||
final JsonElement element = this.fromApiJsonHelper.parse(json);
|
final JsonElement element = this.fromApiJsonHelper.parse(json);
|
||||||
final Long documentTypeId = this.fromApiJsonHelper.extractLongNamed("documentTypeId", element);
|
final Long documentTypeId = this.fromApiJsonHelper.extractLongNamed(DOCUMENT_TYPE_ID, element);
|
||||||
final String documentKey = this.fromApiJsonHelper.extractStringNamed("documentKey", element);
|
final String documentKey = this.fromApiJsonHelper.extractStringNamed(DOCUMENT_KEY, element);
|
||||||
final String documentDescription = this.fromApiJsonHelper.extractStringNamed("documentDescription", element);
|
final String documentDescription = this.fromApiJsonHelper.extractStringNamed(DOCUMENT_DESCRIPTION, element);
|
||||||
final String statusString = this.fromApiJsonHelper.extractStringNamed("status", element);
|
final String statusString = this.fromApiJsonHelper.extractStringNamed(STATUS, element);
|
||||||
return new ClientIdentifierCommand(documentTypeId, documentKey, statusString, documentDescription);
|
return new ClientIdentifierCommand(documentTypeId, documentKey, statusString, documentDescription);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+1
-1
@@ -723,7 +723,7 @@ public class ClientWritePlatformServiceJpaRepositoryImpl implements ClientWriteP
|
|||||||
|
|
||||||
final List<Loan> clientLoans = this.loanRepositoryWrapper.findLoanByClientId(clientId);
|
final List<Loan> clientLoans = this.loanRepositoryWrapper.findLoanByClientId(clientId);
|
||||||
for (final Loan loan : clientLoans) {
|
for (final Loan loan : clientLoans) {
|
||||||
final LoanStatusMapper loanStatus = new LoanStatusMapper(loan.status().getValue());
|
final LoanStatusMapper loanStatus = new LoanStatusMapper(loan.getStatus().getValue());
|
||||||
if (loanStatus.isOpen() || loanStatus.isPendingApproval() || loanStatus.isAwaitingDisbursal()) {
|
if (loanStatus.isOpen() || loanStatus.isPendingApproval() || loanStatus.isAwaitingDisbursal()) {
|
||||||
final String errorMessage = "Client cannot be closed because of non-closed loans.";
|
final String errorMessage = "Client cannot be closed because of non-closed loans.";
|
||||||
throw new InvalidClientStateTransitionException("close", "loan.non-closed", errorMessage);
|
throw new InvalidClientStateTransitionException("close", "loan.non-closed", errorMessage);
|
||||||
|
|||||||
+6
-6
@@ -68,7 +68,7 @@ public class CollateralsApiResource {
|
|||||||
private static final Set<String> RESPONSE_DATA_PARAMETERS = new HashSet<>(
|
private static final Set<String> RESPONSE_DATA_PARAMETERS = new HashSet<>(
|
||||||
Arrays.asList("id", "type", "value", "description", "allowedCollateralTypes", "currency"));
|
Arrays.asList("id", "type", "value", "description", "allowedCollateralTypes", "currency"));
|
||||||
|
|
||||||
private final String resourceNameForPermission = "COLLATERAL";
|
private static final String RESOURCE_NAME_FOR_PERMISSION = "COLLATERAL";
|
||||||
|
|
||||||
private final CollateralReadPlatformService collateralReadPlatformService;
|
private final CollateralReadPlatformService collateralReadPlatformService;
|
||||||
private final DefaultToApiJsonSerializer<CollateralData> apiJsonSerializerService;
|
private final DefaultToApiJsonSerializer<CollateralData> apiJsonSerializerService;
|
||||||
@@ -101,7 +101,7 @@ public class CollateralsApiResource {
|
|||||||
public String newCollateralTemplate(@Context final UriInfo uriInfo,
|
public String newCollateralTemplate(@Context final UriInfo uriInfo,
|
||||||
@PathParam("loanId") @Parameter(description = "loanId") final Long loanId) {
|
@PathParam("loanId") @Parameter(description = "loanId") final Long loanId) {
|
||||||
|
|
||||||
this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermission);
|
this.context.authenticatedUser().validateHasReadPermission(RESOURCE_NAME_FOR_PERMISSION);
|
||||||
|
|
||||||
final Collection<CodeValueData> codeValues = this.codeValueReadPlatformService.retrieveCodeValuesByCode("LoanCollateral");
|
final Collection<CodeValueData> codeValues = this.codeValueReadPlatformService.retrieveCodeValuesByCode("LoanCollateral");
|
||||||
final CollateralData collateralData = CollateralData.template(codeValues);
|
final CollateralData collateralData = CollateralData.template(codeValues);
|
||||||
@@ -119,13 +119,13 @@ public class CollateralsApiResource {
|
|||||||
@ApiResponse(responseCode = "200", description = "OK", content = @Content(array = @ArraySchema(schema = @Schema(implementation = CollateralsApiResourceSwagger.GetLoansLoanIdCollateralsResponse.class)))) })
|
@ApiResponse(responseCode = "200", description = "OK", content = @Content(array = @ArraySchema(schema = @Schema(implementation = CollateralsApiResourceSwagger.GetLoansLoanIdCollateralsResponse.class)))) })
|
||||||
public String retrieveCollateralDetails(@Context final UriInfo uriInfo,
|
public String retrieveCollateralDetails(@Context final UriInfo uriInfo,
|
||||||
@PathParam("loanId") @Parameter(description = "loanId") final Long loanId) {
|
@PathParam("loanId") @Parameter(description = "loanId") final Long loanId) {
|
||||||
this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermission);
|
this.context.authenticatedUser().validateHasReadPermission(RESOURCE_NAME_FOR_PERMISSION);
|
||||||
|
|
||||||
final List<CollateralData> CollateralDatas = this.collateralReadPlatformService.retrieveCollateralsForValidLoan(loanId);
|
final List<CollateralData> collateralDatas = this.collateralReadPlatformService.retrieveCollateralsForValidLoan(loanId);
|
||||||
|
|
||||||
final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters());
|
final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters());
|
||||||
|
|
||||||
return this.apiJsonSerializerService.serialize(settings, CollateralDatas, RESPONSE_DATA_PARAMETERS);
|
return this.apiJsonSerializerService.serialize(settings, collateralDatas, RESPONSE_DATA_PARAMETERS);
|
||||||
}
|
}
|
||||||
|
|
||||||
@GET
|
@GET
|
||||||
@@ -139,7 +139,7 @@ public class CollateralsApiResource {
|
|||||||
public String retrieveCollateralDetails(@Context final UriInfo uriInfo,
|
public String retrieveCollateralDetails(@Context final UriInfo uriInfo,
|
||||||
@PathParam("loanId") @Parameter(description = "loanId") final Long loanId,
|
@PathParam("loanId") @Parameter(description = "loanId") final Long loanId,
|
||||||
@PathParam("collateralId") @Parameter(description = "collateralId") final Long CollateralId) {
|
@PathParam("collateralId") @Parameter(description = "collateralId") final Long CollateralId) {
|
||||||
this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermission);
|
this.context.authenticatedUser().validateHasReadPermission(RESOURCE_NAME_FOR_PERMISSION);
|
||||||
|
|
||||||
CollateralData collateralData = this.collateralReadPlatformService.retrieveCollateral(loanId, CollateralId);
|
CollateralData collateralData = this.collateralReadPlatformService.retrieveCollateral(loanId, CollateralId);
|
||||||
|
|
||||||
|
|||||||
+3
-3
@@ -90,7 +90,7 @@ public class CollateralWritePlatformServiceJpaRepositoryImpl implements Collater
|
|||||||
/**
|
/**
|
||||||
* Collaterals may be added only when the loan associated with them are yet to be approved
|
* Collaterals may be added only when the loan associated with them are yet to be approved
|
||||||
**/
|
**/
|
||||||
if (!loan.status().isSubmittedAndPendingApproval()) {
|
if (!loan.getStatus().isSubmittedAndPendingApproval()) {
|
||||||
throw new CollateralCannotBeCreatedException(
|
throw new CollateralCannotBeCreatedException(
|
||||||
LoanCollateralCannotBeCreatedReason.LOAN_NOT_IN_SUBMITTED_AND_PENDING_APPROVAL_STAGE, loan.getId());
|
LoanCollateralCannotBeCreatedReason.LOAN_NOT_IN_SUBMITTED_AND_PENDING_APPROVAL_STAGE, loan.getId());
|
||||||
}
|
}
|
||||||
@@ -136,7 +136,7 @@ public class CollateralWritePlatformServiceJpaRepositoryImpl implements Collater
|
|||||||
/**
|
/**
|
||||||
* Collaterals may be updated only when the loan associated with them are yet to be approved
|
* Collaterals may be updated only when the loan associated with them are yet to be approved
|
||||||
**/
|
**/
|
||||||
if (!loan.status().isSubmittedAndPendingApproval()) {
|
if (!loan.getStatus().isSubmittedAndPendingApproval()) {
|
||||||
throw new CollateralCannotBeUpdatedException(
|
throw new CollateralCannotBeUpdatedException(
|
||||||
LoanCollateralCannotBeUpdatedReason.LOAN_NOT_IN_SUBMITTED_AND_PENDING_APPROVAL_STAGE, loan.getId());
|
LoanCollateralCannotBeUpdatedReason.LOAN_NOT_IN_SUBMITTED_AND_PENDING_APPROVAL_STAGE, loan.getId());
|
||||||
}
|
}
|
||||||
@@ -169,7 +169,7 @@ public class CollateralWritePlatformServiceJpaRepositoryImpl implements Collater
|
|||||||
/**
|
/**
|
||||||
* Collaterals may be deleted only when the loan associated with them are yet to be approved
|
* Collaterals may be deleted only when the loan associated with them are yet to be approved
|
||||||
**/
|
**/
|
||||||
if (!loan.status().isSubmittedAndPendingApproval()) {
|
if (!loan.getStatus().isSubmittedAndPendingApproval()) {
|
||||||
throw new CollateralCannotBeDeletedException(
|
throw new CollateralCannotBeDeletedException(
|
||||||
LoanCollateralCannotBeDeletedReason.LOAN_NOT_IN_SUBMITTED_AND_PENDING_APPROVAL_STAGE, loanId, collateralId);
|
LoanCollateralCannotBeDeletedReason.LOAN_NOT_IN_SUBMITTED_AND_PENDING_APPROVAL_STAGE, loanId, collateralId);
|
||||||
}
|
}
|
||||||
|
|||||||
-13
@@ -42,15 +42,12 @@ import javax.ws.rs.core.UriInfo;
|
|||||||
import org.apache.fineract.commands.domain.CommandWrapper;
|
import org.apache.fineract.commands.domain.CommandWrapper;
|
||||||
import org.apache.fineract.commands.service.CommandWrapperBuilder;
|
import org.apache.fineract.commands.service.CommandWrapperBuilder;
|
||||||
import org.apache.fineract.commands.service.PortfolioCommandSourceWritePlatformService;
|
import org.apache.fineract.commands.service.PortfolioCommandSourceWritePlatformService;
|
||||||
import org.apache.fineract.infrastructure.codes.service.CodeValueReadPlatformService;
|
|
||||||
import org.apache.fineract.infrastructure.core.api.ApiRequestParameterHelper;
|
|
||||||
import org.apache.fineract.infrastructure.core.data.CommandProcessingResult;
|
import org.apache.fineract.infrastructure.core.data.CommandProcessingResult;
|
||||||
import org.apache.fineract.infrastructure.core.serialization.DefaultToApiJsonSerializer;
|
import org.apache.fineract.infrastructure.core.serialization.DefaultToApiJsonSerializer;
|
||||||
import org.apache.fineract.infrastructure.security.service.PlatformSecurityContext;
|
import org.apache.fineract.infrastructure.security.service.PlatformSecurityContext;
|
||||||
import org.apache.fineract.organisation.monetary.data.CurrencyData;
|
import org.apache.fineract.organisation.monetary.data.CurrencyData;
|
||||||
import org.apache.fineract.organisation.monetary.service.CurrencyReadPlatformService;
|
import org.apache.fineract.organisation.monetary.service.CurrencyReadPlatformService;
|
||||||
import org.apache.fineract.portfolio.collateralmanagement.data.CollateralManagementData;
|
import org.apache.fineract.portfolio.collateralmanagement.data.CollateralManagementData;
|
||||||
import org.apache.fineract.portfolio.collateralmanagement.service.ClientCollateralManagementReadPlatformService;
|
|
||||||
import org.apache.fineract.portfolio.collateralmanagement.service.CollateralManagementReadPlatformService;
|
import org.apache.fineract.portfolio.collateralmanagement.service.CollateralManagementReadPlatformService;
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
import org.springframework.context.annotation.Scope;
|
import org.springframework.context.annotation.Scope;
|
||||||
@@ -64,31 +61,21 @@ public class CollateralManagementApiResource {
|
|||||||
|
|
||||||
private final DefaultToApiJsonSerializer<CollateralManagementData> apiJsonSerializerService;
|
private final DefaultToApiJsonSerializer<CollateralManagementData> apiJsonSerializerService;
|
||||||
private final DefaultToApiJsonSerializer<CurrencyData> apiJsonSerializerServiceForCurrency;
|
private final DefaultToApiJsonSerializer<CurrencyData> apiJsonSerializerServiceForCurrency;
|
||||||
private final ApiRequestParameterHelper apiRequestParameterHelper;
|
|
||||||
private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService;
|
private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService;
|
||||||
private final PlatformSecurityContext context;
|
private final PlatformSecurityContext context;
|
||||||
private final CodeValueReadPlatformService codeValueReadPlatformService;
|
|
||||||
private final CollateralManagementReadPlatformService collateralManagementReadPlatformService;
|
private final CollateralManagementReadPlatformService collateralManagementReadPlatformService;
|
||||||
private final String collateralReadPermission = "COLLATERAL_PRODUCT";
|
|
||||||
private final ClientCollateralManagementReadPlatformService clientCollateralManagementReadPlatformService;
|
|
||||||
private final CurrencyReadPlatformService currencyReadPlatformService;
|
private final CurrencyReadPlatformService currencyReadPlatformService;
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
public CollateralManagementApiResource(final DefaultToApiJsonSerializer<CollateralManagementData> apiJsonSerializerService,
|
public CollateralManagementApiResource(final DefaultToApiJsonSerializer<CollateralManagementData> apiJsonSerializerService,
|
||||||
final ApiRequestParameterHelper apiRequestParameterHelper,
|
|
||||||
final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService, final PlatformSecurityContext context,
|
final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService, final PlatformSecurityContext context,
|
||||||
final CodeValueReadPlatformService codeValueReadPlatformService,
|
|
||||||
final CollateralManagementReadPlatformService collateralManagementReadPlatformService,
|
final CollateralManagementReadPlatformService collateralManagementReadPlatformService,
|
||||||
final ClientCollateralManagementReadPlatformService clientCollateralManagementReadPlatformService,
|
|
||||||
final CurrencyReadPlatformService currencyReadPlatformService,
|
final CurrencyReadPlatformService currencyReadPlatformService,
|
||||||
final DefaultToApiJsonSerializer<CurrencyData> apiJsonSerializerServiceForCurrency) {
|
final DefaultToApiJsonSerializer<CurrencyData> apiJsonSerializerServiceForCurrency) {
|
||||||
this.apiJsonSerializerService = apiJsonSerializerService;
|
this.apiJsonSerializerService = apiJsonSerializerService;
|
||||||
this.apiRequestParameterHelper = apiRequestParameterHelper;
|
|
||||||
this.commandsSourceWritePlatformService = commandsSourceWritePlatformService;
|
this.commandsSourceWritePlatformService = commandsSourceWritePlatformService;
|
||||||
this.context = context;
|
this.context = context;
|
||||||
this.codeValueReadPlatformService = codeValueReadPlatformService;
|
|
||||||
this.collateralManagementReadPlatformService = collateralManagementReadPlatformService;
|
this.collateralManagementReadPlatformService = collateralManagementReadPlatformService;
|
||||||
this.clientCollateralManagementReadPlatformService = clientCollateralManagementReadPlatformService;
|
|
||||||
this.currencyReadPlatformService = currencyReadPlatformService;
|
this.currencyReadPlatformService = currencyReadPlatformService;
|
||||||
this.apiJsonSerializerServiceForCurrency = apiJsonSerializerServiceForCurrency;
|
this.apiJsonSerializerServiceForCurrency = apiJsonSerializerServiceForCurrency;
|
||||||
}
|
}
|
||||||
|
|||||||
+11
-8
@@ -47,15 +47,14 @@ import org.springframework.stereotype.Component;
|
|||||||
@Component
|
@Component
|
||||||
public class CollectionSheetGenerateCommandFromApiJsonDeserializer {
|
public class CollectionSheetGenerateCommandFromApiJsonDeserializer {
|
||||||
|
|
||||||
|
public static final String COLLECTIONSHEET = "collectionsheet";
|
||||||
/**
|
/**
|
||||||
* The parameters supported for this command.
|
* The parameters supported for this command.
|
||||||
*/
|
*/
|
||||||
final Set<String> supportedParameters = new HashSet<>(
|
private static final Set<String> SUPPORTED_PARAMETERS = new HashSet<>(
|
||||||
Arrays.asList(transactionDateParamName, localeParamName, dateFormatParamName, calendarIdParamName));
|
Arrays.asList(transactionDateParamName, localeParamName, dateFormatParamName, calendarIdParamName));
|
||||||
|
|
||||||
private static final Set<String> INDIVIDUAL_COLLECTIONSHEET_SUPPORTED_PARAMS = new HashSet<>(
|
private static final Set<String> INDIVIDUAL_COLLECTIONSHEET_SUPPORTED_PARAMS = new HashSet<>(
|
||||||
Arrays.asList(transactionDateParamName, localeParamName, dateFormatParamName, officeIdParamName, staffIdParamName));
|
Arrays.asList(transactionDateParamName, localeParamName, dateFormatParamName, officeIdParamName, staffIdParamName));
|
||||||
|
|
||||||
private final FromJsonHelper fromApiJsonHelper;
|
private final FromJsonHelper fromApiJsonHelper;
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
@@ -69,13 +68,15 @@ public class CollectionSheetGenerateCommandFromApiJsonDeserializer {
|
|||||||
throw new InvalidJsonException();
|
throw new InvalidJsonException();
|
||||||
}
|
}
|
||||||
|
|
||||||
final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType();
|
final Type typeOfMap = new TypeToken<Map<String, Object>>() {
|
||||||
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParameters);
|
|
||||||
|
}.getType();
|
||||||
|
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, SUPPORTED_PARAMETERS);
|
||||||
final JsonElement element = this.fromApiJsonHelper.parse(json);
|
final JsonElement element = this.fromApiJsonHelper.parse(json);
|
||||||
|
|
||||||
final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
|
final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
|
||||||
|
|
||||||
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("collectionsheet");
|
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource(COLLECTIONSHEET);
|
||||||
|
|
||||||
final String transactionDateStr = this.fromApiJsonHelper.extractStringNamed(transactionDateParamName, element);
|
final String transactionDateStr = this.fromApiJsonHelper.extractStringNamed(transactionDateParamName, element);
|
||||||
baseDataValidator.reset().parameter(transactionDateParamName).value(transactionDateStr).notBlank();
|
baseDataValidator.reset().parameter(transactionDateParamName).value(transactionDateStr).notBlank();
|
||||||
@@ -100,13 +101,15 @@ public class CollectionSheetGenerateCommandFromApiJsonDeserializer {
|
|||||||
throw new InvalidJsonException();
|
throw new InvalidJsonException();
|
||||||
}
|
}
|
||||||
|
|
||||||
final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType();
|
final Type typeOfMap = new TypeToken<Map<String, Object>>() {
|
||||||
|
|
||||||
|
}.getType();
|
||||||
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, INDIVIDUAL_COLLECTIONSHEET_SUPPORTED_PARAMS);
|
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, INDIVIDUAL_COLLECTIONSHEET_SUPPORTED_PARAMS);
|
||||||
final JsonElement element = this.fromApiJsonHelper.parse(json);
|
final JsonElement element = this.fromApiJsonHelper.parse(json);
|
||||||
|
|
||||||
final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
|
final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
|
||||||
|
|
||||||
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("collectionsheet");
|
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource(COLLECTIONSHEET);
|
||||||
|
|
||||||
final String transactionDateStr = this.fromApiJsonHelper.extractStringNamed(transactionDateParamName, element);
|
final String transactionDateStr = this.fromApiJsonHelper.extractStringNamed(transactionDateParamName, element);
|
||||||
baseDataValidator.reset().parameter(transactionDateParamName).value(transactionDateStr).notBlank();
|
baseDataValidator.reset().parameter(transactionDateParamName).value(transactionDateStr).notBlank();
|
||||||
|
|||||||
+68
-59
@@ -44,11 +44,20 @@ import org.springframework.stereotype.Component;
|
|||||||
@Component
|
@Component
|
||||||
public class FloatingRateDataValidator {
|
public class FloatingRateDataValidator {
|
||||||
|
|
||||||
private final Set<String> supportedParametersForFloatingRates = new HashSet<>(
|
public static final String NAME = "name";
|
||||||
Arrays.asList("name", "isBaseLendingRate", "isActive", "ratePeriods"));
|
public static final String IS_BASE_LENDING_RATE = "isBaseLendingRate";
|
||||||
private final Set<String> supportedParametersForFloatingRatePeriods = new HashSet<>(
|
public static final String IS_ACTIVE = "isActive";
|
||||||
Arrays.asList("fromDate", "interestRate", "isDifferentialToBaseLendingRate", "locale", "dateFormat"));
|
public static final String RATE_PERIODS = "ratePeriods";
|
||||||
|
public static final String FROM_DATE = "fromDate";
|
||||||
|
public static final String INTEREST_RATE = "interestRate";
|
||||||
|
public static final String IS_DIFFERENTIAL_TO_BASE_LENDING_RATE = "isDifferentialToBaseLendingRate";
|
||||||
|
public static final String LOCALE = "locale";
|
||||||
|
public static final String DATE_FORMAT = "dateFormat";
|
||||||
|
public static final String FLOATINGRATE = "floatingrate";
|
||||||
|
private static final Set<String> SUPPORTED_PARAMETERS_FOR_FLOATING_RATES = new HashSet<>(
|
||||||
|
Arrays.asList(NAME, IS_BASE_LENDING_RATE, IS_ACTIVE, RATE_PERIODS));
|
||||||
|
private static final Set<String> SUPPORTED_PARAMETERS_FOR_FLOATING_RATE_PERIODS = new HashSet<>(
|
||||||
|
Arrays.asList(FROM_DATE, INTEREST_RATE, IS_DIFFERENTIAL_TO_BASE_LENDING_RATE, LOCALE, DATE_FORMAT));
|
||||||
private final FromJsonHelper fromApiJsonHelper;
|
private final FromJsonHelper fromApiJsonHelper;
|
||||||
private final FloatingRateRepository floatingRateRepository;
|
private final FloatingRateRepository floatingRateRepository;
|
||||||
|
|
||||||
@@ -59,37 +68,39 @@ public class FloatingRateDataValidator {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public void validateForCreate(String json) {
|
public void validateForCreate(String json) {
|
||||||
final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType();
|
final Type typeOfMap = new TypeToken<Map<String, Object>>() {
|
||||||
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParametersForFloatingRates);
|
|
||||||
|
}.getType();
|
||||||
|
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, SUPPORTED_PARAMETERS_FOR_FLOATING_RATES);
|
||||||
|
|
||||||
final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
|
final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
|
||||||
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("floatingrate");
|
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource(FLOATINGRATE);
|
||||||
|
|
||||||
final JsonElement element = this.fromApiJsonHelper.parse(json);
|
final JsonElement element = this.fromApiJsonHelper.parse(json);
|
||||||
|
|
||||||
final String name = this.fromApiJsonHelper.extractStringNamed("name", element);
|
final String name = this.fromApiJsonHelper.extractStringNamed(NAME, element);
|
||||||
baseDataValidator.reset().parameter("name").value(name).notBlank().notExceedingLengthOf(200);
|
baseDataValidator.reset().parameter(NAME).value(name).notBlank().notExceedingLengthOf(200);
|
||||||
|
|
||||||
Boolean isBaseLendingRate = null;
|
Boolean isBaseLendingRate = null;
|
||||||
if (this.fromApiJsonHelper.parameterExists("isBaseLendingRate", element)) {
|
if (this.fromApiJsonHelper.parameterExists(IS_BASE_LENDING_RATE, element)) {
|
||||||
isBaseLendingRate = this.fromApiJsonHelper.extractBooleanNamed("isBaseLendingRate", element);
|
isBaseLendingRate = this.fromApiJsonHelper.extractBooleanNamed(IS_BASE_LENDING_RATE, element);
|
||||||
|
|
||||||
baseDataValidator.reset().parameter("isBaseLendingRate").value(isBaseLendingRate).notNull();
|
baseDataValidator.reset().parameter(IS_BASE_LENDING_RATE).value(isBaseLendingRate).notNull();
|
||||||
if (isBaseLendingRate == null) {
|
if (isBaseLendingRate == null) {
|
||||||
baseDataValidator.reset().parameter("isBaseLendingRate").trueOrFalseRequired(false);
|
baseDataValidator.reset().parameter(IS_BASE_LENDING_RATE).trueOrFalseRequired(false);
|
||||||
} else if (isBaseLendingRate) {
|
} else if (isBaseLendingRate) {
|
||||||
FloatingRate baseLendingRate = this.floatingRateRepository.retrieveBaseLendingRate();
|
FloatingRate baseLendingRate = this.floatingRateRepository.retrieveBaseLendingRate();
|
||||||
if (baseLendingRate != null) {
|
if (baseLendingRate != null) {
|
||||||
baseDataValidator.reset().parameter("isBaseLendingRate").value(isBaseLendingRate)
|
baseDataValidator.reset().parameter(IS_BASE_LENDING_RATE).value(isBaseLendingRate)
|
||||||
.failWithCode("baselendingrate.duplicate", "Base Lending Rate already exists");
|
.failWithCode("baselendingrate.duplicate", "Base Lending Rate already exists");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (this.fromApiJsonHelper.parameterExists("isActive", element)) {
|
if (this.fromApiJsonHelper.parameterExists(IS_ACTIVE, element)) {
|
||||||
final Boolean isActive = this.fromApiJsonHelper.extractBooleanNamed("isActive", element);
|
final Boolean isActive = this.fromApiJsonHelper.extractBooleanNamed(IS_ACTIVE, element);
|
||||||
if (isActive == null) {
|
if (isActive == null) {
|
||||||
baseDataValidator.reset().parameter("isActive").trueOrFalseRequired(false);
|
baseDataValidator.reset().parameter(IS_ACTIVE).trueOrFalseRequired(false);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -103,9 +114,9 @@ public class FloatingRateDataValidator {
|
|||||||
|
|
||||||
private void validateRatePeriods(DataValidatorBuilder baseDataValidator, JsonElement element, boolean isBaseLendingRate,
|
private void validateRatePeriods(DataValidatorBuilder baseDataValidator, JsonElement element, boolean isBaseLendingRate,
|
||||||
boolean isBLRModifiedAsNonBLR) {
|
boolean isBLRModifiedAsNonBLR) {
|
||||||
if (this.fromApiJsonHelper.parameterExists("ratePeriods", element)) {
|
if (this.fromApiJsonHelper.parameterExists(RATE_PERIODS, element)) {
|
||||||
final JsonArray ratePeriods = this.fromApiJsonHelper.extractJsonArrayNamed("ratePeriods", element);
|
final JsonArray ratePeriods = this.fromApiJsonHelper.extractJsonArrayNamed(RATE_PERIODS, element);
|
||||||
baseDataValidator.reset().parameter("ratePeriods").value(ratePeriods).notBlank().jsonArrayNotEmpty();
|
baseDataValidator.reset().parameter(RATE_PERIODS).value(ratePeriods).notBlank().jsonArrayNotEmpty();
|
||||||
|
|
||||||
if (ratePeriods != null) {
|
if (ratePeriods != null) {
|
||||||
List<LocalDate> fromDates = new ArrayList<>();
|
List<LocalDate> fromDates = new ArrayList<>();
|
||||||
@@ -113,38 +124,38 @@ public class FloatingRateDataValidator {
|
|||||||
final JsonElement ratePeriod = ratePeriods.get(i);
|
final JsonElement ratePeriod = ratePeriods.get(i);
|
||||||
|
|
||||||
this.fromApiJsonHelper.checkForUnsupportedParameters(ratePeriod.getAsJsonObject(),
|
this.fromApiJsonHelper.checkForUnsupportedParameters(ratePeriod.getAsJsonObject(),
|
||||||
this.supportedParametersForFloatingRatePeriods);
|
SUPPORTED_PARAMETERS_FOR_FLOATING_RATE_PERIODS);
|
||||||
|
|
||||||
final LocalDate fromDate = this.fromApiJsonHelper.extractLocalDateNamed("fromDate", ratePeriod);
|
final LocalDate fromDate = this.fromApiJsonHelper.extractLocalDateNamed(FROM_DATE, ratePeriod);
|
||||||
baseDataValidator.reset().parameter("fromDate").parameterAtIndexArray("fromDate", i + 1).value(fromDate).notBlank()
|
baseDataValidator.reset().parameter(FROM_DATE).parameterAtIndexArray(FROM_DATE, i + 1).value(fromDate).notBlank()
|
||||||
.validateDateAfter(DateUtils.getBusinessLocalDate().plusDays(1));
|
.validateDateAfter(DateUtils.getBusinessLocalDate().plusDays(1));
|
||||||
if (fromDate != null) {
|
if (fromDate != null) {
|
||||||
fromDates.add(fromDate);
|
fromDates.add(fromDate);
|
||||||
}
|
}
|
||||||
|
|
||||||
final BigDecimal interestRatePerPeriod = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed("interestRate",
|
final BigDecimal interestRatePerPeriod = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed(INTEREST_RATE,
|
||||||
ratePeriod);
|
ratePeriod);
|
||||||
baseDataValidator.reset().parameter("interestRate").parameterAtIndexArray("interestRate", i + 1)
|
baseDataValidator.reset().parameter(INTEREST_RATE).parameterAtIndexArray(INTEREST_RATE, i + 1)
|
||||||
.value(interestRatePerPeriod).notNull().zeroOrPositiveAmount();
|
.value(interestRatePerPeriod).notNull().zeroOrPositiveAmount();
|
||||||
|
|
||||||
if (this.fromApiJsonHelper.parameterExists("isDifferentialToBaseLendingRate", ratePeriod)) {
|
if (this.fromApiJsonHelper.parameterExists(IS_DIFFERENTIAL_TO_BASE_LENDING_RATE, ratePeriod)) {
|
||||||
final Boolean isDifferentialToBaseLendingRate = this.fromApiJsonHelper
|
final Boolean isDifferentialToBaseLendingRate = this.fromApiJsonHelper
|
||||||
.extractBooleanNamed("isDifferentialToBaseLendingRate", ratePeriod);
|
.extractBooleanNamed(IS_DIFFERENTIAL_TO_BASE_LENDING_RATE, ratePeriod);
|
||||||
if (isDifferentialToBaseLendingRate == null) {
|
if (isDifferentialToBaseLendingRate == null) {
|
||||||
baseDataValidator.reset().parameter("isDifferentialToBaseLendingRate")
|
baseDataValidator.reset().parameter(IS_DIFFERENTIAL_TO_BASE_LENDING_RATE)
|
||||||
.parameterAtIndexArray("isDifferentialToBaseLendingRate", i + 1).trueOrFalseRequired(false);
|
.parameterAtIndexArray(IS_DIFFERENTIAL_TO_BASE_LENDING_RATE, i + 1).trueOrFalseRequired(false);
|
||||||
} else if (isDifferentialToBaseLendingRate) {
|
} else if (isDifferentialToBaseLendingRate) {
|
||||||
FloatingRate baseLendingRate = this.floatingRateRepository.retrieveBaseLendingRate();
|
FloatingRate baseLendingRate = this.floatingRateRepository.retrieveBaseLendingRate();
|
||||||
if (baseLendingRate == null || isBLRModifiedAsNonBLR) {
|
if (baseLendingRate == null || isBLRModifiedAsNonBLR) {
|
||||||
baseDataValidator.reset().parameter("isDifferentialToBaseLendingRate")
|
baseDataValidator.reset().parameter(IS_DIFFERENTIAL_TO_BASE_LENDING_RATE)
|
||||||
.parameterAtIndexArray("isDifferentialToBaseLendingRate", i + 1)
|
.parameterAtIndexArray(IS_DIFFERENTIAL_TO_BASE_LENDING_RATE, i + 1)
|
||||||
.value(isDifferentialToBaseLendingRate)
|
.value(isDifferentialToBaseLendingRate)
|
||||||
.failWithCode("no.baselending.rate.defined", "Base Lending Rate doesn't exists");
|
.failWithCode("no.baselending.rate.defined", "Base Lending Rate doesn't exists");
|
||||||
}
|
}
|
||||||
|
|
||||||
if (isBaseLendingRate) {
|
if (isBaseLendingRate) {
|
||||||
baseDataValidator.reset().parameter("isDifferentialToBaseLendingRate")
|
baseDataValidator.reset().parameter(IS_DIFFERENTIAL_TO_BASE_LENDING_RATE)
|
||||||
.parameterAtIndexArray("isDifferentialToBaseLendingRate", i + 1)
|
.parameterAtIndexArray(IS_DIFFERENTIAL_TO_BASE_LENDING_RATE, i + 1)
|
||||||
.value(isDifferentialToBaseLendingRate).failWithCode("cannot.be.true.for.baselendingrate",
|
.value(isDifferentialToBaseLendingRate).failWithCode("cannot.be.true.for.baselendingrate",
|
||||||
"isDifferentialToBaseLendingRate cannot be true for floating rate marked as Base Lending Rate.");
|
"isDifferentialToBaseLendingRate cannot be true for floating rate marked as Base Lending Rate.");
|
||||||
}
|
}
|
||||||
@@ -154,7 +165,7 @@ public class FloatingRateDataValidator {
|
|||||||
}
|
}
|
||||||
Set<LocalDate> uniqueFromDates = new HashSet<>(fromDates);
|
Set<LocalDate> uniqueFromDates = new HashSet<>(fromDates);
|
||||||
if (fromDates.size() != uniqueFromDates.size()) {
|
if (fromDates.size() != uniqueFromDates.size()) {
|
||||||
baseDataValidator.reset().parameter("fromDate").failWithCode("multiple.same.date",
|
baseDataValidator.reset().parameter(FROM_DATE).failWithCode("multiple.same.date",
|
||||||
"More than one entry in ratePeriods have same fromDate.");
|
"More than one entry in ratePeriods have same fromDate.");
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -163,41 +174,41 @@ public class FloatingRateDataValidator {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public void validateForUpdate(String json, FloatingRate floatingRateForUpdate) {
|
public void validateForUpdate(String json, FloatingRate floatingRateForUpdate) {
|
||||||
final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType();
|
final Type typeOfMap = new TypeToken<Map<String, Object>>() {
|
||||||
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParametersForFloatingRates);
|
|
||||||
|
}.getType();
|
||||||
|
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, SUPPORTED_PARAMETERS_FOR_FLOATING_RATES);
|
||||||
|
|
||||||
final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
|
final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
|
||||||
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("floatingrate");
|
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource(FLOATINGRATE);
|
||||||
|
|
||||||
final JsonElement element = this.fromApiJsonHelper.parse(json);
|
final JsonElement element = this.fromApiJsonHelper.parse(json);
|
||||||
|
|
||||||
if (this.fromApiJsonHelper.parameterExists("name", element)) {
|
if (this.fromApiJsonHelper.parameterExists(NAME, element)) {
|
||||||
final String name = this.fromApiJsonHelper.extractStringNamed("name", element);
|
final String name = this.fromApiJsonHelper.extractStringNamed(NAME, element);
|
||||||
baseDataValidator.reset().parameter("name").value(name).notBlank().notExceedingLengthOf(200);
|
baseDataValidator.reset().parameter(NAME).value(name).notBlank().notExceedingLengthOf(200);
|
||||||
}
|
}
|
||||||
|
|
||||||
Boolean isBaseLendingRate = null;
|
Boolean isBaseLendingRate = null;
|
||||||
Boolean isBLRModifiedAsNonBLR = false;
|
Boolean isBLRModifiedAsNonBLR = false;
|
||||||
FloatingRate baseLendingRate = this.floatingRateRepository.retrieveBaseLendingRate();
|
FloatingRate baseLendingRate = this.floatingRateRepository.retrieveBaseLendingRate();
|
||||||
if (this.fromApiJsonHelper.parameterExists("isBaseLendingRate", element)) {
|
if (this.fromApiJsonHelper.parameterExists(IS_BASE_LENDING_RATE, element)) {
|
||||||
isBaseLendingRate = this.fromApiJsonHelper.extractBooleanNamed("isBaseLendingRate", element);
|
isBaseLendingRate = this.fromApiJsonHelper.extractBooleanNamed(IS_BASE_LENDING_RATE, element);
|
||||||
|
|
||||||
baseDataValidator.reset().parameter("isBaseLendingRate").value(isBaseLendingRate).notNull();
|
baseDataValidator.reset().parameter(IS_BASE_LENDING_RATE).value(isBaseLendingRate).notNull();
|
||||||
if (isBaseLendingRate == null) {
|
if (isBaseLendingRate == null) {
|
||||||
baseDataValidator.reset().parameter("isBaseLendingRate").trueOrFalseRequired(false);
|
baseDataValidator.reset().parameter(IS_BASE_LENDING_RATE).trueOrFalseRequired(false);
|
||||||
} else if (isBaseLendingRate) {
|
} else if (isBaseLendingRate && baseLendingRate != null && !baseLendingRate.getId().equals(floatingRateForUpdate.getId())) {
|
||||||
if (baseLendingRate != null && !baseLendingRate.getId().equals(floatingRateForUpdate.getId())) {
|
baseDataValidator.reset().parameter(IS_BASE_LENDING_RATE).value(isBaseLendingRate).failWithCode("baselendingrate.duplicate",
|
||||||
baseDataValidator.reset().parameter("isBaseLendingRate").value(isBaseLendingRate)
|
"Base Lending Rate already exists");
|
||||||
.failWithCode("baselendingrate.duplicate", "Base Lending Rate already exists");
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
Boolean isActive = null;
|
Boolean isActive = null;
|
||||||
if (this.fromApiJsonHelper.parameterExists("isActive", element)) {
|
if (this.fromApiJsonHelper.parameterExists(IS_ACTIVE, element)) {
|
||||||
isActive = this.fromApiJsonHelper.extractBooleanNamed("isActive", element);
|
isActive = this.fromApiJsonHelper.extractBooleanNamed(IS_ACTIVE, element);
|
||||||
if (isActive == null) {
|
if (isActive == null) {
|
||||||
baseDataValidator.reset().parameter("isActive").trueOrFalseRequired(false);
|
baseDataValidator.reset().parameter(IS_ACTIVE).trueOrFalseRequired(false);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -209,16 +220,14 @@ public class FloatingRateDataValidator {
|
|||||||
isActive = floatingRateForUpdate.isActive();
|
isActive = floatingRateForUpdate.isActive();
|
||||||
}
|
}
|
||||||
|
|
||||||
if (baseLendingRate != null && baseLendingRate.getId().equals(floatingRateForUpdate.getId())) {
|
if (baseLendingRate != null && baseLendingRate.getId().equals(floatingRateForUpdate.getId()) && (!isBaseLendingRate || !isActive)) {
|
||||||
if (!isBaseLendingRate || !isActive) {
|
isBLRModifiedAsNonBLR = true;
|
||||||
isBLRModifiedAsNonBLR = true;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (isBLRModifiedAsNonBLR) {
|
if (isBLRModifiedAsNonBLR) {
|
||||||
Collection<FloatingRate> floatingRates = this.floatingRateRepository.retrieveFloatingRatesLinkedToBLR();
|
Collection<FloatingRate> floatingRates = this.floatingRateRepository.retrieveFloatingRatesLinkedToBLR();
|
||||||
if (floatingRates != null && floatingRates.size() > 0) {
|
if (floatingRates != null && !floatingRates.isEmpty()) {
|
||||||
baseDataValidator.reset().parameter("isBaseLendingRate").value(isBaseLendingRate).failWithCode(
|
baseDataValidator.reset().parameter(IS_BASE_LENDING_RATE).value(isBaseLendingRate).failWithCode(
|
||||||
"cannot.be.marked.non.baselendingrate",
|
"cannot.be.marked.non.baselendingrate",
|
||||||
"There are floating rates linked to this Base Lending Rate, cannot be marked as non-Base Lending Rate.");
|
"There are floating rates linked to this Base Lending Rate, cannot be marked as non-Base Lending Rate.");
|
||||||
}
|
}
|
||||||
|
|||||||
+6
-6
@@ -65,9 +65,9 @@ public class FundsApiResource {
|
|||||||
/**
|
/**
|
||||||
* The set of parameters that are supported in response for {@link CodeData}
|
* The set of parameters that are supported in response for {@link CodeData}
|
||||||
*/
|
*/
|
||||||
private final Set<String> responseDataParameters = new HashSet<>(Arrays.asList("id", "name", "externalId"));
|
private static final Set<String> RESPONSE_DATA_PARAMETERS = new HashSet<>(Arrays.asList("id", "name", "externalId"));
|
||||||
|
|
||||||
private final String resourceNameForPermissions = "FUND";
|
private static final String RESOURCE_NAME_FOR_PERMISSIONS = "FUND";
|
||||||
|
|
||||||
private final PlatformSecurityContext context;
|
private final PlatformSecurityContext context;
|
||||||
private final FundReadPlatformService readPlatformService;
|
private final FundReadPlatformService readPlatformService;
|
||||||
@@ -94,12 +94,12 @@ public class FundsApiResource {
|
|||||||
@ApiResponse(responseCode = "200", description = "OK", content = @Content(array = @ArraySchema(schema = @Schema(implementation = FundsApiResourceSwagger.GetFundsResponse.class)))) })
|
@ApiResponse(responseCode = "200", description = "OK", content = @Content(array = @ArraySchema(schema = @Schema(implementation = FundsApiResourceSwagger.GetFundsResponse.class)))) })
|
||||||
public String retrieveFunds(@Context final UriInfo uriInfo) {
|
public String retrieveFunds(@Context final UriInfo uriInfo) {
|
||||||
|
|
||||||
this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions);
|
this.context.authenticatedUser().validateHasReadPermission(RESOURCE_NAME_FOR_PERMISSIONS);
|
||||||
|
|
||||||
final Collection<FundData> funds = this.readPlatformService.retrieveAllFunds();
|
final Collection<FundData> funds = this.readPlatformService.retrieveAllFunds();
|
||||||
|
|
||||||
final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters());
|
final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters());
|
||||||
return this.toApiJsonSerializer.serialize(settings, funds, this.responseDataParameters);
|
return this.toApiJsonSerializer.serialize(settings, funds, RESPONSE_DATA_PARAMETERS);
|
||||||
}
|
}
|
||||||
|
|
||||||
@POST
|
@POST
|
||||||
@@ -128,12 +128,12 @@ public class FundsApiResource {
|
|||||||
@ApiResponse(responseCode = "200", description = "OK", content = @Content(schema = @Schema(implementation = FundsApiResourceSwagger.GetFundsResponse.class))) })
|
@ApiResponse(responseCode = "200", description = "OK", content = @Content(schema = @Schema(implementation = FundsApiResourceSwagger.GetFundsResponse.class))) })
|
||||||
public String retreiveFund(@PathParam("fundId") @Parameter(description = "fundId") final Long fundId, @Context final UriInfo uriInfo) {
|
public String retreiveFund(@PathParam("fundId") @Parameter(description = "fundId") final Long fundId, @Context final UriInfo uriInfo) {
|
||||||
|
|
||||||
this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions);
|
this.context.authenticatedUser().validateHasReadPermission(RESOURCE_NAME_FOR_PERMISSIONS);
|
||||||
|
|
||||||
final FundData fund = this.readPlatformService.retrieveFund(fundId);
|
final FundData fund = this.readPlatformService.retrieveFund(fundId);
|
||||||
|
|
||||||
final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters());
|
final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters());
|
||||||
return this.toApiJsonSerializer.serialize(settings, fund, this.responseDataParameters);
|
return this.toApiJsonSerializer.serialize(settings, fund, RESPONSE_DATA_PARAMETERS);
|
||||||
}
|
}
|
||||||
|
|
||||||
@PUT
|
@PUT
|
||||||
|
|||||||
+18
-15
@@ -39,10 +39,13 @@ import org.springframework.stereotype.Component;
|
|||||||
@Component
|
@Component
|
||||||
public final class FundCommandFromApiJsonDeserializer {
|
public final class FundCommandFromApiJsonDeserializer {
|
||||||
|
|
||||||
|
public static final String NAME = "name";
|
||||||
|
public static final String EXTERNAL_ID = "externalId";
|
||||||
/**
|
/**
|
||||||
* The parameters supported for this command.
|
* The parameters supported for this command.
|
||||||
*/
|
*/
|
||||||
private final Set<String> supportedParameters = new HashSet<>(Arrays.asList("name", "externalId"));
|
private static final Set<String> SUPPORTED_PARAMETERS = new HashSet<>(Arrays.asList(NAME, EXTERNAL_ID));
|
||||||
|
public static final String FUND = "fund";
|
||||||
|
|
||||||
private final FromJsonHelper fromApiJsonHelper;
|
private final FromJsonHelper fromApiJsonHelper;
|
||||||
|
|
||||||
@@ -57,18 +60,18 @@ public final class FundCommandFromApiJsonDeserializer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType();
|
final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType();
|
||||||
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParameters);
|
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, SUPPORTED_PARAMETERS);
|
||||||
|
|
||||||
final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
|
final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
|
||||||
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("fund");
|
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource(FUND);
|
||||||
|
|
||||||
final JsonElement element = this.fromApiJsonHelper.parse(json);
|
final JsonElement element = this.fromApiJsonHelper.parse(json);
|
||||||
|
|
||||||
final String name = this.fromApiJsonHelper.extractStringNamed("name", element);
|
final String name = this.fromApiJsonHelper.extractStringNamed(NAME, element);
|
||||||
baseDataValidator.reset().parameter("name").value(name).notBlank().notExceedingLengthOf(100);
|
baseDataValidator.reset().parameter(NAME).value(name).notBlank().notExceedingLengthOf(100);
|
||||||
|
|
||||||
final String externalId = this.fromApiJsonHelper.extractStringNamed("externalId", element);
|
final String externalId = this.fromApiJsonHelper.extractStringNamed(EXTERNAL_ID, element);
|
||||||
baseDataValidator.reset().parameter("externalId").value(externalId).notExceedingLengthOf(100);
|
baseDataValidator.reset().parameter(EXTERNAL_ID).value(externalId).notExceedingLengthOf(100);
|
||||||
|
|
||||||
throwExceptionIfValidationWarningsExist(dataValidationErrors);
|
throwExceptionIfValidationWarningsExist(dataValidationErrors);
|
||||||
}
|
}
|
||||||
@@ -79,20 +82,20 @@ public final class FundCommandFromApiJsonDeserializer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType();
|
final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType();
|
||||||
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParameters);
|
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, SUPPORTED_PARAMETERS);
|
||||||
|
|
||||||
final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
|
final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
|
||||||
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("fund");
|
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource(FUND);
|
||||||
|
|
||||||
final JsonElement element = this.fromApiJsonHelper.parse(json);
|
final JsonElement element = this.fromApiJsonHelper.parse(json);
|
||||||
if (this.fromApiJsonHelper.parameterExists("name", element)) {
|
if (this.fromApiJsonHelper.parameterExists(NAME, element)) {
|
||||||
final String name = this.fromApiJsonHelper.extractStringNamed("name", element);
|
final String name = this.fromApiJsonHelper.extractStringNamed(NAME, element);
|
||||||
baseDataValidator.reset().parameter("name").value(name).notBlank().notExceedingLengthOf(100);
|
baseDataValidator.reset().parameter(NAME).value(name).notBlank().notExceedingLengthOf(100);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (this.fromApiJsonHelper.parameterExists("externalId", element)) {
|
if (this.fromApiJsonHelper.parameterExists(EXTERNAL_ID, element)) {
|
||||||
final String externalId = this.fromApiJsonHelper.extractStringNamed("externalId", element);
|
final String externalId = this.fromApiJsonHelper.extractStringNamed(EXTERNAL_ID, element);
|
||||||
baseDataValidator.reset().parameter("externalId").value(externalId).notExceedingLengthOf(100);
|
baseDataValidator.reset().parameter(EXTERNAL_ID).value(externalId).notExceedingLengthOf(100);
|
||||||
}
|
}
|
||||||
|
|
||||||
throwExceptionIfValidationWarningsExist(dataValidationErrors);
|
throwExceptionIfValidationWarningsExist(dataValidationErrors);
|
||||||
|
|||||||
+36
-34
@@ -59,21 +59,23 @@ import org.springframework.util.CollectionUtils;
|
|||||||
@Service
|
@Service
|
||||||
public class GroupReadPlatformServiceImpl implements GroupReadPlatformService {
|
public class GroupReadPlatformServiceImpl implements GroupReadPlatformService {
|
||||||
|
|
||||||
|
public static final String ID = "id";
|
||||||
|
public static final String NAME = "name";
|
||||||
|
public static final String OFFICE_ID = "officeId";
|
||||||
|
public static final String OFFICE_NAME = "officeName";
|
||||||
|
private static final AllGroupTypesDataMapper ALL_GROUP_TYPES_DATA_MAPPER = new AllGroupTypesDataMapper();
|
||||||
|
private static final Set<String> SUPPORTED_ORDER_BY_VALUES = new HashSet<>(Arrays.asList(ID, NAME, OFFICE_ID, OFFICE_NAME));
|
||||||
private final JdbcTemplate jdbcTemplate;
|
private final JdbcTemplate jdbcTemplate;
|
||||||
private final PlatformSecurityContext context;
|
private final PlatformSecurityContext context;
|
||||||
private final OfficeReadPlatformService officeReadPlatformService;
|
private final OfficeReadPlatformService officeReadPlatformService;
|
||||||
private final StaffReadPlatformService staffReadPlatformService;
|
private final StaffReadPlatformService staffReadPlatformService;
|
||||||
private final CenterReadPlatformService centerReadPlatformService;
|
private final CenterReadPlatformService centerReadPlatformService;
|
||||||
private final CodeValueReadPlatformService codeValueReadPlatformService;
|
private final CodeValueReadPlatformService codeValueReadPlatformService;
|
||||||
|
|
||||||
private final AllGroupTypesDataMapper allGroupTypesDataMapper = new AllGroupTypesDataMapper();
|
|
||||||
private final PaginationHelper paginationHelper;
|
private final PaginationHelper paginationHelper;
|
||||||
private final DatabaseSpecificSQLGenerator sqlGenerator;
|
private final DatabaseSpecificSQLGenerator sqlGenerator;
|
||||||
private final PaginationParametersDataValidator paginationParametersDataValidator;
|
private final PaginationParametersDataValidator paginationParametersDataValidator;
|
||||||
private final ColumnValidator columnValidator;
|
private final ColumnValidator columnValidator;
|
||||||
|
|
||||||
private static final Set<String> supportedOrderByValues = new HashSet<>(Arrays.asList("id", "name", "officeId", "officeName"));
|
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
public GroupReadPlatformServiceImpl(final PlatformSecurityContext context, final JdbcTemplate jdbcTemplate,
|
public GroupReadPlatformServiceImpl(final PlatformSecurityContext context, final JdbcTemplate jdbcTemplate,
|
||||||
final CenterReadPlatformService centerReadPlatformService, final OfficeReadPlatformService officeReadPlatformService,
|
final CenterReadPlatformService centerReadPlatformService, final OfficeReadPlatformService officeReadPlatformService,
|
||||||
@@ -142,16 +144,16 @@ public class GroupReadPlatformServiceImpl implements GroupReadPlatformService {
|
|||||||
@Override
|
@Override
|
||||||
public Page<GroupGeneralData> retrievePagedAll(final SearchParameters searchParameters, final PaginationParameters parameters) {
|
public Page<GroupGeneralData> retrievePagedAll(final SearchParameters searchParameters, final PaginationParameters parameters) {
|
||||||
|
|
||||||
this.paginationParametersDataValidator.validateParameterValues(parameters, supportedOrderByValues, "audits");
|
this.paginationParametersDataValidator.validateParameterValues(parameters, SUPPORTED_ORDER_BY_VALUES, "audits");
|
||||||
final AppUser currentUser = this.context.authenticatedUser();
|
final AppUser currentUser = this.context.authenticatedUser();
|
||||||
final String hierarchy = currentUser.getOffice().getHierarchy();
|
final String hierarchy = currentUser.getOffice().getHierarchy();
|
||||||
final String hierarchySearchString = hierarchy + "%";
|
final String hierarchySearchString = hierarchy + "%";
|
||||||
|
|
||||||
final StringBuilder sqlBuilder = new StringBuilder(200);
|
final StringBuilder sqlBuilder = new StringBuilder(200);
|
||||||
sqlBuilder.append("select " + sqlGenerator.calcFoundRows() + " ");
|
sqlBuilder.append("select " + sqlGenerator.calcFoundRows() + " ");
|
||||||
sqlBuilder.append(this.allGroupTypesDataMapper.schema());
|
sqlBuilder.append(ALL_GROUP_TYPES_DATA_MAPPER.schema());
|
||||||
|
|
||||||
final SQLBuilder extraCriteria = getGroupExtraCriteria(this.allGroupTypesDataMapper.schema(), searchParameters);
|
final SQLBuilder extraCriteria = getGroupExtraCriteria(searchParameters);
|
||||||
extraCriteria.addCriteria(" o.hierarchy like ", hierarchySearchString);
|
extraCriteria.addCriteria(" o.hierarchy like ", hierarchySearchString);
|
||||||
sqlBuilder.append(" ").append(extraCriteria.getSQLTemplate());
|
sqlBuilder.append(" ").append(extraCriteria.getSQLTemplate());
|
||||||
if (parameters.isOrderByRequested()) {
|
if (parameters.isOrderByRequested()) {
|
||||||
@@ -168,7 +170,7 @@ public class GroupReadPlatformServiceImpl implements GroupReadPlatformService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
return this.paginationHelper.fetchPage(this.jdbcTemplate, sqlBuilder.toString(), extraCriteria.getArguments(),
|
return this.paginationHelper.fetchPage(this.jdbcTemplate, sqlBuilder.toString(), extraCriteria.getArguments(),
|
||||||
this.allGroupTypesDataMapper);
|
ALL_GROUP_TYPES_DATA_MAPPER);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@@ -179,16 +181,14 @@ public class GroupReadPlatformServiceImpl implements GroupReadPlatformService {
|
|||||||
|
|
||||||
final StringBuilder sqlBuilder = new StringBuilder(200);
|
final StringBuilder sqlBuilder = new StringBuilder(200);
|
||||||
sqlBuilder.append("select ");
|
sqlBuilder.append("select ");
|
||||||
sqlBuilder.append(this.allGroupTypesDataMapper.schema());
|
sqlBuilder.append(ALL_GROUP_TYPES_DATA_MAPPER.schema());
|
||||||
final SQLBuilder extraCriteria = getGroupExtraCriteria(this.allGroupTypesDataMapper.schema(), searchParameters);
|
final SQLBuilder extraCriteria = getGroupExtraCriteria(searchParameters);
|
||||||
extraCriteria.addCriteria("o.hierarchy like ", hierarchySearchString);
|
extraCriteria.addCriteria("o.hierarchy like ", hierarchySearchString);
|
||||||
|
|
||||||
sqlBuilder.append(" ").append(extraCriteria.getSQLTemplate());
|
sqlBuilder.append(" ").append(extraCriteria.getSQLTemplate());
|
||||||
|
|
||||||
if (searchParameters != null) {
|
if (searchParameters != null && searchParameters.isOrphansOnly()) {
|
||||||
if (searchParameters.isOrphansOnly()) {
|
sqlBuilder.append(" and g.parent_id is NULL");
|
||||||
sqlBuilder.append(" and g.parent_id is NULL");
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (parameters != null) {
|
if (parameters != null) {
|
||||||
@@ -203,13 +203,13 @@ public class GroupReadPlatformServiceImpl implements GroupReadPlatformService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return this.jdbcTemplate.query(sqlBuilder.toString(), this.allGroupTypesDataMapper, extraCriteria.getArguments()); // NOSONAR
|
return this.jdbcTemplate.query(sqlBuilder.toString(), ALL_GROUP_TYPES_DATA_MAPPER, extraCriteria.getArguments()); // NOSONAR
|
||||||
}
|
}
|
||||||
|
|
||||||
// 'g.' preffix because of ERROR 1052 (23000): Column 'column_name' in where
|
// 'g.' preffix because of ERROR 1052 (23000): Column 'column_name' in where
|
||||||
// clause is ambiguous
|
// clause is ambiguous
|
||||||
// caused by the same name of columns in m_office and m_group tables
|
// caused by the same name of columns in m_office and m_group tables
|
||||||
private SQLBuilder getGroupExtraCriteria(String schemaSql, final SearchParameters searchCriteria) {
|
private SQLBuilder getGroupExtraCriteria(final SearchParameters searchCriteria) {
|
||||||
|
|
||||||
SQLBuilder extraCriteria = new SQLBuilder();
|
SQLBuilder extraCriteria = new SQLBuilder();
|
||||||
if (searchCriteria == null) {
|
if (searchCriteria == null) {
|
||||||
@@ -243,8 +243,8 @@ public class GroupReadPlatformServiceImpl implements GroupReadPlatformService {
|
|||||||
final String hierarchy = currentUser.getOffice().getHierarchy();
|
final String hierarchy = currentUser.getOffice().getHierarchy();
|
||||||
final String hierarchySearchString = hierarchy + "%";
|
final String hierarchySearchString = hierarchy + "%";
|
||||||
|
|
||||||
final String sql = "select " + this.allGroupTypesDataMapper.schema() + " where g.id = ? and o.hierarchy like ?";
|
final String sql = "select " + ALL_GROUP_TYPES_DATA_MAPPER.schema() + " where g.id = ? and o.hierarchy like ?";
|
||||||
return this.jdbcTemplate.queryForObject(sql, this.allGroupTypesDataMapper, new Object[] { groupId, hierarchySearchString }); // NOSONAR
|
return this.jdbcTemplate.queryForObject(sql, ALL_GROUP_TYPES_DATA_MAPPER, groupId, hierarchySearchString); // NOSONAR
|
||||||
} catch (final EmptyResultDataAccessException e) {
|
} catch (final EmptyResultDataAccessException e) {
|
||||||
throw new GroupNotFoundException(groupId, e);
|
throw new GroupNotFoundException(groupId, e);
|
||||||
}
|
}
|
||||||
@@ -255,22 +255,7 @@ public class GroupReadPlatformServiceImpl implements GroupReadPlatformService {
|
|||||||
this.context.authenticatedUser();
|
this.context.authenticatedUser();
|
||||||
final GroupLookupDataMapper rm = new GroupLookupDataMapper();
|
final GroupLookupDataMapper rm = new GroupLookupDataMapper();
|
||||||
final String sql = "Select " + rm.schema() + " and g.office_id=?";
|
final String sql = "Select " + rm.schema() + " and g.office_id=?";
|
||||||
return this.jdbcTemplate.query(sql, rm, new Object[] { officeId }); // NOSONAR
|
return this.jdbcTemplate.query(sql, rm, officeId); // NOSONAR
|
||||||
}
|
|
||||||
|
|
||||||
private static final class GroupLookupDataMapper implements RowMapper<GroupGeneralData> {
|
|
||||||
|
|
||||||
public String schema() {
|
|
||||||
return "g.id as id, g.account_no as accountNo, g.display_name as displayName from m_group g where g.level_id = 2 ";
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public GroupGeneralData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) throws SQLException {
|
|
||||||
final Long id = JdbcSupport.getLong(rs, "id");
|
|
||||||
final String accountNo = rs.getString("accountNo");
|
|
||||||
final String displayName = rs.getString("displayName");
|
|
||||||
return GroupGeneralData.lookup(id, accountNo, displayName);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@@ -280,4 +265,21 @@ public class GroupReadPlatformServiceImpl implements GroupReadPlatformService {
|
|||||||
return GroupGeneralData.withClosureReasons(closureReasons);
|
return GroupGeneralData.withClosureReasons(closureReasons);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static final class GroupLookupDataMapper implements RowMapper<GroupGeneralData> {
|
||||||
|
|
||||||
|
public static final String G_ID_AS_ID_G_ACCOUNT_NO_AS_ACCOUNT_NO_G_DISPLAY_NAME_AS_DISPLAY_NAME_FROM_M_GROUP_G_WHERE_G_LEVEL_ID_2 = "g.id as id, g.account_no as accountNo, g.display_name as displayName from m_group g where g.level_id = 2 ";
|
||||||
|
|
||||||
|
public String schema() {
|
||||||
|
return G_ID_AS_ID_G_ACCOUNT_NO_AS_ACCOUNT_NO_G_DISPLAY_NAME_AS_DISPLAY_NAME_FROM_M_GROUP_G_WHERE_G_LEVEL_ID_2;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public GroupGeneralData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) throws SQLException {
|
||||||
|
final Long id = JdbcSupport.getLong(rs, ID);
|
||||||
|
final String accountNo = rs.getString("accountNo");
|
||||||
|
final String displayName = rs.getString("displayName");
|
||||||
|
return GroupGeneralData.lookup(id, accountNo, displayName);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
+1
-1
@@ -611,7 +611,7 @@ public class GroupingTypesWritePlatformServiceJpaRepositoryImpl implements Group
|
|||||||
private void validateLoansAndSavingsForGroupOrCenterClose(final Group groupOrCenter, final LocalDate closureDate) {
|
private void validateLoansAndSavingsForGroupOrCenterClose(final Group groupOrCenter, final LocalDate closureDate) {
|
||||||
final Collection<Loan> groupLoans = this.loanRepositoryWrapper.findByGroupId(groupOrCenter.getId());
|
final Collection<Loan> groupLoans = this.loanRepositoryWrapper.findByGroupId(groupOrCenter.getId());
|
||||||
for (final Loan loan : groupLoans) {
|
for (final Loan loan : groupLoans) {
|
||||||
final LoanStatusMapper loanStatus = new LoanStatusMapper(loan.status().getValue());
|
final LoanStatusMapper loanStatus = new LoanStatusMapper(loan.getStatus().getValue());
|
||||||
if (loanStatus.isOpen()) {
|
if (loanStatus.isOpen()) {
|
||||||
final String errorMessage = groupOrCenter.getGroupLevel().getLevelName() + " cannot be closed because of non-closed loans.";
|
final String errorMessage = groupOrCenter.getGroupLevel().getLevelName() + " cannot be closed because of non-closed loans.";
|
||||||
throw new InvalidGroupStateTransitionException(groupOrCenter.getGroupLevel().getLevelName(), "close", "loan.not.closed",
|
throw new InvalidGroupStateTransitionException(groupOrCenter.getGroupLevel().getLevelName(), "close", "loan.not.closed",
|
||||||
|
|||||||
+4
-6
@@ -53,12 +53,11 @@ public class InterestRateChartReadPlatformServiceImpl implements InterestRateCha
|
|||||||
|
|
||||||
private final PlatformSecurityContext context;
|
private final PlatformSecurityContext context;
|
||||||
private final JdbcTemplate jdbcTemplate;
|
private final JdbcTemplate jdbcTemplate;
|
||||||
private final InterestRateChartMapper chartRowMapper = new InterestRateChartMapper();
|
private static final InterestRateChartMapper CHART_ROW_MAPPER = new InterestRateChartMapper();
|
||||||
private final InterestRateChartExtractor chartExtractor;
|
private final InterestRateChartExtractor chartExtractor;
|
||||||
private final InterestRateChartDropdownReadPlatformService chartDropdownReadPlatformService;
|
private final InterestRateChartDropdownReadPlatformService chartDropdownReadPlatformService;
|
||||||
private final InterestIncentiveDropdownReadPlatformService interestIncentiveDropdownReadPlatformService;
|
private final InterestIncentiveDropdownReadPlatformService interestIncentiveDropdownReadPlatformService;
|
||||||
private final CodeValueReadPlatformService codeValueReadPlatformService;
|
private final CodeValueReadPlatformService codeValueReadPlatformService;
|
||||||
private final DatabaseSpecificSQLGenerator sqlGenerator;
|
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
public InterestRateChartReadPlatformServiceImpl(PlatformSecurityContext context, final JdbcTemplate jdbcTemplate,
|
public InterestRateChartReadPlatformServiceImpl(PlatformSecurityContext context, final JdbcTemplate jdbcTemplate,
|
||||||
@@ -70,16 +69,15 @@ public class InterestRateChartReadPlatformServiceImpl implements InterestRateCha
|
|||||||
this.chartDropdownReadPlatformService = chartDropdownReadPlatformService;
|
this.chartDropdownReadPlatformService = chartDropdownReadPlatformService;
|
||||||
this.interestIncentiveDropdownReadPlatformService = interestIncentiveDropdownReadPlatformService;
|
this.interestIncentiveDropdownReadPlatformService = interestIncentiveDropdownReadPlatformService;
|
||||||
this.codeValueReadPlatformService = codeValueReadPlatformService;
|
this.codeValueReadPlatformService = codeValueReadPlatformService;
|
||||||
this.sqlGenerator = sqlGenerator;
|
chartExtractor = new InterestRateChartExtractor(sqlGenerator);
|
||||||
chartExtractor = new InterestRateChartExtractor(this.sqlGenerator);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public InterestRateChartData retrieveOne(Long chartId) {
|
public InterestRateChartData retrieveOne(Long chartId) {
|
||||||
try {
|
try {
|
||||||
this.context.authenticatedUser();
|
this.context.authenticatedUser();
|
||||||
final String sql = "select " + this.chartRowMapper.schema() + " where irc.id = ?";
|
final String sql = "select " + CHART_ROW_MAPPER.schema() + " where irc.id = ?";
|
||||||
return this.jdbcTemplate.queryForObject(sql, this.chartRowMapper, new Object[] { chartId }); // NOSONAR
|
return this.jdbcTemplate.queryForObject(sql, CHART_ROW_MAPPER, chartId); // NOSONAR
|
||||||
} catch (final EmptyResultDataAccessException e) {
|
} catch (final EmptyResultDataAccessException e) {
|
||||||
throw new InterestRateChartNotFoundException(chartId, e);
|
throw new InterestRateChartNotFoundException(chartId, e);
|
||||||
}
|
}
|
||||||
|
|||||||
+13
-7
@@ -59,10 +59,16 @@ import org.springframework.stereotype.Component;
|
|||||||
@Tag(name = "Bulk Loans", description = "")
|
@Tag(name = "Bulk Loans", description = "")
|
||||||
public class BulkLoansApiResource {
|
public class BulkLoansApiResource {
|
||||||
|
|
||||||
private final Set<String> responseDataParameters = new HashSet<>(Arrays.asList("officeId", "fromLoanOfficerId", "assignmentDate",
|
public static final String OFFICE_ID = "officeId";
|
||||||
"officeOptions", "loanOfficerOptions", "accountSummaryCollection"));
|
public static final String FROM_LOAN_OFFICER_ID = "fromLoanOfficerId";
|
||||||
|
public static final String ASSIGNMENT_DATE = "assignmentDate";
|
||||||
|
public static final String OFFICE_OPTIONS = "officeOptions";
|
||||||
|
public static final String LOAN_OFFICER_OPTIONS = "loanOfficerOptions";
|
||||||
|
public static final String ACCOUNT_SUMMARY_COLLECTION = "accountSummaryCollection";
|
||||||
|
private static final Set<String> RESPONSE_DATA_PARAMETERS = new HashSet<>(Arrays.asList(OFFICE_ID, FROM_LOAN_OFFICER_ID,
|
||||||
|
ASSIGNMENT_DATE, OFFICE_OPTIONS, LOAN_OFFICER_OPTIONS, ACCOUNT_SUMMARY_COLLECTION));
|
||||||
|
|
||||||
private final String resourceNameForPermissions = "LOAN";
|
private static final String RESOURCE_NAME_FOR_PERMISSIONS = "LOAN";
|
||||||
|
|
||||||
private final PlatformSecurityContext context;
|
private final PlatformSecurityContext context;
|
||||||
private final StaffReadPlatformService staffReadPlatformService;
|
private final StaffReadPlatformService staffReadPlatformService;
|
||||||
@@ -91,10 +97,10 @@ public class BulkLoansApiResource {
|
|||||||
@Path("template")
|
@Path("template")
|
||||||
@Consumes({ MediaType.APPLICATION_JSON })
|
@Consumes({ MediaType.APPLICATION_JSON })
|
||||||
@Produces({ MediaType.APPLICATION_JSON })
|
@Produces({ MediaType.APPLICATION_JSON })
|
||||||
public String loanReassignmentTemplate(@QueryParam("officeId") final Long officeId,
|
public String loanReassignmentTemplate(@QueryParam(OFFICE_ID) final Long officeId,
|
||||||
@QueryParam("fromLoanOfficerId") final Long loanOfficerId, @Context final UriInfo uriInfo) {
|
@QueryParam(FROM_LOAN_OFFICER_ID) final Long loanOfficerId, @Context final UriInfo uriInfo) {
|
||||||
|
|
||||||
this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions);
|
this.context.authenticatedUser().validateHasReadPermission(RESOURCE_NAME_FOR_PERMISSIONS);
|
||||||
|
|
||||||
final Collection<OfficeData> offices = this.officeReadPlatformService.retrieveAllOfficesForDropdown();
|
final Collection<OfficeData> offices = this.officeReadPlatformService.retrieveAllOfficesForDropdown();
|
||||||
|
|
||||||
@@ -113,7 +119,7 @@ public class BulkLoansApiResource {
|
|||||||
LocalDate.now(DateUtils.getDateTimeZoneOfTenant()), offices, loanOfficers, staffAccountSummaryCollectionData);
|
LocalDate.now(DateUtils.getDateTimeZoneOfTenant()), offices, loanOfficers, staffAccountSummaryCollectionData);
|
||||||
|
|
||||||
final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters());
|
final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters());
|
||||||
return this.toApiJsonSerializer.serialize(settings, loanReassignmentData, this.responseDataParameters);
|
return this.toApiJsonSerializer.serialize(settings, loanReassignmentData, RESPONSE_DATA_PARAMETERS);
|
||||||
}
|
}
|
||||||
|
|
||||||
@POST
|
@POST
|
||||||
|
|||||||
+11
-2
@@ -23,14 +23,19 @@ public interface LoanApiConstants {
|
|||||||
String emiAmountParameterName = "fixedEmiAmount";
|
String emiAmountParameterName = "fixedEmiAmount";
|
||||||
String maxOutstandingBalanceParameterName = "maxOutstandingLoanBalance";
|
String maxOutstandingBalanceParameterName = "maxOutstandingLoanBalance";
|
||||||
String disbursementDataParameterName = "disbursementData";
|
String disbursementDataParameterName = "disbursementData";
|
||||||
String disbursementDateParameterName = "expectedDisbursementDate";
|
String expectedDisbursementDateParameterName = "expectedDisbursementDate";
|
||||||
String disbursementPrincipalParameterName = "principal";
|
String disbursementPrincipalParameterName = "principal";
|
||||||
|
String principalParameterName = "principal";
|
||||||
String disbursementReversedParameterName = "reversed";
|
String disbursementReversedParameterName = "reversed";
|
||||||
String disbursementNetDisbursalAmountParameterName = "netDisbursalAmount";
|
String disbursementNetDisbursalAmountParameterName = "netDisbursalAmount";
|
||||||
String updatedDisbursementDateParameterName = "updatedExpectedDisbursementDate";
|
String updatedDisbursementDateParameterName = "updatedExpectedDisbursementDate";
|
||||||
String updatedDisbursementPrincipalParameterName = "updatedPrincipal";
|
String updatedDisbursementPrincipalParameterName = "updatedPrincipal";
|
||||||
String disbursementIdParameterName = "id";
|
String disbursementIdParameterName = "id";
|
||||||
String loanChargeIdParameterName = "loanChargeId";
|
String loanChargeIdParameterName = "loanChargeId";
|
||||||
|
String chargeIdParameterName = "chargeId";
|
||||||
|
String amountParameterName = "amount";
|
||||||
|
String chargeTimeTypeParameterName = "chargeTimeType";
|
||||||
|
String chargeCalculationTypeParameterName = "chargeCalculationType";
|
||||||
String principalDisbursedParameterName = "transactionAmount";
|
String principalDisbursedParameterName = "transactionAmount";
|
||||||
String chargesParameterName = "charges";
|
String chargesParameterName = "charges";
|
||||||
String loanIdTobeApproved = "loanId";
|
String loanIdTobeApproved = "loanId";
|
||||||
@@ -73,8 +78,12 @@ public interface LoanApiConstants {
|
|||||||
String inArrearsToleranceParameterName = "inArrearsTolerance";
|
String inArrearsToleranceParameterName = "inArrearsTolerance";
|
||||||
String interestChargedFromDateParameterName = "interestChargedFromDate";
|
String interestChargedFromDateParameterName = "interestChargedFromDate";
|
||||||
String submittedOnDateParameterName = "submittedOnDate";
|
String submittedOnDateParameterName = "submittedOnDate";
|
||||||
String submittedOnNoteParameterName = "interestChargedFromDate";
|
String submittedOnNoteParameterName = "submittedOnNote";
|
||||||
String collateralParameterName = "collateral";
|
String collateralParameterName = "collateral";
|
||||||
|
String collateralsParameterName = "collaterals";
|
||||||
|
String clientCollateralIdParameterName = "clientCollateralId";
|
||||||
|
|
||||||
|
String quantityParameterName = "quantity";
|
||||||
String syncDisbursementWithMeetingParameterName = "syncDisbursementWithMeeting";
|
String syncDisbursementWithMeetingParameterName = "syncDisbursementWithMeeting";
|
||||||
String linkAccountIdParameterName = "linkAccountId";
|
String linkAccountIdParameterName = "linkAccountId";
|
||||||
String createStandingInstructionAtDisbursementParameterName = "createStandingInstructionAtDisbursement";
|
String createStandingInstructionAtDisbursementParameterName = "createStandingInstructionAtDisbursement";
|
||||||
|
|||||||
+8
-8
@@ -71,12 +71,12 @@ import org.springframework.stereotype.Component;
|
|||||||
+ "Loan Charges are instances of Charges and represent either fees and penalties for loan products. Refer Charges for documentation of the various properties of a charge, Only additional properties ( specific to the context of a Charge being associated with a Loan) are described here")
|
+ "Loan Charges are instances of Charges and represent either fees and penalties for loan products. Refer Charges for documentation of the various properties of a charge, Only additional properties ( specific to the context of a Charge being associated with a Loan) are described here")
|
||||||
public class LoanChargesApiResource {
|
public class LoanChargesApiResource {
|
||||||
|
|
||||||
private final Set<String> responseDataParameters = new HashSet<>(
|
private static final Set<String> RESPONSE_DATA_PARAMETERS = new HashSet<>(
|
||||||
Arrays.asList("id", "chargeId", "name", "penalty", "chargeTimeType", "dueAsOfDate", "chargeCalculationType", "percentage",
|
Arrays.asList("id", "chargeId", "name", "penalty", "chargeTimeType", "dueAsOfDate", "chargeCalculationType", "percentage",
|
||||||
"amountPercentageAppliedTo", "currency", "amountWaived", "amountWrittenOff", "amountOutstanding", "amountOrPercentage",
|
"amountPercentageAppliedTo", "currency", "amountWaived", "amountWrittenOff", "amountOutstanding", "amountOrPercentage",
|
||||||
"amount", "amountPaid", "chargeOptions", "installmentChargeData"));
|
"amount", "amountPaid", "chargeOptions", "installmentChargeData"));
|
||||||
|
|
||||||
private final String resourceNameForPermissions = "LOAN";
|
private static final String RESOURCE_NAME_FOR_PERMISSIONS = "LOAN";
|
||||||
|
|
||||||
private final PlatformSecurityContext context;
|
private final PlatformSecurityContext context;
|
||||||
private final ChargeReadPlatformService chargeReadPlatformService;
|
private final ChargeReadPlatformService chargeReadPlatformService;
|
||||||
@@ -112,12 +112,12 @@ public class LoanChargesApiResource {
|
|||||||
public String retrieveAllLoanCharges(@PathParam("loanId") @Parameter(description = "loanId") final Long loanId,
|
public String retrieveAllLoanCharges(@PathParam("loanId") @Parameter(description = "loanId") final Long loanId,
|
||||||
@Context final UriInfo uriInfo) {
|
@Context final UriInfo uriInfo) {
|
||||||
|
|
||||||
this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions);
|
this.context.authenticatedUser().validateHasReadPermission(RESOURCE_NAME_FOR_PERMISSIONS);
|
||||||
|
|
||||||
final Collection<LoanChargeData> loanCharges = this.loanChargeReadPlatformService.retrieveLoanCharges(loanId);
|
final Collection<LoanChargeData> loanCharges = this.loanChargeReadPlatformService.retrieveLoanCharges(loanId);
|
||||||
|
|
||||||
final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters());
|
final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters());
|
||||||
return this.toApiJsonSerializer.serialize(settings, loanCharges, this.responseDataParameters);
|
return this.toApiJsonSerializer.serialize(settings, loanCharges, RESPONSE_DATA_PARAMETERS);
|
||||||
}
|
}
|
||||||
|
|
||||||
@GET
|
@GET
|
||||||
@@ -131,14 +131,14 @@ public class LoanChargesApiResource {
|
|||||||
public String retrieveTemplate(@PathParam("loanId") @Parameter(description = "loanId") final Long loanId,
|
public String retrieveTemplate(@PathParam("loanId") @Parameter(description = "loanId") final Long loanId,
|
||||||
@Context final UriInfo uriInfo) {
|
@Context final UriInfo uriInfo) {
|
||||||
|
|
||||||
this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions);
|
this.context.authenticatedUser().validateHasReadPermission(RESOURCE_NAME_FOR_PERMISSIONS);
|
||||||
|
|
||||||
final Collection<ChargeData> chargeOptions = this.chargeReadPlatformService.retrieveLoanAccountApplicableCharges(loanId,
|
final Collection<ChargeData> chargeOptions = this.chargeReadPlatformService.retrieveLoanAccountApplicableCharges(loanId,
|
||||||
new ChargeTimeType[] { ChargeTimeType.OVERDUE_INSTALLMENT });
|
new ChargeTimeType[] { ChargeTimeType.OVERDUE_INSTALLMENT });
|
||||||
final LoanChargeData loanChargeTemplate = LoanChargeData.template(chargeOptions);
|
final LoanChargeData loanChargeTemplate = LoanChargeData.template(chargeOptions);
|
||||||
|
|
||||||
final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters());
|
final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters());
|
||||||
return this.toApiJsonSerializer.serialize(settings, loanChargeTemplate, this.responseDataParameters);
|
return this.toApiJsonSerializer.serialize(settings, loanChargeTemplate, RESPONSE_DATA_PARAMETERS);
|
||||||
}
|
}
|
||||||
|
|
||||||
@GET
|
@GET
|
||||||
@@ -152,7 +152,7 @@ public class LoanChargesApiResource {
|
|||||||
public String retrieveLoanCharge(@PathParam("loanId") @Parameter(description = "loanId") final Long loanId,
|
public String retrieveLoanCharge(@PathParam("loanId") @Parameter(description = "loanId") final Long loanId,
|
||||||
@PathParam("chargeId") @Parameter(description = "chargeId") final Long loanChargeId, @Context final UriInfo uriInfo) {
|
@PathParam("chargeId") @Parameter(description = "chargeId") final Long loanChargeId, @Context final UriInfo uriInfo) {
|
||||||
|
|
||||||
this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions);
|
this.context.authenticatedUser().validateHasReadPermission(RESOURCE_NAME_FOR_PERMISSIONS);
|
||||||
|
|
||||||
final LoanChargeData loanCharge = this.loanChargeReadPlatformService.retrieveLoanChargeDetails(loanChargeId, loanId);
|
final LoanChargeData loanCharge = this.loanChargeReadPlatformService.retrieveLoanChargeDetails(loanChargeId, loanId);
|
||||||
|
|
||||||
@@ -162,7 +162,7 @@ public class LoanChargesApiResource {
|
|||||||
final LoanChargeData loanChargeData = new LoanChargeData(loanCharge, installmentChargeData);
|
final LoanChargeData loanChargeData = new LoanChargeData(loanCharge, installmentChargeData);
|
||||||
|
|
||||||
final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters());
|
final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters());
|
||||||
return this.toApiJsonSerializer.serialize(settings, loanChargeData, this.responseDataParameters);
|
return this.toApiJsonSerializer.serialize(settings, loanChargeData, RESPONSE_DATA_PARAMETERS);
|
||||||
}
|
}
|
||||||
|
|
||||||
@POST
|
@POST
|
||||||
|
|||||||
+4
-4
@@ -51,10 +51,10 @@ import org.springframework.stereotype.Component;
|
|||||||
@Tag(name = "Loan Disbursement Details", description = "")
|
@Tag(name = "Loan Disbursement Details", description = "")
|
||||||
public class LoanDisbursementDetailApiResource {
|
public class LoanDisbursementDetailApiResource {
|
||||||
|
|
||||||
private final Set<String> responseDataParameters = new HashSet<>(
|
private static final Set<String> RESPONSE_DATA_PARAMETERS = new HashSet<>(
|
||||||
Arrays.asList("id", "expectedDisbursementDate", "actualDisbursementDate", "principal", "approvedPrincipal"));
|
Arrays.asList("id", "expectedDisbursementDate", "actualDisbursementDate", "principal", "approvedPrincipal"));
|
||||||
|
|
||||||
private final String resourceNameForPermissions = "LOAN";
|
private static final String RESOURCE_NAME_FOR_PERMISSIONS = "LOAN";
|
||||||
|
|
||||||
private final DefaultToApiJsonSerializer<DisbursementData> toApiJsonSerializer;
|
private final DefaultToApiJsonSerializer<DisbursementData> toApiJsonSerializer;
|
||||||
private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService;
|
private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService;
|
||||||
@@ -109,12 +109,12 @@ public class LoanDisbursementDetailApiResource {
|
|||||||
public String retriveDetail(@PathParam("loanId") final Long loanId, @PathParam("disbursementId") final Long disbursementId,
|
public String retriveDetail(@PathParam("loanId") final Long loanId, @PathParam("disbursementId") final Long disbursementId,
|
||||||
@Context final UriInfo uriInfo) {
|
@Context final UriInfo uriInfo) {
|
||||||
|
|
||||||
this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions);
|
this.context.authenticatedUser().validateHasReadPermission(RESOURCE_NAME_FOR_PERMISSIONS);
|
||||||
|
|
||||||
final DisbursementData disbursementData = this.loanReadPlatformService.retrieveLoanDisbursementDetail(loanId, disbursementId);
|
final DisbursementData disbursementData = this.loanReadPlatformService.retrieveLoanDisbursementDetail(loanId, disbursementId);
|
||||||
|
|
||||||
final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters());
|
final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters());
|
||||||
return this.toApiJsonSerializer.serialize(settings, disbursementData, this.responseDataParameters);
|
return this.toApiJsonSerializer.serialize(settings, disbursementData, RESPONSE_DATA_PARAMETERS);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
+3
-3
@@ -57,7 +57,7 @@ import org.springframework.stereotype.Component;
|
|||||||
@Tag(name = "Loan Rescheduling", description = "Loan Term Variations provides the ability to change due dates, amounts and number of instalments before loan approval.")
|
@Tag(name = "Loan Rescheduling", description = "Loan Term Variations provides the ability to change due dates, amounts and number of instalments before loan approval.")
|
||||||
public class LoanScheduleApiResource {
|
public class LoanScheduleApiResource {
|
||||||
|
|
||||||
private final String resourceNameForPermissions = "LOAN";
|
private static final String RESOURCE_NAME_FOR_PERMISSIONS = "LOAN";
|
||||||
private final PlatformSecurityContext context;
|
private final PlatformSecurityContext context;
|
||||||
private final DefaultToApiJsonSerializer<LoanScheduleData> toApiJsonSerializer;
|
private final DefaultToApiJsonSerializer<LoanScheduleData> toApiJsonSerializer;
|
||||||
private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService;
|
private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService;
|
||||||
@@ -94,12 +94,12 @@ public class LoanScheduleApiResource {
|
|||||||
|
|
||||||
CommandWrapper commandRequest = null;
|
CommandWrapper commandRequest = null;
|
||||||
if (is(commandParam, "calculateLoanSchedule")) {
|
if (is(commandParam, "calculateLoanSchedule")) {
|
||||||
this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions);
|
this.context.authenticatedUser().validateHasReadPermission(RESOURCE_NAME_FOR_PERMISSIONS);
|
||||||
final LoanScheduleData loanSchedule = this.calculationPlatformService.generateLoanScheduleForVariableInstallmentRequest(loanId,
|
final LoanScheduleData loanSchedule = this.calculationPlatformService.generateLoanScheduleForVariableInstallmentRequest(loanId,
|
||||||
apiRequestBodyAsJson);
|
apiRequestBodyAsJson);
|
||||||
|
|
||||||
final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters());
|
final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters());
|
||||||
return this.toApiJsonSerializer.serialize(settings, loanSchedule, new HashSet<String>());
|
return this.toApiJsonSerializer.serialize(settings, loanSchedule, new HashSet<>());
|
||||||
} else if (is(commandParam, "addVariations")) {
|
} else if (is(commandParam, "addVariations")) {
|
||||||
commandRequest = new CommandWrapperBuilder().createScheduleExceptions(loanId).withJson(apiRequestBodyAsJson).build();
|
commandRequest = new CommandWrapperBuilder().createScheduleExceptions(loanId).withJson(apiRequestBodyAsJson).build();
|
||||||
} else if (is(commandParam, "deleteVariations")) {
|
} else if (is(commandParam, "deleteVariations")) {
|
||||||
|
|||||||
+2
-2
@@ -38,7 +38,7 @@ public class DefaultLoanLifecycleStateMachine implements LoanLifecycleStateMachi
|
|||||||
@Override
|
@Override
|
||||||
public LoanStatus dryTransition(final LoanEvent loanEvent, final Loan loan) {
|
public LoanStatus dryTransition(final LoanEvent loanEvent, final Loan loan) {
|
||||||
LoanStatus nextStatus = getNextState(loanEvent, loan);
|
LoanStatus nextStatus = getNextState(loanEvent, loan);
|
||||||
return nextStatus != null ? nextStatus : loan.status();
|
return nextStatus != null ? nextStatus : loan.getStatus();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@@ -64,7 +64,7 @@ public class DefaultLoanLifecycleStateMachine implements LoanLifecycleStateMachi
|
|||||||
return submittedTransition();
|
return submittedTransition();
|
||||||
}
|
}
|
||||||
|
|
||||||
LoanStatus from = loan.status();
|
LoanStatus from = loan.getStatus();
|
||||||
LoanStatus newState = null;
|
LoanStatus newState = null;
|
||||||
|
|
||||||
switch (loanEvent) {
|
switch (loanEvent) {
|
||||||
|
|||||||
+360
-398
File diff suppressed because it is too large
Load Diff
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user