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
|
||||
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.
|
||||
*/
|
||||
private final Set<String> supportedParameters = new HashSet<>(
|
||||
Arrays.asList("name", "query", "tableName", "tableFields", "email", "isActive", "reportRunFrequency", "reportRunEvery"));
|
||||
private static final Set<String> supportedParameters = new HashSet<>(
|
||||
Arrays.asList(NAME, QUERY, TABLE_NAME, TABLE_FIELDS, EMAIL, "isActive", REPORT_RUN_FREQUENCY, REPORT_RUN_EVERY));
|
||||
|
||||
private final FromJsonHelper fromApiJsonHelper;
|
||||
|
||||
@@ -59,37 +66,37 @@ public final class AdHocDataValidator {
|
||||
}
|
||||
|
||||
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 DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("adhoc");
|
||||
|
||||
final JsonElement element = this.fromApiJsonHelper.parse(json);
|
||||
|
||||
final String name = this.fromApiJsonHelper.extractStringNamed("name", element);
|
||||
baseDataValidator.reset().parameter("name").value(name).notBlank().notExceedingLengthOf(100);
|
||||
final String name = this.fromApiJsonHelper.extractStringNamed(NAME, element);
|
||||
baseDataValidator.reset().parameter(NAME).value(name).notBlank().notExceedingLengthOf(100);
|
||||
|
||||
final String description = this.fromApiJsonHelper.extractStringNamed("query", element);
|
||||
baseDataValidator.reset().parameter("query").value(description).notBlank().notExceedingLengthOf(2000);
|
||||
final String description = this.fromApiJsonHelper.extractStringNamed(QUERY, element);
|
||||
baseDataValidator.reset().parameter(QUERY).value(description).notBlank().notExceedingLengthOf(2000);
|
||||
|
||||
final String tableName = this.fromApiJsonHelper.extractStringNamed("tableName", element);
|
||||
baseDataValidator.reset().parameter("tableName").value(tableName).notBlank().notExceedingLengthOf(100);
|
||||
final String tableName = this.fromApiJsonHelper.extractStringNamed(TABLE_NAME, element);
|
||||
baseDataValidator.reset().parameter(TABLE_NAME).value(tableName).notBlank().notExceedingLengthOf(100);
|
||||
|
||||
final String tableFields = this.fromApiJsonHelper.extractStringNamed("tableFields", element);
|
||||
baseDataValidator.reset().parameter("tableFields").value(tableFields).notBlank().notExceedingLengthOf(1000);
|
||||
final String tableFields = this.fromApiJsonHelper.extractStringNamed(TABLE_FIELDS, element);
|
||||
baseDataValidator.reset().parameter(TABLE_FIELDS).value(tableFields).notBlank().notExceedingLengthOf(1000);
|
||||
|
||||
final String email = this.fromApiJsonHelper.extractStringNamed("email", element);
|
||||
baseDataValidator.reset().parameter("email").value(email).ignoreIfNull().notExceedingLengthOf(500);
|
||||
final String email = this.fromApiJsonHelper.extractStringNamed(EMAIL, element);
|
||||
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) {
|
||||
baseDataValidator.reset().parameter("reportRunFrequency").value(reportRunFrequencyCode)
|
||||
baseDataValidator.reset().parameter(REPORT_RUN_FREQUENCY).value(reportRunFrequencyCode)
|
||||
.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) {
|
||||
baseDataValidator.reset().parameter("reportRunEvery").value(reportRunFrequencyCode).integerGreaterThanZero();
|
||||
baseDataValidator.reset().parameter(REPORT_RUN_EVERY).value(reportRunFrequencyCode).integerGreaterThanZero();
|
||||
}
|
||||
|
||||
throwExceptionIfValidationWarningsExist(dataValidationErrors);
|
||||
@@ -101,42 +108,42 @@ public final class AdHocDataValidator {
|
||||
}
|
||||
|
||||
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 DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("adhoc");
|
||||
|
||||
final JsonElement element = this.fromApiJsonHelper.parse(json);
|
||||
|
||||
if (this.fromApiJsonHelper.parameterExists("name", element)) {
|
||||
final String name = this.fromApiJsonHelper.extractStringNamed("name", element);
|
||||
baseDataValidator.reset().parameter("name").value(name).notBlank().notExceedingLengthOf(100);
|
||||
if (this.fromApiJsonHelper.parameterExists(NAME, element)) {
|
||||
final String name = this.fromApiJsonHelper.extractStringNamed(NAME, element);
|
||||
baseDataValidator.reset().parameter(NAME).value(name).notBlank().notExceedingLengthOf(100);
|
||||
}
|
||||
|
||||
if (this.fromApiJsonHelper.parameterExists("query", element)) {
|
||||
final String query = this.fromApiJsonHelper.extractStringNamed("query", element);
|
||||
baseDataValidator.reset().parameter("query").value(query).notBlank().notExceedingLengthOf(2000);
|
||||
if (this.fromApiJsonHelper.parameterExists(QUERY, element)) {
|
||||
final String query = this.fromApiJsonHelper.extractStringNamed(QUERY, element);
|
||||
baseDataValidator.reset().parameter(QUERY).value(query).notBlank().notExceedingLengthOf(2000);
|
||||
}
|
||||
if (this.fromApiJsonHelper.parameterExists("tableName", element)) {
|
||||
final String tableName = this.fromApiJsonHelper.extractStringNamed("tableName", element);
|
||||
baseDataValidator.reset().parameter("tableName").value(tableName).notBlank().notExceedingLengthOf(100);
|
||||
if (this.fromApiJsonHelper.parameterExists(TABLE_NAME, element)) {
|
||||
final String tableName = this.fromApiJsonHelper.extractStringNamed(TABLE_NAME, element);
|
||||
baseDataValidator.reset().parameter(TABLE_NAME).value(tableName).notBlank().notExceedingLengthOf(100);
|
||||
}
|
||||
if (this.fromApiJsonHelper.parameterExists("tableFields", element)) {
|
||||
final String tableField = this.fromApiJsonHelper.extractStringNamed("tableFields", element);
|
||||
baseDataValidator.reset().parameter("tableFields").value(tableField).notBlank().notExceedingLengthOf(2000);
|
||||
if (this.fromApiJsonHelper.parameterExists(TABLE_FIELDS, element)) {
|
||||
final String tableField = this.fromApiJsonHelper.extractStringNamed(TABLE_FIELDS, element);
|
||||
baseDataValidator.reset().parameter(TABLE_FIELDS).value(tableField).notBlank().notExceedingLengthOf(2000);
|
||||
}
|
||||
if (this.fromApiJsonHelper.parameterExists("email", element)) {
|
||||
final String email = this.fromApiJsonHelper.extractStringNamed("email", element);
|
||||
baseDataValidator.reset().parameter("email").value(email).ignoreIfNull().notExceedingLengthOf(500);
|
||||
if (this.fromApiJsonHelper.parameterExists(EMAIL, element)) {
|
||||
final String email = this.fromApiJsonHelper.extractStringNamed(EMAIL, element);
|
||||
baseDataValidator.reset().parameter(EMAIL).value(email).ignoreIfNull().notExceedingLengthOf(500);
|
||||
}
|
||||
if (this.fromApiJsonHelper.parameterExists("reportRunFrequency", element)) {
|
||||
final Long reportRunFrequencyCode = this.fromApiJsonHelper.extractLongNamed("reportRunFrequency", element);
|
||||
baseDataValidator.reset().parameter("reportRunFrequency").value(reportRunFrequencyCode)
|
||||
if (this.fromApiJsonHelper.parameterExists(REPORT_RUN_FREQUENCY, element)) {
|
||||
final Long reportRunFrequencyCode = this.fromApiJsonHelper.extractLongNamed(REPORT_RUN_FREQUENCY, element);
|
||||
baseDataValidator.reset().parameter(REPORT_RUN_FREQUENCY).value(reportRunFrequencyCode)
|
||||
.inMinMaxRange((int) ReportRunFrequency.DAILY.getValue(), (int) ReportRunFrequency.CUSTOM.getValue());
|
||||
}
|
||||
if (this.fromApiJsonHelper.parameterExists("reportRunEvery", element)) {
|
||||
final Long reportRunEvery = this.fromApiJsonHelper.extractLongNamed("reportRunEvery", element);
|
||||
baseDataValidator.reset().parameter("reportRunEvery").value(reportRunEvery).integerGreaterThanZero();
|
||||
if (this.fromApiJsonHelper.parameterExists(REPORT_RUN_EVERY, element)) {
|
||||
final Long reportRunEvery = this.fromApiJsonHelper.extractLongNamed(REPORT_RUN_EVERY, element);
|
||||
baseDataValidator.reset().parameter(REPORT_RUN_EVERY).value(reportRunEvery).integerGreaterThanZero();
|
||||
}
|
||||
/*
|
||||
* if (this.fromApiJsonHelper.parameterExists("isActive", element)) { final Integer isActive =
|
||||
|
||||
+35
-37
@@ -35,8 +35,9 @@ import org.springframework.stereotype.Component;
|
||||
@Component
|
||||
public class CommandStrategyProvider {
|
||||
|
||||
public static final String CREATE_TRANSACTION_LOAN_COMMAND_STRATEGY = "createTransactionLoanCommandStrategy";
|
||||
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
|
||||
@@ -63,13 +64,13 @@ public class CommandStrategyProvider {
|
||||
*/
|
||||
public CommandStrategy getCommandStrategy(final CommandContext commandContext) {
|
||||
|
||||
if (this.commandStrategies.containsKey(commandContext)) {
|
||||
return (CommandStrategy) this.applicationContext.getBean(this.commandStrategies.get(commandContext));
|
||||
if (commandStrategies.containsKey(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())) {
|
||||
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
|
||||
* command Strategy will have to be added within this function in order to initiate it within the constructor.
|
||||
*/
|
||||
private void init() {
|
||||
this.commandStrategies.put(CommandContext.resource("clients").method("POST").build(), "createClientCommandStrategy");
|
||||
this.commandStrategies.put(CommandContext.resource("clients\\/\\d+").method("PUT").build(), "updateClientCommandStrategy");
|
||||
this.commandStrategies.put(CommandContext.resource("loans").method("POST").build(), "applyLoanCommandStrategy");
|
||||
this.commandStrategies.put(CommandContext.resource("loans\\/\\d+").method("GET").build(), "getLoanByIdCommandStrategy");
|
||||
this.commandStrategies.put(CommandContext.resource("loans/\\d+(\\?(\\w+(?:\\=[\\w,]+|&)+)+)").method("GET").build(),
|
||||
private static void init() {
|
||||
commandStrategies.put(CommandContext.resource("clients").method("POST").build(), "createClientCommandStrategy");
|
||||
commandStrategies.put(CommandContext.resource("clients\\/\\d+").method("PUT").build(), "updateClientCommandStrategy");
|
||||
commandStrategies.put(CommandContext.resource("loans").method("POST").build(), "applyLoanCommandStrategy");
|
||||
commandStrategies.put(CommandContext.resource("loans\\/\\d+").method("GET").build(), "getLoanByIdCommandStrategy");
|
||||
commandStrategies.put(CommandContext.resource("loans/\\d+(\\?(\\w+(?:\\=[\\w,]+|&)+)+)").method("GET").build(),
|
||||
"getLoanByIdCommandStrategy");
|
||||
this.commandStrategies.put(CommandContext.resource("savingsaccounts").method("POST").build(), "applySavingsCommandStrategy");
|
||||
this.commandStrategies.put(CommandContext.resource("loans\\/\\d+\\/charges").method("POST").build(), "createChargeCommandStrategy");
|
||||
this.commandStrategies.put(CommandContext.resource("loans\\/\\d+\\/charges").method("GET").build(),
|
||||
"collectChargesCommandStrategy");
|
||||
this.commandStrategies.put(CommandContext.resource("loans\\/\\d+\\/charges\\/\\d+").method("GET").build(),
|
||||
commandStrategies.put(CommandContext.resource("savingsaccounts").method("POST").build(), "applySavingsCommandStrategy");
|
||||
commandStrategies.put(CommandContext.resource("loans\\/\\d+\\/charges").method("POST").build(), "createChargeCommandStrategy");
|
||||
commandStrategies.put(CommandContext.resource("loans\\/\\d+\\/charges").method("GET").build(), "collectChargesCommandStrategy");
|
||||
commandStrategies.put(CommandContext.resource("loans\\/\\d+\\/charges\\/\\d+").method("GET").build(),
|
||||
"getChargeByIdCommandStrategy");
|
||||
this.commandStrategies.put(CommandContext.resource("loans\\/\\d+\\/transactions\\?command=repayment").method("POST").build(),
|
||||
"createTransactionLoanCommandStrategy");
|
||||
this.commandStrategies.put(
|
||||
CommandContext.resource("loans\\/\\d+\\/transactions\\?command=creditBalanceRefund").method("POST").build(),
|
||||
"createTransactionLoanCommandStrategy");
|
||||
this.commandStrategies.put(CommandContext.resource("loans\\/\\d+\\/transactions\\?command=goodwillCredit").method("POST").build(),
|
||||
"createTransactionLoanCommandStrategy");
|
||||
this.commandStrategies.put(
|
||||
CommandContext.resource("loans\\/\\d+\\/transactions\\?command=merchantIssuedRefund").method("POST").build(),
|
||||
"createTransactionLoanCommandStrategy");
|
||||
this.commandStrategies.put(CommandContext.resource("loans\\/\\d+\\/transactions\\?command=payoutRefund").method("POST").build(),
|
||||
"createTransactionLoanCommandStrategy");
|
||||
this.commandStrategies.put(CommandContext.resource("loans\\/\\d+\\/transactions\\/\\d+").method("POST").build(),
|
||||
commandStrategies.put(CommandContext.resource("loans\\/\\d+\\/transactions\\?command=repayment").method("POST").build(),
|
||||
CREATE_TRANSACTION_LOAN_COMMAND_STRATEGY);
|
||||
commandStrategies.put(CommandContext.resource("loans\\/\\d+\\/transactions\\?command=creditBalanceRefund").method("POST").build(),
|
||||
CREATE_TRANSACTION_LOAN_COMMAND_STRATEGY);
|
||||
commandStrategies.put(CommandContext.resource("loans\\/\\d+\\/transactions\\?command=goodwillCredit").method("POST").build(),
|
||||
CREATE_TRANSACTION_LOAN_COMMAND_STRATEGY);
|
||||
commandStrategies.put(CommandContext.resource("loans\\/\\d+\\/transactions\\?command=merchantIssuedRefund").method("POST").build(),
|
||||
CREATE_TRANSACTION_LOAN_COMMAND_STRATEGY);
|
||||
commandStrategies.put(CommandContext.resource("loans\\/\\d+\\/transactions\\?command=payoutRefund").method("POST").build(),
|
||||
CREATE_TRANSACTION_LOAN_COMMAND_STRATEGY);
|
||||
commandStrategies.put(CommandContext.resource("loans\\/\\d+\\/transactions\\/\\d+").method("POST").build(),
|
||||
"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");
|
||||
this.commandStrategies.put(CommandContext.resource("loans\\/\\d+\\?command=approve").method("POST").build(),
|
||||
commandStrategies.put(CommandContext.resource("loans\\/\\d+\\?command=approve").method("POST").build(),
|
||||
"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");
|
||||
this.commandStrategies.put(CommandContext.resource("rescheduleloans").method("POST").build(),
|
||||
commandStrategies.put(CommandContext.resource("rescheduleloans").method("POST").build(),
|
||||
"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");
|
||||
this.commandStrategies.put(CommandContext.resource("loans\\/\\d+\\/transactions\\/\\d+").method("GET").build(),
|
||||
commandStrategies.put(CommandContext.resource("loans\\/\\d+\\/transactions\\/\\d+").method("GET").build(),
|
||||
"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");
|
||||
this.commandStrategies.put(
|
||||
commandStrategies.put(
|
||||
CommandContext.resource("datatables\\/[a-zA-Z0-9_]*\\/\\d+(\\?(\\w+(?:\\=[\\w,]+|&)+)+)").method("GET").build(),
|
||||
"getDatatableEntryByAppTableIdCommandStrategy");
|
||||
}
|
||||
|
||||
+1
-1
@@ -26,7 +26,7 @@ import org.springframework.stereotype.Service;
|
||||
@Service
|
||||
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);
|
||||
|
||||
@Override
|
||||
|
||||
+3
-3
@@ -49,7 +49,7 @@ import org.springframework.stereotype.Component;
|
||||
@Tag(name = "Bulk Import", description = "")
|
||||
public class BulkImportApiResource {
|
||||
|
||||
private final String resourceNameForPermissions = "IMPORT";
|
||||
private static final String RESOURCE_NAME_FOR_PERMISSION = "IMPORT";
|
||||
|
||||
private final PlatformSecurityContext context;
|
||||
private final BulkImportWorkbookService bulkImportWorkbookService;
|
||||
@@ -70,7 +70,7 @@ public class BulkImportApiResource {
|
||||
@Produces({ MediaType.APPLICATION_JSON })
|
||||
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<>();
|
||||
if (entityType.equals(GlobalEntityType.CLIENT.getCode())) {
|
||||
final Collection<ImportData> importForClientEntity = this.bulkImportWorkbookService.getImports(GlobalEntityType.CLIENTS_ENTTTY);
|
||||
@@ -95,7 +95,7 @@ public class BulkImportApiResource {
|
||||
@GET
|
||||
@Path("getOutputTemplateLocation")
|
||||
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);
|
||||
return this.toApiJsonSerializer.serialize(documentData.fileLocation());
|
||||
}
|
||||
|
||||
+40
-38
@@ -25,6 +25,7 @@ import java.time.LocalDate;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import org.apache.fineract.commands.domain.CommandWrapper;
|
||||
import org.apache.fineract.commands.service.CommandWrapperBuilder;
|
||||
import org.apache.fineract.commands.service.IdempotencyKeyGenerator;
|
||||
@@ -56,12 +57,8 @@ import org.springframework.stereotype.Service;
|
||||
@Service
|
||||
public class CenterImportHandler implements ImportHandler {
|
||||
|
||||
public static final String EMPTY_STR = "";
|
||||
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 IdempotencyKeyGenerator idempotencyKeyGenerator;
|
||||
|
||||
@@ -73,16 +70,16 @@ public class CenterImportHandler implements ImportHandler {
|
||||
}
|
||||
|
||||
@Override
|
||||
public Count process(Workbook workbook, String locale, String dateFormat) {
|
||||
this.centers = new ArrayList<>();
|
||||
this.meetings = new ArrayList<>();
|
||||
this.statuses = new ArrayList<>();
|
||||
this.workbook = workbook;
|
||||
readExcelFile(locale, dateFormat);
|
||||
return importEntity(dateFormat);
|
||||
public Count process(final Workbook workbook, final String locale, final String dateFormat) {
|
||||
List<CenterData> centers = new ArrayList<>();
|
||||
List<CalendarData> meetings = new ArrayList<>();
|
||||
List<String> statuses = new ArrayList<>();
|
||||
readExcelFile(workbook, centers, meetings, statuses, locale, dateFormat);
|
||||
return importEntity(workbook, centers, meetings, statuses, 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);
|
||||
Integer noOfEntries = ImportHandlerUtils.getNumberOfRows(centersSheet, TemplatePopulateImportConstants.FIRST_COLUMN_INDEX);
|
||||
@@ -90,13 +87,13 @@ public class CenterImportHandler implements ImportHandler {
|
||||
Row row;
|
||||
row = centersSheet.getRow(rowIndex);
|
||||
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));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
Boolean isRepeating = ImportHandlerUtils.readAsBoolean(CenterConstants.IS_REPEATING_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 officeName = ImportHandlerUtils.readAsString(CenterConstants.OFFICE_NAME_COL, row);
|
||||
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);
|
||||
Boolean active = ImportHandlerUtils.readAsBoolean(CenterConstants.ACTIVE_COL, row);
|
||||
LocalDate submittedOn = ImportHandlerUtils.readAsDate(CenterConstants.SUBMITTED_ON_DATE_COL, row);
|
||||
LocalDate activationDate = null;
|
||||
if (active) {
|
||||
LocalDate activationDate;
|
||||
if (Boolean.TRUE.equals(active)) {
|
||||
activationDate = ImportHandlerUtils.readAsDate(CenterConstants.ACTIVATION_DATE_COL, row);
|
||||
} else {
|
||||
activationDate = submittedOn;
|
||||
}
|
||||
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");
|
||||
}
|
||||
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++) {
|
||||
String groupName = ImportHandlerUtils.readAsString(cellNo, row);
|
||||
if (groupName == null || groupName.equals("")) {
|
||||
if (groupName == null || groupName.equals(EMPTY_STR)) {
|
||||
break;
|
||||
}
|
||||
Long groupId = ImportHandlerUtils.getIdByName(workbook.getSheet(TemplatePopulateImportConstants.GROUP_SHEET_NAME), groupName);
|
||||
@@ -164,13 +162,14 @@ public class CenterImportHandler implements ImportHandler {
|
||||
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);
|
||||
int progressLevel = 0;
|
||||
String centerId = "";
|
||||
String centerId = EMPTY_STR;
|
||||
int successCount = 0;
|
||||
int errorCount = 0;
|
||||
String errorMessage = "";
|
||||
String errorMessage;
|
||||
for (int i = 0; i < centers.size(); i++) {
|
||||
Row row = centerSheet.getRow(centers.get(i).getRowIndex());
|
||||
Cell errorReportCell = row.createCell(CenterConstants.FAILURE_COL);
|
||||
@@ -181,16 +180,17 @@ public class CenterImportHandler implements ImportHandler {
|
||||
progressLevel = getProgressLevel(status);
|
||||
|
||||
if (progressLevel == 0) {
|
||||
result = importCenter(i, dateFormat);
|
||||
result = importCenter(centers, i, dateFormat);
|
||||
centerId = result.getGroupId().toString();
|
||||
progressLevel = 1;
|
||||
} 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();
|
||||
}
|
||||
|
||||
if (meetings.get(i) != null) {
|
||||
progressLevel = importCenterMeeting(result, i, dateFormat);
|
||||
progressLevel = importCenterMeeting(meetings, Objects.requireNonNull(result), i, dateFormat);
|
||||
}
|
||||
successCount++;
|
||||
statusCell.setCellValue(TemplatePopulateImportConstants.STATUS_CELL_IMPORTED);
|
||||
@@ -199,16 +199,16 @@ public class CenterImportHandler implements ImportHandler {
|
||||
errorCount++;
|
||||
LOG.error("Runtime Exception occured in importEntity function", ex);
|
||||
errorMessage = ImportHandlerUtils.getErrorMessage(ex);
|
||||
writeCenterErrorMessage(centerId, errorMessage, progressLevel, statusCell, errorReportCell, row);
|
||||
writeCenterErrorMessage(workbook, centerId, errorMessage, progressLevel, statusCell, errorReportCell, row);
|
||||
}
|
||||
}
|
||||
setReportHeaders(centerSheet);
|
||||
return Count.instance(successCount, errorCount);
|
||||
}
|
||||
|
||||
private void writeCenterErrorMessage(String centerId, String errorMessage, int progressLevel, Cell statusCell, Cell errorReportCell,
|
||||
Row row) {
|
||||
String status = "";
|
||||
private void writeCenterErrorMessage(final Workbook workbook, final String centerId, final String errorMessage, final int progressLevel,
|
||||
final Cell statusCell, final Cell errorReportCell, final Row row) {
|
||||
String status = EMPTY_STR;
|
||||
if (progressLevel == 0) {
|
||||
status = TemplatePopulateImportConstants.STATUS_CREATION_FAILED;
|
||||
} else if (progressLevel == 1) {
|
||||
@@ -233,21 +233,22 @@ public class CenterImportHandler implements ImportHandler {
|
||||
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.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());
|
||||
String payload = gsonBuilder.create().toJson(centers.get(rowIndex));
|
||||
final CommandWrapper commandRequest = new CommandWrapperBuilder() //
|
||||
.createCenter() //
|
||||
.withJson(payload) //
|
||||
.build(); //
|
||||
final CommandProcessingResult result = commandsSourceWritePlatformService.logCommandSource(commandRequest);
|
||||
return result;
|
||||
return commandsSourceWritePlatformService.logCommandSource(commandRequest);
|
||||
}
|
||||
|
||||
private void setReportHeaders(Sheet sheet) {
|
||||
private void setReportHeaders(final Sheet sheet) {
|
||||
ImportHandlerUtils.writeString(CenterConstants.STATUS_COL, sheet.getRow(0),
|
||||
TemplatePopulateImportConstants.STATUS_COL_REPORT_HEADER);
|
||||
ImportHandlerUtils.writeString(CenterConstants.CENTER_ID_COL, sheet.getRow(0),
|
||||
@@ -256,7 +257,8 @@ public class CenterImportHandler implements ImportHandler {
|
||||
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.setTitle("centers_" + result.getGroupId().toString() + "_CollectionMeeting");
|
||||
GsonBuilder gsonBuilder = GoogleGsonSerializerHelper.createGsonBuilder();
|
||||
@@ -271,7 +273,7 @@ public class CenterImportHandler implements ImportHandler {
|
||||
.createCalendar(commandWrapper, TemplatePopulateImportConstants.CENTER_ENTITY_TYPE, result.getGroupId()) //
|
||||
.withJson(payload) //
|
||||
.build(); //
|
||||
final CommandProcessingResult meetingresult = commandsSourceWritePlatformService.logCommandSource(commandRequest);
|
||||
commandsSourceWritePlatformService.logCommandSource(commandRequest);
|
||||
return 2;
|
||||
}
|
||||
|
||||
|
||||
+38
-44
@@ -23,11 +23,13 @@ import java.math.BigDecimal;
|
||||
import java.time.LocalDate;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import org.apache.fineract.accounting.glaccount.data.GLAccountData;
|
||||
import org.apache.fineract.accounting.glaccount.domain.GLAccount;
|
||||
import org.apache.fineract.accounting.glaccount.domain.GLAccountRepositoryWrapper;
|
||||
import org.apache.fineract.accounting.glaccount.domain.GLAccountType;
|
||||
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.JournalEntryData;
|
||||
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.EnumOptionDataIdSerializer;
|
||||
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.serialization.GoogleGsonSerializerHelper;
|
||||
import org.apache.fineract.infrastructure.core.service.DateUtils;
|
||||
@@ -62,16 +63,6 @@ import org.springframework.stereotype.Service;
|
||||
public class ChartOfAccountsImportHandler implements ImportHandler {
|
||||
|
||||
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 GLAccountRepositoryWrapper glAccountRepository;
|
||||
@@ -84,32 +75,38 @@ public class ChartOfAccountsImportHandler implements ImportHandler {
|
||||
}
|
||||
|
||||
@Override
|
||||
public Count process(Workbook workbook, String locale, String dateFormat) {
|
||||
this.glAccounts = new ArrayList<>();
|
||||
this.workbook = workbook;
|
||||
public Count process(final Workbook workbook, final String locale, final String dateFormat) {
|
||||
List<GLAccountData> glAccounts = new ArrayList<>();
|
||||
// for opening bal
|
||||
gltransaction = new ArrayList<>();
|
||||
credits = new ArrayList<>();
|
||||
debits = new ArrayList<>();
|
||||
this.locale = locale;
|
||||
List<JournalEntryData> glTransactions = new ArrayList<>();
|
||||
List<CreditDebit> credits = new ArrayList<>();
|
||||
List<CreditDebit> debits = new ArrayList<>();
|
||||
|
||||
readExcelFile();
|
||||
return importEntity(dateFormat);
|
||||
boolean flagForOpBal = readExcelFile(workbook, glAccounts);
|
||||
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);
|
||||
Integer noOfEntries = ImportHandlerUtils.getNumberOfRows(chartOfAccountsSheet, TemplatePopulateImportConstants.FIRST_COLUMN_INDEX);
|
||||
boolean flagForOpBal = false;
|
||||
for (int rowIndex = 1; rowIndex <= noOfEntries; rowIndex++) {
|
||||
Row row;
|
||||
row = chartOfAccountsSheet.getRow(rowIndex);
|
||||
if (ImportHandlerUtils.isNotImported(row, ChartOfAcountsConstants.STATUS_COL)) {
|
||||
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);
|
||||
EnumOptionData accountTypeEnum = GLAccountType.fromString(accountType);
|
||||
@@ -127,26 +124,23 @@ public class ChartOfAccountsImportHandler implements ImportHandler {
|
||||
Boolean manualEntriesAllowed = ImportHandlerUtils.readAsBoolean(ChartOfAcountsConstants.MANUAL_ENTRIES_ALLOWED_COL, row);
|
||||
Long parentId = 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);
|
||||
Long tagId = null;
|
||||
CodeValueData tagIdCodeValueData = 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);
|
||||
}
|
||||
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,
|
||||
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);
|
||||
|
||||
GsonBuilder gsonBuilder = GoogleGsonSerializerHelper.createGsonBuilder();
|
||||
@@ -166,7 +160,7 @@ public class ChartOfAccountsImportHandler implements ImportHandler {
|
||||
.createGLAccount() //
|
||||
.withJson(payload) //
|
||||
.build(); //
|
||||
final CommandProcessingResult result = commandsSourceWritePlatformService.logCommandSource(commandRequest);
|
||||
commandsSourceWritePlatformService.logCommandSource(commandRequest);
|
||||
successCount++;
|
||||
Cell statusCell = chartOfAccountsSheet.getRow(glAccount.getRowIndex()).createCell(ChartOfAcountsConstants.STATUS_COL);
|
||||
statusCell.setCellValue(TemplatePopulateImportConstants.STATUS_CELL_IMPORTED);
|
||||
@@ -179,16 +173,15 @@ public class ChartOfAccountsImportHandler implements ImportHandler {
|
||||
ChartOfAcountsConstants.STATUS_COL);
|
||||
}
|
||||
}
|
||||
if (flagForOpBal > 0) {
|
||||
|
||||
if (flagForOpBal) {
|
||||
try {
|
||||
readExcelFileForOpBal(locale, dateFormat);
|
||||
JournalEntryData transaction = gltransaction.get(gltransaction.size() - 1);
|
||||
readExcelFileForOpBal(workbook, glTransactions, credits, debits, locale, dateFormat);
|
||||
JournalEntryData transaction = glTransactions.get(glTransactions.size() - 1);
|
||||
String payload = gsonBuilder.create().toJson(transaction);
|
||||
|
||||
final CommandWrapper commandRequest = new CommandWrapperBuilder().defineOpeningBalanceForJournalEntry()
|
||||
.withJson(payload).build();
|
||||
final CommandProcessingResult result = commandsSourceWritePlatformService.logCommandSource(commandRequest);
|
||||
commandsSourceWritePlatformService.logCommandSource(commandRequest);
|
||||
successCount++;
|
||||
Cell statusCell = chartOfAccountsSheet.getRow(1).createCell(ChartOfAcountsConstants.STATUS_COL);
|
||||
statusCell.setCellValue(TemplatePopulateImportConstants.STATUS_CELL_IMPORTED);
|
||||
@@ -216,7 +209,8 @@ public class ChartOfAccountsImportHandler implements ImportHandler {
|
||||
}
|
||||
|
||||
// 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);
|
||||
Integer noOfEntries = ImportHandlerUtils.getNumberOfRows(chartOfAccountsSheet, TemplatePopulateImportConstants.FIRST_COLUMN_INDEX);
|
||||
@@ -225,18 +219,18 @@ public class ChartOfAccountsImportHandler implements ImportHandler {
|
||||
row = chartOfAccountsSheet.getRow(rowIndex);
|
||||
|
||||
//
|
||||
JournalEntryData journalEntry = null;
|
||||
journalEntry = readAddJournalEntries(row, locale, dateFormat);
|
||||
gltransaction.add(journalEntry);
|
||||
JournalEntryData journalEntry;
|
||||
journalEntry = readAddJournalEntries(row, credits, debits, locale, dateFormat);
|
||||
glTransactions.add(journalEntry);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// for opening balance
|
||||
private JournalEntryData readAddJournalEntries(Row row, String locale, String dateFormat) {
|
||||
transactionDate = DateUtils.getBusinessLocalDate();
|
||||
private JournalEntryData readAddJournalEntries(final Row row, final List<CreditDebit> credits, final List<CreditDebit> debits,
|
||||
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);
|
||||
|
||||
String currencyCode = ImportHandlerUtils.readAsString(ChartOfAcountsConstants.CURRENCY_CODE, row);
|
||||
@@ -245,7 +239,7 @@ public class ChartOfAccountsImportHandler implements ImportHandler {
|
||||
GLAccount glAccount = this.glAccountRepository.findOneByGlCodeWithNotFoundDetection(glCode);
|
||||
Long glAccountIdToDebitedCredited = glAccount.getId();
|
||||
if (glAccountIdToDebitedCredited == null) {
|
||||
throw new RuntimeException("Account does not exist");
|
||||
throw new GLAccountNotFoundException("Account does not exist");
|
||||
}
|
||||
|
||||
// String credit =
|
||||
|
||||
+25
-27
@@ -22,9 +22,9 @@ import com.google.common.base.Splitter;
|
||||
import com.google.gson.GsonBuilder;
|
||||
import java.time.LocalDate;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import org.apache.fineract.commands.domain.CommandWrapper;
|
||||
import org.apache.fineract.commands.service.CommandWrapperBuilder;
|
||||
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.ImportHandlerUtils;
|
||||
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.portfolio.address.data.AddressData;
|
||||
import org.apache.fineract.portfolio.client.data.ClientData;
|
||||
@@ -52,10 +51,8 @@ import org.springframework.stereotype.Service;
|
||||
@Service
|
||||
public class ClientEntityImportHandler implements ImportHandler {
|
||||
|
||||
public static final String SEPARATOR = "-";
|
||||
private static final Logger LOG = LoggerFactory.getLogger(ClientEntityImportHandler.class);
|
||||
private Workbook workbook;
|
||||
private List<ClientData> clients;
|
||||
|
||||
private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService;
|
||||
|
||||
@Autowired
|
||||
@@ -64,26 +61,27 @@ public class ClientEntityImportHandler implements ImportHandler {
|
||||
}
|
||||
|
||||
@Override
|
||||
public Count process(Workbook workbook, String locale, String dateFormat) {
|
||||
this.workbook = workbook;
|
||||
this.clients = new ArrayList<>();
|
||||
readExcelFile(locale, dateFormat);
|
||||
return importEntity(dateFormat);
|
||||
public Count process(final Workbook workbook, final String locale, final String dateFormat) {
|
||||
|
||||
List<ClientData> clients = readExcelFile(workbook, locale, dateFormat);
|
||||
return importEntity(workbook, clients, 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);
|
||||
Integer noOfEntries = ImportHandlerUtils.getNumberOfRows(clientSheet, 0);
|
||||
for (int rowIndex = 1; rowIndex <= noOfEntries; rowIndex++) {
|
||||
Row row;
|
||||
row = clientSheet.getRow(rowIndex);
|
||||
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;
|
||||
String name = ImportHandlerUtils.readAsString(ClientEntityConstants.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);
|
||||
String mobileNo = 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);
|
||||
Long clientTypeId = null;
|
||||
if (clientType != null) {
|
||||
List<String> clientTypeAr = Splitter.on('-').splitToList(clientType);
|
||||
List<String> clientTypeAr = Splitter.on(SEPARATOR).splitToList(clientType);
|
||||
if (clientTypeAr.get(1) != null) {
|
||||
clientTypeId = Long.parseLong(clientTypeAr.get(1));
|
||||
}
|
||||
@@ -114,7 +112,7 @@ public class ClientEntityImportHandler implements ImportHandler {
|
||||
String clientClassification = ImportHandlerUtils.readAsString(ClientEntityConstants.CLIENT_CLASSIFICATION_COL, row);
|
||||
Long clientClassicationId = null;
|
||||
if (clientClassification != null) {
|
||||
List<String> clientClassificationAr = Splitter.on('-').splitToList(clientClassification);
|
||||
List<String> clientClassificationAr = Splitter.on(SEPARATOR).splitToList(clientClassification);
|
||||
if (clientClassificationAr.get(1) != null) {
|
||||
clientClassicationId = Long.parseLong(clientClassificationAr.get(1));
|
||||
}
|
||||
@@ -124,8 +122,8 @@ public class ClientEntityImportHandler implements ImportHandler {
|
||||
String mainBusinessLine = ImportHandlerUtils.readAsString(ClientEntityConstants.MAIN_BUSINESS_LINE, row);
|
||||
Long mainBusinessId = null;
|
||||
if (mainBusinessLine != null) {
|
||||
List<String> mainBusinessLineAr = Splitter.on('-')
|
||||
.splitToList(ImportHandlerUtils.readAsString(ClientEntityConstants.MAIN_BUSINESS_LINE, row));
|
||||
List<String> mainBusinessLineAr = Splitter.on(SEPARATOR)
|
||||
.splitToList(Objects.requireNonNull(ImportHandlerUtils.readAsString(ClientEntityConstants.MAIN_BUSINESS_LINE, row)));
|
||||
if (mainBusinessLineAr.get(1) != null) {
|
||||
mainBusinessId = Long.parseLong(mainBusinessLineAr.get(1));
|
||||
}
|
||||
@@ -133,7 +131,7 @@ public class ClientEntityImportHandler implements ImportHandler {
|
||||
String constitution = ImportHandlerUtils.readAsString(ClientEntityConstants.CONSTITUTION_COL, row);
|
||||
Long constitutionId = null;
|
||||
if (constitution != null) {
|
||||
List<String> constitutionAr = Splitter.on('-').splitToList(constitution);
|
||||
List<String> constitutionAr = Splitter.on(SEPARATOR).splitToList(constitution);
|
||||
if (constitutionAr.get(1) != null) {
|
||||
constitutionId = Long.parseLong(constitutionAr.get(1));
|
||||
}
|
||||
@@ -153,13 +151,13 @@ public class ClientEntityImportHandler implements ImportHandler {
|
||||
if (!active) {
|
||||
activationDate = submittedOn;
|
||||
}
|
||||
AddressData addressDataObj = null;
|
||||
AddressData addressDataObj;
|
||||
Collection<AddressData> addressList = null;
|
||||
if (ImportHandlerUtils.readAsBoolean(ClientEntityConstants.ADDRESS_ENABLED, row)) {
|
||||
String addressType = ImportHandlerUtils.readAsString(ClientEntityConstants.ADDRESS_TYPE_COL, row);
|
||||
Long addressTypeId = null;
|
||||
if (addressType != null) {
|
||||
List<String> addressTypeAr = Splitter.on('-').splitToList(addressType);
|
||||
List<String> addressTypeAr = Splitter.on(SEPARATOR).splitToList(addressType);
|
||||
if (addressTypeAr.get(1) != null) {
|
||||
addressTypeId = Long.parseLong(addressTypeAr.get(1));
|
||||
}
|
||||
@@ -176,7 +174,7 @@ public class ClientEntityImportHandler implements ImportHandler {
|
||||
String stateProvince = ImportHandlerUtils.readAsString(ClientEntityConstants.STATE_PROVINCE_COL, row);
|
||||
Long stateProvinceId = null;
|
||||
if (stateProvince != null) {
|
||||
List<String> stateProvinceAr = Splitter.on('-').splitToList(stateProvince);
|
||||
List<String> stateProvinceAr = Splitter.on(SEPARATOR).splitToList(stateProvince);
|
||||
if (stateProvinceAr.get(1) != null) {
|
||||
stateProvinceId = Long.parseLong(stateProvinceAr.get(1));
|
||||
}
|
||||
@@ -184,26 +182,26 @@ public class ClientEntityImportHandler implements ImportHandler {
|
||||
String country = ImportHandlerUtils.readAsString(ClientEntityConstants.COUNTRY_COL, row);
|
||||
Long countryId = null;
|
||||
if (country != null) {
|
||||
List<String> countryAr = Splitter.on('-').splitToList(country);
|
||||
List<String> countryAr = Splitter.on(SEPARATOR).splitToList(country);
|
||||
if (countryAr.get(1) != null) {
|
||||
countryId = Long.parseLong(countryAr.get(1));
|
||||
}
|
||||
}
|
||||
addressDataObj = new AddressData(addressTypeId, street, addressLine1, addressLine2, addressLine3, city, postalCode,
|
||||
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,
|
||||
staffId, active, activationDate, submittedOn, externalId, incorportionDate, mobileNo, clientNonPersonData, addressList,
|
||||
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);
|
||||
|
||||
int successCount = 0;
|
||||
int errorCount = 0;
|
||||
String errorMessage = "";
|
||||
String errorMessage;
|
||||
|
||||
GsonBuilder gsonBuilder = GoogleGsonSerializerHelper.createGsonBuilder();
|
||||
gsonBuilder.registerTypeAdapter(LocalDate.class, new DateSerializer(dateFormat));
|
||||
@@ -215,7 +213,7 @@ public class ClientEntityImportHandler implements ImportHandler {
|
||||
.createClient() //
|
||||
.withJson(payload) //
|
||||
.build(); //
|
||||
final CommandProcessingResult result = commandsSourceWritePlatformService.logCommandSource(commandRequest);
|
||||
commandsSourceWritePlatformService.logCommandSource(commandRequest);
|
||||
successCount++;
|
||||
Cell statusCell = clientSheet.getRow(client.getRowIndex()).createCell(ClientEntityConstants.STATUS_COL);
|
||||
statusCell.setCellValue(TemplatePopulateImportConstants.STATUS_CELL_IMPORTED);
|
||||
|
||||
+21
-22
@@ -22,9 +22,9 @@ import com.google.common.base.Splitter;
|
||||
import com.google.gson.GsonBuilder;
|
||||
import java.time.LocalDate;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import org.apache.fineract.commands.domain.CommandWrapper;
|
||||
import org.apache.fineract.commands.service.CommandWrapperBuilder;
|
||||
import org.apache.fineract.commands.service.PortfolioCommandSourceWritePlatformService;
|
||||
@@ -50,10 +50,8 @@ import org.springframework.stereotype.Service;
|
||||
@Service
|
||||
public class ClientPersonImportHandler implements ImportHandler {
|
||||
|
||||
public static final String SEPARATOR = "-";
|
||||
private static final Logger LOG = LoggerFactory.getLogger(ClientPersonImportHandler.class);
|
||||
private Workbook workbook;
|
||||
private List<ClientData> clients;
|
||||
|
||||
private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService;
|
||||
|
||||
@Autowired
|
||||
@@ -62,26 +60,27 @@ public class ClientPersonImportHandler implements ImportHandler {
|
||||
}
|
||||
|
||||
@Override
|
||||
public Count process(Workbook workbook, String locale, String dateFormat) {
|
||||
this.workbook = workbook;
|
||||
this.clients = new ArrayList<>();
|
||||
readExcelFile(locale, dateFormat);
|
||||
return importEntity(dateFormat);
|
||||
public Count process(final Workbook workbook, final String locale, final String dateFormat) {
|
||||
|
||||
List<ClientData> clients = readExcelFile(workbook, locale, dateFormat);
|
||||
return importEntity(workbook, clients, 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);
|
||||
Integer noOfEntries = ImportHandlerUtils.getNumberOfRows(clientSheet, 0);
|
||||
for (int rowIndex = 1; rowIndex <= noOfEntries; rowIndex++) {
|
||||
Row row;
|
||||
row = clientSheet.getRow(rowIndex);
|
||||
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;
|
||||
String firstName = ImportHandlerUtils.readAsString(ClientPersonConstants.FIRST_NAME_COL, row);
|
||||
String lastName = ImportHandlerUtils.readAsString(ClientPersonConstants.LAST_NAME_COL, row);
|
||||
@@ -105,14 +104,14 @@ public class ClientPersonImportHandler implements ImportHandler {
|
||||
}
|
||||
String mobileNo = 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);
|
||||
|
||||
String clientType = ImportHandlerUtils.readAsString(ClientPersonConstants.CLIENT_TYPE_COL, row);
|
||||
Long clientTypeId = 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) {
|
||||
clientTypeId = Long.parseLong(clientTypeAr.get(1));
|
||||
}
|
||||
@@ -120,7 +119,7 @@ public class ClientPersonImportHandler implements ImportHandler {
|
||||
String gender = ImportHandlerUtils.readAsString(ClientPersonConstants.GENDER_COL, row);
|
||||
Long genderId = 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) {
|
||||
genderId = Long.parseLong(genderAr.get(1));
|
||||
}
|
||||
@@ -128,7 +127,7 @@ public class ClientPersonImportHandler implements ImportHandler {
|
||||
String clientClassification = ImportHandlerUtils.readAsString(ClientPersonConstants.CLIENT_CLASSIFICATION_COL, row);
|
||||
Long clientClassificationId = 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) {
|
||||
clientClassificationId = Long.parseLong(clientClassificationAr.get(1));
|
||||
}
|
||||
@@ -141,7 +140,7 @@ public class ClientPersonImportHandler implements ImportHandler {
|
||||
String addressType = ImportHandlerUtils.readAsString(ClientPersonConstants.ADDRESS_TYPE_COL, row);
|
||||
Long addressTypeId = 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) {
|
||||
addressTypeId = Long.parseLong(addressTypeAr.get(1));
|
||||
@@ -159,7 +158,7 @@ public class ClientPersonImportHandler implements ImportHandler {
|
||||
String stateProvince = ImportHandlerUtils.readAsString(ClientPersonConstants.STATE_PROVINCE_COL, row);
|
||||
Long stateProvinceId = 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
|
||||
// but probably it's either an empty cell or it is missing a
|
||||
// hyphen
|
||||
@@ -170,14 +169,14 @@ public class ClientPersonImportHandler implements ImportHandler {
|
||||
String country = ImportHandlerUtils.readAsString(ClientPersonConstants.COUNTRY_COL, row);
|
||||
Long countryId = 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) {
|
||||
countryId = Long.parseLong(countryAr.get(1));
|
||||
}
|
||||
}
|
||||
addressDataObj = new AddressData(addressTypeId, street, addressLine1, addressLine2, addressLine3, city, postalCode,
|
||||
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,
|
||||
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);
|
||||
int successCount = 0;
|
||||
int errorCount = 0;
|
||||
String errorMessage = "";
|
||||
String errorMessage;
|
||||
GsonBuilder gsonBuilder = GoogleGsonSerializerHelper.createGsonBuilder();
|
||||
gsonBuilder.registerTypeAdapter(LocalDate.class, new DateSerializer(dateFormat));
|
||||
for (ClientData client : clients) {
|
||||
|
||||
+41
-41
@@ -58,14 +58,6 @@ import org.springframework.stereotype.Service;
|
||||
public class FixedDepositImportHandler implements ImportHandler {
|
||||
|
||||
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;
|
||||
|
||||
@Autowired
|
||||
@@ -74,25 +66,28 @@ public class FixedDepositImportHandler implements ImportHandler {
|
||||
}
|
||||
|
||||
@Override
|
||||
public Count process(Workbook workbook, String locale, String dateFormat) {
|
||||
this.workbook = workbook;
|
||||
savings = new ArrayList<>();
|
||||
approvalDates = new ArrayList<>();
|
||||
activationDates = new ArrayList<>();
|
||||
closedOnDate = new ArrayList<>();
|
||||
statuses = new ArrayList<>();
|
||||
readExcelFile(locale, dateFormat);
|
||||
return importEntity(dateFormat);
|
||||
public Count process(final Workbook workbook, final String locale, final String dateFormat) {
|
||||
|
||||
List<FixedDepositAccountData> savings = new ArrayList<>();
|
||||
List<SavingsApproval> approvalDates = new ArrayList<>();
|
||||
List<SavingsActivation> activationDates = new ArrayList<>();
|
||||
List<ClosingOfSavingsAccounts> closedOnDates = new ArrayList<>();
|
||||
List<String> statuses = new ArrayList<>();
|
||||
|
||||
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);
|
||||
Integer noOfEntries = ImportHandlerUtils.getNumberOfRows(savingsSheet, TemplatePopulateImportConstants.FIRST_COLUMN_INDEX);
|
||||
for (int rowIndex = 1; rowIndex <= noOfEntries; rowIndex++) {
|
||||
Row row;
|
||||
row = savingsSheet.getRow(rowIndex);
|
||||
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));
|
||||
activationDates.add(readSavingsActivation(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);
|
||||
Long productId = ImportHandlerUtils.getIdByName(workbook.getSheet(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME), productName);
|
||||
@@ -164,7 +160,7 @@ public class FixedDepositImportHandler implements ImportHandler {
|
||||
Long interestPostingPeriodTypeId = null;
|
||||
|
||||
EnumOptionData interestPostingPeriodTypeEnum = null;
|
||||
if (interestCompoundingPeriodType != null) {
|
||||
if (interestPostingPeriodType != null) {
|
||||
if (interestPostingPeriodType.equalsIgnoreCase(TemplatePopulateImportConstants.INTEREST_POSTING_PERIOD_MONTHLY)) {
|
||||
interestPostingPeriodTypeId = 4L;
|
||||
} 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 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 charge2 = ImportHandlerUtils.readAsString(FixedDepositConstants.CHARGE_ID_2, row);
|
||||
@@ -273,7 +269,9 @@ public class FixedDepositImportHandler implements ImportHandler {
|
||||
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);
|
||||
int successCount = 0;
|
||||
int errorCount = 0;
|
||||
@@ -289,7 +287,7 @@ public class FixedDepositImportHandler implements ImportHandler {
|
||||
progressLevel = getProgressLevel(status);
|
||||
|
||||
if (progressLevel == 0) {
|
||||
CommandProcessingResult result = importSavings(i, dateFormat);
|
||||
CommandProcessingResult result = importSavings(savings, i, dateFormat);
|
||||
savingsId = result.getSavingsId();
|
||||
progressLevel = 1;
|
||||
} else {
|
||||
@@ -298,15 +296,15 @@ public class FixedDepositImportHandler implements ImportHandler {
|
||||
}
|
||||
|
||||
if (progressLevel <= 1) {
|
||||
progressLevel = importSavingsApproval(savingsId, i, dateFormat);
|
||||
progressLevel = importSavingsApproval(approvalDates, savingsId, i, dateFormat);
|
||||
}
|
||||
|
||||
if (progressLevel <= 2) {
|
||||
progressLevel = importSavingsActivation(savingsId, i, dateFormat);
|
||||
progressLevel = importSavingsActivation(activationDates, savingsId, i, dateFormat);
|
||||
}
|
||||
|
||||
if (progressLevel <= 3) {
|
||||
progressLevel = importSavingsClosing(savingsId, i, dateFormat);
|
||||
progressLevel = importSavingsClosing(closedOnDates, savingsId, i, dateFormat);
|
||||
}
|
||||
|
||||
successCount++;
|
||||
@@ -316,7 +314,7 @@ public class FixedDepositImportHandler implements ImportHandler {
|
||||
errorCount++;
|
||||
LOG.error("Problem occurred in importEntity function", 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);
|
||||
}
|
||||
|
||||
private void writeFixedDepositErrorMessage(Long savingsId, String errorMessage, int progressLevel, Cell statusCell,
|
||||
Cell errorReportCell, Row row) {
|
||||
private void writeFixedDepositErrorMessage(final Workbook workbook, final Long savingsId, final String errorMessage,
|
||||
final int progressLevel, final Cell statusCell, Cell errorReportCell, Row row) {
|
||||
String status = "";
|
||||
if (progressLevel == 0) {
|
||||
status = TemplatePopulateImportConstants.STATUS_CREATION_FAILED;
|
||||
@@ -343,21 +341,22 @@ public class FixedDepositImportHandler implements ImportHandler {
|
||||
errorReportCell.setCellValue(errorMessage);
|
||||
}
|
||||
|
||||
private int importSavingsClosing(Long savingsId, int i, String dateFormat) {
|
||||
if (closedOnDate.get(i) != null) {
|
||||
private int importSavingsClosing(List<ClosingOfSavingsAccounts> closedOnDates, final Long savingsId, final int i,
|
||||
final String dateFormat) {
|
||||
if (closedOnDates.get(i) != null) {
|
||||
GsonBuilder gsonBuilder = GoogleGsonSerializerHelper.createGsonBuilder();
|
||||
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() //
|
||||
.closeFixedDepositAccount(savingsId)//
|
||||
.withJson(payload) //
|
||||
.build(); //
|
||||
final CommandProcessingResult result = commandsSourceWritePlatformService.logCommandSource(commandRequest);
|
||||
commandsSourceWritePlatformService.logCommandSource(commandRequest);
|
||||
}
|
||||
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.registerTypeAdapter(LocalDate.class, new DateSerializer(dateFormat));
|
||||
gsonBuilder.registerTypeAdapter(EnumOptionData.class, new EnumOptionDataIdSerializer());
|
||||
@@ -377,11 +376,11 @@ public class FixedDepositImportHandler implements ImportHandler {
|
||||
.createFixedDepositAccount() //
|
||||
.withJson(payload) //
|
||||
.build(); //
|
||||
final CommandProcessingResult result = commandsSourceWritePlatformService.logCommandSource(commandRequest);
|
||||
return result;
|
||||
return commandsSourceWritePlatformService.logCommandSource(commandRequest);
|
||||
}
|
||||
|
||||
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) {
|
||||
GsonBuilder gsonBuilder = GoogleGsonSerializerHelper.createGsonBuilder();
|
||||
gsonBuilder.registerTypeAdapter(LocalDate.class, new DateSerializer(dateFormat));
|
||||
@@ -390,12 +389,13 @@ public class FixedDepositImportHandler implements ImportHandler {
|
||||
.approveFixedDepositAccountApplication(savingsId)//
|
||||
.withJson(payload) //
|
||||
.build(); //
|
||||
final CommandProcessingResult result = commandsSourceWritePlatformService.logCommandSource(commandRequest);
|
||||
commandsSourceWritePlatformService.logCommandSource(commandRequest);
|
||||
}
|
||||
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) {
|
||||
GsonBuilder gsonBuilder = GoogleGsonSerializerHelper.createGsonBuilder();
|
||||
gsonBuilder.registerTypeAdapter(LocalDate.class, new DateSerializer(dateFormat));
|
||||
@@ -404,7 +404,7 @@ public class FixedDepositImportHandler implements ImportHandler {
|
||||
.fixedDepositAccountActivation(savingsId)//
|
||||
.withJson(payload) //
|
||||
.build(); //
|
||||
final CommandProcessingResult result = commandsSourceWritePlatformService.logCommandSource(commandRequest);
|
||||
commandsSourceWritePlatformService.logCommandSource(commandRequest);
|
||||
}
|
||||
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.helper.DateSerializer;
|
||||
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.portfolio.savings.data.SavingsAccountTransactionData;
|
||||
import org.apache.fineract.portfolio.savings.data.SavingsAccountTransactionEnumData;
|
||||
@@ -51,11 +50,12 @@ import org.springframework.stereotype.Service;
|
||||
@Service
|
||||
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 Workbook workbook;
|
||||
private List<SavingsAccountTransactionData> savingsTransactions;
|
||||
private String savingsAccountId = "";
|
||||
|
||||
private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService;
|
||||
|
||||
@Autowired
|
||||
@@ -64,33 +64,34 @@ public class FixedDepositTransactionImportHandler implements ImportHandler {
|
||||
}
|
||||
|
||||
@Override
|
||||
public Count process(Workbook workbook, String locale, String dateFormat) {
|
||||
this.workbook = workbook;
|
||||
this.savingsTransactions = new ArrayList<>();
|
||||
readExcelFile(locale, dateFormat);
|
||||
return importEntity(dateFormat);
|
||||
public Count process(final Workbook workbook, final String locale, final String dateFormat) {
|
||||
List<SavingsAccountTransactionData> savingsTransactions = readExcelFile(workbook, locale, dateFormat);
|
||||
return importEntity(workbook, savingsTransactions, 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);
|
||||
Integer noOfEntries = ImportHandlerUtils.getNumberOfRows(savingsTransactionSheet, TransactionConstants.AMOUNT_COL);
|
||||
Long savingsAccountId = null;
|
||||
for (int rowIndex = 1; rowIndex <= noOfEntries; rowIndex++) {
|
||||
Row row;
|
||||
row = savingsTransactionSheet.getRow(rowIndex);
|
||||
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) {
|
||||
String savingsAccountIdCheck = null;
|
||||
if (ImportHandlerUtils.readAsLong(TransactionConstants.SAVINGS_ACCOUNT_NO_COL, row) != null) {
|
||||
savingsAccountIdCheck = ImportHandlerUtils.readAsLong(TransactionConstants.SAVINGS_ACCOUNT_NO_COL, row).toString();
|
||||
}
|
||||
if (savingsAccountIdCheck != null) {
|
||||
savingsAccountId = savingsAccountIdCheck;
|
||||
private SavingsAccountTransactionData readSavingsTransaction(final Workbook workbook, final Row row, Long savingsAccountId,
|
||||
final String locale, final String dateFormat) {
|
||||
|
||||
Long newSavingsAccountId = ImportHandlerUtils.readAsLong(TransactionConstants.SAVINGS_ACCOUNT_NO_COL, row);
|
||||
if (newSavingsAccountId != null) {
|
||||
savingsAccountId = newSavingsAccountId;
|
||||
}
|
||||
|
||||
String transactionType = ImportHandlerUtils.readAsString(TransactionConstants.TRANSACTION_TYPE_COL, row);
|
||||
SavingsAccountTransactionEnumData savingsAccountTransactionEnumData = new SavingsAccountTransactionEnumData(null, null,
|
||||
transactionType);
|
||||
@@ -110,12 +111,12 @@ public class FixedDepositTransactionImportHandler implements ImportHandler {
|
||||
String receiptNumber = ImportHandlerUtils.readAsString(TransactionConstants.RECEIPT_NO_COL, row);
|
||||
String bankNumber = ImportHandlerUtils.readAsString(TransactionConstants.BANK_NO_COL, row);
|
||||
return SavingsAccountTransactionData.importInstance(amount, transactionDate, paymentTypeId, accountNumber, checkNumber, routingCode,
|
||||
receiptNumber, bankNumber, Long.parseLong(savingsAccountId), savingsAccountTransactionEnumData, row.getRowNum(), locale,
|
||||
dateFormat);
|
||||
receiptNumber, bankNumber, savingsAccountId, savingsAccountTransactionEnumData, row.getRowNum(), locale, 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);
|
||||
int successCount = 0;
|
||||
int errorCount = 0;
|
||||
@@ -127,24 +128,24 @@ public class FixedDepositTransactionImportHandler implements ImportHandler {
|
||||
for (SavingsAccountTransactionData transaction : savingsTransactions) {
|
||||
try {
|
||||
JsonObject savingsTransactionJsonob = gsonBuilder.create().toJsonTree(transaction).getAsJsonObject();
|
||||
savingsTransactionJsonob.remove("transactionType");
|
||||
savingsTransactionJsonob.remove("reversed");
|
||||
savingsTransactionJsonob.remove("interestedPostedAsOn");
|
||||
savingsTransactionJsonob.remove(TRANSACTION_TYPE);
|
||||
savingsTransactionJsonob.remove(REVERSED);
|
||||
savingsTransactionJsonob.remove(INTERESTED_POSTED_AS_ON);
|
||||
String payload = savingsTransactionJsonob.toString();
|
||||
CommandWrapper commandRequest = null;
|
||||
if (transaction.getTransactionType().getValue().equals("Withdrawal")) {
|
||||
if (transaction.getTransactionType().getValue().equals(WITHDRAWAL)) {
|
||||
commandRequest = new CommandWrapperBuilder() //
|
||||
.fixedDepositAccountWithdrawal(transaction.getSavingsAccountId()) //
|
||||
.withJson(payload) //
|
||||
.build(); //
|
||||
|
||||
} else if (transaction.getTransactionType().getValue().equals("Deposit")) {
|
||||
} else if (transaction.getTransactionType().getValue().equals(DEPOSIT)) {
|
||||
commandRequest = new CommandWrapperBuilder() //
|
||||
.fixedDepositAccountDeposit(transaction.getSavingsAccountId()) //
|
||||
.withJson(payload) //
|
||||
.build();
|
||||
}
|
||||
final CommandProcessingResult result = commandsSourceWritePlatformService.logCommandSource(commandRequest);
|
||||
commandsSourceWritePlatformService.logCommandSource(commandRequest);
|
||||
successCount++;
|
||||
Cell statusCell = savingsTransactionSheet.getRow(transaction.getRowIndex()).createCell(TransactionConstants.STATUS_COL);
|
||||
statusCell.setCellValue(TemplatePopulateImportConstants.STATUS_CELL_IMPORTED);
|
||||
|
||||
+29
-27
@@ -25,6 +25,7 @@ import java.time.LocalDate;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import org.apache.fineract.commands.domain.CommandWrapper;
|
||||
import org.apache.fineract.commands.service.CommandWrapperBuilder;
|
||||
import org.apache.fineract.commands.service.IdempotencyKeyGenerator;
|
||||
@@ -57,10 +58,6 @@ import org.springframework.stereotype.Service;
|
||||
public class GroupImportHandler implements ImportHandler {
|
||||
|
||||
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 IdempotencyKeyGenerator idempotencyKeyGenerator;
|
||||
@@ -73,23 +70,24 @@ public class GroupImportHandler implements ImportHandler {
|
||||
}
|
||||
|
||||
@Override
|
||||
public Count process(Workbook workbook, String locale, String dateFormat) {
|
||||
this.workbook = workbook;
|
||||
groups = new ArrayList<>();
|
||||
meetings = new ArrayList<>();
|
||||
statuses = new ArrayList<>();
|
||||
readExcelFile(locale, dateFormat);
|
||||
return importEntity(dateFormat);
|
||||
public Count process(final Workbook workbook, final String locale, final String dateFormat) {
|
||||
|
||||
List<GroupGeneralData> groups = new ArrayList<>();
|
||||
List<CalendarData> meetings = new ArrayList<>();
|
||||
List<String> statuses = new ArrayList<>();
|
||||
readExcelFile(workbook, groups, meetings, statuses, locale, 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);
|
||||
Integer noOfEntries = ImportHandlerUtils.getNumberOfRows(groupsSheet, TemplatePopulateImportConstants.FIRST_COLUMN_INDEX);
|
||||
for (int rowIndex = 1; rowIndex <= noOfEntries; rowIndex++) {
|
||||
Row row;
|
||||
row = groupsSheet.getRow(rowIndex);
|
||||
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));
|
||||
}
|
||||
}
|
||||
@@ -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 officeName = ImportHandlerUtils.readAsString(GroupConstants.OFFICE_NAME_COL, row);
|
||||
Long officeId = ImportHandlerUtils.getIdByName(workbook.getSheet(TemplatePopulateImportConstants.OFFICE_SHEET_NAME), officeName);
|
||||
@@ -167,7 +166,8 @@ public class GroupImportHandler implements ImportHandler {
|
||||
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);
|
||||
int successCount = 0;
|
||||
int errorCount = 0;
|
||||
@@ -184,16 +184,17 @@ public class GroupImportHandler implements ImportHandler {
|
||||
progressLevel = getProgressLevel(status);
|
||||
|
||||
if (progressLevel == 0) {
|
||||
result = importGroup(i, dateFormat);
|
||||
result = importGroup(groups, i, dateFormat);
|
||||
groupId = result.getGroupId().toString();
|
||||
progressLevel = 1;
|
||||
} 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();
|
||||
}
|
||||
|
||||
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);
|
||||
@@ -202,15 +203,15 @@ public class GroupImportHandler implements ImportHandler {
|
||||
errorCount++;
|
||||
LOG.error("Problem occurred in importEntity function", ex);
|
||||
errorMessage = ImportHandlerUtils.getErrorMessage(ex);
|
||||
writeGroupErrorMessage(groupId, errorMessage, progressLevel, statusCell, errorReportCell, row);
|
||||
writeGroupErrorMessage(workbook, groupId, errorMessage, progressLevel, statusCell, errorReportCell, row);
|
||||
}
|
||||
}
|
||||
setReportHeaders(groupSheet);
|
||||
return Count.instance(successCount, errorCount);
|
||||
}
|
||||
|
||||
private void writeGroupErrorMessage(String groupId, String errorMessage, int progressLevel, Cell statusCell, Cell errorReportCell,
|
||||
Row row) {
|
||||
private void writeGroupErrorMessage(final Workbook workbook, final String groupId, final String errorMessage, final int progressLevel,
|
||||
final Cell statusCell, final Cell errorReportCell, final Row row) {
|
||||
String status = "";
|
||||
if (progressLevel == 0) {
|
||||
status = TemplatePopulateImportConstants.STATUS_CREATION_FAILED;
|
||||
@@ -235,7 +236,7 @@ public class GroupImportHandler implements ImportHandler {
|
||||
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.setTitle("group_" + result.getGroupId().toString() + "_CollectionMeeting");
|
||||
GsonBuilder gsonBuilder = GoogleGsonSerializerHelper.createGsonBuilder();
|
||||
@@ -250,22 +251,23 @@ public class GroupImportHandler implements ImportHandler {
|
||||
.createCalendar(commandWrapper, TemplatePopulateImportConstants.CENTER_ENTITY_TYPE, result.getGroupId()) //
|
||||
.withJson(payload) //
|
||||
.build(); //
|
||||
final CommandProcessingResult meetingresult = commandsSourceWritePlatformService.logCommandSource(commandRequest);
|
||||
commandsSourceWritePlatformService.logCommandSource(commandRequest);
|
||||
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.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());
|
||||
String payload = gsonBuilder.create().toJson(groups.get(rowIndex));
|
||||
final CommandWrapper commandRequest = new CommandWrapperBuilder() //
|
||||
.createGroup() //
|
||||
.withJson(payload) //
|
||||
.build(); //
|
||||
final CommandProcessingResult result = commandsSourceWritePlatformService.logCommandSource(commandRequest);
|
||||
return result;
|
||||
return commandsSourceWritePlatformService.logCommandSource(commandRequest);
|
||||
}
|
||||
|
||||
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.ImportHandlerUtils;
|
||||
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.portfolio.loanaccount.guarantor.data.GuarantorData;
|
||||
import org.apache.poi.ss.usermodel.Cell;
|
||||
@@ -50,11 +49,8 @@ import org.springframework.stereotype.Service;
|
||||
@Service
|
||||
public class GuarantorImportHandler implements ImportHandler {
|
||||
|
||||
public static final String SEPARATOR = "-";
|
||||
private static final Logger LOG = LoggerFactory.getLogger(GuarantorImportHandler.class);
|
||||
private Workbook workbook;
|
||||
private List<GuarantorData> guarantors;
|
||||
private Long loanAccountId;
|
||||
|
||||
private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService;
|
||||
|
||||
@Autowired
|
||||
@@ -63,30 +59,31 @@ public class GuarantorImportHandler implements ImportHandler {
|
||||
}
|
||||
|
||||
@Override
|
||||
public Count process(Workbook workbook, String locale, String dateFormat) {
|
||||
this.workbook = workbook;
|
||||
this.guarantors = new ArrayList<>();
|
||||
readExcelFile(locale, dateFormat);
|
||||
return importEntity(dateFormat);
|
||||
public Count process(final Workbook workbook, final String locale, final String dateFormat) {
|
||||
List<GuarantorData> guarantors = readExcelFile(workbook, locale, dateFormat);
|
||||
return importEntity(workbook, guarantors, 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);
|
||||
Integer noOfEntries = ImportHandlerUtils.getNumberOfRows(addGuarantorSheet, GuarantorConstants.LOAN_ACCOUNT_NO_COL);
|
||||
Long loanAccountId = null;
|
||||
for (int rowIndex = 1; rowIndex <= noOfEntries; rowIndex++) {
|
||||
Row row;
|
||||
row = addGuarantorSheet.getRow(rowIndex);
|
||||
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);
|
||||
if (loanaccountInfo != null) {
|
||||
List<String> loanAccountAr = Splitter.on('-').splitToList(loanaccountInfo);
|
||||
List<String> loanAccountAr = Splitter.on(SEPARATOR).splitToList(loanaccountInfo);
|
||||
loanAccountId = Long.parseLong(loanAccountAr.get(0));
|
||||
}
|
||||
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);
|
||||
Integer clientRelationshipTypeId = 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));
|
||||
}
|
||||
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);
|
||||
}
|
||||
|
||||
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);
|
||||
int successCount = 0;
|
||||
int errorCount = 0;
|
||||
@@ -137,7 +134,7 @@ public class GuarantorImportHandler implements ImportHandler {
|
||||
.createGuarantor(guarantor.getAccountId()) //
|
||||
.withJson(payload) //
|
||||
.build(); //
|
||||
final CommandProcessingResult result = commandsSourceWritePlatformService.logCommandSource(commandRequest);
|
||||
commandsSourceWritePlatformService.logCommandSource(commandRequest);
|
||||
successCount++;
|
||||
Cell statusCell = addGuarantorSheet.getRow(guarantor.getRowIndex()).createCell(GuarantorConstants.STATUS_COL);
|
||||
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.helper.CurrencyDateCodeSerializer;
|
||||
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.organisation.monetary.data.CurrencyData;
|
||||
import org.apache.poi.ss.usermodel.Cell;
|
||||
@@ -52,12 +51,6 @@ import org.springframework.stereotype.Service;
|
||||
public class JournalEntriesImportHandler implements ImportHandler {
|
||||
|
||||
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;
|
||||
|
||||
@@ -67,17 +60,18 @@ public class JournalEntriesImportHandler implements ImportHandler {
|
||||
}
|
||||
|
||||
@Override
|
||||
public Count process(Workbook workbook, String locale, String dateFormat) {
|
||||
this.workbook = workbook;
|
||||
gltransaction = new ArrayList<>();
|
||||
readExcelFile(locale, dateFormat);
|
||||
return importEntity(dateFormat);
|
||||
public Count process(final Workbook workbook, final String locale, final String dateFormat) {
|
||||
|
||||
List<JournalEntryData> glTransactions = readExcelFile(workbook, locale, dateFormat);
|
||||
return importEntity(workbook, glTransactions, 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 prevTransactionId = null;
|
||||
JournalEntryData journalEntry = null;
|
||||
LocalDate transactionDate = null;
|
||||
|
||||
Sheet addJournalEntriesSheet = workbook.getSheet(TemplatePopulateImportConstants.JOURNAL_ENTRY_SHEET_NAME);
|
||||
Integer noOfEntries = ImportHandlerUtils.getNumberOfRows(addJournalEntriesSheet, 4);
|
||||
@@ -120,22 +114,20 @@ public class JournalEntriesImportHandler implements ImportHandler {
|
||||
}
|
||||
}
|
||||
} else {
|
||||
|
||||
if (journalEntry != null) {
|
||||
gltransaction.add(journalEntry);
|
||||
journalEntry = null;
|
||||
glTransactions.add(journalEntry);
|
||||
}
|
||||
|
||||
journalEntry = readAddJournalEntries(row, locale, dateFormat);
|
||||
|
||||
journalEntry = readAddJournalEntries(workbook, row, transactionDate, locale, dateFormat);
|
||||
}
|
||||
prevTransactionId = currentTransactionId;
|
||||
}
|
||||
// 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);
|
||||
if (transactionDateCheck != null) {
|
||||
transactionDate = transactionDateCheck;
|
||||
@@ -147,8 +139,8 @@ public class JournalEntriesImportHandler implements ImportHandler {
|
||||
Long paymentTypeId = ImportHandlerUtils.getIdByName(workbook.getSheet(TemplatePopulateImportConstants.EXTRAS_SHEET_NAME),
|
||||
paymentType);
|
||||
String currencyName = ImportHandlerUtils.readAsString(JournalEntryConstants.CURRENCY_NAME_COL, row);
|
||||
String currencyCode = ImportHandlerUtils
|
||||
.getCodeByName(workbook.getSheet(TemplatePopulateImportConstants.EXTRAS_SHEET_NAME), currencyName).toString();
|
||||
String currencyCode = ImportHandlerUtils.getCodeByName(workbook.getSheet(TemplatePopulateImportConstants.EXTRAS_SHEET_NAME),
|
||||
currencyName);
|
||||
String glAccountNameCredit = ImportHandlerUtils.readAsString(JournalEntryConstants.GL_ACCOUNT_ID_CREDIT_COL, row);
|
||||
Long glAccountIdCredit = ImportHandlerUtils.getIdByName(workbook.getSheet(TemplatePopulateImportConstants.GL_ACCOUNTS_SHEET_NAME),
|
||||
glAccountNameCredit);
|
||||
@@ -156,8 +148,8 @@ public class JournalEntriesImportHandler implements ImportHandler {
|
||||
Long glAccountIdDebit = ImportHandlerUtils.getIdByName(workbook.getSheet(TemplatePopulateImportConstants.GL_ACCOUNTS_SHEET_NAME),
|
||||
glAccountNameDebit);
|
||||
|
||||
credits = new ArrayList<>();
|
||||
debits = new ArrayList<>();
|
||||
List<CreditDebit> credits = new ArrayList<>();
|
||||
List<CreditDebit> debits = new ArrayList<>();
|
||||
|
||||
// String credit =
|
||||
// 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);
|
||||
int successCount = 0;
|
||||
int errorCount = 0;
|
||||
@@ -202,14 +194,14 @@ public class JournalEntriesImportHandler implements ImportHandler {
|
||||
gsonBuilder.registerTypeAdapter(LocalDate.class, new DateSerializer(dateFormat));
|
||||
gsonBuilder.registerTypeAdapter(CurrencyData.class, new CurrencyDateCodeSerializer());
|
||||
|
||||
for (JournalEntryData transaction : gltransaction) {
|
||||
for (JournalEntryData transaction : glTransactions) {
|
||||
try {
|
||||
String payload = gsonBuilder.create().toJson(transaction);
|
||||
final CommandWrapper commandRequest = new CommandWrapperBuilder() //
|
||||
.createJournalEntry() //
|
||||
.withJson(payload) //
|
||||
.build(); //
|
||||
final CommandProcessingResult result = commandsSourceWritePlatformService.logCommandSource(commandRequest);
|
||||
commandsSourceWritePlatformService.logCommandSource(commandRequest);
|
||||
successCount++;
|
||||
Cell statusCell = addJournalEntriesSheet.getRow(transaction.getRowIndex()).createCell(JournalEntryConstants.STATUS_COL);
|
||||
statusCell.setCellValue(TemplatePopulateImportConstants.STATUS_CELL_IMPORTED);
|
||||
|
||||
+48
-47
@@ -27,6 +27,7 @@ import java.time.LocalDate;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Objects;
|
||||
import org.apache.fineract.commands.domain.CommandWrapper;
|
||||
import org.apache.fineract.commands.service.CommandWrapperBuilder;
|
||||
import org.apache.fineract.commands.service.PortfolioCommandSourceWritePlatformService;
|
||||
@@ -61,14 +62,8 @@ import org.springframework.stereotype.Service;
|
||||
@Service
|
||||
public class LoanImportHandler implements ImportHandler {
|
||||
|
||||
public static final String EMPTY_STR = "";
|
||||
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;
|
||||
|
||||
@Autowired
|
||||
@@ -77,34 +72,35 @@ public class LoanImportHandler implements ImportHandler {
|
||||
}
|
||||
|
||||
@Override
|
||||
public Count process(Workbook workbook, String locale, String dateFormat) {
|
||||
this.workbook = workbook;
|
||||
this.loans = new ArrayList<>();
|
||||
this.approvalDates = new ArrayList<>();
|
||||
this.loanRepayments = new ArrayList<>();
|
||||
this.disbursalDates = new ArrayList<>();
|
||||
this.statuses = new ArrayList<>();
|
||||
readExcelFile(locale, dateFormat);
|
||||
return importEntity(dateFormat);
|
||||
public Count process(final Workbook workbook, final String locale, final String dateFormat) {
|
||||
List<LoanAccountData> loans = new ArrayList<>();
|
||||
List<LoanApprovalData> approvalDates = new ArrayList<>();
|
||||
List<LoanTransactionData> loanRepayments = new ArrayList<>();
|
||||
List<DisbursementData> disbursalDates = new ArrayList<>();
|
||||
List<String> statuses = new ArrayList<>();
|
||||
readExcelFile(workbook, loans, approvalDates, loanRepayments, disbursalDates, statuses, locale, dateFormat);
|
||||
return importEntity(workbook, loans, approvalDates, loanRepayments, disbursalDates, statuses, 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);
|
||||
Integer noOfEntries = ImportHandlerUtils.getNumberOfRows(loanSheet, TemplatePopulateImportConstants.FIRST_COLUMN_INDEX);
|
||||
for (int rowIndex = 1; rowIndex <= noOfEntries; rowIndex++) {
|
||||
Row row;
|
||||
row = loanSheet.getRow(rowIndex);
|
||||
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));
|
||||
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;
|
||||
if (ImportHandlerUtils.readAsDouble(LoanConstants.TOTAL_AMOUNT_REPAID_COL, row) != null) {
|
||||
repaymentAmount = BigDecimal.valueOf(ImportHandlerUtils.readAsDouble(LoanConstants.TOTAL_AMOUNT_REPAID_COL, row));
|
||||
@@ -121,11 +117,11 @@ public class LoanImportHandler implements ImportHandler {
|
||||
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);
|
||||
String linkAccountId = 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) {
|
||||
@@ -134,7 +130,7 @@ public class LoanImportHandler implements ImportHandler {
|
||||
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);
|
||||
if (approvedDate != null) {
|
||||
return LoanApprovalData.importInstance(approvedDate, row.getRowNum(), locale, dateFormat);
|
||||
@@ -143,7 +139,8 @@ public class LoanImportHandler implements ImportHandler {
|
||||
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 status = ImportHandlerUtils.readAsString(LoanConstants.STATUS_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 repaidEvery = ImportHandlerUtils.readAsInt(LoanConstants.REPAID_EVERY_COL, row);
|
||||
String repaidEveryFrequency = ImportHandlerUtils.readAsString(LoanConstants.REPAID_EVERY_FREQUENCY_COL, row);
|
||||
String repaidEveryFrequencyId = "";
|
||||
String repaidEveryFrequencyId = EMPTY_STR;
|
||||
EnumOptionData repaidEveryFrequencyEnums = null;
|
||||
if (repaidEveryFrequency != null) {
|
||||
if (repaidEveryFrequency.equalsIgnoreCase("Days")) {
|
||||
@@ -185,7 +182,7 @@ public class LoanImportHandler implements ImportHandler {
|
||||
String loanTermFrequencyType = ImportHandlerUtils.readAsString(LoanConstants.LOAN_TERM_FREQUENCY_COL, row);
|
||||
EnumOptionData loanTermFrequencyEnum = null;
|
||||
if (loanTermFrequencyType != null) {
|
||||
String loanTermFrequencyId = "";
|
||||
String loanTermFrequencyId = EMPTY_STR;
|
||||
if (loanTermFrequencyType.equalsIgnoreCase("Days")) {
|
||||
loanTermFrequencyId = "0";
|
||||
} 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));
|
||||
}
|
||||
String amortization = ImportHandlerUtils.readAsString(LoanConstants.AMORTIZATION_COL, row);
|
||||
String amortizationId = "";
|
||||
String amortizationId = EMPTY_STR;
|
||||
EnumOptionData amortizationEnumOption = null;
|
||||
if (amortization != null) {
|
||||
if (amortization.equalsIgnoreCase("Equal principal payments")) {
|
||||
@@ -211,7 +208,7 @@ public class LoanImportHandler implements ImportHandler {
|
||||
amortizationEnumOption = new EnumOptionData(null, null, amortizationId);
|
||||
}
|
||||
String interestMethod = ImportHandlerUtils.readAsString(LoanConstants.INTEREST_METHOD_COL, row);
|
||||
String interestMethodId = "";
|
||||
String interestMethodId = EMPTY_STR;
|
||||
EnumOptionData interestMethodEnum = null;
|
||||
if (interestMethod != null) {
|
||||
if (interestMethod.equalsIgnoreCase("Flat")) {
|
||||
@@ -222,7 +219,7 @@ public class LoanImportHandler implements ImportHandler {
|
||||
interestMethodEnum = new EnumOptionData(null, null, interestMethodId);
|
||||
}
|
||||
String interestCalculationPeriod = ImportHandlerUtils.readAsString(LoanConstants.INTEREST_CALCULATION_PERIOD_COL, row);
|
||||
String interestCalculationPeriodId = "";
|
||||
String interestCalculationPeriodId = EMPTY_STR;
|
||||
EnumOptionData interestCalculationPeriodEnum = null;
|
||||
if (interestCalculationPeriod != null) {
|
||||
if (interestCalculationPeriod.equalsIgnoreCase("Daily")) {
|
||||
@@ -385,25 +382,27 @@ public class LoanImportHandler implements ImportHandler {
|
||||
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);
|
||||
int successCount = 0;
|
||||
int errorCount = 0;
|
||||
int progressLevel = 0;
|
||||
String loanId;
|
||||
String errorMessage = "";
|
||||
String errorMessage;
|
||||
for (int i = 0; i < loans.size(); i++) {
|
||||
Row row = loanSheet.getRow(loans.get(i).getRowIndex());
|
||||
Cell errorReportCell = row.createCell(LoanConstants.FAILURE_REPORT_COL);
|
||||
Cell statusCell = row.createCell(LoanConstants.STATUS_COL);
|
||||
CommandProcessingResult result = null;
|
||||
loanId = "";
|
||||
loanId = EMPTY_STR;
|
||||
try {
|
||||
String status = statuses.get(i);
|
||||
progressLevel = getProgressLevel(status);
|
||||
|
||||
if (progressLevel == 0 && loans.get(i) != null) {
|
||||
result = importLoan(i, dateFormat);
|
||||
result = importLoan(loans, i, dateFormat);
|
||||
loanId = result.getLoanId().toString();
|
||||
progressLevel = 1;
|
||||
} else {
|
||||
@@ -411,15 +410,15 @@ public class LoanImportHandler implements ImportHandler {
|
||||
}
|
||||
|
||||
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) {
|
||||
progressLevel = importDisbursalData(result, i, dateFormat);
|
||||
progressLevel = importDisbursalData(approvalDates, disbursalDates, result, i, dateFormat);
|
||||
}
|
||||
|
||||
if (loanRepayments.get(i) != null) {
|
||||
progressLevel = importLoanRepayment(result, i, dateFormat);
|
||||
progressLevel = importLoanRepayment(loanRepayments, result, i, dateFormat);
|
||||
}
|
||||
|
||||
successCount++;
|
||||
@@ -429,7 +428,7 @@ public class LoanImportHandler implements ImportHandler {
|
||||
errorCount++;
|
||||
LOG.error("Problem occurred in importEntity function", 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);
|
||||
}
|
||||
|
||||
private void writeLoanErrorMessage(String loanId, String errorMessage, int progressLevel, Cell statusCell, Cell errorReportCell,
|
||||
Row row) {
|
||||
String status = "";
|
||||
private void writeLoanErrorMessage(final Workbook workbook, final String loanId, final String errorMessage, final int progressLevel,
|
||||
final Cell statusCell, final Cell errorReportCell, final Row row) {
|
||||
String status = EMPTY_STR;
|
||||
if (progressLevel == 0) {
|
||||
status = TemplatePopulateImportConstants.STATUS_CREATION_FAILED;
|
||||
} else if (progressLevel == 1) {
|
||||
@@ -466,7 +465,8 @@ public class LoanImportHandler implements ImportHandler {
|
||||
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.registerTypeAdapter(LocalDate.class, new DateSerializer(dateFormat));
|
||||
JsonObject loanRepaymentJsonob = gsonBuilder.create().toJsonTree(loanRepayments.get(rowIndex)).getAsJsonObject();
|
||||
@@ -482,14 +482,15 @@ public class LoanImportHandler implements ImportHandler {
|
||||
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) {
|
||||
|
||||
DisbursementData disbusalData = disbursalDates.get(rowIndex);
|
||||
String linkAccountId = disbusalData.getLinkAccountId();
|
||||
GsonBuilder gsonBuilder = GoogleGsonSerializerHelper.createGsonBuilder();
|
||||
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);
|
||||
final CommandWrapper commandRequest = new CommandWrapperBuilder() //
|
||||
.disburseLoanToSavingsApplication(result.getLoanId()) //
|
||||
@@ -509,7 +510,8 @@ public class LoanImportHandler implements ImportHandler {
|
||||
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) {
|
||||
GsonBuilder gsonBuilder = GoogleGsonSerializerHelper.createGsonBuilder();
|
||||
gsonBuilder.registerTypeAdapter(LocalDate.class, new DateSerializer(dateFormat));
|
||||
@@ -524,7 +526,7 @@ public class LoanImportHandler implements ImportHandler {
|
||||
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.registerTypeAdapter(LocalDate.class, new DateSerializer(dateFormat));
|
||||
gsonBuilder.registerTypeAdapter(EnumOptionData.class, new EnumOptionDataValueSerializer());
|
||||
@@ -550,8 +552,7 @@ public class LoanImportHandler implements ImportHandler {
|
||||
.createLoanApplication() //
|
||||
.withJson(payload) //
|
||||
.build(); //
|
||||
final CommandProcessingResult result = commandsSourceWritePlatformService.logCommandSource(commandRequest);
|
||||
return result;
|
||||
return commandsSourceWritePlatformService.logCommandSource(commandRequest);
|
||||
}
|
||||
|
||||
private int getProgressLevel(String status) {
|
||||
|
||||
+17
-15
@@ -50,10 +50,9 @@ import org.springframework.stereotype.Service;
|
||||
@Service
|
||||
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 Workbook workbook;
|
||||
private List<LoanTransactionData> loanRepayments;
|
||||
private Long loanAccountId;
|
||||
private final LoanReadPlatformService loanReadPlatformService;
|
||||
|
||||
private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService;
|
||||
@@ -66,29 +65,32 @@ public class LoanRepaymentImportHandler implements ImportHandler {
|
||||
}
|
||||
|
||||
@Override
|
||||
public Count process(Workbook workbook, String locale, String dateFormat) {
|
||||
this.workbook = workbook;
|
||||
this.loanRepayments = new ArrayList<>();
|
||||
readExcelFile(locale, dateFormat);
|
||||
return importEntity(dateFormat);
|
||||
public Count process(final Workbook workbook, final String locale, final String dateFormat) {
|
||||
|
||||
List<LoanTransactionData> loanRepayments = readExcelFile(workbook, locale, dateFormat);
|
||||
return importEntity(workbook, loanRepayments, 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);
|
||||
Integer noOfEntries = ImportHandlerUtils.getNumberOfRows(loanRepaymentSheet, LoanRepaymentConstants.AMOUNT_COL);
|
||||
Long loanAccountId = null;
|
||||
for (int rowIndex = 1; rowIndex <= noOfEntries; rowIndex++) {
|
||||
Row row;
|
||||
row = loanRepaymentSheet.getRow(rowIndex);
|
||||
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);
|
||||
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));
|
||||
}
|
||||
BigDecimal repaymentAmount = null;
|
||||
@@ -105,14 +107,14 @@ public class LoanRepaymentImportHandler implements ImportHandler {
|
||||
Integer receiptNumber = ImportHandlerUtils.readAsInt(LoanRepaymentConstants.RECEIPT_NO_COL, row);
|
||||
Integer bankNumber = ImportHandlerUtils.readAsInt(LoanRepaymentConstants.BANK_NO_COL, row);
|
||||
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);
|
||||
int successCount = 0;
|
||||
int errorCount = 0;
|
||||
String errorMessage = "";
|
||||
String errorMessage;
|
||||
GsonBuilder gsonBuilder = GoogleGsonSerializerHelper.createGsonBuilder();
|
||||
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.ImportHandlerUtils;
|
||||
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.organisation.office.data.OfficeData;
|
||||
import org.apache.poi.ss.usermodel.Cell;
|
||||
@@ -48,8 +47,6 @@ import org.springframework.stereotype.Service;
|
||||
public class OfficeImportHandler implements ImportHandler {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(OfficeImportHandler.class);
|
||||
private List<OfficeData> offices;
|
||||
private Workbook workbook;
|
||||
private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService;
|
||||
|
||||
@Autowired
|
||||
@@ -59,13 +56,12 @@ public class OfficeImportHandler implements ImportHandler {
|
||||
|
||||
@Override
|
||||
public Count process(final Workbook workbook, final String locale, final String dateFormat) {
|
||||
this.offices = new ArrayList<>();
|
||||
this.workbook = workbook;
|
||||
readExcelFile(locale, dateFormat);
|
||||
return importEntity(dateFormat);
|
||||
List<OfficeData> offices = readExcelFile(workbook, locale, dateFormat);
|
||||
return importEntity(workbook, offices, 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);
|
||||
Integer noOfEntries = ImportHandlerUtils.getNumberOfRows(officeSheet, 0);
|
||||
for (int rowIndex = 1; rowIndex <= noOfEntries; rowIndex++) {
|
||||
@@ -75,6 +71,7 @@ public class OfficeImportHandler implements ImportHandler {
|
||||
offices.add(readOffice(row, locale, dateFormat));
|
||||
}
|
||||
}
|
||||
return offices;
|
||||
}
|
||||
|
||||
private OfficeData readOffice(Row row, final String locale, final String dateFormat) {
|
||||
@@ -87,14 +84,14 @@ public class OfficeImportHandler implements ImportHandler {
|
||||
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);
|
||||
GsonBuilder gsonBuilder = GoogleGsonSerializerHelper.createGsonBuilder();
|
||||
gsonBuilder.registerTypeAdapter(LocalDate.class, new DateSerializer(dateFormat));
|
||||
|
||||
int successCount = 0;
|
||||
int errorCount = 0;
|
||||
String errorMessage = "";
|
||||
String errorMessage;
|
||||
for (OfficeData office : offices) {
|
||||
try {
|
||||
String payload = gsonBuilder.create().toJson(office);
|
||||
@@ -102,7 +99,7 @@ public class OfficeImportHandler implements ImportHandler {
|
||||
.createOffice() //
|
||||
.withJson(payload) //
|
||||
.build(); //
|
||||
final CommandProcessingResult result = commandsSourceWritePlatformService.logCommandSource(commandRequest);
|
||||
commandsSourceWritePlatformService.logCommandSource(commandRequest);
|
||||
successCount++;
|
||||
Cell statusCell = officeSheet.getRow(office.getRowIndex()).createCell(OfficeConstants.STATUS_COL);
|
||||
statusCell.setCellValue(TemplatePopulateImportConstants.STATUS_CELL_IMPORTED);
|
||||
@@ -119,8 +116,4 @@ public class OfficeImportHandler implements ImportHandler {
|
||||
TemplatePopulateImportConstants.STATUS_COL_REPORT_HEADER);
|
||||
return Count.instance(successCount, errorCount);
|
||||
}
|
||||
|
||||
public List<OfficeData> getOffices() {
|
||||
return offices;
|
||||
}
|
||||
}
|
||||
|
||||
+49
-47
@@ -54,40 +54,38 @@ import org.springframework.stereotype.Service;
|
||||
@Service
|
||||
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 Workbook workbook;
|
||||
private List<RecurringDepositAccountData> savings;
|
||||
private List<SavingsApproval> approvalDates;
|
||||
private List<SavingsActivation> activationDates;
|
||||
private List<String> statuses;
|
||||
|
||||
private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService;
|
||||
|
||||
@Autowired
|
||||
public RecurringDepositImportHandler(final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService) {
|
||||
this.commandsSourceWritePlatformService = commandsSourceWritePlatformService;
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public Count process(Workbook workbook, String locale, String dateFormat) {
|
||||
this.workbook = workbook;
|
||||
savings = new ArrayList<>();
|
||||
approvalDates = new ArrayList<>();
|
||||
activationDates = new ArrayList<>();
|
||||
statuses = new ArrayList<>();
|
||||
readExcelFile(locale, dateFormat);
|
||||
return importEntity(dateFormat);
|
||||
public Count process(final Workbook workbook, final String locale, final String dateFormat) {
|
||||
List<RecurringDepositAccountData> savings = new ArrayList<>();
|
||||
List<SavingsApproval> approvalDates = new ArrayList<>();
|
||||
List<SavingsActivation> activationDates = new ArrayList<>();
|
||||
List<String> statuses = new ArrayList<>();
|
||||
readExcelFile(workbook, savings, approvalDates, activationDates, statuses, locale, dateFormat);
|
||||
return importEntity(workbook, savings, approvalDates, activationDates, statuses, 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);
|
||||
Integer noOfEntries = ImportHandlerUtils.getNumberOfRows(savingsSheet, TemplatePopulateImportConstants.ROWHEADER_INDEX);
|
||||
for (int rowIndex = 1; rowIndex <= noOfEntries; rowIndex++) {
|
||||
Row row;
|
||||
row = savingsSheet.getRow(rowIndex);
|
||||
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));
|
||||
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);
|
||||
if (activationDate != null) {
|
||||
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);
|
||||
if (approvalDate != null) {
|
||||
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);
|
||||
Long productId = ImportHandlerUtils.getIdByName(workbook.getSheet(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME), productName);
|
||||
@@ -183,13 +182,13 @@ public class RecurringDepositImportHandler implements ImportHandler {
|
||||
Long lockinPeriodFrequencyTypeId = null;
|
||||
EnumOptionData lockinPeriodFrequencyTypeEnum = null;
|
||||
if (lockinPeriodFrequencyType != null) {
|
||||
if (lockinPeriodFrequencyType.equalsIgnoreCase("Days")) {
|
||||
if (lockinPeriodFrequencyType.equalsIgnoreCase(DAYS)) {
|
||||
lockinPeriodFrequencyTypeId = 0L;
|
||||
} else if (lockinPeriodFrequencyType.equalsIgnoreCase("Weeks")) {
|
||||
} else if (lockinPeriodFrequencyType.equalsIgnoreCase(WEEKS)) {
|
||||
lockinPeriodFrequencyTypeId = 1L;
|
||||
} else if (lockinPeriodFrequencyType.equalsIgnoreCase("Months")) {
|
||||
} else if (lockinPeriodFrequencyType.equalsIgnoreCase(MONTHS)) {
|
||||
lockinPeriodFrequencyTypeId = 2L;
|
||||
} else if (lockinPeriodFrequencyType.equalsIgnoreCase("Years")) {
|
||||
} else if (lockinPeriodFrequencyType.equalsIgnoreCase(YEARS)) {
|
||||
lockinPeriodFrequencyTypeId = 3L;
|
||||
}
|
||||
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);
|
||||
Long depositPeriodFrequencyId = null;
|
||||
if (depositPeriodFrequency != null) {
|
||||
if (depositPeriodFrequency.equalsIgnoreCase("Days")) {
|
||||
if (depositPeriodFrequency.equalsIgnoreCase(DAYS)) {
|
||||
depositPeriodFrequencyId = 0L;
|
||||
} else if (depositPeriodFrequency.equalsIgnoreCase("Weeks")) {
|
||||
} else if (depositPeriodFrequency.equalsIgnoreCase(WEEKS)) {
|
||||
depositPeriodFrequencyId = 1L;
|
||||
} else if (depositPeriodFrequency.equalsIgnoreCase("Months")) {
|
||||
} else if (depositPeriodFrequency.equalsIgnoreCase(MONTHS)) {
|
||||
depositPeriodFrequencyId = 2L;
|
||||
} else if (depositPeriodFrequency.equalsIgnoreCase("Years")) {
|
||||
} else if (depositPeriodFrequency.equalsIgnoreCase(YEARS)) {
|
||||
depositPeriodFrequencyId = 3L;
|
||||
}
|
||||
}
|
||||
@@ -218,13 +217,13 @@ public class RecurringDepositImportHandler implements ImportHandler {
|
||||
Long recurringFrequencyTypeId = null;
|
||||
EnumOptionData recurringFrequencyTypeEnum = null;
|
||||
if (recurringFrequencyType != null) {
|
||||
if (recurringFrequencyType.equalsIgnoreCase("Days")) {
|
||||
if (recurringFrequencyType.equalsIgnoreCase(DAYS)) {
|
||||
recurringFrequencyTypeId = 0L;
|
||||
} else if (recurringFrequencyType.equalsIgnoreCase("Weeks")) {
|
||||
} else if (recurringFrequencyType.equalsIgnoreCase(WEEKS)) {
|
||||
recurringFrequencyTypeId = 1L;
|
||||
} else if (recurringFrequencyType.equalsIgnoreCase("Months")) {
|
||||
} else if (recurringFrequencyType.equalsIgnoreCase(MONTHS)) {
|
||||
recurringFrequencyTypeId = 2L;
|
||||
} else if (recurringFrequencyType.equalsIgnoreCase("Years")) {
|
||||
} else if (recurringFrequencyType.equalsIgnoreCase(YEARS)) {
|
||||
recurringFrequencyTypeId = 3L;
|
||||
}
|
||||
recurringFrequencyTypeEnum = new EnumOptionData(recurringFrequencyTypeId, null, null);
|
||||
@@ -272,7 +271,9 @@ public class RecurringDepositImportHandler implements ImportHandler {
|
||||
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);
|
||||
int successCount = 0;
|
||||
int errorCount = 0;
|
||||
@@ -288,7 +289,7 @@ public class RecurringDepositImportHandler implements ImportHandler {
|
||||
progressLevel = getProgressLevel(status);
|
||||
|
||||
if (progressLevel == 0) {
|
||||
CommandProcessingResult result = importSavings(i, dateFormat);
|
||||
CommandProcessingResult result = importSavings(savings, i, dateFormat);
|
||||
savingsId = result.getSavingsId();
|
||||
progressLevel = 1;
|
||||
} else {
|
||||
@@ -297,11 +298,11 @@ public class RecurringDepositImportHandler implements ImportHandler {
|
||||
}
|
||||
|
||||
if (progressLevel <= 1) {
|
||||
progressLevel = importSavingsApproval(savingsId, i, dateFormat);
|
||||
progressLevel = importSavingsApproval(approvalDates, savingsId, i, dateFormat);
|
||||
}
|
||||
|
||||
if (progressLevel <= 2) {
|
||||
progressLevel = importSavingsActivation(savingsId, i, dateFormat);
|
||||
progressLevel = importSavingsActivation(activationDates, savingsId, i, dateFormat);
|
||||
}
|
||||
successCount++;
|
||||
statusCell.setCellValue(TemplatePopulateImportConstants.STATUS_CELL_IMPORTED);
|
||||
@@ -310,15 +311,15 @@ public class RecurringDepositImportHandler implements ImportHandler {
|
||||
errorCount++;
|
||||
LOG.error("Problem occurred in importEntity function", ex);
|
||||
errorMessage = ImportHandlerUtils.getErrorMessage(ex);
|
||||
writeRecurringDepositErrorMessage(savingsId, errorMessage, progressLevel, statusCell, errorReportCell, row);
|
||||
writeRecurringDepositErrorMessage(workbook, savingsId, errorMessage, progressLevel, statusCell, errorReportCell, row);
|
||||
}
|
||||
}
|
||||
setReportHeaders(savingsSheet);
|
||||
return Count.instance(successCount, errorCount);
|
||||
}
|
||||
|
||||
private void writeRecurringDepositErrorMessage(Long savingsId, String errorMessage, int progressLevel, Cell statusCell,
|
||||
Cell errorReportCell, Row row) {
|
||||
private void writeRecurringDepositErrorMessage(final Workbook workbook, final Long savingsId, final String errorMessage,
|
||||
final int progressLevel, final Cell statusCell, final Cell errorReportCell, final Row row) {
|
||||
String status = "";
|
||||
if (progressLevel == 0) {
|
||||
status = TemplatePopulateImportConstants.STATUS_CREATION_FAILED;
|
||||
@@ -337,7 +338,7 @@ public class RecurringDepositImportHandler implements ImportHandler {
|
||||
errorReportCell.setCellValue(errorMessage);
|
||||
}
|
||||
|
||||
private void setReportHeaders(Sheet savingsSheet) {
|
||||
private void setReportHeaders(final Sheet savingsSheet) {
|
||||
savingsSheet.setColumnWidth(RecurringDepositConstants.STATUS_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
|
||||
Row rowHeader = savingsSheet.getRow(TemplatePopulateImportConstants.ROWHEADER_INDEX);
|
||||
ImportHandlerUtils.writeString(RecurringDepositConstants.STATUS_COL, rowHeader, "Status");
|
||||
@@ -345,7 +346,8 @@ public class RecurringDepositImportHandler implements ImportHandler {
|
||||
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) {
|
||||
GsonBuilder gsonBuilder = GoogleGsonSerializerHelper.createGsonBuilder();
|
||||
gsonBuilder.registerTypeAdapter(LocalDate.class, new DateSerializer(dateFormat));
|
||||
@@ -354,12 +356,13 @@ public class RecurringDepositImportHandler implements ImportHandler {
|
||||
.recurringDepositAccountActivation(savingsId)//
|
||||
.withJson(payload) //
|
||||
.build(); //
|
||||
final CommandProcessingResult result = commandsSourceWritePlatformService.logCommandSource(commandRequest);
|
||||
commandsSourceWritePlatformService.logCommandSource(commandRequest);
|
||||
}
|
||||
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) {
|
||||
GsonBuilder gsonBuilder = GoogleGsonSerializerHelper.createGsonBuilder();
|
||||
gsonBuilder.registerTypeAdapter(LocalDate.class, new DateSerializer(dateFormat));
|
||||
@@ -368,12 +371,12 @@ public class RecurringDepositImportHandler implements ImportHandler {
|
||||
.approveRecurringDepositAccountApplication(savingsId)//
|
||||
.withJson(payload) //
|
||||
.build(); //
|
||||
final CommandProcessingResult result = commandsSourceWritePlatformService.logCommandSource(commandRequest);
|
||||
commandsSourceWritePlatformService.logCommandSource(commandRequest);
|
||||
}
|
||||
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.registerTypeAdapter(LocalDate.class, new DateSerializer(dateFormat));
|
||||
gsonBuilder.registerTypeAdapter(EnumOptionData.class, new EnumOptionDataIdSerializer());
|
||||
@@ -384,8 +387,7 @@ public class RecurringDepositImportHandler implements ImportHandler {
|
||||
.createRecurringDepositAccount() //
|
||||
.withJson(payload) //
|
||||
.build(); //
|
||||
final CommandProcessingResult result = commandsSourceWritePlatformService.logCommandSource(commandRequest);
|
||||
return result;
|
||||
return commandsSourceWritePlatformService.logCommandSource(commandRequest);
|
||||
}
|
||||
|
||||
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.helper.DateSerializer;
|
||||
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.serialization.GoogleGsonSerializerHelper;
|
||||
import org.apache.fineract.portfolio.savings.data.SavingsAccountTransactionData;
|
||||
@@ -53,9 +52,6 @@ import org.springframework.stereotype.Service;
|
||||
public class RecurringDepositTransactionImportHandler implements ImportHandler {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(RecurringDepositTransactionImportHandler.class);
|
||||
private Workbook workbook;
|
||||
private List<SavingsAccountTransactionData> savingsTransactions;
|
||||
private String savingsAccountId = "";
|
||||
|
||||
private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService;
|
||||
|
||||
@@ -65,32 +61,32 @@ public class RecurringDepositTransactionImportHandler implements ImportHandler {
|
||||
}
|
||||
|
||||
@Override
|
||||
public Count process(Workbook workbook, String locale, String dateFormat) {
|
||||
this.workbook = workbook;
|
||||
this.savingsTransactions = new ArrayList<>();
|
||||
readExcelFile(locale, dateFormat);
|
||||
return importEntity(dateFormat);
|
||||
public Count process(final Workbook workbook, final String locale, final String dateFormat) {
|
||||
List<SavingsAccountTransactionData> savingsTransactions = readExcelFile(workbook, locale, dateFormat);
|
||||
return importEntity(workbook, savingsTransactions, 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);
|
||||
Integer noOfEntries = ImportHandlerUtils.getNumberOfRows(savingsTransactionSheet, TransactionConstants.AMOUNT_COL);
|
||||
Long savingsAccountId = null;
|
||||
for (int rowIndex = 1; rowIndex <= noOfEntries; rowIndex++) {
|
||||
Row row;
|
||||
row = savingsTransactionSheet.getRow(rowIndex);
|
||||
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) {
|
||||
String savingsAccountIdCheck = null;
|
||||
if (ImportHandlerUtils.readAsLong(TransactionConstants.SAVINGS_ACCOUNT_NO_COL, row) != null) {
|
||||
savingsAccountIdCheck = ImportHandlerUtils.readAsLong(TransactionConstants.SAVINGS_ACCOUNT_NO_COL, row).toString();
|
||||
}
|
||||
if (savingsAccountIdCheck != null) {
|
||||
savingsAccountId = savingsAccountIdCheck;
|
||||
private SavingsAccountTransactionData readSavingsTransaction(final Workbook workbook, final Row row, Long savingsAccountId,
|
||||
final String locale, final String dateFormat) {
|
||||
Long internalSavingsAccountId = ImportHandlerUtils.readAsLong(TransactionConstants.SAVINGS_ACCOUNT_NO_COL, row);
|
||||
|
||||
if (internalSavingsAccountId != null) {
|
||||
savingsAccountId = internalSavingsAccountId;
|
||||
}
|
||||
String transactionType = ImportHandlerUtils.readAsString(TransactionConstants.TRANSACTION_TYPE_COL, row);
|
||||
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 bankNumber = ImportHandlerUtils.readAsString(TransactionConstants.BANK_NO_COL, row);
|
||||
return SavingsAccountTransactionData.importInstance(amount, transactionDate, paymentTypeId, accountNumber, checkNumber, routingCode,
|
||||
receiptNumber, bankNumber, Long.parseLong(savingsAccountId), savingsAccountTransactionEnumData, row.getRowNum(), locale,
|
||||
dateFormat);
|
||||
receiptNumber, bankNumber, savingsAccountId, savingsAccountTransactionEnumData, row.getRowNum(), locale, 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);
|
||||
int successCount = 0;
|
||||
int errorCount = 0;
|
||||
@@ -145,7 +141,7 @@ public class RecurringDepositTransactionImportHandler implements ImportHandler {
|
||||
.withJson(payload) //
|
||||
.build();
|
||||
}
|
||||
final CommandProcessingResult result = commandsSourceWritePlatformService.logCommandSource(commandRequest);
|
||||
commandsSourceWritePlatformService.logCommandSource(commandRequest);
|
||||
successCount++;
|
||||
Cell statusCell = savingsTransactionSheet.getRow(transaction.getRowIndex()).createCell(TransactionConstants.STATUS_COL);
|
||||
statusCell.setCellValue(TemplatePopulateImportConstants.STATUS_CELL_IMPORTED);
|
||||
|
||||
+43
-40
@@ -55,13 +55,13 @@ import org.springframework.stereotype.Service;
|
||||
@Service
|
||||
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 Workbook workbook;
|
||||
private List<SavingsAccountData> savings;
|
||||
private List<SavingsApproval> approvalDates;
|
||||
private List<SavingsActivation> activationDates;
|
||||
private List<String> statuses;
|
||||
|
||||
private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService;
|
||||
|
||||
@Autowired
|
||||
@@ -70,24 +70,24 @@ public class SavingsImportHandler implements ImportHandler {
|
||||
}
|
||||
|
||||
@Override
|
||||
public Count process(Workbook workbook, String locale, String dateFormat) {
|
||||
this.workbook = workbook;
|
||||
this.savings = new ArrayList<>();
|
||||
this.approvalDates = new ArrayList<>();
|
||||
this.activationDates = new ArrayList<>();
|
||||
this.statuses = new ArrayList<>();
|
||||
readExcelFile(locale, dateFormat);
|
||||
return importEntity(dateFormat);
|
||||
public Count process(final Workbook workbook, final String locale, final String dateFormat) {
|
||||
List<SavingsAccountData> savings = new ArrayList<>();
|
||||
List<SavingsApproval> approvalDates = new ArrayList<>();
|
||||
List<SavingsActivation> activationDates = new ArrayList<>();
|
||||
List<String> statuses = new ArrayList<>();
|
||||
readExcelFile(workbook, savings, approvalDates, activationDates, statuses, locale, dateFormat);
|
||||
return importEntity(workbook, savings, approvalDates, activationDates, statuses, 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);
|
||||
Integer noOfEntries = ImportHandlerUtils.getNumberOfRows(savingsSheet, TemplatePopulateImportConstants.FIRST_COLUMN_INDEX);
|
||||
for (int rowIndex = 1; rowIndex <= noOfEntries; rowIndex++) {
|
||||
Row row;
|
||||
row = savingsSheet.getRow(rowIndex);
|
||||
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));
|
||||
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);
|
||||
Long productId = ImportHandlerUtils.getIdByName(workbook.getSheet(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME), productName);
|
||||
String fieldOfficerName = ImportHandlerUtils.readAsString(SavingsConstants.FIELD_OFFICER_NAME_COL, row);
|
||||
@@ -129,15 +130,15 @@ public class SavingsImportHandler implements ImportHandler {
|
||||
Long interestCompoundingPeriodTypeId = null;
|
||||
EnumOptionData interestCompoundingPeriodTypeEnum = null;
|
||||
if (interestCompoundingPeriodType != null) {
|
||||
if (interestCompoundingPeriodType.equalsIgnoreCase("Daily")) {
|
||||
if (interestCompoundingPeriodType.equalsIgnoreCase(DAILY)) {
|
||||
interestCompoundingPeriodTypeId = 1L;
|
||||
} else if (interestCompoundingPeriodType.equalsIgnoreCase("Monthly")) {
|
||||
} else if (interestCompoundingPeriodType.equalsIgnoreCase(MONTHLY)) {
|
||||
interestCompoundingPeriodTypeId = 4L;
|
||||
} else if (interestCompoundingPeriodType.equalsIgnoreCase("Quarterly")) {
|
||||
} else if (interestCompoundingPeriodType.equalsIgnoreCase(QUARTERLY)) {
|
||||
interestCompoundingPeriodTypeId = 5L;
|
||||
} else if (interestCompoundingPeriodType.equalsIgnoreCase("Semi-Annual")) {
|
||||
} else if (interestCompoundingPeriodType.equalsIgnoreCase(SEMI_ANNUAL)) {
|
||||
interestCompoundingPeriodTypeId = 6L;
|
||||
} else if (interestCompoundingPeriodType.equalsIgnoreCase("Annually")) {
|
||||
} else if (interestCompoundingPeriodType.equalsIgnoreCase(ANNUALLY)) {
|
||||
interestCompoundingPeriodTypeId = 7L;
|
||||
}
|
||||
interestCompoundingPeriodTypeEnum = new EnumOptionData(interestCompoundingPeriodTypeId, null, null);
|
||||
@@ -146,13 +147,13 @@ public class SavingsImportHandler implements ImportHandler {
|
||||
Long interestPostingPeriodTypeId = null;
|
||||
EnumOptionData interestPostingPeriodTypeEnum = null;
|
||||
if (interestPostingPeriodType != null) {
|
||||
if (interestPostingPeriodType.equalsIgnoreCase("Monthly")) {
|
||||
if (interestPostingPeriodType.equalsIgnoreCase(MONTHLY)) {
|
||||
interestPostingPeriodTypeId = 4L;
|
||||
} else if (interestPostingPeriodType.equalsIgnoreCase("Quarterly")) {
|
||||
} else if (interestPostingPeriodType.equalsIgnoreCase(QUARTERLY)) {
|
||||
interestPostingPeriodTypeId = 5L;
|
||||
} else if (interestPostingPeriodType.equalsIgnoreCase("Annually")) {
|
||||
} else if (interestPostingPeriodType.equalsIgnoreCase(ANNUALLY)) {
|
||||
interestPostingPeriodTypeId = 7L;
|
||||
} else if (interestPostingPeriodType.equalsIgnoreCase("BiAnnual")) {
|
||||
} else if (interestPostingPeriodType.equalsIgnoreCase(BI_ANNUAL)) {
|
||||
interestPostingPeriodTypeId = 6L;
|
||||
}
|
||||
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);
|
||||
int successCount = 0;
|
||||
int errorCount = 0;
|
||||
@@ -280,7 +282,7 @@ public class SavingsImportHandler implements ImportHandler {
|
||||
progressLevel = getProgressLevel(status);
|
||||
|
||||
if (progressLevel == 0) {
|
||||
CommandProcessingResult result = importSavings(i, dateFormat);
|
||||
CommandProcessingResult result = importSavings(savings, i, dateFormat);
|
||||
savingsId = result.getSavingsId();
|
||||
progressLevel = 1;
|
||||
} else {
|
||||
@@ -289,11 +291,11 @@ public class SavingsImportHandler implements ImportHandler {
|
||||
}
|
||||
|
||||
if (progressLevel <= 1) {
|
||||
progressLevel = importSavingsApproval(savingsId, i, dateFormat);
|
||||
progressLevel = importSavingsApproval(approvalDates, savingsId, i, dateFormat);
|
||||
}
|
||||
|
||||
if (progressLevel <= 2) {
|
||||
progressLevel = importSavingsActivation(savingsId, i, dateFormat);
|
||||
progressLevel = importSavingsActivation(activationDates, savingsId, i, dateFormat);
|
||||
}
|
||||
successCount++;
|
||||
statusCell.setCellValue(TemplatePopulateImportConstants.STATUS_CELL_IMPORTED);
|
||||
@@ -302,15 +304,15 @@ public class SavingsImportHandler implements ImportHandler {
|
||||
errorCount++;
|
||||
LOG.error("Problem occurred in importEntity function", ex);
|
||||
errorMessage = ImportHandlerUtils.getErrorMessage(ex);
|
||||
writeSavingsErrorMessage(savingsId, errorMessage, progressLevel, statusCell, errorReportCell, row);
|
||||
writeSavingsErrorMessage(workbook, savingsId, errorMessage, progressLevel, statusCell, errorReportCell, row);
|
||||
}
|
||||
}
|
||||
setReportHeaders(savingsSheet);
|
||||
return Count.instance(successCount, errorCount);
|
||||
}
|
||||
|
||||
private void writeSavingsErrorMessage(Long savingsId, String errorMessage, int progressLevel, Cell statusCell, Cell errorReportCell,
|
||||
Row row) {
|
||||
private void writeSavingsErrorMessage(final Workbook workbook, final Long savingsId, final String errorMessage, final int progressLevel,
|
||||
final Cell statusCell, final Cell errorReportCell, final Row row) {
|
||||
String status = "";
|
||||
|
||||
if (progressLevel == 0) {
|
||||
@@ -340,7 +342,8 @@ public class SavingsImportHandler implements ImportHandler {
|
||||
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) {
|
||||
GsonBuilder gsonBuilder = GoogleGsonSerializerHelper.createGsonBuilder();
|
||||
gsonBuilder.registerTypeAdapter(LocalDate.class, new DateSerializer(dateFormat));
|
||||
@@ -349,12 +352,13 @@ public class SavingsImportHandler implements ImportHandler {
|
||||
.savingsAccountActivation(savingsId)//
|
||||
.withJson(payload) //
|
||||
.build(); //
|
||||
final CommandProcessingResult result = commandsSourceWritePlatformService.logCommandSource(commandRequest);
|
||||
commandsSourceWritePlatformService.logCommandSource(commandRequest);
|
||||
}
|
||||
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) {
|
||||
GsonBuilder gsonBuilder = GoogleGsonSerializerHelper.createGsonBuilder();
|
||||
gsonBuilder.registerTypeAdapter(LocalDate.class, new DateSerializer(dateFormat));
|
||||
@@ -363,12 +367,12 @@ public class SavingsImportHandler implements ImportHandler {
|
||||
.approveSavingsAccountApplication(savingsId)//
|
||||
.withJson(payload) //
|
||||
.build(); //
|
||||
final CommandProcessingResult result = commandsSourceWritePlatformService.logCommandSource(commandRequest);
|
||||
commandsSourceWritePlatformService.logCommandSource(commandRequest);
|
||||
}
|
||||
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.registerTypeAdapter(LocalDate.class, new DateSerializer(dateFormat));
|
||||
gsonBuilder.registerTypeAdapter(EnumOptionData.class, new EnumOptionDataIdSerializer());
|
||||
@@ -379,8 +383,7 @@ public class SavingsImportHandler implements ImportHandler {
|
||||
.createSavingsAccount() //
|
||||
.withJson(payload) //
|
||||
.build(); //
|
||||
final CommandProcessingResult result = commandsSourceWritePlatformService.logCommandSource(commandRequest);
|
||||
return result;
|
||||
return commandsSourceWritePlatformService.logCommandSource(commandRequest);
|
||||
}
|
||||
|
||||
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.helper.DateSerializer;
|
||||
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.portfolio.savings.data.SavingsAccountTransactionData;
|
||||
import org.apache.fineract.portfolio.savings.data.SavingsAccountTransactionEnumData;
|
||||
@@ -51,11 +50,12 @@ import org.springframework.stereotype.Service;
|
||||
@Service
|
||||
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 Workbook workbook;
|
||||
private List<SavingsAccountTransactionData> savingsTransactions;
|
||||
private String savingsAccountId = "";
|
||||
|
||||
private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService;
|
||||
|
||||
@Autowired
|
||||
@@ -64,30 +64,30 @@ public class SavingsTransactionImportHandler implements ImportHandler {
|
||||
}
|
||||
|
||||
@Override
|
||||
public Count process(Workbook workbook, String locale, String dateFormat) {
|
||||
this.workbook = workbook;
|
||||
this.savingsTransactions = new ArrayList<>();
|
||||
readExcelFile(locale, dateFormat);
|
||||
return importEntity(dateFormat);
|
||||
public Count process(final Workbook workbook, final String locale, final String dateFormat) {
|
||||
List<SavingsAccountTransactionData> savingsTransactions = readExcelFile(workbook, locale, dateFormat);
|
||||
return importEntity(workbook, savingsTransactions, 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);
|
||||
Integer noOfEntries = ImportHandlerUtils.getNumberOfRows(savingsTransactionSheet, TransactionConstants.AMOUNT_COL);
|
||||
Long savingsAccountId = null;
|
||||
for (int rowIndex = 1; rowIndex <= noOfEntries; rowIndex++) {
|
||||
Row row;
|
||||
row = savingsTransactionSheet.getRow(rowIndex);
|
||||
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) {
|
||||
String savingsAccountIdCheck = null;
|
||||
if (ImportHandlerUtils.readAsLong(TransactionConstants.SAVINGS_ACCOUNT_NO_COL, row) != null) {
|
||||
savingsAccountIdCheck = ImportHandlerUtils.readAsLong(TransactionConstants.SAVINGS_ACCOUNT_NO_COL, row).toString();
|
||||
}
|
||||
private SavingsAccountTransactionData readSavingsTransaction(final Workbook workbook, final Row row, Long savingsAccountId,
|
||||
final String locale, final String dateFormat) {
|
||||
Long savingsAccountIdCheck = ImportHandlerUtils.readAsLong(TransactionConstants.SAVINGS_ACCOUNT_NO_COL, row);
|
||||
|
||||
if (savingsAccountIdCheck != null) {
|
||||
savingsAccountId = savingsAccountIdCheck;
|
||||
}
|
||||
@@ -110,12 +110,12 @@ public class SavingsTransactionImportHandler implements ImportHandler {
|
||||
String receiptNumber = ImportHandlerUtils.readAsString(TransactionConstants.RECEIPT_NO_COL, row);
|
||||
String bankNumber = ImportHandlerUtils.readAsString(TransactionConstants.BANK_NO_COL, row);
|
||||
return SavingsAccountTransactionData.importInstance(amount, transactionDate, paymentTypeId, accountNumber, checkNumber, routingCode,
|
||||
receiptNumber, bankNumber, Long.parseLong(savingsAccountId), savingsAccountTransactionEnumData, row.getRowNum(), locale,
|
||||
dateFormat);
|
||||
receiptNumber, bankNumber, savingsAccountId, savingsAccountTransactionEnumData, row.getRowNum(), locale, 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);
|
||||
int successCount = 0;
|
||||
int errorCount = 0;
|
||||
@@ -127,24 +127,24 @@ public class SavingsTransactionImportHandler implements ImportHandler {
|
||||
for (SavingsAccountTransactionData transaction : savingsTransactions) {
|
||||
try {
|
||||
JsonObject savingsTransactionJsonob = gsonBuilder.create().toJsonTree(transaction).getAsJsonObject();
|
||||
savingsTransactionJsonob.remove("transactionType");
|
||||
savingsTransactionJsonob.remove("reversed");
|
||||
savingsTransactionJsonob.remove("interestedPostedAsOn");
|
||||
savingsTransactionJsonob.remove(TRANSACTION_TYPE);
|
||||
savingsTransactionJsonob.remove(REVERSED);
|
||||
savingsTransactionJsonob.remove(INTERESTED_POSTED_AS_ON);
|
||||
String payload = savingsTransactionJsonob.toString();
|
||||
CommandWrapper commandRequest = null;
|
||||
if (transaction.getTransactionType().getValue().equals("Withdrawal")) {
|
||||
if (transaction.getTransactionType().getValue().equals(WITHDRAWAL)) {
|
||||
commandRequest = new CommandWrapperBuilder() //
|
||||
.savingsAccountWithdrawal(transaction.getSavingsAccountId()) //
|
||||
.withJson(payload) //
|
||||
.build(); //
|
||||
|
||||
} else if (transaction.getTransactionType().getValue().equals("Deposit")) {
|
||||
} else if (transaction.getTransactionType().getValue().equals(DEPOSIT)) {
|
||||
commandRequest = new CommandWrapperBuilder() //
|
||||
.savingsAccountDeposit(transaction.getSavingsAccountId()) //
|
||||
.withJson(payload) //
|
||||
.build();
|
||||
}
|
||||
final CommandProcessingResult result = commandsSourceWritePlatformService.logCommandSource(commandRequest);
|
||||
commandsSourceWritePlatformService.logCommandSource(commandRequest);
|
||||
successCount++;
|
||||
Cell statusCell = savingsTransactionSheet.getRow(transaction.getRowIndex()).createCell(TransactionConstants.STATUS_COL);
|
||||
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.ImportHandlerUtils;
|
||||
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.portfolio.shareaccounts.data.ShareAccountChargeData;
|
||||
import org.apache.fineract.portfolio.shareaccounts.data.ShareAccountData;
|
||||
@@ -49,11 +48,10 @@ import org.springframework.stereotype.Service;
|
||||
@Service
|
||||
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 Workbook workbook;
|
||||
private List<ShareAccountData> shareAccountDataList;
|
||||
private List<String> statuses;
|
||||
|
||||
private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService;
|
||||
|
||||
@Autowired
|
||||
@@ -62,27 +60,28 @@ public class SharedAccountImportHandler implements ImportHandler {
|
||||
}
|
||||
|
||||
@Override
|
||||
public Count process(Workbook workbook, String locale, String dateFormat) {
|
||||
this.workbook = workbook;
|
||||
this.shareAccountDataList = new ArrayList<>();
|
||||
statuses = new ArrayList<String>();
|
||||
readExcelFile(locale, dateFormat);
|
||||
return importEntity(dateFormat);
|
||||
public Count process(final Workbook workbook, final String locale, final String dateFormat) {
|
||||
List<ShareAccountData> shareAccountDataList = new ArrayList<>();
|
||||
List<String> statuses = new ArrayList<>();
|
||||
readExcelFile(workbook, shareAccountDataList, statuses, locale, dateFormat);
|
||||
return importEntity(workbook, shareAccountDataList, 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);
|
||||
Integer noOfEntries = ImportHandlerUtils.getNumberOfRows(sharedAccountsSheet, TemplatePopulateImportConstants.FIRST_COLUMN_INDEX);
|
||||
for (int rowIndex = 1; rowIndex <= noOfEntries; rowIndex++) {
|
||||
Row row;
|
||||
row = sharedAccountsSheet.getRow(rowIndex);
|
||||
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);
|
||||
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<>();
|
||||
for (int cellNo = SharedAccountsConstants.CHARGES_NAME_1_COL; cellNo < SharedAccountsConstants.CHARGES_NAME_3_COL; cellNo += 2) {
|
||||
String chargeName = ImportHandlerUtils.readAsString(cellNo, row);
|
||||
if (chargeName == null || chargeName.equals("0")) {
|
||||
if (chargeName == null || chargeName.equals(ZERO)) {
|
||||
break;
|
||||
}
|
||||
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);
|
||||
}
|
||||
|
||||
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);
|
||||
int successCount = 0;
|
||||
int errorCount = 0;
|
||||
String errorMessage = "";
|
||||
String errorMessage;
|
||||
GsonBuilder gsonBuilder = GoogleGsonSerializerHelper.createGsonBuilder();
|
||||
gsonBuilder.registerTypeAdapter(LocalDate.class, new DateSerializer(dateFormat));
|
||||
|
||||
@@ -161,10 +160,10 @@ public class SharedAccountImportHandler implements ImportHandler {
|
||||
try {
|
||||
String payload = gsonBuilder.create().toJson(shareAccountData);
|
||||
final CommandWrapper commandRequest = new CommandWrapperBuilder() //
|
||||
.createAccount("share")//
|
||||
.createAccount(SHARE)//
|
||||
.withJson(payload) //
|
||||
.build(); //
|
||||
final CommandProcessingResult result = commandsSourceWritePlatformService.logCommandSource(commandRequest);
|
||||
commandsSourceWritePlatformService.logCommandSource(commandRequest);
|
||||
successCount++;
|
||||
Cell statusCell = sharedAccountsSheet.getRow(shareAccountData.getRowIndex()).createCell(SharedAccountsConstants.STATUS_COL);
|
||||
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.ImportHandlerUtils;
|
||||
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.organisation.staff.data.StaffData;
|
||||
import org.apache.poi.ss.usermodel.Cell;
|
||||
@@ -48,8 +47,6 @@ import org.springframework.stereotype.Service;
|
||||
public class StaffImportHandler implements ImportHandler {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(StaffImportHandler.class);
|
||||
private List<StaffData> staffList;
|
||||
private Workbook workbook;
|
||||
|
||||
private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService;
|
||||
|
||||
@@ -59,27 +56,26 @@ public class StaffImportHandler implements ImportHandler {
|
||||
}
|
||||
|
||||
@Override
|
||||
public Count process(Workbook workbook, String locale, String dateFormat) {
|
||||
this.workbook = workbook;
|
||||
this.staffList = new ArrayList<>();
|
||||
readExcelFile(locale, dateFormat);
|
||||
return importEntity(dateFormat);
|
||||
public Count process(final Workbook workbook, final String locale, final String dateFormat) {
|
||||
List<StaffData> staffList = readExcelFile(workbook, locale, dateFormat);
|
||||
return importEntity(workbook, staffList, 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);
|
||||
Integer noOfEntries = ImportHandlerUtils.getNumberOfRows(staffSheet, TemplatePopulateImportConstants.FIRST_COLUMN_INDEX);
|
||||
for (int rowIndex = 1; rowIndex <= noOfEntries; rowIndex++) {
|
||||
Row row;
|
||||
row = staffSheet.getRow(rowIndex);
|
||||
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);
|
||||
Long officeId = ImportHandlerUtils.getIdByName(workbook.getSheet(TemplatePopulateImportConstants.OFFICE_SHEET_NAME), officeName);
|
||||
String firstName = ImportHandlerUtils.readAsString(StaffConstants.FIRST_NAME_COL, row);
|
||||
@@ -97,11 +93,11 @@ public class StaffImportHandler implements ImportHandler {
|
||||
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);
|
||||
int successCount = 0;
|
||||
int errorCount = 0;
|
||||
String errorMessage = "";
|
||||
String errorMessage;
|
||||
GsonBuilder gsonBuilder = GoogleGsonSerializerHelper.createGsonBuilder();
|
||||
gsonBuilder.registerTypeAdapter(LocalDate.class, new DateSerializer(dateFormat));
|
||||
for (StaffData staff : staffList) {
|
||||
@@ -111,7 +107,7 @@ public class StaffImportHandler implements ImportHandler {
|
||||
.createStaff()//
|
||||
.withJson(payload) //
|
||||
.build(); //
|
||||
final CommandProcessingResult result = commandsSourceWritePlatformService.logCommandSource(commandRequest);
|
||||
commandsSourceWritePlatformService.logCommandSource(commandRequest);
|
||||
successCount++;
|
||||
Cell statusCell = staffSheet.getRow(staff.getRowIndex()).createCell(StaffConstants.STATUS_COL);
|
||||
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.importhandler.ImportHandler;
|
||||
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.useradministration.data.AppUserData;
|
||||
import org.apache.poi.ss.usermodel.Cell;
|
||||
@@ -47,9 +46,6 @@ import org.springframework.stereotype.Service;
|
||||
public class UserImportHandler implements ImportHandler {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(UserImportHandler.class);
|
||||
private Workbook workbook;
|
||||
private List<AppUserData> users;
|
||||
private List<String> statuses;
|
||||
|
||||
private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService;
|
||||
|
||||
@@ -59,27 +55,27 @@ public class UserImportHandler implements ImportHandler {
|
||||
}
|
||||
|
||||
@Override
|
||||
public Count process(Workbook workbook, String locale, String dateFormat) {
|
||||
this.workbook = workbook;
|
||||
users = new ArrayList<>();
|
||||
statuses = new ArrayList<>();
|
||||
readExcelFile();
|
||||
return importEntity(dateFormat);
|
||||
public Count process(final Workbook workbook, final String locale, final String dateFormat) {
|
||||
List<String> statuses = new ArrayList<>();
|
||||
List<AppUserData> users = readExcelFile(workbook, statuses);
|
||||
return importEntity(workbook, users);
|
||||
}
|
||||
|
||||
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);
|
||||
Integer noOfEntries = ImportHandlerUtils.getNumberOfRows(usersSheet, TemplatePopulateImportConstants.FIRST_COLUMN_INDEX);
|
||||
for (int rowIndex = 1; rowIndex <= noOfEntries; rowIndex++) {
|
||||
Row row;
|
||||
row = usersSheet.getRow(rowIndex);
|
||||
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);
|
||||
Long officeId = ImportHandlerUtils.getIdByName(workbook.getSheet(TemplatePopulateImportConstants.OFFICE_SHEET_NAME), officeName);
|
||||
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);
|
||||
int successCount = 0;
|
||||
int errorCount = 0;
|
||||
String errorMessage = "";
|
||||
String errorMessage;
|
||||
GsonBuilder gsonBuilder = GoogleGsonSerializerHelper.createGsonBuilder();
|
||||
for (AppUserData user : users) {
|
||||
try {
|
||||
@@ -123,7 +119,7 @@ public class UserImportHandler implements ImportHandler {
|
||||
.createUser() //
|
||||
.withJson(payload) //
|
||||
.build(); //
|
||||
final CommandProcessingResult result = commandsSourceWritePlatformService.logCommandSource(commandRequest);
|
||||
commandsSourceWritePlatformService.logCommandSource(commandRequest);
|
||||
successCount++;
|
||||
Cell statusCell = userSheet.getRow(user.getRowIndex()).createCell(UserConstants.STATUS_COL);
|
||||
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.ApiResponses;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import javax.ws.rs.Consumes;
|
||||
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.")
|
||||
public class CacheApiResource {
|
||||
|
||||
private static final Set<String> RESPONSE_DATA_PARAMETERS = new HashSet<>(Arrays.asList("id"));
|
||||
private final String resourceNameForPermissions = "CACHE";
|
||||
private static final Set<String> RESPONSE_DATA_PARAMETERS = new HashSet<>(List.of("id"));
|
||||
private static final String RESOURCE_NAME_FOR_PERMISSIONS = "CACHE";
|
||||
|
||||
private final PlatformSecurityContext context;
|
||||
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)))) })
|
||||
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();
|
||||
|
||||
|
||||
+2
-4
@@ -49,9 +49,8 @@ import org.springframework.stereotype.Component;
|
||||
@Scope("singleton")
|
||||
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 EmailReadPlatformService readPlatformService;
|
||||
private final DefaultToApiJsonSerializer<EmailConfigurationData> toApiJsonSerializer;
|
||||
private final ApiRequestParameterHelper apiRequestParameterHelper;
|
||||
private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService;
|
||||
@@ -64,7 +63,6 @@ public class EmailConfigurationApiResource {
|
||||
final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService,
|
||||
final EmailConfigurationReadPlatformService emailConfigurationReadPlatformService) {
|
||||
this.context = context;
|
||||
this.readPlatformService = readPlatformService;
|
||||
this.toApiJsonSerializer = toApiJsonSerializer;
|
||||
this.apiRequestParameterHelper = apiRequestParameterHelper;
|
||||
this.commandsSourceWritePlatformService = commandsSourceWritePlatformService;
|
||||
@@ -73,7 +71,7 @@ public class EmailConfigurationApiResource {
|
||||
|
||||
@GET
|
||||
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();
|
||||
|
||||
|
||||
+3
-3
@@ -73,7 +73,7 @@ public class CodeValuesApiResource {
|
||||
Arrays.asList(CodevalueJSONinputParams.CODEVALUE_ID.getValue(), CodevalueJSONinputParams.NAME.getValue(),
|
||||
CodevalueJSONinputParams.POSITION.getValue(), CodevalueJSONinputParams.IS_MANDATORY.getValue(),
|
||||
CodevalueJSONinputParams.DESCRIPTION.getValue()));
|
||||
private final String resourceNameForPermissions = "CODEVALUE";
|
||||
private static final String RESOURCE_NAME_FOR_PERMISSIONS = "CODEVALUE";
|
||||
|
||||
private final PlatformSecurityContext context;
|
||||
private final CodeValueReadPlatformService readPlatformService;
|
||||
@@ -102,7 +102,7 @@ public class CodeValuesApiResource {
|
||||
public String retrieveAllCodeValues(@Context final UriInfo uriInfo,
|
||||
@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);
|
||||
|
||||
@@ -122,7 +122,7 @@ public class CodeValuesApiResource {
|
||||
@PathParam("codeValueId") @Parameter(description = "codeValueId") final Long codeValueId,
|
||||
@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);
|
||||
|
||||
|
||||
+2
-2
@@ -68,7 +68,7 @@ public class CodesApiResource {
|
||||
* 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 final String resourceNameForPermissions = "CODE";
|
||||
private static final String RESOURCE_NAME_FOR_PERMISSIONS = "CODE";
|
||||
|
||||
private final PlatformSecurityContext context;
|
||||
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)))) })
|
||||
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();
|
||||
|
||||
|
||||
+3
-4
@@ -22,7 +22,6 @@ import com.google.gson.JsonElement;
|
||||
import com.google.gson.reflect.TypeToken;
|
||||
import java.lang.reflect.Type;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
@@ -45,7 +44,7 @@ public final class CodeCommandFromApiJsonDeserializer {
|
||||
/**
|
||||
* 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;
|
||||
|
||||
@Autowired
|
||||
@@ -59,7 +58,7 @@ public final class CodeCommandFromApiJsonDeserializer {
|
||||
}
|
||||
|
||||
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 DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("code");
|
||||
@@ -78,7 +77,7 @@ public final class CodeCommandFromApiJsonDeserializer {
|
||||
}
|
||||
|
||||
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 DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("code");
|
||||
|
||||
+3
-3
@@ -44,7 +44,7 @@ public final class CodeValueCommandFromApiJsonDeserializer {
|
||||
/**
|
||||
* 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;
|
||||
|
||||
@Autowired
|
||||
@@ -58,7 +58,7 @@ public final class CodeValueCommandFromApiJsonDeserializer {
|
||||
}
|
||||
|
||||
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 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();
|
||||
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParameters);
|
||||
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, SUPPORTED_PARAMETERS);
|
||||
|
||||
final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
|
||||
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 final String resourceNameForPermissions = "CONFIGURATION";
|
||||
private static final String RESOURCE_NAME_FOR_PERMISSIONS = "CONFIGURATION";
|
||||
|
||||
private final PlatformSecurityContext context;
|
||||
private final ConfigurationReadPlatformService readPlatformService;
|
||||
@@ -106,7 +106,7 @@ public class GlobalConfigurationApiResource {
|
||||
public String retrieveConfiguration(@Context final UriInfo uriInfo,
|
||||
@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);
|
||||
|
||||
@@ -125,7 +125,7 @@ public class GlobalConfigurationApiResource {
|
||||
public String retrieveOne(@PathParam("configId") @Parameter(description = "configId") final Long configId,
|
||||
@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);
|
||||
|
||||
@@ -143,7 +143,7 @@ public class GlobalConfigurationApiResource {
|
||||
@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) {
|
||||
|
||||
this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions);
|
||||
this.context.authenticatedUser().validateHasReadPermission(RESOURCE_NAME_FOR_PERMISSIONS);
|
||||
|
||||
final GlobalConfigurationPropertyData configurationData = this.readPlatformService.retrieveGlobalConfiguration(name);
|
||||
|
||||
|
||||
+16
-26
@@ -36,10 +36,10 @@ import org.springframework.stereotype.Component;
|
||||
@Component
|
||||
public class ExternalServicesPropertiesCommandFromApiJsonDeserializer {
|
||||
|
||||
private final Set<String> s3SupportedParameters = S3JSONinputParams.getAllValues();
|
||||
private final Set<String> smtpSupportedParameters = SMTPJSONinputParams.getAllValues();
|
||||
private final Set<String> smsSupportedParameters = SMSJSONinputParams.getAllValues();
|
||||
private final Set<String> notificationSupportedParameters = NotificationJSONinputParams.getAllValues();
|
||||
private static final Set<String> S3_SUPPORTED_PARAMETERS = S3JSONinputParams.getAllValues();
|
||||
private static final Set<String> SMTP_SUPPORTED_PARAMETERS = SMTPJSONinputParams.getAllValues();
|
||||
private static final Set<String> SMS_SUPPORTED_PARAMETERS = SMSJSONinputParams.getAllValues();
|
||||
private static final Set<String> NOTIFICATION_SUPPORTED_PARAMETERS = NotificationJSONinputParams.getAllValues();
|
||||
private final FromJsonHelper fromApiJsonHelper;
|
||||
|
||||
@Autowired
|
||||
@@ -52,34 +52,24 @@ public class ExternalServicesPropertiesCommandFromApiJsonDeserializer {
|
||||
throw new InvalidJsonException();
|
||||
}
|
||||
|
||||
final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType();
|
||||
final Type typeOfMap = new TypeToken<Map<String, Object>>() {
|
||||
|
||||
}.getType();
|
||||
switch (externalServiceName) {
|
||||
case "S3":
|
||||
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.s3SupportedParameters);
|
||||
break;
|
||||
|
||||
case "SMTP":
|
||||
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);
|
||||
case "S3" -> this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, S3_SUPPORTED_PARAMETERS);
|
||||
case "SMTP" -> this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, SMTP_SUPPORTED_PARAMETERS);
|
||||
case "SMS" -> this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, SMS_SUPPORTED_PARAMETERS);
|
||||
case "NOTIFICATION" -> this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, NOTIFICATION_SUPPORTED_PARAMETERS);
|
||||
default -> throw new ExternalServiceConfigurationNotFoundException(externalServiceName);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
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);
|
||||
Set<String> keyNames = jsonMap.keySet();
|
||||
return keyNames;
|
||||
return jsonMap.keySet();
|
||||
}
|
||||
}
|
||||
|
||||
+3
-3
@@ -20,8 +20,8 @@ package org.apache.fineract.infrastructure.configuration.serialization;
|
||||
|
||||
import com.google.gson.reflect.TypeToken;
|
||||
import java.lang.reflect.Type;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
@@ -43,7 +43,7 @@ public final class GlobalConfigurationCommandFromApiJsonDeserializer
|
||||
/**
|
||||
* 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;
|
||||
|
||||
@Autowired
|
||||
@@ -59,7 +59,7 @@ public final class GlobalConfigurationCommandFromApiJsonDeserializer
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
+3
-3
@@ -29,14 +29,14 @@ import org.springframework.stereotype.Component;
|
||||
@Component
|
||||
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,
|
||||
final String resourceName) {
|
||||
final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
|
||||
if (parameters.isOrderByRequested() && !supportedOrdeByValues.contains(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(
|
||||
"validation.msg." + resourceName + ".orderBy.value.is.not.supported", defaultUserMessage, "orderBy",
|
||||
parameters.getOrderBy(), supportedOrdeByValues.toString());
|
||||
@@ -45,7 +45,7 @@ public class PaginationParametersDataValidator {
|
||||
|
||||
if (parameters.isSortOrderProvided() && !sortOrderValues.contains(parameters.getSortOrder().toUpperCase())) {
|
||||
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(
|
||||
"validation.msg." + resourceName + ".sortOrder.value.is.not.supported", defaultUserMessage, "sortOrder",
|
||||
parameters.getSortOrder(), sortOrderValues.toString());
|
||||
|
||||
+125
-89
@@ -40,25 +40,57 @@ import org.springframework.stereotype.Component;
|
||||
@Component
|
||||
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_COLUMN_NAME_REGEX_PATTERN = "^[a-zA-Z][a-zA-Z0-9\\-_\\s]{0,}[a-zA-Z0-9]$";
|
||||
/**
|
||||
* The parameters supported for this command.
|
||||
*/
|
||||
private final Set<String> supportedParametersForCreate = new HashSet<>(
|
||||
Arrays.asList("datatableName", "entitySubType", "apptableName", "multiRow", "columns"));
|
||||
private final Set<String> supportedParametersForCreateColumns = new HashSet<>(
|
||||
Arrays.asList("name", "type", "length", "mandatory", "code"));
|
||||
private final Set<String> supportedParametersForUpdate = new HashSet<>(
|
||||
Arrays.asList("apptableName", "entitySubType", "changeColumns", "addColumns", "dropColumns"));
|
||||
private final Set<String> supportedParametersForAddColumns = new HashSet<>(
|
||||
Arrays.asList("name", "type", "length", "mandatory", "after", "code"));
|
||||
private final Set<String> supportedParametersForChangeColumns = new HashSet<>(
|
||||
Arrays.asList("name", "newName", "length", "mandatory", "after", "code", "newCode"));
|
||||
private final Set<String> supportedParametersForDropColumns = new HashSet<>(Arrays.asList("name"));
|
||||
private final Object[] supportedColumnTypes = { "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",
|
||||
"m_savings_product", "m_product_loan" };
|
||||
private static final Set<String> SUPPORTED_PARAMETERS_FOR_CREATE = new HashSet<>(
|
||||
Arrays.asList(DATATABLE_NAME, ENTITY_SUB_TYPE, APPTABLE_NAME, MULTI_ROW, COLUMNS));
|
||||
private static final Set<String> SUPPORTED_PARAMETERS_FOR_CREATE_COLUMNS = new HashSet<>(
|
||||
Arrays.asList(NAME, TYPE, LENGTH, MANDATORY, CODE));
|
||||
private static final Set<String> SUPPORTED_PARAMETERS_FOR_UPDATE = new HashSet<>(
|
||||
Arrays.asList(APPTABLE_NAME, ENTITY_SUB_TYPE, CHANGE_COLUMNS, ADD_COLUMNS, DROP_COLUMNS));
|
||||
private static final Set<String> SUPPORTED_PARAMETERS_FOR_ADD_COLUMNS = new HashSet<>(
|
||||
Arrays.asList(NAME, TYPE, LENGTH, MANDATORY, AFTER, CODE));
|
||||
private static final Set<String> SUPPORTED_PARAMETERS_FOR_CHANGE_COLUMNS = new HashSet<>(
|
||||
Arrays.asList(NAME, NEW_NAME, LENGTH, MANDATORY, AFTER, CODE, NEW_CODE));
|
||||
private static final Set<String> SUPPORTED_PARAMETERS_FOR_DROP_COLUMNS = new HashSet<>(List.of(NAME));
|
||||
private static final Object[] SUPPORTED_COLUMN_TYPES = { STRING, NUMBER, BOOLEAN, DECIMAL, DATE, DATETIME, TEXT, DROPDOWN };
|
||||
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 };
|
||||
|
||||
private final FromJsonHelper fromApiJsonHelper;
|
||||
|
||||
@@ -68,37 +100,37 @@ public class DatatableCommandFromApiJsonDeserializer {
|
||||
}
|
||||
|
||||
private void validateType(final DataValidatorBuilder baseDataValidator, final JsonElement column) {
|
||||
final String type = this.fromApiJsonHelper.extractStringNamed("type", column);
|
||||
baseDataValidator.reset().parameter("type").value(type).notBlank().isOneOfTheseStringValues(this.supportedColumnTypes);
|
||||
final String type = this.fromApiJsonHelper.extractStringNamed(TYPE, column);
|
||||
baseDataValidator.reset().parameter(TYPE).value(type).notBlank().isOneOfTheseStringValues(SUPPORTED_COLUMN_TYPES);
|
||||
|
||||
if (type != null && type.equalsIgnoreCase("String")) {
|
||||
if (this.fromApiJsonHelper.parameterExists("length", column)) {
|
||||
final String lengthStr = this.fromApiJsonHelper.extractStringNamed("length", column);
|
||||
if (this.fromApiJsonHelper.parameterExists(LENGTH, column)) {
|
||||
final String lengthStr = this.fromApiJsonHelper.extractStringNamed(LENGTH, column);
|
||||
if (lengthStr != null && !StringUtils.isWhitespace(lengthStr) && StringUtils.isNumeric(lengthStr)
|
||||
&& StringUtils.isNotBlank(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)) {
|
||||
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)) {
|
||||
baseDataValidator.reset().parameter("length").failWithCode("not.greater.than.zero");
|
||||
baseDataValidator.reset().parameter(LENGTH).failWithCode("not.greater.than.zero");
|
||||
}
|
||||
} 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 {
|
||||
baseDataValidator.reset().parameter("length").mustBeBlankWhenParameterProvidedIs("type", type);
|
||||
baseDataValidator.reset().parameter(LENGTH).mustBeBlankWhenParameterProvidedIs(TYPE, type);
|
||||
}
|
||||
|
||||
final String code = this.fromApiJsonHelper.extractStringNamed("code", column);
|
||||
if (type != null && type.equalsIgnoreCase("Dropdown")) {
|
||||
final String code = this.fromApiJsonHelper.extractStringNamed(CODE, column);
|
||||
if (type != null && type.equalsIgnoreCase(DROPDOWN)) {
|
||||
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 {
|
||||
baseDataValidator.reset().parameter("code").value(code).cantBeBlankWhenParameterProvidedIs("type", type);
|
||||
baseDataValidator.reset().parameter(CODE).value(code).cantBeBlankWhenParameterProvidedIs(TYPE, type);
|
||||
}
|
||||
} 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();
|
||||
}
|
||||
|
||||
final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType();
|
||||
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParametersForCreate);
|
||||
final Type typeOfMap = new TypeToken<Map<String, Object>>() {
|
||||
|
||||
}.getType();
|
||||
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, SUPPORTED_PARAMETERS_FOR_CREATE);
|
||||
|
||||
final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
|
||||
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("datatable");
|
||||
|
||||
final JsonElement element = this.fromApiJsonHelper.parse(json);
|
||||
|
||||
final String datatableName = this.fromApiJsonHelper.extractStringNamed("datatableName", element);
|
||||
baseDataValidator.reset().parameter("datatableName").value(datatableName).notBlank().notExceedingLengthOf(50)
|
||||
final String datatableName = this.fromApiJsonHelper.extractStringNamed(DATATABLE_NAME, element);
|
||||
baseDataValidator.reset().parameter(DATATABLE_NAME).value(datatableName).notBlank().notExceedingLengthOf(50)
|
||||
.matchesRegularExpression(DATATABLE_NAME_REGEX_PATTERN);
|
||||
|
||||
final String apptableName = this.fromApiJsonHelper.extractStringNamed("apptableName", element);
|
||||
baseDataValidator.reset().parameter("apptableName").value(apptableName).notBlank().notExceedingLengthOf(50)
|
||||
.isOneOfTheseValues(this.supportedApptableNames);
|
||||
final String apptableName = this.fromApiJsonHelper.extractStringNamed(APPTABLE_NAME, element);
|
||||
baseDataValidator.reset().parameter(APPTABLE_NAME).value(apptableName).notBlank().notExceedingLengthOf(50)
|
||||
.isOneOfTheseValues(SUPPORTED_APPTABLE_NAMES);
|
||||
|
||||
if ("m_client".equals(apptableName)) {
|
||||
String entitySubType = this.fromApiJsonHelper.extractStringNamed("entitySubType", element);
|
||||
baseDataValidator.reset().parameter("entitySubType").value(entitySubType).notBlank(); // Person or Entity
|
||||
if (M_CLIENT.equals(apptableName)) {
|
||||
String entitySubType = this.fromApiJsonHelper.extractStringNamed(ENTITY_SUB_TYPE, element);
|
||||
baseDataValidator.reset().parameter(ENTITY_SUB_TYPE).value(entitySubType).notBlank(); // Person or Entity
|
||||
}
|
||||
final String fkColumnName = (apptableName != null) ? apptableName.substring(2) + "_id" : "";
|
||||
|
||||
final Boolean multiRow = this.fromApiJsonHelper.extractBooleanNamed("multiRow", element);
|
||||
baseDataValidator.reset().parameter("multiRow").value(multiRow).ignoreIfNull().notBlank().isOneOfTheseValues(true, false);
|
||||
final Boolean multiRow = this.fromApiJsonHelper.extractBooleanNamed(MULTI_ROW, element);
|
||||
baseDataValidator.reset().parameter(MULTI_ROW).value(multiRow).ignoreIfNull().notBlank().isOneOfTheseValues(true, false);
|
||||
|
||||
final JsonArray columns = this.fromApiJsonHelper.extractJsonArrayNamed("columns", element);
|
||||
baseDataValidator.reset().parameter("columns").value(columns).notNull().jsonArrayNotEmpty();
|
||||
final JsonArray columns = this.fromApiJsonHelper.extractJsonArrayNamed(COLUMNS, element);
|
||||
baseDataValidator.reset().parameter(COLUMNS).value(columns).notNull().jsonArrayNotEmpty();
|
||||
|
||||
if (columns != null) {
|
||||
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);
|
||||
baseDataValidator.reset().parameter("name").value(name).notBlank().isNotOneOfTheseValues("id", fkColumnName)
|
||||
final String name = this.fromApiJsonHelper.extractStringNamed(NAME, column);
|
||||
baseDataValidator.reset().parameter(NAME).value(name).notBlank().isNotOneOfTheseValues("id", fkColumnName)
|
||||
.matchesRegularExpression(DATATABLE_COLUMN_NAME_REGEX_PATTERN);
|
||||
|
||||
validateType(baseDataValidator, column);
|
||||
|
||||
final Boolean mandatory = this.fromApiJsonHelper.extractBooleanNamed("mandatory", column);
|
||||
baseDataValidator.reset().parameter("mandatory").value(mandatory).ignoreIfNull().notBlank().isOneOfTheseValues(true, false);
|
||||
final Boolean mandatory = this.fromApiJsonHelper.extractBooleanNamed(MANDATORY, column);
|
||||
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.");
|
||||
}
|
||||
|
||||
final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType();
|
||||
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParametersForUpdate);
|
||||
final Type typeOfMap = new TypeToken<Map<String, Object>>() {
|
||||
|
||||
}.getType();
|
||||
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, SUPPORTED_PARAMETERS_FOR_UPDATE);
|
||||
|
||||
final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
|
||||
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("datatable");
|
||||
|
||||
final JsonElement element = this.fromApiJsonHelper.parse(json);
|
||||
final String apptableName = this.fromApiJsonHelper.extractStringNamed("apptableName", element);
|
||||
baseDataValidator.reset().parameter("apptableName").value(apptableName).ignoreIfNull().notBlank()
|
||||
.isOneOfTheseValues(this.supportedApptableNames);
|
||||
final String apptableName = this.fromApiJsonHelper.extractStringNamed(APPTABLE_NAME, element);
|
||||
baseDataValidator.reset().parameter(APPTABLE_NAME).value(apptableName).ignoreIfNull().notBlank()
|
||||
.isOneOfTheseValues(SUPPORTED_APPTABLE_NAMES);
|
||||
|
||||
if ("m_client".equals(apptableName)) {
|
||||
String entitySubType = this.fromApiJsonHelper.extractStringNamed("entitySubType", element);
|
||||
baseDataValidator.reset().parameter("entitySubType").value(entitySubType).notBlank(); // Person or Entity
|
||||
if (M_CLIENT.equals(apptableName)) {
|
||||
String entitySubType = this.fromApiJsonHelper.extractStringNamed(ENTITY_SUB_TYPE, element);
|
||||
baseDataValidator.reset().parameter(ENTITY_SUB_TYPE).value(entitySubType).notBlank(); // Person or Entity
|
||||
}
|
||||
|
||||
final String fkColumnName = (apptableName != null) ? apptableName.substring(2) + "_id" : "";
|
||||
|
||||
final JsonArray changeColumns = this.fromApiJsonHelper.extractJsonArrayNamed("changeColumns", element);
|
||||
baseDataValidator.reset().parameter("changeColumns").value(changeColumns).ignoreIfNull().jsonArrayNotEmpty();
|
||||
final JsonArray changeColumns = this.fromApiJsonHelper.extractJsonArrayNamed(CHANGE_COLUMNS, element);
|
||||
baseDataValidator.reset().parameter(CHANGE_COLUMNS).value(changeColumns).ignoreIfNull().jsonArrayNotEmpty();
|
||||
|
||||
if (changeColumns != null) {
|
||||
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);
|
||||
baseDataValidator.reset().parameter("name").value(name).notBlank().isNotOneOfTheseValues("id", fkColumnName)
|
||||
final String name = this.fromApiJsonHelper.extractStringNamed(NAME, column);
|
||||
baseDataValidator.reset().parameter(NAME).value(name).notBlank().isNotOneOfTheseValues("id", fkColumnName)
|
||||
.matchesRegularExpression(DATATABLE_COLUMN_NAME_REGEX_PATTERN);
|
||||
|
||||
final String newName = this.fromApiJsonHelper.extractStringNamed("newName", column);
|
||||
baseDataValidator.reset().parameter("newName").value(newName).ignoreIfNull().notBlank().notExceedingLengthOf(50)
|
||||
final String newName = this.fromApiJsonHelper.extractStringNamed(NEW_NAME, column);
|
||||
baseDataValidator.reset().parameter(NEW_NAME).value(newName).ignoreIfNull().notBlank().notExceedingLengthOf(50)
|
||||
.isNotOneOfTheseValues("id", fkColumnName).matchesRegularExpression(DATATABLE_COLUMN_NAME_REGEX_PATTERN);
|
||||
|
||||
if (this.fromApiJsonHelper.parameterExists("length", column)) {
|
||||
final String lengthStr = this.fromApiJsonHelper.extractStringNamed("length", column);
|
||||
if (this.fromApiJsonHelper.parameterExists(LENGTH, column)) {
|
||||
final String lengthStr = this.fromApiJsonHelper.extractStringNamed(LENGTH, column);
|
||||
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 {
|
||||
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);
|
||||
baseDataValidator.reset().parameter("code").value(code).ignoreIfNull().notBlank().notExceedingLengthOf(100)
|
||||
final String code = this.fromApiJsonHelper.extractStringNamed(CODE, column);
|
||||
baseDataValidator.reset().parameter(CODE).value(code).ignoreIfNull().notBlank().notExceedingLengthOf(100)
|
||||
.matchesRegularExpression(DATATABLE_COLUMN_NAME_REGEX_PATTERN);
|
||||
|
||||
final String newCode = this.fromApiJsonHelper.extractStringNamed("newCode", column);
|
||||
baseDataValidator.reset().parameter("newCode").value(newCode).ignoreIfNull().notBlank().notExceedingLengthOf(100)
|
||||
final String newCode = this.fromApiJsonHelper.extractStringNamed(NEW_CODE, column);
|
||||
baseDataValidator.reset().parameter(NEW_CODE).value(newCode).ignoreIfNull().notBlank().notExceedingLengthOf(100)
|
||||
.matchesRegularExpression(DATATABLE_COLUMN_NAME_REGEX_PATTERN);
|
||||
|
||||
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);
|
||||
baseDataValidator.reset().parameter("mandatory").value(mandatory).ignoreIfNull().notBlank().isOneOfTheseValues(true, false);
|
||||
final Boolean mandatory = this.fromApiJsonHelper.extractBooleanNamed(MANDATORY, column);
|
||||
baseDataValidator.reset().parameter(MANDATORY).value(mandatory).ignoreIfNull().notBlank().isOneOfTheseValues(true, false);
|
||||
|
||||
final Boolean after = this.fromApiJsonHelper.extractBooleanNamed("after", column);
|
||||
baseDataValidator.reset().parameter("after").value(after).ignoreIfNull().notBlank().isOneOfTheseValues(true, false);
|
||||
final Boolean after = this.fromApiJsonHelper.extractBooleanNamed(AFTER, column);
|
||||
baseDataValidator.reset().parameter(AFTER).value(after).ignoreIfNull().notBlank().isOneOfTheseValues(true, false);
|
||||
}
|
||||
}
|
||||
|
||||
final JsonArray addColumns = this.fromApiJsonHelper.extractJsonArrayNamed("addColumns", element);
|
||||
baseDataValidator.reset().parameter("addColumns").value(addColumns).ignoreIfNull().jsonArrayNotEmpty();
|
||||
final JsonArray addColumns = this.fromApiJsonHelper.extractJsonArrayNamed(ADD_COLUMNS, element);
|
||||
baseDataValidator.reset().parameter(ADD_COLUMNS).value(addColumns).ignoreIfNull().jsonArrayNotEmpty();
|
||||
|
||||
if (addColumns != null) {
|
||||
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);
|
||||
baseDataValidator.reset().parameter("name").value(name).notBlank().isNotOneOfTheseValues("id", fkColumnName)
|
||||
final String name = this.fromApiJsonHelper.extractStringNamed(NAME, column);
|
||||
baseDataValidator.reset().parameter(NAME).value(name).notBlank().isNotOneOfTheseValues("id", fkColumnName)
|
||||
.matchesRegularExpression(DATATABLE_COLUMN_NAME_REGEX_PATTERN);
|
||||
|
||||
validateType(baseDataValidator, column);
|
||||
|
||||
final Boolean mandatory = this.fromApiJsonHelper.extractBooleanNamed("mandatory", column);
|
||||
baseDataValidator.reset().parameter("mandatory").value(mandatory).ignoreIfNull().notBlank().isOneOfTheseValues(true, false);
|
||||
final Boolean mandatory = this.fromApiJsonHelper.extractBooleanNamed(MANDATORY, column);
|
||||
baseDataValidator.reset().parameter(MANDATORY).value(mandatory).ignoreIfNull().notBlank().isOneOfTheseValues(true, false);
|
||||
|
||||
final Boolean after = this.fromApiJsonHelper.extractBooleanNamed("after", column);
|
||||
baseDataValidator.reset().parameter("after").value(after).ignoreIfNull().notBlank().isOneOfTheseValues(true, false);
|
||||
final Boolean after = this.fromApiJsonHelper.extractBooleanNamed(AFTER, column);
|
||||
baseDataValidator.reset().parameter(AFTER).value(after).ignoreIfNull().notBlank().isOneOfTheseValues(true, false);
|
||||
}
|
||||
}
|
||||
|
||||
final JsonArray dropColumns = this.fromApiJsonHelper.extractJsonArrayNamed("dropColumns", element);
|
||||
baseDataValidator.reset().parameter("dropColumns").value(dropColumns).ignoreIfNull().jsonArrayNotEmpty();
|
||||
final JsonArray dropColumns = this.fromApiJsonHelper.extractJsonArrayNamed(DROP_COLUMNS, element);
|
||||
baseDataValidator.reset().parameter(DROP_COLUMNS).value(dropColumns).ignoreIfNull().jsonArrayNotEmpty();
|
||||
|
||||
if (dropColumns != null) {
|
||||
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);
|
||||
baseDataValidator.reset().parameter("name").value(name).notBlank().isNotOneOfTheseValues("id", fkColumnName)
|
||||
final String name = this.fromApiJsonHelper.extractStringNamed(NAME, column);
|
||||
baseDataValidator.reset().parameter(NAME).value(name).notBlank().isNotOneOfTheseValues("id", fkColumnName)
|
||||
.matchesRegularExpression(DATATABLE_COLUMN_NAME_REGEX_PATTERN);
|
||||
}
|
||||
}
|
||||
|
||||
+8
-8
@@ -36,7 +36,7 @@ import org.springframework.stereotype.Service;
|
||||
@Service
|
||||
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 DataSourcePerTenantServiceFactory dataSourcePerTenantServiceFactory;
|
||||
@@ -51,25 +51,25 @@ public class TomcatJdbcDataSourcePerTenantService implements RoutingDataSourceSe
|
||||
@Override
|
||||
public DataSource retrieveDataSource() {
|
||||
// default to tenant database datasource
|
||||
DataSource tenantDataSource = this.tenantDataSource;
|
||||
DataSource actualDataSource = this.tenantDataSource;
|
||||
|
||||
final FineractPlatformTenant tenant = ThreadLocalContextUtil.getTenant();
|
||||
if (tenant != null) {
|
||||
final FineractPlatformTenantConnection tenantConnection = tenant.getConnection();
|
||||
|
||||
synchronized (this.tenantToDataSourceMap) {
|
||||
synchronized (TENANT_TO_DATA_SOURCE_MAP) {
|
||||
// if tenantConnection information available switch to the
|
||||
// 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) {
|
||||
tenantDataSource = possibleDS;
|
||||
actualDataSource = possibleDS;
|
||||
} else {
|
||||
tenantDataSource = dataSourcePerTenantServiceFactory.createNewDataSourceFor(tenantConnection);
|
||||
this.tenantToDataSourceMap.put(tenantConnection.getConnectionId(), tenantDataSource);
|
||||
actualDataSource = dataSourcePerTenantServiceFactory.createNewDataSourceFor(tenantConnection);
|
||||
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
|
||||
public class DatabaseTypeResolver implements InitializingBean {
|
||||
|
||||
private final Map<String, DatabaseType> driverMapping = Map.of("org.mariadb.jdbc.Driver", DatabaseType.MYSQL, "com.mysql.jdbc.Driver",
|
||||
DatabaseType.MYSQL, "com.mysql.cj.jdbc.Driver", DatabaseType.MYSQL, "org.postgresql.Driver", DatabaseType.POSTGRESQL);
|
||||
private static final Map<String, DatabaseType> DRIVER_MAPPING = Map.of("org.mariadb.jdbc.Driver", DatabaseType.MYSQL,
|
||||
"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;
|
||||
|
||||
@Autowired
|
||||
@@ -45,7 +46,7 @@ public class DatabaseTypeResolver implements InitializingBean {
|
||||
}
|
||||
|
||||
private DatabaseType determineDatabaseType(String driverClassName) {
|
||||
DatabaseType databaseType = driverMapping.get(driverClassName);
|
||||
DatabaseType databaseType = DRIVER_MAPPING.get(driverClassName);
|
||||
if (databaseType == null) {
|
||||
throw new IllegalArgumentException("The driver's class is not supported " + driverClassName);
|
||||
}
|
||||
|
||||
+3
-2
@@ -27,7 +27,8 @@ import org.springframework.stereotype.Component;
|
||||
@Component
|
||||
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;
|
||||
|
||||
@@ -38,7 +39,7 @@ public class DatabaseAwareMigrationContextProvider {
|
||||
|
||||
public String provide() {
|
||||
DatabaseType databaseType = databaseTypeResolver.databaseType();
|
||||
String context = contextMapping.get(databaseType);
|
||||
String context = CONTEXT_MAPPING.get(databaseType);
|
||||
if (context == null) {
|
||||
throw new IllegalStateException("Database is not supported");
|
||||
}
|
||||
|
||||
+13
-13
@@ -60,9 +60,9 @@ import org.springframework.stereotype.Component;
|
||||
@Tag(name = "Credit Bureau Configuration", description = "")
|
||||
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"));
|
||||
private final String resourceNameForPermissions = "CreditBureau";
|
||||
private static final String RESOURCE_NAME_FOR_PERMISSIONS = "CreditBureau";
|
||||
private final PlatformSecurityContext context;
|
||||
private final CreditBureauReadPlatformService readPlatformService;
|
||||
private final DefaultToApiJsonSerializer<CreditBureauData> toApiJsonSerializer;
|
||||
@@ -105,12 +105,12 @@ public class CreditBureauConfigurationAPI {
|
||||
@Consumes({ MediaType.APPLICATION_JSON })
|
||||
@Produces({ MediaType.APPLICATION_JSON })
|
||||
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 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 })
|
||||
@Produces({ MediaType.APPLICATION_JSON })
|
||||
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
|
||||
.readCreditBureauLoanProductMapping();
|
||||
|
||||
final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters());
|
||||
return this.toApiJsonSerializerCreditBureauLoanProduct.serialize(settings, creditBureauLoanProductMapping,
|
||||
this.responseDataParameters);
|
||||
RESPONSE_DATA_PARAMETERS);
|
||||
|
||||
}
|
||||
|
||||
@@ -135,13 +135,13 @@ public class CreditBureauConfigurationAPI {
|
||||
@Consumes({ MediaType.APPLICATION_JSON })
|
||||
@Produces({ MediaType.APPLICATION_JSON })
|
||||
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
|
||||
.retrieveOrgCreditBureau();
|
||||
|
||||
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,
|
||||
@Context final UriInfo uriInfo) {
|
||||
|
||||
this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions);
|
||||
this.context.authenticatedUser().validateHasReadPermission(RESOURCE_NAME_FOR_PERMISSIONS);
|
||||
|
||||
final Collection<CreditBureauConfigurationData> configurationData = this.creditBureauConfiguration
|
||||
.readConfigurationByOrganisationCreditBureauId(organisationCreditBureauId);
|
||||
@@ -165,14 +165,14 @@ public class CreditBureauConfigurationAPI {
|
||||
@Consumes({ MediaType.APPLICATION_JSON })
|
||||
@Produces({ MediaType.APPLICATION_JSON })
|
||||
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
|
||||
.fetchLoanProducts();
|
||||
|
||||
final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters());
|
||||
return this.toApiJsonSerializerCreditBureauLoanProduct.serialize(settings, creditBureauLoanProductMapping,
|
||||
this.responseDataParameters);
|
||||
RESPONSE_DATA_PARAMETERS);
|
||||
}
|
||||
|
||||
@GET
|
||||
@@ -180,14 +180,14 @@ public class CreditBureauConfigurationAPI {
|
||||
@Consumes({ MediaType.APPLICATION_JSON })
|
||||
@Produces({ MediaType.APPLICATION_JSON })
|
||||
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
|
||||
.readMappingByLoanId(loanProductId);
|
||||
|
||||
final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters());
|
||||
return this.toApiJsonSerializerCreditBureauLoanProduct.serialize(settings, creditBureauLoanProductMapping,
|
||||
this.responseDataParameters);
|
||||
RESPONSE_DATA_PARAMETERS);
|
||||
}
|
||||
|
||||
@PUT
|
||||
|
||||
+17
-14
@@ -39,7 +39,10 @@ import org.springframework.stereotype.Component;
|
||||
@Component
|
||||
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;
|
||||
|
||||
@@ -54,7 +57,7 @@ public class CreditBureauCommandFromApiJsonDeserializer {
|
||||
}
|
||||
|
||||
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 DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("CreditBureau");
|
||||
@@ -63,13 +66,13 @@ public class CreditBureauCommandFromApiJsonDeserializer {
|
||||
|
||||
baseDataValidator.reset().value(creditBureauId).notBlank().integerGreaterThanZero();
|
||||
|
||||
final String alias = this.fromApiJsonHelper.extractStringNamed("alias", element);
|
||||
baseDataValidator.reset().parameter("alias").value(alias).notNull().notBlank().notExceedingLengthOf(100);
|
||||
final String alias = this.fromApiJsonHelper.extractStringNamed(ALIAS, element);
|
||||
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)) {
|
||||
final boolean isActive = this.fromApiJsonHelper.extractBooleanNamed("isActive", element);
|
||||
baseDataValidator.reset().parameter("isActive").value(isActive).notNull().notBlank().trueOrFalseRequired(isActive);
|
||||
final boolean isActive = this.fromApiJsonHelper.extractBooleanNamed(IS_ACTIVE, element);
|
||||
baseDataValidator.reset().parameter(IS_ACTIVE).value(isActive).notNull().notBlank().trueOrFalseRequired(isActive);
|
||||
}
|
||||
|
||||
throwExceptionIfValidationWarningsExist(dataValidationErrors);
|
||||
@@ -81,23 +84,23 @@ public class CreditBureauCommandFromApiJsonDeserializer {
|
||||
}
|
||||
|
||||
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 DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("CreditBureau");
|
||||
|
||||
final JsonElement element = this.fromApiJsonHelper.parse(json);
|
||||
|
||||
final String creditBureauIdParameter = "creditBureauId";
|
||||
final String creditBureauIdParameter = CREDIT_BUREAU_ID;
|
||||
if (this.fromApiJsonHelper.parameterExists(creditBureauIdParameter, element)) {
|
||||
final Long creditBureauId = this.fromApiJsonHelper.extractLongNamed("creditBureauId", element);
|
||||
baseDataValidator.reset().parameter("creditBureauId").value(creditBureauId).notNull().notBlank().longGreaterThanZero();
|
||||
final Long creditBureauId = this.fromApiJsonHelper.extractLongNamed(CREDIT_BUREAU_ID, element);
|
||||
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)) {
|
||||
final boolean isActive = this.fromApiJsonHelper.extractBooleanNamed("isActive", element);
|
||||
baseDataValidator.reset().parameter("isActive").value(isActive).notNull().notBlank().trueOrFalseRequired(isActive);
|
||||
final boolean isActive = this.fromApiJsonHelper.extractBooleanNamed(IS_ACTIVE, element);
|
||||
baseDataValidator.reset().parameter(IS_ACTIVE).value(isActive).notNull().notBlank().trueOrFalseRequired(isActive);
|
||||
}
|
||||
|
||||
throwExceptionIfValidationWarningsExist(dataValidationErrors);
|
||||
|
||||
+19
-16
@@ -39,7 +39,10 @@ import org.springframework.stereotype.Component;
|
||||
@Component
|
||||
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;
|
||||
|
||||
@Autowired
|
||||
@@ -53,7 +56,7 @@ public final class CreditBureauConfigurationCommandFromApiJsonDeserializer {
|
||||
}
|
||||
|
||||
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 DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors)
|
||||
@@ -63,16 +66,16 @@ public final class CreditBureauConfigurationCommandFromApiJsonDeserializer {
|
||||
|
||||
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);
|
||||
baseDataValidator.reset().parameter("configkey").value(configkey).notBlank().notExceedingLengthOf(100);
|
||||
final String configkey = this.fromApiJsonHelper.extractStringNamed(CONFIGKEY, element);
|
||||
baseDataValidator.reset().parameter(CONFIGKEY).value(configkey).notBlank().notExceedingLengthOf(100);
|
||||
|
||||
final String value = this.fromApiJsonHelper.extractStringNamed("value", element);
|
||||
baseDataValidator.reset().parameter("value").value(value).notBlank().notExceedingLengthOf(100);
|
||||
final String value = this.fromApiJsonHelper.extractStringNamed(VALUE, element);
|
||||
baseDataValidator.reset().parameter(VALUE).value(value).notBlank().notExceedingLengthOf(100);
|
||||
|
||||
final String description = this.fromApiJsonHelper.extractStringNamed("description", element);
|
||||
baseDataValidator.reset().parameter("description").value(description).notBlank().notExceedingLengthOf(100);
|
||||
final String description = this.fromApiJsonHelper.extractStringNamed(DESCRIPTION, element);
|
||||
baseDataValidator.reset().parameter(DESCRIPTION).value(description).notBlank().notExceedingLengthOf(100);
|
||||
|
||||
throwExceptionIfValidationWarningsExist(dataValidationErrors);
|
||||
}
|
||||
@@ -83,21 +86,21 @@ public final class CreditBureauConfigurationCommandFromApiJsonDeserializer {
|
||||
}
|
||||
|
||||
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 DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("config");
|
||||
|
||||
final JsonElement element = this.fromApiJsonHelper.parse(json);
|
||||
|
||||
if (this.fromApiJsonHelper.parameterExists("value", element)) {
|
||||
final String value = this.fromApiJsonHelper.extractStringNamed("value", element);
|
||||
baseDataValidator.reset().parameter("value").value(value).notBlank().notExceedingLengthOf(100);
|
||||
if (this.fromApiJsonHelper.parameterExists(VALUE, element)) {
|
||||
final String value = this.fromApiJsonHelper.extractStringNamed(VALUE, element);
|
||||
baseDataValidator.reset().parameter(VALUE).value(value).notBlank().notExceedingLengthOf(100);
|
||||
}
|
||||
|
||||
if (this.fromApiJsonHelper.parameterExists("description", element)) {
|
||||
final String description = this.fromApiJsonHelper.extractStringNamed("description", element);
|
||||
baseDataValidator.reset().parameter("description").value(description).notBlank().notExceedingLengthOf(100);
|
||||
if (this.fromApiJsonHelper.parameterExists(DESCRIPTION, element)) {
|
||||
final String description = this.fromApiJsonHelper.extractStringNamed(DESCRIPTION, element);
|
||||
baseDataValidator.reset().parameter(DESCRIPTION).value(description).notBlank().notExceedingLengthOf(100);
|
||||
}
|
||||
|
||||
throwExceptionIfValidationWarningsExist(dataValidationErrors);
|
||||
|
||||
+38
-31
@@ -39,8 +39,15 @@ import org.springframework.stereotype.Component;
|
||||
@Component
|
||||
public class CreditBureauLoanProductCommandFromApiJsonDeserializer {
|
||||
|
||||
private final Set<String> supportedParameters = new HashSet<>(Arrays.asList("loanProductId", "isCreditcheckMandatory",
|
||||
"skipCreditcheckInFailure", "stalePeriod", "isActive", "locale", "creditbureauLoanProductMappingId"));
|
||||
public static final String LOAN_PRODUCT_ID = "loanProductId";
|
||||
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;
|
||||
|
||||
@@ -55,7 +62,7 @@ public class CreditBureauLoanProductCommandFromApiJsonDeserializer {
|
||||
}
|
||||
|
||||
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 DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors)
|
||||
@@ -65,45 +72,45 @@ public class CreditBureauLoanProductCommandFromApiJsonDeserializer {
|
||||
|
||||
baseDataValidator.reset().value(cb_id).notBlank().integerGreaterThanZero();
|
||||
|
||||
final long loanProductId = this.fromApiJsonHelper.extractLongNamed("loanProductId", element);
|
||||
baseDataValidator.reset().parameter("loanProductId").value(loanProductId).notBlank().integerGreaterThanZero();
|
||||
final long loanProductId = this.fromApiJsonHelper.extractLongNamed(LOAN_PRODUCT_ID, element);
|
||||
baseDataValidator.reset().parameter(LOAN_PRODUCT_ID).value(loanProductId).notBlank().integerGreaterThanZero();
|
||||
|
||||
if (this.fromApiJsonHelper.extractBooleanNamed("isCreditcheckMandatory", element) != null) {
|
||||
final boolean isCreditcheckMandatory = this.fromApiJsonHelper.extractBooleanNamed("isCreditcheckMandatory", element);
|
||||
baseDataValidator.reset().parameter("isCreditcheckMandatory").value(isCreditcheckMandatory).notBlank()
|
||||
if (this.fromApiJsonHelper.extractBooleanNamed(IS_CREDITCHECK_MANDATORY, element) != null) {
|
||||
final boolean isCreditcheckMandatory = this.fromApiJsonHelper.extractBooleanNamed(IS_CREDITCHECK_MANDATORY, element);
|
||||
baseDataValidator.reset().parameter(IS_CREDITCHECK_MANDATORY).value(isCreditcheckMandatory).notBlank()
|
||||
.trueOrFalseRequired(isCreditcheckMandatory);
|
||||
} else {
|
||||
baseDataValidator.reset().parameter("isCreditcheckMandatory")
|
||||
.value(this.fromApiJsonHelper.extractBooleanNamed("isCreditcheckMandatory", element)).notBlank()
|
||||
.trueOrFalseRequired(this.fromApiJsonHelper.extractBooleanNamed("isCreditcheckMandatory", element));
|
||||
baseDataValidator.reset().parameter(IS_CREDITCHECK_MANDATORY)
|
||||
.value(this.fromApiJsonHelper.extractBooleanNamed(IS_CREDITCHECK_MANDATORY, element)).notBlank()
|
||||
.trueOrFalseRequired(this.fromApiJsonHelper.extractBooleanNamed(IS_CREDITCHECK_MANDATORY, element));
|
||||
}
|
||||
|
||||
if (this.fromApiJsonHelper.extractBooleanNamed("skipCreditcheckInFailure", element) != null) {
|
||||
final boolean skipCreditcheckInFailure = this.fromApiJsonHelper.extractBooleanNamed("skipCreditcheckInFailure", element);
|
||||
baseDataValidator.reset().parameter("skipCreditcheckInFailure").value(skipCreditcheckInFailure).notBlank()
|
||||
if (this.fromApiJsonHelper.extractBooleanNamed(SKIP_CREDITCHECK_IN_FAILURE, element) != null) {
|
||||
final boolean skipCreditcheckInFailure = this.fromApiJsonHelper.extractBooleanNamed(SKIP_CREDITCHECK_IN_FAILURE, element);
|
||||
baseDataValidator.reset().parameter(SKIP_CREDITCHECK_IN_FAILURE).value(skipCreditcheckInFailure).notBlank()
|
||||
.trueOrFalseRequired(skipCreditcheckInFailure);
|
||||
|
||||
} else {
|
||||
baseDataValidator.reset().parameter("skipCreditcheckInFailure")
|
||||
.value(this.fromApiJsonHelper.extractBooleanNamed("skipCreditcheckInFailure", element)).notBlank()
|
||||
.trueOrFalseRequired(this.fromApiJsonHelper.extractBooleanNamed("skipCreditcheckInFailure", element));
|
||||
baseDataValidator.reset().parameter(SKIP_CREDITCHECK_IN_FAILURE)
|
||||
.value(this.fromApiJsonHelper.extractBooleanNamed(SKIP_CREDITCHECK_IN_FAILURE, element)).notBlank()
|
||||
.trueOrFalseRequired(this.fromApiJsonHelper.extractBooleanNamed(SKIP_CREDITCHECK_IN_FAILURE, element));
|
||||
}
|
||||
|
||||
if (this.fromApiJsonHelper.extractLongNamed("stalePeriod", element) != null) {
|
||||
final long stalePeriod = this.fromApiJsonHelper.extractLongNamed("stalePeriod", element);
|
||||
baseDataValidator.reset().parameter("stalePeriod").value(stalePeriod).notBlank().integerGreaterThanZero();
|
||||
if (this.fromApiJsonHelper.extractLongNamed(STALE_PERIOD, element) != null) {
|
||||
final long stalePeriod = this.fromApiJsonHelper.extractLongNamed(STALE_PERIOD, element);
|
||||
baseDataValidator.reset().parameter(STALE_PERIOD).value(stalePeriod).notBlank().integerGreaterThanZero();
|
||||
} 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();
|
||||
}
|
||||
|
||||
if (this.fromApiJsonHelper.extractBooleanNamed("isActive", element) != null) {
|
||||
Boolean isActive = this.fromApiJsonHelper.extractBooleanNamed("isActive", element);
|
||||
if (this.fromApiJsonHelper.extractBooleanNamed(IS_ACTIVE, element) != null) {
|
||||
Boolean isActive = this.fromApiJsonHelper.extractBooleanNamed(IS_ACTIVE, element);
|
||||
if (isActive == null) {
|
||||
isActive = false;
|
||||
} 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();
|
||||
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParameters);
|
||||
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, SUPPORTED_PARAMETERS);
|
||||
|
||||
final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
|
||||
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors)
|
||||
@@ -125,18 +132,18 @@ public class CreditBureauLoanProductCommandFromApiJsonDeserializer {
|
||||
|
||||
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)) {
|
||||
final Long creditbureauLoanProductMappingId = this.fromApiJsonHelper.extractLongNamed("creditbureauLoanProductMappingId",
|
||||
final Long creditbureauLoanProductMappingId = this.fromApiJsonHelper.extractLongNamed(CREDITBUREAU_LOAN_PRODUCT_MAPPING_ID,
|
||||
element);
|
||||
baseDataValidator.reset().parameter("creditbureauLoanProductMappingId").value(creditbureauLoanProductMappingId).notNull()
|
||||
baseDataValidator.reset().parameter(CREDITBUREAU_LOAN_PRODUCT_MAPPING_ID).value(creditbureauLoanProductMappingId).notNull()
|
||||
.notBlank().longGreaterThanZero();
|
||||
}
|
||||
|
||||
final String is_activeParameter = "isActive";
|
||||
final String is_activeParameter = IS_ACTIVE;
|
||||
if (this.fromApiJsonHelper.parameterExists(is_activeParameter, element)) {
|
||||
final boolean isActive = this.fromApiJsonHelper.extractBooleanNamed("isActive", element);
|
||||
baseDataValidator.reset().parameter("isActive").value(isActive).notNull().notBlank().trueOrFalseRequired(isActive);
|
||||
final boolean isActive = this.fromApiJsonHelper.extractBooleanNamed(IS_ACTIVE, element);
|
||||
baseDataValidator.reset().parameter(IS_ACTIVE).value(isActive).notNull().notBlank().trueOrFalseRequired(isActive);
|
||||
}
|
||||
|
||||
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.PlatformApiDataValidationException;
|
||||
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.stereotype.Component;
|
||||
|
||||
@Component
|
||||
public class CreditBureauTokenCommandFromApiJsonDeserializer {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(CreditBureauTokenCommandFromApiJsonDeserializer.class);
|
||||
|
||||
private final Set<String> supportedParameters = new HashSet<>(
|
||||
Arrays.asList("access_token", "token_type", "expires_in", "userName", ".issued", ".expires"));
|
||||
|
||||
private final Set<String> supportedTokenConfigParameters = new HashSet<>(
|
||||
Arrays.asList("userName", "password", "subscriptionId", "subscriptionKey"));
|
||||
public static final String ACCESS_TOKEN = "access_token";
|
||||
public static final String TOKEN_TYPE = "token_type";
|
||||
public static final String EXPIRES_IN = "expires_in";
|
||||
public static final String USER_NAME = "userName";
|
||||
public static final String ISSUED = ".issued";
|
||||
public static final String EXPIRES = ".expires";
|
||||
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;
|
||||
|
||||
@Autowired
|
||||
@@ -61,31 +65,33 @@ public class CreditBureauTokenCommandFromApiJsonDeserializer {
|
||||
throw new InvalidJsonException();
|
||||
}
|
||||
|
||||
final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType();
|
||||
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParameters);
|
||||
final Type typeOfMap = new TypeToken<Map<String, Object>>() {
|
||||
|
||||
}.getType();
|
||||
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, SUPPORTED_PARAMETERS);
|
||||
|
||||
final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
|
||||
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("tokens");
|
||||
|
||||
final JsonElement element = this.fromApiJsonHelper.parse(json);
|
||||
|
||||
final String access_token = this.fromApiJsonHelper.extractStringNamed("access_token", element);
|
||||
baseDataValidator.reset().parameter("access_token").value(access_token).notBlank().notExceedingLengthOf(1000);
|
||||
final String access_token = this.fromApiJsonHelper.extractStringNamed(ACCESS_TOKEN, element);
|
||||
baseDataValidator.reset().parameter(ACCESS_TOKEN).value(access_token).notBlank().notExceedingLengthOf(1000);
|
||||
|
||||
final String token_type = this.fromApiJsonHelper.extractStringNamed("token_type", element);
|
||||
baseDataValidator.reset().parameter("token_type").value(token_type).notBlank().notExceedingLengthOf(100);
|
||||
final String token_type = this.fromApiJsonHelper.extractStringNamed(TOKEN_TYPE, element);
|
||||
baseDataValidator.reset().parameter(TOKEN_TYPE).value(token_type).notBlank().notExceedingLengthOf(100);
|
||||
|
||||
final String expires_in = this.fromApiJsonHelper.extractStringNamed("expires_in", element);
|
||||
baseDataValidator.reset().parameter("expires_in").value(expires_in).notBlank().notExceedingLengthOf(100);
|
||||
final String expires_in = this.fromApiJsonHelper.extractStringNamed(EXPIRES_IN, element);
|
||||
baseDataValidator.reset().parameter(EXPIRES_IN).value(expires_in).notBlank().notExceedingLengthOf(100);
|
||||
|
||||
final String userName = this.fromApiJsonHelper.extractStringNamed("userName", element);
|
||||
baseDataValidator.reset().parameter("userName").value(userName).notBlank().notExceedingLengthOf(100);
|
||||
final String userName = this.fromApiJsonHelper.extractStringNamed(USER_NAME, element);
|
||||
baseDataValidator.reset().parameter(USER_NAME).value(userName).notBlank().notExceedingLengthOf(100);
|
||||
|
||||
final String issued = this.fromApiJsonHelper.extractStringNamed(".issued", element);
|
||||
baseDataValidator.reset().parameter(".issued").value(issued).notBlank().notExceedingLengthOf(100);
|
||||
final String issued = this.fromApiJsonHelper.extractStringNamed(ISSUED, element);
|
||||
baseDataValidator.reset().parameter(ISSUED).value(issued).notBlank().notExceedingLengthOf(100);
|
||||
|
||||
final String expires = this.fromApiJsonHelper.extractStringNamed(".expires", element);
|
||||
baseDataValidator.reset().parameter(".expires").value(expires).notBlank().notExceedingLengthOf(100);
|
||||
final String expires = this.fromApiJsonHelper.extractStringNamed(EXPIRES, element);
|
||||
baseDataValidator.reset().parameter(EXPIRES).value(expires).notBlank().notExceedingLengthOf(100);
|
||||
|
||||
throwExceptionIfValidationWarningsExist(dataValidationErrors);
|
||||
}
|
||||
@@ -95,25 +101,27 @@ public class CreditBureauTokenCommandFromApiJsonDeserializer {
|
||||
throw new InvalidJsonException();
|
||||
}
|
||||
|
||||
final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType();
|
||||
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedTokenConfigParameters);
|
||||
final Type typeOfMap = new TypeToken<Map<String, Object>>() {
|
||||
|
||||
}.getType();
|
||||
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, SUPPORTED_TOKEN_CONFIG_PARAMETERS);
|
||||
|
||||
final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
|
||||
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("configdata");
|
||||
|
||||
final JsonElement element = this.fromApiJsonHelper.parse(json);
|
||||
|
||||
final String userName = this.fromApiJsonHelper.extractStringNamed("userName", element);
|
||||
baseDataValidator.reset().parameter("userName").value(userName).notBlank().notExceedingLengthOf(1000);
|
||||
final String userName = this.fromApiJsonHelper.extractStringNamed(USER_NAME, element);
|
||||
baseDataValidator.reset().parameter(USER_NAME).value(userName).notBlank().notExceedingLengthOf(1000);
|
||||
|
||||
final String password = this.fromApiJsonHelper.extractStringNamed("password", element);
|
||||
baseDataValidator.reset().parameter("password").value(password).notBlank().notExceedingLengthOf(100);
|
||||
final String password = this.fromApiJsonHelper.extractStringNamed(PASSWORD, element);
|
||||
baseDataValidator.reset().parameter(PASSWORD).value(password).notBlank().notExceedingLengthOf(100);
|
||||
|
||||
final String subscriptionId = this.fromApiJsonHelper.extractStringNamed("subscriptionId", element);
|
||||
baseDataValidator.reset().parameter("subscriptionId").value(subscriptionId).notBlank().notExceedingLengthOf(100);
|
||||
final String subscriptionId = this.fromApiJsonHelper.extractStringNamed(SUBSCRIPTION_ID, element);
|
||||
baseDataValidator.reset().parameter(SUBSCRIPTION_ID).value(subscriptionId).notBlank().notExceedingLengthOf(100);
|
||||
|
||||
final String subscriptionKey = this.fromApiJsonHelper.extractStringNamed("subscriptionKey", element);
|
||||
baseDataValidator.reset().parameter("subscriptionKey").value(subscriptionKey).notBlank().notExceedingLengthOf(100);
|
||||
final String subscriptionKey = this.fromApiJsonHelper.extractStringNamed(SUBSCRIPTION_KEY, element);
|
||||
baseDataValidator.reset().parameter(SUBSCRIPTION_KEY).value(subscriptionKey).notBlank().notExceedingLengthOf(100);
|
||||
|
||||
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.exception.PlatformApiDataValidationException;
|
||||
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.CreditBureauReportData;
|
||||
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.CreditReport;
|
||||
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.glassfish.jersey.media.multipart.FormDataContentDisposition;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
@@ -56,36 +51,29 @@ import org.springframework.transaction.annotation.Transactional;
|
||||
@Service
|
||||
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 CreditBureauConfigurationRepositoryWrapper configDataRepository;
|
||||
|
||||
private final CreditBureauRepository creditBureauRepository;
|
||||
private final CreditReportRepository creditReportRepository;
|
||||
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
|
||||
public CreditReportWritePlatformServiceImpl(final PlatformSecurityContext context, final FromJsonHelper fromApiJsonHelper,
|
||||
final TokenRepositoryWrapper tokenRepository, final CreditBureauConfigurationRepositoryWrapper configDataRepository,
|
||||
final CreditBureauTokenCommandFromApiJsonDeserializer fromApiJsonDeserializer,
|
||||
final CreditBureauLoanProductMappingRepository loanProductMappingRepository,
|
||||
final CreditBureauRepository creditBureauRepository, final CreditReportRepository creditReportRepository,
|
||||
final ThitsaWorksCreditBureauIntegrationWritePlatformService thitsaWorksCreditBureauIntegrationWritePlatformService,
|
||||
final ThitsaWorksCreditBureauIntegrationWritePlatformServiceImpl thitsaWorksCreditBureauIntegrationWritePlatformServiceImpl) {
|
||||
public CreditReportWritePlatformServiceImpl(final PlatformSecurityContext context, final CreditBureauRepository creditBureauRepository,
|
||||
final CreditReportRepository creditReportRepository,
|
||||
final ThitsaWorksCreditBureauIntegrationWritePlatformService thitsaWorksCreditBureauIntegrationWritePlatformService) {
|
||||
this.context = context;
|
||||
this.configDataRepository = configDataRepository;
|
||||
this.creditBureauRepository = creditBureauRepository;
|
||||
this.creditReportRepository = creditReportRepository;
|
||||
this.thitsaWorksCreditBureauIntegrationWritePlatformService = thitsaWorksCreditBureauIntegrationWritePlatformService;
|
||||
this.thitsaWorksCreditBureauIntegrationWritePlatformServiceImpl = thitsaWorksCreditBureauIntegrationWritePlatformServiceImpl;
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
public CommandProcessingResult getCreditReport(JsonCommand command) {
|
||||
|
||||
List<ApiParameterError> dataValidationErrors = new ArrayList<>();
|
||||
DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource(CREDIT_BUREAU_INTEGRATION);
|
||||
try {
|
||||
Long creditBureauID = command.longValueOfParameterNamed("creditBureauID");
|
||||
|
||||
@@ -103,16 +91,16 @@ public class CreditReportWritePlatformServiceImpl implements CreditReportWritePl
|
||||
return new CommandProcessingResultBuilder().withCreditReport(reportMap).build();
|
||||
}
|
||||
|
||||
baseDataValidator.reset().failWithCode("creditBureau.has.not.been.Integrated");
|
||||
throw new PlatformApiDataValidationException("creditBureau.has.not.been.Integrated", "creditBureau.has.not.been.Integrated",
|
||||
baseDataValidator.reset().failWithCode(CREDIT_BUREAU_HAS_NOT_BEEN_INTEGRATED);
|
||||
throw new PlatformApiDataValidationException(CREDIT_BUREAU_HAS_NOT_BEEN_INTEGRATED, CREDIT_BUREAU_HAS_NOT_BEEN_INTEGRATED,
|
||||
dataValidationErrors);
|
||||
|
||||
} catch (final JpaSystemException | DataIntegrityViolationException dve) {
|
||||
handleTokenDataIntegrityIssues(command, dve.getMostSpecificCause(), dve);
|
||||
handleTokenDataIntegrityIssues(dve.getMostSpecificCause());
|
||||
return CommandProcessingResult.empty();
|
||||
} catch (final PersistenceException ee) {
|
||||
Throwable throwable = ExceptionUtils.getRootCause(ee.getCause());
|
||||
handleTokenDataIntegrityIssues(command, throwable, ee);
|
||||
handleTokenDataIntegrityIssues(throwable);
|
||||
return CommandProcessingResult.empty();
|
||||
}
|
||||
|
||||
@@ -121,7 +109,8 @@ public class CreditReportWritePlatformServiceImpl implements CreditReportWritePl
|
||||
@Override
|
||||
@Transactional
|
||||
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 responseMessage = null;
|
||||
|
||||
@@ -130,8 +119,8 @@ public class CreditReportWritePlatformServiceImpl implements CreditReportWritePl
|
||||
fileDetail);
|
||||
} else {
|
||||
|
||||
baseDataValidator.reset().failWithCode("creditBureau.has.not.been.Integrated");
|
||||
throw new PlatformApiDataValidationException("creditBureau.has.not.been.Integrated", "creditBureau.has.not.been.Integrated",
|
||||
baseDataValidator.reset().failWithCode(CREDIT_BUREAU_HAS_NOT_BEEN_INTEGRATED);
|
||||
throw new PlatformApiDataValidationException(CREDIT_BUREAU_HAS_NOT_BEEN_INTEGRATED, CREDIT_BUREAU_HAS_NOT_BEEN_INTEGRATED,
|
||||
dataValidationErrors);
|
||||
|
||||
}
|
||||
@@ -141,7 +130,8 @@ public class CreditReportWritePlatformServiceImpl implements CreditReportWritePl
|
||||
}
|
||||
|
||||
private String getCreditBureauName(Long creditBureauID) {
|
||||
|
||||
List<ApiParameterError> dataValidationErrors = new ArrayList<>();
|
||||
DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource(CREDIT_BUREAU_INTEGRATION);
|
||||
if (creditBureauID != null) {
|
||||
Optional<CreditBureau> creditBureau = this.creditBureauRepository.findById(creditBureauID);
|
||||
|
||||
@@ -150,8 +140,8 @@ public class CreditReportWritePlatformServiceImpl implements CreditReportWritePl
|
||||
}
|
||||
}
|
||||
|
||||
baseDataValidator.reset().failWithCode("creditBureau.has.not.been.Integrated");
|
||||
throw new PlatformApiDataValidationException("creditBureau.has.not.been.Integrated", "creditBureau.has.not.been.Integrated",
|
||||
baseDataValidator.reset().failWithCode(CREDIT_BUREAU_HAS_NOT_BEEN_INTEGRATED);
|
||||
throw new PlatformApiDataValidationException(CREDIT_BUREAU_HAS_NOT_BEEN_INTEGRATED, CREDIT_BUREAU_HAS_NOT_BEEN_INTEGRATED,
|
||||
dataValidationErrors);
|
||||
}
|
||||
|
||||
@@ -186,11 +176,11 @@ public class CreditReportWritePlatformServiceImpl implements CreditReportWritePl
|
||||
|
||||
return new CommandProcessingResultBuilder().withEntityId(creditReport.getId()).build();
|
||||
} catch (final JpaSystemException | DataIntegrityViolationException dve) {
|
||||
handleTokenDataIntegrityIssues(command, dve.getMostSpecificCause(), dve);
|
||||
handleTokenDataIntegrityIssues(dve.getMostSpecificCause());
|
||||
return CommandProcessingResult.empty();
|
||||
} catch (final PersistenceException ee) {
|
||||
Throwable throwable = ExceptionUtils.getRootCause(ee.getCause());
|
||||
handleTokenDataIntegrityIssues(command, throwable, ee);
|
||||
handleTokenDataIntegrityIssues(throwable);
|
||||
return CommandProcessingResult.empty();
|
||||
}
|
||||
}
|
||||
@@ -219,7 +209,7 @@ public class CreditReportWritePlatformServiceImpl implements CreditReportWritePl
|
||||
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",
|
||||
"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.CreditBureauReportData;
|
||||
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.CreditBureauToken;
|
||||
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;
|
||||
@@ -68,22 +66,18 @@ import org.springframework.transaction.annotation.Transactional;
|
||||
@Service
|
||||
public class ThitsaWorksCreditBureauIntegrationWritePlatformServiceImpl implements ThitsaWorksCreditBureauIntegrationWritePlatformService {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(ThitsaWorksCreditBureauIntegrationWritePlatformServiceImpl.class);
|
||||
private final PlatformSecurityContext context;
|
||||
private final FromJsonHelper fromApiJsonHelper;
|
||||
private final TokenRepositoryWrapper tokenRepositoryWrapper;
|
||||
private final CreditBureauConfigurationRepositoryWrapper configDataRepository;
|
||||
private final CreditBureauTokenCommandFromApiJsonDeserializer fromApiJsonDeserializer;
|
||||
private final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
|
||||
private final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors)
|
||||
.resource("ThitsaWorksCreditBureauIntegration");
|
||||
|
||||
@Autowired
|
||||
public ThitsaWorksCreditBureauIntegrationWritePlatformServiceImpl(final PlatformSecurityContext context,
|
||||
final FromJsonHelper fromApiJsonHelper, final TokenRepositoryWrapper tokenRepositoryWrapper,
|
||||
final CreditBureauConfigurationRepositoryWrapper configDataRepository,
|
||||
final CreditBureauConfigurationRepository configurationDataRepository,
|
||||
final CreditBureauTokenCommandFromApiJsonDeserializer fromApiJsonDeserializer,
|
||||
final CreditReportRepository creditReportRepository) {
|
||||
final CreditBureauTokenCommandFromApiJsonDeserializer fromApiJsonDeserializer) {
|
||||
this.context = context;
|
||||
this.tokenRepositoryWrapper = tokenRepositoryWrapper;
|
||||
this.configDataRepository = configDataRepository;
|
||||
@@ -91,8 +85,6 @@ public class ThitsaWorksCreditBureauIntegrationWritePlatformServiceImpl implemen
|
||||
this.fromApiJsonDeserializer = fromApiJsonDeserializer;
|
||||
}
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(ThitsaWorksCreditBureauIntegrationWritePlatformServiceImpl.class);
|
||||
|
||||
@Transactional
|
||||
@Override
|
||||
@SuppressWarnings("deprecation")
|
||||
@@ -171,8 +163,8 @@ public class ThitsaWorksCreditBureauIntegrationWritePlatformServiceImpl implemen
|
||||
|
||||
if (process.equals("UploadCreditReport")) { // to show the Response on frontEnd
|
||||
JsonObject reportObject = JsonParser.parseString(reponseMessage).getAsJsonObject();
|
||||
String ResponseMessageJson = reportObject.get("ResponseMessage").getAsString();
|
||||
this.handleAPIIntegrityIssues(ResponseMessageJson);
|
||||
String responseMessageJson = reportObject.get("ResponseMessage").getAsString();
|
||||
this.handleAPIIntegrityIssues(responseMessageJson);
|
||||
}
|
||||
|
||||
return reponseMessage;
|
||||
@@ -249,7 +241,7 @@ public class ThitsaWorksCreditBureauIntegrationWritePlatformServiceImpl implemen
|
||||
JsonElement element = reportObject.get("Data");
|
||||
|
||||
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;
|
||||
|
||||
}
|
||||
@@ -265,9 +257,9 @@ public class ThitsaWorksCreditBureauIntegrationWritePlatformServiceImpl implemen
|
||||
borrowerInfo = gson.toJson(borrowerInfos);
|
||||
}
|
||||
|
||||
String Name = borrowerInfos.get("Name").toString();
|
||||
String Gender = borrowerInfos.get("Gender").toString();
|
||||
String Address = borrowerInfos.get("Address").toString();
|
||||
String name = borrowerInfos.get("Name").toString();
|
||||
String gender = borrowerInfos.get("Gender").toString();
|
||||
String address = borrowerInfos.get("Address").toString();
|
||||
|
||||
String creditScore = "CreditScore";
|
||||
creditScore = getJsonObjectToString(creditScore, element, jsonData);
|
||||
@@ -288,7 +280,7 @@ public class ThitsaWorksCreditBureauIntegrationWritePlatformServiceImpl implemen
|
||||
writeoffLoanStringArray = convertArrayintoStringArray(writeOffLoansArray);
|
||||
}
|
||||
|
||||
return CreditBureauReportData.instance(Name, Gender, Address, creditScore, borrowerInfo, activeLoanStringArray,
|
||||
return CreditBureauReportData.instance(name, gender, address, creditScore, borrowerInfo, activeLoanStringArray,
|
||||
writeoffLoanStringArray);
|
||||
}
|
||||
|
||||
@@ -311,10 +303,8 @@ public class ThitsaWorksCreditBureauIntegrationWritePlatformServiceImpl implemen
|
||||
|
||||
String process = "UploadCreditReport";
|
||||
|
||||
String responseMessage = this.okHttpConnectionMethod(userName, password, subscriptionKey, subscriptionId, url, token, creditReport,
|
||||
fileDetail, 0L, null, process);
|
||||
|
||||
return responseMessage;
|
||||
return this.okHttpConnectionMethod(userName, password, subscriptionKey, subscriptionId, url, token, creditReport, fileDetail, 0L,
|
||||
null, process);
|
||||
}
|
||||
|
||||
private String[] convertArrayintoStringArray(JsonArray jsonResult) {
|
||||
@@ -338,8 +328,8 @@ public class ThitsaWorksCreditBureauIntegrationWritePlatformServiceImpl implemen
|
||||
JsonElement element = reportObject.get("Data");
|
||||
|
||||
if (element.isJsonNull()) {
|
||||
String ResponseMessage = reportObject.get("ResponseMessage").getAsString();
|
||||
handleAPIIntegrityIssues(ResponseMessage);
|
||||
String responseMessage = reportObject.get("ResponseMessage").getAsString();
|
||||
handleAPIIntegrityIssues(responseMessage);
|
||||
}
|
||||
|
||||
// to fetch the Unique ID from Result
|
||||
@@ -354,16 +344,16 @@ public class ThitsaWorksCreditBureauIntegrationWritePlatformServiceImpl implemen
|
||||
JsonObject jobject = dataArray.get(0).getAsJsonObject();
|
||||
|
||||
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) {
|
||||
String ResponseMessage = reportObject.get("ResponseMessage").getAsString();
|
||||
handleAPIIntegrityIssues(ResponseMessage);
|
||||
String responseMessage = reportObject.get("ResponseMessage").getAsString();
|
||||
handleAPIIntegrityIssues(responseMessage);
|
||||
} else {
|
||||
String nrc = null;
|
||||
List<String> arrlist = new ArrayList<String>();
|
||||
String nrc;
|
||||
List<String> arrlist = new ArrayList<>();
|
||||
|
||||
for (int i = 0; i < dataArray.size(); ++i) {
|
||||
JsonObject data = dataArray.get(i).getAsJsonObject();
|
||||
@@ -377,8 +367,8 @@ public class ThitsaWorksCreditBureauIntegrationWritePlatformServiceImpl implemen
|
||||
}
|
||||
|
||||
} catch (IndexOutOfBoundsException e) {
|
||||
String ResponseMessage = jsonObject.get("ResponseMessage").getAsString();
|
||||
handleAPIIntegrityIssues(ResponseMessage);
|
||||
String responseMessage = jsonObject.get("ResponseMessage").getAsString();
|
||||
handleAPIIntegrityIssues(responseMessage);
|
||||
}
|
||||
return uniqueID;
|
||||
}
|
||||
@@ -471,7 +461,9 @@ public class ThitsaWorksCreditBureauIntegrationWritePlatformServiceImpl implemen
|
||||
}
|
||||
|
||||
public String getCreditBureauConfiguration(Integer creditBureauId, String configurationParameterName) {
|
||||
|
||||
List<ApiParameterError> dataValidationErrors = new ArrayList<>();
|
||||
DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors)
|
||||
.resource("ThitsaWorksCreditBureauIntegration");
|
||||
String creditBureauConfigurationValue = null;
|
||||
|
||||
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.")
|
||||
public class ReportsApiResource {
|
||||
|
||||
private final Set<String> responseDataParameters = new HashSet<>(Arrays.asList("id", "reportName", "reportType", "reportSubType",
|
||||
"reportCategory", "description", "reportSql", "coreReport", "useReport", "reportParameters"));
|
||||
private static final Set<String> RESPONSE_DATA_PARAMETERS = new HashSet<>(Arrays.asList("id", "reportName", "reportType",
|
||||
"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 ToApiJsonSerializer<ReportData> toApiJsonSerializer;
|
||||
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))))
|
||||
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 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
|
||||
@@ -113,7 +113,7 @@ public class ReportsApiResource {
|
||||
@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) {
|
||||
|
||||
this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions);
|
||||
this.context.authenticatedUser().validateHasReadPermission(RESOURCE_NAME_FOR_PERMISSIONS);
|
||||
|
||||
final ReportData result = this.readReportingService.retrieveReport(id);
|
||||
|
||||
@@ -123,7 +123,7 @@ public class ReportsApiResource {
|
||||
result.appendedTemplate(this.readReportingService.getAllowedParameters(),
|
||||
this.reportingProcessServiceProvider.findAllReportingTypes());
|
||||
}
|
||||
return this.toApiJsonSerializer.serialize(settings, result, this.responseDataParameters);
|
||||
return this.toApiJsonSerializer.serialize(settings, result, RESPONSE_DATA_PARAMETERS);
|
||||
}
|
||||
|
||||
@GET
|
||||
@@ -136,14 +136,14 @@ public class ReportsApiResource {
|
||||
@ApiResponse(responseCode = "200", description = "OK", content = @Content(schema = @Schema(implementation = ReportsApiResourceSwagger.GetReportsTemplateResponse.class))) })
|
||||
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();
|
||||
result.appendedTemplate(this.readReportingService.getAllowedParameters(),
|
||||
this.reportingProcessServiceProvider.findAllReportingTypes());
|
||||
|
||||
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
|
||||
|
||||
+2
-2
@@ -39,7 +39,7 @@ import org.springframework.stereotype.Component;
|
||||
public class DataTableValidator {
|
||||
|
||||
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));
|
||||
|
||||
@Autowired
|
||||
@@ -50,7 +50,7 @@ public class DataTableValidator {
|
||||
public void validateDataTableRegistration(final String json) {
|
||||
|
||||
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 DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors)
|
||||
|
||||
+2
-2
@@ -36,7 +36,7 @@ public final class ReportCommandFromApiJsonDeserializer {
|
||||
/**
|
||||
* 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"));
|
||||
|
||||
private final FromJsonHelper fromApiJsonHelper;
|
||||
@@ -53,6 +53,6 @@ public final class ReportCommandFromApiJsonDeserializer {
|
||||
|
||||
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
|
||||
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.
|
||||
*/
|
||||
private final Set<String> supportedParameters = new HashSet<>(
|
||||
Arrays.asList("entity", "datatableName", "status", "systemDefined", "productId"));
|
||||
|
||||
private static final Set<String> SUPPORTED_PARAMETERS = new HashSet<>(
|
||||
Arrays.asList(ENTITY, DATATABLE_NAME, STATUS, SYSTEM_DEFINED, PRODUCT_ID));
|
||||
private final FromJsonHelper fromApiJsonHelper;
|
||||
|
||||
@Autowired
|
||||
@@ -58,33 +63,35 @@ public final class EntityDatatableChecksDataValidator {
|
||||
throw new InvalidJsonException();
|
||||
}
|
||||
|
||||
final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType();
|
||||
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParameters);
|
||||
final Type typeOfMap = new TypeToken<Map<String, Object>>() {
|
||||
|
||||
}.getType();
|
||||
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, SUPPORTED_PARAMETERS);
|
||||
|
||||
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 String entity = this.fromApiJsonHelper.extractStringNamed("entity", element);
|
||||
baseDataValidator.reset().parameter("entity").value(entity).notBlank().isOneOfTheseStringValues(EntityTables.getEntitiesList());
|
||||
final String entity = this.fromApiJsonHelper.extractStringNamed(ENTITY, element);
|
||||
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();
|
||||
|
||||
baseDataValidator.reset().parameter("status").value(status).isOneOfTheseValues(entityTablesStatuses);
|
||||
baseDataValidator.reset().parameter(STATUS).value(status).isOneOfTheseValues(entityTablesStatuses);
|
||||
|
||||
final String datatableName = this.fromApiJsonHelper.extractStringNamed("datatableName", element);
|
||||
baseDataValidator.reset().parameter("datatableName").value(datatableName).notBlank();
|
||||
final String datatableName = this.fromApiJsonHelper.extractStringNamed(DATATABLE_NAME, element);
|
||||
baseDataValidator.reset().parameter(DATATABLE_NAME).value(datatableName).notBlank();
|
||||
|
||||
if (this.fromApiJsonHelper.parameterExists("systemDefined", element)) {
|
||||
final String systemDefined = this.fromApiJsonHelper.extractStringNamed("systemDefined", element);
|
||||
baseDataValidator.reset().parameter("systemDefined").value(systemDefined).validateForBooleanValue();
|
||||
if (this.fromApiJsonHelper.parameterExists(SYSTEM_DEFINED, element)) {
|
||||
final String systemDefined = this.fromApiJsonHelper.extractStringNamed(SYSTEM_DEFINED, element);
|
||||
baseDataValidator.reset().parameter(SYSTEM_DEFINED).value(systemDefined).validateForBooleanValue();
|
||||
}
|
||||
|
||||
if (this.fromApiJsonHelper.parameterExists("productId", element)) {
|
||||
final long productId = this.fromApiJsonHelper.extractLongNamed("productId", element);
|
||||
baseDataValidator.reset().parameter("productId").value(productId).integerZeroOrGreater();
|
||||
if (this.fromApiJsonHelper.parameterExists(PRODUCT_ID, element)) {
|
||||
final long productId = this.fromApiJsonHelper.extractLongNamed(PRODUCT_ID, element);
|
||||
baseDataValidator.reset().parameter(PRODUCT_ID).value(productId).integerZeroOrGreater();
|
||||
}
|
||||
|
||||
throwExceptionIfValidationWarningsExist(dataValidationErrors);
|
||||
|
||||
+7
-7
@@ -71,10 +71,10 @@ import org.springframework.stereotype.Component;
|
||||
+ "Groups: URL Pattern as groups")
|
||||
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"));
|
||||
|
||||
private final String systemEntityType = "DOCUMENT";
|
||||
private static final String SYSTEM_ENTITY_TYPE = "DOCUMENT";
|
||||
|
||||
private final PlatformSecurityContext context;
|
||||
private final DocumentReadPlatformService documentReadPlatformService;
|
||||
@@ -107,12 +107,12 @@ public class DocumentManagementApiResource {
|
||||
@PathParam("entityType") @Parameter(description = "entityType") final String entityType,
|
||||
@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 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
|
||||
@@ -202,12 +202,12 @@ public class DocumentManagementApiResource {
|
||||
@PathParam("entityId") @Parameter(description = "entityId") final Long entityId,
|
||||
@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 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
|
||||
@@ -221,7 +221,7 @@ public class DocumentManagementApiResource {
|
||||
@PathParam("entityId") @Parameter(description = "entityId") final Long entityId,
|
||||
@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);
|
||||
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.webTemplateName;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.apache.fineract.infrastructure.hooks.domain.Hook;
|
||||
import org.springframework.beans.BeansException;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.context.ApplicationContextAware;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Service
|
||||
public class HookProcessorProvider implements ApplicationContextAware {
|
||||
@RequiredArgsConstructor
|
||||
public class HookProcessorProvider {
|
||||
|
||||
private ApplicationContext applicationContext;
|
||||
|
||||
@Override
|
||||
public void setApplicationContext(final ApplicationContext applicationContext) throws BeansException {
|
||||
this.applicationContext = applicationContext;
|
||||
}
|
||||
private final ApplicationContext applicationContext;
|
||||
|
||||
public HookProcessor getProcessor(final Hook hook) {
|
||||
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 com.fasterxml.jackson.core.JsonParseException;
|
||||
import com.fasterxml.jackson.databind.JsonMappingException;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.google.gson.Gson;
|
||||
import com.google.gson.JsonObject;
|
||||
@@ -80,11 +78,11 @@ public class TwilioHookProcessor implements HookProcessor {
|
||||
}
|
||||
|
||||
if (apiKey != null && !apiKey.equals("")) {
|
||||
JsonObject json = null;
|
||||
JsonObject json;
|
||||
if (hook.getUgdTemplate() != null) {
|
||||
entityName = "sms";
|
||||
actionName = "send";
|
||||
json = processUgdTemplate(payload, hook, context.getAuthTokenContext());
|
||||
json = processUgdTemplate(payload, hook);
|
||||
if (json == null) {
|
||||
return;
|
||||
}
|
||||
@@ -96,8 +94,7 @@ public class TwilioHookProcessor implements HookProcessor {
|
||||
}
|
||||
}
|
||||
|
||||
private JsonObject processUgdTemplate(final String payload, final Hook hook, final String authToken)
|
||||
throws JsonParseException, JsonMappingException, IOException {
|
||||
private JsonObject processUgdTemplate(final String payload, final Hook hook) throws IOException {
|
||||
JsonObject json = null;
|
||||
@SuppressWarnings("unchecked")
|
||||
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 String mobileNo = client.mobileNo();
|
||||
if (mobileNo != null && !mobileNo.isEmpty()) {
|
||||
this.templateMergeService.setAuthToken(authToken);
|
||||
final String compiledMessage = this.templateMergeService.compile(hook.getUgdTemplate(), map).replace("<p>", "")
|
||||
.replace("</p>", "");
|
||||
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.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.ApplicationListener;
|
||||
import org.springframework.context.annotation.Lazy;
|
||||
import org.springframework.context.event.ContextClosedEvent;
|
||||
import org.springframework.scheduling.quartz.CronTriggerFactoryBean;
|
||||
import org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean;
|
||||
@@ -68,10 +69,11 @@ public class JobRegisterServiceImpl implements JobRegisterService, ApplicationLi
|
||||
@Autowired
|
||||
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
|
||||
private SchedulerStopListener schedulerStopListener = new SchedulerStopListener(this);
|
||||
@Autowired
|
||||
@Lazy
|
||||
private SchedulerStopListener schedulerStopListener;
|
||||
|
||||
@Autowired
|
||||
private FineractProperties fineractProperties;
|
||||
@@ -93,14 +95,14 @@ public class JobRegisterServiceImpl implements JobRegisterService, ApplicationLi
|
||||
jobDataMap.put(SchedulerServiceConstants.TRIGGER_TYPE_REFERENCE, triggerType);
|
||||
jobDataMap.put(SchedulerServiceConstants.TENANT_IDENTIFIER, ThreadLocalContextUtil.getTenant().getTenantIdentifier());
|
||||
final String schedulerName = getSchedulerName(scheduledJobDetail);
|
||||
final Scheduler scheduler = this.schedulers.get(schedulerName);
|
||||
final Scheduler scheduler = SCHEDULERS.get(schedulerName);
|
||||
final JobDetail jobDetail = createJobDetail(scheduledJobDetail);
|
||||
JobKey jobKey = jobDetail.getKey();
|
||||
if (scheduler == null || !scheduler.checkExists(jobKey)) {
|
||||
final String tempSchedulerName = "temp" + scheduledJobDetail.getId();
|
||||
final Scheduler tempScheduler = createScheduler(tempSchedulerName, 1, schedulerJobListener, schedulerStopListener);
|
||||
jobDataMap.put(SchedulerServiceConstants.SCHEDULER_NAME, tempSchedulerName);
|
||||
schedulers.put(tempSchedulerName, tempScheduler);
|
||||
SCHEDULERS.put(tempSchedulerName, tempScheduler);
|
||||
tempScheduler.addJob(jobDetail, true);
|
||||
tempScheduler.triggerJob(jobKey, jobDataMap);
|
||||
} else {
|
||||
@@ -120,13 +122,13 @@ public class JobRegisterServiceImpl implements JobRegisterService, ApplicationLi
|
||||
final String jobIdentity = scheduledJobDetail.getJobKey();
|
||||
final JobKey jobKey = constructJobKey(jobIdentity);
|
||||
final String schedulername = getSchedulerName(scheduledJobDetail);
|
||||
final Scheduler scheduler = this.schedulers.get(schedulername);
|
||||
final Scheduler scheduler = SCHEDULERS.get(schedulername);
|
||||
if (scheduler != null) {
|
||||
scheduler.deleteJob(jobKey);
|
||||
}
|
||||
scheduleJob(scheduledJobDetail);
|
||||
this.schedularWritePlatformService.saveOrUpdate(scheduledJobDetail);
|
||||
} catch (final Throwable throwable) {
|
||||
} catch (final Exception throwable) {
|
||||
final String stackTrace = getStackTraceAsString(throwable);
|
||||
scheduledJobDetail.setErrorLog(stackTrace);
|
||||
this.schedularWritePlatformService.saveOrUpdate(scheduledJobDetail);
|
||||
@@ -158,7 +160,7 @@ public class JobRegisterServiceImpl implements JobRegisterService, ApplicationLi
|
||||
jobDetail.setMismatchedJob(false);
|
||||
}
|
||||
final String schedulerName = getSchedulerName(jobDetail);
|
||||
final Scheduler scheduler = this.schedulers.get(schedulerName);
|
||||
final Scheduler scheduler = SCHEDULERS.get(schedulerName);
|
||||
if (scheduler != null) {
|
||||
final String key = jobDetail.getJobKey();
|
||||
final JobKey jobKey = constructJobKey(key);
|
||||
@@ -244,7 +246,7 @@ public class JobRegisterServiceImpl implements JobRegisterService, ApplicationLi
|
||||
scheduler.scheduleJob(jobDetail, trigger);
|
||||
scheduledJobDetails.setNextRunTime(trigger.getNextFireTime());
|
||||
scheduledJobDetails.setErrorLog(null);
|
||||
} catch (final Throwable throwable) {
|
||||
} catch (final Exception throwable) {
|
||||
scheduledJobDetails.setNextRunTime(null);
|
||||
final String stackTrace = getStackTraceAsString(throwable);
|
||||
scheduledJobDetails.setErrorLog(stackTrace);
|
||||
@@ -255,7 +257,7 @@ public class JobRegisterServiceImpl implements JobRegisterService, ApplicationLi
|
||||
|
||||
@Override
|
||||
public void stopAllSchedulers() {
|
||||
for (Scheduler scheduler : this.schedulers.values()) {
|
||||
for (Scheduler scheduler : SCHEDULERS.values()) {
|
||||
try {
|
||||
scheduler.shutdown();
|
||||
} catch (final SchedulerException e) {
|
||||
@@ -266,21 +268,21 @@ public class JobRegisterServiceImpl implements JobRegisterService, ApplicationLi
|
||||
|
||||
private Scheduler getScheduler(final ScheduledJobDetail scheduledJobDetail) throws Exception {
|
||||
final String schedulername = getSchedulerName(scheduledJobDetail);
|
||||
Scheduler scheduler = this.schedulers.get(schedulername);
|
||||
Scheduler scheduler = SCHEDULERS.get(schedulername);
|
||||
if (scheduler == null) {
|
||||
int noOfThreads = SchedulerServiceConstants.DEFAULT_THREAD_COUNT;
|
||||
if (scheduledJobDetail.getSchedulerGroup() > 0) {
|
||||
noOfThreads = SchedulerServiceConstants.GROUP_THREAD_COUNT;
|
||||
}
|
||||
scheduler = createScheduler(schedulername, noOfThreads, schedulerJobListener);
|
||||
this.schedulers.put(schedulername, scheduler);
|
||||
SCHEDULERS.put(schedulername, scheduler);
|
||||
}
|
||||
return scheduler;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void stopScheduler(final String name) {
|
||||
final Scheduler scheduler = this.schedulers.remove(name);
|
||||
final Scheduler scheduler = SCHEDULERS.remove(name);
|
||||
try {
|
||||
scheduler.shutdown();
|
||||
} catch (final SchedulerException e) {
|
||||
@@ -363,7 +365,6 @@ public class JobRegisterServiceImpl implements JobRegisterService, ApplicationLi
|
||||
|
||||
private JobKey constructJobKey(final String 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 jobKey;
|
||||
return new JobKey(keyParams.get(0), keyParams.get(1));
|
||||
}
|
||||
}
|
||||
|
||||
+5
-7
@@ -18,13 +18,17 @@
|
||||
*/
|
||||
package org.apache.fineract.infrastructure.jobs.service;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.quartz.JobExecutionContext;
|
||||
import org.quartz.JobExecutionException;
|
||||
import org.quartz.JobListener;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* Global job Listener class to Stop the temporary scheduler once job execution completes
|
||||
*/
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class SchedulerStopListener implements JobListener {
|
||||
|
||||
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) {
|
||||
final String schedulerName = context.getTrigger().getJobDataMap().getString(SchedulerServiceConstants.SCHEDULER_NAME);
|
||||
if (schedulerName != null) {
|
||||
final Thread newThread = new Thread(new Runnable() {
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
SchedulerStopListener.this.jobRegisterService.stopScheduler(schedulerName);
|
||||
}
|
||||
});
|
||||
final Thread newThread = new Thread(() -> SchedulerStopListener.this.jobRegisterService.stopScheduler(schedulerName));
|
||||
newThread.start();
|
||||
}
|
||||
}
|
||||
|
||||
+26
-27
@@ -38,7 +38,6 @@ public class ReportMailingJobEmailServiceImpl implements ReportMailingJobEmailSe
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(ReportMailingJobEmailServiceImpl.class);
|
||||
private final ReportMailingJobConfigurationReadPlatformService reportMailingJobConfigurationReadPlatformService;
|
||||
private Collection<ReportMailingJobConfigurationData> reportMailingJobConfigurationDataCollection;
|
||||
|
||||
/**
|
||||
* ReportMailingJobEmailServiceImpl constructor
|
||||
@@ -52,17 +51,18 @@ public class ReportMailingJobEmailServiceImpl implements ReportMailingJobEmailSe
|
||||
|
||||
@Override
|
||||
public void sendEmailWithAttachment(ReportMailingJobEmailData reportMailingJobEmailData) {
|
||||
Collection<ReportMailingJobConfigurationData> reportMailingJobConfigurationDataCollection;
|
||||
try {
|
||||
// get all ReportMailingJobConfiguration objects from the database
|
||||
this.reportMailingJobConfigurationDataCollection = this.reportMailingJobConfigurationReadPlatformService
|
||||
reportMailingJobConfigurationDataCollection = this.reportMailingJobConfigurationReadPlatformService
|
||||
.retrieveAllReportMailingJobConfigurations();
|
||||
|
||||
JavaMailSenderImpl javaMailSenderImpl = new JavaMailSenderImpl();
|
||||
javaMailSenderImpl.setHost(this.getGmailSmtpServer());
|
||||
javaMailSenderImpl.setPort(this.getGmailSmtpPort());
|
||||
javaMailSenderImpl.setUsername(this.getGmailSmtpUsername());
|
||||
javaMailSenderImpl.setPassword(this.getGmailSmtpPassword());
|
||||
javaMailSenderImpl.setJavaMailProperties(this.getJavaMailProperties());
|
||||
javaMailSenderImpl.setHost(this.getGmailSmtpServer(reportMailingJobConfigurationDataCollection));
|
||||
javaMailSenderImpl.setPort(this.getGmailSmtpPort(reportMailingJobConfigurationDataCollection));
|
||||
javaMailSenderImpl.setUsername(this.getGmailSmtpUsername(reportMailingJobConfigurationDataCollection));
|
||||
javaMailSenderImpl.setPassword(this.getGmailSmtpPassword(reportMailingJobConfigurationDataCollection));
|
||||
javaMailSenderImpl.setJavaMailProperties(this.getJavaMailProperties(reportMailingJobConfigurationDataCollection));
|
||||
|
||||
MimeMessage mimeMessage = javaMailSenderImpl.createMimeMessage();
|
||||
|
||||
@@ -79,9 +79,7 @@ public class ReportMailingJobEmailServiceImpl implements ReportMailingJobEmailSe
|
||||
}
|
||||
|
||||
javaMailSenderImpl.send(mimeMessage);
|
||||
}
|
||||
|
||||
catch (MessagingException e) {
|
||||
} catch (MessagingException e) {
|
||||
// handle the exception
|
||||
LOG.error("Problem occurred in sendEmailWithAttachment function", e);
|
||||
}
|
||||
@@ -90,12 +88,12 @@ public class ReportMailingJobEmailServiceImpl implements ReportMailingJobEmailSe
|
||||
/**
|
||||
* @return Properties object containing JavaMail properties
|
||||
**/
|
||||
private Properties getJavaMailProperties() {
|
||||
private Properties getJavaMailProperties(Collection<ReportMailingJobConfigurationData> reportMailingJobConfigurationDataCollection) {
|
||||
Properties properties = new Properties();
|
||||
|
||||
properties.setProperty("mail.smtp.auth", "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;
|
||||
}
|
||||
@@ -107,11 +105,12 @@ public class ReportMailingJobEmailServiceImpl implements ReportMailingJobEmailSe
|
||||
* -- the value of the name property
|
||||
* @return ReportMailingJobConfigurationData object
|
||||
**/
|
||||
private ReportMailingJobConfigurationData getReportMailingJobConfigurationData(final String name) {
|
||||
private ReportMailingJobConfigurationData getReportMailingJobConfigurationData(
|
||||
final Collection<ReportMailingJobConfigurationData> reportMailingJobConfigurationDataCollection, final String name) {
|
||||
ReportMailingJobConfigurationData reportMailingJobConfigurationData = null;
|
||||
|
||||
if (this.reportMailingJobConfigurationDataCollection != null && !this.reportMailingJobConfigurationDataCollection.isEmpty()) {
|
||||
for (ReportMailingJobConfigurationData reportMailingJobConfigurationDataObject : this.reportMailingJobConfigurationDataCollection) {
|
||||
if (reportMailingJobConfigurationDataCollection != null && !reportMailingJobConfigurationDataCollection.isEmpty()) {
|
||||
for (ReportMailingJobConfigurationData reportMailingJobConfigurationDataObject : reportMailingJobConfigurationDataCollection) {
|
||||
String configurationName = reportMailingJobConfigurationDataObject.getName();
|
||||
|
||||
if (!StringUtils.isEmpty(configurationName) && configurationName.equals(name)) {
|
||||
@@ -127,9 +126,9 @@ public class ReportMailingJobEmailServiceImpl implements ReportMailingJobEmailSe
|
||||
/**
|
||||
* @return Gmail smtp server name
|
||||
**/
|
||||
private String getGmailSmtpServer() {
|
||||
final ReportMailingJobConfigurationData reportMailingJobConfigurationData = this
|
||||
.getReportMailingJobConfigurationData(ReportMailingJobConstants.GMAIL_SMTP_SERVER);
|
||||
private String getGmailSmtpServer(Collection<ReportMailingJobConfigurationData> reportMailingJobConfigurationDataCollection) {
|
||||
final ReportMailingJobConfigurationData reportMailingJobConfigurationData = this.getReportMailingJobConfigurationData(
|
||||
reportMailingJobConfigurationDataCollection, ReportMailingJobConstants.GMAIL_SMTP_SERVER);
|
||||
|
||||
return (reportMailingJobConfigurationData != null) ? reportMailingJobConfigurationData.getValue() : null;
|
||||
}
|
||||
@@ -137,9 +136,9 @@ public class ReportMailingJobEmailServiceImpl implements ReportMailingJobEmailSe
|
||||
/**
|
||||
* @return Gmail smtp server port number
|
||||
**/
|
||||
private Integer getGmailSmtpPort() {
|
||||
final ReportMailingJobConfigurationData reportMailingJobConfigurationData = this
|
||||
.getReportMailingJobConfigurationData(ReportMailingJobConstants.GMAIL_SMTP_PORT);
|
||||
private Integer getGmailSmtpPort(Collection<ReportMailingJobConfigurationData> reportMailingJobConfigurationDataCollection) {
|
||||
final ReportMailingJobConfigurationData reportMailingJobConfigurationData = this.getReportMailingJobConfigurationData(
|
||||
reportMailingJobConfigurationDataCollection, ReportMailingJobConstants.GMAIL_SMTP_PORT);
|
||||
final String portNumber = (reportMailingJobConfigurationData != null) ? reportMailingJobConfigurationData.getValue() : null;
|
||||
|
||||
return (portNumber != null) ? Integer.parseInt(portNumber) : null;
|
||||
@@ -148,9 +147,9 @@ public class ReportMailingJobEmailServiceImpl implements ReportMailingJobEmailSe
|
||||
/**
|
||||
* @return Gmail smtp username
|
||||
**/
|
||||
private String getGmailSmtpUsername() {
|
||||
final ReportMailingJobConfigurationData reportMailingJobConfigurationData = this
|
||||
.getReportMailingJobConfigurationData(ReportMailingJobConstants.GMAIL_SMTP_USERNAME);
|
||||
private String getGmailSmtpUsername(Collection<ReportMailingJobConfigurationData> reportMailingJobConfigurationDataCollection) {
|
||||
final ReportMailingJobConfigurationData reportMailingJobConfigurationData = this.getReportMailingJobConfigurationData(
|
||||
reportMailingJobConfigurationDataCollection, ReportMailingJobConstants.GMAIL_SMTP_USERNAME);
|
||||
|
||||
return (reportMailingJobConfigurationData != null) ? reportMailingJobConfigurationData.getValue() : null;
|
||||
}
|
||||
@@ -158,9 +157,9 @@ public class ReportMailingJobEmailServiceImpl implements ReportMailingJobEmailSe
|
||||
/**
|
||||
* @return Gmail smtp password
|
||||
**/
|
||||
private String getGmailSmtpPassword() {
|
||||
final ReportMailingJobConfigurationData reportMailingJobConfigurationData = this
|
||||
.getReportMailingJobConfigurationData(ReportMailingJobConstants.GMAIL_SMTP_PASSWORD);
|
||||
private String getGmailSmtpPassword(Collection<ReportMailingJobConfigurationData> reportMailingJobConfigurationDataCollection) {
|
||||
final ReportMailingJobConfigurationData reportMailingJobConfigurationData = this.getReportMailingJobConfigurationData(
|
||||
reportMailingJobConfigurationDataCollection, ReportMailingJobConstants.GMAIL_SMTP_PASSWORD);
|
||||
|
||||
return (reportMailingJobConfigurationData != null) ? reportMailingJobConfigurationData.getValue() : null;
|
||||
}
|
||||
|
||||
+2
-2
@@ -45,7 +45,7 @@ import org.springframework.stereotype.Component;
|
||||
@ConditionalOnProperty("fineract.security.2fa.enabled")
|
||||
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 TwoFactorConfigurationService configurationService;
|
||||
@@ -64,7 +64,7 @@ public class TwoFactorConfigurationApiResource {
|
||||
|
||||
@GET
|
||||
public String retrieveAll() {
|
||||
this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions);
|
||||
this.context.authenticatedUser().validateHasReadPermission(RESOURCE_NAME_FOR_PERMISSIONS);
|
||||
Map<String, Object> configurationMap = configurationService.retrieveAll();
|
||||
return toApiJsonSerializer.serialize(configurationMap);
|
||||
}
|
||||
|
||||
+4
-4
@@ -30,21 +30,21 @@ import org.springframework.util.Assert;
|
||||
@SuppressWarnings({ "MemberName" })
|
||||
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) {
|
||||
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) {
|
||||
Assert.notNull(user, "User 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) {
|
||||
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 = "")
|
||||
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"));
|
||||
|
||||
private final PlatformSecurityContext context;
|
||||
@@ -75,6 +75,6 @@ public class MixTaxonomyApiResource {
|
||||
final List<MixTaxonomyData> taxonomyDatas = this.readTaxonomyService.retrieveAll();
|
||||
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 = "")
|
||||
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 ToApiJsonSerializer<MixTaxonomyMappingData> toApiJsonSerializer;
|
||||
@@ -80,7 +80,7 @@ public class MixTaxonomyMappingApiResource {
|
||||
this.context.authenticatedUser();
|
||||
final MixTaxonomyMappingData mappingData = this.readTaxonomyMappingService.retrieveTaxonomyMapping();
|
||||
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
|
||||
|
||||
@@ -44,13 +44,6 @@ public class XBRLBuilder {
|
||||
private static final String UNITID_PURE = "Unit1";
|
||||
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
|
||||
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) {
|
||||
this.instantScenarioCounter = 1;
|
||||
this.durationScenarioCounter = 1;
|
||||
this.contextMap = new HashMap<>();
|
||||
Integer instantScenarioCounter = 0;
|
||||
Integer durationScenarioCounter = 0;
|
||||
Map<ContextData, String> contextMap = new HashMap<>();
|
||||
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");
|
||||
|
||||
this.startDate = startDate;
|
||||
this.endDate = endDate;
|
||||
|
||||
for (final Map.Entry<MixTaxonomyData, BigDecimal> entry : map.entrySet()) {
|
||||
final MixTaxonomyData taxonomy = entry.getKey();
|
||||
final BigDecimal value = entry.getValue();
|
||||
addTaxonomy(this.root, taxonomy, value);
|
||||
addTaxonomy(root, taxonomy, value, startDate, endDate, instantScenarioCounter, durationScenarioCounter, contextMap);
|
||||
|
||||
}
|
||||
|
||||
addContexts();
|
||||
addCurrencyUnit(currency);
|
||||
addNumberUnit();
|
||||
addContexts(root, startDate, endDate, contextMap);
|
||||
addCurrencyUnit(root, currency);
|
||||
addNumberUnit(root);
|
||||
|
||||
doc.setXMLEncoding("UTF-8");
|
||||
|
||||
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
|
||||
if (this.startDate == null || this.endDate == null) {
|
||||
if (startDate == null || endDate == 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);
|
||||
if (ns != null) {
|
||||
|
||||
this.root.addNamespace(prefix, ns.getUrl());
|
||||
rootElement.addNamespace(prefix, ns.getUrl());
|
||||
}
|
||||
qname = prefix + ":" + taxonomy.getName();
|
||||
|
||||
@@ -127,18 +119,19 @@ public class XBRLBuilder {
|
||||
: 1);
|
||||
}
|
||||
|
||||
if (!this.contextMap.containsKey(context)) {
|
||||
if (!contextMap.containsKey(context)) {
|
||||
|
||||
final String startDateStr = timeFormat.format(this.startDate);
|
||||
final String endDateStr = timeFormat.format(this.endDate);
|
||||
final String startDateStr = timeFormat.format(startDate);
|
||||
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++
|
||||
: "Duration_" + startDateStr + "_To_" + endDateStr + this.durationScenarioCounter++;
|
||||
|
||||
this.contextMap.put(context, contextRefID);
|
||||
contextMap.put(context, contextRefID);
|
||||
}
|
||||
|
||||
xmlElement.addAttribute("contextRef", this.contextMap.get(context));
|
||||
xmlElement.addAttribute("contextRef", contextMap.get(context));
|
||||
xmlElement.addAttribute("unitRef", getUnitRef(taxonomy));
|
||||
xmlElement.addAttribute("decimals", getNumberOfDecimalPlaces(value).toString());
|
||||
|
||||
@@ -155,8 +148,8 @@ public class XBRLBuilder {
|
||||
/**
|
||||
* Adds the generic number unit
|
||||
*/
|
||||
void addNumberUnit() {
|
||||
final Element numerUnit = this.root.addElement("unit");
|
||||
private void addNumberUnit(final Element root) {
|
||||
final Element numerUnit = root.addElement("unit");
|
||||
numerUnit.addAttribute("id", UNITID_PURE);
|
||||
final Element measure = numerUnit.addElement("measure");
|
||||
measure.addText("xbrli:pure");
|
||||
@@ -168,29 +161,29 @@ public class XBRLBuilder {
|
||||
*
|
||||
* @param currencyCode
|
||||
*/
|
||||
public void addCurrencyUnit(final String currencyCode) {
|
||||
final Element currencyUnitElement = this.root.addElement("unit");
|
||||
private void addCurrencyUnit(final Element root, final String currencyCode) {
|
||||
final Element currencyUnitElement = root.addElement("unit");
|
||||
currencyUnitElement.addAttribute("id", UNITID_CUR);
|
||||
final Element measure = currencyUnitElement.addElement("measure");
|
||||
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");
|
||||
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 Element contextElement = this.root.addElement("context");
|
||||
final Element contextElement = root.addElement("context");
|
||||
contextElement.addAttribute("id", entry.getValue());
|
||||
contextElement.addElement("entity").addElement("identifier").addAttribute("scheme", SCHEME_URL).addText(IDENTIFIER);
|
||||
|
||||
final Element periodElement = contextElement.addElement("period");
|
||||
|
||||
if (context.getPeriodType() == 0) {
|
||||
periodElement.addElement("instant").addText(format.format(this.endDate));
|
||||
periodElement.addElement("instant").addText(format.format(endDate));
|
||||
} else {
|
||||
periodElement.addElement("startDate").addText(format.format(this.startDate));
|
||||
periodElement.addElement("endDate").addText(format.format(this.endDate));
|
||||
periodElement.addElement("startDate").addText(format.format(startDate));
|
||||
periodElement.addElement("endDate").addText(format.format(endDate));
|
||||
}
|
||||
|
||||
final String dimension = context.getDimension();
|
||||
|
||||
+20
-22
@@ -23,6 +23,7 @@ import java.math.BigDecimal;
|
||||
import java.sql.Date;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
@@ -49,7 +50,6 @@ public class XBRLResultServiceImpl implements XBRLResultService {
|
||||
private final MixTaxonomyMappingReadPlatformService readTaxonomyMappingService;
|
||||
private final MixTaxonomyReadPlatformService readTaxonomyService;
|
||||
private final JdbcTemplate jdbcTemplate;
|
||||
private HashMap<String, BigDecimal> accountBalanceMap;
|
||||
|
||||
@Autowired
|
||||
public XBRLResultServiceImpl(final JdbcTemplate jdbcTemplate, final MixTaxonomyMappingReadPlatformService readTaxonomyMappingService,
|
||||
@@ -85,13 +85,11 @@ public class XBRLResultServiceImpl implements XBRLResultService {
|
||||
}
|
||||
// <taxonomyId, value>
|
||||
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()) {
|
||||
final BigDecimal value = processMappingString(entry.getValue());
|
||||
if (value != null) {
|
||||
final MixTaxonomyData taxonomy = this.readTaxonomyService.retrieveOne(Long.parseLong(entry.getKey()));
|
||||
resultMap.put(taxonomy, value);
|
||||
}
|
||||
final BigDecimal value = processMappingString(accountBalanceMap, entry.getValue());
|
||||
final MixTaxonomyData taxonomy = this.readTaxonomyService.retrieveOne(Long.parseLong(entry.getKey()));
|
||||
resultMap.put(taxonomy, value);
|
||||
|
||||
}
|
||||
return resultMap;
|
||||
@@ -100,7 +98,7 @@ public class XBRLResultServiceImpl implements XBRLResultService {
|
||||
}
|
||||
|
||||
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 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
|
||||
@@ -134,30 +132,30 @@ public class XBRLResultServiceImpl implements XBRLResultService {
|
||||
// ${branch}=1) "
|
||||
// +
|
||||
+ " group by name, glcode " + "order by glcode) credits " + "on debits.glcode=credits.glcode;";
|
||||
return sql;
|
||||
}
|
||||
|
||||
private void setupBalanceMap(final String sql) {
|
||||
if (this.accountBalanceMap == null) {
|
||||
this.accountBalanceMap = new HashMap<>();
|
||||
final SqlRowSet rs = this.jdbcTemplate.queryForRowSet(sql);
|
||||
while (rs.next()) {
|
||||
this.accountBalanceMap.put(rs.getString("glcode"), rs.getBigDecimal("balance"));
|
||||
}
|
||||
private Map<String, BigDecimal> setupBalanceMap(final String sql) {
|
||||
Map<String, BigDecimal> accountBalanceMap = new HashMap<>();
|
||||
|
||||
final SqlRowSet rs = this.jdbcTemplate.queryForRowSet(sql);
|
||||
while (rs.next()) {
|
||||
accountBalanceMap.put(rs.getString("glcode"), rs.getBigDecimal("balance"));
|
||||
}
|
||||
|
||||
return accountBalanceMap;
|
||||
}
|
||||
|
||||
// Calculate Taxonomy value from expression
|
||||
private BigDecimal processMappingString(String mappingString) {
|
||||
final ArrayList<String> glCodes = getGLCodes(mappingString);
|
||||
private BigDecimal processMappingString(Map<String, BigDecimal> accountBalanceMap, String mappingString) {
|
||||
final List<String> glCodes = getGLCodes(mappingString);
|
||||
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");
|
||||
}
|
||||
|
||||
// evaluate the expression
|
||||
Float eval = 0f;
|
||||
float eval = 0f;
|
||||
try {
|
||||
final Number value = (Number) SCRIPT_ENGINE.eval(mappingString);
|
||||
if (value != null) {
|
||||
@@ -168,10 +166,10 @@ public class XBRLResultServiceImpl implements XBRLResultService {
|
||||
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<>();
|
||||
|
||||
|
||||
+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.")
|
||||
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 OrganisationCurrencyReadPlatformService readPlatformService;
|
||||
@@ -89,12 +89,12 @@ public class CurrenciesApiResource {
|
||||
@ApiResponse(responseCode = "200", description = "OK", content = @Content(schema = @Schema(implementation = CurrenciesApiResourceSwagger.GetCurrenciesResponse.class))) })
|
||||
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 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
|
||||
|
||||
+6
-6
@@ -22,7 +22,6 @@ import com.google.gson.JsonElement;
|
||||
import com.google.gson.reflect.TypeToken;
|
||||
import java.lang.reflect.Type;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
@@ -39,10 +38,11 @@ import org.springframework.stereotype.Component;
|
||||
@Component
|
||||
public final class CurrencyCommandFromApiJsonDeserializer {
|
||||
|
||||
public static final String CURRENCIES = "currencies";
|
||||
/**
|
||||
* 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;
|
||||
|
||||
@@ -58,14 +58,14 @@ public final class CurrencyCommandFromApiJsonDeserializer {
|
||||
}
|
||||
|
||||
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 DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("currencies");
|
||||
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource(CURRENCIES);
|
||||
|
||||
final JsonElement element = this.fromApiJsonHelper.parse(json);
|
||||
final String[] currencies = this.fromApiJsonHelper.extractArrayNamed("currencies", element);
|
||||
baseDataValidator.reset().parameter("currencies").value(currencies).arrayNotEmpty();
|
||||
final String[] currencies = this.fromApiJsonHelper.extractArrayNamed(CURRENCIES, element);
|
||||
baseDataValidator.reset().parameter(CURRENCIES).value(currencies).arrayNotEmpty();
|
||||
|
||||
throwExceptionIfValidationWarningsExist(dataValidationErrors);
|
||||
}
|
||||
|
||||
+3
-3
@@ -56,7 +56,7 @@ public class OfficeTransactionsApiResource {
|
||||
Arrays.asList("id", "transactionDate", "fromOfficeId", "fromOfficeName", "toOfficeId", "toOfficeIdName", "currencyCode",
|
||||
"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 OfficeReadPlatformService readPlatformService;
|
||||
@@ -81,7 +81,7 @@ public class OfficeTransactionsApiResource {
|
||||
@Produces({ MediaType.APPLICATION_JSON })
|
||||
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();
|
||||
|
||||
@@ -95,7 +95,7 @@ public class OfficeTransactionsApiResource {
|
||||
@Produces({ MediaType.APPLICATION_JSON })
|
||||
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();
|
||||
|
||||
|
||||
+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.tags.Tag;
|
||||
import java.io.InputStream;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import javax.ws.rs.Consumes;
|
||||
import javax.ws.rs.DefaultValue;
|
||||
@@ -75,10 +75,10 @@ public class OfficesApiResource {
|
||||
/**
|
||||
* 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",
|
||||
"openingDate", "hierarchy", "parentId", "parentName", "allowedParents"));
|
||||
private static final Set<String> RESPONSE_DATA_PARAMETERS = new HashSet<>(
|
||||
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 OfficeReadPlatformService readPlatformService;
|
||||
@@ -115,14 +115,14 @@ public class OfficesApiResource {
|
||||
@QueryParam("orderBy") @Parameter(description = "orderBy") final String orderBy,
|
||||
@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 Collection<OfficeData> offices = this.readPlatformService.retrieveAllOffices(onlyManualEntries, searchParameters);
|
||||
|
||||
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
|
||||
@@ -135,7 +135,7 @@ public class OfficesApiResource {
|
||||
@ApiResponse(responseCode = "200", description = "OK", content = @Content(schema = @Schema(implementation = OfficesApiResourceSwagger.GetOfficesTemplateResponse.class))) })
|
||||
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();
|
||||
|
||||
@@ -143,7 +143,7 @@ public class OfficesApiResource {
|
||||
office = OfficeData.appendedTemplate(office, allowedParents);
|
||||
|
||||
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
|
||||
@@ -176,7 +176,7 @@ public class OfficesApiResource {
|
||||
public String retreiveOffice(@PathParam("officeId") @Parameter(description = "officeId") final Long officeId,
|
||||
@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());
|
||||
|
||||
@@ -186,7 +186,7 @@ public class OfficesApiResource {
|
||||
office = OfficeData.appendedTemplate(office, allowedParents);
|
||||
}
|
||||
|
||||
return this.toApiJsonSerializer.serialize(settings, office, this.responseDataParameters);
|
||||
return this.toApiJsonSerializer.serialize(settings, office, RESPONSE_DATA_PARAMETERS);
|
||||
}
|
||||
|
||||
@PUT
|
||||
|
||||
+32
-26
@@ -43,11 +43,17 @@ import org.springframework.stereotype.Component;
|
||||
@Component
|
||||
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.
|
||||
*/
|
||||
private final Set<String> supportedParameters = new HashSet<>(
|
||||
Arrays.asList("name", "parentId", "openingDate", "externalId", "locale", "dateFormat"));
|
||||
private static final Set<String> SUPPORTED_PARAMETERS = new HashSet<>(
|
||||
Arrays.asList(NAME, PARENT_ID, OPENING_DATE, EXTERNAL_ID, LOCALE, DATE_FORMAT));
|
||||
|
||||
private final FromJsonHelper fromApiJsonHelper;
|
||||
|
||||
@@ -62,27 +68,27 @@ public final class OfficeCommandFromApiJsonDeserializer {
|
||||
}
|
||||
|
||||
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 DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("office");
|
||||
|
||||
final JsonElement element = this.fromApiJsonHelper.parse(json);
|
||||
|
||||
final String name = this.fromApiJsonHelper.extractStringNamed("name", element);
|
||||
baseDataValidator.reset().parameter("name").value(name).notBlank().notExceedingLengthOf(100);
|
||||
final String name = this.fromApiJsonHelper.extractStringNamed(NAME, element);
|
||||
baseDataValidator.reset().parameter(NAME).value(name).notBlank().notExceedingLengthOf(100);
|
||||
|
||||
final LocalDate openingDate = this.fromApiJsonHelper.extractLocalDateNamed("openingDate", element);
|
||||
baseDataValidator.reset().parameter("openingDate").value(openingDate).notNull();
|
||||
final LocalDate openingDate = this.fromApiJsonHelper.extractLocalDateNamed(OPENING_DATE, element);
|
||||
baseDataValidator.reset().parameter(OPENING_DATE).value(openingDate).notNull();
|
||||
|
||||
if (this.fromApiJsonHelper.parameterExists("externalId", element)) {
|
||||
final String externalId = this.fromApiJsonHelper.extractStringNamed("externalId", element);
|
||||
baseDataValidator.reset().parameter("externalId").value(externalId).notExceedingLengthOf(100);
|
||||
if (this.fromApiJsonHelper.parameterExists(EXTERNAL_ID, element)) {
|
||||
final String externalId = this.fromApiJsonHelper.extractStringNamed(EXTERNAL_ID, element);
|
||||
baseDataValidator.reset().parameter(EXTERNAL_ID).value(externalId).notExceedingLengthOf(100);
|
||||
}
|
||||
|
||||
if (this.fromApiJsonHelper.parameterExists("parentId", element)) {
|
||||
final Long parentId = this.fromApiJsonHelper.extractLongNamed("parentId", element);
|
||||
baseDataValidator.reset().parameter("parentId").value(parentId).notNull().integerGreaterThanZero();
|
||||
if (this.fromApiJsonHelper.parameterExists(PARENT_ID, element)) {
|
||||
final Long parentId = this.fromApiJsonHelper.extractLongNamed(PARENT_ID, element);
|
||||
baseDataValidator.reset().parameter(PARENT_ID).value(parentId).notNull().integerGreaterThanZero();
|
||||
}
|
||||
|
||||
throwExceptionIfValidationWarningsExist(dataValidationErrors);
|
||||
@@ -101,31 +107,31 @@ public final class OfficeCommandFromApiJsonDeserializer {
|
||||
}
|
||||
|
||||
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 DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("office");
|
||||
|
||||
final JsonElement element = this.fromApiJsonHelper.parse(json);
|
||||
|
||||
if (this.fromApiJsonHelper.parameterExists("name", element)) {
|
||||
final String name = this.fromApiJsonHelper.extractStringNamed("name", element);
|
||||
baseDataValidator.reset().parameter("name").value(name).notBlank().notExceedingLengthOf(100);
|
||||
if (this.fromApiJsonHelper.parameterExists(NAME, element)) {
|
||||
final String name = this.fromApiJsonHelper.extractStringNamed(NAME, element);
|
||||
baseDataValidator.reset().parameter(NAME).value(name).notBlank().notExceedingLengthOf(100);
|
||||
}
|
||||
|
||||
if (this.fromApiJsonHelper.parameterExists("openingDate", element)) {
|
||||
final LocalDate openingDate = this.fromApiJsonHelper.extractLocalDateNamed("openingDate", element);
|
||||
baseDataValidator.reset().parameter("openingDate").value(openingDate).notNull();
|
||||
if (this.fromApiJsonHelper.parameterExists(OPENING_DATE, element)) {
|
||||
final LocalDate openingDate = this.fromApiJsonHelper.extractLocalDateNamed(OPENING_DATE, element);
|
||||
baseDataValidator.reset().parameter(OPENING_DATE).value(openingDate).notNull();
|
||||
}
|
||||
|
||||
if (this.fromApiJsonHelper.parameterExists("externalId", element)) {
|
||||
final String externalId = this.fromApiJsonHelper.extractStringNamed("externalId", element);
|
||||
baseDataValidator.reset().parameter("externalId").value(externalId).notExceedingLengthOf(100);
|
||||
if (this.fromApiJsonHelper.parameterExists(EXTERNAL_ID, element)) {
|
||||
final String externalId = this.fromApiJsonHelper.extractStringNamed(EXTERNAL_ID, element);
|
||||
baseDataValidator.reset().parameter(EXTERNAL_ID).value(externalId).notExceedingLengthOf(100);
|
||||
}
|
||||
|
||||
if (this.fromApiJsonHelper.parameterExists("parentId", element)) {
|
||||
final Long parentId = this.fromApiJsonHelper.extractLongNamed("parentId", element);
|
||||
baseDataValidator.reset().parameter("parentId").value(parentId).notNull().integerGreaterThanZero();
|
||||
if (this.fromApiJsonHelper.parameterExists(PARENT_ID, element)) {
|
||||
final Long parentId = this.fromApiJsonHelper.extractLongNamed(PARENT_ID, element);
|
||||
baseDataValidator.reset().parameter(PARENT_ID).value(parentId).notNull().integerGreaterThanZero();
|
||||
}
|
||||
|
||||
throwExceptionIfValidationWarningsExist(dataValidationErrors);
|
||||
|
||||
+28
-18
@@ -41,11 +41,19 @@ import org.springframework.stereotype.Component;
|
||||
@Component
|
||||
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.
|
||||
*/
|
||||
private final Set<String> supportedParameters = new HashSet<>(Arrays.asList("fromOfficeId", "toOfficeId", "transactionDate",
|
||||
"currencyCode", "transactionAmount", "description", "locale", "dateFormat"));
|
||||
private static final Set<String> SUPPORTED_PARAMETERS = new HashSet<>(Arrays.asList(FROM_OFFICE_ID, TO_OFFICE_ID, TRANSACTION_DATE,
|
||||
CURRENCY_CODE, TRANSACTION_AMOUNT, DESCRIPTION, LOCALE, DATE_FORMAT));
|
||||
|
||||
private final FromJsonHelper fromApiJsonHelper;
|
||||
|
||||
@@ -59,38 +67,40 @@ public final class OfficeTransactionCommandFromApiJsonDeserializer {
|
||||
throw new InvalidJsonException();
|
||||
}
|
||||
|
||||
final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType();
|
||||
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParameters);
|
||||
final Type typeOfMap = new TypeToken<Map<String, Object>>() {
|
||||
|
||||
}.getType();
|
||||
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, SUPPORTED_PARAMETERS);
|
||||
|
||||
final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
|
||||
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("officeTransaction");
|
||||
|
||||
final JsonElement element = this.fromApiJsonHelper.parse(json);
|
||||
final Long fromOfficeId = this.fromApiJsonHelper.extractLongNamed("fromOfficeId", element);
|
||||
baseDataValidator.reset().parameter("fromOfficeId").value(fromOfficeId).ignoreIfNull().integerGreaterThanZero();
|
||||
final Long fromOfficeId = this.fromApiJsonHelper.extractLongNamed(FROM_OFFICE_ID, element);
|
||||
baseDataValidator.reset().parameter(FROM_OFFICE_ID).value(fromOfficeId).ignoreIfNull().integerGreaterThanZero();
|
||||
|
||||
final Long toOfficeId = this.fromApiJsonHelper.extractLongNamed("toOfficeId", element);
|
||||
baseDataValidator.reset().parameter("toOfficeId").value(toOfficeId).ignoreIfNull().integerGreaterThanZero();
|
||||
final Long toOfficeId = this.fromApiJsonHelper.extractLongNamed(TO_OFFICE_ID, element);
|
||||
baseDataValidator.reset().parameter(TO_OFFICE_ID).value(toOfficeId).ignoreIfNull().integerGreaterThanZero();
|
||||
|
||||
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) {
|
||||
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);
|
||||
baseDataValidator.reset().parameter("transactionDate").value(transactionDate).notNull();
|
||||
final LocalDate transactionDate = this.fromApiJsonHelper.extractLocalDateNamed(TRANSACTION_DATE, element);
|
||||
baseDataValidator.reset().parameter(TRANSACTION_DATE).value(transactionDate).notNull();
|
||||
|
||||
final String currencyCode = this.fromApiJsonHelper.extractStringNamed("currencyCode", element);
|
||||
baseDataValidator.reset().parameter("currencyCode").value(currencyCode).notBlank().notExceedingLengthOf(3);
|
||||
final String currencyCode = this.fromApiJsonHelper.extractStringNamed(CURRENCY_CODE, element);
|
||||
baseDataValidator.reset().parameter(CURRENCY_CODE).value(currencyCode).notBlank().notExceedingLengthOf(3);
|
||||
|
||||
final BigDecimal transactionAmount = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed("transactionAmount", element);
|
||||
baseDataValidator.reset().parameter("transactionAmount").value(transactionAmount).notNull().positiveAmount();
|
||||
final BigDecimal transactionAmount = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed(TRANSACTION_AMOUNT, element);
|
||||
baseDataValidator.reset().parameter(TRANSACTION_AMOUNT).value(transactionAmount).notNull().positiveAmount();
|
||||
|
||||
final String description = this.fromApiJsonHelper.extractStringNamed("description", element);
|
||||
baseDataValidator.reset().parameter("description").value(description).notExceedingLengthOf(100);
|
||||
final String description = this.fromApiJsonHelper.extractStringNamed(DESCRIPTION, element);
|
||||
baseDataValidator.reset().parameter(DESCRIPTION).value(description).notExceedingLengthOf(100);
|
||||
|
||||
throwExceptionIfValidationWarningsExist(dataValidationErrors);
|
||||
}
|
||||
|
||||
+19
-13
@@ -39,11 +39,13 @@ import org.springframework.stereotype.Component;
|
||||
@Component
|
||||
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.
|
||||
*/
|
||||
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;
|
||||
|
||||
@Autowired
|
||||
@@ -55,15 +57,17 @@ public class ProvisioningCategoryDefinitionJsonDeserializer {
|
||||
if (StringUtils.isBlank(json)) {
|
||||
throw new InvalidJsonException();
|
||||
}
|
||||
final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType();
|
||||
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParameters);
|
||||
final Type typeOfMap = new TypeToken<Map<String, Object>>() {
|
||||
|
||||
}.getType();
|
||||
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, SUPPORTED_PARAMETERS);
|
||||
|
||||
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 String name = this.fromApiJsonHelper.extractStringNamed("categoryname", element);
|
||||
baseDataValidator.reset().parameter("categoryname").value(name).notBlank().notExceedingLengthOf(100);
|
||||
final String name = this.fromApiJsonHelper.extractStringNamed(CATEGORYNAME, element);
|
||||
baseDataValidator.reset().parameter(CATEGORYNAME).value(name).notBlank().notExceedingLengthOf(100);
|
||||
if (!dataValidationErrors.isEmpty()) {
|
||||
throw new PlatformApiDataValidationException(dataValidationErrors);
|
||||
}
|
||||
@@ -73,16 +77,18 @@ public class ProvisioningCategoryDefinitionJsonDeserializer {
|
||||
if (StringUtils.isBlank(json)) {
|
||||
throw new InvalidJsonException();
|
||||
}
|
||||
final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType();
|
||||
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParameters);
|
||||
final Type typeOfMap = new TypeToken<Map<String, Object>>() {
|
||||
|
||||
}.getType();
|
||||
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, SUPPORTED_PARAMETERS);
|
||||
|
||||
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);
|
||||
|
||||
if (this.fromApiJsonHelper.parameterExists("categoryname", element)) {
|
||||
final String categoryName = this.fromApiJsonHelper.extractStringNamed("categoryname", element);
|
||||
baseDataValidator.reset().parameter("categoryname").value(categoryName).notBlank().notExceedingLengthOf(100);
|
||||
if (this.fromApiJsonHelper.parameterExists(CATEGORYNAME, element)) {
|
||||
final String categoryName = this.fromApiJsonHelper.extractStringNamed(CATEGORYNAME, element);
|
||||
baseDataValidator.reset().parameter(CATEGORYNAME).value(categoryName).notBlank().notExceedingLengthOf(100);
|
||||
}
|
||||
|
||||
if (!dataValidationErrors.isEmpty()) {
|
||||
|
||||
+7
-7
@@ -76,10 +76,10 @@ public class StaffApiResource {
|
||||
/**
|
||||
* 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",
|
||||
"officeName", "isLoanOfficer", "externalId", "mobileNo", "allowedOffices", "isActive", "joiningDate"));
|
||||
private static final Set<String> RESPONSE_DATA_PARAMETERS = new HashSet<>(Arrays.asList("id", "firstname", "lastname", "displayName",
|
||||
"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 StaffReadPlatformService readPlatformService;
|
||||
@@ -123,7 +123,7 @@ public class StaffApiResource {
|
||||
@DefaultValue("false") @QueryParam("loanOfficersOnly") @Parameter(description = "loanOfficersOnly") final boolean loanOfficersOnly,
|
||||
@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;
|
||||
if (staffInOfficeHierarchy) {
|
||||
@@ -133,7 +133,7 @@ public class StaffApiResource {
|
||||
}
|
||||
|
||||
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
|
||||
@@ -164,7 +164,7 @@ public class StaffApiResource {
|
||||
public String retrieveOne(@PathParam("staffId") @Parameter(description = "staffId") final Long staffId,
|
||||
@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());
|
||||
|
||||
@@ -173,7 +173,7 @@ public class StaffApiResource {
|
||||
final Collection<OfficeData> allowedOffices = this.officeReadPlatformService.retrieveAllOfficesForDropdown();
|
||||
staff = StaffData.templateData(staff, allowedOffices);
|
||||
}
|
||||
return this.toApiJsonSerializer.serialize(settings, staff, this.responseDataParameters);
|
||||
return this.toApiJsonSerializer.serialize(settings, staff, RESPONSE_DATA_PARAMETERS);
|
||||
}
|
||||
|
||||
@PUT
|
||||
|
||||
+74
-59
@@ -42,11 +42,22 @@ import org.springframework.stereotype.Component;
|
||||
@Component
|
||||
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.
|
||||
*/
|
||||
private final Set<String> supportedParameters = new HashSet<>(Arrays.asList("firstname", "lastname", "officeId", "externalId",
|
||||
"mobileNo", "isLoanOfficer", "isActive", "joiningDate", "dateFormat", "locale", "forceStatus"));
|
||||
private static final Set<String> SUPPORTED_PARAMETERS = new HashSet<>(Arrays.asList(FIRSTNAME, LASTNAME, OFFICE_ID, EXTERNAL_ID,
|
||||
MOBILE_NO, IS_LOAN_OFFICER, IS_ACTIVE, JOINING_DATE, DATE_FORMAT, LOCALE, FORCE_STATUS));
|
||||
|
||||
private final FromJsonHelper fromApiJsonHelper;
|
||||
|
||||
@@ -64,22 +75,24 @@ public final class StaffCommandFromApiJsonDeserializer {
|
||||
throw new InvalidJsonException();
|
||||
}
|
||||
|
||||
final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType();
|
||||
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParameters);
|
||||
final Type typeOfMap = new TypeToken<Map<String, Object>>() {
|
||||
|
||||
}.getType();
|
||||
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, SUPPORTED_PARAMETERS);
|
||||
|
||||
final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
|
||||
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("staff");
|
||||
|
||||
final JsonElement element = this.fromApiJsonHelper.parse(json);
|
||||
|
||||
final Long officeId = this.fromApiJsonHelper.extractLongNamed("officeId", element);
|
||||
baseDataValidator.reset().parameter("officeId").value(officeId).notNull().integerGreaterThanZero();
|
||||
final Long officeId = this.fromApiJsonHelper.extractLongNamed(OFFICE_ID, element);
|
||||
baseDataValidator.reset().parameter(OFFICE_ID).value(officeId).notNull().integerGreaterThanZero();
|
||||
|
||||
final String firstname = this.fromApiJsonHelper.extractStringNamed("firstname", element);
|
||||
baseDataValidator.reset().parameter("firstname").value(firstname).notBlank().notExceedingLengthOf(50);
|
||||
final String firstname = this.fromApiJsonHelper.extractStringNamed(FIRSTNAME, element);
|
||||
baseDataValidator.reset().parameter(FIRSTNAME).value(firstname).notBlank().notExceedingLengthOf(50);
|
||||
|
||||
final String lastname = this.fromApiJsonHelper.extractStringNamed("lastname", element);
|
||||
baseDataValidator.reset().parameter("lastname").value(lastname).notBlank().notExceedingLengthOf(50);
|
||||
final String lastname = this.fromApiJsonHelper.extractStringNamed(LASTNAME, element);
|
||||
baseDataValidator.reset().parameter(LASTNAME).value(lastname).notBlank().notExceedingLengthOf(50);
|
||||
|
||||
if (this.fromApiJsonHelper.parameterExists(ClientApiConstants.mobileNoParamName, element)) {
|
||||
final String mobileNo = this.fromApiJsonHelper.extractStringNamed(ClientApiConstants.mobileNoParamName, element);
|
||||
@@ -87,32 +100,32 @@ public final class StaffCommandFromApiJsonDeserializer {
|
||||
.notExceedingLengthOf(50);
|
||||
}
|
||||
|
||||
if (this.fromApiJsonHelper.parameterExists("isLoanOfficer", element)) {
|
||||
final String loanOfficerFlag = this.fromApiJsonHelper.extractStringNamed("isLoanOfficer", element);
|
||||
baseDataValidator.reset().parameter("isLoanOfficer").trueOrFalseRequired(loanOfficerFlag);
|
||||
if (this.fromApiJsonHelper.parameterExists(IS_LOAN_OFFICER, element)) {
|
||||
final String loanOfficerFlag = this.fromApiJsonHelper.extractStringNamed(IS_LOAN_OFFICER, element);
|
||||
baseDataValidator.reset().parameter(IS_LOAN_OFFICER).trueOrFalseRequired(loanOfficerFlag);
|
||||
}
|
||||
|
||||
if (this.fromApiJsonHelper.parameterExists("isActive", element)) {
|
||||
final String activeFlag = this.fromApiJsonHelper.extractStringNamed("isActive", element);
|
||||
baseDataValidator.reset().parameter("isActive").trueOrFalseRequired(activeFlag);
|
||||
if (this.fromApiJsonHelper.parameterExists(IS_ACTIVE, element)) {
|
||||
final String activeFlag = this.fromApiJsonHelper.extractStringNamed(IS_ACTIVE, element);
|
||||
baseDataValidator.reset().parameter(IS_ACTIVE).trueOrFalseRequired(activeFlag);
|
||||
}
|
||||
|
||||
final LocalDate joiningDate = this.fromApiJsonHelper.extractLocalDateNamed("joiningDate", element);
|
||||
baseDataValidator.reset().parameter("joiningDate").value(joiningDate).notNull();
|
||||
final LocalDate joiningDate = this.fromApiJsonHelper.extractLocalDateNamed(JOINING_DATE, element);
|
||||
baseDataValidator.reset().parameter(JOINING_DATE).value(joiningDate).notNull();
|
||||
|
||||
if (this.fromApiJsonHelper.parameterExists("dateFormat", element)) {
|
||||
final String dateFormat = this.fromApiJsonHelper.extractStringNamed("dateFormat", element);
|
||||
baseDataValidator.reset().parameter("dateFormat").value(dateFormat).notBlank();
|
||||
if (this.fromApiJsonHelper.parameterExists(DATE_FORMAT, element)) {
|
||||
final String dateFormat = this.fromApiJsonHelper.extractStringNamed(DATE_FORMAT, element);
|
||||
baseDataValidator.reset().parameter(DATE_FORMAT).value(dateFormat).notBlank();
|
||||
}
|
||||
|
||||
if (this.fromApiJsonHelper.parameterExists("locale", element)) {
|
||||
final String locale = this.fromApiJsonHelper.extractStringNamed("locale", element);
|
||||
baseDataValidator.reset().parameter("locale").value(locale).notBlank();
|
||||
if (this.fromApiJsonHelper.parameterExists(LOCALE, element)) {
|
||||
final String locale = this.fromApiJsonHelper.extractStringNamed(LOCALE, element);
|
||||
baseDataValidator.reset().parameter(LOCALE).value(locale).notBlank();
|
||||
}
|
||||
|
||||
if (this.fromApiJsonHelper.parameterExists("externalId", element)) {
|
||||
final String externalId = this.fromApiJsonHelper.extractStringNamed("externalId", element);
|
||||
baseDataValidator.reset().parameter("externalId").value(externalId).notBlank().notExceedingLengthOf(100);
|
||||
if (this.fromApiJsonHelper.parameterExists(EXTERNAL_ID, element)) {
|
||||
final String externalId = this.fromApiJsonHelper.extractStringNamed(EXTERNAL_ID, element);
|
||||
baseDataValidator.reset().parameter(EXTERNAL_ID).value(externalId).notBlank().notExceedingLengthOf(100);
|
||||
}
|
||||
|
||||
throwExceptionIfValidationWarningsExist(dataValidationErrors);
|
||||
@@ -127,26 +140,28 @@ public final class StaffCommandFromApiJsonDeserializer {
|
||||
throw new InvalidJsonException();
|
||||
}
|
||||
|
||||
final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType();
|
||||
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParameters);
|
||||
final Type typeOfMap = new TypeToken<Map<String, Object>>() {
|
||||
|
||||
}.getType();
|
||||
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, SUPPORTED_PARAMETERS);
|
||||
|
||||
final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
|
||||
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("staff");
|
||||
|
||||
final JsonElement element = this.fromApiJsonHelper.parse(json);
|
||||
if (this.fromApiJsonHelper.parameterExists("officeId", element)) {
|
||||
final Long officeId = this.fromApiJsonHelper.extractLongNamed("officeId", element);
|
||||
baseDataValidator.reset().parameter("officeId").value(officeId).notNull().integerGreaterThanZero();
|
||||
if (this.fromApiJsonHelper.parameterExists(OFFICE_ID, element)) {
|
||||
final Long officeId = this.fromApiJsonHelper.extractLongNamed(OFFICE_ID, element);
|
||||
baseDataValidator.reset().parameter(OFFICE_ID).value(officeId).notNull().integerGreaterThanZero();
|
||||
}
|
||||
|
||||
if (this.fromApiJsonHelper.parameterExists("firstname", element)) {
|
||||
final String firstname = this.fromApiJsonHelper.extractStringNamed("firstname", element);
|
||||
baseDataValidator.reset().parameter("firstname").value(firstname).notBlank().notExceedingLengthOf(50);
|
||||
if (this.fromApiJsonHelper.parameterExists(FIRSTNAME, element)) {
|
||||
final String firstname = this.fromApiJsonHelper.extractStringNamed(FIRSTNAME, element);
|
||||
baseDataValidator.reset().parameter(FIRSTNAME).value(firstname).notBlank().notExceedingLengthOf(50);
|
||||
}
|
||||
|
||||
if (this.fromApiJsonHelper.parameterExists("lastname", element)) {
|
||||
final String lastname = this.fromApiJsonHelper.extractStringNamed("lastname", element);
|
||||
baseDataValidator.reset().parameter("lastname").value(lastname).notBlank().notExceedingLengthOf(50);
|
||||
if (this.fromApiJsonHelper.parameterExists(LASTNAME, element)) {
|
||||
final String lastname = this.fromApiJsonHelper.extractStringNamed(LASTNAME, element);
|
||||
baseDataValidator.reset().parameter(LASTNAME).value(lastname).notBlank().notExceedingLengthOf(50);
|
||||
}
|
||||
|
||||
if (this.fromApiJsonHelper.parameterExists(ClientApiConstants.mobileNoParamName, element)) {
|
||||
@@ -154,21 +169,21 @@ public final class StaffCommandFromApiJsonDeserializer {
|
||||
baseDataValidator.reset().parameter(ClientApiConstants.mobileNoParamName).value(mobileNo).notExceedingLengthOf(50);
|
||||
}
|
||||
|
||||
if (this.fromApiJsonHelper.parameterExists("isLoanOfficer", element)) {
|
||||
final String loanOfficerFlag = this.fromApiJsonHelper.extractStringNamed("isLoanOfficer", element);
|
||||
baseDataValidator.reset().parameter("isLoanOfficer").trueOrFalseRequired(loanOfficerFlag);
|
||||
if (this.fromApiJsonHelper.parameterExists(IS_LOAN_OFFICER, element)) {
|
||||
final String loanOfficerFlag = this.fromApiJsonHelper.extractStringNamed(IS_LOAN_OFFICER, element);
|
||||
baseDataValidator.reset().parameter(IS_LOAN_OFFICER).trueOrFalseRequired(loanOfficerFlag);
|
||||
}
|
||||
|
||||
if (this.fromApiJsonHelper.parameterExists("isActive", element)) {
|
||||
final String activeFlagStr = this.fromApiJsonHelper.extractStringNamed("isActive", element);
|
||||
baseDataValidator.reset().parameter("isActive").trueOrFalseRequired(activeFlagStr);
|
||||
if (this.fromApiJsonHelper.parameterExists(IS_ACTIVE, element)) {
|
||||
final String activeFlagStr = this.fromApiJsonHelper.extractStringNamed(IS_ACTIVE, element);
|
||||
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
|
||||
// loans are assigned to this staff if staff is being set to
|
||||
// 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)) {
|
||||
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)) {
|
||||
final LocalDate joiningDate = this.fromApiJsonHelper.extractLocalDateNamed("joiningDate", element);
|
||||
baseDataValidator.reset().parameter("joiningDate").value(joiningDate).notNull();
|
||||
if (this.fromApiJsonHelper.parameterExists(JOINING_DATE, element)) {
|
||||
final LocalDate joiningDate = this.fromApiJsonHelper.extractLocalDateNamed(JOINING_DATE, element);
|
||||
baseDataValidator.reset().parameter(JOINING_DATE).value(joiningDate).notNull();
|
||||
}
|
||||
|
||||
if (this.fromApiJsonHelper.parameterExists("dateFormat", element)) {
|
||||
final String dateFormat = this.fromApiJsonHelper.extractStringNamed("dateFormat", element);
|
||||
baseDataValidator.reset().parameter("dateFormat").value(dateFormat).notBlank();
|
||||
if (this.fromApiJsonHelper.parameterExists(DATE_FORMAT, element)) {
|
||||
final String dateFormat = this.fromApiJsonHelper.extractStringNamed(DATE_FORMAT, element);
|
||||
baseDataValidator.reset().parameter(DATE_FORMAT).value(dateFormat).notBlank();
|
||||
}
|
||||
|
||||
if (this.fromApiJsonHelper.parameterExists("locale", element)) {
|
||||
final String locale = this.fromApiJsonHelper.extractStringNamed("locale", element);
|
||||
baseDataValidator.reset().parameter("locale").value(locale).notBlank();
|
||||
if (this.fromApiJsonHelper.parameterExists(LOCALE, element)) {
|
||||
final String locale = this.fromApiJsonHelper.extractStringNamed(LOCALE, element);
|
||||
baseDataValidator.reset().parameter(LOCALE).value(locale).notBlank();
|
||||
}
|
||||
|
||||
if (this.fromApiJsonHelper.parameterExists("externalId", element)) {
|
||||
final String externalId = this.fromApiJsonHelper.extractStringNamed("externalId", element);
|
||||
baseDataValidator.reset().parameter("externalId").value(externalId).notBlank().notExceedingLengthOf(100);
|
||||
if (this.fromApiJsonHelper.parameterExists(EXTERNAL_ID, element)) {
|
||||
final String externalId = this.fromApiJsonHelper.extractStringNamed(EXTERNAL_ID, element);
|
||||
baseDataValidator.reset().parameter(EXTERNAL_ID).value(externalId).notBlank().notExceedingLengthOf(100);
|
||||
}
|
||||
|
||||
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.exception.UnrecognizedQueryParamException;
|
||||
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.organisation.staff.data.StaffData;
|
||||
import org.apache.fineract.organisation.staff.exception.StaffNotFoundException;
|
||||
@@ -46,16 +45,13 @@ public class StaffReadPlatformServiceImpl implements StaffReadPlatformService {
|
||||
|
||||
private final JdbcTemplate jdbcTemplate;
|
||||
private final PlatformSecurityContext context;
|
||||
private final StaffLookupMapper lookupMapper = new StaffLookupMapper();
|
||||
private final StaffInOfficeHierarchyMapper staffInOfficeHierarchyMapper = new StaffInOfficeHierarchyMapper();
|
||||
private final ColumnValidator columnValidator;
|
||||
private static final StaffLookupMapper LOOKUP_MAPPER = new StaffLookupMapper();
|
||||
private static final StaffInOfficeHierarchyMapper STAFF_IN_OFFICE_HIERARCHY_MAPPER = new StaffInOfficeHierarchyMapper();
|
||||
|
||||
@Autowired
|
||||
public StaffReadPlatformServiceImpl(final PlatformSecurityContext context, final JdbcTemplate jdbcTemplate,
|
||||
final ColumnValidator columnValidator) {
|
||||
public StaffReadPlatformServiceImpl(final PlatformSecurityContext context, final JdbcTemplate jdbcTemplate) {
|
||||
this.context = context;
|
||||
this.jdbcTemplate = jdbcTemplate;
|
||||
this.columnValidator = columnValidator;
|
||||
}
|
||||
|
||||
private static final class StaffMapper implements RowMapper<StaffData> {
|
||||
@@ -174,9 +170,9 @@ public class StaffReadPlatformServiceImpl implements StaffReadPlatformService {
|
||||
|
||||
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) {
|
||||
@@ -199,7 +195,7 @@ public class StaffReadPlatformServiceImpl implements StaffReadPlatformService {
|
||||
final StaffMapper rm = new StaffMapper();
|
||||
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) {
|
||||
throw new StaffNotFoundException(staffId, e);
|
||||
}
|
||||
@@ -246,7 +242,7 @@ public class StaffReadPlatformServiceImpl implements StaffReadPlatformService {
|
||||
extraCriteria.addCriteria(" s.is_active =", false);
|
||||
} else {
|
||||
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
|
||||
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";
|
||||
return this.jdbcTemplate.query(sql, this.staffInOfficeHierarchyMapper, new Object[] { officeId }); // NOSONAR
|
||||
return this.jdbcTemplate.query(sql, STAFF_IN_OFFICE_HIERARCHY_MAPPER, officeId); // NOSONAR
|
||||
}
|
||||
|
||||
@Override
|
||||
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"
|
||||
+ " 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 < ? "
|
||||
+ " 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(),
|
||||
LoanStatus.WITHDRAWN_BY_CLIENT.getValue(), SavingsAccountStatusType.WITHDRAWN_BY_APPLICANT.getValue(), staffId });
|
||||
List<Map<String, Object>> result = this.jdbcTemplate.queryForList(sql, ClientStatus.CLOSED.getValue(),
|
||||
LoanStatus.WITHDRAWN_BY_CLIENT.getValue(), SavingsAccountStatusType.WITHDRAWN_BY_APPLICANT.getValue(), staffId);
|
||||
if (result != null) {
|
||||
for (Map<String, Object> map : result) {
|
||||
if (map.get("client") != null) {
|
||||
|
||||
+77
-53
@@ -46,13 +46,33 @@ import org.springframework.stereotype.Component;
|
||||
@Component
|
||||
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.
|
||||
*/
|
||||
private final Set<String> supportedParameters = new HashSet<>(Arrays.asList("officeId", "name", "description", "startDate", "endDate",
|
||||
"status", "dateFormat", "locale", "isFullDay", "staffId", "hourStartTime", "minStartTime", "hourEndTime", "minEndTime",
|
||||
"txnAmount", "txnDate", "txnNote", "entityType", "entityId", "currencyCode"));
|
||||
|
||||
private static final Set<String> SUPPORTED_PARAMETERS = new HashSet<>(Arrays.asList(OFFICE_ID, NAME, DESCRIPTION, START_DATE, END_DATE,
|
||||
STATUS, DATE_FORMAT, LOCALE, IS_FULL_DAY, STAFF_ID, HOUR_START_TIME, MIN_START_TIME, HOUR_END_TIME, MIN_END_TIME, TXN_AMOUNT,
|
||||
TXN_DATE, TXN_NOTE, ENTITY_TYPE, ENTITY_ID, CURRENCY_CODE));
|
||||
private final FromJsonHelper fromApiJsonHelper;
|
||||
|
||||
@Autowired
|
||||
@@ -65,36 +85,36 @@ public final class TellerCommandFromApiJsonDeserializer {
|
||||
throw new InvalidJsonException();
|
||||
}
|
||||
|
||||
final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType();
|
||||
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParameters);
|
||||
final Type typeOfMap = new TypeToken<Map<String, Object>>() {
|
||||
|
||||
}.getType();
|
||||
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, SUPPORTED_PARAMETERS);
|
||||
|
||||
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 Long officeId = this.fromApiJsonHelper.extractLongNamed("officeId", element);
|
||||
baseDataValidator.reset().parameter("officeId").value(officeId).notNull().integerGreaterThanZero();
|
||||
final Long officeId = this.fromApiJsonHelper.extractLongNamed(OFFICE_ID, element);
|
||||
baseDataValidator.reset().parameter(OFFICE_ID).value(officeId).notNull().integerGreaterThanZero();
|
||||
|
||||
final String name = this.fromApiJsonHelper.extractStringNamed("name", element);
|
||||
baseDataValidator.reset().parameter("name").value(name).notBlank().notExceedingLengthOf(50);
|
||||
final String name = this.fromApiJsonHelper.extractStringNamed(NAME, element);
|
||||
baseDataValidator.reset().parameter(NAME).value(name).notBlank().notExceedingLengthOf(50);
|
||||
|
||||
final String description = this.fromApiJsonHelper.extractStringNamed("description", element);
|
||||
baseDataValidator.reset().parameter("description").value(description).notExceedingLengthOf(100);
|
||||
final String description = this.fromApiJsonHelper.extractStringNamed(DESCRIPTION, element);
|
||||
baseDataValidator.reset().parameter(DESCRIPTION).value(description).notExceedingLengthOf(100);
|
||||
|
||||
final LocalDate startDate = this.fromApiJsonHelper.extractLocalDateNamed("startDate", element);
|
||||
baseDataValidator.reset().parameter("startDate").value(startDate).notNull();
|
||||
final LocalDate startDate = this.fromApiJsonHelper.extractLocalDateNamed(START_DATE, element);
|
||||
baseDataValidator.reset().parameter(START_DATE).value(startDate).notNull();
|
||||
|
||||
final LocalDate endDate = this.fromApiJsonHelper.extractLocalDateNamed("endDate", element);
|
||||
baseDataValidator.reset().parameter("endDate").value(endDate).ignoreIfNull();
|
||||
final LocalDate endDate = this.fromApiJsonHelper.extractLocalDateNamed(END_DATE, element);
|
||||
baseDataValidator.reset().parameter(END_DATE).value(endDate).ignoreIfNull();
|
||||
|
||||
final String status = this.fromApiJsonHelper.extractStringNamed("status", element);
|
||||
baseDataValidator.reset().parameter("status").value(status).notBlank().notExceedingLengthOf(50);
|
||||
final String status = this.fromApiJsonHelper.extractStringNamed(STATUS, element);
|
||||
baseDataValidator.reset().parameter(STATUS).value(status).notBlank().notExceedingLengthOf(50);
|
||||
|
||||
if (endDate != null) {
|
||||
if (endDate.isBefore(startDate)) {
|
||||
throw new InvalidDateInputException(startDate.toString(), endDate.toString());
|
||||
}
|
||||
if (endDate != null && endDate.isBefore(startDate)) {
|
||||
throw new InvalidDateInputException(startDate.toString(), endDate.toString());
|
||||
}
|
||||
throwExceptionIfValidationWarningsExist(dataValidationErrors);
|
||||
}
|
||||
@@ -111,38 +131,40 @@ public final class TellerCommandFromApiJsonDeserializer {
|
||||
throw new InvalidJsonException();
|
||||
}
|
||||
|
||||
final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType();
|
||||
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParameters);
|
||||
final Type typeOfMap = new TypeToken<Map<String, Object>>() {
|
||||
|
||||
}.getType();
|
||||
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, SUPPORTED_PARAMETERS);
|
||||
|
||||
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 Long staffId = this.fromApiJsonHelper.extractLongNamed("staffId", element);
|
||||
baseDataValidator.reset().parameter("staffId").value(staffId).notNull().integerGreaterThanZero();
|
||||
final Long staffId = this.fromApiJsonHelper.extractLongNamed(STAFF_ID, element);
|
||||
baseDataValidator.reset().parameter(STAFF_ID).value(staffId).notNull().integerGreaterThanZero();
|
||||
|
||||
final String description = this.fromApiJsonHelper.extractStringNamed("description", element);
|
||||
baseDataValidator.reset().parameter("description").value(description).notExceedingLengthOf(100);
|
||||
final String description = this.fromApiJsonHelper.extractStringNamed(DESCRIPTION, element);
|
||||
baseDataValidator.reset().parameter(DESCRIPTION).value(description).notExceedingLengthOf(100);
|
||||
|
||||
final LocalDate startDate = this.fromApiJsonHelper.extractLocalDateNamed("startDate", element);
|
||||
baseDataValidator.reset().parameter("startDate").value(startDate).notNull();
|
||||
final LocalDate startDate = this.fromApiJsonHelper.extractLocalDateNamed(START_DATE, element);
|
||||
baseDataValidator.reset().parameter(START_DATE).value(startDate).notNull();
|
||||
|
||||
final LocalDate endDate = this.fromApiJsonHelper.extractLocalDateNamed("endDate", element);
|
||||
baseDataValidator.reset().parameter("endDate").value(endDate).notNull();
|
||||
final LocalDate endDate = this.fromApiJsonHelper.extractLocalDateNamed(END_DATE, element);
|
||||
baseDataValidator.reset().parameter(END_DATE).value(endDate).notNull();
|
||||
|
||||
final Boolean isFullDay = this.fromApiJsonHelper.extractBooleanNamed("isFullDay", element);
|
||||
baseDataValidator.reset().parameter("isFullDay").value(isFullDay).notNull();
|
||||
final Boolean isFullDay = this.fromApiJsonHelper.extractBooleanNamed(IS_FULL_DAY, element);
|
||||
baseDataValidator.reset().parameter(IS_FULL_DAY).value(isFullDay).notNull();
|
||||
|
||||
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();
|
||||
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();
|
||||
final String hourEndTime = this.fromApiJsonHelper.extractStringNamed("hourEndTime", element);
|
||||
baseDataValidator.reset().parameter("hourEndTime").value(hourEndTime).notBlank();
|
||||
final String minEndTime = this.fromApiJsonHelper.extractStringNamed("minEndTime", element);
|
||||
baseDataValidator.reset().parameter("minEndTime").value(minEndTime).notBlank();
|
||||
final String hourEndTime = this.fromApiJsonHelper.extractStringNamed(HOUR_END_TIME, element);
|
||||
baseDataValidator.reset().parameter(HOUR_END_TIME).value(hourEndTime).notBlank();
|
||||
final String minEndTime = this.fromApiJsonHelper.extractStringNamed(MIN_END_TIME, element);
|
||||
baseDataValidator.reset().parameter(MIN_END_TIME).value(minEndTime).notBlank();
|
||||
|
||||
}
|
||||
|
||||
@@ -154,24 +176,26 @@ public final class TellerCommandFromApiJsonDeserializer {
|
||||
throw new InvalidJsonException();
|
||||
}
|
||||
|
||||
final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType();
|
||||
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParameters);
|
||||
final Type typeOfMap = new TypeToken<Map<String, Object>>() {
|
||||
|
||||
}.getType();
|
||||
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, SUPPORTED_PARAMETERS);
|
||||
|
||||
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 BigDecimal txnAmount = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed("txnAmount", element);
|
||||
baseDataValidator.reset().parameter("txnAmount").value(txnAmount).notNull();
|
||||
final BigDecimal txnAmount = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed(TXN_AMOUNT, element);
|
||||
baseDataValidator.reset().parameter(TXN_AMOUNT).value(txnAmount).notNull();
|
||||
|
||||
final LocalDate txnDate = this.fromApiJsonHelper.extractLocalDateNamed("txnDate", element);
|
||||
baseDataValidator.reset().parameter("txnDate").value(txnDate).notNull();
|
||||
final LocalDate txnDate = this.fromApiJsonHelper.extractLocalDateNamed(TXN_DATE, element);
|
||||
baseDataValidator.reset().parameter(TXN_DATE).value(txnDate).notNull();
|
||||
|
||||
final String txnNote = this.fromApiJsonHelper.extractStringNamed("txnNote", element);
|
||||
baseDataValidator.reset().parameter("txnNote").value(txnNote).notExceedingLengthOf(200);
|
||||
final String txnNote = this.fromApiJsonHelper.extractStringNamed(TXN_NOTE, element);
|
||||
baseDataValidator.reset().parameter(TXN_NOTE).value(txnNote).notExceedingLengthOf(200);
|
||||
|
||||
final String currencyCode = this.fromApiJsonHelper.extractStringNamed("currencyCode", element);
|
||||
baseDataValidator.reset().parameter("currencyCode").value(currencyCode).notExceedingLengthOf(3);
|
||||
final String currencyCode = this.fromApiJsonHelper.extractStringNamed(CURRENCY_CODE, element);
|
||||
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.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import org.apache.fineract.infrastructure.core.data.EnumOptionData;
|
||||
import org.apache.fineract.infrastructure.core.domain.JdbcSupport;
|
||||
import org.apache.fineract.infrastructure.core.service.DateUtils;
|
||||
@@ -56,19 +55,17 @@ import org.springframework.util.CollectionUtils;
|
||||
@Service
|
||||
public class AccountTransfersReadPlatformServiceImpl implements AccountTransfersReadPlatformService {
|
||||
|
||||
private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");
|
||||
private final JdbcTemplate jdbcTemplate;
|
||||
private final ClientReadPlatformService clientReadPlatformService;
|
||||
private final OfficeReadPlatformService officeReadPlatformService;
|
||||
private final PortfolioAccountReadPlatformService portfolioAccountReadPlatformService;
|
||||
private final ColumnValidator columnValidator;
|
||||
private final DatabaseSpecificSQLGenerator sqlGenerator;
|
||||
|
||||
// mapper
|
||||
private final AccountTransfersMapper accountTransfersMapper;
|
||||
|
||||
// pagination
|
||||
private final PaginationHelper paginationHelper;
|
||||
private final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
|
||||
|
||||
@Autowired
|
||||
public AccountTransfersReadPlatformServiceImpl(final JdbcTemplate jdbcTemplate,
|
||||
@@ -260,137 +257,14 @@ public class AccountTransfersReadPlatformServiceImpl implements AccountTransfers
|
||||
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 List<Long> transactionId = this.jdbcTemplate.queryForList(sql, Long.class, accountId,
|
||||
AccountTransferType.INTEREST_TRANSFER.getValue());
|
||||
|
||||
return transactionId;
|
||||
return this.jdbcTemplate.queryForList(sql, Long.class, accountId, AccountTransferType.INTEREST_TRANSFER.getValue());
|
||||
}
|
||||
|
||||
@Override
|
||||
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 List<Long> transactionIds = this.jdbcTemplate.queryForList(sql, Long.class, accountId,
|
||||
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);
|
||||
}
|
||||
return this.jdbcTemplate.queryForList(sql, Long.class, accountId, AccountTransferType.INTEREST_TRANSFER.getValue(), pivotDate);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -561,8 +435,125 @@ public class AccountTransfersReadPlatformServiceImpl implements AccountTransfers
|
||||
sqlBuilder.append(" and trans.transaction_date = ? ");
|
||||
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);
|
||||
}
|
||||
|
||||
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.MediaType;
|
||||
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.serialization.ApiRequestJsonSerializationSettings;
|
||||
import org.apache.fineract.infrastructure.core.serialization.DefaultToApiJsonSerializer;
|
||||
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.service.FieldConfigurationReadPlatformService;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
@@ -58,30 +56,24 @@ import org.springframework.stereotype.Component;
|
||||
+ "add regular expression for validation")
|
||||
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",
|
||||
"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 DefaultToApiJsonSerializer<AddressData> toApiJsonSerializer;
|
||||
private final FieldConfigurationReadPlatformService readPlatformServicefld;
|
||||
private final DefaultToApiJsonSerializer<FieldConfigurationData> toApiJsonSerializerfld;
|
||||
private final ApiRequestParameterHelper apiRequestParameterHelper;
|
||||
private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService;
|
||||
|
||||
@Autowired
|
||||
public EntityFieldConfigurationApiResources(final PlatformSecurityContext context,
|
||||
final DefaultToApiJsonSerializer<AddressData> toApiJsonSerializer,
|
||||
final FieldConfigurationReadPlatformService readPlatformServicefld,
|
||||
final DefaultToApiJsonSerializer<FieldConfigurationData> toApiJsonSerializerfld,
|
||||
final ApiRequestParameterHelper apiRequestParameterHelper,
|
||||
final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService) {
|
||||
final ApiRequestParameterHelper apiRequestParameterHelper) {
|
||||
this.context = context;
|
||||
this.toApiJsonSerializer = toApiJsonSerializer;
|
||||
this.readPlatformServicefld = readPlatformServicefld;
|
||||
this.toApiJsonSerializerfld = toApiJsonSerializerfld;
|
||||
this.apiRequestParameterHelper = apiRequestParameterHelper;
|
||||
this.commandsSourceWritePlatformService = commandsSourceWritePlatformService;
|
||||
}
|
||||
|
||||
@GET
|
||||
@@ -92,12 +84,12 @@ public class EntityFieldConfigurationApiResources {
|
||||
@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,
|
||||
@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 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}
|
||||
*/
|
||||
private final Set<String> responseDataParameters = new HashSet<>(Arrays.asList("id", "entityId", "entityType", "title", "description",
|
||||
"location", "startDate", "endDate", "duration", "type", "repeating", "recurrence", "frequency", "interval", "repeatsOnDay",
|
||||
"remindBy", "firstReminder", "secondReminder", "humanReadable", "createdDate", "lastUpdatedDate", "createdByUserId",
|
||||
"createdByUsername", "lastUpdatedByUserId", "lastUpdatedByUsername", "recurringDates", "nextTenRecurringDates",
|
||||
"entityTypeOptions", "calendarTypeOptions", "remindByOptions", "frequencyOptions", "repeatsOnDayOptions"));
|
||||
private final String resourceNameForPermissions = "CALENDAR";
|
||||
private static final Set<String> RESPONSE_DATA_PARAMETERS = new HashSet<>(
|
||||
Arrays.asList("id", "entityId", "entityType", "title", "description", "location", "startDate", "endDate", "duration", "type",
|
||||
"repeating", "recurrence", "frequency", "interval", "repeatsOnDay", "remindBy", "firstReminder", "secondReminder",
|
||||
"humanReadable", "createdDate", "lastUpdatedDate", "createdByUserId", "createdByUsername", "lastUpdatedByUserId",
|
||||
"lastUpdatedByUsername", "recurringDates", "nextTenRecurringDates", "entityTypeOptions", "calendarTypeOptions",
|
||||
"remindByOptions", "frequencyOptions", "repeatsOnDayOptions"));
|
||||
private static final String RESOURCE_NAME_FOR_PERMISSIONS = "CALENDAR";
|
||||
|
||||
private final PlatformSecurityContext context;
|
||||
private final CalendarReadPlatformService readPlatformService;
|
||||
@@ -103,7 +104,7 @@ public class CalendarsApiResource {
|
||||
public String retrieveCalendar(@PathParam("calendarId") final Long calendarId, @PathParam("entityType") final String entityType,
|
||||
@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();
|
||||
CalendarData calendarData = this.readPlatformService.retrieveCalendar(calendarId, entityId, entityTypeId);
|
||||
|
||||
@@ -119,7 +120,7 @@ public class CalendarsApiResource {
|
||||
if (settings.isTemplate()) {
|
||||
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,
|
||||
@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());
|
||||
|
||||
@@ -143,11 +144,9 @@ public class CalendarsApiResource {
|
||||
|
||||
final List<Integer> calendarTypeOptions = CalendarUtils.createIntegerListFromQueryParameter(calendarType);
|
||||
|
||||
if (!associationParameters.isEmpty()) {
|
||||
if (associationParameters.contains("parentCalendars")) {
|
||||
calendarsData.addAll(this.readPlatformService.retrieveParentCalendarsByEntity(entityId,
|
||||
CalendarEntityType.valueOf(entityType.toUpperCase()).getValue(), calendarTypeOptions));
|
||||
}
|
||||
if (!associationParameters.isEmpty() && associationParameters.contains("parentCalendars")) {
|
||||
calendarsData.addAll(this.readPlatformService.retrieveParentCalendarsByEntity(entityId,
|
||||
CalendarEntityType.valueOf(entityType.toUpperCase()).getValue(), calendarTypeOptions));
|
||||
}
|
||||
|
||||
calendarsData.addAll(this.readPlatformService.retrieveCalendarsByEntity(entityId,
|
||||
@@ -157,7 +156,7 @@ public class CalendarsApiResource {
|
||||
calendarsData = this.readPlatformService.updateWithRecurringDates(calendarsData);
|
||||
|
||||
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
|
||||
@@ -167,13 +166,13 @@ public class CalendarsApiResource {
|
||||
public String retrieveNewCalendarDetails(@Context final UriInfo uriInfo, @PathParam("entityType") final String entityType,
|
||||
@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 = handleTemplate(calendarData);
|
||||
|
||||
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
|
||||
|
||||
+4
-4
@@ -50,7 +50,7 @@ public class CalendarCommandFromApiJsonDeserializer extends AbstractFromApiJsonD
|
||||
/**
|
||||
* 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;
|
||||
|
||||
@@ -66,7 +66,7 @@ public class CalendarCommandFromApiJsonDeserializer extends AbstractFromApiJsonD
|
||||
}
|
||||
|
||||
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 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();
|
||||
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParameters);
|
||||
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, SUPPORTED_PARAMETERS);
|
||||
final JsonElement element = this.fromApiJsonHelper.parse(json);
|
||||
|
||||
final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
|
||||
@@ -221,7 +221,7 @@ public class CalendarCommandFromApiJsonDeserializer extends AbstractFromApiJsonD
|
||||
}
|
||||
|
||||
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 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.")
|
||||
public class ChargesApiResource {
|
||||
|
||||
private final Set<String> chargesDataParameters = new HashSet<>(Arrays.asList("id", "name", "amount", "currency", "penalty", "active",
|
||||
"chargeAppliesTo", "chargeTimeType", "chargeCalculationType", "chargeCalculationTypeOptions", "chargeAppliesToOptions",
|
||||
"chargeTimeTypeOptions", "currencyOptions", "loanChargeCalculationTypeOptions", "loanChargeTimeTypeOptions",
|
||||
"savingsChargeCalculationTypeOptions", "savingsChargeTimeTypeOptions", "incomeAccount", "clientChargeCalculationTypeOptions",
|
||||
"clientChargeTimeTypeOptions"));
|
||||
private static final Set<String> CHARGES_DATA_PARAMETERS = new HashSet<>(Arrays.asList("id", "name", "amount", "currency", "penalty",
|
||||
"active", "chargeAppliesTo", "chargeTimeType", "chargeCalculationType", "chargeCalculationTypeOptions",
|
||||
"chargeAppliesToOptions", "chargeTimeTypeOptions", "currencyOptions", "loanChargeCalculationTypeOptions",
|
||||
"loanChargeTimeTypeOptions", "savingsChargeCalculationTypeOptions", "savingsChargeTimeTypeOptions", "incomeAccount",
|
||||
"clientChargeCalculationTypeOptions", "clientChargeTimeTypeOptions"));
|
||||
|
||||
private final String resourceNameForPermissions = "CHARGE";
|
||||
private static final String RESOURCE_NAME_FOR_PERMISSIONS = "CHARGE";
|
||||
|
||||
private final PlatformSecurityContext context;
|
||||
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)))) })
|
||||
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 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
|
||||
@@ -117,7 +117,7 @@ public class ChargesApiResource {
|
||||
public String retrieveCharge(@PathParam("chargeId") @Parameter(description = "chargeId") final Long chargeId,
|
||||
@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());
|
||||
|
||||
@@ -127,7 +127,7 @@ public class ChargesApiResource {
|
||||
charge = ChargeData.withTemplate(charge, templateData);
|
||||
}
|
||||
|
||||
return this.toApiJsonSerializer.serialize(settings, charge, this.chargesDataParameters);
|
||||
return this.toApiJsonSerializer.serialize(settings, charge, CHARGES_DATA_PARAMETERS);
|
||||
}
|
||||
|
||||
@GET
|
||||
@@ -140,12 +140,12 @@ public class ChargesApiResource {
|
||||
@ApiResponse(responseCode = "200", description = "OK", content = @Content(schema = @Schema(implementation = ChargesApiResourceSwagger.GetChargesTemplateResponse.class))) })
|
||||
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 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
|
||||
|
||||
+186
-159
@@ -48,15 +48,39 @@ import org.springframework.stereotype.Component;
|
||||
@Component
|
||||
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.
|
||||
*/
|
||||
private final Set<String> supportedParameters = new HashSet<>(Arrays.asList("name", "amount", "locale", "currencyCode",
|
||||
"currencyOptions", "chargeAppliesTo", "chargeTimeType", "chargeCalculationType", "chargeCalculationTypeOptions", "penalty",
|
||||
"active", "chargePaymentMode", "feeOnMonthDay", "feeInterval", "monthDayFormat", "minCap", "maxCap", "feeFrequency",
|
||||
"enableFreeWithdrawalCharge", "freeWithdrawalFrequency", "restartCountFrequency", "countFrequencyType", "paymentTypeId",
|
||||
"enablePaymentType", ChargesApiConstants.glAccountIdParamName, ChargesApiConstants.taxGroupIdParamName));
|
||||
|
||||
private static final Set<String> SUPPORTED_PARAMETERS = new HashSet<>(Arrays.asList(NAME, AMOUNT, LOCALE, CURRENCY_CODE,
|
||||
CURRENCY_OPTIONS, CHARGE_APPLIES_TO, CHARGE_TIME_TYPE, CHARGE_CALCULATION_TYPE, CHARGE_CALCULATION_TYPE_OPTIONS, PENALTY,
|
||||
ACTIVE, CHARGE_PAYMENT_MODE, FEE_ON_MONTH_DAY, FEE_INTERVAL, MONTH_DAY_FORMAT, MIN_CAP, MAX_CAP, FEE_FREQUENCY,
|
||||
ENABLE_FREE_WITHDRAWAL_CHARGE, FREE_WITHDRAWAL_FREQUENCY, RESTART_COUNT_FREQUENCY, COUNT_FREQUENCY_TYPE, PAYMENT_TYPE_ID,
|
||||
ENABLE_PAYMENT_TYPE, ChargesApiConstants.glAccountIdParamName, ChargesApiConstants.taxGroupIdParamName));
|
||||
private final FromJsonHelper fromApiJsonHelper;
|
||||
|
||||
@Autowired
|
||||
@@ -69,86 +93,88 @@ public final class ChargeDefinitionCommandFromApiJsonDeserializer {
|
||||
throw new InvalidJsonException();
|
||||
}
|
||||
|
||||
final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType();
|
||||
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParameters);
|
||||
final Type typeOfMap = new TypeToken<Map<String, Object>>() {
|
||||
|
||||
}.getType();
|
||||
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, SUPPORTED_PARAMETERS);
|
||||
|
||||
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 Integer chargeAppliesTo = this.fromApiJsonHelper.extractIntegerSansLocaleNamed("chargeAppliesTo", element);
|
||||
baseDataValidator.reset().parameter("chargeAppliesTo").value(chargeAppliesTo).notNull();
|
||||
final Integer chargeAppliesTo = this.fromApiJsonHelper.extractIntegerSansLocaleNamed(CHARGE_APPLIES_TO, element);
|
||||
baseDataValidator.reset().parameter(CHARGE_APPLIES_TO).value(chargeAppliesTo).notNull();
|
||||
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);
|
||||
baseDataValidator.reset().parameter("chargeCalculationType").value(chargeCalculationType).notNull();
|
||||
final Integer chargeCalculationType = this.fromApiJsonHelper.extractIntegerSansLocaleNamed(CHARGE_CALCULATION_TYPE, element);
|
||||
baseDataValidator.reset().parameter(CHARGE_CALCULATION_TYPE).value(chargeCalculationType).notNull();
|
||||
|
||||
final Integer feeInterval = this.fromApiJsonHelper.extractIntegerNamed("feeInterval", element, Locale.getDefault());
|
||||
baseDataValidator.reset().parameter("feeInterval").value(feeInterval).integerGreaterThanZero();
|
||||
final Integer feeInterval = this.fromApiJsonHelper.extractIntegerNamed(FEE_INTERVAL, element, Locale.getDefault());
|
||||
baseDataValidator.reset().parameter(FEE_INTERVAL).value(feeInterval).integerGreaterThanZero();
|
||||
|
||||
final Integer feeFrequency = this.fromApiJsonHelper.extractIntegerNamed("feeFrequency", element, Locale.getDefault());
|
||||
baseDataValidator.reset().parameter("feeFrequency").value(feeFrequency).inMinMaxRange(0, 3);
|
||||
final Integer feeFrequency = this.fromApiJsonHelper.extractIntegerNamed(FEE_FREQUENCY, element, Locale.getDefault());
|
||||
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);
|
||||
baseDataValidator.reset().parameter("enableFreeWithdrawalCharge").value(enableFreeWithdrawalCharge).notNull();
|
||||
final Boolean enableFreeWithdrawalCharge = this.fromApiJsonHelper.extractBooleanNamed(ENABLE_FREE_WITHDRAWAL_CHARGE, element);
|
||||
baseDataValidator.reset().parameter(ENABLE_FREE_WITHDRAWAL_CHARGE).value(enableFreeWithdrawalCharge).notNull();
|
||||
|
||||
if (enableFreeWithdrawalCharge) {
|
||||
|
||||
final Integer freeWithdrawalFrequency = this.fromApiJsonHelper.extractIntegerNamed("freeWithdrawalFrequency", element,
|
||||
final Integer freeWithdrawalFrequency = this.fromApiJsonHelper.extractIntegerNamed(FREE_WITHDRAWAL_FREQUENCY, element,
|
||||
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());
|
||||
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());
|
||||
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);
|
||||
baseDataValidator.reset().parameter("enablePaymentType").value(enablePaymentType).notNull();
|
||||
final boolean enablePaymentType = this.fromApiJsonHelper.extractBooleanNamed(ENABLE_PAYMENT_TYPE, element);
|
||||
baseDataValidator.reset().parameter(ENABLE_PAYMENT_TYPE).value(enablePaymentType).notNull();
|
||||
|
||||
if (enablePaymentType) {
|
||||
final Integer paymentTypeId = this.fromApiJsonHelper.extractIntegerNamed("paymentTypeId", element, Locale.getDefault());
|
||||
baseDataValidator.reset().parameter("paymentTypeId").value(paymentTypeId).integerGreaterThanZero();
|
||||
final Integer paymentTypeId = this.fromApiJsonHelper.extractIntegerNamed(PAYMENT_TYPE_ID, element, Locale.getDefault());
|
||||
baseDataValidator.reset().parameter(PAYMENT_TYPE_ID).value(paymentTypeId).integerGreaterThanZero();
|
||||
}
|
||||
}
|
||||
|
||||
if (feeFrequency != null) {
|
||||
baseDataValidator.reset().parameter("feeInterval").value(feeInterval).notNull();
|
||||
baseDataValidator.reset().parameter(FEE_INTERVAL).value(feeInterval).notNull();
|
||||
}
|
||||
|
||||
final ChargeAppliesTo appliesTo = ChargeAppliesTo.fromInt(chargeAppliesTo);
|
||||
if (appliesTo.isLoanCharge()) {
|
||||
// loan applicable validation
|
||||
final Integer chargeTimeType = this.fromApiJsonHelper.extractIntegerSansLocaleNamed("chargeTimeType", element);
|
||||
baseDataValidator.reset().parameter("chargeTimeType").value(chargeTimeType).notNull();
|
||||
final Integer chargeTimeType = this.fromApiJsonHelper.extractIntegerSansLocaleNamed(CHARGE_TIME_TYPE, element);
|
||||
baseDataValidator.reset().parameter(CHARGE_TIME_TYPE).value(chargeTimeType).notNull();
|
||||
if (chargeTimeType != null) {
|
||||
baseDataValidator.reset().parameter("chargeTimeType").value(chargeTimeType)
|
||||
baseDataValidator.reset().parameter(CHARGE_TIME_TYPE).value(chargeTimeType)
|
||||
.isOneOfTheseValues(ChargeTimeType.validLoanValues());
|
||||
}
|
||||
|
||||
final Integer chargePaymentMode = this.fromApiJsonHelper.extractIntegerSansLocaleNamed("chargePaymentMode", element);
|
||||
baseDataValidator.reset().parameter("chargePaymentMode").value(chargePaymentMode).notNull()
|
||||
final Integer chargePaymentMode = this.fromApiJsonHelper.extractIntegerSansLocaleNamed(CHARGE_PAYMENT_MODE, element);
|
||||
baseDataValidator.reset().parameter(CHARGE_PAYMENT_MODE).value(chargePaymentMode).notNull()
|
||||
.isOneOfTheseValues(ChargePaymentMode.validValues());
|
||||
if (chargePaymentMode != null) {
|
||||
baseDataValidator.reset().parameter("chargePaymentMode").value(chargePaymentMode)
|
||||
baseDataValidator.reset().parameter(CHARGE_PAYMENT_MODE).value(chargePaymentMode)
|
||||
.isOneOfTheseValues(ChargePaymentMode.validValues());
|
||||
}
|
||||
|
||||
if (chargeCalculationType != null) {
|
||||
baseDataValidator.reset().parameter("chargeCalculationType").value(chargeCalculationType)
|
||||
baseDataValidator.reset().parameter(CHARGE_CALCULATION_TYPE).value(chargeCalculationType)
|
||||
.isOneOfTheseValues(ChargeCalculationType.validValuesForLoan());
|
||||
}
|
||||
|
||||
@@ -158,49 +184,49 @@ public final class ChargeDefinitionCommandFromApiJsonDeserializer {
|
||||
|
||||
} else if (appliesTo.isSavingsCharge()) {
|
||||
// savings applicable validation
|
||||
final Integer chargeTimeType = this.fromApiJsonHelper.extractIntegerSansLocaleNamed("chargeTimeType", element);
|
||||
baseDataValidator.reset().parameter("chargeTimeType").value(chargeTimeType).notNull();
|
||||
final Integer chargeTimeType = this.fromApiJsonHelper.extractIntegerSansLocaleNamed(CHARGE_TIME_TYPE, element);
|
||||
baseDataValidator.reset().parameter(CHARGE_TIME_TYPE).value(chargeTimeType).notNull();
|
||||
if (chargeTimeType != null) {
|
||||
baseDataValidator.reset().parameter("chargeTimeType").value(chargeTimeType)
|
||||
baseDataValidator.reset().parameter(CHARGE_TIME_TYPE).value(chargeTimeType)
|
||||
.isOneOfTheseValues(ChargeTimeType.validSavingsValues());
|
||||
}
|
||||
|
||||
final ChargeTimeType ctt = ChargeTimeType.fromInt(chargeTimeType);
|
||||
|
||||
if (ctt.isWeeklyFee()) {
|
||||
final String monthDay = this.fromApiJsonHelper.extractStringNamed("feeOnMonthDay", element);
|
||||
baseDataValidator.reset().parameter("feeOnMonthDay").value(monthDay).mustBeBlankWhenParameterProvidedIs("chargeTimeType",
|
||||
final String monthDay = this.fromApiJsonHelper.extractStringNamed(FEE_ON_MONTH_DAY, element);
|
||||
baseDataValidator.reset().parameter(FEE_ON_MONTH_DAY).value(monthDay).mustBeBlankWhenParameterProvidedIs(CHARGE_TIME_TYPE,
|
||||
chargeTimeType);
|
||||
}
|
||||
|
||||
if (ctt.isMonthlyFee()) {
|
||||
final MonthDay monthDay = this.fromApiJsonHelper.extractMonthDayNamed("feeOnMonthDay", element);
|
||||
baseDataValidator.reset().parameter("feeOnMonthDay").value(monthDay).notNull();
|
||||
final MonthDay monthDay = this.fromApiJsonHelper.extractMonthDayNamed(FEE_ON_MONTH_DAY, element);
|
||||
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()) {
|
||||
final MonthDay monthDay = this.fromApiJsonHelper.extractMonthDayNamed("feeOnMonthDay", element);
|
||||
baseDataValidator.reset().parameter("feeOnMonthDay").value(monthDay).notNull();
|
||||
final MonthDay monthDay = this.fromApiJsonHelper.extractMonthDayNamed(FEE_ON_MONTH_DAY, element);
|
||||
baseDataValidator.reset().parameter(FEE_ON_MONTH_DAY).value(monthDay).notNull();
|
||||
}
|
||||
|
||||
if (chargeCalculationType != null) {
|
||||
baseDataValidator.reset().parameter("chargeCalculationType").value(chargeCalculationType)
|
||||
baseDataValidator.reset().parameter(CHARGE_CALCULATION_TYPE).value(chargeCalculationType)
|
||||
.isOneOfTheseValues(ChargeCalculationType.validValuesForSavings());
|
||||
}
|
||||
|
||||
} else if (appliesTo.isClientCharge()) {
|
||||
// client applicable validation
|
||||
final Integer chargeTimeType = this.fromApiJsonHelper.extractIntegerSansLocaleNamed("chargeTimeType", element);
|
||||
baseDataValidator.reset().parameter("chargeTimeType").value(chargeTimeType).notNull();
|
||||
final Integer chargeTimeType = this.fromApiJsonHelper.extractIntegerSansLocaleNamed(CHARGE_TIME_TYPE, element);
|
||||
baseDataValidator.reset().parameter(CHARGE_TIME_TYPE).value(chargeTimeType).notNull();
|
||||
if (chargeTimeType != null) {
|
||||
baseDataValidator.reset().parameter("chargeTimeType").value(chargeTimeType)
|
||||
baseDataValidator.reset().parameter(CHARGE_TIME_TYPE).value(chargeTimeType)
|
||||
.isOneOfTheseValues(ChargeTimeType.validClientValues());
|
||||
}
|
||||
|
||||
if (chargeCalculationType != null) {
|
||||
baseDataValidator.reset().parameter("chargeCalculationType").value(chargeCalculationType)
|
||||
baseDataValidator.reset().parameter(CHARGE_CALCULATION_TYPE).value(chargeCalculationType)
|
||||
.isOneOfTheseValues(ChargeCalculationType.validValuesForClients());
|
||||
}
|
||||
|
||||
@@ -212,52 +238,51 @@ public final class ChargeDefinitionCommandFromApiJsonDeserializer {
|
||||
}
|
||||
|
||||
} else if (appliesTo.isSharesCharge()) {
|
||||
final Integer chargeTimeType = this.fromApiJsonHelper.extractIntegerSansLocaleNamed("chargeTimeType", element);
|
||||
baseDataValidator.reset().parameter("chargeTimeType").value(chargeTimeType).notNull();
|
||||
final Integer chargeTimeType = this.fromApiJsonHelper.extractIntegerSansLocaleNamed(CHARGE_TIME_TYPE, element);
|
||||
baseDataValidator.reset().parameter(CHARGE_TIME_TYPE).value(chargeTimeType).notNull();
|
||||
if (chargeTimeType != null) {
|
||||
baseDataValidator.reset().parameter("chargeTimeType").value(chargeTimeType)
|
||||
baseDataValidator.reset().parameter(CHARGE_TIME_TYPE).value(chargeTimeType)
|
||||
.isOneOfTheseValues(ChargeTimeType.validShareValues());
|
||||
}
|
||||
|
||||
if (chargeCalculationType != null) {
|
||||
baseDataValidator.reset().parameter("chargeCalculationType").value(chargeCalculationType)
|
||||
baseDataValidator.reset().parameter(CHARGE_CALCULATION_TYPE).value(chargeCalculationType)
|
||||
.isOneOfTheseValues(ChargeCalculationType.validValuesForShares());
|
||||
}
|
||||
|
||||
if (chargeTimeType != null && chargeTimeType.equals(ChargeTimeType.SHAREACCOUNT_ACTIVATION.getValue())) {
|
||||
if (chargeCalculationType != null) {
|
||||
baseDataValidator.reset().parameter("chargeCalculationType").value(chargeCalculationType)
|
||||
.isOneOfTheseValues(ChargeCalculationType.validValuesForShareAccountActivation());
|
||||
}
|
||||
if (chargeTimeType != null && chargeTimeType.equals(ChargeTimeType.SHAREACCOUNT_ACTIVATION.getValue())
|
||||
&& chargeCalculationType != null) {
|
||||
baseDataValidator.reset().parameter(CHARGE_CALCULATION_TYPE).value(chargeCalculationType)
|
||||
.isOneOfTheseValues(ChargeCalculationType.validValuesForShareAccountActivation());
|
||||
}
|
||||
}
|
||||
|
||||
final String name = this.fromApiJsonHelper.extractStringNamed("name", element);
|
||||
baseDataValidator.reset().parameter("name").value(name).notBlank().notExceedingLengthOf(100);
|
||||
final String name = this.fromApiJsonHelper.extractStringNamed(NAME, element);
|
||||
baseDataValidator.reset().parameter(NAME).value(name).notBlank().notExceedingLengthOf(100);
|
||||
|
||||
final String currencyCode = this.fromApiJsonHelper.extractStringNamed("currencyCode", element);
|
||||
baseDataValidator.reset().parameter("currencyCode").value(currencyCode).notBlank().notExceedingLengthOf(3);
|
||||
final String currencyCode = this.fromApiJsonHelper.extractStringNamed(CURRENCY_CODE, element);
|
||||
baseDataValidator.reset().parameter(CURRENCY_CODE).value(currencyCode).notBlank().notExceedingLengthOf(3);
|
||||
|
||||
final BigDecimal amount = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed("amount", element.getAsJsonObject());
|
||||
baseDataValidator.reset().parameter("amount").value(amount).notNull().positiveAmount();
|
||||
final BigDecimal amount = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed(AMOUNT, element.getAsJsonObject());
|
||||
baseDataValidator.reset().parameter(AMOUNT).value(amount).notNull().positiveAmount();
|
||||
|
||||
if (this.fromApiJsonHelper.parameterExists("penalty", element)) {
|
||||
final Boolean penalty = this.fromApiJsonHelper.extractBooleanNamed("penalty", element);
|
||||
baseDataValidator.reset().parameter("penalty").value(penalty).notNull();
|
||||
if (this.fromApiJsonHelper.parameterExists(PENALTY, element)) {
|
||||
final Boolean penalty = this.fromApiJsonHelper.extractBooleanNamed(PENALTY, element);
|
||||
baseDataValidator.reset().parameter(PENALTY).value(penalty).notNull();
|
||||
}
|
||||
|
||||
if (this.fromApiJsonHelper.parameterExists("active", element)) {
|
||||
final Boolean active = this.fromApiJsonHelper.extractBooleanNamed("active", element);
|
||||
baseDataValidator.reset().parameter("active").value(active).notNull();
|
||||
if (this.fromApiJsonHelper.parameterExists(ACTIVE, element)) {
|
||||
final Boolean active = this.fromApiJsonHelper.extractBooleanNamed(ACTIVE, element);
|
||||
baseDataValidator.reset().parameter(ACTIVE).value(active).notNull();
|
||||
}
|
||||
|
||||
if (this.fromApiJsonHelper.parameterExists("minCap", element)) {
|
||||
final BigDecimal minCap = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed("minCap", element.getAsJsonObject());
|
||||
baseDataValidator.reset().parameter("minCap").value(minCap).notNull().positiveAmount();
|
||||
if (this.fromApiJsonHelper.parameterExists(MIN_CAP, element)) {
|
||||
final BigDecimal minCap = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed(MIN_CAP, element.getAsJsonObject());
|
||||
baseDataValidator.reset().parameter(MIN_CAP).value(minCap).notNull().positiveAmount();
|
||||
}
|
||||
if (this.fromApiJsonHelper.parameterExists("maxCap", element)) {
|
||||
final BigDecimal maxCap = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed("maxCap", element.getAsJsonObject());
|
||||
baseDataValidator.reset().parameter("maxCap").value(maxCap).notNull().positiveAmount();
|
||||
if (this.fromApiJsonHelper.parameterExists(MAX_CAP, element)) {
|
||||
final BigDecimal maxCap = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed(MAX_CAP, element.getAsJsonObject());
|
||||
baseDataValidator.reset().parameter(MAX_CAP).value(maxCap).notNull().positiveAmount();
|
||||
}
|
||||
|
||||
if (this.fromApiJsonHelper.parameterExists(ChargesApiConstants.taxGroupIdParamName, element)) {
|
||||
@@ -273,92 +298,94 @@ public final class ChargeDefinitionCommandFromApiJsonDeserializer {
|
||||
throw new InvalidJsonException();
|
||||
}
|
||||
|
||||
final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType();
|
||||
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParameters);
|
||||
final Type typeOfMap = new TypeToken<Map<String, Object>>() {
|
||||
|
||||
}.getType();
|
||||
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, SUPPORTED_PARAMETERS);
|
||||
|
||||
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);
|
||||
|
||||
if (this.fromApiJsonHelper.parameterExists("name", element)) {
|
||||
final String name = this.fromApiJsonHelper.extractStringNamed("name", element);
|
||||
baseDataValidator.reset().parameter("name").value(name).notBlank().notExceedingLengthOf(100);
|
||||
if (this.fromApiJsonHelper.parameterExists(NAME, element)) {
|
||||
final String name = this.fromApiJsonHelper.extractStringNamed(NAME, element);
|
||||
baseDataValidator.reset().parameter(NAME).value(name).notBlank().notExceedingLengthOf(100);
|
||||
}
|
||||
|
||||
if (this.fromApiJsonHelper.parameterExists("currencyCode", element)) {
|
||||
final String currencyCode = this.fromApiJsonHelper.extractStringNamed("currencyCode", element);
|
||||
baseDataValidator.reset().parameter("currencyCode").value(currencyCode).notBlank().notExceedingLengthOf(3);
|
||||
if (this.fromApiJsonHelper.parameterExists(CURRENCY_CODE, element)) {
|
||||
final String currencyCode = this.fromApiJsonHelper.extractStringNamed(CURRENCY_CODE, element);
|
||||
baseDataValidator.reset().parameter(CURRENCY_CODE).value(currencyCode).notBlank().notExceedingLengthOf(3);
|
||||
}
|
||||
|
||||
if (this.fromApiJsonHelper.parameterExists("amount", element)) {
|
||||
final BigDecimal amount = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed("amount", element.getAsJsonObject());
|
||||
baseDataValidator.reset().parameter("amount").value(amount).notNull().positiveAmount();
|
||||
if (this.fromApiJsonHelper.parameterExists(AMOUNT, element)) {
|
||||
final BigDecimal amount = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed(AMOUNT, element.getAsJsonObject());
|
||||
baseDataValidator.reset().parameter(AMOUNT).value(amount).notNull().positiveAmount();
|
||||
}
|
||||
|
||||
if (this.fromApiJsonHelper.parameterExists("minCap", element)) {
|
||||
final BigDecimal minCap = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed("minCap", element.getAsJsonObject());
|
||||
baseDataValidator.reset().parameter("minCap").value(minCap).notNull().positiveAmount();
|
||||
if (this.fromApiJsonHelper.parameterExists(MIN_CAP, element)) {
|
||||
final BigDecimal minCap = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed(MIN_CAP, element.getAsJsonObject());
|
||||
baseDataValidator.reset().parameter(MIN_CAP).value(minCap).notNull().positiveAmount();
|
||||
}
|
||||
|
||||
if (this.fromApiJsonHelper.parameterExists("maxCap", element)) {
|
||||
final BigDecimal maxCap = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed("maxCap", element.getAsJsonObject());
|
||||
baseDataValidator.reset().parameter("maxCap").value(maxCap).notNull().positiveAmount();
|
||||
if (this.fromApiJsonHelper.parameterExists(MAX_CAP, element)) {
|
||||
final BigDecimal maxCap = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed(MAX_CAP, element.getAsJsonObject());
|
||||
baseDataValidator.reset().parameter(MAX_CAP).value(maxCap).notNull().positiveAmount();
|
||||
}
|
||||
|
||||
if (this.fromApiJsonHelper.parameterExists("chargeAppliesTo", element)) {
|
||||
final Integer chargeAppliesTo = this.fromApiJsonHelper.extractIntegerSansLocaleNamed("chargeAppliesTo", element);
|
||||
baseDataValidator.reset().parameter("chargeAppliesTo").value(chargeAppliesTo).notNull()
|
||||
if (this.fromApiJsonHelper.parameterExists(CHARGE_APPLIES_TO, element)) {
|
||||
final Integer chargeAppliesTo = this.fromApiJsonHelper.extractIntegerSansLocaleNamed(CHARGE_APPLIES_TO, element);
|
||||
baseDataValidator.reset().parameter(CHARGE_APPLIES_TO).value(chargeAppliesTo).notNull()
|
||||
.isOneOfTheseValues(ChargeAppliesTo.validValues());
|
||||
}
|
||||
|
||||
Boolean enableFreeWithdrawalCharge = false;
|
||||
if (this.fromApiJsonHelper.parameterExists("enableFreeWithdrawalCharge", element)) {
|
||||
enableFreeWithdrawalCharge = this.fromApiJsonHelper.extractBooleanNamed("enableFreeWithdrawalCharge", element);
|
||||
baseDataValidator.reset().parameter("enableFreeWithdrawalCharge").value(enableFreeWithdrawalCharge).notNull();
|
||||
if (this.fromApiJsonHelper.parameterExists(ENABLE_FREE_WITHDRAWAL_CHARGE, element)) {
|
||||
enableFreeWithdrawalCharge = this.fromApiJsonHelper.extractBooleanNamed(ENABLE_FREE_WITHDRAWAL_CHARGE, element);
|
||||
baseDataValidator.reset().parameter(ENABLE_FREE_WITHDRAWAL_CHARGE).value(enableFreeWithdrawalCharge).notNull();
|
||||
|
||||
if (enableFreeWithdrawalCharge) {
|
||||
|
||||
final Integer freeWithdrawalFrequency = this.fromApiJsonHelper.extractIntegerNamed("freeWithdrawalFrequency", element,
|
||||
final Integer freeWithdrawalFrequency = this.fromApiJsonHelper.extractIntegerNamed(FREE_WITHDRAWAL_FREQUENCY, element,
|
||||
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());
|
||||
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());
|
||||
baseDataValidator.reset().parameter("countFrequencyType").value(countFrequencyType);
|
||||
baseDataValidator.reset().parameter(COUNT_FREQUENCY_TYPE).value(countFrequencyType);
|
||||
}
|
||||
|
||||
Boolean enablePaymentType = false;
|
||||
if (this.fromApiJsonHelper.parameterExists("enablePaymentType", element)) {
|
||||
enablePaymentType = this.fromApiJsonHelper.extractBooleanNamed("enablePaymentType", element);
|
||||
baseDataValidator.reset().parameter("enablePaymentType").value(enablePaymentType).notNull();
|
||||
if (this.fromApiJsonHelper.parameterExists(ENABLE_PAYMENT_TYPE, element)) {
|
||||
enablePaymentType = this.fromApiJsonHelper.extractBooleanNamed(ENABLE_PAYMENT_TYPE, element);
|
||||
baseDataValidator.reset().parameter(ENABLE_PAYMENT_TYPE).value(enablePaymentType).notNull();
|
||||
|
||||
if (enablePaymentType) {
|
||||
final Integer paymentTypeId = this.fromApiJsonHelper.extractIntegerNamed("paymentTypeId", element, Locale.getDefault());
|
||||
baseDataValidator.reset().parameter("paymentTypeId").value(paymentTypeId).integerGreaterThanZero();
|
||||
final Integer paymentTypeId = this.fromApiJsonHelper.extractIntegerNamed(PAYMENT_TYPE_ID, element, Locale.getDefault());
|
||||
baseDataValidator.reset().parameter(PAYMENT_TYPE_ID).value(paymentTypeId).integerGreaterThanZero();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (this.fromApiJsonHelper.parameterExists("chargeAppliesTo", element)) {
|
||||
final Integer chargeAppliesTo = this.fromApiJsonHelper.extractIntegerSansLocaleNamed("chargeAppliesTo", element);
|
||||
baseDataValidator.reset().parameter("chargeAppliesTo").value(chargeAppliesTo).notNull()
|
||||
if (this.fromApiJsonHelper.parameterExists(CHARGE_APPLIES_TO, element)) {
|
||||
final Integer chargeAppliesTo = this.fromApiJsonHelper.extractIntegerSansLocaleNamed(CHARGE_APPLIES_TO, element);
|
||||
baseDataValidator.reset().parameter(CHARGE_APPLIES_TO).value(chargeAppliesTo).notNull()
|
||||
.isOneOfTheseValues(ChargeAppliesTo.validValues());
|
||||
}
|
||||
|
||||
if (this.fromApiJsonHelper.parameterExists("chargeAppliesTo", element)) {
|
||||
final Integer chargeAppliesTo = this.fromApiJsonHelper.extractIntegerSansLocaleNamed("chargeAppliesTo", element);
|
||||
baseDataValidator.reset().parameter("chargeAppliesTo").value(chargeAppliesTo).notNull()
|
||||
if (this.fromApiJsonHelper.parameterExists(CHARGE_APPLIES_TO, element)) {
|
||||
final Integer chargeAppliesTo = this.fromApiJsonHelper.extractIntegerSansLocaleNamed(CHARGE_APPLIES_TO, element);
|
||||
baseDataValidator.reset().parameter(CHARGE_APPLIES_TO).value(chargeAppliesTo).notNull()
|
||||
.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> validSavingsValues = Arrays.asList(ChargeTimeType.validSavingsValues());
|
||||
@@ -368,51 +395,51 @@ public final class ChargeDefinitionCommandFromApiJsonDeserializer {
|
||||
allValidValues.addAll(validSavingsValues);
|
||||
allValidValues.addAll(validClientValues);
|
||||
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()]));
|
||||
}
|
||||
|
||||
if (this.fromApiJsonHelper.parameterExists("feeOnMonthDay", element)) {
|
||||
final MonthDay monthDay = this.fromApiJsonHelper.extractMonthDayNamed("feeOnMonthDay", element);
|
||||
baseDataValidator.reset().parameter("feeOnMonthDay").value(monthDay).notNull();
|
||||
if (this.fromApiJsonHelper.parameterExists(FEE_ON_MONTH_DAY, element)) {
|
||||
final MonthDay monthDay = this.fromApiJsonHelper.extractMonthDayNamed(FEE_ON_MONTH_DAY, element);
|
||||
baseDataValidator.reset().parameter(FEE_ON_MONTH_DAY).value(monthDay).notNull();
|
||||
}
|
||||
|
||||
if (this.fromApiJsonHelper.parameterExists("feeInterval", element)) {
|
||||
final Integer feeInterval = this.fromApiJsonHelper.extractIntegerNamed("feeInterval", element, Locale.getDefault());
|
||||
baseDataValidator.reset().parameter("feeInterval").value(feeInterval).integerGreaterThanZero();
|
||||
if (this.fromApiJsonHelper.parameterExists(FEE_INTERVAL, element)) {
|
||||
final Integer feeInterval = this.fromApiJsonHelper.extractIntegerNamed(FEE_INTERVAL, element, Locale.getDefault());
|
||||
baseDataValidator.reset().parameter(FEE_INTERVAL).value(feeInterval).integerGreaterThanZero();
|
||||
}
|
||||
|
||||
if (this.fromApiJsonHelper.parameterExists("chargeCalculationType", element)) {
|
||||
final Integer chargeCalculationType = this.fromApiJsonHelper.extractIntegerNamed("chargeCalculationType", element,
|
||||
if (this.fromApiJsonHelper.parameterExists(CHARGE_CALCULATION_TYPE, element)) {
|
||||
final Integer chargeCalculationType = this.fromApiJsonHelper.extractIntegerNamed(CHARGE_CALCULATION_TYPE, element,
|
||||
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)) {
|
||||
final Integer chargePaymentMode = this.fromApiJsonHelper.extractIntegerNamed("chargePaymentMode", element, Locale.getDefault());
|
||||
baseDataValidator.reset().parameter("chargePaymentMode").value(chargePaymentMode).notNull().inMinMaxRange(0, 1);
|
||||
if (this.fromApiJsonHelper.parameterExists(CHARGE_PAYMENT_MODE, element)) {
|
||||
final Integer chargePaymentMode = this.fromApiJsonHelper.extractIntegerNamed(CHARGE_PAYMENT_MODE, element, Locale.getDefault());
|
||||
baseDataValidator.reset().parameter(CHARGE_PAYMENT_MODE).value(chargePaymentMode).notNull().inMinMaxRange(0, 1);
|
||||
}
|
||||
|
||||
if (this.fromApiJsonHelper.parameterExists("penalty", element)) {
|
||||
final Boolean penalty = this.fromApiJsonHelper.extractBooleanNamed("penalty", element);
|
||||
baseDataValidator.reset().parameter("penalty").value(penalty).notNull();
|
||||
if (this.fromApiJsonHelper.parameterExists(PENALTY, element)) {
|
||||
final Boolean penalty = this.fromApiJsonHelper.extractBooleanNamed(PENALTY, element);
|
||||
baseDataValidator.reset().parameter(PENALTY).value(penalty).notNull();
|
||||
}
|
||||
|
||||
if (this.fromApiJsonHelper.parameterExists("active", element)) {
|
||||
final Boolean active = this.fromApiJsonHelper.extractBooleanNamed("active", element);
|
||||
baseDataValidator.reset().parameter("active").value(active).notNull();
|
||||
if (this.fromApiJsonHelper.parameterExists(ACTIVE, element)) {
|
||||
final Boolean active = this.fromApiJsonHelper.extractBooleanNamed(ACTIVE, element);
|
||||
baseDataValidator.reset().parameter(ACTIVE).value(active).notNull();
|
||||
}
|
||||
if (this.fromApiJsonHelper.parameterExists("minCap", element)) {
|
||||
final BigDecimal minCap = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed("minCap", element.getAsJsonObject());
|
||||
baseDataValidator.reset().parameter("minCap").value(minCap).notNull().positiveAmount();
|
||||
if (this.fromApiJsonHelper.parameterExists(MIN_CAP, element)) {
|
||||
final BigDecimal minCap = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed(MIN_CAP, element.getAsJsonObject());
|
||||
baseDataValidator.reset().parameter(MIN_CAP).value(minCap).notNull().positiveAmount();
|
||||
}
|
||||
if (this.fromApiJsonHelper.parameterExists("maxCap", element)) {
|
||||
final BigDecimal maxCap = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed("maxCap", element.getAsJsonObject());
|
||||
baseDataValidator.reset().parameter("maxCap").value(maxCap).notNull().positiveAmount();
|
||||
if (this.fromApiJsonHelper.parameterExists(MAX_CAP, element)) {
|
||||
final BigDecimal maxCap = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed(MAX_CAP, element.getAsJsonObject());
|
||||
baseDataValidator.reset().parameter(MAX_CAP).value(maxCap).notNull().positiveAmount();
|
||||
}
|
||||
if (this.fromApiJsonHelper.parameterExists("feeFrequency", element)) {
|
||||
final Integer feeFrequency = this.fromApiJsonHelper.extractIntegerNamed("feeFrequency", element, Locale.getDefault());
|
||||
baseDataValidator.reset().parameter("feeFrequency").value(feeFrequency).inMinMaxRange(0, 3);
|
||||
if (this.fromApiJsonHelper.parameterExists(FEE_FREQUENCY, element)) {
|
||||
final Integer feeFrequency = this.fromApiJsonHelper.extractIntegerNamed(FEE_FREQUENCY, element, Locale.getDefault());
|
||||
baseDataValidator.reset().parameter(FEE_FREQUENCY).value(feeFrequency).inMinMaxRange(0, 3);
|
||||
}
|
||||
|
||||
if (this.fromApiJsonHelper.parameterExists(ChargesApiConstants.glAccountIdParamName, element)) {
|
||||
@@ -429,25 +456,25 @@ public final class ChargeDefinitionCommandFromApiJsonDeserializer {
|
||||
throwExceptionIfValidationWarningsExist(dataValidationErrors);
|
||||
}
|
||||
|
||||
public void validateChargeTimeNCalculationType(Integer chargeTimeType, Integer ChargeCalculationType) {
|
||||
public void validateChargeTimeNCalculationType(Integer chargeTimeType, Integer chargeCalculationType) {
|
||||
final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
|
||||
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("charge");
|
||||
performChargeTimeNCalculationTypeValidation(baseDataValidator, chargeTimeType, ChargeCalculationType);
|
||||
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource(CHARGE);
|
||||
performChargeTimeNCalculationTypeValidation(baseDataValidator, chargeTimeType, chargeCalculationType);
|
||||
throwExceptionIfValidationWarningsExist(dataValidationErrors);
|
||||
}
|
||||
|
||||
private void performChargeTimeNCalculationTypeValidation(DataValidatorBuilder baseDataValidator, final Integer chargeTimeType,
|
||||
final Integer chargeCalculationType) {
|
||||
if (chargeTimeType.equals(ChargeTimeType.SHAREACCOUNT_ACTIVATION.getValue())) {
|
||||
baseDataValidator.reset().parameter("chargeCalculationType").value(chargeCalculationType)
|
||||
baseDataValidator.reset().parameter(CHARGE_CALCULATION_TYPE).value(chargeCalculationType)
|
||||
.isOneOfTheseValues(ChargeCalculationType.validValuesForShareAccountActivation());
|
||||
}
|
||||
|
||||
if (chargeTimeType.equals(ChargeTimeType.TRANCHE_DISBURSEMENT.getValue())) {
|
||||
baseDataValidator.reset().parameter("chargeCalculationType").value(chargeCalculationType)
|
||||
baseDataValidator.reset().parameter(CHARGE_CALCULATION_TYPE).value(chargeCalculationType)
|
||||
.isOneOfTheseValues(ChargeCalculationType.validValuesForTrancheDisbursement());
|
||||
} else {
|
||||
baseDataValidator.reset().parameter("chargeCalculationType").value(chargeCalculationType)
|
||||
baseDataValidator.reset().parameter(CHARGE_CALCULATION_TYPE).value(chargeCalculationType)
|
||||
.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.")
|
||||
public class ClientAddressApiResources {
|
||||
|
||||
private final Set<String> responseDataParameters = new HashSet<>(Arrays.asList("addressId", "street", "addressLine1", "addressLine2",
|
||||
"addressLine3", "townVillage", "city", "countyDistrict", "stateProvinceId", "countryId", "postalCode", "latitude", "longitude",
|
||||
"createdBy", "createdOn", "updatedBy", "updatedOn", "clientAddressId", "client_id", "address_id", "address_type_id", "isActive",
|
||||
"fieldConfigurationId", "entity", "table", "field", "is_enabled", "is_mandatory", "validation_regex"));
|
||||
private final String resourceNameForPermissions = "Address";
|
||||
private static final Set<String> RESPONSE_DATA_PARAMETERS = new HashSet<>(
|
||||
Arrays.asList("addressId", "street", "addressLine1", "addressLine2", "addressLine3", "townVillage", "city", "countyDistrict",
|
||||
"stateProvinceId", "countryId", "postalCode", "latitude", "longitude", "createdBy", "createdOn", "updatedBy",
|
||||
"updatedOn", "clientAddressId", "client_id", "address_id", "address_type_id", "isActive", "fieldConfigurationId",
|
||||
"entity", "table", "field", "is_enabled", "is_mandatory", "validation_regex"));
|
||||
private static final String RESOURCE_NAME_FOR_PERMISSIONS = "Address";
|
||||
private final PlatformSecurityContext context;
|
||||
private final AddressReadPlatformServiceImpl readPlatformService;
|
||||
private final DefaultToApiJsonSerializer<AddressData> toApiJsonSerializer;
|
||||
@@ -89,12 +90,12 @@ public class ClientAddressApiResources {
|
||||
@Consumes({ MediaType.APPLICATION_JSON })
|
||||
@Produces({ MediaType.APPLICATION_JSON })
|
||||
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 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) {
|
||||
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
|
||||
// These have to be considered as filtering criterias instead
|
||||
@@ -146,7 +147,7 @@ public class ClientAddressApiResources {
|
||||
}
|
||||
|
||||
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 = "")
|
||||
public class ClientFamilyMembersApiResources {
|
||||
|
||||
private final Set<String> responseDataParameters = new HashSet<>(Arrays.asList("id", "clientId", "firstName", "middleName", "lastName",
|
||||
"qualification", "relationship", "maritalStatus", "gender", "dateOfBirth", "profession", "clientFamilyMemberId"));
|
||||
private final String resourceNameForPermissions = "FamilyMembers";
|
||||
private static final Set<String> RESPONSE_DATA_PARAMETERS = new HashSet<>(Arrays.asList("id", "clientId", "firstName", "middleName",
|
||||
"lastName", "qualification", "relationship", "maritalStatus", "gender", "dateOfBirth", "profession", "clientFamilyMemberId"));
|
||||
private static final String RESOURCE_NAME_FOR_PERMISSIONS = "FamilyMembers";
|
||||
private final PlatformSecurityContext context;
|
||||
private final ClientFamilyMembersReadPlatformService readPlatformService;
|
||||
private final ToApiJsonSerializer<ClientFamilyMembersData> toApiJsonSerializer;
|
||||
@@ -86,12 +86,12 @@ public class ClientFamilyMembersApiResources {
|
||||
public String getFamilyMember(@Context final UriInfo uriInfo, @PathParam("familyMemberId") final Long familyMemberId,
|
||||
@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 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 })
|
||||
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 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 })
|
||||
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 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<>(
|
||||
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 ClientReadPlatformService clientReadPlatformService;
|
||||
@@ -107,7 +107,7 @@ public class ClientIdentifiersApiResource {
|
||||
public String retrieveAllClientIdentifiers(@Context final UriInfo uriInfo,
|
||||
@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
|
||||
.retrieveClientIdentifiers(clientId);
|
||||
@@ -127,7 +127,7 @@ public class ClientIdentifiersApiResource {
|
||||
public String newClientIdentifierDetails(@Context final UriInfo uriInfo,
|
||||
@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 ClientIdentifierData clientIdentifierData = ClientIdentifierData.template(codeValues);
|
||||
@@ -178,7 +178,7 @@ public class ClientIdentifiersApiResource {
|
||||
@PathParam("identifierId") @Parameter(description = "identifierId") final Long clientIdentifierId,
|
||||
@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());
|
||||
|
||||
|
||||
+107
-82
@@ -42,10 +42,29 @@ import org.springframework.stereotype.Component;
|
||||
@Component
|
||||
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 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
|
||||
public ClientFamilyMemberCommandFromApiJsonDeserializer(final FromJsonHelper fromApiJsonHelper) {
|
||||
@@ -58,18 +77,20 @@ public final class ClientFamilyMemberCommandFromApiJsonDeserializer {
|
||||
throw new InvalidJsonException();
|
||||
}
|
||||
|
||||
final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType();
|
||||
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParameters);
|
||||
final Type typeOfMap = new TypeToken<Map<String, Object>>() {
|
||||
|
||||
}.getType();
|
||||
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, SUPPORTED_PARAMETERS);
|
||||
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);
|
||||
|
||||
if (this.fromApiJsonHelper.extractArrayNamed("familyMembers", element) != null) {
|
||||
final JsonArray familyMembers = this.fromApiJsonHelper.extractJsonArrayNamed("familyMembers", element);
|
||||
if (this.fromApiJsonHelper.extractArrayNamed(FAMILY_MEMBERS, element) != null) {
|
||||
final JsonArray familyMembers = this.fromApiJsonHelper.extractJsonArrayNamed(FAMILY_MEMBERS, element);
|
||||
baseDataValidator.reset().value(familyMembers).arrayNotEmpty();
|
||||
} else {
|
||||
baseDataValidator.reset().value(this.fromApiJsonHelper.extractJsonArrayNamed("familyMembers", element)).arrayNotEmpty();
|
||||
baseDataValidator.reset().value(this.fromApiJsonHelper.extractJsonArrayNamed(FAMILY_MEMBERS, element)).arrayNotEmpty();
|
||||
}
|
||||
|
||||
validateForCreate(1, json);
|
||||
@@ -82,85 +103,87 @@ public final class ClientFamilyMemberCommandFromApiJsonDeserializer {
|
||||
throw new InvalidJsonException();
|
||||
}
|
||||
|
||||
final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType();
|
||||
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParameters);
|
||||
final Type typeOfMap = new TypeToken<Map<String, Object>>() {
|
||||
|
||||
}.getType();
|
||||
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, SUPPORTED_PARAMETERS);
|
||||
|
||||
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);
|
||||
|
||||
baseDataValidator.reset().value(clientId).notBlank().integerGreaterThanZero();
|
||||
|
||||
if (this.fromApiJsonHelper.extractStringNamed("firstName", element) != null) {
|
||||
final String firstName = this.fromApiJsonHelper.extractStringNamed("firstName", element);
|
||||
baseDataValidator.reset().parameter("firstName").value(firstName).notNull().notBlank().notExceedingLengthOf(100);
|
||||
if (this.fromApiJsonHelper.extractStringNamed(FIRST_NAME, element) != null) {
|
||||
final String firstName = this.fromApiJsonHelper.extractStringNamed(FIRST_NAME, element);
|
||||
baseDataValidator.reset().parameter(FIRST_NAME).value(firstName).notNull().notBlank().notExceedingLengthOf(100);
|
||||
} else {
|
||||
baseDataValidator.reset().parameter("firstName").value(this.fromApiJsonHelper.extractStringNamed("firstName", element))
|
||||
.notNull().notBlank().notExceedingLengthOf(100);
|
||||
baseDataValidator.reset().parameter(FIRST_NAME).value(this.fromApiJsonHelper.extractStringNamed(FIRST_NAME, element)).notNull()
|
||||
.notBlank().notExceedingLengthOf(100);
|
||||
}
|
||||
|
||||
if (this.fromApiJsonHelper.extractStringNamed("lastName", element) != null) {
|
||||
final String lastName = this.fromApiJsonHelper.extractStringNamed("lastName", element);
|
||||
baseDataValidator.reset().parameter("lastName").value(lastName).notNull().notBlank().notExceedingLengthOf(100);
|
||||
if (this.fromApiJsonHelper.extractStringNamed(LAST_NAME, element) != null) {
|
||||
final String lastName = this.fromApiJsonHelper.extractStringNamed(LAST_NAME, element);
|
||||
baseDataValidator.reset().parameter(LAST_NAME).value(lastName).notNull().notBlank().notExceedingLengthOf(100);
|
||||
}
|
||||
|
||||
if (this.fromApiJsonHelper.extractStringNamed("middleName", element) != null) {
|
||||
final String middleName = this.fromApiJsonHelper.extractStringNamed("middleName", element);
|
||||
baseDataValidator.reset().parameter("middleName").value(middleName).notNull().notBlank().notExceedingLengthOf(100);
|
||||
if (this.fromApiJsonHelper.extractStringNamed(MIDDLE_NAME, element) != null) {
|
||||
final String middleName = this.fromApiJsonHelper.extractStringNamed(MIDDLE_NAME, element);
|
||||
baseDataValidator.reset().parameter(MIDDLE_NAME).value(middleName).notNull().notBlank().notExceedingLengthOf(100);
|
||||
}
|
||||
|
||||
if (this.fromApiJsonHelper.extractStringNamed("qualification", element) != null) {
|
||||
final String qualification = this.fromApiJsonHelper.extractStringNamed("qualification", element);
|
||||
baseDataValidator.reset().parameter("qualification").value(qualification).notNull().notBlank().notExceedingLengthOf(100);
|
||||
if (this.fromApiJsonHelper.extractStringNamed(QUALIFICATION, element) != null) {
|
||||
final String qualification = this.fromApiJsonHelper.extractStringNamed(QUALIFICATION, element);
|
||||
baseDataValidator.reset().parameter(QUALIFICATION).value(qualification).notNull().notBlank().notExceedingLengthOf(100);
|
||||
}
|
||||
|
||||
if (this.fromApiJsonHelper.extractStringNamed("mobileNumber", element) != null) {
|
||||
final String mobileNumber = this.fromApiJsonHelper.extractStringNamed("mobileNumber", element);
|
||||
baseDataValidator.reset().parameter("mobileNumber").value(mobileNumber).notNull().notBlank().notExceedingLengthOf(100);
|
||||
if (this.fromApiJsonHelper.extractStringNamed(MOBILE_NUMBER, element) != null) {
|
||||
final String mobileNumber = this.fromApiJsonHelper.extractStringNamed(MOBILE_NUMBER, element);
|
||||
baseDataValidator.reset().parameter(MOBILE_NUMBER).value(mobileNumber).notNull().notBlank().notExceedingLengthOf(100);
|
||||
}
|
||||
|
||||
if (this.fromApiJsonHelper.extractBooleanNamed("isDependent", element) != null) {
|
||||
final Boolean isDependent = this.fromApiJsonHelper.extractBooleanNamed("isDependent", element);
|
||||
baseDataValidator.reset().parameter("isDependent").value(isDependent).notNull().notBlank().notExceedingLengthOf(100);
|
||||
if (this.fromApiJsonHelper.extractBooleanNamed(IS_DEPENDENT, element) != null) {
|
||||
final Boolean isDependent = this.fromApiJsonHelper.extractBooleanNamed(IS_DEPENDENT, element);
|
||||
baseDataValidator.reset().parameter(IS_DEPENDENT).value(isDependent).notNull().notBlank().notExceedingLengthOf(100);
|
||||
}
|
||||
|
||||
if (this.fromApiJsonHelper.extractLongNamed("relationShipId", element) != null) {
|
||||
final long relationShipId = this.fromApiJsonHelper.extractLongNamed("relationShipId", element);
|
||||
baseDataValidator.reset().parameter("relationShipId").value(relationShipId).notBlank().longGreaterThanZero();
|
||||
if (this.fromApiJsonHelper.extractLongNamed(RELATION_SHIP_ID, element) != null) {
|
||||
final long relationShipId = this.fromApiJsonHelper.extractLongNamed(RELATION_SHIP_ID, element);
|
||||
baseDataValidator.reset().parameter(RELATION_SHIP_ID).value(relationShipId).notBlank().longGreaterThanZero();
|
||||
|
||||
} 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();
|
||||
}
|
||||
|
||||
if (this.fromApiJsonHelper.extractLongNamed("maritalStatusId", element) != null) {
|
||||
final long maritalStatusId = this.fromApiJsonHelper.extractLongNamed("maritalStatusId", element);
|
||||
baseDataValidator.reset().parameter("maritalStatusId").value(maritalStatusId).notBlank().longGreaterThanZero();
|
||||
if (this.fromApiJsonHelper.extractLongNamed(MARITAL_STATUS_ID, element) != null) {
|
||||
final long maritalStatusId = this.fromApiJsonHelper.extractLongNamed(MARITAL_STATUS_ID, element);
|
||||
baseDataValidator.reset().parameter(MARITAL_STATUS_ID).value(maritalStatusId).notBlank().longGreaterThanZero();
|
||||
|
||||
}
|
||||
|
||||
if (this.fromApiJsonHelper.extractLongNamed("genderId", element) != null) {
|
||||
final long genderId = this.fromApiJsonHelper.extractLongNamed("genderId", element);
|
||||
baseDataValidator.reset().parameter("genderId").value(genderId).notBlank().longGreaterThanZero();
|
||||
if (this.fromApiJsonHelper.extractLongNamed(GENDER_ID, element) != null) {
|
||||
final long genderId = this.fromApiJsonHelper.extractLongNamed(GENDER_ID, element);
|
||||
baseDataValidator.reset().parameter(GENDER_ID).value(genderId).notBlank().longGreaterThanZero();
|
||||
|
||||
}
|
||||
|
||||
if (this.fromApiJsonHelper.extractLongNamed("age", element) != null) {
|
||||
final long age = this.fromApiJsonHelper.extractLongNamed("age", element);
|
||||
baseDataValidator.reset().parameter("age").value(age).notBlank().longGreaterThanZero();
|
||||
if (this.fromApiJsonHelper.extractLongNamed(AGE, element) != null) {
|
||||
final long age = this.fromApiJsonHelper.extractLongNamed(AGE, element);
|
||||
baseDataValidator.reset().parameter(AGE).value(age).notBlank().longGreaterThanZero();
|
||||
|
||||
}
|
||||
|
||||
if (this.fromApiJsonHelper.extractLongNamed("professionId", element) != null) {
|
||||
final long professionId = this.fromApiJsonHelper.extractLongNamed("professionId", element);
|
||||
baseDataValidator.reset().parameter("professionId").value(professionId).notBlank().longGreaterThanZero();
|
||||
if (this.fromApiJsonHelper.extractLongNamed(PROFESSION_ID, element) != null) {
|
||||
final long professionId = this.fromApiJsonHelper.extractLongNamed(PROFESSION_ID, element);
|
||||
baseDataValidator.reset().parameter(PROFESSION_ID).value(professionId).notBlank().longGreaterThanZero();
|
||||
|
||||
}
|
||||
|
||||
if (this.fromApiJsonHelper.extractLocalDateNamed("dateOfBirth", element) != null) {
|
||||
final LocalDate dateOfBirth = this.fromApiJsonHelper.extractLocalDateNamed("dateOfBirth", element);
|
||||
baseDataValidator.reset().parameter("dateOfBirth").value(dateOfBirth).value(dateOfBirth).notNull()
|
||||
if (this.fromApiJsonHelper.extractLocalDateNamed(DATE_OF_BIRTH, element) != null) {
|
||||
final LocalDate dateOfBirth = this.fromApiJsonHelper.extractLocalDateNamed(DATE_OF_BIRTH, element);
|
||||
baseDataValidator.reset().parameter(DATE_OF_BIRTH).value(dateOfBirth).value(dateOfBirth).notNull()
|
||||
.validateDateBefore(DateUtils.getBusinessLocalDate());
|
||||
|
||||
}
|
||||
@@ -173,63 +196,65 @@ public final class ClientFamilyMemberCommandFromApiJsonDeserializer {
|
||||
throw new InvalidJsonException();
|
||||
}
|
||||
|
||||
final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType();
|
||||
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParameters);
|
||||
final Type typeOfMap = new TypeToken<Map<String, Object>>() {
|
||||
|
||||
}.getType();
|
||||
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, SUPPORTED_PARAMETERS);
|
||||
|
||||
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);
|
||||
|
||||
baseDataValidator.reset().value(familyMemberId).notBlank().integerGreaterThanZero();
|
||||
|
||||
if (this.fromApiJsonHelper.extractStringNamed("firstName", element) != null) {
|
||||
final String firstName = this.fromApiJsonHelper.extractStringNamed("firstName", element);
|
||||
baseDataValidator.reset().parameter("firstName").value(firstName).notNull().notBlank().notExceedingLengthOf(100);
|
||||
if (this.fromApiJsonHelper.extractStringNamed(FIRST_NAME, element) != null) {
|
||||
final String firstName = this.fromApiJsonHelper.extractStringNamed(FIRST_NAME, element);
|
||||
baseDataValidator.reset().parameter(FIRST_NAME).value(firstName).notNull().notBlank().notExceedingLengthOf(100);
|
||||
}
|
||||
|
||||
if (this.fromApiJsonHelper.extractStringNamed("lastName", element) != null) {
|
||||
final String lastName = this.fromApiJsonHelper.extractStringNamed("lastName", element);
|
||||
baseDataValidator.reset().parameter("lastName").value(lastName).notNull().notBlank().notExceedingLengthOf(100);
|
||||
if (this.fromApiJsonHelper.extractStringNamed(LAST_NAME, element) != null) {
|
||||
final String lastName = this.fromApiJsonHelper.extractStringNamed(LAST_NAME, element);
|
||||
baseDataValidator.reset().parameter(LAST_NAME).value(lastName).notNull().notBlank().notExceedingLengthOf(100);
|
||||
}
|
||||
|
||||
if (this.fromApiJsonHelper.extractStringNamed("middleName", element) != null) {
|
||||
final String middleName = this.fromApiJsonHelper.extractStringNamed("middleName", element);
|
||||
baseDataValidator.reset().parameter("middleName").value(middleName).notNull().notBlank().notExceedingLengthOf(100);
|
||||
if (this.fromApiJsonHelper.extractStringNamed(MIDDLE_NAME, element) != null) {
|
||||
final String middleName = this.fromApiJsonHelper.extractStringNamed(MIDDLE_NAME, element);
|
||||
baseDataValidator.reset().parameter(MIDDLE_NAME).value(middleName).notNull().notBlank().notExceedingLengthOf(100);
|
||||
}
|
||||
|
||||
if (this.fromApiJsonHelper.extractStringNamed("qualification", element) != null) {
|
||||
final String qualification = this.fromApiJsonHelper.extractStringNamed("qualification", element);
|
||||
baseDataValidator.reset().parameter("qualification").value(qualification).notNull().notBlank().notExceedingLengthOf(100);
|
||||
if (this.fromApiJsonHelper.extractStringNamed(QUALIFICATION, element) != null) {
|
||||
final String qualification = this.fromApiJsonHelper.extractStringNamed(QUALIFICATION, element);
|
||||
baseDataValidator.reset().parameter(QUALIFICATION).value(qualification).notNull().notBlank().notExceedingLengthOf(100);
|
||||
}
|
||||
|
||||
if (this.fromApiJsonHelper.extractLongNamed("relationShipId", element) != null) {
|
||||
final long relationShipId = this.fromApiJsonHelper.extractLongNamed("relationShipId", element);
|
||||
baseDataValidator.reset().parameter("relationShipId").value(relationShipId).notBlank().longGreaterThanZero();
|
||||
if (this.fromApiJsonHelper.extractLongNamed(RELATION_SHIP_ID, element) != null) {
|
||||
final long relationShipId = this.fromApiJsonHelper.extractLongNamed(RELATION_SHIP_ID, element);
|
||||
baseDataValidator.reset().parameter(RELATION_SHIP_ID).value(relationShipId).notBlank().longGreaterThanZero();
|
||||
|
||||
}
|
||||
|
||||
if (this.fromApiJsonHelper.extractLongNamed("maritalStatusId", element) != null) {
|
||||
final long maritalStatusId = this.fromApiJsonHelper.extractLongNamed("maritalStatusId", element);
|
||||
baseDataValidator.reset().parameter("maritalStatusId").value(maritalStatusId).notBlank().longGreaterThanZero();
|
||||
if (this.fromApiJsonHelper.extractLongNamed(MARITAL_STATUS_ID, element) != null) {
|
||||
final long maritalStatusId = this.fromApiJsonHelper.extractLongNamed(MARITAL_STATUS_ID, element);
|
||||
baseDataValidator.reset().parameter(MARITAL_STATUS_ID).value(maritalStatusId).notBlank().longGreaterThanZero();
|
||||
|
||||
}
|
||||
|
||||
if (this.fromApiJsonHelper.extractLongNamed("genderId", element) != null) {
|
||||
final long genderId = this.fromApiJsonHelper.extractLongNamed("genderId", element);
|
||||
baseDataValidator.reset().parameter("genderId").value(genderId).longGreaterThanZero();
|
||||
if (this.fromApiJsonHelper.extractLongNamed(GENDER_ID, element) != null) {
|
||||
final long genderId = this.fromApiJsonHelper.extractLongNamed(GENDER_ID, element);
|
||||
baseDataValidator.reset().parameter(GENDER_ID).value(genderId).longGreaterThanZero();
|
||||
|
||||
}
|
||||
|
||||
if (this.fromApiJsonHelper.extractLongNamed("professionId", element) != null) {
|
||||
final long professionId = this.fromApiJsonHelper.extractLongNamed("professionId", element);
|
||||
baseDataValidator.reset().parameter("professionId").value(professionId).longGreaterThanZero();
|
||||
if (this.fromApiJsonHelper.extractLongNamed(PROFESSION_ID, element) != null) {
|
||||
final long professionId = this.fromApiJsonHelper.extractLongNamed(PROFESSION_ID, element);
|
||||
baseDataValidator.reset().parameter(PROFESSION_ID).value(professionId).longGreaterThanZero();
|
||||
|
||||
}
|
||||
|
||||
if (this.fromApiJsonHelper.extractLocalDateNamed("dateOfBirth", element) != null) {
|
||||
final LocalDate dateOfBirth = this.fromApiJsonHelper.extractLocalDateNamed("dateOfBirth", element);
|
||||
baseDataValidator.reset().parameter("dateOfBirth").value(dateOfBirth).validateDateBefore(DateUtils.getBusinessLocalDate());
|
||||
if (this.fromApiJsonHelper.extractLocalDateNamed(DATE_OF_BIRTH, element) != null) {
|
||||
final LocalDate dateOfBirth = this.fromApiJsonHelper.extractLocalDateNamed(DATE_OF_BIRTH, element);
|
||||
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) {
|
||||
|
||||
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);
|
||||
|
||||
|
||||
+15
-8
@@ -40,11 +40,16 @@ import org.springframework.stereotype.Component;
|
||||
@Component
|
||||
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.
|
||||
*/
|
||||
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;
|
||||
|
||||
@Autowired
|
||||
@@ -59,14 +64,16 @@ public final class ClientIdentifierCommandFromApiJsonDeserializer extends Abstra
|
||||
throw new InvalidJsonException();
|
||||
}
|
||||
|
||||
final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType();
|
||||
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParameters);
|
||||
final Type typeOfMap = new TypeToken<Map<String, Object>>() {
|
||||
|
||||
}.getType();
|
||||
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, SUPPORTED_PARAMETERS);
|
||||
|
||||
final JsonElement element = this.fromApiJsonHelper.parse(json);
|
||||
final Long documentTypeId = this.fromApiJsonHelper.extractLongNamed("documentTypeId", element);
|
||||
final String documentKey = this.fromApiJsonHelper.extractStringNamed("documentKey", element);
|
||||
final String documentDescription = this.fromApiJsonHelper.extractStringNamed("documentDescription", element);
|
||||
final String statusString = this.fromApiJsonHelper.extractStringNamed("status", element);
|
||||
final Long documentTypeId = this.fromApiJsonHelper.extractLongNamed(DOCUMENT_TYPE_ID, element);
|
||||
final String documentKey = this.fromApiJsonHelper.extractStringNamed(DOCUMENT_KEY, element);
|
||||
final String documentDescription = this.fromApiJsonHelper.extractStringNamed(DOCUMENT_DESCRIPTION, element);
|
||||
final String statusString = this.fromApiJsonHelper.extractStringNamed(STATUS, element);
|
||||
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);
|
||||
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()) {
|
||||
final String errorMessage = "Client cannot be closed because of non-closed loans.";
|
||||
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<>(
|
||||
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 DefaultToApiJsonSerializer<CollateralData> apiJsonSerializerService;
|
||||
@@ -101,7 +101,7 @@ public class CollateralsApiResource {
|
||||
public String newCollateralTemplate(@Context final UriInfo uriInfo,
|
||||
@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 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)))) })
|
||||
public String retrieveCollateralDetails(@Context final UriInfo uriInfo,
|
||||
@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());
|
||||
|
||||
return this.apiJsonSerializerService.serialize(settings, CollateralDatas, RESPONSE_DATA_PARAMETERS);
|
||||
return this.apiJsonSerializerService.serialize(settings, collateralDatas, RESPONSE_DATA_PARAMETERS);
|
||||
}
|
||||
|
||||
@GET
|
||||
@@ -139,7 +139,7 @@ public class CollateralsApiResource {
|
||||
public String retrieveCollateralDetails(@Context final UriInfo uriInfo,
|
||||
@PathParam("loanId") @Parameter(description = "loanId") final Long loanId,
|
||||
@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);
|
||||
|
||||
|
||||
+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
|
||||
**/
|
||||
if (!loan.status().isSubmittedAndPendingApproval()) {
|
||||
if (!loan.getStatus().isSubmittedAndPendingApproval()) {
|
||||
throw new CollateralCannotBeCreatedException(
|
||||
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
|
||||
**/
|
||||
if (!loan.status().isSubmittedAndPendingApproval()) {
|
||||
if (!loan.getStatus().isSubmittedAndPendingApproval()) {
|
||||
throw new CollateralCannotBeUpdatedException(
|
||||
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
|
||||
**/
|
||||
if (!loan.status().isSubmittedAndPendingApproval()) {
|
||||
if (!loan.getStatus().isSubmittedAndPendingApproval()) {
|
||||
throw new CollateralCannotBeDeletedException(
|
||||
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.service.CommandWrapperBuilder;
|
||||
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.serialization.DefaultToApiJsonSerializer;
|
||||
import org.apache.fineract.infrastructure.security.service.PlatformSecurityContext;
|
||||
import org.apache.fineract.organisation.monetary.data.CurrencyData;
|
||||
import org.apache.fineract.organisation.monetary.service.CurrencyReadPlatformService;
|
||||
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.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Scope;
|
||||
@@ -64,31 +61,21 @@ public class CollateralManagementApiResource {
|
||||
|
||||
private final DefaultToApiJsonSerializer<CollateralManagementData> apiJsonSerializerService;
|
||||
private final DefaultToApiJsonSerializer<CurrencyData> apiJsonSerializerServiceForCurrency;
|
||||
private final ApiRequestParameterHelper apiRequestParameterHelper;
|
||||
private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService;
|
||||
private final PlatformSecurityContext context;
|
||||
private final CodeValueReadPlatformService codeValueReadPlatformService;
|
||||
private final CollateralManagementReadPlatformService collateralManagementReadPlatformService;
|
||||
private final String collateralReadPermission = "COLLATERAL_PRODUCT";
|
||||
private final ClientCollateralManagementReadPlatformService clientCollateralManagementReadPlatformService;
|
||||
private final CurrencyReadPlatformService currencyReadPlatformService;
|
||||
|
||||
@Autowired
|
||||
public CollateralManagementApiResource(final DefaultToApiJsonSerializer<CollateralManagementData> apiJsonSerializerService,
|
||||
final ApiRequestParameterHelper apiRequestParameterHelper,
|
||||
final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService, final PlatformSecurityContext context,
|
||||
final CodeValueReadPlatformService codeValueReadPlatformService,
|
||||
final CollateralManagementReadPlatformService collateralManagementReadPlatformService,
|
||||
final ClientCollateralManagementReadPlatformService clientCollateralManagementReadPlatformService,
|
||||
final CurrencyReadPlatformService currencyReadPlatformService,
|
||||
final DefaultToApiJsonSerializer<CurrencyData> apiJsonSerializerServiceForCurrency) {
|
||||
this.apiJsonSerializerService = apiJsonSerializerService;
|
||||
this.apiRequestParameterHelper = apiRequestParameterHelper;
|
||||
this.commandsSourceWritePlatformService = commandsSourceWritePlatformService;
|
||||
this.context = context;
|
||||
this.codeValueReadPlatformService = codeValueReadPlatformService;
|
||||
this.collateralManagementReadPlatformService = collateralManagementReadPlatformService;
|
||||
this.clientCollateralManagementReadPlatformService = clientCollateralManagementReadPlatformService;
|
||||
this.currencyReadPlatformService = currencyReadPlatformService;
|
||||
this.apiJsonSerializerServiceForCurrency = apiJsonSerializerServiceForCurrency;
|
||||
}
|
||||
|
||||
+11
-8
@@ -47,15 +47,14 @@ import org.springframework.stereotype.Component;
|
||||
@Component
|
||||
public class CollectionSheetGenerateCommandFromApiJsonDeserializer {
|
||||
|
||||
public static final String COLLECTIONSHEET = "collectionsheet";
|
||||
/**
|
||||
* 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));
|
||||
|
||||
private static final Set<String> INDIVIDUAL_COLLECTIONSHEET_SUPPORTED_PARAMS = new HashSet<>(
|
||||
Arrays.asList(transactionDateParamName, localeParamName, dateFormatParamName, officeIdParamName, staffIdParamName));
|
||||
|
||||
private final FromJsonHelper fromApiJsonHelper;
|
||||
|
||||
@Autowired
|
||||
@@ -69,13 +68,15 @@ public class CollectionSheetGenerateCommandFromApiJsonDeserializer {
|
||||
throw new InvalidJsonException();
|
||||
}
|
||||
|
||||
final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType();
|
||||
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParameters);
|
||||
final Type typeOfMap = new TypeToken<Map<String, Object>>() {
|
||||
|
||||
}.getType();
|
||||
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, SUPPORTED_PARAMETERS);
|
||||
final JsonElement element = this.fromApiJsonHelper.parse(json);
|
||||
|
||||
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);
|
||||
baseDataValidator.reset().parameter(transactionDateParamName).value(transactionDateStr).notBlank();
|
||||
@@ -100,13 +101,15 @@ public class CollectionSheetGenerateCommandFromApiJsonDeserializer {
|
||||
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);
|
||||
final JsonElement element = this.fromApiJsonHelper.parse(json);
|
||||
|
||||
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);
|
||||
baseDataValidator.reset().parameter(transactionDateParamName).value(transactionDateStr).notBlank();
|
||||
|
||||
+68
-59
@@ -44,11 +44,20 @@ import org.springframework.stereotype.Component;
|
||||
@Component
|
||||
public class FloatingRateDataValidator {
|
||||
|
||||
private final Set<String> supportedParametersForFloatingRates = new HashSet<>(
|
||||
Arrays.asList("name", "isBaseLendingRate", "isActive", "ratePeriods"));
|
||||
private final Set<String> supportedParametersForFloatingRatePeriods = new HashSet<>(
|
||||
Arrays.asList("fromDate", "interestRate", "isDifferentialToBaseLendingRate", "locale", "dateFormat"));
|
||||
|
||||
public static final String NAME = "name";
|
||||
public static final String IS_BASE_LENDING_RATE = "isBaseLendingRate";
|
||||
public static final String IS_ACTIVE = "isActive";
|
||||
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 FloatingRateRepository floatingRateRepository;
|
||||
|
||||
@@ -59,37 +68,39 @@ public class FloatingRateDataValidator {
|
||||
}
|
||||
|
||||
public void validateForCreate(String json) {
|
||||
final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType();
|
||||
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParametersForFloatingRates);
|
||||
final Type typeOfMap = new TypeToken<Map<String, Object>>() {
|
||||
|
||||
}.getType();
|
||||
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, SUPPORTED_PARAMETERS_FOR_FLOATING_RATES);
|
||||
|
||||
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 String name = this.fromApiJsonHelper.extractStringNamed("name", element);
|
||||
baseDataValidator.reset().parameter("name").value(name).notBlank().notExceedingLengthOf(200);
|
||||
final String name = this.fromApiJsonHelper.extractStringNamed(NAME, element);
|
||||
baseDataValidator.reset().parameter(NAME).value(name).notBlank().notExceedingLengthOf(200);
|
||||
|
||||
Boolean isBaseLendingRate = null;
|
||||
if (this.fromApiJsonHelper.parameterExists("isBaseLendingRate", element)) {
|
||||
isBaseLendingRate = this.fromApiJsonHelper.extractBooleanNamed("isBaseLendingRate", element);
|
||||
if (this.fromApiJsonHelper.parameterExists(IS_BASE_LENDING_RATE, 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) {
|
||||
baseDataValidator.reset().parameter("isBaseLendingRate").trueOrFalseRequired(false);
|
||||
baseDataValidator.reset().parameter(IS_BASE_LENDING_RATE).trueOrFalseRequired(false);
|
||||
} else if (isBaseLendingRate) {
|
||||
FloatingRate baseLendingRate = this.floatingRateRepository.retrieveBaseLendingRate();
|
||||
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");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (this.fromApiJsonHelper.parameterExists("isActive", element)) {
|
||||
final Boolean isActive = this.fromApiJsonHelper.extractBooleanNamed("isActive", element);
|
||||
if (this.fromApiJsonHelper.parameterExists(IS_ACTIVE, element)) {
|
||||
final Boolean isActive = this.fromApiJsonHelper.extractBooleanNamed(IS_ACTIVE, element);
|
||||
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,
|
||||
boolean isBLRModifiedAsNonBLR) {
|
||||
if (this.fromApiJsonHelper.parameterExists("ratePeriods", element)) {
|
||||
final JsonArray ratePeriods = this.fromApiJsonHelper.extractJsonArrayNamed("ratePeriods", element);
|
||||
baseDataValidator.reset().parameter("ratePeriods").value(ratePeriods).notBlank().jsonArrayNotEmpty();
|
||||
if (this.fromApiJsonHelper.parameterExists(RATE_PERIODS, element)) {
|
||||
final JsonArray ratePeriods = this.fromApiJsonHelper.extractJsonArrayNamed(RATE_PERIODS, element);
|
||||
baseDataValidator.reset().parameter(RATE_PERIODS).value(ratePeriods).notBlank().jsonArrayNotEmpty();
|
||||
|
||||
if (ratePeriods != null) {
|
||||
List<LocalDate> fromDates = new ArrayList<>();
|
||||
@@ -113,38 +124,38 @@ public class FloatingRateDataValidator {
|
||||
final JsonElement ratePeriod = ratePeriods.get(i);
|
||||
|
||||
this.fromApiJsonHelper.checkForUnsupportedParameters(ratePeriod.getAsJsonObject(),
|
||||
this.supportedParametersForFloatingRatePeriods);
|
||||
SUPPORTED_PARAMETERS_FOR_FLOATING_RATE_PERIODS);
|
||||
|
||||
final LocalDate fromDate = this.fromApiJsonHelper.extractLocalDateNamed("fromDate", ratePeriod);
|
||||
baseDataValidator.reset().parameter("fromDate").parameterAtIndexArray("fromDate", i + 1).value(fromDate).notBlank()
|
||||
final LocalDate fromDate = this.fromApiJsonHelper.extractLocalDateNamed(FROM_DATE, ratePeriod);
|
||||
baseDataValidator.reset().parameter(FROM_DATE).parameterAtIndexArray(FROM_DATE, i + 1).value(fromDate).notBlank()
|
||||
.validateDateAfter(DateUtils.getBusinessLocalDate().plusDays(1));
|
||||
if (fromDate != null) {
|
||||
fromDates.add(fromDate);
|
||||
}
|
||||
|
||||
final BigDecimal interestRatePerPeriod = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed("interestRate",
|
||||
final BigDecimal interestRatePerPeriod = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed(INTEREST_RATE,
|
||||
ratePeriod);
|
||||
baseDataValidator.reset().parameter("interestRate").parameterAtIndexArray("interestRate", i + 1)
|
||||
baseDataValidator.reset().parameter(INTEREST_RATE).parameterAtIndexArray(INTEREST_RATE, i + 1)
|
||||
.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
|
||||
.extractBooleanNamed("isDifferentialToBaseLendingRate", ratePeriod);
|
||||
.extractBooleanNamed(IS_DIFFERENTIAL_TO_BASE_LENDING_RATE, ratePeriod);
|
||||
if (isDifferentialToBaseLendingRate == null) {
|
||||
baseDataValidator.reset().parameter("isDifferentialToBaseLendingRate")
|
||||
.parameterAtIndexArray("isDifferentialToBaseLendingRate", i + 1).trueOrFalseRequired(false);
|
||||
baseDataValidator.reset().parameter(IS_DIFFERENTIAL_TO_BASE_LENDING_RATE)
|
||||
.parameterAtIndexArray(IS_DIFFERENTIAL_TO_BASE_LENDING_RATE, i + 1).trueOrFalseRequired(false);
|
||||
} else if (isDifferentialToBaseLendingRate) {
|
||||
FloatingRate baseLendingRate = this.floatingRateRepository.retrieveBaseLendingRate();
|
||||
if (baseLendingRate == null || isBLRModifiedAsNonBLR) {
|
||||
baseDataValidator.reset().parameter("isDifferentialToBaseLendingRate")
|
||||
.parameterAtIndexArray("isDifferentialToBaseLendingRate", i + 1)
|
||||
baseDataValidator.reset().parameter(IS_DIFFERENTIAL_TO_BASE_LENDING_RATE)
|
||||
.parameterAtIndexArray(IS_DIFFERENTIAL_TO_BASE_LENDING_RATE, i + 1)
|
||||
.value(isDifferentialToBaseLendingRate)
|
||||
.failWithCode("no.baselending.rate.defined", "Base Lending Rate doesn't exists");
|
||||
}
|
||||
|
||||
if (isBaseLendingRate) {
|
||||
baseDataValidator.reset().parameter("isDifferentialToBaseLendingRate")
|
||||
.parameterAtIndexArray("isDifferentialToBaseLendingRate", i + 1)
|
||||
baseDataValidator.reset().parameter(IS_DIFFERENTIAL_TO_BASE_LENDING_RATE)
|
||||
.parameterAtIndexArray(IS_DIFFERENTIAL_TO_BASE_LENDING_RATE, i + 1)
|
||||
.value(isDifferentialToBaseLendingRate).failWithCode("cannot.be.true.for.baselendingrate",
|
||||
"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);
|
||||
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.");
|
||||
}
|
||||
|
||||
@@ -163,41 +174,41 @@ public class FloatingRateDataValidator {
|
||||
}
|
||||
|
||||
public void validateForUpdate(String json, FloatingRate floatingRateForUpdate) {
|
||||
final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType();
|
||||
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParametersForFloatingRates);
|
||||
final Type typeOfMap = new TypeToken<Map<String, Object>>() {
|
||||
|
||||
}.getType();
|
||||
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, SUPPORTED_PARAMETERS_FOR_FLOATING_RATES);
|
||||
|
||||
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);
|
||||
|
||||
if (this.fromApiJsonHelper.parameterExists("name", element)) {
|
||||
final String name = this.fromApiJsonHelper.extractStringNamed("name", element);
|
||||
baseDataValidator.reset().parameter("name").value(name).notBlank().notExceedingLengthOf(200);
|
||||
if (this.fromApiJsonHelper.parameterExists(NAME, element)) {
|
||||
final String name = this.fromApiJsonHelper.extractStringNamed(NAME, element);
|
||||
baseDataValidator.reset().parameter(NAME).value(name).notBlank().notExceedingLengthOf(200);
|
||||
}
|
||||
|
||||
Boolean isBaseLendingRate = null;
|
||||
Boolean isBLRModifiedAsNonBLR = false;
|
||||
FloatingRate baseLendingRate = this.floatingRateRepository.retrieveBaseLendingRate();
|
||||
if (this.fromApiJsonHelper.parameterExists("isBaseLendingRate", element)) {
|
||||
isBaseLendingRate = this.fromApiJsonHelper.extractBooleanNamed("isBaseLendingRate", element);
|
||||
if (this.fromApiJsonHelper.parameterExists(IS_BASE_LENDING_RATE, 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) {
|
||||
baseDataValidator.reset().parameter("isBaseLendingRate").trueOrFalseRequired(false);
|
||||
} else if (isBaseLendingRate) {
|
||||
if (baseLendingRate != null && !baseLendingRate.getId().equals(floatingRateForUpdate.getId())) {
|
||||
baseDataValidator.reset().parameter("isBaseLendingRate").value(isBaseLendingRate)
|
||||
.failWithCode("baselendingrate.duplicate", "Base Lending Rate already exists");
|
||||
}
|
||||
baseDataValidator.reset().parameter(IS_BASE_LENDING_RATE).trueOrFalseRequired(false);
|
||||
} else if (isBaseLendingRate && baseLendingRate != null && !baseLendingRate.getId().equals(floatingRateForUpdate.getId())) {
|
||||
baseDataValidator.reset().parameter(IS_BASE_LENDING_RATE).value(isBaseLendingRate).failWithCode("baselendingrate.duplicate",
|
||||
"Base Lending Rate already exists");
|
||||
}
|
||||
}
|
||||
|
||||
Boolean isActive = null;
|
||||
if (this.fromApiJsonHelper.parameterExists("isActive", element)) {
|
||||
isActive = this.fromApiJsonHelper.extractBooleanNamed("isActive", element);
|
||||
if (this.fromApiJsonHelper.parameterExists(IS_ACTIVE, element)) {
|
||||
isActive = this.fromApiJsonHelper.extractBooleanNamed(IS_ACTIVE, element);
|
||||
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();
|
||||
}
|
||||
|
||||
if (baseLendingRate != null && baseLendingRate.getId().equals(floatingRateForUpdate.getId())) {
|
||||
if (!isBaseLendingRate || !isActive) {
|
||||
isBLRModifiedAsNonBLR = true;
|
||||
}
|
||||
if (baseLendingRate != null && baseLendingRate.getId().equals(floatingRateForUpdate.getId()) && (!isBaseLendingRate || !isActive)) {
|
||||
isBLRModifiedAsNonBLR = true;
|
||||
}
|
||||
|
||||
if (isBLRModifiedAsNonBLR) {
|
||||
Collection<FloatingRate> floatingRates = this.floatingRateRepository.retrieveFloatingRatesLinkedToBLR();
|
||||
if (floatingRates != null && floatingRates.size() > 0) {
|
||||
baseDataValidator.reset().parameter("isBaseLendingRate").value(isBaseLendingRate).failWithCode(
|
||||
if (floatingRates != null && !floatingRates.isEmpty()) {
|
||||
baseDataValidator.reset().parameter(IS_BASE_LENDING_RATE).value(isBaseLendingRate).failWithCode(
|
||||
"cannot.be.marked.non.baselendingrate",
|
||||
"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}
|
||||
*/
|
||||
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 FundReadPlatformService readPlatformService;
|
||||
@@ -94,12 +94,12 @@ public class FundsApiResource {
|
||||
@ApiResponse(responseCode = "200", description = "OK", content = @Content(array = @ArraySchema(schema = @Schema(implementation = FundsApiResourceSwagger.GetFundsResponse.class)))) })
|
||||
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 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
|
||||
@@ -128,12 +128,12 @@ public class FundsApiResource {
|
||||
@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) {
|
||||
|
||||
this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions);
|
||||
this.context.authenticatedUser().validateHasReadPermission(RESOURCE_NAME_FOR_PERMISSIONS);
|
||||
|
||||
final FundData fund = this.readPlatformService.retrieveFund(fundId);
|
||||
|
||||
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
|
||||
|
||||
+18
-15
@@ -39,10 +39,13 @@ import org.springframework.stereotype.Component;
|
||||
@Component
|
||||
public final class FundCommandFromApiJsonDeserializer {
|
||||
|
||||
public static final String NAME = "name";
|
||||
public static final String EXTERNAL_ID = "externalId";
|
||||
/**
|
||||
* 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;
|
||||
|
||||
@@ -57,18 +60,18 @@ public final class FundCommandFromApiJsonDeserializer {
|
||||
}
|
||||
|
||||
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 DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("fund");
|
||||
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource(FUND);
|
||||
|
||||
final JsonElement element = this.fromApiJsonHelper.parse(json);
|
||||
|
||||
final String name = this.fromApiJsonHelper.extractStringNamed("name", element);
|
||||
baseDataValidator.reset().parameter("name").value(name).notBlank().notExceedingLengthOf(100);
|
||||
final String name = this.fromApiJsonHelper.extractStringNamed(NAME, element);
|
||||
baseDataValidator.reset().parameter(NAME).value(name).notBlank().notExceedingLengthOf(100);
|
||||
|
||||
final String externalId = this.fromApiJsonHelper.extractStringNamed("externalId", element);
|
||||
baseDataValidator.reset().parameter("externalId").value(externalId).notExceedingLengthOf(100);
|
||||
final String externalId = this.fromApiJsonHelper.extractStringNamed(EXTERNAL_ID, element);
|
||||
baseDataValidator.reset().parameter(EXTERNAL_ID).value(externalId).notExceedingLengthOf(100);
|
||||
|
||||
throwExceptionIfValidationWarningsExist(dataValidationErrors);
|
||||
}
|
||||
@@ -79,20 +82,20 @@ public final class FundCommandFromApiJsonDeserializer {
|
||||
}
|
||||
|
||||
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 DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("fund");
|
||||
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource(FUND);
|
||||
|
||||
final JsonElement element = this.fromApiJsonHelper.parse(json);
|
||||
if (this.fromApiJsonHelper.parameterExists("name", element)) {
|
||||
final String name = this.fromApiJsonHelper.extractStringNamed("name", element);
|
||||
baseDataValidator.reset().parameter("name").value(name).notBlank().notExceedingLengthOf(100);
|
||||
if (this.fromApiJsonHelper.parameterExists(NAME, element)) {
|
||||
final String name = this.fromApiJsonHelper.extractStringNamed(NAME, element);
|
||||
baseDataValidator.reset().parameter(NAME).value(name).notBlank().notExceedingLengthOf(100);
|
||||
}
|
||||
|
||||
if (this.fromApiJsonHelper.parameterExists("externalId", element)) {
|
||||
final String externalId = this.fromApiJsonHelper.extractStringNamed("externalId", element);
|
||||
baseDataValidator.reset().parameter("externalId").value(externalId).notExceedingLengthOf(100);
|
||||
if (this.fromApiJsonHelper.parameterExists(EXTERNAL_ID, element)) {
|
||||
final String externalId = this.fromApiJsonHelper.extractStringNamed(EXTERNAL_ID, element);
|
||||
baseDataValidator.reset().parameter(EXTERNAL_ID).value(externalId).notExceedingLengthOf(100);
|
||||
}
|
||||
|
||||
throwExceptionIfValidationWarningsExist(dataValidationErrors);
|
||||
|
||||
+36
-34
@@ -59,21 +59,23 @@ import org.springframework.util.CollectionUtils;
|
||||
@Service
|
||||
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 PlatformSecurityContext context;
|
||||
private final OfficeReadPlatformService officeReadPlatformService;
|
||||
private final StaffReadPlatformService staffReadPlatformService;
|
||||
private final CenterReadPlatformService centerReadPlatformService;
|
||||
private final CodeValueReadPlatformService codeValueReadPlatformService;
|
||||
|
||||
private final AllGroupTypesDataMapper allGroupTypesDataMapper = new AllGroupTypesDataMapper();
|
||||
private final PaginationHelper paginationHelper;
|
||||
private final DatabaseSpecificSQLGenerator sqlGenerator;
|
||||
private final PaginationParametersDataValidator paginationParametersDataValidator;
|
||||
private final ColumnValidator columnValidator;
|
||||
|
||||
private static final Set<String> supportedOrderByValues = new HashSet<>(Arrays.asList("id", "name", "officeId", "officeName"));
|
||||
|
||||
@Autowired
|
||||
public GroupReadPlatformServiceImpl(final PlatformSecurityContext context, final JdbcTemplate jdbcTemplate,
|
||||
final CenterReadPlatformService centerReadPlatformService, final OfficeReadPlatformService officeReadPlatformService,
|
||||
@@ -142,16 +144,16 @@ public class GroupReadPlatformServiceImpl implements GroupReadPlatformService {
|
||||
@Override
|
||||
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 String hierarchy = currentUser.getOffice().getHierarchy();
|
||||
final String hierarchySearchString = hierarchy + "%";
|
||||
|
||||
final StringBuilder sqlBuilder = new StringBuilder(200);
|
||||
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);
|
||||
sqlBuilder.append(" ").append(extraCriteria.getSQLTemplate());
|
||||
if (parameters.isOrderByRequested()) {
|
||||
@@ -168,7 +170,7 @@ public class GroupReadPlatformServiceImpl implements GroupReadPlatformService {
|
||||
}
|
||||
|
||||
return this.paginationHelper.fetchPage(this.jdbcTemplate, sqlBuilder.toString(), extraCriteria.getArguments(),
|
||||
this.allGroupTypesDataMapper);
|
||||
ALL_GROUP_TYPES_DATA_MAPPER);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -179,16 +181,14 @@ public class GroupReadPlatformServiceImpl implements GroupReadPlatformService {
|
||||
|
||||
final StringBuilder sqlBuilder = new StringBuilder(200);
|
||||
sqlBuilder.append("select ");
|
||||
sqlBuilder.append(this.allGroupTypesDataMapper.schema());
|
||||
final SQLBuilder extraCriteria = getGroupExtraCriteria(this.allGroupTypesDataMapper.schema(), searchParameters);
|
||||
sqlBuilder.append(ALL_GROUP_TYPES_DATA_MAPPER.schema());
|
||||
final SQLBuilder extraCriteria = getGroupExtraCriteria(searchParameters);
|
||||
extraCriteria.addCriteria("o.hierarchy like ", hierarchySearchString);
|
||||
|
||||
sqlBuilder.append(" ").append(extraCriteria.getSQLTemplate());
|
||||
|
||||
if (searchParameters != null) {
|
||||
if (searchParameters.isOrphansOnly()) {
|
||||
sqlBuilder.append(" and g.parent_id is NULL");
|
||||
}
|
||||
if (searchParameters != null && searchParameters.isOrphansOnly()) {
|
||||
sqlBuilder.append(" and g.parent_id is 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
|
||||
// clause is ambiguous
|
||||
// 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();
|
||||
if (searchCriteria == null) {
|
||||
@@ -243,8 +243,8 @@ public class GroupReadPlatformServiceImpl implements GroupReadPlatformService {
|
||||
final String hierarchy = currentUser.getOffice().getHierarchy();
|
||||
final String hierarchySearchString = hierarchy + "%";
|
||||
|
||||
final String sql = "select " + this.allGroupTypesDataMapper.schema() + " where g.id = ? and o.hierarchy like ?";
|
||||
return this.jdbcTemplate.queryForObject(sql, this.allGroupTypesDataMapper, new Object[] { groupId, hierarchySearchString }); // NOSONAR
|
||||
final String sql = "select " + ALL_GROUP_TYPES_DATA_MAPPER.schema() + " where g.id = ? and o.hierarchy like ?";
|
||||
return this.jdbcTemplate.queryForObject(sql, ALL_GROUP_TYPES_DATA_MAPPER, groupId, hierarchySearchString); // NOSONAR
|
||||
} catch (final EmptyResultDataAccessException e) {
|
||||
throw new GroupNotFoundException(groupId, e);
|
||||
}
|
||||
@@ -255,22 +255,7 @@ public class GroupReadPlatformServiceImpl implements GroupReadPlatformService {
|
||||
this.context.authenticatedUser();
|
||||
final GroupLookupDataMapper rm = new GroupLookupDataMapper();
|
||||
final String sql = "Select " + rm.schema() + " and g.office_id=?";
|
||||
return this.jdbcTemplate.query(sql, rm, new Object[] { 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);
|
||||
}
|
||||
return this.jdbcTemplate.query(sql, rm, officeId); // NOSONAR
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -280,4 +265,21 @@ public class GroupReadPlatformServiceImpl implements GroupReadPlatformService {
|
||||
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) {
|
||||
final Collection<Loan> groupLoans = this.loanRepositoryWrapper.findByGroupId(groupOrCenter.getId());
|
||||
for (final Loan loan : groupLoans) {
|
||||
final LoanStatusMapper loanStatus = new LoanStatusMapper(loan.status().getValue());
|
||||
final LoanStatusMapper loanStatus = new LoanStatusMapper(loan.getStatus().getValue());
|
||||
if (loanStatus.isOpen()) {
|
||||
final String errorMessage = groupOrCenter.getGroupLevel().getLevelName() + " cannot be closed because of non-closed loans.";
|
||||
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 JdbcTemplate jdbcTemplate;
|
||||
private final InterestRateChartMapper chartRowMapper = new InterestRateChartMapper();
|
||||
private static final InterestRateChartMapper CHART_ROW_MAPPER = new InterestRateChartMapper();
|
||||
private final InterestRateChartExtractor chartExtractor;
|
||||
private final InterestRateChartDropdownReadPlatformService chartDropdownReadPlatformService;
|
||||
private final InterestIncentiveDropdownReadPlatformService interestIncentiveDropdownReadPlatformService;
|
||||
private final CodeValueReadPlatformService codeValueReadPlatformService;
|
||||
private final DatabaseSpecificSQLGenerator sqlGenerator;
|
||||
|
||||
@Autowired
|
||||
public InterestRateChartReadPlatformServiceImpl(PlatformSecurityContext context, final JdbcTemplate jdbcTemplate,
|
||||
@@ -70,16 +69,15 @@ public class InterestRateChartReadPlatformServiceImpl implements InterestRateCha
|
||||
this.chartDropdownReadPlatformService = chartDropdownReadPlatformService;
|
||||
this.interestIncentiveDropdownReadPlatformService = interestIncentiveDropdownReadPlatformService;
|
||||
this.codeValueReadPlatformService = codeValueReadPlatformService;
|
||||
this.sqlGenerator = sqlGenerator;
|
||||
chartExtractor = new InterestRateChartExtractor(this.sqlGenerator);
|
||||
chartExtractor = new InterestRateChartExtractor(sqlGenerator);
|
||||
}
|
||||
|
||||
@Override
|
||||
public InterestRateChartData retrieveOne(Long chartId) {
|
||||
try {
|
||||
this.context.authenticatedUser();
|
||||
final String sql = "select " + this.chartRowMapper.schema() + " where irc.id = ?";
|
||||
return this.jdbcTemplate.queryForObject(sql, this.chartRowMapper, new Object[] { chartId }); // NOSONAR
|
||||
final String sql = "select " + CHART_ROW_MAPPER.schema() + " where irc.id = ?";
|
||||
return this.jdbcTemplate.queryForObject(sql, CHART_ROW_MAPPER, chartId); // NOSONAR
|
||||
} catch (final EmptyResultDataAccessException e) {
|
||||
throw new InterestRateChartNotFoundException(chartId, e);
|
||||
}
|
||||
|
||||
+13
-7
@@ -59,10 +59,16 @@ import org.springframework.stereotype.Component;
|
||||
@Tag(name = "Bulk Loans", description = "")
|
||||
public class BulkLoansApiResource {
|
||||
|
||||
private final Set<String> responseDataParameters = new HashSet<>(Arrays.asList("officeId", "fromLoanOfficerId", "assignmentDate",
|
||||
"officeOptions", "loanOfficerOptions", "accountSummaryCollection"));
|
||||
public static final String OFFICE_ID = "officeId";
|
||||
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 StaffReadPlatformService staffReadPlatformService;
|
||||
@@ -91,10 +97,10 @@ public class BulkLoansApiResource {
|
||||
@Path("template")
|
||||
@Consumes({ MediaType.APPLICATION_JSON })
|
||||
@Produces({ MediaType.APPLICATION_JSON })
|
||||
public String loanReassignmentTemplate(@QueryParam("officeId") final Long officeId,
|
||||
@QueryParam("fromLoanOfficerId") final Long loanOfficerId, @Context final UriInfo uriInfo) {
|
||||
public String loanReassignmentTemplate(@QueryParam(OFFICE_ID) final Long officeId,
|
||||
@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();
|
||||
|
||||
@@ -113,7 +119,7 @@ public class BulkLoansApiResource {
|
||||
LocalDate.now(DateUtils.getDateTimeZoneOfTenant()), offices, loanOfficers, staffAccountSummaryCollectionData);
|
||||
|
||||
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
|
||||
|
||||
+11
-2
@@ -23,14 +23,19 @@ public interface LoanApiConstants {
|
||||
String emiAmountParameterName = "fixedEmiAmount";
|
||||
String maxOutstandingBalanceParameterName = "maxOutstandingLoanBalance";
|
||||
String disbursementDataParameterName = "disbursementData";
|
||||
String disbursementDateParameterName = "expectedDisbursementDate";
|
||||
String expectedDisbursementDateParameterName = "expectedDisbursementDate";
|
||||
String disbursementPrincipalParameterName = "principal";
|
||||
String principalParameterName = "principal";
|
||||
String disbursementReversedParameterName = "reversed";
|
||||
String disbursementNetDisbursalAmountParameterName = "netDisbursalAmount";
|
||||
String updatedDisbursementDateParameterName = "updatedExpectedDisbursementDate";
|
||||
String updatedDisbursementPrincipalParameterName = "updatedPrincipal";
|
||||
String disbursementIdParameterName = "id";
|
||||
String loanChargeIdParameterName = "loanChargeId";
|
||||
String chargeIdParameterName = "chargeId";
|
||||
String amountParameterName = "amount";
|
||||
String chargeTimeTypeParameterName = "chargeTimeType";
|
||||
String chargeCalculationTypeParameterName = "chargeCalculationType";
|
||||
String principalDisbursedParameterName = "transactionAmount";
|
||||
String chargesParameterName = "charges";
|
||||
String loanIdTobeApproved = "loanId";
|
||||
@@ -73,8 +78,12 @@ public interface LoanApiConstants {
|
||||
String inArrearsToleranceParameterName = "inArrearsTolerance";
|
||||
String interestChargedFromDateParameterName = "interestChargedFromDate";
|
||||
String submittedOnDateParameterName = "submittedOnDate";
|
||||
String submittedOnNoteParameterName = "interestChargedFromDate";
|
||||
String submittedOnNoteParameterName = "submittedOnNote";
|
||||
String collateralParameterName = "collateral";
|
||||
String collateralsParameterName = "collaterals";
|
||||
String clientCollateralIdParameterName = "clientCollateralId";
|
||||
|
||||
String quantityParameterName = "quantity";
|
||||
String syncDisbursementWithMeetingParameterName = "syncDisbursementWithMeeting";
|
||||
String linkAccountIdParameterName = "linkAccountId";
|
||||
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")
|
||||
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",
|
||||
"amountPercentageAppliedTo", "currency", "amountWaived", "amountWrittenOff", "amountOutstanding", "amountOrPercentage",
|
||||
"amount", "amountPaid", "chargeOptions", "installmentChargeData"));
|
||||
|
||||
private final String resourceNameForPermissions = "LOAN";
|
||||
private static final String RESOURCE_NAME_FOR_PERMISSIONS = "LOAN";
|
||||
|
||||
private final PlatformSecurityContext context;
|
||||
private final ChargeReadPlatformService chargeReadPlatformService;
|
||||
@@ -112,12 +112,12 @@ public class LoanChargesApiResource {
|
||||
public String retrieveAllLoanCharges(@PathParam("loanId") @Parameter(description = "loanId") final Long loanId,
|
||||
@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 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
|
||||
@@ -131,14 +131,14 @@ public class LoanChargesApiResource {
|
||||
public String retrieveTemplate(@PathParam("loanId") @Parameter(description = "loanId") final Long loanId,
|
||||
@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,
|
||||
new ChargeTimeType[] { ChargeTimeType.OVERDUE_INSTALLMENT });
|
||||
final LoanChargeData loanChargeTemplate = LoanChargeData.template(chargeOptions);
|
||||
|
||||
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
|
||||
@@ -152,7 +152,7 @@ public class LoanChargesApiResource {
|
||||
public String retrieveLoanCharge(@PathParam("loanId") @Parameter(description = "loanId") final Long loanId,
|
||||
@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);
|
||||
|
||||
@@ -162,7 +162,7 @@ public class LoanChargesApiResource {
|
||||
final LoanChargeData loanChargeData = new LoanChargeData(loanCharge, installmentChargeData);
|
||||
|
||||
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
|
||||
|
||||
+4
-4
@@ -51,10 +51,10 @@ import org.springframework.stereotype.Component;
|
||||
@Tag(name = "Loan Disbursement Details", description = "")
|
||||
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"));
|
||||
|
||||
private final String resourceNameForPermissions = "LOAN";
|
||||
private static final String RESOURCE_NAME_FOR_PERMISSIONS = "LOAN";
|
||||
|
||||
private final DefaultToApiJsonSerializer<DisbursementData> toApiJsonSerializer;
|
||||
private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService;
|
||||
@@ -109,12 +109,12 @@ public class LoanDisbursementDetailApiResource {
|
||||
public String retriveDetail(@PathParam("loanId") final Long loanId, @PathParam("disbursementId") final Long disbursementId,
|
||||
@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 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.")
|
||||
public class LoanScheduleApiResource {
|
||||
|
||||
private final String resourceNameForPermissions = "LOAN";
|
||||
private static final String RESOURCE_NAME_FOR_PERMISSIONS = "LOAN";
|
||||
private final PlatformSecurityContext context;
|
||||
private final DefaultToApiJsonSerializer<LoanScheduleData> toApiJsonSerializer;
|
||||
private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService;
|
||||
@@ -94,12 +94,12 @@ public class LoanScheduleApiResource {
|
||||
|
||||
CommandWrapper commandRequest = null;
|
||||
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,
|
||||
apiRequestBodyAsJson);
|
||||
|
||||
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")) {
|
||||
commandRequest = new CommandWrapperBuilder().createScheduleExceptions(loanId).withJson(apiRequestBodyAsJson).build();
|
||||
} else if (is(commandParam, "deleteVariations")) {
|
||||
|
||||
+2
-2
@@ -38,7 +38,7 @@ public class DefaultLoanLifecycleStateMachine implements LoanLifecycleStateMachi
|
||||
@Override
|
||||
public LoanStatus dryTransition(final LoanEvent loanEvent, final Loan loan) {
|
||||
LoanStatus nextStatus = getNextState(loanEvent, loan);
|
||||
return nextStatus != null ? nextStatus : loan.status();
|
||||
return nextStatus != null ? nextStatus : loan.getStatus();
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -64,7 +64,7 @@ public class DefaultLoanLifecycleStateMachine implements LoanLifecycleStateMachi
|
||||
return submittedTransition();
|
||||
}
|
||||
|
||||
LoanStatus from = loan.status();
|
||||
LoanStatus from = loan.getStatus();
|
||||
LoanStatus newState = null;
|
||||
|
||||
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