replace 51013 Tabs with 4 Spaces in 3122 Java files (FINERACT-821)

rpl -eRxjava "\t" "    " .
This commit is contained in:
Michael Vorburger
2020-01-19 19:58:21 +01:00
committed by Michael Vorburger ⛑️
parent 68006ae8f2
commit b0196049f1
673 changed files with 23127 additions and 23127 deletions
@@ -291,11 +291,11 @@ public class AccountNumberPreferencesTest {
this.groupAccountNo = Utils.performServerGet(requestSpec, responseSpec, GROUP_URL, "accountNo");
if (isAccountPreferenceSetUp) {
String groupsPrefixName = (String) this.accountNumberPreferencesHelper.getAccountNumberPreference(
String groupsPrefixName = (String) this.accountNumberPreferencesHelper.getAccountNumberPreference(
this.groupsAccountNumberPreferenceId, "prefixType.value");
if (groupsPrefixName.equals(this.officeName)) {
final String groupOfficeName = Utils.performServerGet(requestSpec, responseSpec, GROUP_URL, "officeName");
this.validateAccountNumberLengthAndStartsWithPrefix(this.groupAccountNo, groupOfficeName);
@@ -316,15 +316,15 @@ public class AccountNumberPreferencesTest {
Assert.assertTrue(center.getName().equals(name));
if (isAccountPreferenceSetUp) {
String centerPrefixName = (String) this.accountNumberPreferencesHelper.getAccountNumberPreference(
String centerPrefixName = (String) this.accountNumberPreferencesHelper.getAccountNumberPreference(
this.centerAccountNumberPreferenceId, "prefixType.value");
final String CENTER_URL = "/fineract-provider/api/v1/centers/" + this.centerId + "?" + Utils.TENANT_IDENTIFIER;
if (centerPrefixName.equals(this.officeName)) {
final String centerOfficeName = Utils.performServerGet(requestSpec, responseSpec, CENTER_URL, "officeName");
this.validateAccountNumberLengthAndStartsWithPrefix(center.getAccountNo(), centerOfficeName);
}
} else {
} else {
validateAccountNumberLengthAndStartsWithPrefix(center.getAccountNo(), null);
}
}
@@ -375,7 +375,7 @@ public class AccountNumberPreferencesTest {
private void validateAccountNumberLengthAndStartsWithPrefix(final String accountNumber, String prefix) {
if (prefix != null) {
prefix = prefix.substring(0, Math.min(prefix.length(), 10));
prefix = prefix.substring(0, Math.min(prefix.length(), 10));
Assert.assertEquals(accountNumber.length(), prefix.length() + 9);
Assert.assertTrue(accountNumber.startsWith(prefix));
} else {
@@ -81,8 +81,8 @@ public class ClientTest {
@Test
public void testClientAsPersonStatus() {
this.clientHelper = new ClientHelper(this.requestSpec, this.responseSpec);
this.clientHelper = new ClientHelper(this.requestSpec, this.responseSpec);
final Integer clientId = ClientHelper.createClientAsPerson(this.requestSpec, this.responseSpec);
Assert.assertNotNull(clientId);
@@ -114,8 +114,8 @@ public class ClientTest {
@Test
public void testClientAsEntityStatus() {
this.clientHelper = new ClientHelper(this.requestSpec, this.responseSpec);
this.clientHelper = new ClientHelper(this.requestSpec, this.responseSpec);
final Integer clientId = ClientHelper.createClientAsEntity(this.requestSpec, this.responseSpec);
Assert.assertNotNull(clientId);
@@ -42,301 +42,301 @@ import static org.junit.Assert.assertEquals;
@SuppressWarnings({ "unused" })
public class ClientUndoRejectAndWithdrawalIntegrationTest {
private static final String CREATE_CLIENT_URL = "/fineract-provider/api/v1/clients?" + Utils.TENANT_IDENTIFIER;
public static final String DATE_FORMAT = "dd MMMM yyyy";
private final String submittedOnDate = "submittedOnDate";
private final String officeId = "officeId";
private ResponseSpecification responseSpec;
private RequestSpecification requestSpec;
private ClientHelper clientHelper;
@Before
public void setup() {
Utils.initializeRESTAssured();
this.requestSpec = new RequestSpecBuilder().setContentType(ContentType.JSON).build();
this.requestSpec.header("Authorization",
"Basic " + Utils.loginIntoServerAndGetBase64EncodedAuthenticationKey());
this.responseSpec = new ResponseSpecBuilder().expectStatusCode(200).build();
private static final String CREATE_CLIENT_URL = "/fineract-provider/api/v1/clients?" + Utils.TENANT_IDENTIFIER;
public static final String DATE_FORMAT = "dd MMMM yyyy";
private final String submittedOnDate = "submittedOnDate";
private final String officeId = "officeId";
private ResponseSpecification responseSpec;
private RequestSpecification requestSpec;
private ClientHelper clientHelper;
@Before
public void setup() {
Utils.initializeRESTAssured();
this.requestSpec = new RequestSpecBuilder().setContentType(ContentType.JSON).build();
this.requestSpec.header("Authorization",
"Basic " + Utils.loginIntoServerAndGetBase64EncodedAuthenticationKey());
this.responseSpec = new ResponseSpecBuilder().expectStatusCode(200).build();
this.clientHelper = new ClientHelper(this.requestSpec, this.responseSpec);
}
this.clientHelper = new ClientHelper(this.requestSpec, this.responseSpec);
}
@Test
public void clientUndoRejectIntegrationTest() {
// CREATE CLIENT
this.clientHelper = new ClientHelper(this.requestSpec, this.responseSpec);
final Integer clientId = ClientHelper.createClientPending(this.requestSpec, this.responseSpec);
Assert.assertNotNull(clientId);
// GET CLIENT STATUS
HashMap<String, Object> status = ClientHelper.getClientStatus(requestSpec, responseSpec,
String.valueOf(clientId));
ClientStatusChecker.verifyClientPending(status);
status = this.clientHelper.rejectClient(clientId);
ClientStatusChecker.verifyClientRejected(status);
status = this.clientHelper.undoReject(clientId);
ClientStatusChecker.verifyClientPending(status);
}
@Test
public void testClientUndoRejectWithDateBeforeRejectDate() {
final ResponseSpecification errorResponse = new ResponseSpecBuilder().expectStatusCode(403).build();
final ClientHelper validationErrorHelper = new ClientHelper(this.requestSpec, errorResponse);
@Test
public void clientUndoRejectIntegrationTest() {
// CREATE CLIENT
this.clientHelper = new ClientHelper(this.requestSpec, this.responseSpec);
final Integer clientId = ClientHelper.createClientPending(this.requestSpec, this.responseSpec);
Assert.assertNotNull(clientId);
// GET CLIENT STATUS
HashMap<String, Object> status = ClientHelper.getClientStatus(requestSpec, responseSpec,
String.valueOf(clientId));
ClientStatusChecker.verifyClientPending(status);
status = this.clientHelper.rejectClient(clientId);
ClientStatusChecker.verifyClientRejected(status);
status = this.clientHelper.undoReject(clientId);
ClientStatusChecker.verifyClientPending(status);
}
@Test
public void testClientUndoRejectWithDateBeforeRejectDate() {
final ResponseSpecification errorResponse = new ResponseSpecBuilder().expectStatusCode(403).build();
final ClientHelper validationErrorHelper = new ClientHelper(this.requestSpec, errorResponse);
// CREATE CLIENT
this.clientHelper = new ClientHelper(this.requestSpec, this.responseSpec);
final Integer clientId = ClientHelper.createClientPending(this.requestSpec, this.responseSpec);
Assert.assertNotNull(clientId);
// CREATE CLIENT
this.clientHelper = new ClientHelper(this.requestSpec, this.responseSpec);
final Integer clientId = ClientHelper.createClientPending(this.requestSpec, this.responseSpec);
Assert.assertNotNull(clientId);
// GET CLIENT STATUS
HashMap<String, Object> status = ClientHelper.getClientStatus(requestSpec, responseSpec,
String.valueOf(clientId));
// GET CLIENT STATUS
HashMap<String, Object> status = ClientHelper.getClientStatus(requestSpec, responseSpec,
String.valueOf(clientId));
ClientStatusChecker.verifyClientPending(status);
ClientStatusChecker.verifyClientPending(status);
status = this.clientHelper.rejectClient(clientId);
ClientStatusChecker.verifyClientRejected(status);
status = this.clientHelper.rejectClient(clientId);
ClientStatusChecker.verifyClientRejected(status);
ArrayList<HashMap> clientErrorData = (ArrayList<HashMap>) validationErrorHelper.undoRejectedclient(clientId,
CommonConstants.RESPONSE_ERROR, ClientHelper.CREATED_DATE);
assertEquals("error.msg.client.reopened.date.cannot.before.client.rejected.date",
((HashMap<String, Object>) clientErrorData.get(0)).get(CommonConstants.RESPONSE_ERROR_MESSAGE_CODE));
ArrayList<HashMap> clientErrorData = (ArrayList<HashMap>) validationErrorHelper.undoRejectedclient(clientId,
CommonConstants.RESPONSE_ERROR, ClientHelper.CREATED_DATE);
assertEquals("error.msg.client.reopened.date.cannot.before.client.rejected.date",
((HashMap<String, Object>) clientErrorData.get(0)).get(CommonConstants.RESPONSE_ERROR_MESSAGE_CODE));
status = this.clientHelper.undoReject(clientId);
ClientStatusChecker.verifyClientPending(status);
}
status = this.clientHelper.undoReject(clientId);
ClientStatusChecker.verifyClientPending(status);
}
@SuppressWarnings({ "unchecked", "rawtypes" })
@Test
public void testClientUndoRejectWithoutReject() {
final ResponseSpecification errorResponse = new ResponseSpecBuilder().expectStatusCode(403).build();
final ClientHelper validationErrorHelper = new ClientHelper(this.requestSpec, errorResponse);
@SuppressWarnings({ "unchecked", "rawtypes" })
@Test
public void testClientUndoRejectWithoutReject() {
final ResponseSpecification errorResponse = new ResponseSpecBuilder().expectStatusCode(403).build();
final ClientHelper validationErrorHelper = new ClientHelper(this.requestSpec, errorResponse);
// CREATE CLIENT
this.clientHelper = new ClientHelper(this.requestSpec, this.responseSpec);
final Integer clientId = ClientHelper.createClientPending(this.requestSpec, this.responseSpec);
Assert.assertNotNull(clientId);
// CREATE CLIENT
this.clientHelper = new ClientHelper(this.requestSpec, this.responseSpec);
final Integer clientId = ClientHelper.createClientPending(this.requestSpec, this.responseSpec);
Assert.assertNotNull(clientId);
// GET CLIENT STATUS
HashMap<String, Object> status = ClientHelper.getClientStatus(requestSpec, responseSpec,
String.valueOf(clientId));
ClientStatusChecker.verifyClientPending(status);
// GET CLIENT STATUS
HashMap<String, Object> status = ClientHelper.getClientStatus(requestSpec, responseSpec,
String.valueOf(clientId));
ClientStatusChecker.verifyClientPending(status);
DateFormat dateFormat = new SimpleDateFormat("dd MMMM yyyy", Locale.US);
Calendar todaysDate = Calendar.getInstance();
final String undoRejectDate = dateFormat.format(todaysDate.getTime());
DateFormat dateFormat = new SimpleDateFormat("dd MMMM yyyy", Locale.US);
Calendar todaysDate = Calendar.getInstance();
final String undoRejectDate = dateFormat.format(todaysDate.getTime());
ArrayList<HashMap> clientErrorData = (ArrayList<HashMap>) validationErrorHelper.undoRejectedclient(clientId,
CommonConstants.RESPONSE_ERROR, undoRejectDate);
assertEquals("error.msg.client.undorejection.on.nonrejected.account",
((HashMap<String, Object>) clientErrorData.get(0)).get(CommonConstants.RESPONSE_ERROR_MESSAGE_CODE));
ArrayList<HashMap> clientErrorData = (ArrayList<HashMap>) validationErrorHelper.undoRejectedclient(clientId,
CommonConstants.RESPONSE_ERROR, undoRejectDate);
assertEquals("error.msg.client.undorejection.on.nonrejected.account",
((HashMap<String, Object>) clientErrorData.get(0)).get(CommonConstants.RESPONSE_ERROR_MESSAGE_CODE));
status = this.clientHelper.getClientStatus(requestSpec, responseSpec, String.valueOf(clientId));
ClientStatusChecker.verifyClientPending(status);
status = this.clientHelper.getClientStatus(requestSpec, responseSpec, String.valueOf(clientId));
ClientStatusChecker.verifyClientPending(status);
}
}
@Test
public void testClientUndoRejectWithFutureDate() {
@Test
public void testClientUndoRejectWithFutureDate() {
final ResponseSpecification errorResponse = new ResponseSpecBuilder().expectStatusCode(400).build();
final ClientHelper validationErrorHelper = new ClientHelper(this.requestSpec, errorResponse);
final ResponseSpecification errorResponse = new ResponseSpecBuilder().expectStatusCode(400).build();
final ClientHelper validationErrorHelper = new ClientHelper(this.requestSpec, errorResponse);
// CREATE CLIENT
this.clientHelper = new ClientHelper(this.requestSpec, this.responseSpec);
final Integer clientId = ClientHelper.createClientPending(this.requestSpec, this.responseSpec);
Assert.assertNotNull(clientId);
// CREATE CLIENT
this.clientHelper = new ClientHelper(this.requestSpec, this.responseSpec);
final Integer clientId = ClientHelper.createClientPending(this.requestSpec, this.responseSpec);
Assert.assertNotNull(clientId);
// GET CLIENT STATUS
HashMap<String, Object> status = ClientHelper.getClientStatus(requestSpec, responseSpec,
String.valueOf(clientId));
// GET CLIENT STATUS
HashMap<String, Object> status = ClientHelper.getClientStatus(requestSpec, responseSpec,
String.valueOf(clientId));
ClientStatusChecker.verifyClientPending(status);
ClientStatusChecker.verifyClientPending(status);
status = this.clientHelper.rejectClient(clientId);
ClientStatusChecker.verifyClientRejected(status);
DateFormat dateFormat = new SimpleDateFormat("dd MMMM yyyy", Locale.US);
Calendar todaysDate = Calendar.getInstance();
todaysDate.add(Calendar.DATE, 1);
final String undoRejectDate = dateFormat.format(todaysDate.getTime());
ArrayList<HashMap> clientErrorData = (ArrayList<HashMap>) validationErrorHelper.undoWithdrawclient(clientId,
CommonConstants.RESPONSE_ERROR, undoRejectDate);
assertEquals("validation.msg.client.reopenedDate.is.greater.than.date",
((HashMap<String, Object>) clientErrorData.get(0)).get(CommonConstants.RESPONSE_ERROR_MESSAGE_CODE));
status = this.clientHelper.rejectClient(clientId);
ClientStatusChecker.verifyClientRejected(status);
DateFormat dateFormat = new SimpleDateFormat("dd MMMM yyyy", Locale.US);
Calendar todaysDate = Calendar.getInstance();
todaysDate.add(Calendar.DATE, 1);
final String undoRejectDate = dateFormat.format(todaysDate.getTime());
ArrayList<HashMap> clientErrorData = (ArrayList<HashMap>) validationErrorHelper.undoWithdrawclient(clientId,
CommonConstants.RESPONSE_ERROR, undoRejectDate);
assertEquals("validation.msg.client.reopenedDate.is.greater.than.date",
((HashMap<String, Object>) clientErrorData.get(0)).get(CommonConstants.RESPONSE_ERROR_MESSAGE_CODE));
status = this.clientHelper.undoReject(clientId);
ClientStatusChecker.verifyClientPending(status);
status = this.clientHelper.undoReject(clientId);
ClientStatusChecker.verifyClientPending(status);
}
}
@Test
public void clientUndoWithDrawnIntegrationTest() {
@Test
public void clientUndoWithDrawnIntegrationTest() {
// CREATE CLIENT
this.clientHelper = new ClientHelper(this.requestSpec, this.responseSpec);
final Integer clientId = ClientHelper.createClientPending(this.requestSpec, this.responseSpec);
Assert.assertNotNull(clientId);
// CREATE CLIENT
this.clientHelper = new ClientHelper(this.requestSpec, this.responseSpec);
final Integer clientId = ClientHelper.createClientPending(this.requestSpec, this.responseSpec);
Assert.assertNotNull(clientId);
// GET CLIENT STATUS
HashMap<String, Object> status = ClientHelper.getClientStatus(requestSpec, responseSpec,
String.valueOf(clientId));
// GET CLIENT STATUS
HashMap<String, Object> status = ClientHelper.getClientStatus(requestSpec, responseSpec,
String.valueOf(clientId));
ClientStatusChecker.verifyClientPending(status);
ClientStatusChecker.verifyClientPending(status);
status = this.clientHelper.withdrawClient(clientId);
ClientStatusChecker.verifyClientWithdrawn(status);
status = this.clientHelper.withdrawClient(clientId);
ClientStatusChecker.verifyClientWithdrawn(status);
status = this.clientHelper.undoWithdrawn(clientId);
ClientStatusChecker.verifyClientPending(status);
status = this.clientHelper.undoWithdrawn(clientId);
ClientStatusChecker.verifyClientPending(status);
}
}
@Test
public void testClientUndoWithDrawnWithDateBeforeWithdrawal() {
@Test
public void testClientUndoWithDrawnWithDateBeforeWithdrawal() {
final ResponseSpecification errorResponse = new ResponseSpecBuilder().expectStatusCode(403).build();
final ClientHelper validationErrorHelper = new ClientHelper(this.requestSpec, errorResponse);
final ResponseSpecification errorResponse = new ResponseSpecBuilder().expectStatusCode(403).build();
final ClientHelper validationErrorHelper = new ClientHelper(this.requestSpec, errorResponse);
// CREATE CLIENT
this.clientHelper = new ClientHelper(this.requestSpec, this.responseSpec);
final Integer clientId = ClientHelper.createClientPending(this.requestSpec, this.responseSpec);
Assert.assertNotNull(clientId);
// GET CLIENT STATUS
HashMap<String, Object> status = ClientHelper.getClientStatus(requestSpec, responseSpec,
String.valueOf(clientId));
ClientStatusChecker.verifyClientPending(status);
status = this.clientHelper.withdrawClient(clientId);
ClientStatusChecker.verifyClientWithdrawn(status);
ArrayList<HashMap> clientErrorData = (ArrayList<HashMap>) validationErrorHelper.undoWithdrawclient(clientId,
CommonConstants.RESPONSE_ERROR, ClientHelper.CREATED_DATE);
assertEquals("error.msg.client.reopened.date.cannot.before.client.withdrawal.date",
((HashMap<String, Object>) clientErrorData.get(0)).get(CommonConstants.RESPONSE_ERROR_MESSAGE_CODE));
status = this.clientHelper.undoWithdrawn(clientId);
ClientStatusChecker.verifyClientPending(status);
}
@SuppressWarnings({ "unchecked", "rawtypes" })
@Test
public void testClientUndoWithDrawnWithoutWithdrawal() {
final ResponseSpecification errorResponse = new ResponseSpecBuilder().expectStatusCode(403).build();
final ClientHelper validationErrorHelper = new ClientHelper(this.requestSpec, errorResponse);
// CREATE CLIENT
this.clientHelper = new ClientHelper(this.requestSpec, this.responseSpec);
final Integer clientId = ClientHelper.createClientPending(this.requestSpec, this.responseSpec);
Assert.assertNotNull(clientId);
// GET CLIENT STATUS
HashMap<String, Object> status = ClientHelper.getClientStatus(requestSpec, responseSpec,
String.valueOf(clientId));
DateFormat dateFormat = new SimpleDateFormat("dd MMMM yyyy", Locale.US);
Calendar todaysDate = Calendar.getInstance();
final String undoWithdrawDate = dateFormat.format(todaysDate.getTime());
ArrayList<HashMap> clientErrorData = (ArrayList<HashMap>) validationErrorHelper.undoWithdrawclient(clientId,
CommonConstants.RESPONSE_ERROR, undoWithdrawDate);
assertEquals("error.msg.client.undoWithdrawal.on.nonwithdrawal.account",
((HashMap<String, Object>) clientErrorData.get(0)).get(CommonConstants.RESPONSE_ERROR_MESSAGE_CODE));
status = this.clientHelper.getClientStatus(requestSpec, responseSpec, String.valueOf(clientId));
ClientStatusChecker.verifyClientPending(status);
}
@Test
public void testClientUndoWithDrawnWithFutureDate() {
final ResponseSpecification errorResponse = new ResponseSpecBuilder().expectStatusCode(400).build();
final ClientHelper validationErrorHelper = new ClientHelper(this.requestSpec, errorResponse);
// CREATE CLIENT
this.clientHelper = new ClientHelper(this.requestSpec, this.responseSpec);
final Integer clientId = ClientHelper.createClientPending(this.requestSpec, this.responseSpec);
Assert.assertNotNull(clientId);
// GET CLIENT STATUS
HashMap<String, Object> status = ClientHelper.getClientStatus(requestSpec, responseSpec,
String.valueOf(clientId));
ClientStatusChecker.verifyClientPending(status);
status = this.clientHelper.withdrawClient(clientId);
ClientStatusChecker.verifyClientWithdrawn(status);
DateFormat dateFormat = new SimpleDateFormat("dd MMMM yyyy", Locale.US);
Calendar todaysDate = Calendar.getInstance();
todaysDate.add(Calendar.DATE, 1);
final String undoWithdrawDate = dateFormat.format(todaysDate.getTime());
ArrayList<HashMap> clientErrorData = (ArrayList<HashMap>) validationErrorHelper.undoWithdrawclient(clientId,
CommonConstants.RESPONSE_ERROR, undoWithdrawDate);
assertEquals("validation.msg.client.reopenedDate.is.greater.than.date",
((HashMap<String, Object>) clientErrorData.get(0)).get(CommonConstants.RESPONSE_ERROR_MESSAGE_CODE));
status = this.clientHelper.undoWithdrawn(clientId);
ClientStatusChecker.verifyClientPending(status);
}
@SuppressWarnings({ "unchecked", "rawtypes" })
@Test
public void testValidateReopenedDate() {
final ResponseSpecification errorResponse = new ResponseSpecBuilder().expectStatusCode(400).build();
final ClientHelper validationErrorHelper = new ClientHelper(this.requestSpec, errorResponse);
// CREATE CLIENT
this.clientHelper = new ClientHelper(this.requestSpec, this.responseSpec);
final Integer clientId = ClientHelper.createClientPending(this.requestSpec, this.responseSpec);
Assert.assertNotNull(clientId);
// GET CLIENT STATUS
HashMap<String, Object> status = ClientHelper.getClientStatus(requestSpec, responseSpec,
String.valueOf(clientId));
ClientStatusChecker.verifyClientPending(status);
status = this.clientHelper.withdrawClient(clientId);
ClientStatusChecker.verifyClientWithdrawn(status);
status = this.clientHelper.undoWithdrawn(clientId);
ClientStatusChecker.verifyClientPending(status);
ArrayList<HashMap> clientErrorData = (ArrayList<HashMap>) validationErrorHelper.activateClient(clientId,
CommonConstants.RESPONSE_ERROR);
assertEquals("error.msg.clients.submittedOnDate.after.reopened.date",
((HashMap<String, Object>) clientErrorData.get(0)).get(CommonConstants.RESPONSE_ERROR_MESSAGE_CODE));
}
@Test
public void testReopenedDate() {
final ResponseSpecification errorResponse = new ResponseSpecBuilder().expectStatusCode(400).build();
//final ClientHelper validationErrorHelper = new ClientHelper(this.requestSpec, errorResponse);
// CREATE CLIENT
this.clientHelper = new ClientHelper(this.requestSpec, this.responseSpec);
final Integer clientId = ClientHelper.createClientPending(this.requestSpec, this.responseSpec);
Assert.assertNotNull(clientId);
// GET CLIENT STATUS
HashMap<String, Object> status = ClientHelper.getClientStatus(requestSpec, responseSpec,
String.valueOf(clientId));
ClientStatusChecker.verifyClientPending(status);
status = this.clientHelper.withdrawClient(clientId);
ClientStatusChecker.verifyClientWithdrawn(status);
status = this.clientHelper.undoWithdrawn(clientId);
ClientStatusChecker.verifyClientPending(status);
status = this.clientHelper.activateClientWithDiffDateOption(clientId, ClientHelper.CREATED_DATE_PLUS_TWO);
}
private static String randomIDGenerator(final String prefix, final int lenOfRandomSuffix) {
return Utils.randomStringGenerator(prefix, lenOfRandomSuffix, "ABCDEFGHIJKLMNOPQRSTUVWXYZ");
}
// CREATE CLIENT
this.clientHelper = new ClientHelper(this.requestSpec, this.responseSpec);
final Integer clientId = ClientHelper.createClientPending(this.requestSpec, this.responseSpec);
Assert.assertNotNull(clientId);
// GET CLIENT STATUS
HashMap<String, Object> status = ClientHelper.getClientStatus(requestSpec, responseSpec,
String.valueOf(clientId));
ClientStatusChecker.verifyClientPending(status);
status = this.clientHelper.withdrawClient(clientId);
ClientStatusChecker.verifyClientWithdrawn(status);
ArrayList<HashMap> clientErrorData = (ArrayList<HashMap>) validationErrorHelper.undoWithdrawclient(clientId,
CommonConstants.RESPONSE_ERROR, ClientHelper.CREATED_DATE);
assertEquals("error.msg.client.reopened.date.cannot.before.client.withdrawal.date",
((HashMap<String, Object>) clientErrorData.get(0)).get(CommonConstants.RESPONSE_ERROR_MESSAGE_CODE));
status = this.clientHelper.undoWithdrawn(clientId);
ClientStatusChecker.verifyClientPending(status);
}
@SuppressWarnings({ "unchecked", "rawtypes" })
@Test
public void testClientUndoWithDrawnWithoutWithdrawal() {
final ResponseSpecification errorResponse = new ResponseSpecBuilder().expectStatusCode(403).build();
final ClientHelper validationErrorHelper = new ClientHelper(this.requestSpec, errorResponse);
// CREATE CLIENT
this.clientHelper = new ClientHelper(this.requestSpec, this.responseSpec);
final Integer clientId = ClientHelper.createClientPending(this.requestSpec, this.responseSpec);
Assert.assertNotNull(clientId);
// GET CLIENT STATUS
HashMap<String, Object> status = ClientHelper.getClientStatus(requestSpec, responseSpec,
String.valueOf(clientId));
DateFormat dateFormat = new SimpleDateFormat("dd MMMM yyyy", Locale.US);
Calendar todaysDate = Calendar.getInstance();
final String undoWithdrawDate = dateFormat.format(todaysDate.getTime());
ArrayList<HashMap> clientErrorData = (ArrayList<HashMap>) validationErrorHelper.undoWithdrawclient(clientId,
CommonConstants.RESPONSE_ERROR, undoWithdrawDate);
assertEquals("error.msg.client.undoWithdrawal.on.nonwithdrawal.account",
((HashMap<String, Object>) clientErrorData.get(0)).get(CommonConstants.RESPONSE_ERROR_MESSAGE_CODE));
status = this.clientHelper.getClientStatus(requestSpec, responseSpec, String.valueOf(clientId));
ClientStatusChecker.verifyClientPending(status);
}
@Test
public void testClientUndoWithDrawnWithFutureDate() {
final ResponseSpecification errorResponse = new ResponseSpecBuilder().expectStatusCode(400).build();
final ClientHelper validationErrorHelper = new ClientHelper(this.requestSpec, errorResponse);
// CREATE CLIENT
this.clientHelper = new ClientHelper(this.requestSpec, this.responseSpec);
final Integer clientId = ClientHelper.createClientPending(this.requestSpec, this.responseSpec);
Assert.assertNotNull(clientId);
// GET CLIENT STATUS
HashMap<String, Object> status = ClientHelper.getClientStatus(requestSpec, responseSpec,
String.valueOf(clientId));
ClientStatusChecker.verifyClientPending(status);
status = this.clientHelper.withdrawClient(clientId);
ClientStatusChecker.verifyClientWithdrawn(status);
DateFormat dateFormat = new SimpleDateFormat("dd MMMM yyyy", Locale.US);
Calendar todaysDate = Calendar.getInstance();
todaysDate.add(Calendar.DATE, 1);
final String undoWithdrawDate = dateFormat.format(todaysDate.getTime());
ArrayList<HashMap> clientErrorData = (ArrayList<HashMap>) validationErrorHelper.undoWithdrawclient(clientId,
CommonConstants.RESPONSE_ERROR, undoWithdrawDate);
assertEquals("validation.msg.client.reopenedDate.is.greater.than.date",
((HashMap<String, Object>) clientErrorData.get(0)).get(CommonConstants.RESPONSE_ERROR_MESSAGE_CODE));
status = this.clientHelper.undoWithdrawn(clientId);
ClientStatusChecker.verifyClientPending(status);
}
@SuppressWarnings({ "unchecked", "rawtypes" })
@Test
public void testValidateReopenedDate() {
final ResponseSpecification errorResponse = new ResponseSpecBuilder().expectStatusCode(400).build();
final ClientHelper validationErrorHelper = new ClientHelper(this.requestSpec, errorResponse);
// CREATE CLIENT
this.clientHelper = new ClientHelper(this.requestSpec, this.responseSpec);
final Integer clientId = ClientHelper.createClientPending(this.requestSpec, this.responseSpec);
Assert.assertNotNull(clientId);
// GET CLIENT STATUS
HashMap<String, Object> status = ClientHelper.getClientStatus(requestSpec, responseSpec,
String.valueOf(clientId));
ClientStatusChecker.verifyClientPending(status);
status = this.clientHelper.withdrawClient(clientId);
ClientStatusChecker.verifyClientWithdrawn(status);
status = this.clientHelper.undoWithdrawn(clientId);
ClientStatusChecker.verifyClientPending(status);
ArrayList<HashMap> clientErrorData = (ArrayList<HashMap>) validationErrorHelper.activateClient(clientId,
CommonConstants.RESPONSE_ERROR);
assertEquals("error.msg.clients.submittedOnDate.after.reopened.date",
((HashMap<String, Object>) clientErrorData.get(0)).get(CommonConstants.RESPONSE_ERROR_MESSAGE_CODE));
}
@Test
public void testReopenedDate() {
final ResponseSpecification errorResponse = new ResponseSpecBuilder().expectStatusCode(400).build();
//final ClientHelper validationErrorHelper = new ClientHelper(this.requestSpec, errorResponse);
// CREATE CLIENT
this.clientHelper = new ClientHelper(this.requestSpec, this.responseSpec);
final Integer clientId = ClientHelper.createClientPending(this.requestSpec, this.responseSpec);
Assert.assertNotNull(clientId);
// GET CLIENT STATUS
HashMap<String, Object> status = ClientHelper.getClientStatus(requestSpec, responseSpec,
String.valueOf(clientId));
ClientStatusChecker.verifyClientPending(status);
status = this.clientHelper.withdrawClient(clientId);
ClientStatusChecker.verifyClientWithdrawn(status);
status = this.clientHelper.undoWithdrawn(clientId);
ClientStatusChecker.verifyClientPending(status);
status = this.clientHelper.activateClientWithDiffDateOption(clientId, ClientHelper.CREATED_DATE_PLUS_TWO);
}
private static String randomIDGenerator(final String prefix, final int lenOfRandomSuffix) {
return Utils.randomStringGenerator(prefix, lenOfRandomSuffix, "ABCDEFGHIJKLMNOPQRSTUVWXYZ");
}
}
@@ -146,83 +146,83 @@ public class GlobalConfigurationTest {
}
@Test
public void testGlobalConfigForcePasswordResetDays() {
public void testGlobalConfigForcePasswordResetDays() {
// Retrieving All Global Configuration details
final ArrayList<HashMap> globalConfig = this.globalConfigurationHelper
.getAllGlobalConfigurations(this.requestSpec, this.responseSpec);
Assert.assertNotNull(globalConfig);
// Retrieving All Global Configuration details
final ArrayList<HashMap> globalConfig = this.globalConfigurationHelper
.getAllGlobalConfigurations(this.requestSpec, this.responseSpec);
Assert.assertNotNull(globalConfig);
String configName = "force-password-reset-days";
String newValue = "0";
String newBooleanValue = "true";
String configName = "force-password-reset-days";
String newValue = "0";
String newBooleanValue = "true";
for (Integer configIndex = 0; configIndex < (globalConfig.size() - 1); configIndex++) {
if (globalConfig.get(configIndex).get("name").equals(configName)) {
Integer configId = (Integer) globalConfig.get(configIndex).get(
"id");
Assert.assertNotNull(configId);
for (Integer configIndex = 0; configIndex < (globalConfig.size() - 1); configIndex++) {
if (globalConfig.get(configIndex).get("name").equals(configName)) {
Integer configId = (Integer) globalConfig.get(configIndex).get(
"id");
Assert.assertNotNull(configId);
/*
* Update force-password-reset-days with value as 0 and Enable
* as true - failure case
*/
ArrayList error = (ArrayList) this.globalConfigurationHelper
.updatePasswordResetDaysForGlobalConfiguration(
this.requestSpec, this.httpStatusForidden,
configId, newValue, newBooleanValue,
CommonConstants.RESPONSE_ERROR);
HashMap hash = (HashMap) error.get(0);
/*
* Update force-password-reset-days with value as 0 and Enable
* as true - failure case
*/
ArrayList error = (ArrayList) this.globalConfigurationHelper
.updatePasswordResetDaysForGlobalConfiguration(
this.requestSpec, this.httpStatusForidden,
configId, newValue, newBooleanValue,
CommonConstants.RESPONSE_ERROR);
HashMap hash = (HashMap) error.get(0);
Assert.assertEquals(
"Force Password Reset days value must be greater than zero.",
"error.msg.password.reset.days.value.must.be.greater.than.zero",
hash.get(CommonConstants.RESPONSE_ERROR_MESSAGE_CODE));
Assert.assertEquals(
"Force Password Reset days value must be greater than zero.",
"error.msg.password.reset.days.value.must.be.greater.than.zero",
hash.get(CommonConstants.RESPONSE_ERROR_MESSAGE_CODE));
/*
* Update force-password-reset-days with value as 50 and Enable
* as true - success case
*/
final HashMap updateSuccess = (HashMap) this.globalConfigurationHelper
.updatePasswordResetDaysForGlobalConfiguration(
this.requestSpec, this.responseSpec, configId,
"50", newBooleanValue, "changes");
Assert.assertNotNull(updateSuccess);
/*
* Update force-password-reset-days with value as 50 and Enable
* as true - success case
*/
final HashMap updateSuccess = (HashMap) this.globalConfigurationHelper
.updatePasswordResetDaysForGlobalConfiguration(
this.requestSpec, this.responseSpec, configId,
"50", newBooleanValue, "changes");
Assert.assertNotNull(updateSuccess);
/* Update with value as 0 and Enable as false - success case */
final HashMap updateSuccess1 = (HashMap) this.globalConfigurationHelper
.updatePasswordResetDaysForGlobalConfiguration(
this.requestSpec, this.responseSpec, configId,
newValue, "false", "changes");
Assert.assertNotNull(updateSuccess1);
/* Update with value as 0 and Enable as false - success case */
final HashMap updateSuccess1 = (HashMap) this.globalConfigurationHelper
.updatePasswordResetDaysForGlobalConfiguration(
this.requestSpec, this.responseSpec, configId,
newValue, "false", "changes");
Assert.assertNotNull(updateSuccess1);
/* Update without sending value and Enable as true - failure case*/
ArrayList failure = (ArrayList) this.globalConfigurationHelper
.updatePasswordResetDaysForGlobalConfiguration(
this.requestSpec, this.httpStatusForidden, configId,
null, newBooleanValue, CommonConstants.RESPONSE_ERROR);
HashMap failureHash = (HashMap) failure.get(0);
Assert.assertEquals(
"Force Password Reset days value must be greater than zero.",
"error.msg.password.reset.days.value.must.be.greater.than.zero",
failureHash.get(CommonConstants.RESPONSE_ERROR_MESSAGE_CODE));
/* Update without sending value and Enable as true - failure case*/
ArrayList failure = (ArrayList) this.globalConfigurationHelper
.updatePasswordResetDaysForGlobalConfiguration(
this.requestSpec, this.httpStatusForidden, configId,
null, newBooleanValue, CommonConstants.RESPONSE_ERROR);
HashMap failureHash = (HashMap) failure.get(0);
Assert.assertEquals(
"Force Password Reset days value must be greater than zero.",
"error.msg.password.reset.days.value.must.be.greater.than.zero",
failureHash.get(CommonConstants.RESPONSE_ERROR_MESSAGE_CODE));
break;
}
}
/* Update other global configuration property */
String otherConfigName = "maker-checker";
for (Integer configIndex = 0; configIndex < (globalConfig.size() - 1); configIndex++) {
if (globalConfig.get(configIndex).get("name")
.equals(otherConfigName)) {
String configId = (globalConfig.get(configIndex).get("id"))
.toString();
Integer updateConfigId = this.globalConfigurationHelper
.updateValueForGlobalConfiguration(this.requestSpec,
this.responseSpec, configId, newValue);
Assert.assertNotNull(updateConfigId);
break;
}
}
}
break;
}
}
/* Update other global configuration property */
String otherConfigName = "maker-checker";
for (Integer configIndex = 0; configIndex < (globalConfig.size() - 1); configIndex++) {
if (globalConfig.get(configIndex).get("name")
.equals(otherConfigName)) {
String configId = (globalConfig.get(configIndex).get("id"))
.toString();
Integer updateConfigId = this.globalConfigurationHelper
.updateValueForGlobalConfiguration(this.requestSpec,
this.responseSpec, configId, newValue);
Assert.assertNotNull(updateConfigId);
break;
}
}
}
}
@@ -99,19 +99,19 @@ public class HookIntegrationTest {
@Test
public void createUpdateAndDeleteHook(){
final String payloadURL = "http://echo-webhook.herokuapp.com:80/Z7RXoCBdLSFMDrpn?";
final String updateURL = "http://localhost";
final String payloadURL = "http://echo-webhook.herokuapp.com:80/Z7RXoCBdLSFMDrpn?";
final String updateURL = "http://localhost";
Long hookId = this.hookHelper.createHook(payloadURL).longValue();
Assert.assertNotNull(hookId);
this.hookHelper.verifyHookCreatedOnServer(hookId);
System.out.println("---------------------SUCCESSFULLY CREATED AND VERIFIED HOOK-------------------------"+hookId);
this.hookHelper.updateHook(updateURL, hookId);
this.hookHelper.verifyUpdateHook(updateURL, hookId);
System.out.println("---------------------SUCCESSFULLY UPDATED AND VERIFIED HOOK-------------------------"+hookId);
this.hookHelper.deleteHook(hookId);
this.hookHelper.verifyDeleteHook(hookId);
System.out.println("---------------------SUCCESSFULLY DELETED AND VERIFIED HOOK-------------------------"+hookId);
System.out.println("---------------------SUCCESSFULLY CREATED AND VERIFIED HOOK-------------------------"+hookId);
this.hookHelper.updateHook(updateURL, hookId);
this.hookHelper.verifyUpdateHook(updateURL, hookId);
System.out.println("---------------------SUCCESSFULLY UPDATED AND VERIFIED HOOK-------------------------"+hookId);
this.hookHelper.deleteHook(hookId);
this.hookHelper.verifyDeleteHook(hookId);
System.out.println("---------------------SUCCESSFULLY DELETED AND VERIFIED HOOK-------------------------"+hookId);
}
}
@@ -95,13 +95,13 @@ public class LoanDisbursalDateValidationTest {
List<HashMap> disbursalError = (List<HashMap>) this.loanTransactionHelper.disburseLoan(disbursalDate, loanID, this.responseForbiddenError);
Assert.assertEquals("error.msg.actual.disbursement.date.does.not.match.with.expected.disbursal.date",
disbursalError.get(0).get(CommonConstants.RESPONSE_ERROR_MESSAGE_CODE));
disbursalError.get(0).get(CommonConstants.RESPONSE_ERROR_MESSAGE_CODE));
}
private Integer applyForLoanApplication(final Integer clientID, final Integer loanProductID, final String proposedAmount) {
final String loanApplication = new LoanApplicationTestBuilder()
.withPrincipal(proposedAmount).withLoanTermFrequency("5")
.withPrincipal(proposedAmount).withLoanTermFrequency("5")
.withLoanTermFrequencyAsMonths().withNumberOfRepayments("5")
.withRepaymentEveryAfter("1")
.withRepaymentFrequencyTypeAsMonths()
@@ -46,7 +46,7 @@ import com.jayway.restassured.specification.ResponseSpecification;
@SuppressWarnings("rawtypes")
public class LoanRepaymentRescheduleAtDisbursementTest {
private ResponseSpecification responseSpec;
private ResponseSpecification responseSpec;
private RequestSpecification requestSpec;
private LoanTransactionHelper loanTransactionHelper;
private LoanApplicationApprovalTest loanApplicationApprovalTest;
@@ -63,10 +63,10 @@ public class LoanRepaymentRescheduleAtDisbursementTest {
this.generalResponseSpec = new ResponseSpecBuilder().build();
}
@SuppressWarnings("unchecked")
@Test
@SuppressWarnings("unchecked")
@Test
public void testLoanRepaymentRescheduleAtDisbursement(){
final String approvalAmount = "10000";
final String approveDate = "01 March 2015";
final String expectedDisbursementDate = "01 March 2015";
@@ -74,7 +74,7 @@ public class LoanRepaymentRescheduleAtDisbursementTest {
final String adjustRepaymentDate = "16 March 2015";
// CREATE CLIENT
final Integer clientID = ClientHelper.createClient(this.requestSpec, this.responseSpec, "01 January 2014");
final Integer clientID = ClientHelper.createClient(this.requestSpec, this.responseSpec, "01 January 2014");
System.out.println("---------------------------------CLIENT CREATED WITH ID---------------------------------------------------"
+ clientID);
@@ -89,7 +89,7 @@ public class LoanRepaymentRescheduleAtDisbursementTest {
List<HashMap> createTranches = new ArrayList<>();
createTranches.add(this.loanApplicationApprovalTest.createTrancheDetail("01 March 2015", "5000"));
createTranches.add(this.loanApplicationApprovalTest.createTrancheDetail("01 May 2015", "5000"));
// APPROVE TRANCHES
List<HashMap> approveTranches = new ArrayList<>();
approveTranches.add(this.loanApplicationApprovalTest.createTrancheDetail("01 March 2015", "5000"));
@@ -132,15 +132,15 @@ public class LoanRepaymentRescheduleAtDisbursementTest {
verifyLoanRepaymentSchedule(firstInstallement, expectedvalues);
}
private void verifyLoanRepaymentSchedule(final HashMap firstInstallement, final Map<String, Object> expectedvalues) {
private void verifyLoanRepaymentSchedule(final HashMap firstInstallement, final Map<String, Object> expectedvalues) {
assertEquals(expectedvalues.get("dueDate"), firstInstallement.get("dueDate"));
assertEquals(String.valueOf(expectedvalues.get("principalDue")), String.valueOf(firstInstallement.get("principalDue")));
assertEquals(String.valueOf(expectedvalues.get("interestDue")), String.valueOf(firstInstallement.get("interestDue")));
assertEquals(String.valueOf(expectedvalues.get("feeChargesDue")), String.valueOf(firstInstallement.get("feeChargesDue")));
assertEquals(String.valueOf(expectedvalues.get("penaltyChargesDue")), String.valueOf(firstInstallement.get("penaltyChargesDue")));
assertEquals(String.valueOf(expectedvalues.get("totalDueForPeriod")), String.valueOf(firstInstallement.get("totalDueForPeriod")));
assertEquals(expectedvalues.get("dueDate"), firstInstallement.get("dueDate"));
assertEquals(String.valueOf(expectedvalues.get("principalDue")), String.valueOf(firstInstallement.get("principalDue")));
assertEquals(String.valueOf(expectedvalues.get("interestDue")), String.valueOf(firstInstallement.get("interestDue")));
assertEquals(String.valueOf(expectedvalues.get("feeChargesDue")), String.valueOf(firstInstallement.get("feeChargesDue")));
assertEquals(String.valueOf(expectedvalues.get("penaltyChargesDue")), String.valueOf(firstInstallement.get("penaltyChargesDue")));
assertEquals(String.valueOf(expectedvalues.get("totalDueForPeriod")), String.valueOf(firstInstallement.get("totalDueForPeriod")));
}
@@ -237,8 +237,8 @@ public class LoanRepaymentRescheduleAtDisbursementTest {
}
private List getDateAsArray(Calendar date, int addvalue, int type) {
date.add(type, addvalue);
date.add(type, addvalue);
return new ArrayList<>(Arrays.asList(date.get(Calendar.YEAR), date.get(Calendar.MONTH) + 1,
date.get(Calendar.DAY_OF_MONTH)));
date.get(Calendar.DAY_OF_MONTH)));
}
}
@@ -44,8 +44,8 @@ import com.jayway.restassured.specification.ResponseSpecification;
**/
@SuppressWarnings({ "rawtypes" })
public class LoanRescheduleRequestTest {
private ResponseSpecification responseSpec;
private ResponseSpecification generalResponseSpec;
private ResponseSpecification responseSpec;
private ResponseSpecification generalResponseSpec;
private RequestSpecification requestSpec;
private LoanTransactionHelper loanTransactionHelper;
private LoanRescheduleRequestHelper loanRescheduleRequestHelper;
@@ -60,7 +60,7 @@ public class LoanRescheduleRequestTest {
@Before
public void initialize() {
Utils.initializeRESTAssured();
Utils.initializeRESTAssured();
this.requestSpec = new RequestSpecBuilder().setContentType(ContentType.JSON).build();
this.requestSpec.header("Authorization", "Basic " + Utils.loginIntoServerAndGetBase64EncodedAuthenticationKey());
this.responseSpec = new ResponseSpecBuilder().expectStatusCode(200).build();
@@ -77,17 +77,17 @@ public class LoanRescheduleRequestTest {
* Creates the client, loan product, and loan entities
**/
private void createRequiredEntities() {
this.createClientEntity();
this.createLoanProductEntity();
this.createLoanEntity();
this.createClientEntity();
this.createLoanProductEntity();
this.createLoanEntity();
}
/**
* create a new client
**/
private void createClientEntity() {
this.clientId = ClientHelper.createClient(this.requestSpec, this.responseSpec);
this.clientId = ClientHelper.createClient(this.requestSpec, this.responseSpec);
ClientHelper.verifyClientCreatedOnServer(this.requestSpec, this.responseSpec, this.clientId);
}
@@ -95,28 +95,28 @@ public class LoanRescheduleRequestTest {
* create a new loan product
**/
private void createLoanProductEntity() {
System.out.println("---------------------------------CREATING LOAN PRODUCT------------------------------------------");
final String loanProductJSON = new LoanProductTestBuilder()
.withPrincipal(loanPrincipalAmount)
.withNumberOfRepayments(numberOfRepayments)
.withinterestRatePerPeriod(interestRatePerPeriod)
.withInterestRateFrequencyTypeAsYear()
.build(null);
this.loanProductId = this.loanTransactionHelper.getLoanProductId(loanProductJSON);
System.out.println("Successfully created loan product (ID: " + this.loanProductId + ")");
System.out.println("---------------------------------CREATING LOAN PRODUCT------------------------------------------");
final String loanProductJSON = new LoanProductTestBuilder()
.withPrincipal(loanPrincipalAmount)
.withNumberOfRepayments(numberOfRepayments)
.withinterestRatePerPeriod(interestRatePerPeriod)
.withInterestRateFrequencyTypeAsYear()
.build(null);
this.loanProductId = this.loanTransactionHelper.getLoanProductId(loanProductJSON);
System.out.println("Successfully created loan product (ID: " + this.loanProductId + ")");
}
/**
* submit a new loan application, approve and disburse the loan
**/
private void createLoanEntity() {
System.out.println("---------------------------------NEW LOAN APPLICATION------------------------------------------");
final String loanApplicationJSON = new LoanApplicationTestBuilder()
.withPrincipal(loanPrincipalAmount)
.withLoanTermFrequency(numberOfRepayments)
System.out.println("---------------------------------NEW LOAN APPLICATION------------------------------------------");
final String loanApplicationJSON = new LoanApplicationTestBuilder()
.withPrincipal(loanPrincipalAmount)
.withLoanTermFrequency(numberOfRepayments)
.withLoanTermFrequencyAsMonths()
.withNumberOfRepayments(numberOfRepayments)
.withRepaymentEveryAfter("1")
@@ -129,91 +129,91 @@ public class LoanRescheduleRequestTest {
.withExpectedDisbursementDate(dateString)
.withPrincipalGrace("2")
.withInterestGrace("2")
.build(this.clientId.toString(), this.loanProductId.toString(), null);
this.loanId = this.loanTransactionHelper.getLoanId(loanApplicationJSON);
System.out.println("Sucessfully created loan (ID: " + this.loanId + ")");
this.approveLoanApplication();
this.disburseLoan();
.build(this.clientId.toString(), this.loanProductId.toString(), null);
this.loanId = this.loanTransactionHelper.getLoanId(loanApplicationJSON);
System.out.println("Sucessfully created loan (ID: " + this.loanId + ")");
this.approveLoanApplication();
this.disburseLoan();
}
/**
* approve the loan application
**/
private void approveLoanApplication() {
if(this.loanId != null) {
this.loanTransactionHelper.approveLoan(this.dateString, this.loanId);
System.out.println("Successfully approved loan (ID: " + this.loanId + ")");
}
if(this.loanId != null) {
this.loanTransactionHelper.approveLoan(this.dateString, this.loanId);
System.out.println("Successfully approved loan (ID: " + this.loanId + ")");
}
}
/**
* disburse the newly created loan
**/
private void disburseLoan() {
if(this.loanId != null) {
this.loanTransactionHelper.disburseLoan(this.dateString, this.loanId);
System.out.println("Successfully disbursed loan (ID: " + this.loanId + ")");
}
if(this.loanId != null) {
this.loanTransactionHelper.disburseLoan(this.dateString, this.loanId);
System.out.println("Successfully disbursed loan (ID: " + this.loanId + ")");
}
}
/**
* create new loan reschedule request
**/
private void createLoanRescheduleRequest() {
System.out.println("---------------------------------CREATING LOAN RESCHEDULE REQUEST------------------------------------------");
final String requestJSON = new LoanRescheduleRequestTestBuilder().build(this.loanId.toString());
this.loanRescheduleRequestId = this.loanRescheduleRequestHelper.createLoanRescheduleRequest(requestJSON);
this.loanRescheduleRequestHelper.verifyCreationOfLoanRescheduleRequest(this.loanRescheduleRequestId);
System.out.println("Successfully created loan reschedule request (ID: " + this.loanRescheduleRequestId + ")");
System.out.println("---------------------------------CREATING LOAN RESCHEDULE REQUEST------------------------------------------");
final String requestJSON = new LoanRescheduleRequestTestBuilder().build(this.loanId.toString());
this.loanRescheduleRequestId = this.loanRescheduleRequestHelper.createLoanRescheduleRequest(requestJSON);
this.loanRescheduleRequestHelper.verifyCreationOfLoanRescheduleRequest(this.loanRescheduleRequestId);
System.out.println("Successfully created loan reschedule request (ID: " + this.loanRescheduleRequestId + ")");
}
@Test
public void testCreateLoanRescheduleRequest() {
this.createLoanRescheduleRequest();
this.createLoanRescheduleRequest();
}
@Test
public void testRejectLoanRescheduleRequest() {
this.createLoanRescheduleRequest();
System.out.println("-----------------------------REJECTING LOAN RESCHEDULE REQUEST--------------------------");
final String requestJSON = new LoanRescheduleRequestTestBuilder().getRejectLoanRescheduleRequestJSON();
this.loanRescheduleRequestHelper.rejectLoanRescheduleRequest(this.loanRescheduleRequestId, requestJSON);
final HashMap response = (HashMap) this.loanRescheduleRequestHelper.getLoanRescheduleRequest(loanRescheduleRequestId, "statusEnum");
assertTrue((Boolean)response.get("rejected"));
System.out.println("Successfully rejected loan reschedule request (ID: " + this.loanRescheduleRequestId + ")");
this.createLoanRescheduleRequest();
System.out.println("-----------------------------REJECTING LOAN RESCHEDULE REQUEST--------------------------");
final String requestJSON = new LoanRescheduleRequestTestBuilder().getRejectLoanRescheduleRequestJSON();
this.loanRescheduleRequestHelper.rejectLoanRescheduleRequest(this.loanRescheduleRequestId, requestJSON);
final HashMap response = (HashMap) this.loanRescheduleRequestHelper.getLoanRescheduleRequest(loanRescheduleRequestId, "statusEnum");
assertTrue((Boolean)response.get("rejected"));
System.out.println("Successfully rejected loan reschedule request (ID: " + this.loanRescheduleRequestId + ")");
}
@Test
public void testApproveLoanRescheduleRequest() {
this.createLoanRescheduleRequest();
System.out.println("-----------------------------APPROVING LOAN RESCHEDULE REQUEST--------------------------");
final String requestJSON = new LoanRescheduleRequestTestBuilder().getApproveLoanRescheduleRequestJSON();
this.loanRescheduleRequestHelper.approveLoanRescheduleRequest(this.loanRescheduleRequestId, requestJSON);
final HashMap response = (HashMap) this.loanRescheduleRequestHelper.getLoanRescheduleRequest(loanRescheduleRequestId, "statusEnum");
assertTrue((Boolean)response.get("approved"));
final Integer numberOfRepayments = (Integer) this.loanTransactionHelper.getLoanDetail(requestSpec, generalResponseSpec, loanId, "numberOfRepayments");
final HashMap loanSummary = this.loanTransactionHelper.getLoanSummary(requestSpec, generalResponseSpec, loanId);
final Float totalExpectedRepayment = (Float) loanSummary.get("totalExpectedRepayment");
assertEquals("NUMBER OF REPAYMENTS SHOULD BE 16, NOT 12", "12", numberOfRepayments.toString());
assertEquals("TOTAL EXPECTED REPAYMENT MUST BE EQUAL TO 118000.0", "118000.0", totalExpectedRepayment.toString());
System.out.println("Successfully approved loan reschedule request (ID: " + this.loanRescheduleRequestId + ")");
this.createLoanRescheduleRequest();
System.out.println("-----------------------------APPROVING LOAN RESCHEDULE REQUEST--------------------------");
final String requestJSON = new LoanRescheduleRequestTestBuilder().getApproveLoanRescheduleRequestJSON();
this.loanRescheduleRequestHelper.approveLoanRescheduleRequest(this.loanRescheduleRequestId, requestJSON);
final HashMap response = (HashMap) this.loanRescheduleRequestHelper.getLoanRescheduleRequest(loanRescheduleRequestId, "statusEnum");
assertTrue((Boolean)response.get("approved"));
final Integer numberOfRepayments = (Integer) this.loanTransactionHelper.getLoanDetail(requestSpec, generalResponseSpec, loanId, "numberOfRepayments");
final HashMap loanSummary = this.loanTransactionHelper.getLoanSummary(requestSpec, generalResponseSpec, loanId);
final Float totalExpectedRepayment = (Float) loanSummary.get("totalExpectedRepayment");
assertEquals("NUMBER OF REPAYMENTS SHOULD BE 16, NOT 12", "12", numberOfRepayments.toString());
assertEquals("TOTAL EXPECTED REPAYMENT MUST BE EQUAL TO 118000.0", "118000.0", totalExpectedRepayment.toString());
System.out.println("Successfully approved loan reschedule request (ID: " + this.loanRescheduleRequestId + ")");
}
}
@@ -33,34 +33,34 @@ import com.jayway.restassured.specification.ResponseSpecification;
public class OfficeIntegrationTest {
private ResponseSpecification responseSpec;
private RequestSpecification requestSpec;
private ResponseSpecification responseSpec;
private RequestSpecification requestSpec;
@Before
public void setup() {
Utils.initializeRESTAssured();
this.requestSpec = new RequestSpecBuilder().setContentType(
ContentType.JSON).build();
this.requestSpec
.header("Authorization",
"Basic "
+ Utils.loginIntoServerAndGetBase64EncodedAuthenticationKey());
this.responseSpec = new ResponseSpecBuilder().expectStatusCode(200)
.build();
}
@Before
public void setup() {
Utils.initializeRESTAssured();
this.requestSpec = new RequestSpecBuilder().setContentType(
ContentType.JSON).build();
this.requestSpec
.header("Authorization",
"Basic "
+ Utils.loginIntoServerAndGetBase64EncodedAuthenticationKey());
this.responseSpec = new ResponseSpecBuilder().expectStatusCode(200)
.build();
}
@Test
public void testOfficeModification() {
OfficeHelper oh = new OfficeHelper(requestSpec, responseSpec);
int officeId = oh.createOffice("01 July 2007");
String name = Utils.randomNameGenerator("New_Office_", 4);
String date = "02 July 2007";
String[] dateArr = { "2007", "7", "2" };
@Test
public void testOfficeModification() {
OfficeHelper oh = new OfficeHelper(requestSpec, responseSpec);
int officeId = oh.createOffice("01 July 2007");
String name = Utils.randomNameGenerator("New_Office_", 4);
String date = "02 July 2007";
String[] dateArr = { "2007", "7", "2" };
oh.updateOffice(officeId, name, date);
OfficeDomain newOffice = oh.retrieveOfficeByID(officeId);
oh.updateOffice(officeId, name, date);
OfficeDomain newOffice = oh.retrieveOfficeByID(officeId);
Assert.assertTrue(name.equals(newOffice.getName()));
Assert.assertArrayEquals(dateArr, newOffice.getOpeningDate());
}
Assert.assertTrue(name.equals(newOffice.getName()));
Assert.assertArrayEquals(dateArr, newOffice.getOpeningDate());
}
}
@@ -142,14 +142,14 @@ public class SchedulerJobsTestResults {
Float chargeAmount = (Float) chargeData.get("amount");
final HashMap savingsDetails = this.savingsAccountHelper.getSavingsDetails(savingsId);
final HashMap annualFeeDetails = (HashMap) savingsDetails.get("annualFee");
ArrayList<Integer> annualFeeDueDateAsArrayList = (ArrayList<Integer>) annualFeeDetails.get("dueDate");
LocalDate nextDueDateForAnnualFee = LocalDate.of(annualFeeDueDateAsArrayList.get(0), annualFeeDueDateAsArrayList.get(1), annualFeeDueDateAsArrayList.get(2));
LocalDate todaysDate = LocalDate.now(ZoneId.of("Asia/Kolkata"));
final HashMap savingsDetails = this.savingsAccountHelper.getSavingsDetails(savingsId);
final HashMap annualFeeDetails = (HashMap) savingsDetails.get("annualFee");
ArrayList<Integer> annualFeeDueDateAsArrayList = (ArrayList<Integer>) annualFeeDetails.get("dueDate");
LocalDate nextDueDateForAnnualFee = LocalDate.of(annualFeeDueDateAsArrayList.get(0), annualFeeDueDateAsArrayList.get(1), annualFeeDueDateAsArrayList.get(2));
LocalDate todaysDate = LocalDate.now(ZoneId.of("Asia/Kolkata"));
Assert.assertTrue("Verifying that all due Annual Fees have been paid ",
nextDueDateForAnnualFee.isAfter(todaysDate));
Assert.assertTrue("Verifying that all due Annual Fees have been paid ",
nextDueDateForAnnualFee.isAfter(todaysDate));
}
@@ -47,130 +47,130 @@ import junit.framework.Assert;
@SuppressWarnings({ "static-access", "rawtypes", "unchecked", "deprecation" })
public class SkipRepaymentOnMonthFirstTest {
private ResponseSpecification responseSpec;
private RequestSpecification requestSpec;
private GlobalConfigurationHelper globalConfigurationHelper;
private LoanTransactionHelper loanTransactionHelper;
private CalendarHelper calendarHelper;
private ResponseSpecification responseSpec;
private RequestSpecification requestSpec;
private GlobalConfigurationHelper globalConfigurationHelper;
private LoanTransactionHelper loanTransactionHelper;
private CalendarHelper calendarHelper;
@Before
public void setup() {
Utils.initializeRESTAssured();
this.requestSpec = new RequestSpecBuilder().setContentType(ContentType.JSON).build();
this.requestSpec.header("Authorization",
"Basic " + Utils.loginIntoServerAndGetBase64EncodedAuthenticationKey());
this.responseSpec = new ResponseSpecBuilder().expectStatusCode(200).build();
}
@Before
public void setup() {
Utils.initializeRESTAssured();
this.requestSpec = new RequestSpecBuilder().setContentType(ContentType.JSON).build();
this.requestSpec.header("Authorization",
"Basic " + Utils.loginIntoServerAndGetBase64EncodedAuthenticationKey());
this.responseSpec = new ResponseSpecBuilder().expectStatusCode(200).build();
}
@After
public void tearDown() {
GlobalConfigurationHelper.resetAllDefaultGlobalConfigurations(this.requestSpec, this.responseSpec);
GlobalConfigurationHelper.verifyAllDefaultGlobalConfigurations(this.requestSpec, this.responseSpec);
}
@After
public void tearDown() {
GlobalConfigurationHelper.resetAllDefaultGlobalConfigurations(this.requestSpec, this.responseSpec);
GlobalConfigurationHelper.verifyAllDefaultGlobalConfigurations(this.requestSpec, this.responseSpec);
}
@Test
public void testSkippingRepaymentOnFirstDayOfMonth() {
this.globalConfigurationHelper = new GlobalConfigurationHelper(this.requestSpec, this.responseSpec);
@Test
public void testSkippingRepaymentOnFirstDayOfMonth() {
this.globalConfigurationHelper = new GlobalConfigurationHelper(this.requestSpec, this.responseSpec);
// Retrieving All Global Configuration details
final ArrayList<HashMap> globalConfig = this.globalConfigurationHelper
.getAllGlobalConfigurations(this.requestSpec, this.responseSpec);
Assert.assertNotNull(globalConfig);
// Retrieving All Global Configuration details
final ArrayList<HashMap> globalConfig = this.globalConfigurationHelper
.getAllGlobalConfigurations(this.requestSpec, this.responseSpec);
Assert.assertNotNull(globalConfig);
String configName = "skip-repayment-on-first-day-of-month";
boolean newBooleanValue = true;
String configName = "skip-repayment-on-first-day-of-month";
boolean newBooleanValue = true;
for (Integer configIndex = 0; configIndex < (globalConfig.size()); configIndex++) {
if (globalConfig.get(configIndex).get("name").equals(configName)) {
String configId = (globalConfig.get(configIndex).get("id")).toString();
Integer updateConfigId = this.globalConfigurationHelper.updateEnabledFlagForGlobalConfiguration(
this.requestSpec, this.responseSpec, configId.toString(), newBooleanValue);
Assert.assertNotNull(updateConfigId);
break;
}
}
for (Integer configIndex = 0; configIndex < (globalConfig.size()); configIndex++) {
if (globalConfig.get(configIndex).get("name").equals(configName)) {
String configId = (globalConfig.get(configIndex).get("id")).toString();
Integer updateConfigId = this.globalConfigurationHelper.updateEnabledFlagForGlobalConfiguration(
this.requestSpec, this.responseSpec, configId.toString(), newBooleanValue);
Assert.assertNotNull(updateConfigId);
break;
}
}
}
}
@Test
public void checkRepaymentSkipOnFirstDayOfMonth() {
this.loanTransactionHelper = new LoanTransactionHelper(this.requestSpec, this.responseSpec);
@Test
public void checkRepaymentSkipOnFirstDayOfMonth() {
this.loanTransactionHelper = new LoanTransactionHelper(this.requestSpec, this.responseSpec);
final Integer clientID = ClientHelper.createClient(this.requestSpec, this.responseSpec);
Integer groupID = GroupHelper.createGroup(this.requestSpec, this.responseSpec, true);
groupID = GroupHelper.associateClient(this.requestSpec, this.responseSpec, groupID.toString(),
clientID.toString());
final String startDate = "15 September 2011";
final String frequency = "3"; // Monthly
final String interval = "1"; //Every One Moth
Integer calendarID = calendarHelper.createMeetingForGroup(requestSpec, responseSpec, groupID, startDate, frequency,
interval, null);
System.out.println("caladerId --------------------" + calendarID);
final Integer loanProductID = createLoanProduct();
final Integer loanID = applyForLoanApplication(groupID, loanProductID, calendarID, clientID);
System.out.println("loanID----" + loanID);
final ArrayList<HashMap> loanSchedule = this.loanTransactionHelper.getLoanRepaymentSchedule(this.requestSpec,
this.responseSpec, loanID);
verifyLoanRepaymentSchedule(loanSchedule);
final Integer clientID = ClientHelper.createClient(this.requestSpec, this.responseSpec);
Integer groupID = GroupHelper.createGroup(this.requestSpec, this.responseSpec, true);
groupID = GroupHelper.associateClient(this.requestSpec, this.responseSpec, groupID.toString(),
clientID.toString());
final String startDate = "15 September 2011";
final String frequency = "3"; // Monthly
final String interval = "1"; //Every One Moth
Integer calendarID = calendarHelper.createMeetingForGroup(requestSpec, responseSpec, groupID, startDate, frequency,
interval, null);
System.out.println("caladerId --------------------" + calendarID);
final Integer loanProductID = createLoanProduct();
final Integer loanID = applyForLoanApplication(groupID, loanProductID, calendarID, clientID);
System.out.println("loanID----" + loanID);
final ArrayList<HashMap> loanSchedule = this.loanTransactionHelper.getLoanRepaymentSchedule(this.requestSpec,
this.responseSpec, loanID);
verifyLoanRepaymentSchedule(loanSchedule);
}
}
private Integer createLoanProduct() {
System.out.println(
"------------------------------CREATING NEW LOAN PRODUCT ---------------------------------------");
final String loanProductJSON = new LoanProductTestBuilder() //
.withPrincipal("12,000.00") //
.withNumberOfRepayments("4") //
.withRepaymentAfterEvery("1") //
.withRepaymentTypeAsMonth() //
.withinterestRatePerPeriod("1") //
.withInterestRateFrequencyTypeAsMonths() //
.withAmortizationTypeAsEqualInstallments() //
.withInterestTypeAsDecliningBalance() //
.build(null);
return this.loanTransactionHelper.getLoanProductId(loanProductJSON);
}
private Integer createLoanProduct() {
System.out.println(
"------------------------------CREATING NEW LOAN PRODUCT ---------------------------------------");
final String loanProductJSON = new LoanProductTestBuilder() //
.withPrincipal("12,000.00") //
.withNumberOfRepayments("4") //
.withRepaymentAfterEvery("1") //
.withRepaymentTypeAsMonth() //
.withinterestRatePerPeriod("1") //
.withInterestRateFrequencyTypeAsMonths() //
.withAmortizationTypeAsEqualInstallments() //
.withInterestTypeAsDecliningBalance() //
.build(null);
return this.loanTransactionHelper.getLoanProductId(loanProductJSON);
}
private Integer applyForLoanApplication(final Integer groupID, final Integer loanProductID, Integer calendarID,
Integer clientID) {
System.out.println(
"--------------------------------APPLYING FOR LOAN APPLICATION--------------------------------");
final String loanApplicationJSON = new LoanApplicationTestBuilder() //
.withPrincipal("12,000.00") //
.withLoanTermFrequency("4") //
.withLoanTermFrequencyAsMonths() //
.withNumberOfRepayments("4") //
.withRepaymentEveryAfter("1") //
.withRepaymentFrequencyTypeAsMonths() //
.withInterestRatePerPeriod("2") //
.withAmortizationTypeAsEqualInstallments() //
.withInterestTypeAsDecliningBalance() //
.withInterestCalculationPeriodTypeSameAsRepaymentPeriod() //
.withExpectedDisbursementDate("01 October 2011") //
.withCalendarID(calendarID.toString()) //
.withSubmittedOnDate("01 October 2011") //
.withLoanType("jlg").build(clientID.toString(), groupID.toString(), loanProductID.toString(), null);
System.out.println(loanApplicationJSON);
return this.loanTransactionHelper.getLoanId(loanApplicationJSON);
}
private Integer applyForLoanApplication(final Integer groupID, final Integer loanProductID, Integer calendarID,
Integer clientID) {
System.out.println(
"--------------------------------APPLYING FOR LOAN APPLICATION--------------------------------");
final String loanApplicationJSON = new LoanApplicationTestBuilder() //
.withPrincipal("12,000.00") //
.withLoanTermFrequency("4") //
.withLoanTermFrequencyAsMonths() //
.withNumberOfRepayments("4") //
.withRepaymentEveryAfter("1") //
.withRepaymentFrequencyTypeAsMonths() //
.withInterestRatePerPeriod("2") //
.withAmortizationTypeAsEqualInstallments() //
.withInterestTypeAsDecliningBalance() //
.withInterestCalculationPeriodTypeSameAsRepaymentPeriod() //
.withExpectedDisbursementDate("01 October 2011") //
.withCalendarID(calendarID.toString()) //
.withSubmittedOnDate("01 October 2011") //
.withLoanType("jlg").build(clientID.toString(), groupID.toString(), loanProductID.toString(), null);
System.out.println(loanApplicationJSON);
return this.loanTransactionHelper.getLoanId(loanApplicationJSON);
}
private void verifyLoanRepaymentSchedule(final ArrayList<HashMap> loanSchedule) {
System.out.println("--------------------VERIFYING THE REPAYMENT DATE--------------------------");
assertEquals("Checking for Repayment Date for 1st Month", new ArrayList<>(Arrays.asList(2011, 10, 15)),
loanSchedule.get(1).get("dueDate"));
System.out.println("Repayment Date for 1st Month--" + loanSchedule.get(1).get("dueDate"));
assertEquals("Checking for Repayment Date for 2nd Month", new ArrayList<>(Arrays.asList(2011, 11, 15)),
loanSchedule.get(2).get("dueDate"));
System.out.println("Repayment Date for 2nd Month--" + loanSchedule.get(2).get("dueDate"));
assertEquals("Checking for Repayment Date for 3rd Month", new ArrayList<>(Arrays.asList(2011, 12, 15)),
loanSchedule.get(3).get("dueDate"));
System.out.println("Repayment Date for 3rd Month--" + loanSchedule.get(3).get("dueDate"));
assertEquals("Checking for Repayment Date for 4th Month", new ArrayList<>(Arrays.asList(2012, 1, 15)),
loanSchedule.get(4).get("dueDate"));
System.out.println("Repayment Date for 4th Month--" + loanSchedule.get(4).get("dueDate"));
}
private void verifyLoanRepaymentSchedule(final ArrayList<HashMap> loanSchedule) {
System.out.println("--------------------VERIFYING THE REPAYMENT DATE--------------------------");
assertEquals("Checking for Repayment Date for 1st Month", new ArrayList<>(Arrays.asList(2011, 10, 15)),
loanSchedule.get(1).get("dueDate"));
System.out.println("Repayment Date for 1st Month--" + loanSchedule.get(1).get("dueDate"));
assertEquals("Checking for Repayment Date for 2nd Month", new ArrayList<>(Arrays.asList(2011, 11, 15)),
loanSchedule.get(2).get("dueDate"));
System.out.println("Repayment Date for 2nd Month--" + loanSchedule.get(2).get("dueDate"));
assertEquals("Checking for Repayment Date for 3rd Month", new ArrayList<>(Arrays.asList(2011, 12, 15)),
loanSchedule.get(3).get("dueDate"));
System.out.println("Repayment Date for 3rd Month--" + loanSchedule.get(3).get("dueDate"));
assertEquals("Checking for Repayment Date for 4th Month", new ArrayList<>(Arrays.asList(2012, 1, 15)),
loanSchedule.get(4).get("dueDate"));
System.out.println("Repayment Date for 4th Month--" + loanSchedule.get(4).get("dueDate"));
}
}
@@ -92,14 +92,14 @@ public class CalendarHelper {
public static Integer createMeetingForGroup(final RequestSpecification requestSpec, final ResponseSpecification responseSpec,
final Integer groupId, final String startDate, final String frequency, final String interval, final String repeatsOnDay) {
System.out.println("---------------------------------CREATING A MEETING CALENDAR FOR THE GROUP------------------------------");
System.out.println("---------------------------------CREATING A MEETING CALENDAR FOR THE GROUP------------------------------");
final String CALENDAR_RESOURCE_URL = BASE_URL + Center_Entity + groupId + ENITY_NAME + "?" + Utils.TENANT_IDENTIFIER;
final String CALENDAR_RESOURCE_URL = BASE_URL + Center_Entity + groupId + ENITY_NAME + "?" + Utils.TENANT_IDENTIFIER;
System.out.println(CALENDAR_RESOURCE_URL);
System.out.println(CALENDAR_RESOURCE_URL);
return Utils.performServerPost(requestSpec, responseSpec, CALENDAR_RESOURCE_URL,
getTestCalendarAsJSON(frequency, interval, repeatsOnDay, startDate), "resourceId");
return Utils.performServerPost(requestSpec, responseSpec, CALENDAR_RESOURCE_URL,
getTestCalendarAsJSON(frequency, interval, repeatsOnDay, startDate), "resourceId");
}
public static Integer updateMeetingCalendarForCenter(final RequestSpecification requestSpec, final ResponseSpecification responseSpec,
@@ -197,7 +197,7 @@ public class CenterDomain implements Comparable<CenterDomain> {
}
public String getAccountNo(){
return this.accountNo;
return this.accountNo;
}
public int[] getGroupMembers() {
@@ -43,7 +43,7 @@ public class CenterHelper {
final String GET_CENTER_BY_ID_URL = CENTERS_URL + "/" + id + "?associations=groupMembers&" + Utils.TENANT_IDENTIFIER;
System.out.println("------------------------ RETRIEVING CENTER AT " + id + "-------------------------");
Object get = Utils.performServerGet(requestSpec, responseSpec, GET_CENTER_BY_ID_URL, "");
final String jsonData = new Gson().toJson(get);
final String jsonData = new Gson().toJson(get);
return new Gson().fromJson(jsonData, new TypeToken<CenterDomain>() {}.getType());
}
@@ -128,7 +128,7 @@ public class ClientHelper {
public static Integer createClientAsPerson(final RequestSpecification requestSpec, final ResponseSpecification responseSpec,
final String activationDate, final String officeId) {
System.out.println("---------------------------------CREATING A CLIENT NON PERSON(ORGANISATION)---------------------------------------------");
return Utils.performServerPost(requestSpec, responseSpec, CREATE_CLIENT_URL, getTestPersonClientAsJSON(activationDate, officeId),
"clientId");
@@ -145,10 +145,10 @@ public class ClientHelper {
public static Integer createClientAsEntity(final RequestSpecification requestSpec, final ResponseSpecification responseSpec,
final String activationDate, final String officeId) {
Integer constitutionCodeId = (Integer) CodeHelper.getCodeByName(requestSpec, responseSpec, "Constitution").get("id");
Integer soleProprietorCodeValueId = (Integer) CodeHelper.retrieveOrCreateCodeValue(constitutionCodeId, requestSpec, responseSpec).get("id");
Integer constitutionCodeId = (Integer) CodeHelper.getCodeByName(requestSpec, responseSpec, "Constitution").get("id");
Integer soleProprietorCodeValueId = (Integer) CodeHelper.retrieveOrCreateCodeValue(constitutionCodeId, requestSpec, responseSpec).get("id");
System.out.println("---------------------------------CREATING A CLIENT NON PERSON(ORGANISATION)---------------------------------------------");
return Utils.performServerPost(requestSpec, responseSpec, CREATE_CLIENT_URL, getTestEntityClientAsJSON(activationDate, officeId, soleProprietorCodeValueId),
"clientId");
@@ -185,11 +185,11 @@ public class ClientHelper {
map.put("lastname", Utils.randomNameGenerator("Client_LastName_", 4));
map.put("externalId", randomIDGenerator("ID_", 7));
map.put("dateFormat", DATE_FORMAT);
map.put("locale", "en");
map.put("active", "true");
map.put("activationDate", dateOfJoining);
System.out.println("map : " + map);
return new Gson().toJson(map);
map.put("locale", "en");
map.put("active", "true");
map.put("activationDate", dateOfJoining);
System.out.println("map : " + map);
return new Gson().toJson(map);
}
public static String getTestClientAsJSONPending(final String submittedOnDate, final String officeId) {
@@ -199,11 +199,11 @@ public class ClientHelper {
map.put("lastname", Utils.randomNameGenerator("Client_LastName_", 4));
map.put("externalId", randomIDGenerator("ID_", 7));
map.put("dateFormat", DATE_FORMAT);
map.put("locale", "en");
map.put("active", "false");
map.put("submittedOnDate", submittedOnDate);
System.out.println("map : " + map);
return new Gson().toJson(map);
map.put("locale", "en");
map.put("active", "false");
map.put("submittedOnDate", submittedOnDate);
System.out.println("map : " + map);
return new Gson().toJson(map);
}
public static String getTestPendingClientWithDatatableAsJson(final String registeredTableName) {
@@ -344,60 +344,60 @@ public class ClientHelper {
}
private String getReactivateClientAsJSON() {
final HashMap<String, String> map = new HashMap<>();
map.put("locale", CommonConstants.locale);
map.put("dateFormat", CommonConstants.dateFormat);
map.put("reactivationDate", CREATED_DATE_PLUS_ONE);
String clientJson = new Gson().toJson(map);
System.out.println(clientJson);
return clientJson;
private String getReactivateClientAsJSON() {
final HashMap<String, String> map = new HashMap<>();
map.put("locale", CommonConstants.locale);
map.put("dateFormat", CommonConstants.dateFormat);
map.put("reactivationDate", CREATED_DATE_PLUS_ONE);
String clientJson = new Gson().toJson(map);
System.out.println(clientJson);
return clientJson;
}
}
private String getUndoRejectClientAsJSON(final String date) {
final HashMap<String, String> map = new HashMap<>();
map.put("locale", CommonConstants.locale);
map.put("dateFormat", CommonConstants.dateFormat);
map.put("reopenedDate", date);
String clientJson = new Gson().toJson(map);
System.out.println(clientJson);
return clientJson;
private String getUndoRejectClientAsJSON(final String date) {
final HashMap<String, String> map = new HashMap<>();
map.put("locale", CommonConstants.locale);
map.put("dateFormat", CommonConstants.dateFormat);
map.put("reopenedDate", date);
String clientJson = new Gson().toJson(map);
System.out.println(clientJson);
return clientJson;
}
}
private String getUndoWithdrawnClientAsJSON(final String date) {
final HashMap<String, String> map = new HashMap<>();
map.put("locale", CommonConstants.locale);
map.put("dateFormat", CommonConstants.dateFormat);
map.put("reopenedDate", date);
String clientJson = new Gson().toJson(map);
System.out.println(clientJson);
return clientJson;
private String getUndoWithdrawnClientAsJSON(final String date) {
final HashMap<String, String> map = new HashMap<>();
map.put("locale", CommonConstants.locale);
map.put("dateFormat", CommonConstants.dateFormat);
map.put("reopenedDate", date);
String clientJson = new Gson().toJson(map);
System.out.println(clientJson);
return clientJson;
}
}
private String getRejectClientAsJSON() {
final HashMap<String, String> map = new HashMap<>();
/* Retrieve Code id for the Code "ClientRejectReason" */
String codeName = "ClientRejectReason";
HashMap<String, Object> code = CodeHelper.getCodeByName(this.requestSpec, this.responseSpec, codeName);
Integer clientRejectionReasonCodeId = (Integer) code.get("id");
private String getRejectClientAsJSON() {
final HashMap<String, String> map = new HashMap<>();
/* Retrieve Code id for the Code "ClientRejectReason" */
String codeName = "ClientRejectReason";
HashMap<String, Object> code = CodeHelper.getCodeByName(this.requestSpec, this.responseSpec, codeName);
Integer clientRejectionReasonCodeId = (Integer) code.get("id");
/* Retrieve/Create Code Values for the Code "ClientRejectReason" */
HashMap<String, Object> codeValue = CodeHelper.retrieveOrCreateCodeValue(clientRejectionReasonCodeId,
this.requestSpec, this.responseSpec);
Integer rejectionReasonId = (Integer) codeValue.get("id");
/* Retrieve/Create Code Values for the Code "ClientRejectReason" */
HashMap<String, Object> codeValue = CodeHelper.retrieveOrCreateCodeValue(clientRejectionReasonCodeId,
this.requestSpec, this.responseSpec);
Integer rejectionReasonId = (Integer) codeValue.get("id");
map.put("locale", CommonConstants.locale);
map.put("dateFormat", CommonConstants.dateFormat);
map.put("rejectionDate", CREATED_DATE_PLUS_ONE);
map.put("rejectionReasonId", rejectionReasonId.toString());
String clientJson = new Gson().toJson(map);
System.out.println(clientJson);
return clientJson;
map.put("locale", CommonConstants.locale);
map.put("dateFormat", CommonConstants.dateFormat);
map.put("rejectionDate", CREATED_DATE_PLUS_ONE);
map.put("rejectionReasonId", rejectionReasonId.toString());
String clientJson = new Gson().toJson(map);
System.out.println(clientJson);
return clientJson;
}
}
private String getActivateClientAsJSON(String date) {
final HashMap<String, String> map = new HashMap<>();
@@ -490,55 +490,55 @@ public class ClientHelper {
return performClientActions(createClientOperationURL(WITHDRAW_CLIENT_COMMAND, clientId), getWithdrawClientAsJSON(), clientId);
}
private String createClientOperationURL(final String command, final Integer clientId) {
return CLIENT_URL + "/" + clientId + "?command=" + command + "&" + Utils.TENANT_IDENTIFIER;
}
private String createClientOperationURL(final String command, final Integer clientId) {
return CLIENT_URL + "/" + clientId + "?command=" + command + "&" + Utils.TENANT_IDENTIFIER;
}
public HashMap<String, Object> undoReject(final Integer clientId) {
System.out.println("--------------------------------- UNDO REJECT CLIENT -------------------------------");
return performClientActions(createClientOperationURL(UNDOREJECT_CLIENT_COMMAND, clientId),
getUndoRejectClientAsJSON(CREATED_DATE_PLUS_TWO), clientId);
}
public HashMap<String, Object> undoReject(final Integer clientId) {
System.out.println("--------------------------------- UNDO REJECT CLIENT -------------------------------");
return performClientActions(createClientOperationURL(UNDOREJECT_CLIENT_COMMAND, clientId),
getUndoRejectClientAsJSON(CREATED_DATE_PLUS_TWO), clientId);
}
public HashMap<String, Object> undoWithdrawn(final Integer clientId) {
System.out.println("--------------------------------- UNDO WITHDRAWN CLIENT -------------------------------");
return performClientActions(createClientOperationURL(UNDOWITHDRAWN_CLIENT_COMMAND, clientId),
getUndoWithdrawnClientAsJSON(CREATED_DATE_PLUS_TWO), clientId);
}
public HashMap<String, Object> undoWithdrawn(final Integer clientId) {
System.out.println("--------------------------------- UNDO WITHDRAWN CLIENT -------------------------------");
return performClientActions(createClientOperationURL(UNDOWITHDRAWN_CLIENT_COMMAND, clientId),
getUndoWithdrawnClientAsJSON(CREATED_DATE_PLUS_TWO), clientId);
}
public Object undoRejectedclient(final Integer clientId, final String jsonAttributeToGetBack,
final String rejectedDate) {
System.out.println("----------------------------------UNDO REJECT CLIENT ----------------------------------");
return performClientActionsWithValidationErrors(createClientOperationURL(UNDOREJECT_CLIENT_COMMAND, clientId),
getUndoRejectClientAsJSON(rejectedDate), jsonAttributeToGetBack);
}
public Object undoRejectedclient(final Integer clientId, final String jsonAttributeToGetBack,
final String rejectedDate) {
System.out.println("----------------------------------UNDO REJECT CLIENT ----------------------------------");
return performClientActionsWithValidationErrors(createClientOperationURL(UNDOREJECT_CLIENT_COMMAND, clientId),
getUndoRejectClientAsJSON(rejectedDate), jsonAttributeToGetBack);
}
public Object undoWithdrawclient(final Integer clientId, final String jsonAttributeToGetBack,
final String rejectedDate) {
System.out.println("----------------------------------UNDO WITHDRAW CLIENT ----------------------------------");
return performClientActionsWithValidationErrors(
createClientOperationURL(UNDOWITHDRAWN_CLIENT_COMMAND, clientId),
getUndoWithdrawnClientAsJSON(rejectedDate), jsonAttributeToGetBack);
}
public Object undoWithdrawclient(final Integer clientId, final String jsonAttributeToGetBack,
final String rejectedDate) {
System.out.println("----------------------------------UNDO WITHDRAW CLIENT ----------------------------------");
return performClientActionsWithValidationErrors(
createClientOperationURL(UNDOWITHDRAWN_CLIENT_COMMAND, clientId),
getUndoWithdrawnClientAsJSON(rejectedDate), jsonAttributeToGetBack);
}
public Object activateClient(final Integer clientId, final String jsonAttributeToGetBack) {
System.out.println("--------------------------------- ACTIVATE CLIENT -------------------------------");
return performClientActionsWithValidationErrors(createClientOperationURL(ACTIVATE_CLIENT_COMMAND, clientId),
getActivateClientAsJSON(CREATED_DATE_PLUS_ONE), jsonAttributeToGetBack);
}
public Object activateClient(final Integer clientId, final String jsonAttributeToGetBack) {
System.out.println("--------------------------------- ACTIVATE CLIENT -------------------------------");
return performClientActionsWithValidationErrors(createClientOperationURL(ACTIVATE_CLIENT_COMMAND, clientId),
getActivateClientAsJSON(CREATED_DATE_PLUS_ONE), jsonAttributeToGetBack);
}
public HashMap<String, Object> activateClientWithDiffDateOption(final Integer clientId,
final String activationDate) {
System.out.println("--------------------------------- ACTIVATE CLIENT -------------------------------");
return performClientActions(createClientOperationURL(ACTIVATE_CLIENT_COMMAND, clientId),
getActivateClientAsJSON(activationDate), clientId);
}
public HashMap<String, Object> activateClientWithDiffDateOption(final Integer clientId,
final String activationDate) {
System.out.println("--------------------------------- ACTIVATE CLIENT -------------------------------");
return performClientActions(createClientOperationURL(ACTIVATE_CLIENT_COMMAND, clientId),
getActivateClientAsJSON(activationDate), clientId);
}
private ArrayList<HashMap> performClientActionsWithValidationErrors(final String postURLForClient,
final String jsonToBeSent, final String jsonAttributeToGetBack) {
return Utils.performServerPost(this.requestSpec, this.responseSpec, postURLForClient, jsonToBeSent,
jsonAttributeToGetBack);
}
private ArrayList<HashMap> performClientActionsWithValidationErrors(final String postURLForClient,
final String jsonToBeSent, final String jsonAttributeToGetBack) {
return Utils.performServerPost(this.requestSpec, this.responseSpec, postURLForClient, jsonToBeSent,
jsonAttributeToGetBack);
}
private HashMap<String, Object> performClientActions(final String postURLForClient, final String jsonToBeSent, final Integer clientId) {
Utils.performServerPost(this.requestSpec, this.responseSpec, postURLForClient, jsonToBeSent, CommonConstants.RESPONSE_STATUS);
@@ -29,8 +29,8 @@ import com.jayway.restassured.specification.RequestSpecification;
import com.jayway.restassured.specification.ResponseSpecification;
public class HookHelper {
private final RequestSpecification requestSpec;
private final RequestSpecification requestSpec;
private final ResponseSpecification responseSpec;
private static final String CREATE_HOOK_URL = "/fineract-provider/api/v1/hooks?" + Utils.TENANT_IDENTIFIER;
@@ -47,9 +47,9 @@ public class HookHelper {
}
public String getTestHookAsJson(final String payloadURL) {
final HashMap<String, Object> map = new HashMap<>();
map.put("name", "Web");
map.put("displayName", Utils.randomNameGenerator("Hook_DisplayName_", 5));
final HashMap<String, Object> map = new HashMap<>();
map.put("name", "Web");
map.put("displayName", Utils.randomNameGenerator("Hook_DisplayName_", 5));
map.put("isActive", "true");
final HashMap<String, String> config = new HashMap<>();
config.put("Content Type", "json");
@@ -97,7 +97,7 @@ public class HookHelper {
final String GET_URL = "/fineract-provider/api/v1/hooks/" + hookId + "?" + Utils.TENANT_IDENTIFIER;
ResponseSpecification responseSpec404 = new ResponseSpecBuilder().expectStatusCode(404).build();
ArrayList array = Utils.performServerGet(this.requestSpec, responseSpec404, GET_URL, "errors");
HashMap<String, String> map = (HashMap<String, String>)array.get(0);
HashMap<String, String> map = (HashMap<String, String>)array.get(0);
assertEquals("error.msg.hook.identifier.not.found",map.get("userMessageGlobalisationCode"));
}
}
@@ -24,7 +24,7 @@ import com.jayway.restassured.specification.RequestSpecification;
import com.jayway.restassured.specification.ResponseSpecification;
public class LoanRescheduleRequestHelper {
private final RequestSpecification requestSpec;
private final RequestSpecification requestSpec;
private final ResponseSpecification responseSpec;
private static final String LOAN_RESCHEDULE_REQUEST_URL = "/fineract-provider/api/v1/rescheduleloans";
@@ -35,32 +35,32 @@ public class LoanRescheduleRequestHelper {
}
public Integer createLoanRescheduleRequest(final String requestJSON) {
final String URL = LOAN_RESCHEDULE_REQUEST_URL + "?" + Utils.TENANT_IDENTIFIER;
return Utils.performServerPost(this.requestSpec, this.responseSpec, URL, requestJSON, "resourceId");
final String URL = LOAN_RESCHEDULE_REQUEST_URL + "?" + Utils.TENANT_IDENTIFIER;
return Utils.performServerPost(this.requestSpec, this.responseSpec, URL, requestJSON, "resourceId");
}
public Integer rejectLoanRescheduleRequest(final Integer requestId, final String requestJSON) {
final String URL = LOAN_RESCHEDULE_REQUEST_URL + "/" + requestId + "?" + Utils.TENANT_IDENTIFIER + "&command=reject";
return Utils.performServerPost(this.requestSpec, this.responseSpec, URL, requestJSON, "resourceId");
final String URL = LOAN_RESCHEDULE_REQUEST_URL + "/" + requestId + "?" + Utils.TENANT_IDENTIFIER + "&command=reject";
return Utils.performServerPost(this.requestSpec, this.responseSpec, URL, requestJSON, "resourceId");
}
public Integer approveLoanRescheduleRequest(final Integer requestId, final String requestJSON) {
final String URL = LOAN_RESCHEDULE_REQUEST_URL + "/" + requestId + "?" + Utils.TENANT_IDENTIFIER + "&command=approve";
return Utils.performServerPost(this.requestSpec, this.responseSpec, URL, requestJSON, "resourceId");
final String URL = LOAN_RESCHEDULE_REQUEST_URL + "/" + requestId + "?" + Utils.TENANT_IDENTIFIER + "&command=approve";
return Utils.performServerPost(this.requestSpec, this.responseSpec, URL, requestJSON, "resourceId");
}
public Object getLoanRescheduleRequest(final Integer requestId, final String param) {
final String URL = LOAN_RESCHEDULE_REQUEST_URL + "/" + requestId + "?" + Utils.TENANT_IDENTIFIER;
return Utils.performServerGet(requestSpec, responseSpec, URL, param);
final String URL = LOAN_RESCHEDULE_REQUEST_URL + "/" + requestId + "?" + Utils.TENANT_IDENTIFIER;
return Utils.performServerGet(requestSpec, responseSpec, URL, param);
}
public void verifyCreationOfLoanRescheduleRequest(final Integer requestId) {
final String URL = LOAN_RESCHEDULE_REQUEST_URL + "/" + requestId + "?" + Utils.TENANT_IDENTIFIER;
final Integer id = Utils.performServerGet(requestSpec, responseSpec, URL, "id");
assertEquals("ERROR IN CREATING LOAN RESCHEDULE REQUEST", requestId, id);
final String URL = LOAN_RESCHEDULE_REQUEST_URL + "/" + requestId + "?" + Utils.TENANT_IDENTIFIER;
final Integer id = Utils.performServerGet(requestSpec, responseSpec, URL, "id");
assertEquals("ERROR IN CREATING LOAN RESCHEDULE REQUEST", requestId, id);
}
}
@@ -22,132 +22,132 @@ import com.google.gson.Gson;
public class OfficeDomain {
public static class Builder {
public static class Builder {
private int id;
private String name;
private String nameDecorated;
private String externalId;
private String[] openingDate;
private String hierarchy;
private int id;
private String name;
private String nameDecorated;
private String externalId;
private String[] openingDate;
private String hierarchy;
private Builder(final int id, final String name,
final String nameDecorated, final String externalId,
final String[] openingDate, final String hierarchy) {
this.id = id;
this.name = name;
this.nameDecorated = nameDecorated;
this.externalId = externalId;
this.openingDate = openingDate;
this.hierarchy = hierarchy;
}
private Builder(final int id, final String name,
final String nameDecorated, final String externalId,
final String[] openingDate, final String hierarchy) {
this.id = id;
this.name = name;
this.nameDecorated = nameDecorated;
this.externalId = externalId;
this.openingDate = openingDate;
this.hierarchy = hierarchy;
}
public OfficeDomain build() {
return new OfficeDomain(this.id, this.name, this.nameDecorated,
this.externalId, this.openingDate, this.hierarchy);
}
}
public OfficeDomain build() {
return new OfficeDomain(this.id, this.name, this.nameDecorated,
this.externalId, this.openingDate, this.hierarchy);
}
}
private int id;
private String name;
private String nameDecorated;
private String externalId;
private String[] openingDate;
private String hierarchy;
private int id;
private String name;
private String nameDecorated;
private String externalId;
private String[] openingDate;
private String hierarchy;
OfficeDomain() {
super();
}
OfficeDomain() {
super();
}
private OfficeDomain(final int id, final String name,
final String nameDecorated, final String externalId,
final String[] openingDate, final String hierarchy) {
super();
this.id = id;
this.name = name;
this.nameDecorated = nameDecorated;
this.externalId = externalId;
this.openingDate = openingDate;
this.hierarchy = hierarchy;
}
private OfficeDomain(final int id, final String name,
final String nameDecorated, final String externalId,
final String[] openingDate, final String hierarchy) {
super();
this.id = id;
this.name = name;
this.nameDecorated = nameDecorated;
this.externalId = externalId;
this.openingDate = openingDate;
this.hierarchy = hierarchy;
}
public String toJSON() {
return new Gson().toJson(this);
}
public String toJSON() {
return new Gson().toJson(this);
}
public static OfficeDomain fromJSON(final String jsonData) {
return new Gson().fromJson(jsonData, OfficeDomain.class);
}
public static OfficeDomain fromJSON(final String jsonData) {
return new Gson().fromJson(jsonData, OfficeDomain.class);
}
public static Builder create(final int id, final String name,
final String nameDecorated, final String externalId,
final String[] openingDate, final String hierarchy) {
return new Builder(id, name, nameDecorated, externalId, openingDate,
hierarchy);
}
public static Builder create(final int id, final String name,
final String nameDecorated, final String externalId,
final String[] openingDate, final String hierarchy) {
return new Builder(id, name, nameDecorated, externalId, openingDate,
hierarchy);
}
public int getId() {
return this.id;
}
public int getId() {
return this.id;
}
public String getName() {
return this.name;
}
public String getName() {
return this.name;
}
public String getNameDecorated() {
return this.nameDecorated;
}
public String getNameDecorated() {
return this.nameDecorated;
}
public String getExternalId() {
return this.externalId;
}
public String getExternalId() {
return this.externalId;
}
public String[] getOpeningDate() {
return this.openingDate;
}
public String[] getOpeningDate() {
return this.openingDate;
}
public String getHierarchy() {
return this.hierarchy;
}
public String getHierarchy() {
return this.hierarchy;
}
@Override
public int hashCode() {
int hash = 1;
@Override
public int hashCode() {
int hash = 1;
if (this.id > 0)
hash += this.id;
if (this.name != null)
hash += this.name.hashCode();
if (this.nameDecorated != null)
hash += this.nameDecorated.hashCode();
if (this.externalId != null)
hash += this.externalId.hashCode();
if (this.openingDate != null)
hash += this.openingDate.hashCode();
if (this.hierarchy != null)
hash += this.hierarchy.hashCode();
if (this.id > 0)
hash += this.id;
if (this.name != null)
hash += this.name.hashCode();
if (this.nameDecorated != null)
hash += this.nameDecorated.hashCode();
if (this.externalId != null)
hash += this.externalId.hashCode();
if (this.openingDate != null)
hash += this.openingDate.hashCode();
if (this.hierarchy != null)
hash += this.hierarchy.hashCode();
return hash;
}
return hash;
}
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof OfficeDomain))
return false;
if (!(obj instanceof OfficeDomain))
return false;
OfficeDomain od = (OfficeDomain) obj;
OfficeDomain od = (OfficeDomain) obj;
if (this.id == od.getId() && this.name.equals(od.getName())
&& this.nameDecorated.equals(od.getName())
&& this.externalId.equals(od.getExternalId())
&& this.openingDate.equals(od.getOpeningDate())
&& this.hierarchy.equals(od.getHierarchy()))
return true;
if (this.id == od.getId() && this.name.equals(od.getName())
&& this.nameDecorated.equals(od.getName())
&& this.externalId.equals(od.getExternalId())
&& this.openingDate.equals(od.getOpeningDate())
&& this.hierarchy.equals(od.getHierarchy()))
return true;
return false;
}
return false;
}
}
@@ -37,77 +37,77 @@ import javax.ws.rs.core.MediaType;
public class OfficeHelper {
private static final String OFFICE_URL = "/fineract-provider/api/v1/offices";
private final RequestSpecification requestSpec;
private final ResponseSpecification responseSpec;
private static final String OFFICE_URL = "/fineract-provider/api/v1/offices";
private final RequestSpecification requestSpec;
private final ResponseSpecification responseSpec;
public OfficeHelper(final RequestSpecification requestSpec,
final ResponseSpecification responseSpec) {
this.requestSpec = requestSpec;
this.responseSpec = responseSpec;
}
public OfficeHelper(final RequestSpecification requestSpec,
final ResponseSpecification responseSpec) {
this.requestSpec = requestSpec;
this.responseSpec = responseSpec;
}
public OfficeDomain retrieveOfficeByID(int id) {
Object get = Utils.performServerGet(
requestSpec, responseSpec, OFFICE_URL + "/" + id + "?"
+ Utils.TENANT_IDENTIFIER, "");
final String json = new Gson().toJson(get);
return new Gson().fromJson(json, new TypeToken<OfficeDomain>() {
}.getType());
}
public OfficeDomain retrieveOfficeByID(int id) {
Object get = Utils.performServerGet(
requestSpec, responseSpec, OFFICE_URL + "/" + id + "?"
+ Utils.TENANT_IDENTIFIER, "");
final String json = new Gson().toJson(get);
return new Gson().fromJson(json, new TypeToken<OfficeDomain>() {
}.getType());
}
public Integer createOffice(final String openingDate) {
String json = getAsJSON(openingDate);
return Utils.performServerPost(this.requestSpec, this.responseSpec,
OFFICE_URL + "?" + Utils.TENANT_IDENTIFIER, json,
CommonConstants.RESPONSE_RESOURCE_ID);
}
public Integer createOffice(final String openingDate) {
String json = getAsJSON(openingDate);
return Utils.performServerPost(this.requestSpec, this.responseSpec,
OFFICE_URL + "?" + Utils.TENANT_IDENTIFIER, json,
CommonConstants.RESPONSE_RESOURCE_ID);
}
public Integer updateOffice(int id, String name, String openingDate) {
final HashMap map = new HashMap<>();
map.put("name", name);
map.put("dateFormat", "dd MMMM yyyy");
map.put("locale", "en");
map.put("openingDate", openingDate);
public Integer updateOffice(int id, String name, String openingDate) {
final HashMap map = new HashMap<>();
map.put("name", name);
map.put("dateFormat", "dd MMMM yyyy");
map.put("locale", "en");
map.put("openingDate", openingDate);
System.out.println("map : " + map);
System.out.println("map : " + map);
return Utils.performServerPut(requestSpec, responseSpec, OFFICE_URL
+ "/" + id + "?" + Utils.TENANT_IDENTIFIER,
new Gson().toJson(map), "resourceId");
}
return Utils.performServerPut(requestSpec, responseSpec, OFFICE_URL
+ "/" + id + "?" + Utils.TENANT_IDENTIFIER,
new Gson().toJson(map), "resourceId");
}
public static String getAsJSON(final String openingDate) {
final HashMap<String, String> map = new HashMap<>();
map.put("parentId", "1");
map.put("name", Utils.randomNameGenerator("Office_", 4));
map.put("dateFormat", "dd MMMM yyyy");
map.put("locale", "en");
map.put("openingDate", openingDate);
System.out.println("map : " + map);
return new Gson().toJson(map);
}
public static String getAsJSON(final String openingDate) {
final HashMap<String, String> map = new HashMap<>();
map.put("parentId", "1");
map.put("name", Utils.randomNameGenerator("Office_", 4));
map.put("dateFormat", "dd MMMM yyyy");
map.put("locale", "en");
map.put("openingDate", openingDate);
System.out.println("map : " + map);
return new Gson().toJson(map);
}
public String importOfficeTemplate(File file){
String locale="en";
String dateFormat="dd MMMM yyyy";
requestSpec.header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA);
return Utils.performServerTemplatePost(requestSpec,responseSpec,OFFICE_URL+"/uploadtemplate"+"?"+Utils.TENANT_IDENTIFIER,
null,file,locale,dateFormat);
public String importOfficeTemplate(File file){
String locale="en";
String dateFormat="dd MMMM yyyy";
requestSpec.header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA);
return Utils.performServerTemplatePost(requestSpec,responseSpec,OFFICE_URL+"/uploadtemplate"+"?"+Utils.TENANT_IDENTIFIER,
null,file,locale,dateFormat);
}
}
public String getOutputTemplateLocation(final String importDocumentId){
requestSpec.header(HttpHeaders.CONTENT_TYPE,MediaType.TEXT_PLAIN);
return Utils.performServerOutputTemplateLocationGet(requestSpec,responseSpec,"/fineract-provider/api/v1/imports/getOutputTemplateLocation"+"?"
+Utils.TENANT_IDENTIFIER,importDocumentId);
}
public Workbook getOfficeWorkBook(final String dateFormat) throws IOException {
requestSpec.header(HttpHeaders.CONTENT_TYPE,"application/vnd.ms-excel");
byte[] byteArray=Utils.performGetBinaryResponse(requestSpec,responseSpec,OFFICE_URL+"/downloadtemplate"+"?"+
Utils.TENANT_IDENTIFIER+"&dateFormat="+dateFormat);
InputStream inputStream= new ByteArrayInputStream(byteArray);
Workbook workbook=new HSSFWorkbook(inputStream);
return workbook;
}
public String getOutputTemplateLocation(final String importDocumentId){
requestSpec.header(HttpHeaders.CONTENT_TYPE,MediaType.TEXT_PLAIN);
return Utils.performServerOutputTemplateLocationGet(requestSpec,responseSpec,"/fineract-provider/api/v1/imports/getOutputTemplateLocation"+"?"
+Utils.TENANT_IDENTIFIER,importDocumentId);
}
public Workbook getOfficeWorkBook(final String dateFormat) throws IOException {
requestSpec.header(HttpHeaders.CONTENT_TYPE,"application/vnd.ms-excel");
byte[] byteArray=Utils.performGetBinaryResponse(requestSpec,responseSpec,OFFICE_URL+"/downloadtemplate"+"?"+
Utils.TENANT_IDENTIFIER+"&dateFormat="+dateFormat);
InputStream inputStream= new ByteArrayInputStream(byteArray);
Workbook workbook=new HSSFWorkbook(inputStream);
return workbook;
}
}
@@ -158,10 +158,10 @@ public class ProvisioningIntegrationTest {
Object requestedCategoryId = requestedMap.get("categoryId") ;
boolean found = false ;
for(int j = 0 ; j < newdefintions.size(); j++) {
Map newMap = (Map)newdefintions.get(j) ;
Map newMap = (Map)newdefintions.get(j) ;
Object newCategoryId = newMap.get("categoryId") ;
if(requestedCategoryId.equals(newCategoryId)) {
found = true ;
found = true ;
checkProperty("categoryId", requestedMap, newMap) ;
checkProperty("categoryName", requestedMap, newMap) ;
checkProperty("minAge", requestedMap, newMap) ;
@@ -23,86 +23,86 @@ import static org.junit.Assert.assertEquals;
import java.util.HashMap;
public class LoanDisbursementTestBuilder {
String dueDate = null;
Float totalOriginalDueForPeriod = null;
Float totalOutstandingForPeriod = null;
Float interestOutstanding = null;
Float principalOutstanding = null;
Float principalLoanBalanceOutstanding = null;
Float principalDue = null;
Float principalOriginalDue = null;
String fromDate = null;
public LoanDisbursementTestBuilder(String dueDate,Float totalOriginalDueForPeriod,Float totalOutstandingForPeriod,
Float interestOutstanding, Float principalOutstanding, Float principalLoanBalanceOutstanding, Float principalDue,
Float principalOriginalDue, String fromDate) {
this.dueDate = dueDate;
this.totalOriginalDueForPeriod = totalOriginalDueForPeriod;
this.totalOutstandingForPeriod = totalOutstandingForPeriod;
this.interestOutstanding = interestOutstanding;
this.principalOutstanding = principalOutstanding;
this.principalLoanBalanceOutstanding = principalLoanBalanceOutstanding;
this.principalDue = principalDue;
this.principalOriginalDue = principalOriginalDue;
this.fromDate = fromDate;
}
String dueDate = null;
Float totalOriginalDueForPeriod = null;
Float totalOutstandingForPeriod = null;
Float interestOutstanding = null;
Float principalOutstanding = null;
Float principalLoanBalanceOutstanding = null;
Float principalDue = null;
Float principalOriginalDue = null;
String fromDate = null;
public LoanDisbursementTestBuilder(String dueDate,Float totalOriginalDueForPeriod,Float totalOutstandingForPeriod,
Float interestOutstanding, Float principalOutstanding, Float principalLoanBalanceOutstanding, Float principalDue,
Float principalOriginalDue, String fromDate) {
this.dueDate = dueDate;
this.totalOriginalDueForPeriod = totalOriginalDueForPeriod;
this.totalOutstandingForPeriod = totalOutstandingForPeriod;
this.interestOutstanding = interestOutstanding;
this.principalOutstanding = principalOutstanding;
this.principalLoanBalanceOutstanding = principalLoanBalanceOutstanding;
this.principalDue = principalDue;
this.principalOriginalDue = principalOriginalDue;
this.fromDate = fromDate;
}
public String getDueDate() {
return this.dueDate;
}
public String getDueDate() {
return this.dueDate;
}
public Float getTotalOriginalDueForPeriod() {
return this.totalOriginalDueForPeriod;
}
public Float getTotalOriginalDueForPeriod() {
return this.totalOriginalDueForPeriod;
}
public Float getTotalOutstandingForPeriod() {
return this.totalOutstandingForPeriod;
}
public Float getTotalOutstandingForPeriod() {
return this.totalOutstandingForPeriod;
}
public Float getInterestOutstanding() {
return this.interestOutstanding;
}
public Float getInterestOutstanding() {
return this.interestOutstanding;
}
public Float getPrincipalOutstanding() {
return this.principalOutstanding;
}
public Float getPrincipalOutstanding() {
return this.principalOutstanding;
}
public Float getPrincipalLoanBalanceOutstanding() {
return this.principalLoanBalanceOutstanding;
}
public Float getPrincipalLoanBalanceOutstanding() {
return this.principalLoanBalanceOutstanding;
}
public Float getPrincipalDue() {
return this.principalDue;
}
public Float getPrincipalDue() {
return this.principalDue;
}
public Float getPrincipalOriginalDue() {
return this.principalOriginalDue;
}
public Float getPrincipalOriginalDue() {
return this.principalOriginalDue;
}
public String getFromDate() {
return this.fromDate;
}
/*public HashMap<String, String> build(String dueDate,String totalOriginalDueForPeriod,String totalOutstandingForPeriod,
String interestOutstanding, String principalOutstanding, String principalLoanBalanceOutstanding, String principalDue,
String principalOriginalDue, String fromDate) {
HashMap<String, String> expectedRepaymentSchedule = new HashMap<String, String>();
expectedRepaymentSchedule.put("dueDate", dueDate);
expectedRepaymentSchedule.put("totalOriginalDueForPeriod",
totalOriginalDueForPeriod);
expectedRepaymentSchedule.put("totalOutstandingForPeriod",
totalOutstandingForPeriod);
expectedRepaymentSchedule.put("interestOutstanding", interestOutstanding);
expectedRepaymentSchedule.put("principalOutstanding",
principalOutstanding);
expectedRepaymentSchedule.put("principalLoanBalanceOutstanding",
principalLoanBalanceOutstanding);
expectedRepaymentSchedule.put("principalDue", principalDue);
expectedRepaymentSchedule.put("principalOriginalDue",
principalOriginalDue);
expectedRepaymentSchedule.put("fromDate", fromDate);
return expectedRepaymentSchedule;
}*/
public String getFromDate() {
return this.fromDate;
}
/*public HashMap<String, String> build(String dueDate,String totalOriginalDueForPeriod,String totalOutstandingForPeriod,
String interestOutstanding, String principalOutstanding, String principalLoanBalanceOutstanding, String principalDue,
String principalOriginalDue, String fromDate) {
HashMap<String, String> expectedRepaymentSchedule = new HashMap<String, String>();
expectedRepaymentSchedule.put("dueDate", dueDate);
expectedRepaymentSchedule.put("totalOriginalDueForPeriod",
totalOriginalDueForPeriod);
expectedRepaymentSchedule.put("totalOutstandingForPeriod",
totalOutstandingForPeriod);
expectedRepaymentSchedule.put("interestOutstanding", interestOutstanding);
expectedRepaymentSchedule.put("principalOutstanding",
principalOutstanding);
expectedRepaymentSchedule.put("principalLoanBalanceOutstanding",
principalLoanBalanceOutstanding);
expectedRepaymentSchedule.put("principalDue", principalDue);
expectedRepaymentSchedule.put("principalOriginalDue",
principalOriginalDue);
expectedRepaymentSchedule.put("fromDate", fromDate);
return expectedRepaymentSchedule;
}*/
}
@@ -213,7 +213,7 @@ public class LoanProductTestBuilder {
map.put("maximumGap", maximumGap) ;
}
map.put("syncExpectedWithDisbursementDate",
this.syncExpectedWithDisbursementDate);
this.syncExpectedWithDisbursementDate);
return new Gson().toJson(map);
}
@@ -504,7 +504,7 @@ public class LoanProductTestBuilder {
public LoanProductTestBuilder withSyncExpectedWithDisbursementDate(Boolean syncExpectedWithDisbursementDate) {
this.syncExpectedWithDisbursementDate =
syncExpectedWithDisbursementDate ;
syncExpectedWithDisbursementDate ;
return this ;
}
}
@@ -193,7 +193,7 @@ public class LoanTransactionHelper {
public HashMap disburseLoanWithRepaymentReschedule(final String date, final Integer loanID, String adjustRepaymentDate) {
return performLoanTransaction(createLoanOperationURL(DISBURSE_LOAN_COMMAND, loanID), getDisburseLoanWithRepaymentRescheduleAsJSON(date,
null, adjustRepaymentDate));
null, adjustRepaymentDate));
}
public HashMap disburseLoan(final String date, final Integer loanID, final String disburseAmt) {
@@ -522,8 +522,8 @@ public class LoanTransactionHelper {
}
private Object performLoanTransaction(final String postURLForLoanTransaction, final String jsonToBeSent, ResponseSpecification responseValidationError) {
return Utils.performServerPost(this.requestSpec, responseValidationError, postURLForLoanTransaction, jsonToBeSent, CommonConstants.RESPONSE_ERROR);
return Utils.performServerPost(this.requestSpec, responseValidationError, postURLForLoanTransaction, jsonToBeSent, CommonConstants.RESPONSE_ERROR);
}
public Object adjustLoanTransaction(final Integer loanId, final Integer transactionId, final String date,
@@ -648,17 +648,17 @@ public class LoanTransactionHelper {
}
public Object editDisbursementDetail(final Integer loanID, final Integer disbursementId, final String approvalAmount, final String expectedDisbursementDate,
final String updatedExpectedDisbursementDate, final String updatedPrincipal, final String jsonAttributeToGetBack) {
return Utils.performServerPut(this.requestSpec, this.responseSpec, createEditDisbursementURL(loanID, disbursementId), getEditDisbursementsAsJSON(approvalAmount, expectedDisbursementDate,
updatedExpectedDisbursementDate, updatedPrincipal), jsonAttributeToGetBack);
final String updatedExpectedDisbursementDate, final String updatedPrincipal, final String jsonAttributeToGetBack) {
return Utils.performServerPut(this.requestSpec, this.responseSpec, createEditDisbursementURL(loanID, disbursementId), getEditDisbursementsAsJSON(approvalAmount, expectedDisbursementDate,
updatedExpectedDisbursementDate, updatedPrincipal), jsonAttributeToGetBack);
}
public Object addAndDeleteDisbursementDetail(final Integer loanID, final String approvalAmount, final String expectedDisbursementDate
, List<HashMap> disbursementData, final String jsonAttributeToGetBack) {
return Utils.performServerPut(this.requestSpec, this.responseSpec, createAddAndDeleteDisbursementURL(loanID),
getAddAndDeleteDisbursementsAsJSON(approvalAmount, expectedDisbursementDate, disbursementData), jsonAttributeToGetBack);
, List<HashMap> disbursementData, final String jsonAttributeToGetBack) {
return Utils.performServerPut(this.requestSpec, this.responseSpec, createAddAndDeleteDisbursementURL(loanID),
getAddAndDeleteDisbursementsAsJSON(approvalAmount, expectedDisbursementDate, disbursementData), jsonAttributeToGetBack);
}
private String createEditDisbursementURL(Integer loanID, Integer disbursementId) {
@@ -670,7 +670,7 @@ public class LoanTransactionHelper {
}
public static String getEditDisbursementsAsJSON(final String approvalAmount, final String expectedDisbursementDate,
final String updatedExpectedDisbursementDate, final String updatedPrincipal) {
final String updatedExpectedDisbursementDate, final String updatedPrincipal) {
final HashMap<String, String> map = new HashMap<>();
map.put("locale", "en");
map.put("dateFormat", "dd MMMM yyyy");
@@ -684,7 +684,7 @@ public class LoanTransactionHelper {
}
public static String getAddAndDeleteDisbursementsAsJSON(final String approvalAmount, final String expectedDisbursementDate,
final List<HashMap> disbursementData) {
final List<HashMap> disbursementData) {
final HashMap map = new HashMap<>();
map.put("locale", "en");
map.put("dateFormat", "dd MMMM yyyy");
@@ -136,10 +136,10 @@ public class SavingsProductHelper {
map.putAll(getAccountMappingForCashBased());
}
if(this.isDormancyTrackingActive){
map.put("isDormancyTrackingActive", Boolean.toString(this.isDormancyTrackingActive));
map.put("daysToInactive", this.daysToInactive);
map.put("daysToDormancy", this.daysToDormancy);
map.put("daysToEscheat", this.daysToEscheat);
map.put("isDormancyTrackingActive", Boolean.toString(this.isDormancyTrackingActive));
map.put("daysToInactive", this.daysToInactive);
map.put("daysToDormancy", this.daysToDormancy);
map.put("daysToEscheat", this.daysToEscheat);
}
String savingsProductCreateJson = new Gson().toJson(map);
@@ -285,13 +285,13 @@ public class SavingsProductHelper {
assertEquals("ERROR IN CREATING THE Savings Product", generatedProductID, responseSavingsProductID);
}
public SavingsProductHelper withDormancy() {
this.isDormancyTrackingActive = true;
this.daysToInactive = "30";
this.daysToDormancy = "60";
this.daysToEscheat = "90";
public SavingsProductHelper withDormancy() {
this.isDormancyTrackingActive = true;
this.daysToInactive = "30";
this.daysToDormancy = "60";
this.daysToEscheat = "90";
return this;
}
return this;
}
}
@@ -90,38 +90,38 @@ public class SavingsStatusChecker {
return (Boolean) savingsStatusMap.get(nameOfSavingsStatusString);
}
public static void verifySavingsSubStatusInactive(HashMap savingsStatusHashMap) {
public static void verifySavingsSubStatusInactive(HashMap savingsStatusHashMap) {
System.out.println("\n-------------------------------------- VERIFYING SAVINGS APPLICATION IS ACTIVE ------------------------------------");
assertTrue("UNEXPECTED SAVINGS ACCOUNT SUB STATUS", getStatus(savingsStatusHashMap, "inactive"));
System.out.println("Savings Application Sub Status:" + savingsStatusHashMap + "\n");
}
public static void verifySavingsSubStatusDormant(HashMap savingsStatusHashMap) {
}
public static void verifySavingsSubStatusDormant(HashMap savingsStatusHashMap) {
System.out.println("\n-------------------------------------- VERIFYING SAVINGS APPLICATION IS ACTIVE ------------------------------------");
assertTrue("UNEXPECTED SAVINGS ACCOUNT SUB STATUS", getStatus(savingsStatusHashMap, "dormant"));
System.out.println("Savings Application Sub Status:" + savingsStatusHashMap + "\n");
}
public static void verifySavingsSubStatusEscheat(HashMap savingsStatusHashMap) {
}
public static void verifySavingsSubStatusEscheat(HashMap savingsStatusHashMap) {
System.out.println("\n-------------------------------------- VERIFYING SAVINGS APPLICATION IS ACTIVE ------------------------------------");
assertTrue("UNEXPECTED SAVINGS ACCOUNT SUB STATUS", getStatus(savingsStatusHashMap, "escheat"));
System.out.println("Savings Application Sub Status:" + savingsStatusHashMap + "\n");
}
}
public static void verifySavingsSubStatusNone(HashMap savingsStatusHashMap) {
public static void verifySavingsSubStatusNone(HashMap savingsStatusHashMap) {
System.out.println("\n-------------------------------------- VERIFYING SAVINGS APPLICATION IS ACTIVE ------------------------------------");
assertTrue("UNEXPECTED SAVINGS ACCOUNT SUB STATUS", getStatus(savingsStatusHashMap, "none"));
System.out.println("Savings Application Sub Status:" + savingsStatusHashMap + "\n");
}
public static void verifySavingsSubStatusblock(HashMap savingsStatusHashMap) {
}
public static void verifySavingsSubStatusblock(HashMap savingsStatusHashMap) {
System.out.println(
"\n-------------------------------------- VERIFYING SAVINGS ACCOUNT IS BLOCKED ------------------------------------");
assertTrue("block", getStatus(savingsStatusHashMap, "block"));
System.out.println("Savings Application Sub Status:" + savingsStatusHashMap + "\n");
}
public static void verifySavingsSubStatusIsNone(HashMap savingsStatusHashMap) {
public static void verifySavingsSubStatusIsNone(HashMap savingsStatusHashMap) {
System.out.println("\n------------------------- VERIFYING SAVINGS ACCOUNT IS NOT BLOCKED FOR ANY TYPE OF TRANSACTIONS ---------------------------");
assertTrue("none", getStatus(savingsStatusHashMap, "none"));
System.out.println("Savings Application Sub Status:" + savingsStatusHashMap + "\n");
@@ -28,199 +28,199 @@ import com.jayway.restassured.specification.ResponseSpecification;
public class AccountNumberPreferencesHelper {
private final RequestSpecification requestSpec;
private final RequestSpecification requestSpec;
private final ResponseSpecification responseSpec;
private final ResponseSpecification responseSpec;
private static final String ACCOUNT_NUMBER_FORMATS_REQUEST_URL = "/fineract-provider/api/v1/accountnumberformats";
private static final String ACCOUNT_NUMBER_FORMATS_REQUEST_URL = "/fineract-provider/api/v1/accountnumberformats";
public AccountNumberPreferencesHelper(
final RequestSpecification requestSpec,
final ResponseSpecification responseSpec) {
this.requestSpec = requestSpec;
this.responseSpec = responseSpec;
}
public AccountNumberPreferencesHelper(
final RequestSpecification requestSpec,
final ResponseSpecification responseSpec) {
this.requestSpec = requestSpec;
this.responseSpec = responseSpec;
}
public Object createClientAccountNumberPreference(
ResponseSpecification responseSpec, String jsonAttributeToGetBack) {
System.out
.println("---------------------------------CREATING CLIENT ACCOUNT NUMBER PREFERENCE------------------------------------------");
public Object createClientAccountNumberPreference(
ResponseSpecification responseSpec, String jsonAttributeToGetBack) {
System.out
.println("---------------------------------CREATING CLIENT ACCOUNT NUMBER PREFERENCE------------------------------------------");
final String requestJSON = new AccountNumberPreferencesTestBuilder()
.clientBuild();
final String requestJSON = new AccountNumberPreferencesTestBuilder()
.clientBuild();
final String URL = ACCOUNT_NUMBER_FORMATS_REQUEST_URL + "?"
+ Utils.TENANT_IDENTIFIER;
final String URL = ACCOUNT_NUMBER_FORMATS_REQUEST_URL + "?"
+ Utils.TENANT_IDENTIFIER;
return Utils.performServerPost(this.requestSpec, responseSpec, URL,
requestJSON, jsonAttributeToGetBack);
}
return Utils.performServerPost(this.requestSpec, responseSpec, URL,
requestJSON, jsonAttributeToGetBack);
}
public Object createLoanAccountNumberPreference(
ResponseSpecification responseSpec, String jsonAttributeToGetBack) {
System.out
.println("---------------------------------CREATING LOAN ACCOUNT NUMBER PREFERENCE------------------------------------------");
public Object createLoanAccountNumberPreference(
ResponseSpecification responseSpec, String jsonAttributeToGetBack) {
System.out
.println("---------------------------------CREATING LOAN ACCOUNT NUMBER PREFERENCE------------------------------------------");
final String requestJSON = new AccountNumberPreferencesTestBuilder()
.loanBuild();
final String requestJSON = new AccountNumberPreferencesTestBuilder()
.loanBuild();
final String URL = ACCOUNT_NUMBER_FORMATS_REQUEST_URL + "?"
+ Utils.TENANT_IDENTIFIER;
return Utils.performServerPost(this.requestSpec, responseSpec, URL,
requestJSON, jsonAttributeToGetBack);
}
final String URL = ACCOUNT_NUMBER_FORMATS_REQUEST_URL + "?"
+ Utils.TENANT_IDENTIFIER;
return Utils.performServerPost(this.requestSpec, responseSpec, URL,
requestJSON, jsonAttributeToGetBack);
}
public Object createSavingsAccountNumberPreference(
ResponseSpecification responseSpec, String jsonAttributeToGetBack) {
System.out
.println("---------------------------------CREATING SAVINGS ACCOUNT NUMBER PREFERENCE------------------------------------------");
public Object createSavingsAccountNumberPreference(
ResponseSpecification responseSpec, String jsonAttributeToGetBack) {
System.out
.println("---------------------------------CREATING SAVINGS ACCOUNT NUMBER PREFERENCE------------------------------------------");
final String requestJSON = new AccountNumberPreferencesTestBuilder()
.savingsBuild();
final String requestJSON = new AccountNumberPreferencesTestBuilder()
.savingsBuild();
final String URL = ACCOUNT_NUMBER_FORMATS_REQUEST_URL + "?"
+ Utils.TENANT_IDENTIFIER;
return Utils.performServerPost(this.requestSpec, responseSpec, URL,
requestJSON, jsonAttributeToGetBack);
final String URL = ACCOUNT_NUMBER_FORMATS_REQUEST_URL + "?"
+ Utils.TENANT_IDENTIFIER;
return Utils.performServerPost(this.requestSpec, responseSpec, URL,
requestJSON, jsonAttributeToGetBack);
}
public Object createGroupsAccountNumberPreference(
ResponseSpecification responseSpec, String jsonAttributeToGetBack) {
System.out
.println("---------------------------------CREATING GROUPS ACCOUNT NUMBER PREFERENCE------------------------------------------");
}
public Object createGroupsAccountNumberPreference(
ResponseSpecification responseSpec, String jsonAttributeToGetBack) {
System.out
.println("---------------------------------CREATING GROUPS ACCOUNT NUMBER PREFERENCE------------------------------------------");
final String requestJSON = new AccountNumberPreferencesTestBuilder()
.groupsBuild();
final String requestJSON = new AccountNumberPreferencesTestBuilder()
.groupsBuild();
final String URL = ACCOUNT_NUMBER_FORMATS_REQUEST_URL + "?"
+ Utils.TENANT_IDENTIFIER;
return Utils.performServerPost(this.requestSpec, responseSpec, URL,
requestJSON, jsonAttributeToGetBack);
final String URL = ACCOUNT_NUMBER_FORMATS_REQUEST_URL + "?"
+ Utils.TENANT_IDENTIFIER;
return Utils.performServerPost(this.requestSpec, responseSpec, URL,
requestJSON, jsonAttributeToGetBack);
}
public Object createCenterAccountNumberPreference(
ResponseSpecification responseSpec, String jsonAttributeToGetBack) {
System.out
.println("---------------------------------CREATING CENTER ACCOUNT NUMBER PREFERENCE------------------------------------------");
}
public Object createCenterAccountNumberPreference(
ResponseSpecification responseSpec, String jsonAttributeToGetBack) {
System.out
.println("---------------------------------CREATING CENTER ACCOUNT NUMBER PREFERENCE------------------------------------------");
final String requestJSON = new AccountNumberPreferencesTestBuilder()
.centerBuild();
final String requestJSON = new AccountNumberPreferencesTestBuilder()
.centerBuild();
final String URL = ACCOUNT_NUMBER_FORMATS_REQUEST_URL + "?"
+ Utils.TENANT_IDENTIFIER;
return Utils.performServerPost(this.requestSpec, responseSpec, URL,
requestJSON, jsonAttributeToGetBack);
final String URL = ACCOUNT_NUMBER_FORMATS_REQUEST_URL + "?"
+ Utils.TENANT_IDENTIFIER;
return Utils.performServerPost(this.requestSpec, responseSpec, URL,
requestJSON, jsonAttributeToGetBack);
}
}
public HashMap<String, Object> createAccountNumberPreferenceWithInvalidData(
ResponseSpecification responseSpec, String accountType,
String prefixType, String jsonAttributeToGetBack) {
public HashMap<String, Object> createAccountNumberPreferenceWithInvalidData(
ResponseSpecification responseSpec, String accountType,
String prefixType, String jsonAttributeToGetBack) {
final String requestJSON = new AccountNumberPreferencesTestBuilder()
.invalidDataBuild(accountType, prefixType);
final String requestJSON = new AccountNumberPreferencesTestBuilder()
.invalidDataBuild(accountType, prefixType);
final String URL = ACCOUNT_NUMBER_FORMATS_REQUEST_URL + "?"
+ Utils.TENANT_IDENTIFIER;
return Utils.performServerPost(this.requestSpec, responseSpec, URL,
requestJSON, jsonAttributeToGetBack);
final String URL = ACCOUNT_NUMBER_FORMATS_REQUEST_URL + "?"
+ Utils.TENANT_IDENTIFIER;
return Utils.performServerPost(this.requestSpec, responseSpec, URL,
requestJSON, jsonAttributeToGetBack);
}
}
public HashMap<String, Object> updateAccountNumberPreference(
final Integer accountNumberFormatId, final String prefixType,
ResponseSpecification responseSpec, String jsonAttributeToGetBack) {
public HashMap<String, Object> updateAccountNumberPreference(
final Integer accountNumberFormatId, final String prefixType,
ResponseSpecification responseSpec, String jsonAttributeToGetBack) {
final String requestJSON = new AccountNumberPreferencesTestBuilder()
.updatePrefixType(prefixType);
final String requestJSON = new AccountNumberPreferencesTestBuilder()
.updatePrefixType(prefixType);
final String URL = ACCOUNT_NUMBER_FORMATS_REQUEST_URL + "/"
+ accountNumberFormatId + "?" + Utils.TENANT_IDENTIFIER;
final String URL = ACCOUNT_NUMBER_FORMATS_REQUEST_URL + "/"
+ accountNumberFormatId + "?" + Utils.TENANT_IDENTIFIER;
return Utils.performServerPut(this.requestSpec, responseSpec, URL,
requestJSON, jsonAttributeToGetBack);
return Utils.performServerPut(this.requestSpec, responseSpec, URL,
requestJSON, jsonAttributeToGetBack);
}
}
public HashMap<String, Object> deleteAccountNumberPreference(
final Integer accountNumberFormatId,
ResponseSpecification responseSpec, String jsonAttributeToGetBack) {
public HashMap<String, Object> deleteAccountNumberPreference(
final Integer accountNumberFormatId,
ResponseSpecification responseSpec, String jsonAttributeToGetBack) {
System.out
.println("---------------------------------DELETING ACCOUNT NUMBER PREFERENCE------------------------------------------");
System.out
.println("---------------------------------DELETING ACCOUNT NUMBER PREFERENCE------------------------------------------");
final String URL = ACCOUNT_NUMBER_FORMATS_REQUEST_URL + "/"
+ accountNumberFormatId + "?" + Utils.TENANT_IDENTIFIER;
final String URL = ACCOUNT_NUMBER_FORMATS_REQUEST_URL + "/"
+ accountNumberFormatId + "?" + Utils.TENANT_IDENTIFIER;
return Utils.performServerDelete(this.requestSpec, responseSpec, URL,
jsonAttributeToGetBack);
}
return Utils.performServerDelete(this.requestSpec, responseSpec, URL,
jsonAttributeToGetBack);
}
public Object getAccountNumberPreference(
final Integer accountNumberFormatId,
final String jsonAttributeToGetBack) {
final String URL = ACCOUNT_NUMBER_FORMATS_REQUEST_URL + "/"
+ accountNumberFormatId + "?" + Utils.TENANT_IDENTIFIER;
public Object getAccountNumberPreference(
final Integer accountNumberFormatId,
final String jsonAttributeToGetBack) {
final String URL = ACCOUNT_NUMBER_FORMATS_REQUEST_URL + "/"
+ accountNumberFormatId + "?" + Utils.TENANT_IDENTIFIER;
return Utils.performServerGet(requestSpec, responseSpec, URL,
jsonAttributeToGetBack);
}
return Utils.performServerGet(requestSpec, responseSpec, URL,
jsonAttributeToGetBack);
}
public ArrayList<HashMap<String, Object>> getAllAccountNumberPreferences() {
final String URL = ACCOUNT_NUMBER_FORMATS_REQUEST_URL + "?"
+ Utils.TENANT_IDENTIFIER;
final ArrayList<HashMap<String, Object>> response = Utils
.performServerGet(requestSpec, responseSpec, URL, "");
return response;
}
public ArrayList<HashMap<String, Object>> getAllAccountNumberPreferences() {
final String URL = ACCOUNT_NUMBER_FORMATS_REQUEST_URL + "?"
+ Utils.TENANT_IDENTIFIER;
final ArrayList<HashMap<String, Object>> response = Utils
.performServerGet(requestSpec, responseSpec, URL, "");
return response;
}
public void verifyCreationOfAccountNumberPreferences(
final Integer clientAccountNumberPreferenceId,
final Integer loanAccountNumberPreferenceId,
final Integer savingsAccountNumberPreferenceId,
final Integer groupsAccountNumberPreferenceId,
final Integer centerAccountNumberPreferenceId,
ResponseSpecification responseSpec, RequestSpecification requestSpec) {
public void verifyCreationOfAccountNumberPreferences(
final Integer clientAccountNumberPreferenceId,
final Integer loanAccountNumberPreferenceId,
final Integer savingsAccountNumberPreferenceId,
final Integer groupsAccountNumberPreferenceId,
final Integer centerAccountNumberPreferenceId,
ResponseSpecification responseSpec, RequestSpecification requestSpec) {
final String clientURL = ACCOUNT_NUMBER_FORMATS_REQUEST_URL + "/"
+ clientAccountNumberPreferenceId + "?"
+ Utils.TENANT_IDENTIFIER;
final String clientURL = ACCOUNT_NUMBER_FORMATS_REQUEST_URL + "/"
+ clientAccountNumberPreferenceId + "?"
+ Utils.TENANT_IDENTIFIER;
Utils.performServerGet(requestSpec, responseSpec, clientURL, "id");
Utils.performServerGet(requestSpec, responseSpec, clientURL, "id");
final String loanURL = ACCOUNT_NUMBER_FORMATS_REQUEST_URL + "/"
+ loanAccountNumberPreferenceId + "?" + Utils.TENANT_IDENTIFIER;
final String loanURL = ACCOUNT_NUMBER_FORMATS_REQUEST_URL + "/"
+ loanAccountNumberPreferenceId + "?" + Utils.TENANT_IDENTIFIER;
Utils.performServerGet(requestSpec, responseSpec, loanURL, "id");
Utils.performServerGet(requestSpec, responseSpec, loanURL, "id");
final String savingsURL = ACCOUNT_NUMBER_FORMATS_REQUEST_URL + "/"
+ savingsAccountNumberPreferenceId + "?"
+ Utils.TENANT_IDENTIFIER;
final String savingsURL = ACCOUNT_NUMBER_FORMATS_REQUEST_URL + "/"
+ savingsAccountNumberPreferenceId + "?"
+ Utils.TENANT_IDENTIFIER;
Utils.performServerGet(requestSpec, responseSpec, savingsURL, "id");
final String groupsURL = ACCOUNT_NUMBER_FORMATS_REQUEST_URL + "/"
+ groupsAccountNumberPreferenceId + "?"
+ Utils.TENANT_IDENTIFIER;
Utils.performServerGet(requestSpec, responseSpec, savingsURL, "id");
final String groupsURL = ACCOUNT_NUMBER_FORMATS_REQUEST_URL + "/"
+ groupsAccountNumberPreferenceId + "?"
+ Utils.TENANT_IDENTIFIER;
Utils.performServerGet(requestSpec, responseSpec, groupsURL, "id");
final String centerURL = ACCOUNT_NUMBER_FORMATS_REQUEST_URL + "/"
+ centerAccountNumberPreferenceId + "?"
+ Utils.TENANT_IDENTIFIER;
Utils.performServerGet(requestSpec, responseSpec, groupsURL, "id");
final String centerURL = ACCOUNT_NUMBER_FORMATS_REQUEST_URL + "/"
+ centerAccountNumberPreferenceId + "?"
+ Utils.TENANT_IDENTIFIER;
Utils.performServerGet(requestSpec, responseSpec, centerURL, "id");
}
Utils.performServerGet(requestSpec, responseSpec, centerURL, "id");
}
public void verifyUpdationOfAccountNumberPreferences(
final Integer accountNumberPreferenceId,
ResponseSpecification responseSpec, RequestSpecification requestSpec) {
public void verifyUpdationOfAccountNumberPreferences(
final Integer accountNumberPreferenceId,
ResponseSpecification responseSpec, RequestSpecification requestSpec) {
final String URL = ACCOUNT_NUMBER_FORMATS_REQUEST_URL + "/"
+ accountNumberPreferenceId + "?" + Utils.TENANT_IDENTIFIER;
Utils.performServerGet(requestSpec, responseSpec, URL, "id");
final String URL = ACCOUNT_NUMBER_FORMATS_REQUEST_URL + "/"
+ accountNumberPreferenceId + "?" + Utils.TENANT_IDENTIFIER;
Utils.performServerGet(requestSpec, responseSpec, URL, "id");
}
}
}
@@ -23,69 +23,69 @@ import java.util.HashMap;
import com.google.gson.Gson;
public class AccountNumberPreferencesTestBuilder {
private String clientAccountType = "1";
private String clientPrefixType = "101";
private String loanAccountType = "2";
private String loanPrefixType = "1";
private String savingsAccountType = "3";
private String savingsPrefixType = "1";
private String centerAccountType = "4";
private String centerPrefixType = "1";
private String groupsAccountType = "5";
private String groupsPrefixType = "1";
private String clientAccountType = "1";
private String clientPrefixType = "101";
private String loanAccountType = "2";
private String loanPrefixType = "1";
private String savingsAccountType = "3";
private String savingsPrefixType = "1";
private String centerAccountType = "4";
private String centerPrefixType = "1";
private String groupsAccountType = "5";
private String groupsPrefixType = "1";
public String clientBuild() {
final HashMap<String, Object> map = new HashMap<>();
map.put("accountType", clientAccountType);
map.put("prefixType", clientPrefixType);
public String clientBuild() {
final HashMap<String, Object> map = new HashMap<>();
map.put("accountType", clientAccountType);
map.put("prefixType", clientPrefixType);
return new Gson().toJson(map);
}
return new Gson().toJson(map);
}
public String loanBuild() {
final HashMap<String, Object> map = new HashMap<>();
map.put("accountType", loanAccountType);
map.put("prefixType", loanPrefixType);
public String loanBuild() {
final HashMap<String, Object> map = new HashMap<>();
map.put("accountType", loanAccountType);
map.put("prefixType", loanPrefixType);
return new Gson().toJson(map);
}
return new Gson().toJson(map);
}
public String savingsBuild() {
final HashMap<String, Object> map = new HashMap<>();
map.put("accountType", savingsAccountType);
map.put("prefixType", savingsPrefixType);
public String savingsBuild() {
final HashMap<String, Object> map = new HashMap<>();
map.put("accountType", savingsAccountType);
map.put("prefixType", savingsPrefixType);
return new Gson().toJson(map);
}
public String groupsBuild() {
final HashMap<String, Object> map = new HashMap<>();
map.put("accountType", groupsAccountType);
map.put("prefixType", groupsPrefixType);
return new Gson().toJson(map);
}
public String groupsBuild() {
final HashMap<String, Object> map = new HashMap<>();
map.put("accountType", groupsAccountType);
map.put("prefixType", groupsPrefixType);
return new Gson().toJson(map);
}
return new Gson().toJson(map);
}
public String centerBuild() {
final HashMap<String, Object> map = new HashMap<>();
map.put("accountType", centerAccountType);
map.put("prefixType", centerPrefixType);
public String centerBuild() {
final HashMap<String, Object> map = new HashMap<>();
map.put("accountType", centerAccountType);
map.put("prefixType", centerPrefixType);
return new Gson().toJson(map);
}
public String invalidDataBuild(String accountType, String prefixType) {
final HashMap<String, Object> map = new HashMap<>();
map.put("accountType", accountType);
map.put("prefixType", prefixType);
return new Gson().toJson(map);
}
public String invalidDataBuild(String accountType, String prefixType) {
final HashMap<String, Object> map = new HashMap<>();
map.put("accountType", accountType);
map.put("prefixType", prefixType);
return new Gson().toJson(map);
}
return new Gson().toJson(map);
}
public String updatePrefixType(final String prefixType) {
public String updatePrefixType(final String prefixType) {
final HashMap<String, Object> map = new HashMap<>();
map.put("prefixType", prefixType);
return new Gson().toJson(map);
}
final HashMap<String, Object> map = new HashMap<>();
map.put("prefixType", prefixType);
return new Gson().toJson(map);
}
}
@@ -33,221 +33,221 @@ import com.jayway.restassured.specification.ResponseSpecification;
public class CodeHelper {
public static final String CODE_ID_ATTRIBUTE_NAME = "id";
public static final String RESPONSE_ID_ATTRIBUTE_NAME = "resourceId";
public static final String SUBRESPONSE_ID_ATTRIBUTE_NAME = "subResourceId";
public static final String CODE_NAME_ATTRIBUTE_NAME = "name";
public static final String CODE_SYSTEM_DEFINED_ATTRIBUTE_NAME = "systemDefined";
public static final String CODE_URL = "/fineract-provider/api/v1/codes";
public static final String CODE_ID_ATTRIBUTE_NAME = "id";
public static final String RESPONSE_ID_ATTRIBUTE_NAME = "resourceId";
public static final String SUBRESPONSE_ID_ATTRIBUTE_NAME = "subResourceId";
public static final String CODE_NAME_ATTRIBUTE_NAME = "name";
public static final String CODE_SYSTEM_DEFINED_ATTRIBUTE_NAME = "systemDefined";
public static final String CODE_URL = "/fineract-provider/api/v1/codes";
public static final String CODE_VALUE_ID_ATTRIBUTE_NAME = "id";
public static final String CODE_VALUE_NAME_ATTRIBUTE_NAME = "name";
public static final String CODE_VALUE_DESCRIPTION_ATTRIBUTE_NAME = "description";
public static final String CODE_VALUE_POSITION_ATTRIBUTE_NAME = "position";
public static final String CODE_VALUE_URL = "/fineract-provider/api/v1/codes/[codeId]/codevalues";
public static final String CODE_VALUE_ID_ATTRIBUTE_NAME = "id";
public static final String CODE_VALUE_NAME_ATTRIBUTE_NAME = "name";
public static final String CODE_VALUE_DESCRIPTION_ATTRIBUTE_NAME = "description";
public static final String CODE_VALUE_POSITION_ATTRIBUTE_NAME = "position";
public static final String CODE_VALUE_URL = "/fineract-provider/api/v1/codes/[codeId]/codevalues";
public static Object createCode(final RequestSpecification requestSpec,
final ResponseSpecification responseSpec, final String codeName,
final String jsonAttributeToGetback) {
public static Object createCode(final RequestSpecification requestSpec,
final ResponseSpecification responseSpec, final String codeName,
final String jsonAttributeToGetback) {
return Utils.performServerPost(requestSpec, responseSpec, CODE_URL
+ "?" + Utils.TENANT_IDENTIFIER, getTestCodeAsJSON(codeName),
jsonAttributeToGetback);
}
return Utils.performServerPost(requestSpec, responseSpec, CODE_URL
+ "?" + Utils.TENANT_IDENTIFIER, getTestCodeAsJSON(codeName),
jsonAttributeToGetback);
}
public static Object updateCode(final RequestSpecification requestSpec,
final ResponseSpecification responseSpec, final Integer codeId,
final String codeName, final String jsonAttributeToGetback) {
public static Object updateCode(final RequestSpecification requestSpec,
final ResponseSpecification responseSpec, final Integer codeId,
final String codeName, final String jsonAttributeToGetback) {
return Utils.performServerPut(requestSpec, responseSpec, CODE_URL + "/"
+ codeId + "?" + Utils.TENANT_IDENTIFIER,
getTestCodeAsJSON(codeName), jsonAttributeToGetback);
}
return Utils.performServerPut(requestSpec, responseSpec, CODE_URL + "/"
+ codeId + "?" + Utils.TENANT_IDENTIFIER,
getTestCodeAsJSON(codeName), jsonAttributeToGetback);
}
public static Object getCodeById(final RequestSpecification requestSpec,
final ResponseSpecification responseSpec, final Integer codeId,
final String jsonAttributeToGetback) {
public static Object getCodeById(final RequestSpecification requestSpec,
final ResponseSpecification responseSpec, final Integer codeId,
final String jsonAttributeToGetback) {
return Utils.performServerGet(requestSpec, responseSpec, CODE_URL + "/"
+ codeId + "?" + Utils.TENANT_IDENTIFIER,
jsonAttributeToGetback);
return Utils.performServerGet(requestSpec, responseSpec, CODE_URL + "/"
+ codeId + "?" + Utils.TENANT_IDENTIFIER,
jsonAttributeToGetback);
}
}
public static HashMap<String, Object> getCodeByName(
final RequestSpecification requestSpec,
final ResponseSpecification responseSpec, final String codeName) {
public static HashMap<String, Object> getCodeByName(
final RequestSpecification requestSpec,
final ResponseSpecification responseSpec, final String codeName) {
final HashMap<String, Object> code = new HashMap<>();
final HashMap<String, Object> code = new HashMap<>();
ArrayList<HashMap<String, Object>> getAllCodes = CodeHelper
.getAllCodes(requestSpec, responseSpec);
for (HashMap<String, Object> map : getAllCodes) {
String name = (String) map.get("name");
if (name.equals(codeName)) {
code.put("id", map.get("id"));
code.put("name", map.get("name"));
code.put("systemDefined", map.get("systemDefined"));
break;
}
}
return code;
}
ArrayList<HashMap<String, Object>> getAllCodes = CodeHelper
.getAllCodes(requestSpec, responseSpec);
for (HashMap<String, Object> map : getAllCodes) {
String name = (String) map.get("name");
if (name.equals(codeName)) {
code.put("id", map.get("id"));
code.put("name", map.get("name"));
code.put("systemDefined", map.get("systemDefined"));
break;
}
}
return code;
}
public static HashMap<String, Object> retrieveOrCreateCodeValue(
Integer codeId, final RequestSpecification requestSpec,
final ResponseSpecification responseSpec) {
Integer codeValueId = null;
final List<HashMap<String, Object>> codeValuesList = CodeHelper
.getCodeValuesForCode(requestSpec, responseSpec, codeId, "");
/* If Code Values doesn't exist,then create Code value */
if (codeValuesList.size() == 0) {
final Integer codeValuePosition = 0;
final String codeValue = Utils.randomNameGenerator("", 3);
codeValueId = (Integer) CodeHelper.createCodeValue(requestSpec,
responseSpec, codeId, codeValue, codeValuePosition,
"subResourceId");
} else {
return codeValuesList.get(0);
}
return Utils.performServerGet(requestSpec, responseSpec,
CODE_VALUE_URL.replace("[codeId]", codeId.toString()) + "/"
+ codeValueId.toString() + "?"
+ Utils.TENANT_IDENTIFIER, "");
}
public static HashMap<String, Object> retrieveOrCreateCodeValue(
Integer codeId, final RequestSpecification requestSpec,
final ResponseSpecification responseSpec) {
Integer codeValueId = null;
final List<HashMap<String, Object>> codeValuesList = CodeHelper
.getCodeValuesForCode(requestSpec, responseSpec, codeId, "");
/* If Code Values doesn't exist,then create Code value */
if (codeValuesList.size() == 0) {
final Integer codeValuePosition = 0;
final String codeValue = Utils.randomNameGenerator("", 3);
codeValueId = (Integer) CodeHelper.createCodeValue(requestSpec,
responseSpec, codeId, codeValue, codeValuePosition,
"subResourceId");
} else {
return codeValuesList.get(0);
}
return Utils.performServerGet(requestSpec, responseSpec,
CODE_VALUE_URL.replace("[codeId]", codeId.toString()) + "/"
+ codeValueId.toString() + "?"
+ Utils.TENANT_IDENTIFIER, "");
}
public static ArrayList<HashMap<String, Object>> getAllCodes(
final RequestSpecification requestSpec,
final ResponseSpecification responseSpec) {
public static ArrayList<HashMap<String, Object>> getAllCodes(
final RequestSpecification requestSpec,
final ResponseSpecification responseSpec) {
return Utils.performServerGet(requestSpec, responseSpec, CODE_URL + "?"
+ Utils.TENANT_IDENTIFIER, "");
return Utils.performServerGet(requestSpec, responseSpec, CODE_URL + "?"
+ Utils.TENANT_IDENTIFIER, "");
}
}
public static Object getSystemDefinedCodes(
final RequestSpecification requestSpec,
final ResponseSpecification responseSpec) {
public static Object getSystemDefinedCodes(
final RequestSpecification requestSpec,
final ResponseSpecification responseSpec) {
final String getResponse = given().spec(requestSpec).expect()
.spec(responseSpec).when()
.get(CodeHelper.CODE_URL + "?" + Utils.TENANT_IDENTIFIER)
.asString();
final String getResponse = given().spec(requestSpec).expect()
.spec(responseSpec).when()
.get(CodeHelper.CODE_URL + "?" + Utils.TENANT_IDENTIFIER)
.asString();
final JsonPath getResponseJsonPath = new JsonPath(getResponse);
final JsonPath getResponseJsonPath = new JsonPath(getResponse);
// get any systemDefined code
return getResponseJsonPath.get("find { e -> e.systemDefined == true }");
// get any systemDefined code
return getResponseJsonPath.get("find { e -> e.systemDefined == true }");
}
}
public static String getTestCodeAsJSON(final String codeName) {
final HashMap<String, String> map = new HashMap<>();
map.put(CODE_NAME_ATTRIBUTE_NAME, codeName);
return new Gson().toJson(map);
}
public static String getTestCodeAsJSON(final String codeName) {
final HashMap<String, String> map = new HashMap<>();
map.put(CODE_NAME_ATTRIBUTE_NAME, codeName);
return new Gson().toJson(map);
}
public static String getTestCodeValueAsJSON(final String codeValueName,
final String description, final Integer position) {
final HashMap<String, Object> map = new HashMap<>();
map.put(CODE_VALUE_NAME_ATTRIBUTE_NAME, codeValueName);
if (description != null) {
map.put(CODE_VALUE_DESCRIPTION_ATTRIBUTE_NAME, description);
}
map.put(CODE_VALUE_POSITION_ATTRIBUTE_NAME, position);
return new Gson().toJson(map);
}
public static String getTestCodeValueAsJSON(final String codeValueName,
final String description, final Integer position) {
final HashMap<String, Object> map = new HashMap<>();
map.put(CODE_VALUE_NAME_ATTRIBUTE_NAME, codeValueName);
if (description != null) {
map.put(CODE_VALUE_DESCRIPTION_ATTRIBUTE_NAME, description);
}
map.put(CODE_VALUE_POSITION_ATTRIBUTE_NAME, position);
return new Gson().toJson(map);
}
public static Object deleteCodeById(final RequestSpecification requestSpec,
final ResponseSpecification responseSpec, final Integer codeId,
final String jsonAttributeToGetback) {
public static Object deleteCodeById(final RequestSpecification requestSpec,
final ResponseSpecification responseSpec, final Integer codeId,
final String jsonAttributeToGetback) {
return Utils.performServerDelete(requestSpec, responseSpec, CODE_URL
+ "/" + codeId + "?" + Utils.TENANT_IDENTIFIER,
jsonAttributeToGetback);
return Utils.performServerDelete(requestSpec, responseSpec, CODE_URL
+ "/" + codeId + "?" + Utils.TENANT_IDENTIFIER,
jsonAttributeToGetback);
}
}
public static Object createCodeValue(
final RequestSpecification requestSpec,
final ResponseSpecification responseSpec, final Integer codeId,
final String codeValueName, final Integer position,
final String jsonAttributeToGetback) {
String description = null;
return createCodeValue(requestSpec, responseSpec, codeId,
codeValueName, description, position, jsonAttributeToGetback);
}
public static Object createCodeValue(
final RequestSpecification requestSpec,
final ResponseSpecification responseSpec, final Integer codeId,
final String codeValueName, final Integer position,
final String jsonAttributeToGetback) {
String description = null;
return createCodeValue(requestSpec, responseSpec, codeId,
codeValueName, description, position, jsonAttributeToGetback);
}
public static Object createCodeValue(
final RequestSpecification requestSpec,
final ResponseSpecification responseSpec, final Integer codeId,
final String codeValueName, final String description,
final Integer position, final String jsonAttributeToGetback) {
public static Object createCodeValue(
final RequestSpecification requestSpec,
final ResponseSpecification responseSpec, final Integer codeId,
final String codeValueName, final String description,
final Integer position, final String jsonAttributeToGetback) {
return Utils.performServerPost(requestSpec, responseSpec,
CODE_VALUE_URL.replace("[codeId]", codeId.toString()) + "?"
+ Utils.TENANT_IDENTIFIER,
getTestCodeValueAsJSON(codeValueName, description, position),
jsonAttributeToGetback);
}
return Utils.performServerPost(requestSpec, responseSpec,
CODE_VALUE_URL.replace("[codeId]", codeId.toString()) + "?"
+ Utils.TENANT_IDENTIFIER,
getTestCodeValueAsJSON(codeValueName, description, position),
jsonAttributeToGetback);
}
public static List<HashMap<String, Object>> getCodeValuesForCode(
final RequestSpecification requestSpec,
final ResponseSpecification responseSpec, final Integer codeId,
final String jsonAttributeToGetback) {
public static List<HashMap<String, Object>> getCodeValuesForCode(
final RequestSpecification requestSpec,
final ResponseSpecification responseSpec, final Integer codeId,
final String jsonAttributeToGetback) {
return Utils.performServerGet(requestSpec, responseSpec,
CODE_VALUE_URL.replace("[codeId]", codeId.toString()) + "?"
+ Utils.TENANT_IDENTIFIER, jsonAttributeToGetback);
}
return Utils.performServerGet(requestSpec, responseSpec,
CODE_VALUE_URL.replace("[codeId]", codeId.toString()) + "?"
+ Utils.TENANT_IDENTIFIER, jsonAttributeToGetback);
}
public static Object getCodeValueById(
final RequestSpecification requestSpec,
final ResponseSpecification responseSpec, final Integer codeId,
final Integer codeValueId, final String jsonAttributeToGetback) {
public static Object getCodeValueById(
final RequestSpecification requestSpec,
final ResponseSpecification responseSpec, final Integer codeId,
final Integer codeValueId, final String jsonAttributeToGetback) {
return Utils.performServerGet(requestSpec, responseSpec,
CODE_VALUE_URL.replace("[codeId]", codeId.toString()) + "/"
+ codeValueId.toString() + "?"
+ Utils.TENANT_IDENTIFIER, jsonAttributeToGetback);
}
return Utils.performServerGet(requestSpec, responseSpec,
CODE_VALUE_URL.replace("[codeId]", codeId.toString()) + "/"
+ codeValueId.toString() + "?"
+ Utils.TENANT_IDENTIFIER, jsonAttributeToGetback);
}
public static Object deleteCodeValueById(
final RequestSpecification requestSpec,
final ResponseSpecification responseSpec, final Integer codeId,
final Integer codeValueId, final String jsonAttributeToGetback) {
public static Object deleteCodeValueById(
final RequestSpecification requestSpec,
final ResponseSpecification responseSpec, final Integer codeId,
final Integer codeValueId, final String jsonAttributeToGetback) {
return Utils.performServerDelete(requestSpec, responseSpec,
CODE_VALUE_URL.replace("[codeId]", codeId.toString()) + "/"
+ codeValueId.toString() + "?"
+ Utils.TENANT_IDENTIFIER, jsonAttributeToGetback);
}
return Utils.performServerDelete(requestSpec, responseSpec,
CODE_VALUE_URL.replace("[codeId]", codeId.toString()) + "/"
+ codeValueId.toString() + "?"
+ Utils.TENANT_IDENTIFIER, jsonAttributeToGetback);
}
public static Object updateCodeValue(
final RequestSpecification requestSpec,
final ResponseSpecification responseSpec, final Integer codeId,
final Integer codeValueId, final String codeValueName,
final Integer position, final String jsonAttributeToGetback) {
String description = null;
return updateCodeValue(requestSpec, responseSpec, codeId, codeValueId,
codeValueName, description, position, jsonAttributeToGetback);
}
public static Object updateCodeValue(
final RequestSpecification requestSpec,
final ResponseSpecification responseSpec, final Integer codeId,
final Integer codeValueId, final String codeValueName,
final Integer position, final String jsonAttributeToGetback) {
String description = null;
return updateCodeValue(requestSpec, responseSpec, codeId, codeValueId,
codeValueName, description, position, jsonAttributeToGetback);
}
public static Object updateCodeValue(
final RequestSpecification requestSpec,
final ResponseSpecification responseSpec, final Integer codeId,
final Integer codeValueId, final String codeValueName,
final String description, final Integer position,
final String jsonAttributeToGetback) {
public static Object updateCodeValue(
final RequestSpecification requestSpec,
final ResponseSpecification responseSpec, final Integer codeId,
final Integer codeValueId, final String codeValueName,
final String description, final Integer position,
final String jsonAttributeToGetback) {
return Utils.performServerPut(requestSpec, responseSpec,
CODE_VALUE_URL.replace("[codeId]", codeId.toString()) + "/"
+ codeValueId + "?" + Utils.TENANT_IDENTIFIER,
getTestCodeValueAsJSON(codeValueName, description, position),
jsonAttributeToGetback);
}
return Utils.performServerPut(requestSpec, responseSpec,
CODE_VALUE_URL.replace("[codeId]", codeId.toString()) + "/"
+ codeValueId + "?" + Utils.TENANT_IDENTIFIER,
getTestCodeValueAsJSON(codeValueName, description, position),
jsonAttributeToGetback);
}
}
@@ -45,12 +45,12 @@ import org.springframework.context.annotation.Import;
*/
public class ServerApplication {
@Import({ DataSourceConfiguration.class, EmbeddedTomcatWithSSLConfiguration.class })
private static class Configuration extends AbstractApplicationConfiguration { }
@Import({ DataSourceConfiguration.class, EmbeddedTomcatWithSSLConfiguration.class })
private static class Configuration extends AbstractApplicationConfiguration { }
public static void main(String[] args) throws Exception {
ConfigurableApplicationContext ctx = SpringApplication.run(Configuration.class, args);
ApplicationExitUtil.waitForKeyPressToCleanlyExit(ctx);
}
public static void main(String[] args) throws Exception {
ConfigurableApplicationContext ctx = SpringApplication.run(Configuration.class, args);
ApplicationExitUtil.waitForKeyPressToCleanlyExit(ctx);
}
}
@@ -49,57 +49,57 @@ import org.springframework.core.io.Resource;
public class ServerWithMariaDB4jApplication {
private final static Logger logger = LoggerFactory.getLogger(ServerWithMariaDB4jApplication.class);
@Import({ MariaDB4jDataSourceConfiguration.class, EmbeddedTomcatWithSSLConfiguration.class })
public static class Configuration extends AbstractApplicationConfiguration { }
@Import({ MariaDB4jDataSourceConfiguration.class, EmbeddedTomcatWithSSLConfiguration.class })
public static class Configuration extends AbstractApplicationConfiguration { }
public static void main(String[] args) throws Exception {
ConfigurableApplicationContext ctx = SpringApplication.run(Configuration.class, args);
if (!Desktop.isDesktopSupported()) {
logger.info("Not going to open UI homepage in local web browser, because !Desktop.isDesktopSupported()");
public static void main(String[] args) throws Exception {
ConfigurableApplicationContext ctx = SpringApplication.run(Configuration.class, args);
if (!Desktop.isDesktopSupported()) {
logger.info("Not going to open UI homepage in local web browser, because !Desktop.isDesktopSupported()");
} else {
// apps/community-app/dist/community-app/index.html
Resource distResource = ctx.getResource("file:" + System.getProperty("user.dir") +
System.getProperty("file.separator") + "apps" +
System.getProperty("file.separator") + "community-app" +
System.getProperty("file.separator") + "dist" +
System.getProperty("file.separator") + "community-app" +
System.getProperty("file.separator") + "index.html");
URI distURI = URI.create("https://localhost:8443/fineract-provider" +
"/apps/community-app/index.html?baseApiUrl=https://localhost:8443" +
"&tenantIdentifier=default#/");
} else {
// apps/community-app/dist/community-app/index.html
Resource distResource = ctx.getResource("file:" + System.getProperty("user.dir") +
System.getProperty("file.separator") + "apps" +
System.getProperty("file.separator") + "community-app" +
System.getProperty("file.separator") + "dist" +
System.getProperty("file.separator") + "community-app" +
System.getProperty("file.separator") + "index.html");
URI distURI = URI.create("https://localhost:8443/fineract-provider" +
"/apps/community-app/index.html?baseApiUrl=https://localhost:8443" +
"&tenantIdentifier=default#/");
// apps/community-app/app/index.html
Resource devResource = ctx.getResource("file:" + System.getProperty("user.dir") +
System.getProperty("file.separator") + "apps" +
System.getProperty("file.separator") + "community-app" +
System.getProperty("file.separator") + "app" +
System.getProperty("file.separator") + "index.html");
URI devURI = URI.create("https://localhost:8443/fineract-provider" +
"/apps/community-app/app/index.html?baseApiUrl=https://localhost:8443" +
"&tenantIdentifier=default#/");
// apps/community-app/app/index.html
Resource devResource = ctx.getResource("file:" + System.getProperty("user.dir") +
System.getProperty("file.separator") + "apps" +
System.getProperty("file.separator") + "community-app" +
System.getProperty("file.separator") + "app" +
System.getProperty("file.separator") + "index.html");
URI devURI = URI.create("https://localhost:8443/fineract-provider" +
"/apps/community-app/app/index.html?baseApiUrl=https://localhost:8443" +
"&tenantIdentifier=default#/");
if (distResource.exists()) {
openWebBrowser(distURI);
} else if (devResource.exists()) {
openWebBrowser(devURI);
} else {
logger.error("Cannot open Fineract UI in browser; not found: " + distResource.toString());
}
}
// TODO Tray Icon stuff; dig out my very own old @see https://github.com/mifos/head/tree/hudsonBuild-MIFOS-5157_Launch4j-EXE_NewDist-squash1/server-jetty/src/main/java/org/mifos/server/tray
ApplicationExitUtil.waitForKeyPressToCleanlyExit(ctx);
}
if (distResource.exists()) {
openWebBrowser(distURI);
} else if (devResource.exists()) {
openWebBrowser(devURI);
} else {
logger.error("Cannot open Fineract UI in browser; not found: " + distResource.toString());
}
}
// TODO Tray Icon stuff; dig out my very own old @see https://github.com/mifos/head/tree/hudsonBuild-MIFOS-5157_Launch4j-EXE_NewDist-squash1/server-jetty/src/main/java/org/mifos/server/tray
ApplicationExitUtil.waitForKeyPressToCleanlyExit(ctx);
}
private static void openWebBrowser(URI uri) {
try {
logger.info("Opening Fineract UI in browser: " + uri.toString());
Desktop.getDesktop().browse(uri);
} catch (IOException e) {
logger.error("IOException when opening Fineract UI in browser: " + uri.toString(), e);
}
}
private static void openWebBrowser(URI uri) {
try {
logger.info("Opening Fineract UI in browser: " + uri.toString());
Desktop.getDesktop().browse(uri);
} catch (IOException e) {
logger.error("IOException when opening Fineract UI in browser: " + uri.toString(), e);
}
}
}
@@ -54,9 +54,9 @@ import com.google.gson.reflect.TypeToken;
public final class AccrualAccountingDataValidator {
private final FromJsonHelper fromApiJsonHelper;
private static final Set<String> LOAN_PERIODIC_REQUEST_DATA_PARAMETERS = new HashSet<>(
Arrays.asList(accrueTillParamName, AccrualAccountingConstants.localeParamName,
AccrualAccountingConstants.dateFormatParamName));
private static final Set<String> LOAN_PERIODIC_REQUEST_DATA_PARAMETERS = new HashSet<>(
Arrays.asList(accrueTillParamName, AccrualAccountingConstants.localeParamName,
AccrualAccountingConstants.dateFormatParamName));
@Autowired
public AccrualAccountingDataValidator(final FromJsonHelper fromApiJsonfromApiJsonHelper) {
@@ -246,7 +246,7 @@ public class AccountingConstants {
private static List<FinancialActivityData> financialActivities;
static {
financialActivities = new ArrayList<>();
financialActivities = new ArrayList<>();
for (final FINANCIAL_ACTIVITY type : FINANCIAL_ACTIVITY.values()) {
FinancialActivityData financialActivityData = convertToFinancialActivityData(type);
financialActivities.add(financialActivityData);
@@ -23,13 +23,13 @@ import java.util.HashSet;
import java.util.Set;
public class FinancialActivityAccountsConstants {
private static final String idParamName = "id";
private static final String factivityDataParamName = "financialActivityData";
private static final String glAccountDataParamName = "glAccountData";
private static final String glAccountOptionsParamName = "glAccountOptions";
private static final String financialActivityOptionsParamName = "financialActivityOptions";
private static final String idParamName = "id";
private static final String factivityDataParamName = "financialActivityData";
private static final String glAccountDataParamName = "glAccountData";
private static final String glAccountOptionsParamName = "glAccountOptions";
private static final String financialActivityOptionsParamName = "financialActivityOptions";
public static final String resourceNameForPermission = "FINANCIALACTIVITYACCOUNT";
protected static final Set<String> RESPONSE_DATA_PARAMETERS = new HashSet<>(
Arrays.asList(idParamName, factivityDataParamName, glAccountDataParamName, glAccountOptionsParamName,
financialActivityOptionsParamName));
protected static final Set<String> RESPONSE_DATA_PARAMETERS = new HashSet<>(
Arrays.asList(idParamName, factivityDataParamName, glAccountDataParamName, glAccountOptionsParamName,
financialActivityOptionsParamName));
}
@@ -82,8 +82,8 @@ public class FinancialActivityAccountWritePlatformServiceImpl implements Financi
handleFinancialActivityAccountDataIntegrityIssues(command, dataIntegrityViolationException.getMostSpecificCause(), dataIntegrityViolationException);
return CommandProcessingResult.empty();
}catch(final PersistenceException ee) {
Throwable throwable = ExceptionUtils.getRootCause(ee.getCause()) ;
handleFinancialActivityAccountDataIntegrityIssues(command, throwable, ee);
Throwable throwable = ExceptionUtils.getRootCause(ee.getCause()) ;
handleFinancialActivityAccountDataIntegrityIssues(command, throwable, ee);
return CommandProcessingResult.empty();
}
}
@@ -132,9 +132,9 @@ public class FinancialActivityAccountWritePlatformServiceImpl implements Financi
handleFinancialActivityAccountDataIntegrityIssues(command, dataIntegrityViolationException.getMostSpecificCause(), dataIntegrityViolationException);
return CommandProcessingResult.empty();
}catch(final PersistenceException ee) {
Throwable throwable = ExceptionUtils.getRootCause(ee.getCause()) ;
handleFinancialActivityAccountDataIntegrityIssues(command, throwable, ee);
return CommandProcessingResult.empty();
Throwable throwable = ExceptionUtils.getRootCause(ee.getCause()) ;
handleFinancialActivityAccountDataIntegrityIssues(command, throwable, ee);
return CommandProcessingResult.empty();
}
}
@@ -16,7 +16,7 @@
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.accounting.glaccount.domain;
@@ -26,10 +26,10 @@ import org.apache.fineract.infrastructure.core.exception.AbstractPlatformDomainR
* disable the gl account
*/
public class GLAccountDisableException extends
AbstractPlatformDomainRuleException {
AbstractPlatformDomainRuleException {
public GLAccountDisableException() {
super("error.msg.glaccount.attached.to.product",
"General Ledger Account is already attached to product.");
}
public GLAccountDisableException() {
super("error.msg.glaccount.attached.to.product",
"General Ledger Account is already attached to product.");
}
}
@@ -121,13 +121,13 @@ public class GLAccountWritePlatformServiceJpaRepositoryImpl implements GLAccount
try {
final GLAccountCommand accountCommand = this.fromApiJsonDeserializer.commandFromApiJson(command.json());
accountCommand.validateForUpdate();
if (command.hasParameter(GLAccountJsonInputParams.DISABLED
.getValue())
&& command
.booleanPrimitiveValueOfParameterNamed(GLAccountJsonInputParams.DISABLED
.getValue())) {
validateForAttachedProduct(glAccountId);
}
if (command.hasParameter(GLAccountJsonInputParams.DISABLED
.getValue())
&& command
.booleanPrimitiveValueOfParameterNamed(GLAccountJsonInputParams.DISABLED
.getValue())) {
validateForAttachedProduct(glAccountId);
}
final Long parentId = command.longValueOfParameterNamed(GLAccountJsonInputParams.PARENT_ID.getValue());
if (glAccountId.equals(parentId)) { throw new InvalidParentGLAccountHeadException(glAccountId, parentId); }
// is the glAccount valid
@@ -178,17 +178,17 @@ public class GLAccountWritePlatformServiceJpaRepositoryImpl implements GLAccount
}
private void validateForAttachedProduct(Long glAccountId) {
String sql = "select count(*) from acc_product_mapping acc where acc.gl_account_id = ?";
try {
int count = this.jdbcTemplate.queryForObject(sql, Integer.class, glAccountId);
if (count > 0) {
throw new GLAccountDisableException();
}
} catch (EmptyResultDataAccessException e) {
}
}
String sql = "select count(*) from acc_product_mapping acc where acc.gl_account_id = ?";
try {
int count = this.jdbcTemplate.queryForObject(sql, Integer.class, glAccountId);
if (count > 0) {
throw new GLAccountDisableException();
}
} catch (EmptyResultDataAccessException e) {
}
}
@Transactional
@Transactional
@Override
public CommandProcessingResult deleteGLAccount(final Long glAccountId) {
final GLAccount glAccount = this.glAccountRepository.findById(glAccountId)
@@ -145,7 +145,7 @@ public class CashBasedAccountingProcessorForSavings implements AccountingProcess
else if (savingsTransactionDTO.getTransactionType().isEscheat()) {
this.helper.createCashBasedJournalEntriesAndReversalsForSavings(office, currencyCode,
CASH_ACCOUNTS_FOR_SAVINGS.SAVINGS_CONTROL.getValue(), CASH_ACCOUNTS_FOR_SAVINGS.ESCHEAT_LIABILITY.getValue(),
CASH_ACCOUNTS_FOR_SAVINGS.SAVINGS_CONTROL.getValue(), CASH_ACCOUNTS_FOR_SAVINGS.ESCHEAT_LIABILITY.getValue(),
savingsProductId, paymentTypeId, savingsId, transactionId, transactionDate, amount, isReversal);
}
/**
@@ -125,7 +125,7 @@ public class CashBasedAccountingProcessorForShares implements AccountingProcesso
transactionId, transactionDate, amount);
}else{
this.helper.createJournalEntriesForShares(office, currencyCode, CASH_ACCOUNTS_FOR_SHARES.SHARES_SUSPENSE.getValue(),
this.helper.createJournalEntriesForShares(office, currencyCode, CASH_ACCOUNTS_FOR_SHARES.SHARES_SUSPENSE.getValue(),
CASH_ACCOUNTS_FOR_SHARES.SHARES_REFERENCE.getValue(), shareProductId, paymentTypeId, shareAccountId, transactionId,
transactionDate, amount);
}
@@ -138,7 +138,7 @@ public class JournalEntryRunningBalanceUpdateServiceImpl implements JournalEntry
List<Map<String, Object>> list = jdbcTemplate.queryForList(organizationRunningBalanceSql, entityDate, entityDate);
for (Map<String, Object> entries : list) {
Long accountId = Long.parseLong(entries.get("accountId").toString()); //Drizzle is returning Big Integer where as MySQL returns Long.
Long accountId = Long.parseLong(entries.get("accountId").toString()); //Drizzle is returning Big Integer where as MySQL returns Long.
if (!runningBalanceMap.containsKey(accountId)) {
runningBalanceMap.put(accountId, (BigDecimal) entries.get("runningBalance"));
}
@@ -168,7 +168,7 @@ public class JournalEntryRunningBalanceUpdateServiceImpl implements JournalEntry
ArrayList<String> updateSql = new ArrayList<>();
int batchIndex = 0;
for (int index = 0 ; index < entryDatas.size() ; index++) {
JournalEntryData entryData = entryDatas.get(index) ;
JournalEntryData entryData = entryDatas.get(index) ;
Map<Long, BigDecimal> officeRunningBalanceMap = null;
if (officesRunningBalance.containsKey(entryData.getOfficeId())) {
officeRunningBalanceMap = officesRunningBalance.get(entryData.getOfficeId());
@@ -184,8 +184,8 @@ public class JournalEntryRunningBalanceUpdateServiceImpl implements JournalEntry
batchIndex++ ;
if (batchIndex == batchUpdateSize || index == entryDatas.size()-1) {
// run a batch update of the 1000 update SQL statements
String[] batch = new String[updateSql.size()] ;
updateSql.toArray(batch) ;
String[] batch = new String[updateSql.size()] ;
updateSql.toArray(batch) ;
this.jdbcTemplate.batchUpdate(batch);
// reset counter and string array
batchIndex = 0;
@@ -249,9 +249,9 @@ public class JournalEntryWritePlatformServiceJpaRepositoryImpl implements Journa
}
}
}
if (credits.length != validCredits.length) {
throw new JournalEntryRuntimeException("error.msg.glJournalEntry.invalid.credits", "Invalid Credits.");
}
if (credits.length != validCredits.length) {
throw new JournalEntryRuntimeException("error.msg.glJournalEntry.invalid.credits", "Invalid Credits.");
}
}
if (debits != null && debits.length > 0) {
@@ -264,11 +264,11 @@ public class JournalEntryWritePlatformServiceJpaRepositoryImpl implements Journa
validDebits[i] = debit;
}
}
}
if (debits.length != validDebits.length) {
throw new JournalEntryRuntimeException("error.msg.glJournalEntry.invalid.debits","Invalid Debits");
}
}
}
if (debits.length != validDebits.length) {
throw new JournalEntryRuntimeException("error.msg.glJournalEntry.invalid.debits","Invalid Debits");
}
}
}
private void checkDebitAndCreditAmounts(final SingleDebitOrCreditEntryCommand[] credits, final SingleDebitOrCreditEntryCommand[] debits) {
@@ -68,8 +68,8 @@ public class ProvisioningEntriesApiResource {
private final DefaultToApiJsonSerializer<Object> entriesApiJsonSerializer;
private final ProvisioningEntriesReadPlatformService provisioningEntriesReadPlatformService;
private final ApiRequestParameterHelper apiRequestParameterHelper;
private static final Set<String> PROVISIONING_ENTRY_PARAMETERS = new HashSet<>(Arrays.asList(
ProvisioningEntriesApiConstants.PROVISIONINGENTRY_PARAM, ProvisioningEntriesApiConstants.ENTRIES_PARAM));
private static final Set<String> PROVISIONING_ENTRY_PARAMETERS = new HashSet<>(Arrays.asList(
ProvisioningEntriesApiConstants.PROVISIONINGENTRY_PARAM, ProvisioningEntriesApiConstants.ENTRIES_PARAM));
private static final Set<String> ALL_PROVISIONING_ENTRIES = new HashSet<>(Arrays.asList
(ProvisioningEntriesApiConstants.PROVISIONINGENTRY_PARAM));
@Autowired
@@ -95,50 +95,50 @@ public class LoanProductProvisioningEntry extends AbstractPersistableCustom<Long
}
public BigDecimal getReservedAmount() {
return this.reservedAmount;
return this.reservedAmount;
}
public void addReservedAmount(BigDecimal value) {
this.reservedAmount = this.reservedAmount.add(value);
this.reservedAmount = this.reservedAmount.add(value);
}
public Office getOffice() {
return this.office;
}
return this.office;
}
public GLAccount getLiabilityAccount() {
return this.liabilityAccount;
}
public GLAccount getLiabilityAccount() {
return this.liabilityAccount;
}
public String getCurrencyCode() {
return this.currencyCode;
}
public String getCurrencyCode() {
return this.currencyCode;
}
public GLAccount getExpenseAccount() {
return this.expenseAccount;
}
public GLAccount getExpenseAccount() {
return this.expenseAccount;
}
// TODO Note that this domain class does equals() & hashCode() on getId() for @JoinColumn attributes, which not all other classes do...
// TODO Note that this domain class does equals() & hashCode() on getId() for @JoinColumn attributes, which not all other classes do...
@Override
public boolean equals(Object obj) {
if (!obj.getClass().equals(getClass())) return false;
LoanProductProvisioningEntry other = (LoanProductProvisioningEntry) obj;
return Objects.equals(other.entry.getId(), this.entry.getId())
&& Objects.equals(other.criteriaId, this.criteriaId)
&& Objects.equals(other.office.getId(), this.office.getId())
&& Objects.equals(other.currencyCode, this.currencyCode)
&& Objects.equals(other.loanProduct.getId(), this.loanProduct.getId())
&& Objects.equals(other.criteriaId, this.criteriaId)
&& Objects.equals(other.office.getId(), this.office.getId())
&& Objects.equals(other.currencyCode, this.currencyCode)
&& Objects.equals(other.loanProduct.getId(), this.loanProduct.getId())
&& Objects.equals(other.provisioningCategory.getId(), this.provisioningCategory.getId())
&& Objects.equals(other.overdueInDays, this.overdueInDays)
&& Objects.equals(other.reservedAmount, this.reservedAmount)
&& Objects.equals(other.liabilityAccount.getId(), this.liabilityAccount.getId())
&& Objects.equals(other.expenseAccount.getId(), this.expenseAccount.getId());
&& Objects.equals(other.liabilityAccount.getId(), this.liabilityAccount.getId())
&& Objects.equals(other.expenseAccount.getId(), this.expenseAccount.getId());
}
@Override
public int hashCode() {
// NOT return Objects.hash(entry, criteriaId, office, currencyCode, loanProduct, provisioningCategory, overdueInDays, reservedAmount, liabilityAccount, expenseAccount);
// to remain consistent with the implementation in equals(), also use getId() here.
return Objects.hash(entry.getId(), criteriaId, office.getId(), currencyCode, loanProduct.getId(), provisioningCategory.getId(), overdueInDays, reservedAmount, liabilityAccount.getId(), expenseAccount.getId());
// to remain consistent with the implementation in equals(), also use getId() here.
return Objects.hash(entry.getId(), criteriaId, office.getId(), currencyCode, loanProduct.getId(), provisioningCategory.getId(), overdueInDays, reservedAmount, liabilityAccount.getId(), expenseAccount.getId());
}
}
@@ -27,7 +27,7 @@ import org.springframework.data.repository.query.Param;
public interface ProvisioningEntryRepository extends JpaRepository<ProvisioningEntry, Long>, JpaSpecificationExecutor<ProvisioningEntry> {
//OPENJPA throws error if we use entry
//OPENJPA throws error if we use entry
@Query("select entry1 from ProvisioningEntry entry1 where entry1.createdDate = :createdDate")
ProvisioningEntry findByProvisioningEntryDate(@Param("createdDate") Date createdDate);
@@ -46,8 +46,8 @@ import com.google.gson.reflect.TypeToken;
public class ProvisioningEntriesDefinitionJsonDeserializer implements ProvisioningEntriesApiConstants {
private final FromJsonHelper fromApiJsonHelper;
private static final Set<String> supportedParameters = new HashSet<>(
Arrays.asList(JSON_DATE_PARAM, JSON_DATEFORMAT_PARAM, JSON_LOCALE_PARAM, JSON_CREATEJOURNALENTRIES_PARAM));
private static final Set<String> supportedParameters = new HashSet<>(
Arrays.asList(JSON_DATE_PARAM, JSON_DATEFORMAT_PARAM, JSON_LOCALE_PARAM, JSON_CREATEJOURNALENTRIES_PARAM));
@Autowired
@@ -87,7 +87,7 @@ public class AdHocApiResource {
@Consumes({ MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_JSON })
public String retrieveAll(@Context final UriInfo uriInfo) {
this.context.authenticatedUser();
final Collection<AdHocData> adhocs = this.adHocReadPlatformService.retrieveAllAdHocQuery();
final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters());
@@ -34,31 +34,31 @@ public class AdHocData {
@SuppressWarnings("unused")
@SuppressWarnings("unused")
private final Long id;
@SuppressWarnings("unused")
private final String name;
@SuppressWarnings("unused")
@SuppressWarnings("unused")
private final String query;
@SuppressWarnings("unused")
@SuppressWarnings("unused")
private final String tableName;
@SuppressWarnings("unused")
@SuppressWarnings("unused")
private final String tableFields;
@SuppressWarnings("unused")
private final String email;
@SuppressWarnings("unused")
@SuppressWarnings("unused")
private final String email;
@SuppressWarnings("unused")
private final boolean isActive;
@SuppressWarnings("unused")
@SuppressWarnings("unused")
private final DateTime createdOn;
@SuppressWarnings("unused")
private final Long createdById;
@SuppressWarnings("unused")
@SuppressWarnings("unused")
private final Long createdById;
@SuppressWarnings("unused")
private final Long updatedById;
@SuppressWarnings("unused")
@SuppressWarnings("unused")
private final DateTime updatedOn;
@SuppressWarnings("unused")
private final String createdBy;
@SuppressWarnings("unused")
private final String createdBy;
private final List<EnumOptionData> reportRunFrequencies;
private final Long reportRunFrequency;
@@ -84,65 +84,65 @@ public class AdHocData {
this.updatedOn=updatedOn;
this.createdBy=createdBy;
this.email=email;
this.reportRunFrequencies = reportRunFrequencies;
this.reportRunFrequency = reportRunFrequency;
this.reportRunEvery = reportRunEvery;
this.lastRun = lastRun;
this.reportRunFrequencies = reportRunFrequencies;
this.reportRunFrequency = reportRunFrequency;
this.reportRunEvery = reportRunEvery;
this.lastRun = lastRun;
}
public static AdHocData template() {
List<EnumOptionData> reportRunFrequencies = Arrays.stream(ReportRunFrequency.values()).map(rrf -> new EnumOptionData(
(long) rrf.getValue(), rrf.getCode(), rrf.getCode()
)).collect(Collectors.toList());
List<EnumOptionData> reportRunFrequencies = Arrays.stream(ReportRunFrequency.values()).map(rrf -> new EnumOptionData(
(long) rrf.getValue(), rrf.getCode(), rrf.getCode()
)).collect(Collectors.toList());
AdHocData adHocData = new AdHocData(null,null,null,null,null,false,null,null,null,null,null,null, reportRunFrequencies, null, null, null);
return adHocData;
AdHocData adHocData = new AdHocData(null,null,null,null,null,false,null,null,null,null,null,null, reportRunFrequencies, null, null, null);
return adHocData;
}
public Long getId() {
return this.id;
}
public String getName() {
return this.name;
}
public String getQuery() {
return this.query;
}
public String getTableName() {
return this.tableName;
}
public String getTableFields() {
return this.tableFields;
}
public String getEmail() {
return this.email;
}
public boolean isActive() {
return this.isActive;
}
public DateTime getCreatedOn() {
return this.createdOn;
}
public Long getCreatedById() {
return this.createdById;
}
public Long getUpdatedById() {
return this.updatedById;
}
public DateTime getUpdatedOn() {
return this.updatedOn;
}
public String getCreatedBy() {
return this.createdBy;
}
public List<EnumOptionData> getReportRunFrequencies() {
return this.reportRunFrequencies;
}
public Long getReportRunFrequency() {
return this.reportRunFrequency;
}
public Long getReportRunEvery() {
return this.reportRunEvery;
}
public DateTime getLastRun() {
return this.lastRun;
}
return this.id;
}
public String getName() {
return this.name;
}
public String getQuery() {
return this.query;
}
public String getTableName() {
return this.tableName;
}
public String getTableFields() {
return this.tableFields;
}
public String getEmail() {
return this.email;
}
public boolean isActive() {
return this.isActive;
}
public DateTime getCreatedOn() {
return this.createdOn;
}
public Long getCreatedById() {
return this.createdById;
}
public Long getUpdatedById() {
return this.updatedById;
}
public DateTime getUpdatedOn() {
return this.updatedOn;
}
public String getCreatedBy() {
return this.createdBy;
}
public List<EnumOptionData> getReportRunFrequencies() {
return this.reportRunFrequencies;
}
public Long getReportRunFrequency() {
return this.reportRunFrequency;
}
public Long getReportRunEvery() {
return this.reportRunEvery;
}
public DateTime getLastRun() {
return this.lastRun;
}
}
@@ -38,19 +38,19 @@ import org.apache.fineract.useradministration.domain.AppUser;
@Table(name = "m_adhoc")
public class AdHoc extends AbstractAuditableCustom<AppUser, Long> {
@Column(name = "name", length = 100)
@Column(name = "name", length = 100)
private String name;
@Column(name = "query", length = 2000)
private String query;
@Column(name = "table_name", length = 100)
private String tableName;
@Column(name = "table_fields", length = 2000)
private String tableFields;
@Column(name = "email", length = 500)
private String email;
@@ -60,9 +60,9 @@ public class AdHoc extends AbstractAuditableCustom<AppUser, Long> {
@Column(name = "report_run_every")
private Long reportRunEvery;
@Column(name = "IsActive", nullable = false)
@Column(name = "IsActive", nullable = false)
private boolean isActive = false;
private AdHoc(final String name, final String query,final String tableName,final String tableFields ,final String email, final Long reportRunFrequency, final Long reportRunEvery, final boolean isActive) {
this.name = StringUtils.defaultIfEmpty(name, null);
this.query=StringUtils.defaultIfEmpty(query,null);
@@ -139,7 +139,7 @@ public class AdHoc extends AbstractAuditableCustom<AppUser, Long> {
}
final String paramisActive = "isActive";
if (command.isChangeInBooleanParameterNamed(paramisActive, this.isActive)) {
final Boolean newValue = command.booleanObjectValueOfParameterNamed(paramisActive);
final Boolean newValue = command.booleanObjectValueOfParameterNamed(paramisActive);
actualChanges.put(paramisActive, newValue);
this.isActive = newValue;
}
@@ -147,28 +147,28 @@ public class AdHoc extends AbstractAuditableCustom<AppUser, Long> {
}
public String getName() {
return name;
}
public String getQuery() {
return query;
}
public String getTableName() {
return tableName;
}
public String getTableFields() {
return tableFields;
}
return name;
}
public String getQuery() {
return query;
}
public String getTableName() {
return tableName;
}
public String getTableFields() {
return tableFields;
}
public boolean isActive() {
return this.isActive;
}
public String getEmail() {
return email;
}
public String getEmail() {
return email;
}
public void disableActive() {
this.isActive = true;
}
public void enableActive() {
this.isActive = false;
this.isActive = false;
}
public Long getReportRunFrequency() {
return this.reportRunFrequency;
@@ -98,16 +98,16 @@ public class AdHocReadPlatformServiceImpl implements AdHocReadPlatformService {
public String schema() {
return " r.id as id, r.name as name, r.query as query, r.table_name as tableName,r.table_fields as tableField ,r.IsActive as isActive ,r.email as email ,"
+ " r.report_run_frequency_code, r.report_run_every, r.last_run, "
+ " r.created_date as createdDate, r.createdby_id as createdById,cb.username as createdBy,r.lastmodifiedby_id as updatedById ,r.lastmodified_date as updatedOn "
+ " r.created_date as createdDate, r.createdby_id as createdById,cb.username as createdBy,r.lastmodifiedby_id as updatedById ,r.lastmodified_date as updatedOn "
+ " from m_adhoc r left join m_appuser cb on cb.id=r.createdby_id left join m_appuser mb on mb.id=r.lastmodifiedby_id";
}
}
@Override
public AdHocData retrieveNewAdHocDetails() {
return AdHocData.template();
}
@Override
public AdHocData retrieveNewAdHocDetails() {
return AdHocData.template();
}
}
@@ -48,9 +48,9 @@ public class AdHocScheduledJobRunnerServiceImpl implements AdHocScheduledJobRunn
@Autowired
public AdHocScheduledJobRunnerServiceImpl(final RoutingDataSource dataSource,
final AdHocReadPlatformService adHocReadPlatformService
final AdHocReadPlatformService adHocReadPlatformService
) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
this.jdbcTemplate = new JdbcTemplate(dataSource);
this.adHocReadPlatformService = adHocReadPlatformService;
}
@@ -59,12 +59,12 @@ public class AdHocScheduledJobRunnerServiceImpl implements AdHocScheduledJobRunn
@Override
@CronTarget(jobName = JobName.GENERATE_ADHOCCLIENT_SCEHDULE)
public void generateClientSchedule() {
final Collection<AdHocData> adhocs = this.adHocReadPlatformService.retrieveAllActiveAdHocQuery();
final Collection<AdHocData> adhocs = this.adHocReadPlatformService.retrieveAllActiveAdHocQuery();
if(adhocs.size()>0){
adhocs.forEach(adhoc->{
boolean run = true;
adhocs.forEach(adhoc->{
boolean run = true;
LocalDate next = null;
if (adhoc.getReportRunFrequency() != null) {
if (adhoc.getReportRunFrequency() != null) {
if (adhoc.getLastRun() != null) {
LocalDate start = adhoc.getLastRun().toLocalDate();
LocalDate end = new DateTime().toLocalDate();
@@ -113,9 +113,9 @@ public class AdHocScheduledJobRunnerServiceImpl implements AdHocScheduledJobRunn
} else {
logger.info(ThreadLocalContextUtil.getTenant().getName() + ": Skipping execution of " + adhoc.getName() + ", scheduled for execution on " + next);
}
});
});
}else{
logger.info(ThreadLocalContextUtil.getTenant().getName() + "Nothing to update ");
logger.info(ThreadLocalContextUtil.getTenant().getName() + "Nothing to update ");
}
@@ -22,8 +22,8 @@ import org.apache.fineract.infrastructure.core.exception.AbstractPlatformDomainR
public class ClientDetailsNotFoundException extends AbstractPlatformDomainRuleException{
public ClientDetailsNotFoundException() {
super("validation.msg.batch.jlg.no.clients.defined", "No Client details found", "");
}
public ClientDetailsNotFoundException() {
super("validation.msg.batch.jlg.no.clients.defined", "No Client details found", "");
}
}
@@ -70,12 +70,12 @@ public class ErrorHandler extends RuntimeException {
*/
public static ErrorInfo handler(final RuntimeException exception) {
if(exception instanceof AbstractPlatformDomainRuleException) {
PlatformDomainRuleExceptionMapper mapper = new PlatformDomainRuleExceptionMapper() ;
final String errorBody = jsonHelper
if(exception instanceof AbstractPlatformDomainRuleException) {
PlatformDomainRuleExceptionMapper mapper = new PlatformDomainRuleExceptionMapper() ;
final String errorBody = jsonHelper
.toJson(mapper.toResponse((AbstractPlatformDomainRuleException) exception).getEntity());
return new ErrorInfo(500, 9999, errorBody);
}else if (exception instanceof AbstractPlatformResourceNotFoundException) {
return new ErrorInfo(500, 9999, errorBody);
}else if (exception instanceof AbstractPlatformResourceNotFoundException) {
final PlatformResourceNotFoundExceptionMapper mapper = new PlatformResourceNotFoundExceptionMapper();
final String errorBody = jsonHelper
@@ -128,7 +128,7 @@ public class ErrorHandler extends RuntimeException {
return new ErrorInfo(500, 5001, errorBody);
}else if(exception instanceof NonTransientDataAccessException) {
return new ErrorInfo(400, 4001, "{\"Exception\": " + exception.getMessage()+"}");
return new ErrorInfo(400, 4001, "{\"Exception\": " + exception.getMessage()+"}");
}
return new ErrorInfo(500, 9999, "{\"Exception\": " + exception.toString() + "}");
@@ -95,8 +95,8 @@ public class BatchApiServiceImpl implements BatchApiService {
final List<BatchRequestNode> batchRequestNodes = this.resolutionHelper.getDependingRequests(requestList);
if(batchRequestNodes.isEmpty()) {
final BatchResponse response = new BatchResponse();
ErrorInfo ex = ErrorHandler.handler(new ClientDetailsNotFoundException());
final BatchResponse response = new BatchResponse();
ErrorInfo ex = ErrorHandler.handler(new ClientDetailsNotFoundException());
response.setStatusCode(500);
response.setBody(ex.getMessage());
responseList.add(response) ;
@@ -222,7 +222,7 @@ public class BatchApiServiceImpl implements BatchApiService {
return errResponseList;
}catch (final NonTransientDataAccessException ex) {
ErrorInfo e = ErrorHandler.handler(ex);
ErrorInfo e = ErrorHandler.handler(ex);
BatchResponse errResponse = new BatchResponse();
errResponse.setStatusCode(e.getStatusCode());
@@ -274,7 +274,7 @@ public class AuditReadPlatformServiceImpl implements AuditReadPlatformService {
}
sql += extraCriteria;
if(isExtraCritereaIncluded){
this.columnValidator.validateSqlInjection(sql, extraCriteria);
this.columnValidator.validateSqlInjection(sql, extraCriteria);
}
logger.info("sql: " + sql);
@@ -2836,31 +2836,31 @@ public class CommandWrapperBuilder {
return this;
}
public CommandWrapperBuilder addSelfServiceBeneficiaryTPT() {
public CommandWrapperBuilder addSelfServiceBeneficiaryTPT() {
this.actionName = "CREATE";
this.entityName = "SSBENEFICIARYTPT";
this.entityId = null;
this.href = "/self/beneficiaries/tpt";
return this;
}
}
public CommandWrapperBuilder updateSelfServiceBeneficiaryTPT(final Long beneficiaryId) {
public CommandWrapperBuilder updateSelfServiceBeneficiaryTPT(final Long beneficiaryId) {
this.actionName = "UPDATE";
this.entityName = "SSBENEFICIARYTPT";
this.entityId = beneficiaryId;
this.href = "/self/beneficiaries/tpt/"+beneficiaryId;
return this;
}
}
public CommandWrapperBuilder deleteSelfServiceBeneficiaryTPT(final Long beneficiaryId) {
public CommandWrapperBuilder deleteSelfServiceBeneficiaryTPT(final Long beneficiaryId) {
this.actionName = "DELETE";
this.entityName = "SSBENEFICIARYTPT";
this.entityId = beneficiaryId;
this.href = "/self/beneficiaries/tpt/"+beneficiaryId;
return this;
}
}
public CommandWrapperBuilder createReportMailingJob(final String entityName) {
public CommandWrapperBuilder createReportMailingJob(final String entityName) {
this.actionName = "CREATE";
this.entityName = entityName;
this.entityId = null;
@@ -3003,7 +3003,7 @@ public class CommandWrapperBuilder {
this.href = "/savingsaccounts/" + accountId + "?command=unblock";
return this;
}
public CommandWrapperBuilder disableAdHoc(Long adHocId) {
public CommandWrapperBuilder disableAdHoc(Long adHocId) {
this.actionName = "DISABLE";
this.entityName = "ADHOC";
this.entityId = adHocId;
@@ -66,10 +66,10 @@ public class AccountNumberFormatsApiResource {
private final ToApiJsonSerializer<AccountNumberFormatData> toApiJsonSerializer;
private final ApiRequestParameterHelper apiRequestParameterHelper;
private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService;
private static final Set<String> ACCOUNT_NUMBER_FORMAT_RESPONSE_DATA_PARAMETERS = new HashSet<>(Arrays.asList(
AccountNumberFormatConstants.idParamName, AccountNumberFormatConstants.accountTypeParamName,
AccountNumberFormatConstants.prefixTypeParamName, AccountNumberFormatConstants.accountTypeOptionsParamName,
AccountNumberFormatConstants.prefixTypeOptionsParamName));
private static final Set<String> ACCOUNT_NUMBER_FORMAT_RESPONSE_DATA_PARAMETERS = new HashSet<>(Arrays.asList(
AccountNumberFormatConstants.idParamName, AccountNumberFormatConstants.accountTypeParamName,
AccountNumberFormatConstants.prefixTypeParamName, AccountNumberFormatConstants.accountTypeOptionsParamName,
AccountNumberFormatConstants.prefixTypeOptionsParamName));
@Autowired
public AccountNumberFormatsApiResource(final PlatformSecurityContext context,
@@ -98,8 +98,8 @@ public class AccountNumberFormatsApiResource {
AccountNumberFormatData accountNumberFormatData = this.accountNumberFormatReadPlatformService.retrieveTemplate(accountType);
final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters());
return this.toApiJsonSerializer.serialize(settings, accountNumberFormatData,
ACCOUNT_NUMBER_FORMAT_RESPONSE_DATA_PARAMETERS);
return this.toApiJsonSerializer.serialize(settings, accountNumberFormatData,
ACCOUNT_NUMBER_FORMAT_RESPONSE_DATA_PARAMETERS);
}
@GET
@@ -115,8 +115,8 @@ public class AccountNumberFormatsApiResource {
.getAllAccountNumberFormats();
final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters());
return this.toApiJsonSerializer.serialize(settings, accountNumberFormatData,
ACCOUNT_NUMBER_FORMAT_RESPONSE_DATA_PARAMETERS);
return this.toApiJsonSerializer.serialize(settings, accountNumberFormatData,
ACCOUNT_NUMBER_FORMAT_RESPONSE_DATA_PARAMETERS);
}
@GET
@@ -139,8 +139,8 @@ public class AccountNumberFormatsApiResource {
accountNumberFormatData.templateOnTop(templateData.getAccountTypeOptions(), templateData.getPrefixTypeOptions());
}
return this.toApiJsonSerializer.serialize(settings, accountNumberFormatData,
ACCOUNT_NUMBER_FORMAT_RESPONSE_DATA_PARAMETERS);
return this.toApiJsonSerializer.serialize(settings, accountNumberFormatData,
ACCOUNT_NUMBER_FORMAT_RESPONSE_DATA_PARAMETERS);
}
@POST
@@ -49,8 +49,8 @@ public class AccountNumberFormatDataValidator {
private static final Set<String> ACCOUNT_NUMBER_FORMAT_CREATE_REQUEST_DATA_PARAMETERS = new HashSet<>(Arrays.asList(
AccountNumberFormatConstants.accountTypeParamName, AccountNumberFormatConstants.prefixTypeParamName));
private static final Set<String> ACCOUNT_NUMBER_FORMAT_UPDATE_REQUEST_DATA_PARAMETERS = new HashSet<>(
Arrays.asList(AccountNumberFormatConstants.prefixTypeParamName));
private static final Set<String> ACCOUNT_NUMBER_FORMAT_UPDATE_REQUEST_DATA_PARAMETERS = new HashSet<>(
Arrays.asList(AccountNumberFormatConstants.prefixTypeParamName));
@Autowired
public AccountNumberFormatDataValidator(final FromJsonHelper fromApiJsonHelper) {
@@ -61,8 +61,8 @@ public class AccountNumberFormatDataValidator {
if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); }
final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType();
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json,
ACCOUNT_NUMBER_FORMAT_CREATE_REQUEST_DATA_PARAMETERS);
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json,
ACCOUNT_NUMBER_FORMAT_CREATE_REQUEST_DATA_PARAMETERS);
final JsonElement element = this.fromApiJsonHelper.parse(json);
final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
@@ -105,31 +105,31 @@ public class AccountNumberFormatDataValidator {
}
public Set<Integer> determineValidAccountNumberPrefixes(
EntityAccountType entityAccountType) {
Set<AccountNumberPrefixType> validAccountNumberPrefixes = new HashSet<>();
public Set<Integer> determineValidAccountNumberPrefixes(
EntityAccountType entityAccountType) {
Set<AccountNumberPrefixType> validAccountNumberPrefixes = new HashSet<>();
switch (entityAccountType) {
case CLIENT:
validAccountNumberPrefixes = AccountNumberFormatEnumerations.accountNumberPrefixesForClientAccounts;
break;
switch (entityAccountType) {
case CLIENT:
validAccountNumberPrefixes = AccountNumberFormatEnumerations.accountNumberPrefixesForClientAccounts;
break;
case LOAN:
validAccountNumberPrefixes = AccountNumberFormatEnumerations.accountNumberPrefixesForLoanAccounts;
break;
case LOAN:
validAccountNumberPrefixes = AccountNumberFormatEnumerations.accountNumberPrefixesForLoanAccounts;
break;
case SAVINGS:
validAccountNumberPrefixes = AccountNumberFormatEnumerations.accountNumberPrefixesForSavingsAccounts;
break;
case SAVINGS:
validAccountNumberPrefixes = AccountNumberFormatEnumerations.accountNumberPrefixesForSavingsAccounts;
break;
case CENTER:
validAccountNumberPrefixes = AccountNumberFormatEnumerations.accountNumberPrefixesForCenters;
break;
case GROUP:
validAccountNumberPrefixes = AccountNumberFormatEnumerations.accountNumberPrefixesForGroups;
break;
}
case CENTER:
validAccountNumberPrefixes = AccountNumberFormatEnumerations.accountNumberPrefixesForCenters;
break;
case GROUP:
validAccountNumberPrefixes = AccountNumberFormatEnumerations.accountNumberPrefixesForGroups;
break;
}
Set<Integer> validAccountNumberPrefixValues = new HashSet<>();
for (AccountNumberPrefixType validAccountNumberPrefix : validAccountNumberPrefixes) {
@@ -143,8 +143,8 @@ public class AccountNumberFormatDataValidator {
if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); }
final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType();
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json,
ACCOUNT_NUMBER_FORMAT_UPDATE_REQUEST_DATA_PARAMETERS);
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json,
ACCOUNT_NUMBER_FORMAT_UPDATE_REQUEST_DATA_PARAMETERS);
final JsonElement element = this.fromApiJsonHelper.parse(json);
final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
@@ -92,11 +92,11 @@ public enum EntityAccountType {
}
public Boolean isCenterAccount(){
return this.value.equals(EntityAccountType.CENTER.getValue());
return this.value.equals(EntityAccountType.CENTER.getValue());
}
public Boolean isGroupAccount(){
return this.value.equals(EntityAccountType.GROUP.getValue());
return this.value.equals(EntityAccountType.GROUP.getValue());
}
}
@@ -80,9 +80,9 @@ public class AccountNumberFormatWritePlatformServiceJpaRepositoryImpl implements
handleDataIntegrityIssues(command, dve.getMostSpecificCause(), dve);
return CommandProcessingResult.empty();
}catch (final PersistenceException ee) {
Throwable throwable = ExceptionUtils.getRootCause(ee.getCause()) ;
handleDataIntegrityIssues(command, throwable, ee);
return CommandProcessingResult.empty();
Throwable throwable = ExceptionUtils.getRootCause(ee.getCause()) ;
handleDataIntegrityIssues(command, throwable, ee);
return CommandProcessingResult.empty();
}
}
@@ -120,9 +120,9 @@ public class AccountNumberFormatWritePlatformServiceJpaRepositoryImpl implements
handleDataIntegrityIssues(command, dve.getMostSpecificCause(), dve);
return CommandProcessingResult.empty();
} catch (final PersistenceException ee) {
Throwable throwable = ExceptionUtils.getRootCause(ee.getCause()) ;
handleDataIntegrityIssues(command, throwable, ee);
return CommandProcessingResult.empty();
Throwable throwable = ExceptionUtils.getRootCause(ee.getCause()) ;
handleDataIntegrityIssues(command, throwable, ee);
return CommandProcessingResult.empty();
}
}
@@ -126,7 +126,7 @@ public class ImportHandlerUtils {
public static String trimEmptyDecimalPortion(String result) {
if(result != null && result.endsWith(".0"))
return result.split("\\.")[0];
return result.split("\\.")[0];
else
return result;
}
@@ -177,9 +177,9 @@ public class ClientEntityImportHandler implements ImportHandler {
addressList = new ArrayList<AddressData>(Arrays.asList(addressDataObj));
}
return ClientData.importClientEntityInstance(legalFormId,row.getRowNum(),name,officeId,clientTypeId,clientClassicationId,
staffId, active, activationDate, submittedOn, externalId, incorportionDate, mobileNo,
clientNonPersonData, addressList, locale, dateFormat);
}
staffId, active, activationDate, submittedOn, externalId, incorportionDate, mobileNo,
clientNonPersonData, addressList, locale, dateFormat);
}
public Count importEntity(String dateFormat) {
Sheet clientSheet=workbook.getSheet(TemplatePopulateImportConstants.CLIENT_ENTITY_SHEET_NAME);
@@ -163,10 +163,10 @@ public class ClientPersonImportHandler implements ImportHandler {
addressList = new ArrayList<AddressData>(Arrays.asList(addressDataObj));
}
return ClientData.importClientPersonInstance(legalFormId,row.getRowNum(),firstName,lastName,middleName,submittedOn,activationDate,active,externalId,
officeId, staffId, mobileNo, dob, clientTypeId, genderId, clientClassicationId, isStaff,
addressList, locale, dateFormat);
officeId, staffId, mobileNo, dob, clientTypeId, genderId, clientClassicationId, isStaff,
addressList, locale, dateFormat);
}
}
public Count importEntity(String dateFormat) {
Sheet clientSheet=workbook.getSheet(TemplatePopulateImportConstants.CLIENT_PERSON_SHEET_NAME);
@@ -88,8 +88,8 @@ public abstract class AbstractWorkbookPopulator implements WorkbookPopulator {
}
protected void writeBigDecimal(int colIndex, Row row, BigDecimal value) {
row.createCell(colIndex).setCellValue(((value != null) ? value.doubleValue() : 0));
}
row.createCell(colIndex).setCellValue(((value != null) ? value.doubleValue() : 0));
}
protected void setOfficeDateLookupTable(Sheet sheet, List<OfficeData> offices, int officeNameCol,
int activationDateCol,String dateFormat) {
@@ -142,23 +142,23 @@ public abstract class AbstractWorkbookPopulator implements WorkbookPopulator {
}
}
if (groups != null) {
for (GroupGeneralData group : groups) {
Row row = sheet.getRow(++rowIndex);
if (row == null)
row = sheet.createRow(rowIndex);
writeString(nameCol, row, group.getName().replaceAll("[ )(] ", "_"));
if (groups != null) {
for (GroupGeneralData group : groups) {
Row row = sheet.getRow(++rowIndex);
if (row == null)
row = sheet.createRow(rowIndex);
writeString(nameCol, row, group.getName().replaceAll("[ )(] ", "_"));
if (group.getActivationDate() != null) {
date = inputFormat.parse(group.getActivationDate().toString());
writeDate(activationDateCol, row, outputFormat.format(date), dateCellStyle, dateFormat);
}
if (group.getActivationDate() != null) {
date = inputFormat.parse(group.getActivationDate().toString());
writeDate(activationDateCol, row, outputFormat.format(date), dateCellStyle, dateFormat);
}
}
}
}
}
} catch (ParseException e) {
e.printStackTrace();
}
}
}
}
@@ -31,93 +31,93 @@ import java.util.List;
import java.util.Map;
public class CenterSheetPopulator extends AbstractWorkbookPopulator {
private List<CenterData> allCenters;
private List<OfficeData> offices;
private List<CenterData> allCenters;
private List<OfficeData> offices;
private Map<String, ArrayList<String>> officeToCenters;
private Map<Integer, Integer[]> officeNameToBeginEndIndexesOfCenters;
private Map<String, Long> centerNameToCenterId;
private Map<String, ArrayList<String>> officeToCenters;
private Map<Integer, Integer[]> officeNameToBeginEndIndexesOfCenters;
private Map<String, Long> centerNameToCenterId;
private static final int OFFICE_NAME_COL = 0;
private static final int CENTER_NAME_COL = 1;
private static final int CENTER_ID_COL = 2;
private static final int OFFICE_NAME_COL = 0;
private static final int CENTER_NAME_COL = 1;
private static final int CENTER_ID_COL = 2;
public CenterSheetPopulator(List<CenterData> centers, List<OfficeData> offices) {
this.allCenters = centers;
this.offices = offices;
}
public CenterSheetPopulator(List<CenterData> centers, List<OfficeData> offices) {
this.allCenters = centers;
this.offices = offices;
}
@Override
public void populate(Workbook workbook,String dateFormat) {
Sheet centerSheet = workbook.createSheet(TemplatePopulateImportConstants.CENTER_SHEET_NAME);
setLayout(centerSheet);
setOfficeToCentersMap();
centerNameToCenterIdMap();
populateCentersByOfficeName(centerSheet);
centerSheet.protectSheet("");
}
@Override
public void populate(Workbook workbook,String dateFormat) {
Sheet centerSheet = workbook.createSheet(TemplatePopulateImportConstants.CENTER_SHEET_NAME);
setLayout(centerSheet);
setOfficeToCentersMap();
centerNameToCenterIdMap();
populateCentersByOfficeName(centerSheet);
centerSheet.protectSheet("");
}
private void centerNameToCenterIdMap() {
centerNameToCenterId = new HashMap<String, Long>();
for (CenterData centerData : allCenters) {
centerNameToCenterId.put(centerData.getName(), centerData.getId());
}
}
private void centerNameToCenterIdMap() {
centerNameToCenterId = new HashMap<String, Long>();
for (CenterData centerData : allCenters) {
centerNameToCenterId.put(centerData.getName(), centerData.getId());
}
}
private void populateCentersByOfficeName(Sheet centerSheet) {
int rowIndex = 1, officeIndex = 0, startIndex = 1;
officeNameToBeginEndIndexesOfCenters = new HashMap<Integer, Integer[]>();
Row row = centerSheet.createRow(rowIndex);
for (OfficeData office : offices) {
startIndex = rowIndex + 1;
writeString(OFFICE_NAME_COL, row, office.name());
ArrayList<String> centersList = new ArrayList<String>();
private void populateCentersByOfficeName(Sheet centerSheet) {
int rowIndex = 1, officeIndex = 0, startIndex = 1;
officeNameToBeginEndIndexesOfCenters = new HashMap<Integer, Integer[]>();
Row row = centerSheet.createRow(rowIndex);
for (OfficeData office : offices) {
startIndex = rowIndex + 1;
writeString(OFFICE_NAME_COL, row, office.name());
ArrayList<String> centersList = new ArrayList<String>();
if (officeToCenters.containsKey(office.name().trim().replaceAll("[ )(]", "_"))){
centersList = officeToCenters.get(office.name().trim().replaceAll("[ )(]", "_"));
if (!centersList.isEmpty()) {
for (String centerName : centersList) {
writeString(CENTER_NAME_COL, row, centerName);
writeLong(CENTER_ID_COL, row, centerNameToCenterId.get(centerName));
row = centerSheet.createRow(++rowIndex);
}
officeNameToBeginEndIndexesOfCenters.put(officeIndex++, new Integer[] { startIndex, rowIndex });
} else {
officeNameToBeginEndIndexesOfCenters.put(officeIndex++, new Integer[] { startIndex, rowIndex + 1 });
}
}
}
}
if (officeToCenters.containsKey(office.name().trim().replaceAll("[ )(]", "_"))){
centersList = officeToCenters.get(office.name().trim().replaceAll("[ )(]", "_"));
if (!centersList.isEmpty()) {
for (String centerName : centersList) {
writeString(CENTER_NAME_COL, row, centerName);
writeLong(CENTER_ID_COL, row, centerNameToCenterId.get(centerName));
row = centerSheet.createRow(++rowIndex);
}
officeNameToBeginEndIndexesOfCenters.put(officeIndex++, new Integer[] { startIndex, rowIndex });
} else {
officeNameToBeginEndIndexesOfCenters.put(officeIndex++, new Integer[] { startIndex, rowIndex + 1 });
}
}
}
}
private void setLayout(Sheet worksheet) {
Row rowHeader = worksheet.createRow(TemplatePopulateImportConstants.ROWHEADER_INDEX);
rowHeader.setHeight(TemplatePopulateImportConstants.ROW_HEADER_HEIGHT);
for (int colIndex = 0; colIndex <= 10; colIndex++)
worksheet.setColumnWidth(colIndex, TemplatePopulateImportConstants.MEDIUM_COL_SIZE);
writeString(OFFICE_NAME_COL, rowHeader, "Office Names");
writeString(CENTER_NAME_COL, rowHeader, "Center Names");
writeString(CENTER_ID_COL, rowHeader, "Center ID");
}
private void setLayout(Sheet worksheet) {
Row rowHeader = worksheet.createRow(TemplatePopulateImportConstants.ROWHEADER_INDEX);
rowHeader.setHeight(TemplatePopulateImportConstants.ROW_HEADER_HEIGHT);
for (int colIndex = 0; colIndex <= 10; colIndex++)
worksheet.setColumnWidth(colIndex, TemplatePopulateImportConstants.MEDIUM_COL_SIZE);
writeString(OFFICE_NAME_COL, rowHeader, "Office Names");
writeString(CENTER_NAME_COL, rowHeader, "Center Names");
writeString(CENTER_ID_COL, rowHeader, "Center ID");
}
private void setOfficeToCentersMap() {
officeToCenters = new HashMap<>();
for (CenterData center : allCenters) {
add(center.getOfficeName().trim().replaceAll("[ )(]", "_"), center.getName().trim());
}
}
private void setOfficeToCentersMap() {
officeToCenters = new HashMap<>();
for (CenterData center : allCenters) {
add(center.getOfficeName().trim().replaceAll("[ )(]", "_"), center.getName().trim());
}
}
// Guava Multi-map can reduce this.
private void add(String key, String value) {
ArrayList<String> values = officeToCenters.get(key);
if (values == null) {
values = new ArrayList<>();
}
values.add(value);
officeToCenters.put(key, values);
}
// Guava Multi-map can reduce this.
private void add(String key, String value) {
ArrayList<String> values = officeToCenters.get(key);
if (values == null) {
values = new ArrayList<>();
}
values.add(value);
officeToCenters.put(key, values);
}
public Map<Integer, Integer[]> getOfficeNameToBeginEndIndexesOfCenters() {
return officeNameToBeginEndIndexesOfCenters;
}
public Map<Integer, Integer[]> getOfficeNameToBeginEndIndexesOfCenters() {
return officeNameToBeginEndIndexesOfCenters;
}
}
@@ -31,114 +31,114 @@ import java.util.List;
import java.util.Map;
public class ClientSheetPopulator extends AbstractWorkbookPopulator {
private List<ClientData> allClients;
private List<OfficeData> officesDataList;
private List<ClientData> allClients;
private List<OfficeData> officesDataList;
private Map<String, ArrayList<String>> officeToClients;
private Map<Integer, Integer[]> officeNameToBeginEndIndexesOfClients;
private Map<String, Long> clientNameToClientId;
private Map<String, Long> clientNameToSavingsAccountIds;
private Map<String, ArrayList<String>> officeToClients;
private Map<Integer, Integer[]> officeNameToBeginEndIndexesOfClients;
private Map<String, Long> clientNameToClientId;
private Map<String, Long> clientNameToSavingsAccountIds;
private static final int OFFICE_NAME_COL = 0;
private static final int CLIENT_NAME_COL = 1;
private static final int CLIENT_ID_COL = 2;
private static final int OFFICE_NAME_COL = 0;
private static final int CLIENT_NAME_COL = 1;
private static final int CLIENT_ID_COL = 2;
public ClientSheetPopulator(final List<ClientData> clients, final List<OfficeData> Offices) {
this.allClients = clients;
this.officesDataList = Offices;
}
public ClientSheetPopulator(final List<ClientData> clients, final List<OfficeData> Offices) {
this.allClients = clients;
this.officesDataList = Offices;
}
@Override
public void populate(Workbook workbook,String dateFormat) {
Sheet clientSheet = workbook.createSheet(TemplatePopulateImportConstants.CLIENT_SHEET_NAME);
setLayout(clientSheet);
setOfficeToClientsMap();
setClientNameToClientIdMap();
populateClientsByOfficeName(clientSheet);
clientSheet.protectSheet("");
setClientNameToSavingsAccountsIdsMap();
}
@Override
public void populate(Workbook workbook,String dateFormat) {
Sheet clientSheet = workbook.createSheet(TemplatePopulateImportConstants.CLIENT_SHEET_NAME);
setLayout(clientSheet);
setOfficeToClientsMap();
setClientNameToClientIdMap();
populateClientsByOfficeName(clientSheet);
clientSheet.protectSheet("");
setClientNameToSavingsAccountsIdsMap();
}
private void setClientNameToClientIdMap() {
clientNameToClientId = new HashMap<>();
for (ClientData clientData : allClients) {
clientNameToClientId.put(clientData.displayName().trim() + "(" + clientData.id() + ")",
clientData.id());
}
}
private void setClientNameToClientIdMap() {
clientNameToClientId = new HashMap<>();
for (ClientData clientData : allClients) {
clientNameToClientId.put(clientData.displayName().trim() + "(" + clientData.id() + ")",
clientData.id());
}
}
private void setLayout(Sheet worksheet) {
Row rowHeader = worksheet.createRow(TemplatePopulateImportConstants.ROWHEADER_INDEX);
rowHeader.setHeight(TemplatePopulateImportConstants.ROW_HEADER_HEIGHT);
worksheet.setColumnWidth(OFFICE_NAME_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE);
for (int colIndex = 1; colIndex <= 10; colIndex++)
worksheet.setColumnWidth(colIndex, TemplatePopulateImportConstants.MEDIUM_COL_SIZE);
writeString(OFFICE_NAME_COL, rowHeader, "Office Names");
writeString(CLIENT_NAME_COL, rowHeader, "Client Names");
writeString(CLIENT_ID_COL, rowHeader, "Client ID");
}
private void setLayout(Sheet worksheet) {
Row rowHeader = worksheet.createRow(TemplatePopulateImportConstants.ROWHEADER_INDEX);
rowHeader.setHeight(TemplatePopulateImportConstants.ROW_HEADER_HEIGHT);
worksheet.setColumnWidth(OFFICE_NAME_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE);
for (int colIndex = 1; colIndex <= 10; colIndex++)
worksheet.setColumnWidth(colIndex, TemplatePopulateImportConstants.MEDIUM_COL_SIZE);
writeString(OFFICE_NAME_COL, rowHeader, "Office Names");
writeString(CLIENT_NAME_COL, rowHeader, "Client Names");
writeString(CLIENT_ID_COL, rowHeader, "Client ID");
}
private void setOfficeToClientsMap() {
officeToClients = new HashMap<>();
for (ClientData person : allClients) {
addToOfficeClientMap(person.getOfficeName().trim().replaceAll("[ )(]", "_"),
person.displayName().trim() + "(" + person.id() + ")");
}
}
private void setOfficeToClientsMap() {
officeToClients = new HashMap<>();
for (ClientData person : allClients) {
addToOfficeClientMap(person.getOfficeName().trim().replaceAll("[ )(]", "_"),
person.displayName().trim() + "(" + person.id() + ")");
}
}
private void setClientNameToSavingsAccountsIdsMap(){
clientNameToSavingsAccountIds=new HashMap<>();
for (ClientData client: allClients) {
clientNameToSavingsAccountIds.put(client.displayName().trim() + "(" + client.id() + ")",client.getSavingsAccountId());
}
private void setClientNameToSavingsAccountsIdsMap(){
clientNameToSavingsAccountIds=new HashMap<>();
for (ClientData client: allClients) {
clientNameToSavingsAccountIds.put(client.displayName().trim() + "(" + client.id() + ")",client.getSavingsAccountId());
}
}
}
// Guava Multi-map can reduce this.
private void addToOfficeClientMap(String key, String value) {
ArrayList<String> values = officeToClients.get(key);
if (values == null) {
values = new ArrayList<String>();
}
values.add(value);
officeToClients.put(key, values);
}
// Guava Multi-map can reduce this.
private void addToOfficeClientMap(String key, String value) {
ArrayList<String> values = officeToClients.get(key);
if (values == null) {
values = new ArrayList<String>();
}
values.add(value);
officeToClients.put(key, values);
}
private void populateClientsByOfficeName(Sheet clientSheet) {
int rowIndex = 1, startIndex = 1, officeIndex = 0;
officeNameToBeginEndIndexesOfClients = new HashMap<>();
Row row = clientSheet.createRow(rowIndex);
for (OfficeData office : officesDataList) {
startIndex = rowIndex + 1;
writeString(OFFICE_NAME_COL, row, office.name());
ArrayList<String> clientList = new ArrayList<String>();
if (officeToClients.containsKey(office.name().trim().replaceAll("[ )(]", "_")))
clientList = officeToClients.get(office.name().trim().replaceAll("[ )(]", "_"));
if (!clientList.isEmpty()) {
for (String clientName : clientList) {
writeString(CLIENT_NAME_COL, row, clientName);
writeLong(CLIENT_ID_COL, row, clientNameToClientId.get(clientName));
row = clientSheet.createRow(++rowIndex);
}
officeNameToBeginEndIndexesOfClients.put(officeIndex++, new Integer[] { startIndex, rowIndex });
} else
officeIndex++;
}
}
private void populateClientsByOfficeName(Sheet clientSheet) {
int rowIndex = 1, startIndex = 1, officeIndex = 0;
officeNameToBeginEndIndexesOfClients = new HashMap<>();
Row row = clientSheet.createRow(rowIndex);
for (OfficeData office : officesDataList) {
startIndex = rowIndex + 1;
writeString(OFFICE_NAME_COL, row, office.name());
ArrayList<String> clientList = new ArrayList<String>();
if (officeToClients.containsKey(office.name().trim().replaceAll("[ )(]", "_")))
clientList = officeToClients.get(office.name().trim().replaceAll("[ )(]", "_"));
if (!clientList.isEmpty()) {
for (String clientName : clientList) {
writeString(CLIENT_NAME_COL, row, clientName);
writeLong(CLIENT_ID_COL, row, clientNameToClientId.get(clientName));
row = clientSheet.createRow(++rowIndex);
}
officeNameToBeginEndIndexesOfClients.put(officeIndex++, new Integer[] { startIndex, rowIndex });
} else
officeIndex++;
}
}
public List<ClientData> getClients() {
return allClients;
}
public List<ClientData> getClients() {
return allClients;
}
public Integer getClientsSize() {
return allClients.size();
}
public Integer getClientsSize() {
return allClients.size();
}
public Map<Integer, Integer[]> getOfficeNameToBeginEndIndexesOfClients() {
return officeNameToBeginEndIndexesOfClients;
}
public Map<Integer, Integer[]> getOfficeNameToBeginEndIndexesOfClients() {
return officeNameToBeginEndIndexesOfClients;
}
public Map<String, Long> getClientNameToSavingsAccountIds() {
return clientNameToSavingsAccountIds;
}
public Map<String, Long> getClientNameToSavingsAccountIds() {
return clientNameToSavingsAccountIds;
}
}
@@ -30,87 +30,87 @@ import java.util.List;
public class ExtrasSheetPopulator extends AbstractWorkbookPopulator {
private List<FundData> funds;
private List<PaymentTypeData> paymentTypes;
private List<CurrencyData> currencies;
private List<FundData> funds;
private List<PaymentTypeData> paymentTypes;
private List<CurrencyData> currencies;
private static final int FUND_ID_COL = 0;
private static final int FUND_NAME_COL = 1;
private static final int PAYMENT_TYPE_ID_COL = 2;
private static final int PAYMENT_TYPE_NAME_COL = 3;
private static final int CURRENCY_CODE_COL = 4;
private static final int CURRENCY_NAME_COL = 5;
private static final int FUND_ID_COL = 0;
private static final int FUND_NAME_COL = 1;
private static final int PAYMENT_TYPE_ID_COL = 2;
private static final int PAYMENT_TYPE_NAME_COL = 3;
private static final int CURRENCY_CODE_COL = 4;
private static final int CURRENCY_NAME_COL = 5;
public ExtrasSheetPopulator(List<FundData> funds, List<PaymentTypeData> paymentTypes,
List<CurrencyData> currencies) {
this.funds = funds;
this.paymentTypes = paymentTypes;
this.currencies = currencies;
}
public ExtrasSheetPopulator(List<FundData> funds, List<PaymentTypeData> paymentTypes,
List<CurrencyData> currencies) {
this.funds = funds;
this.paymentTypes = paymentTypes;
this.currencies = currencies;
}
@Override
public void populate(Workbook workbook,String dateFormat) {
int fundRowIndex = 1;
Sheet extrasSheet = workbook.createSheet(TemplatePopulateImportConstants.EXTRAS_SHEET_NAME);
setLayout(extrasSheet);
for (FundData fund : funds) {
Row row = extrasSheet.createRow(fundRowIndex++);
writeLong(FUND_ID_COL, row, fund.getId());
writeString(FUND_NAME_COL, row, fund.getName());
}
int paymentTypeRowIndex = 1;
for (PaymentTypeData paymentType : paymentTypes) {
Row row;
if (paymentTypeRowIndex < fundRowIndex)
row = extrasSheet.getRow(paymentTypeRowIndex++);
else
row = extrasSheet.createRow(paymentTypeRowIndex++);
writeLong(PAYMENT_TYPE_ID_COL, row, paymentType.getId());
writeString(PAYMENT_TYPE_NAME_COL, row, paymentType.getName().trim().replaceAll("[ )(]", "_"));
}
int currencyCodeRowIndex = 1;
for (CurrencyData currencies : currencies) {
Row row;
if (currencyCodeRowIndex < paymentTypeRowIndex)
row = extrasSheet.getRow(currencyCodeRowIndex++);
else
row = extrasSheet.createRow(currencyCodeRowIndex++);
@Override
public void populate(Workbook workbook,String dateFormat) {
int fundRowIndex = 1;
Sheet extrasSheet = workbook.createSheet(TemplatePopulateImportConstants.EXTRAS_SHEET_NAME);
setLayout(extrasSheet);
for (FundData fund : funds) {
Row row = extrasSheet.createRow(fundRowIndex++);
writeLong(FUND_ID_COL, row, fund.getId());
writeString(FUND_NAME_COL, row, fund.getName());
}
int paymentTypeRowIndex = 1;
for (PaymentTypeData paymentType : paymentTypes) {
Row row;
if (paymentTypeRowIndex < fundRowIndex)
row = extrasSheet.getRow(paymentTypeRowIndex++);
else
row = extrasSheet.createRow(paymentTypeRowIndex++);
writeLong(PAYMENT_TYPE_ID_COL, row, paymentType.getId());
writeString(PAYMENT_TYPE_NAME_COL, row, paymentType.getName().trim().replaceAll("[ )(]", "_"));
}
int currencyCodeRowIndex = 1;
for (CurrencyData currencies : currencies) {
Row row;
if (currencyCodeRowIndex < paymentTypeRowIndex)
row = extrasSheet.getRow(currencyCodeRowIndex++);
else
row = extrasSheet.createRow(currencyCodeRowIndex++);
writeString(CURRENCY_NAME_COL, row, currencies.getName().trim().replaceAll("[ )(]", "_"));
writeString(CURRENCY_CODE_COL, row, currencies.code());
}
extrasSheet.protectSheet("");
writeString(CURRENCY_NAME_COL, row, currencies.getName().trim().replaceAll("[ )(]", "_"));
writeString(CURRENCY_CODE_COL, row, currencies.code());
}
extrasSheet.protectSheet("");
}
}
private void setLayout(Sheet worksheet) {
worksheet.setColumnWidth(FUND_ID_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE);
worksheet.setColumnWidth(FUND_NAME_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE);
worksheet.setColumnWidth(PAYMENT_TYPE_ID_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE);
worksheet.setColumnWidth(PAYMENT_TYPE_NAME_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE);
worksheet.setColumnWidth(CURRENCY_NAME_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE);
worksheet.setColumnWidth(CURRENCY_CODE_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE);
Row rowHeader = worksheet.createRow(TemplatePopulateImportConstants.ROWHEADER_INDEX);
rowHeader.setHeight(TemplatePopulateImportConstants.ROW_HEADER_HEIGHT);
writeString(FUND_ID_COL, rowHeader, "Fund ID");
writeString(FUND_NAME_COL, rowHeader, "Name");
writeString(PAYMENT_TYPE_ID_COL, rowHeader, "Payment Type ID");
writeString(PAYMENT_TYPE_NAME_COL, rowHeader, "Payment Type Name");
writeString(CURRENCY_NAME_COL, rowHeader, "Currency Type ");
writeString(CURRENCY_CODE_COL, rowHeader, "Currency Code ");
}
public Integer getFundsSize() {
return funds.size();
}
public Integer getPaymentTypesSize() {
return paymentTypes.size();
}
private void setLayout(Sheet worksheet) {
worksheet.setColumnWidth(FUND_ID_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE);
worksheet.setColumnWidth(FUND_NAME_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE);
worksheet.setColumnWidth(PAYMENT_TYPE_ID_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE);
worksheet.setColumnWidth(PAYMENT_TYPE_NAME_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE);
worksheet.setColumnWidth(CURRENCY_NAME_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE);
worksheet.setColumnWidth(CURRENCY_CODE_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE);
Row rowHeader = worksheet.createRow(TemplatePopulateImportConstants.ROWHEADER_INDEX);
rowHeader.setHeight(TemplatePopulateImportConstants.ROW_HEADER_HEIGHT);
writeString(FUND_ID_COL, rowHeader, "Fund ID");
writeString(FUND_NAME_COL, rowHeader, "Name");
writeString(PAYMENT_TYPE_ID_COL, rowHeader, "Payment Type ID");
writeString(PAYMENT_TYPE_NAME_COL, rowHeader, "Payment Type Name");
writeString(CURRENCY_NAME_COL, rowHeader, "Currency Type ");
writeString(CURRENCY_CODE_COL, rowHeader, "Currency Code ");
}
public Integer getFundsSize() {
return funds.size();
}
public Integer getPaymentTypesSize() {
return paymentTypes.size();
}
public Integer getCurrenciesSize() {
return currencies.size();
}
public Integer getCurrenciesSize() {
return currencies.size();
}
}
@@ -27,45 +27,45 @@ import org.apache.poi.ss.usermodel.Workbook;
import java.util.List;
public class GlAccountSheetPopulator extends AbstractWorkbookPopulator {
private List<GLAccountData> allGlAccounts;
private List<GLAccountData> allGlAccounts;
private static final int ID_COL = 0;
private static final int ACCOUNT_NAME_COL = 1;
private static final int ID_COL = 0;
private static final int ACCOUNT_NAME_COL = 1;
public GlAccountSheetPopulator(List<GLAccountData> glAccounts) {
this.allGlAccounts = glAccounts;
}
public GlAccountSheetPopulator(List<GLAccountData> glAccounts) {
this.allGlAccounts = glAccounts;
}
@Override
public void populate(Workbook workbook,String dateFormat) {
int rowIndex = 1;
Sheet glAccountSheet = workbook.createSheet(TemplatePopulateImportConstants.GL_ACCOUNTS_SHEET_NAME);
setLayout(glAccountSheet);
populateglAccounts(glAccountSheet, rowIndex);
glAccountSheet.protectSheet("");
@Override
public void populate(Workbook workbook,String dateFormat) {
int rowIndex = 1;
Sheet glAccountSheet = workbook.createSheet(TemplatePopulateImportConstants.GL_ACCOUNTS_SHEET_NAME);
setLayout(glAccountSheet);
populateglAccounts(glAccountSheet, rowIndex);
glAccountSheet.protectSheet("");
}
}
private void setLayout(Sheet worksheet) {
worksheet.setColumnWidth(ID_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(ACCOUNT_NAME_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE);
Row rowHeader = worksheet.createRow(TemplatePopulateImportConstants.ROWHEADER_INDEX);
rowHeader.setHeight(TemplatePopulateImportConstants.ROW_HEADER_HEIGHT);
writeString(ID_COL, rowHeader, "Gl Account ID");
writeString(ACCOUNT_NAME_COL, rowHeader, "Gl Account Name");
}
private void setLayout(Sheet worksheet) {
worksheet.setColumnWidth(ID_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(ACCOUNT_NAME_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE);
Row rowHeader = worksheet.createRow(TemplatePopulateImportConstants.ROWHEADER_INDEX);
rowHeader.setHeight(TemplatePopulateImportConstants.ROW_HEADER_HEIGHT);
writeString(ID_COL, rowHeader, "Gl Account ID");
writeString(ACCOUNT_NAME_COL, rowHeader, "Gl Account Name");
}
private void populateglAccounts(Sheet GlAccountSheet, int rowIndex) {
for (GLAccountData glAccount : allGlAccounts) {
Row row = GlAccountSheet.createRow(rowIndex);
writeLong(ID_COL, row, glAccount.getId());
writeString(ACCOUNT_NAME_COL, row, glAccount.getName().trim().replaceAll("[ )(]", "_"));
rowIndex++;
}
}
private void populateglAccounts(Sheet GlAccountSheet, int rowIndex) {
for (GLAccountData glAccount : allGlAccounts) {
Row row = GlAccountSheet.createRow(rowIndex);
writeLong(ID_COL, row, glAccount.getId());
writeString(ACCOUNT_NAME_COL, row, glAccount.getName().trim().replaceAll("[ )(]", "_"));
rowIndex++;
}
}
public Integer getGlAccountNamesSize() {
return allGlAccounts.size();
}
public Integer getGlAccountNamesSize() {
return allGlAccounts.size();
}
}
@@ -32,49 +32,49 @@ import java.util.Map;
public class GroupSheetPopulator extends AbstractWorkbookPopulator {
private List<GroupGeneralData> groups;
private List<OfficeData> offices;
private Map<String, ArrayList<String>> officeToGroups;
private Map<Integer, Integer[]> officeNameToBeginEndIndexesOfGroups;
private Map<String,Long> groupNameToGroupId;
private List<GroupGeneralData> groups;
private List<OfficeData> offices;
private Map<String, ArrayList<String>> officeToGroups;
private Map<Integer, Integer[]> officeNameToBeginEndIndexesOfGroups;
private Map<String,Long> groupNameToGroupId;
private static final int OFFICE_NAME_COL = 0;
private static final int GROUP_NAME_COL = 1;
private static final int GROUP_ID_COL = 2;
private static final int OFFICE_NAME_COL = 0;
private static final int GROUP_NAME_COL = 1;
private static final int GROUP_ID_COL = 2;
public GroupSheetPopulator(final List<GroupGeneralData> groups, final List<OfficeData> offices) {
this.groups = groups;
this.offices = offices;
}
public GroupSheetPopulator(final List<GroupGeneralData> groups, final List<OfficeData> offices) {
this.groups = groups;
this.offices = offices;
}
@Override
public void populate(Workbook workbook,String dateFormat) {
Sheet groupSheet = workbook.createSheet(TemplatePopulateImportConstants.GROUP_SHEET_NAME);
setLayout(groupSheet);
setGroupNameToGroupIdMap();
setOfficeToGroupsMap();
populateGroupsByOfficeName(groupSheet);
groupSheet.protectSheet("");
}
@Override
public void populate(Workbook workbook,String dateFormat) {
Sheet groupSheet = workbook.createSheet(TemplatePopulateImportConstants.GROUP_SHEET_NAME);
setLayout(groupSheet);
setGroupNameToGroupIdMap();
setOfficeToGroupsMap();
populateGroupsByOfficeName(groupSheet);
groupSheet.protectSheet("");
}
private void setLayout(Sheet worksheet) {
Row rowHeader = worksheet.createRow(TemplatePopulateImportConstants.ROWHEADER_INDEX);
rowHeader.setHeight(TemplatePopulateImportConstants.ROW_HEADER_HEIGHT);
for (int colIndex = 0; colIndex <= 10; colIndex++)
worksheet.setColumnWidth(colIndex, TemplatePopulateImportConstants.MEDIUM_COL_SIZE);
writeString(OFFICE_NAME_COL, rowHeader, "Office Names");
writeString(GROUP_NAME_COL, rowHeader, "Group Names");
writeString(GROUP_ID_COL, rowHeader, "Group ID");
}
private void setLayout(Sheet worksheet) {
Row rowHeader = worksheet.createRow(TemplatePopulateImportConstants.ROWHEADER_INDEX);
rowHeader.setHeight(TemplatePopulateImportConstants.ROW_HEADER_HEIGHT);
for (int colIndex = 0; colIndex <= 10; colIndex++)
worksheet.setColumnWidth(colIndex, TemplatePopulateImportConstants.MEDIUM_COL_SIZE);
writeString(OFFICE_NAME_COL, rowHeader, "Office Names");
writeString(GROUP_NAME_COL, rowHeader, "Group Names");
writeString(GROUP_ID_COL, rowHeader, "Group ID");
}
private void setOfficeToGroupsMap() {
officeToGroups = new HashMap<>();
for (GroupGeneralData group : groups) {
add(group.getOfficeName().trim().replaceAll("[ )(]", "_"), group.getName().trim());
}
}
//Guava Multi-map can reduce this.
private void setOfficeToGroupsMap() {
officeToGroups = new HashMap<>();
for (GroupGeneralData group : groups) {
add(group.getOfficeName().trim().replaceAll("[ )(]", "_"), group.getName().trim());
}
}
//Guava Multi-map can reduce this.
private void add(String key, String value) {
ArrayList<String> values = officeToGroups.get(key);
if (values == null) {
@@ -84,43 +84,43 @@ public class GroupSheetPopulator extends AbstractWorkbookPopulator {
officeToGroups.put(key, values);
}
private void populateGroupsByOfficeName(Sheet groupSheet) {
int rowIndex = 1, officeIndex = 0, startIndex = 1;
officeNameToBeginEndIndexesOfGroups = new HashMap<>();
Row row = groupSheet.createRow(rowIndex);
for(OfficeData office : offices) {
startIndex = rowIndex+1;
writeString(OFFICE_NAME_COL, row, office.name());
ArrayList<String> groupsList = new ArrayList<>();
if(officeToGroups.containsKey(office.name().trim().replaceAll("[ )(]", "_")))
groupsList = officeToGroups.get(office.name().trim().replaceAll("[ )(]", "_"));
if(!groupsList.isEmpty()) {
for(String groupName : groupsList) {
writeString(GROUP_NAME_COL, row, groupName);
writeLong(GROUP_ID_COL, row, groupNameToGroupId.get(groupName));
row = groupSheet.createRow(++rowIndex);
}
officeNameToBeginEndIndexesOfGroups.put(officeIndex++, new Integer[]{startIndex, rowIndex});
}
else {
officeNameToBeginEndIndexesOfGroups.put(officeIndex++, new Integer[]{startIndex, rowIndex+1});
}
}
int rowIndex = 1, officeIndex = 0, startIndex = 1;
officeNameToBeginEndIndexesOfGroups = new HashMap<>();
Row row = groupSheet.createRow(rowIndex);
for(OfficeData office : offices) {
startIndex = rowIndex+1;
writeString(OFFICE_NAME_COL, row, office.name());
ArrayList<String> groupsList = new ArrayList<>();
if(officeToGroups.containsKey(office.name().trim().replaceAll("[ )(]", "_")))
groupsList = officeToGroups.get(office.name().trim().replaceAll("[ )(]", "_"));
if(!groupsList.isEmpty()) {
for(String groupName : groupsList) {
writeString(GROUP_NAME_COL, row, groupName);
writeLong(GROUP_ID_COL, row, groupNameToGroupId.get(groupName));
row = groupSheet.createRow(++rowIndex);
}
officeNameToBeginEndIndexesOfGroups.put(officeIndex++, new Integer[]{startIndex, rowIndex});
}
else {
officeNameToBeginEndIndexesOfGroups.put(officeIndex++, new Integer[]{startIndex, rowIndex+1});
}
}
}
public List<GroupGeneralData> getGroups() {
return groups;
return groups;
}
public Integer getGroupsSize() {
return groups.size();
return groups.size();
}
public Map<Integer, Integer[]> getOfficeNameToBeginEndIndexesOfGroups() {
return officeNameToBeginEndIndexesOfGroups;
return officeNameToBeginEndIndexesOfGroups;
}
private void setGroupNameToGroupIdMap(){
groupNameToGroupId=new HashMap<String,Long>();
for (GroupGeneralData group : groups) {
groupNameToGroupId.put(group.getName().trim(), group.getId());
}
groupNameToGroupId=new HashMap<String,Long>();
for (GroupGeneralData group : groups) {
groupNameToGroupId.put(group.getName().trim(), group.getId());
}
}
}
@@ -30,170 +30,170 @@ import java.util.List;
public class LoanProductSheetPopulator extends AbstractWorkbookPopulator {
private List<LoanProductData> products;
private static final int ID_COL = 0;
private static final int NAME_COL = 1;
private static final int FUND_NAME_COL = 2;
private static final int PRINCIPAL_COL = 3;
private static final int MIN_PRINCIPAL_COL = 4;
private static final int MAX_PRINCIPAL_COL = 5;
private static final int NO_OF_REPAYMENTS_COL = 6;
private static final int MIN_REPAYMENTS_COL = 7;
private static final int MAX_REPAYMENTS_COL = 8;
private static final int REPAYMENT_EVERY_COL = 9;
private static final int REPAYMENT_FREQUENCY_COL = 10;
private static final int INTEREST_RATE_COL = 11;
private static final int MIN_INTEREST_RATE_COL = 12;
private static final int MAX_INTEREST_RATE_COL = 13;
private static final int INTEREST_RATE_FREQUENCY_COL = 14;
private static final int AMORTIZATION_TYPE_COL = 15;
private static final int INTEREST_TYPE_COL = 16;
private static final int INTEREST_CALCULATION_PERIOD_TYPE_COL = 17;
private static final int IN_ARREARS_TOLERANCE_COL = 18;
private static final int TRANSACTION_PROCESSING_STRATEGY_NAME_COL = 19;
private static final int GRACE_ON_PRINCIPAL_PAYMENT_COL = 20;
private static final int GRACE_ON_INTEREST_PAYMENT_COL = 21;
private static final int GRACE_ON_INTEREST_CHARGED_COL = 22;
private static final int START_DATE_COL = 23;
private static final int CLOSE_DATE_COL = 24;
private List<LoanProductData> products;
private static final int ID_COL = 0;
private static final int NAME_COL = 1;
private static final int FUND_NAME_COL = 2;
private static final int PRINCIPAL_COL = 3;
private static final int MIN_PRINCIPAL_COL = 4;
private static final int MAX_PRINCIPAL_COL = 5;
private static final int NO_OF_REPAYMENTS_COL = 6;
private static final int MIN_REPAYMENTS_COL = 7;
private static final int MAX_REPAYMENTS_COL = 8;
private static final int REPAYMENT_EVERY_COL = 9;
private static final int REPAYMENT_FREQUENCY_COL = 10;
private static final int INTEREST_RATE_COL = 11;
private static final int MIN_INTEREST_RATE_COL = 12;
private static final int MAX_INTEREST_RATE_COL = 13;
private static final int INTEREST_RATE_FREQUENCY_COL = 14;
private static final int AMORTIZATION_TYPE_COL = 15;
private static final int INTEREST_TYPE_COL = 16;
private static final int INTEREST_CALCULATION_PERIOD_TYPE_COL = 17;
private static final int IN_ARREARS_TOLERANCE_COL = 18;
private static final int TRANSACTION_PROCESSING_STRATEGY_NAME_COL = 19;
private static final int GRACE_ON_PRINCIPAL_PAYMENT_COL = 20;
private static final int GRACE_ON_INTEREST_PAYMENT_COL = 21;
private static final int GRACE_ON_INTEREST_CHARGED_COL = 22;
private static final int START_DATE_COL = 23;
private static final int CLOSE_DATE_COL = 24;
public LoanProductSheetPopulator(List<LoanProductData> products) {
this.products = products;
}
public LoanProductSheetPopulator(List<LoanProductData> products) {
this.products = products;
}
@Override
public void populate(Workbook workbook,String dateFormat) {
int rowIndex = 1;
Sheet productSheet = workbook.createSheet(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME);
setLayout(productSheet);
CellStyle dateCellStyle = workbook.createCellStyle();
short df = workbook.createDataFormat().getFormat(dateFormat);
dateCellStyle.setDataFormat(df);
for (LoanProductData product : products) {
Row row = productSheet.createRow(rowIndex++);
writeLong(ID_COL, row, product.getId());
writeString(NAME_COL, row, product.getName().trim().replaceAll("[ )(]", "_"));
if (product.getFundName() != null)
writeString(FUND_NAME_COL, row, product.getFundName());
writeBigDecimal(PRINCIPAL_COL, row, product.getPrincipal());
if (product.getMinPrincipal() != null)
writeBigDecimal(MIN_PRINCIPAL_COL, row, product.getMinPrincipal());
else
writeInt(MIN_PRINCIPAL_COL, row, 1);
if (product.getMaxPrincipal() != null)
writeBigDecimal(MAX_PRINCIPAL_COL, row, product.getMaxPrincipal());
else
writeInt(MAX_PRINCIPAL_COL, row, 999999999);
writeInt(NO_OF_REPAYMENTS_COL, row, product.getNumberOfRepayments());
if (product.getMinNumberOfRepayments() != null)
writeInt(MIN_REPAYMENTS_COL, row, product.getMinNumberOfRepayments());
else
writeInt(MIN_REPAYMENTS_COL, row, 1);
if (product.getMaxNumberOfRepayments() != null)
writeInt(MAX_REPAYMENTS_COL, row, product.getMaxNumberOfRepayments());
else
writeInt(MAX_REPAYMENTS_COL, row, 999999999);
writeInt(REPAYMENT_EVERY_COL, row, product.getRepaymentEvery());
writeString(REPAYMENT_FREQUENCY_COL, row, product.getRepaymentFrequencyType().getValue());
writeBigDecimal(INTEREST_RATE_COL, row, product.getInterestRatePerPeriod());
if (product.getMinInterestRatePerPeriod() != null)
writeBigDecimal(MIN_INTEREST_RATE_COL, row, product.getMinInterestRatePerPeriod());
else
writeInt(MIN_INTEREST_RATE_COL, row, 1);
if (product.getMaxInterestRatePerPeriod() != null)
writeBigDecimal(MAX_INTEREST_RATE_COL, row, product.getMaxInterestRatePerPeriod());
else
writeInt(MAX_INTEREST_RATE_COL, row, 999999999);
writeString(INTEREST_RATE_FREQUENCY_COL, row, product.getInterestRateFrequencyType().getValue());
writeString(AMORTIZATION_TYPE_COL, row, product.getAmortizationType().getValue());
writeString(INTEREST_TYPE_COL, row, product.getInterestType().getValue());
writeString(INTEREST_CALCULATION_PERIOD_TYPE_COL, row,
product.getInterestCalculationPeriodType().getValue());
if (product.getInArrearsTolerance() != null)
writeBigDecimal(IN_ARREARS_TOLERANCE_COL, row, product.getInArrearsTolerance());
writeString(TRANSACTION_PROCESSING_STRATEGY_NAME_COL, row, product.getTransactionProcessingStrategyName());
if (product.getGraceOnPrincipalPayment() != null)
writeInt(GRACE_ON_PRINCIPAL_PAYMENT_COL, row, product.getGraceOnPrincipalPayment());
if (product.getGraceOnInterestPayment() != null)
writeInt(GRACE_ON_INTEREST_PAYMENT_COL, row, product.getGraceOnInterestPayment());
if (product.getGraceOnInterestCharged() != null)
writeInt(GRACE_ON_INTEREST_CHARGED_COL, row, product.getGraceOnInterestCharged());
if (product.getStartDate() != null)
writeDate(START_DATE_COL, row, product.getStartDate().toString(), dateCellStyle,dateFormat);
else
writeDate(START_DATE_COL, row, "1/1/1970", dateCellStyle,dateFormat);
if (product.getCloseDate() != null)
writeDate(CLOSE_DATE_COL, row, product.getCloseDate().toString(), dateCellStyle,dateFormat);
else
writeDate(CLOSE_DATE_COL, row, "1/1/2040", dateCellStyle,dateFormat);
productSheet.protectSheet("");
}
@Override
public void populate(Workbook workbook,String dateFormat) {
int rowIndex = 1;
Sheet productSheet = workbook.createSheet(TemplatePopulateImportConstants.PRODUCT_SHEET_NAME);
setLayout(productSheet);
CellStyle dateCellStyle = workbook.createCellStyle();
short df = workbook.createDataFormat().getFormat(dateFormat);
dateCellStyle.setDataFormat(df);
for (LoanProductData product : products) {
Row row = productSheet.createRow(rowIndex++);
writeLong(ID_COL, row, product.getId());
writeString(NAME_COL, row, product.getName().trim().replaceAll("[ )(]", "_"));
if (product.getFundName() != null)
writeString(FUND_NAME_COL, row, product.getFundName());
writeBigDecimal(PRINCIPAL_COL, row, product.getPrincipal());
if (product.getMinPrincipal() != null)
writeBigDecimal(MIN_PRINCIPAL_COL, row, product.getMinPrincipal());
else
writeInt(MIN_PRINCIPAL_COL, row, 1);
if (product.getMaxPrincipal() != null)
writeBigDecimal(MAX_PRINCIPAL_COL, row, product.getMaxPrincipal());
else
writeInt(MAX_PRINCIPAL_COL, row, 999999999);
writeInt(NO_OF_REPAYMENTS_COL, row, product.getNumberOfRepayments());
if (product.getMinNumberOfRepayments() != null)
writeInt(MIN_REPAYMENTS_COL, row, product.getMinNumberOfRepayments());
else
writeInt(MIN_REPAYMENTS_COL, row, 1);
if (product.getMaxNumberOfRepayments() != null)
writeInt(MAX_REPAYMENTS_COL, row, product.getMaxNumberOfRepayments());
else
writeInt(MAX_REPAYMENTS_COL, row, 999999999);
writeInt(REPAYMENT_EVERY_COL, row, product.getRepaymentEvery());
writeString(REPAYMENT_FREQUENCY_COL, row, product.getRepaymentFrequencyType().getValue());
writeBigDecimal(INTEREST_RATE_COL, row, product.getInterestRatePerPeriod());
if (product.getMinInterestRatePerPeriod() != null)
writeBigDecimal(MIN_INTEREST_RATE_COL, row, product.getMinInterestRatePerPeriod());
else
writeInt(MIN_INTEREST_RATE_COL, row, 1);
if (product.getMaxInterestRatePerPeriod() != null)
writeBigDecimal(MAX_INTEREST_RATE_COL, row, product.getMaxInterestRatePerPeriod());
else
writeInt(MAX_INTEREST_RATE_COL, row, 999999999);
writeString(INTEREST_RATE_FREQUENCY_COL, row, product.getInterestRateFrequencyType().getValue());
writeString(AMORTIZATION_TYPE_COL, row, product.getAmortizationType().getValue());
writeString(INTEREST_TYPE_COL, row, product.getInterestType().getValue());
writeString(INTEREST_CALCULATION_PERIOD_TYPE_COL, row,
product.getInterestCalculationPeriodType().getValue());
if (product.getInArrearsTolerance() != null)
writeBigDecimal(IN_ARREARS_TOLERANCE_COL, row, product.getInArrearsTolerance());
writeString(TRANSACTION_PROCESSING_STRATEGY_NAME_COL, row, product.getTransactionProcessingStrategyName());
if (product.getGraceOnPrincipalPayment() != null)
writeInt(GRACE_ON_PRINCIPAL_PAYMENT_COL, row, product.getGraceOnPrincipalPayment());
if (product.getGraceOnInterestPayment() != null)
writeInt(GRACE_ON_INTEREST_PAYMENT_COL, row, product.getGraceOnInterestPayment());
if (product.getGraceOnInterestCharged() != null)
writeInt(GRACE_ON_INTEREST_CHARGED_COL, row, product.getGraceOnInterestCharged());
if (product.getStartDate() != null)
writeDate(START_DATE_COL, row, product.getStartDate().toString(), dateCellStyle,dateFormat);
else
writeDate(START_DATE_COL, row, "1/1/1970", dateCellStyle,dateFormat);
if (product.getCloseDate() != null)
writeDate(CLOSE_DATE_COL, row, product.getCloseDate().toString(), dateCellStyle,dateFormat);
else
writeDate(CLOSE_DATE_COL, row, "1/1/2040", dateCellStyle,dateFormat);
productSheet.protectSheet("");
}
}
}
private void setLayout(Sheet worksheet) {
worksheet.setColumnWidth(ID_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(NAME_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(FUND_NAME_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(PRINCIPAL_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(MIN_PRINCIPAL_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(MAX_PRINCIPAL_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(NO_OF_REPAYMENTS_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(MIN_REPAYMENTS_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(MAX_REPAYMENTS_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(REPAYMENT_EVERY_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(REPAYMENT_FREQUENCY_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(INTEREST_RATE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(MIN_INTEREST_RATE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(MAX_INTEREST_RATE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(INTEREST_RATE_FREQUENCY_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(AMORTIZATION_TYPE_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE);
worksheet.setColumnWidth(INTEREST_TYPE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(INTEREST_CALCULATION_PERIOD_TYPE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(IN_ARREARS_TOLERANCE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(TRANSACTION_PROCESSING_STRATEGY_NAME_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(GRACE_ON_PRINCIPAL_PAYMENT_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(GRACE_ON_INTEREST_PAYMENT_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE);
worksheet.setColumnWidth(GRACE_ON_INTEREST_CHARGED_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE);
worksheet.setColumnWidth(START_DATE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(CLOSE_DATE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
private void setLayout(Sheet worksheet) {
worksheet.setColumnWidth(ID_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(NAME_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(FUND_NAME_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(PRINCIPAL_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(MIN_PRINCIPAL_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(MAX_PRINCIPAL_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(NO_OF_REPAYMENTS_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(MIN_REPAYMENTS_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(MAX_REPAYMENTS_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(REPAYMENT_EVERY_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(REPAYMENT_FREQUENCY_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(INTEREST_RATE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(MIN_INTEREST_RATE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(MAX_INTEREST_RATE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(INTEREST_RATE_FREQUENCY_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(AMORTIZATION_TYPE_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE);
worksheet.setColumnWidth(INTEREST_TYPE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(INTEREST_CALCULATION_PERIOD_TYPE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(IN_ARREARS_TOLERANCE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(TRANSACTION_PROCESSING_STRATEGY_NAME_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(GRACE_ON_PRINCIPAL_PAYMENT_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(GRACE_ON_INTEREST_PAYMENT_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE);
worksheet.setColumnWidth(GRACE_ON_INTEREST_CHARGED_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE);
worksheet.setColumnWidth(START_DATE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(CLOSE_DATE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
Row rowHeader = worksheet.createRow(TemplatePopulateImportConstants.ROWHEADER_INDEX);
rowHeader.setHeight(TemplatePopulateImportConstants.ROW_HEADER_HEIGHT);
writeString(ID_COL, rowHeader, "ID");
writeString(NAME_COL, rowHeader, "Name");
writeString(FUND_NAME_COL, rowHeader, "Fund");
writeString(PRINCIPAL_COL, rowHeader, "Principal");
writeString(MIN_PRINCIPAL_COL, rowHeader, "Min Principal");
writeString(MAX_PRINCIPAL_COL, rowHeader, "Max Principal");
writeString(NO_OF_REPAYMENTS_COL, rowHeader, "# of Repayments");
writeString(MIN_REPAYMENTS_COL, rowHeader, "Min Repayments");
writeString(MAX_REPAYMENTS_COL, rowHeader, "Max Repayments");
writeString(REPAYMENT_EVERY_COL, rowHeader, "Repayment Every");
writeString(REPAYMENT_FREQUENCY_COL, rowHeader, "Frequency");
writeString(INTEREST_RATE_COL, rowHeader, "Interest");
writeString(MIN_INTEREST_RATE_COL, rowHeader, "Min Interest");
writeString(MAX_INTEREST_RATE_COL, rowHeader, "Max Interest");
writeString(INTEREST_RATE_FREQUENCY_COL, rowHeader, "Frequency");
writeString(AMORTIZATION_TYPE_COL, rowHeader, "Amortization Type");
writeString(INTEREST_TYPE_COL, rowHeader, "Interest Type");
writeString(INTEREST_CALCULATION_PERIOD_TYPE_COL, rowHeader, "Interest Calculation Period");
writeString(IN_ARREARS_TOLERANCE_COL, rowHeader, "In Arrears Tolerance");
writeString(TRANSACTION_PROCESSING_STRATEGY_NAME_COL, rowHeader, "Transaction Processing Strategy");
writeString(GRACE_ON_PRINCIPAL_PAYMENT_COL, rowHeader, "Grace On Principal Payment");
writeString(GRACE_ON_INTEREST_PAYMENT_COL, rowHeader, "Grace on Interest Payment");
writeString(GRACE_ON_INTEREST_CHARGED_COL, rowHeader, "Grace on Interest Charged");
writeString(START_DATE_COL, rowHeader, "Start Date");
writeString(CLOSE_DATE_COL, rowHeader, "End Date");
}
public List<LoanProductData> getProducts(){
return products;
}
public Integer getProductsSize() {
return products.size();
}
Row rowHeader = worksheet.createRow(TemplatePopulateImportConstants.ROWHEADER_INDEX);
rowHeader.setHeight(TemplatePopulateImportConstants.ROW_HEADER_HEIGHT);
writeString(ID_COL, rowHeader, "ID");
writeString(NAME_COL, rowHeader, "Name");
writeString(FUND_NAME_COL, rowHeader, "Fund");
writeString(PRINCIPAL_COL, rowHeader, "Principal");
writeString(MIN_PRINCIPAL_COL, rowHeader, "Min Principal");
writeString(MAX_PRINCIPAL_COL, rowHeader, "Max Principal");
writeString(NO_OF_REPAYMENTS_COL, rowHeader, "# of Repayments");
writeString(MIN_REPAYMENTS_COL, rowHeader, "Min Repayments");
writeString(MAX_REPAYMENTS_COL, rowHeader, "Max Repayments");
writeString(REPAYMENT_EVERY_COL, rowHeader, "Repayment Every");
writeString(REPAYMENT_FREQUENCY_COL, rowHeader, "Frequency");
writeString(INTEREST_RATE_COL, rowHeader, "Interest");
writeString(MIN_INTEREST_RATE_COL, rowHeader, "Min Interest");
writeString(MAX_INTEREST_RATE_COL, rowHeader, "Max Interest");
writeString(INTEREST_RATE_FREQUENCY_COL, rowHeader, "Frequency");
writeString(AMORTIZATION_TYPE_COL, rowHeader, "Amortization Type");
writeString(INTEREST_TYPE_COL, rowHeader, "Interest Type");
writeString(INTEREST_CALCULATION_PERIOD_TYPE_COL, rowHeader, "Interest Calculation Period");
writeString(IN_ARREARS_TOLERANCE_COL, rowHeader, "In Arrears Tolerance");
writeString(TRANSACTION_PROCESSING_STRATEGY_NAME_COL, rowHeader, "Transaction Processing Strategy");
writeString(GRACE_ON_PRINCIPAL_PAYMENT_COL, rowHeader, "Grace On Principal Payment");
writeString(GRACE_ON_INTEREST_PAYMENT_COL, rowHeader, "Grace on Interest Payment");
writeString(GRACE_ON_INTEREST_CHARGED_COL, rowHeader, "Grace on Interest Charged");
writeString(START_DATE_COL, rowHeader, "Start Date");
writeString(CLOSE_DATE_COL, rowHeader, "End Date");
}
public List<LoanProductData> getProducts(){
return products;
}
public Integer getProductsSize() {
return products.size();
}
}
@@ -72,11 +72,11 @@ public class OfficeSheetPopulator extends AbstractWorkbookPopulator {
}
public List<String> getOfficeNames() {
List<String> officeNames=new ArrayList<>();
for (OfficeData office : offices) {
officeNames.add(office.name());
}
return officeNames;
List<String> officeNames=new ArrayList<>();
for (OfficeData office : offices) {
officeNames.add(office.name());
}
return officeNames;
}
}
@@ -37,152 +37,152 @@ import java.util.List;
public class CentersWorkbookPopulator extends AbstractWorkbookPopulator {
private OfficeSheetPopulator officeSheetPopulator;
private PersonnelSheetPopulator personnelSheetPopulator;
private GroupSheetPopulator groupSheetPopulator;
private OfficeSheetPopulator officeSheetPopulator;
private PersonnelSheetPopulator personnelSheetPopulator;
private GroupSheetPopulator groupSheetPopulator;
public CentersWorkbookPopulator(OfficeSheetPopulator officeSheetPopulator,
PersonnelSheetPopulator personnelSheetPopulator,GroupSheetPopulator groupSheetPopulator) {
this.officeSheetPopulator = officeSheetPopulator;
this.personnelSheetPopulator = personnelSheetPopulator;
this.groupSheetPopulator=groupSheetPopulator;
}
public CentersWorkbookPopulator(OfficeSheetPopulator officeSheetPopulator,
PersonnelSheetPopulator personnelSheetPopulator,GroupSheetPopulator groupSheetPopulator) {
this.officeSheetPopulator = officeSheetPopulator;
this.personnelSheetPopulator = personnelSheetPopulator;
this.groupSheetPopulator=groupSheetPopulator;
}
@Override
public void populate(Workbook workbook,String dateFormat) {
Sheet centerSheet = workbook.createSheet(TemplatePopulateImportConstants.CENTER_SHEET_NAME);
personnelSheetPopulator.populate(workbook,dateFormat);
officeSheetPopulator.populate(workbook,dateFormat);
groupSheetPopulator.populate(workbook,dateFormat);
setLayout(centerSheet);
setLookupTable(centerSheet,dateFormat);
setRules(centerSheet,dateFormat);
}
@Override
public void populate(Workbook workbook,String dateFormat) {
Sheet centerSheet = workbook.createSheet(TemplatePopulateImportConstants.CENTER_SHEET_NAME);
personnelSheetPopulator.populate(workbook,dateFormat);
officeSheetPopulator.populate(workbook,dateFormat);
groupSheetPopulator.populate(workbook,dateFormat);
setLayout(centerSheet);
setLookupTable(centerSheet,dateFormat);
setRules(centerSheet,dateFormat);
}
private void setLayout(Sheet worksheet) {
Row rowHeader = worksheet.createRow(0);
rowHeader.setHeight(TemplatePopulateImportConstants.ROW_HEADER_HEIGHT);
worksheet.setColumnWidth(CenterConstants.CENTER_NAME_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(CenterConstants.OFFICE_NAME_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE);
worksheet.setColumnWidth(CenterConstants.STAFF_NAME_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE);
worksheet.setColumnWidth(CenterConstants.EXTERNAL_ID_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(CenterConstants.ACTIVE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(CenterConstants.ACTIVATION_DATE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(CenterConstants.SUBMITTED_ON_DATE_COL,TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(CenterConstants.MEETING_START_DATE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(CenterConstants.IS_REPEATING_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(CenterConstants.FREQUENCY_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(CenterConstants.INTERVAL_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(CenterConstants.REPEATS_ON_DAY_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(CenterConstants.STATUS_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(CenterConstants.CENTER_ID_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(CenterConstants.FAILURE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(CenterConstants.GROUP_NAMES_STARTING_COL,TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(CenterConstants.LOOKUP_OFFICE_NAME_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE);
worksheet.setColumnWidth(CenterConstants.LOOKUP_OFFICE_OPENING_DATE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(CenterConstants.LOOKUP_REPEAT_NORMAL_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(CenterConstants.LOOKUP_REPEAT_MONTHLY_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(CenterConstants.LOOKUP_IF_REPEAT_WEEKLY_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
private void setLayout(Sheet worksheet) {
Row rowHeader = worksheet.createRow(0);
rowHeader.setHeight(TemplatePopulateImportConstants.ROW_HEADER_HEIGHT);
worksheet.setColumnWidth(CenterConstants.CENTER_NAME_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(CenterConstants.OFFICE_NAME_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE);
worksheet.setColumnWidth(CenterConstants.STAFF_NAME_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE);
worksheet.setColumnWidth(CenterConstants.EXTERNAL_ID_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(CenterConstants.ACTIVE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(CenterConstants.ACTIVATION_DATE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(CenterConstants.SUBMITTED_ON_DATE_COL,TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(CenterConstants.MEETING_START_DATE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(CenterConstants.IS_REPEATING_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(CenterConstants.FREQUENCY_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(CenterConstants.INTERVAL_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(CenterConstants.REPEATS_ON_DAY_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(CenterConstants.STATUS_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(CenterConstants.CENTER_ID_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(CenterConstants.FAILURE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(CenterConstants.GROUP_NAMES_STARTING_COL,TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(CenterConstants.LOOKUP_OFFICE_NAME_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE);
worksheet.setColumnWidth(CenterConstants.LOOKUP_OFFICE_OPENING_DATE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(CenterConstants.LOOKUP_REPEAT_NORMAL_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(CenterConstants.LOOKUP_REPEAT_MONTHLY_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(CenterConstants.LOOKUP_IF_REPEAT_WEEKLY_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
writeString(CenterConstants.CENTER_NAME_COL, rowHeader, "Center Name*");
writeString(CenterConstants.OFFICE_NAME_COL, rowHeader, "Office Name*");
writeString(CenterConstants.STAFF_NAME_COL, rowHeader, "Staff Name*");
writeString(CenterConstants.EXTERNAL_ID_COL, rowHeader, "External ID");
writeString(CenterConstants.ACTIVE_COL, rowHeader, "Active*");
writeString(CenterConstants.ACTIVATION_DATE_COL, rowHeader, "Activation Date*");
writeString(CenterConstants.SUBMITTED_ON_DATE_COL,rowHeader,"Submitted On Date");
writeString(CenterConstants.MEETING_START_DATE_COL, rowHeader, "Meeting Start Date* (On or After)");
writeString(CenterConstants.IS_REPEATING_COL, rowHeader, "Repeat*");
writeString(CenterConstants.FREQUENCY_COL, rowHeader, "Frequency*");
writeString(CenterConstants.INTERVAL_COL, rowHeader, "Interval*");
writeString(CenterConstants.REPEATS_ON_DAY_COL, rowHeader, "Repeats On*");
writeString(CenterConstants.GROUP_NAMES_STARTING_COL,rowHeader,"Group Names* (Enter in consecutive cells horizontally)");
writeString(CenterConstants.LOOKUP_OFFICE_NAME_COL, rowHeader, "Office Name");
writeString(CenterConstants.LOOKUP_OFFICE_OPENING_DATE_COL, rowHeader, "Opening Date");
writeString(CenterConstants.LOOKUP_REPEAT_NORMAL_COL, rowHeader, "Repeat Normal Range");
writeString(CenterConstants.LOOKUP_REPEAT_MONTHLY_COL, rowHeader, "Repeat Monthly Range");
writeString(CenterConstants.LOOKUP_IF_REPEAT_WEEKLY_COL, rowHeader, "If Repeat Weekly Range");
}
private void setLookupTable(Sheet centerSheet,String dateFormat) {
setOfficeDateLookupTable(centerSheet, officeSheetPopulator.getOffices(), CenterConstants.LOOKUP_OFFICE_NAME_COL,CenterConstants.LOOKUP_OFFICE_OPENING_DATE_COL,dateFormat);
int rowIndex;
for(rowIndex = 1; rowIndex <= 11; rowIndex++) {
Row row = centerSheet.getRow(rowIndex);
if(row == null)
row = centerSheet.createRow(rowIndex);
writeInt(CenterConstants.LOOKUP_REPEAT_MONTHLY_COL, row, rowIndex);
}
for(rowIndex = 1; rowIndex <= 3; rowIndex++)
writeInt(CenterConstants.LOOKUP_REPEAT_NORMAL_COL, centerSheet.getRow(rowIndex), rowIndex);
writeString(CenterConstants.CENTER_NAME_COL, rowHeader, "Center Name*");
writeString(CenterConstants.OFFICE_NAME_COL, rowHeader, "Office Name*");
writeString(CenterConstants.STAFF_NAME_COL, rowHeader, "Staff Name*");
writeString(CenterConstants.EXTERNAL_ID_COL, rowHeader, "External ID");
writeString(CenterConstants.ACTIVE_COL, rowHeader, "Active*");
writeString(CenterConstants.ACTIVATION_DATE_COL, rowHeader, "Activation Date*");
writeString(CenterConstants.SUBMITTED_ON_DATE_COL,rowHeader,"Submitted On Date");
writeString(CenterConstants.MEETING_START_DATE_COL, rowHeader, "Meeting Start Date* (On or After)");
writeString(CenterConstants.IS_REPEATING_COL, rowHeader, "Repeat*");
writeString(CenterConstants.FREQUENCY_COL, rowHeader, "Frequency*");
writeString(CenterConstants.INTERVAL_COL, rowHeader, "Interval*");
writeString(CenterConstants.REPEATS_ON_DAY_COL, rowHeader, "Repeats On*");
writeString(CenterConstants.GROUP_NAMES_STARTING_COL,rowHeader,"Group Names* (Enter in consecutive cells horizontally)");
writeString(CenterConstants.LOOKUP_OFFICE_NAME_COL, rowHeader, "Office Name");
writeString(CenterConstants.LOOKUP_OFFICE_OPENING_DATE_COL, rowHeader, "Opening Date");
writeString(CenterConstants.LOOKUP_REPEAT_NORMAL_COL, rowHeader, "Repeat Normal Range");
writeString(CenterConstants.LOOKUP_REPEAT_MONTHLY_COL, rowHeader, "Repeat Monthly Range");
writeString(CenterConstants.LOOKUP_IF_REPEAT_WEEKLY_COL, rowHeader, "If Repeat Weekly Range");
}
private void setLookupTable(Sheet centerSheet,String dateFormat) {
setOfficeDateLookupTable(centerSheet, officeSheetPopulator.getOffices(), CenterConstants.LOOKUP_OFFICE_NAME_COL,CenterConstants.LOOKUP_OFFICE_OPENING_DATE_COL,dateFormat);
int rowIndex;
for(rowIndex = 1; rowIndex <= 11; rowIndex++) {
Row row = centerSheet.getRow(rowIndex);
if(row == null)
row = centerSheet.createRow(rowIndex);
writeInt(CenterConstants.LOOKUP_REPEAT_MONTHLY_COL, row, rowIndex);
}
for(rowIndex = 1; rowIndex <= 3; rowIndex++)
writeInt(CenterConstants.LOOKUP_REPEAT_NORMAL_COL, centerSheet.getRow(rowIndex), rowIndex);
String[] days = new String[]{
TemplatePopulateImportConstants.MONDAY,
TemplatePopulateImportConstants.TUESDAY,
TemplatePopulateImportConstants.WEDNESDAY,
TemplatePopulateImportConstants.THURSDAY,
TemplatePopulateImportConstants.FRIDAY,
TemplatePopulateImportConstants.SATURDAY,
TemplatePopulateImportConstants.SUNDAY};
String[] days = new String[]{
TemplatePopulateImportConstants.MONDAY,
TemplatePopulateImportConstants.TUESDAY,
TemplatePopulateImportConstants.WEDNESDAY,
TemplatePopulateImportConstants.THURSDAY,
TemplatePopulateImportConstants.FRIDAY,
TemplatePopulateImportConstants.SATURDAY,
TemplatePopulateImportConstants.SUNDAY};
for(rowIndex = 1; rowIndex <= 7; rowIndex++)
writeString(CenterConstants.LOOKUP_IF_REPEAT_WEEKLY_COL, centerSheet.getRow(rowIndex), days[rowIndex-1]);
}
private void setRules(Sheet worksheet,String dateFormat) {
CellRangeAddressList officeNameRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), CenterConstants.OFFICE_NAME_COL,CenterConstants. OFFICE_NAME_COL);
CellRangeAddressList staffNameRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), CenterConstants.STAFF_NAME_COL,CenterConstants. STAFF_NAME_COL);
CellRangeAddressList activationDateRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(),CenterConstants. ACTIVATION_DATE_COL,CenterConstants. ACTIVATION_DATE_COL);
CellRangeAddressList activeRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), CenterConstants.ACTIVE_COL, CenterConstants.ACTIVE_COL);
CellRangeAddressList submittedDateRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(),CenterConstants. SUBMITTED_ON_DATE_COL,CenterConstants.SUBMITTED_ON_DATE_COL);
CellRangeAddressList meetingStartDateRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), CenterConstants.MEETING_START_DATE_COL,CenterConstants. MEETING_START_DATE_COL);
CellRangeAddressList isRepeatRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(),CenterConstants. IS_REPEATING_COL,CenterConstants. IS_REPEATING_COL);
CellRangeAddressList repeatsRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), CenterConstants.FREQUENCY_COL, CenterConstants.FREQUENCY_COL);
CellRangeAddressList repeatsEveryRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), CenterConstants.INTERVAL_COL,CenterConstants. INTERVAL_COL);
CellRangeAddressList repeatsOnRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), CenterConstants.REPEATS_ON_DAY_COL,CenterConstants. REPEATS_ON_DAY_COL);
DataValidationHelper validationHelper = new HSSFDataValidationHelper((HSSFSheet)worksheet);
List<OfficeData> offices = officeSheetPopulator.getOffices();
setNames(worksheet, offices);
for(rowIndex = 1; rowIndex <= 7; rowIndex++)
writeString(CenterConstants.LOOKUP_IF_REPEAT_WEEKLY_COL, centerSheet.getRow(rowIndex), days[rowIndex-1]);
}
private void setRules(Sheet worksheet,String dateFormat) {
CellRangeAddressList officeNameRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), CenterConstants.OFFICE_NAME_COL,CenterConstants. OFFICE_NAME_COL);
CellRangeAddressList staffNameRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), CenterConstants.STAFF_NAME_COL,CenterConstants. STAFF_NAME_COL);
CellRangeAddressList activationDateRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(),CenterConstants. ACTIVATION_DATE_COL,CenterConstants. ACTIVATION_DATE_COL);
CellRangeAddressList activeRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), CenterConstants.ACTIVE_COL, CenterConstants.ACTIVE_COL);
CellRangeAddressList submittedDateRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(),CenterConstants. SUBMITTED_ON_DATE_COL,CenterConstants.SUBMITTED_ON_DATE_COL);
CellRangeAddressList meetingStartDateRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), CenterConstants.MEETING_START_DATE_COL,CenterConstants. MEETING_START_DATE_COL);
CellRangeAddressList isRepeatRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(),CenterConstants. IS_REPEATING_COL,CenterConstants. IS_REPEATING_COL);
CellRangeAddressList repeatsRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), CenterConstants.FREQUENCY_COL, CenterConstants.FREQUENCY_COL);
CellRangeAddressList repeatsEveryRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), CenterConstants.INTERVAL_COL,CenterConstants. INTERVAL_COL);
CellRangeAddressList repeatsOnRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(), CenterConstants.REPEATS_ON_DAY_COL,CenterConstants. REPEATS_ON_DAY_COL);
DataValidationHelper validationHelper = new HSSFDataValidationHelper((HSSFSheet)worksheet);
List<OfficeData> offices = officeSheetPopulator.getOffices();
setNames(worksheet, offices);
DataValidationConstraint officeNameConstraint = validationHelper.createFormulaListConstraint("Office");
DataValidationConstraint staffNameConstraint = validationHelper.
createFormulaListConstraint("INDIRECT(CONCATENATE(\"Staff_\",$B1))");
DataValidationConstraint activationDateConstraint = validationHelper.createDateConstraint
(DataValidationConstraint.OperatorType.BETWEEN, "=VLOOKUP($B1,$IR$2:$IS" + (offices.size() + 1)+",2,FALSE)",
"=TODAY()", dateFormat);
DataValidationConstraint booleanConstraint = validationHelper.createExplicitListConstraint(new String[]{"True", "False"});
DataValidationConstraint submittedOnDateConstraint =
validationHelper.createDateConstraint(DataValidationConstraint.OperatorType.LESS_OR_EQUAL,
"=$F1", null,dateFormat);
DataValidationConstraint meetingStartDateConstraint =
validationHelper.createDateConstraint(DataValidationConstraint.OperatorType.BETWEEN,
"=$F1", "=TODAY()", dateFormat);
DataValidationConstraint repeatsConstraint =
validationHelper.createExplicitListConstraint(new String[]{
TemplatePopulateImportConstants.FREQUENCY_DAILY,
TemplatePopulateImportConstants.FREQUENCY_WEEKLY,
TemplatePopulateImportConstants.FREQUENCY_MONTHLY,
TemplatePopulateImportConstants.FREQUENCY_YEARLY});
DataValidationConstraint repeatsEveryConstraint = validationHelper.createFormulaListConstraint("INDIRECT($J1)");
DataValidationConstraint repeatsOnConstraint = validationHelper.createFormulaListConstraint("INDIRECT(CONCATENATE($J1,\"_DAYS\"))");
DataValidationConstraint officeNameConstraint = validationHelper.createFormulaListConstraint("Office");
DataValidationConstraint staffNameConstraint = validationHelper.
createFormulaListConstraint("INDIRECT(CONCATENATE(\"Staff_\",$B1))");
DataValidationConstraint activationDateConstraint = validationHelper.createDateConstraint
(DataValidationConstraint.OperatorType.BETWEEN, "=VLOOKUP($B1,$IR$2:$IS" + (offices.size() + 1)+",2,FALSE)",
"=TODAY()", dateFormat);
DataValidationConstraint booleanConstraint = validationHelper.createExplicitListConstraint(new String[]{"True", "False"});
DataValidationConstraint submittedOnDateConstraint =
validationHelper.createDateConstraint(DataValidationConstraint.OperatorType.LESS_OR_EQUAL,
"=$F1", null,dateFormat);
DataValidationConstraint meetingStartDateConstraint =
validationHelper.createDateConstraint(DataValidationConstraint.OperatorType.BETWEEN,
"=$F1", "=TODAY()", dateFormat);
DataValidationConstraint repeatsConstraint =
validationHelper.createExplicitListConstraint(new String[]{
TemplatePopulateImportConstants.FREQUENCY_DAILY,
TemplatePopulateImportConstants.FREQUENCY_WEEKLY,
TemplatePopulateImportConstants.FREQUENCY_MONTHLY,
TemplatePopulateImportConstants.FREQUENCY_YEARLY});
DataValidationConstraint repeatsEveryConstraint = validationHelper.createFormulaListConstraint("INDIRECT($J1)");
DataValidationConstraint repeatsOnConstraint = validationHelper.createFormulaListConstraint("INDIRECT(CONCATENATE($J1,\"_DAYS\"))");
DataValidation officeValidation = validationHelper.createValidation(officeNameConstraint, officeNameRange);
DataValidation staffValidation = validationHelper.createValidation(staffNameConstraint, staffNameRange);
DataValidation activationDateValidation = validationHelper.createValidation(activationDateConstraint, activationDateRange);
DataValidation activeValidation = validationHelper.createValidation(booleanConstraint, activeRange);
DataValidation submittedOnValidation=validationHelper.createValidation(submittedOnDateConstraint,submittedDateRange);
DataValidation meetingStartDateValidation = validationHelper.createValidation(meetingStartDateConstraint, meetingStartDateRange);
DataValidation isRepeatValidation = validationHelper.createValidation(booleanConstraint, isRepeatRange);
DataValidation repeatsValidation = validationHelper.createValidation(repeatsConstraint, repeatsRange);
DataValidation repeatsEveryValidation = validationHelper.createValidation(repeatsEveryConstraint, repeatsEveryRange);
DataValidation repeatsOnValidation = validationHelper.createValidation(repeatsOnConstraint, repeatsOnRange);
DataValidation officeValidation = validationHelper.createValidation(officeNameConstraint, officeNameRange);
DataValidation staffValidation = validationHelper.createValidation(staffNameConstraint, staffNameRange);
DataValidation activationDateValidation = validationHelper.createValidation(activationDateConstraint, activationDateRange);
DataValidation activeValidation = validationHelper.createValidation(booleanConstraint, activeRange);
DataValidation submittedOnValidation=validationHelper.createValidation(submittedOnDateConstraint,submittedDateRange);
DataValidation meetingStartDateValidation = validationHelper.createValidation(meetingStartDateConstraint, meetingStartDateRange);
DataValidation isRepeatValidation = validationHelper.createValidation(booleanConstraint, isRepeatRange);
DataValidation repeatsValidation = validationHelper.createValidation(repeatsConstraint, repeatsRange);
DataValidation repeatsEveryValidation = validationHelper.createValidation(repeatsEveryConstraint, repeatsEveryRange);
DataValidation repeatsOnValidation = validationHelper.createValidation(repeatsOnConstraint, repeatsOnRange);
worksheet.addValidationData(activeValidation);
worksheet.addValidationData(activeValidation);
worksheet.addValidationData(officeValidation);
worksheet.addValidationData(staffValidation);
worksheet.addValidationData(activationDateValidation);
@@ -192,44 +192,44 @@ public class CentersWorkbookPopulator extends AbstractWorkbookPopulator {
worksheet.addValidationData(repeatsValidation);
worksheet.addValidationData(repeatsEveryValidation);
worksheet.addValidationData(repeatsOnValidation);
}
private void setNames(Sheet worksheet, List<OfficeData> offices) {
Workbook centerWorkbook = worksheet.getWorkbook();
Name officeCenter = centerWorkbook.createName();
officeCenter.setNameName("Office");
officeCenter.setRefersToFormula(TemplatePopulateImportConstants.OFFICE_SHEET_NAME +"!$B$2:$B$" + (offices.size() + 1));
//Repeat constraint names
Name repeatsDaily = centerWorkbook.createName();
repeatsDaily.setNameName("Daily");
repeatsDaily.setRefersToFormula(TemplatePopulateImportConstants.CENTER_SHEET_NAME+"!$IT$2:$IT$4");
Name repeatsWeekly = centerWorkbook.createName();
repeatsWeekly.setNameName("Weekly");
repeatsWeekly.setRefersToFormula(TemplatePopulateImportConstants.CENTER_SHEET_NAME+"!$IT$2:$IT$4");
Name repeatYearly = centerWorkbook.createName();
repeatYearly.setNameName("Yearly");
repeatYearly.setRefersToFormula(TemplatePopulateImportConstants.CENTER_SHEET_NAME+"!$IT$2:$IT$4");
Name repeatsMonthly = centerWorkbook.createName();
repeatsMonthly.setNameName("Monthly");
repeatsMonthly.setRefersToFormula(TemplatePopulateImportConstants.CENTER_SHEET_NAME+"!$IU$2:$IU$12");
Name repeatsOnWeekly = centerWorkbook.createName();
repeatsOnWeekly.setNameName("Weekly_Days");
repeatsOnWeekly.setRefersToFormula(TemplatePopulateImportConstants.CENTER_SHEET_NAME+"!$IV$2:$IV$8");
//Staff Names for each office
for(Integer i = 0; i < offices.size(); i++) {
Integer[] officeNameToBeginEndIndexesOfStaff = personnelSheetPopulator.getOfficeNameToBeginEndIndexesOfStaff().get(i);
Name loanOfficerName = centerWorkbook.createName();
if(officeNameToBeginEndIndexesOfStaff != null) {
loanOfficerName.setNameName("Staff_" + offices.get(i).name().trim().replaceAll("[ )(]", "_"));
loanOfficerName.setRefersToFormula(TemplatePopulateImportConstants.STAFF_SHEET_NAME+"!$B$" + officeNameToBeginEndIndexesOfStaff[0] + ":$B$" + officeNameToBeginEndIndexesOfStaff[1]);
}
}
}
}
private void setNames(Sheet worksheet, List<OfficeData> offices) {
Workbook centerWorkbook = worksheet.getWorkbook();
Name officeCenter = centerWorkbook.createName();
officeCenter.setNameName("Office");
officeCenter.setRefersToFormula(TemplatePopulateImportConstants.OFFICE_SHEET_NAME +"!$B$2:$B$" + (offices.size() + 1));
//Repeat constraint names
Name repeatsDaily = centerWorkbook.createName();
repeatsDaily.setNameName("Daily");
repeatsDaily.setRefersToFormula(TemplatePopulateImportConstants.CENTER_SHEET_NAME+"!$IT$2:$IT$4");
Name repeatsWeekly = centerWorkbook.createName();
repeatsWeekly.setNameName("Weekly");
repeatsWeekly.setRefersToFormula(TemplatePopulateImportConstants.CENTER_SHEET_NAME+"!$IT$2:$IT$4");
Name repeatYearly = centerWorkbook.createName();
repeatYearly.setNameName("Yearly");
repeatYearly.setRefersToFormula(TemplatePopulateImportConstants.CENTER_SHEET_NAME+"!$IT$2:$IT$4");
Name repeatsMonthly = centerWorkbook.createName();
repeatsMonthly.setNameName("Monthly");
repeatsMonthly.setRefersToFormula(TemplatePopulateImportConstants.CENTER_SHEET_NAME+"!$IU$2:$IU$12");
Name repeatsOnWeekly = centerWorkbook.createName();
repeatsOnWeekly.setNameName("Weekly_Days");
repeatsOnWeekly.setRefersToFormula(TemplatePopulateImportConstants.CENTER_SHEET_NAME+"!$IV$2:$IV$8");
//Staff Names for each office
for(Integer i = 0; i < offices.size(); i++) {
Integer[] officeNameToBeginEndIndexesOfStaff = personnelSheetPopulator.getOfficeNameToBeginEndIndexesOfStaff().get(i);
Name loanOfficerName = centerWorkbook.createName();
if(officeNameToBeginEndIndexesOfStaff != null) {
loanOfficerName.setNameName("Staff_" + offices.get(i).name().trim().replaceAll("[ )(]", "_"));
loanOfficerName.setRefersToFormula(TemplatePopulateImportConstants.STAFF_SHEET_NAME+"!$B$" + officeNameToBeginEndIndexesOfStaff[0] + ":$B$" + officeNameToBeginEndIndexesOfStaff[1]);
}
}
}
}
@@ -32,167 +32,167 @@ import java.util.List;
public class GroupsWorkbookPopulator extends AbstractWorkbookPopulator {
private OfficeSheetPopulator officeSheetPopulator;
private PersonnelSheetPopulator personnelSheetPopulator;
private CenterSheetPopulator centerSheetPopulator;
private ClientSheetPopulator clientSheetPopulator;
private OfficeSheetPopulator officeSheetPopulator;
private PersonnelSheetPopulator personnelSheetPopulator;
private CenterSheetPopulator centerSheetPopulator;
private ClientSheetPopulator clientSheetPopulator;
public GroupsWorkbookPopulator(OfficeSheetPopulator officeSheetPopulator,
PersonnelSheetPopulator personnelSheetPopulator, CenterSheetPopulator centerSheetPopulator,
ClientSheetPopulator clientSheetPopulator) {
this.officeSheetPopulator = officeSheetPopulator;
this.personnelSheetPopulator = personnelSheetPopulator;
this.centerSheetPopulator = centerSheetPopulator;
this.clientSheetPopulator = clientSheetPopulator;
}
public GroupsWorkbookPopulator(OfficeSheetPopulator officeSheetPopulator,
PersonnelSheetPopulator personnelSheetPopulator, CenterSheetPopulator centerSheetPopulator,
ClientSheetPopulator clientSheetPopulator) {
this.officeSheetPopulator = officeSheetPopulator;
this.personnelSheetPopulator = personnelSheetPopulator;
this.centerSheetPopulator = centerSheetPopulator;
this.clientSheetPopulator = clientSheetPopulator;
}
@Override
public void populate(Workbook workbook,String dateFormat) {
Sheet groupSheet = workbook.createSheet(TemplatePopulateImportConstants.GROUP_SHEET_NAME);
personnelSheetPopulator.populate(workbook,dateFormat);
officeSheetPopulator.populate(workbook,dateFormat);
centerSheetPopulator.populate(workbook,dateFormat);
clientSheetPopulator.populate(workbook,dateFormat);
setLayout(groupSheet);
setLookupTable(groupSheet,dateFormat);
setRules(groupSheet,dateFormat);
@Override
public void populate(Workbook workbook,String dateFormat) {
Sheet groupSheet = workbook.createSheet(TemplatePopulateImportConstants.GROUP_SHEET_NAME);
personnelSheetPopulator.populate(workbook,dateFormat);
officeSheetPopulator.populate(workbook,dateFormat);
centerSheetPopulator.populate(workbook,dateFormat);
clientSheetPopulator.populate(workbook,dateFormat);
setLayout(groupSheet);
setLookupTable(groupSheet,dateFormat);
setRules(groupSheet,dateFormat);
}
}
private void setLayout(Sheet worksheet) {
Row rowHeader = worksheet.createRow(TemplatePopulateImportConstants.ROWHEADER_INDEX);
rowHeader.setHeight(TemplatePopulateImportConstants.ROW_HEADER_HEIGHT);
worksheet.setColumnWidth(GroupConstants.NAME_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(GroupConstants.OFFICE_NAME_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE);
worksheet.setColumnWidth(GroupConstants.STAFF_NAME_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE);
worksheet.setColumnWidth(GroupConstants.CENTER_NAME_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE);
worksheet.setColumnWidth(GroupConstants.EXTERNAL_ID_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(GroupConstants.ACTIVE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(GroupConstants.ACTIVATION_DATE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(GroupConstants.SUBMITTED_ON_DATE_COL,TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(GroupConstants.MEETING_START_DATE_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE);
worksheet.setColumnWidth(GroupConstants.IS_REPEATING_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(GroupConstants.FREQUENCY_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(GroupConstants.INTERVAL_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(GroupConstants.REPEATS_ON_DAY_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(GroupConstants.STATUS_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(GroupConstants.GROUP_ID_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(GroupConstants.FAILURE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(GroupConstants.CLIENT_NAMES_STARTING_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(GroupConstants.LOOKUP_OFFICE_NAME_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE);
worksheet.setColumnWidth(GroupConstants.LOOKUP_OFFICE_OPENING_DATE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(GroupConstants.LOOKUP_REPEAT_NORMAL_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(GroupConstants.LOOKUP_REPEAT_MONTHLY_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(GroupConstants.LOOKUP_IF_REPEAT_WEEKLY_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
private void setLayout(Sheet worksheet) {
Row rowHeader = worksheet.createRow(TemplatePopulateImportConstants.ROWHEADER_INDEX);
rowHeader.setHeight(TemplatePopulateImportConstants.ROW_HEADER_HEIGHT);
worksheet.setColumnWidth(GroupConstants.NAME_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(GroupConstants.OFFICE_NAME_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE);
worksheet.setColumnWidth(GroupConstants.STAFF_NAME_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE);
worksheet.setColumnWidth(GroupConstants.CENTER_NAME_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE);
worksheet.setColumnWidth(GroupConstants.EXTERNAL_ID_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(GroupConstants.ACTIVE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(GroupConstants.ACTIVATION_DATE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(GroupConstants.SUBMITTED_ON_DATE_COL,TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(GroupConstants.MEETING_START_DATE_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE);
worksheet.setColumnWidth(GroupConstants.IS_REPEATING_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(GroupConstants.FREQUENCY_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(GroupConstants.INTERVAL_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(GroupConstants.REPEATS_ON_DAY_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(GroupConstants.STATUS_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(GroupConstants.GROUP_ID_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(GroupConstants.FAILURE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(GroupConstants.CLIENT_NAMES_STARTING_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(GroupConstants.LOOKUP_OFFICE_NAME_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE);
worksheet.setColumnWidth(GroupConstants.LOOKUP_OFFICE_OPENING_DATE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(GroupConstants.LOOKUP_REPEAT_NORMAL_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(GroupConstants.LOOKUP_REPEAT_MONTHLY_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(GroupConstants.LOOKUP_IF_REPEAT_WEEKLY_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
writeString(GroupConstants.NAME_COL, rowHeader, "Group Name*");
writeString(GroupConstants.OFFICE_NAME_COL, rowHeader, "Office Name*");
writeString(GroupConstants.STAFF_NAME_COL, rowHeader, "Staff Name*");
writeString(GroupConstants.CENTER_NAME_COL, rowHeader, "Center Name");
writeString(GroupConstants.EXTERNAL_ID_COL, rowHeader, "External ID");
writeString(GroupConstants.ACTIVE_COL, rowHeader, "Active*");
writeString(GroupConstants.ACTIVATION_DATE_COL, rowHeader, "Activation Date*");
writeString(GroupConstants.SUBMITTED_ON_DATE_COL,rowHeader,"Submitted On Date *");
writeString(GroupConstants.MEETING_START_DATE_COL, rowHeader, "Meeting Start Date* (On or After)");
writeString(GroupConstants.IS_REPEATING_COL, rowHeader, "Repeat*");
writeString(GroupConstants.FREQUENCY_COL, rowHeader, "Frequency*");
writeString(GroupConstants.INTERVAL_COL, rowHeader, "Interval*");
writeString(GroupConstants.REPEATS_ON_DAY_COL, rowHeader, "Repeats On*");
writeString(GroupConstants.CLIENT_NAMES_STARTING_COL, rowHeader, "Client Names* (Enter in consecutive cells horizontally)");
writeString(GroupConstants.LOOKUP_OFFICE_NAME_COL, rowHeader, "Office Name");
writeString(GroupConstants.LOOKUP_OFFICE_OPENING_DATE_COL, rowHeader, "Opening Date");
writeString(GroupConstants.LOOKUP_REPEAT_NORMAL_COL, rowHeader, "Repeat Normal Range");
writeString(GroupConstants.LOOKUP_REPEAT_MONTHLY_COL, rowHeader, "Repeat Monthly Range");
writeString(GroupConstants.LOOKUP_IF_REPEAT_WEEKLY_COL, rowHeader, "If Repeat Weekly Range");
writeString(GroupConstants.NAME_COL, rowHeader, "Group Name*");
writeString(GroupConstants.OFFICE_NAME_COL, rowHeader, "Office Name*");
writeString(GroupConstants.STAFF_NAME_COL, rowHeader, "Staff Name*");
writeString(GroupConstants.CENTER_NAME_COL, rowHeader, "Center Name");
writeString(GroupConstants.EXTERNAL_ID_COL, rowHeader, "External ID");
writeString(GroupConstants.ACTIVE_COL, rowHeader, "Active*");
writeString(GroupConstants.ACTIVATION_DATE_COL, rowHeader, "Activation Date*");
writeString(GroupConstants.SUBMITTED_ON_DATE_COL,rowHeader,"Submitted On Date *");
writeString(GroupConstants.MEETING_START_DATE_COL, rowHeader, "Meeting Start Date* (On or After)");
writeString(GroupConstants.IS_REPEATING_COL, rowHeader, "Repeat*");
writeString(GroupConstants.FREQUENCY_COL, rowHeader, "Frequency*");
writeString(GroupConstants.INTERVAL_COL, rowHeader, "Interval*");
writeString(GroupConstants.REPEATS_ON_DAY_COL, rowHeader, "Repeats On*");
writeString(GroupConstants.CLIENT_NAMES_STARTING_COL, rowHeader, "Client Names* (Enter in consecutive cells horizontally)");
writeString(GroupConstants.LOOKUP_OFFICE_NAME_COL, rowHeader, "Office Name");
writeString(GroupConstants.LOOKUP_OFFICE_OPENING_DATE_COL, rowHeader, "Opening Date");
writeString(GroupConstants.LOOKUP_REPEAT_NORMAL_COL, rowHeader, "Repeat Normal Range");
writeString(GroupConstants.LOOKUP_REPEAT_MONTHLY_COL, rowHeader, "Repeat Monthly Range");
writeString(GroupConstants.LOOKUP_IF_REPEAT_WEEKLY_COL, rowHeader, "If Repeat Weekly Range");
}
}
private void setLookupTable(Sheet groupSheet,String dateFormat) {
setOfficeDateLookupTable(groupSheet, officeSheetPopulator.getOffices(),GroupConstants.LOOKUP_OFFICE_NAME_COL,
GroupConstants. LOOKUP_OFFICE_OPENING_DATE_COL,dateFormat);
int rowIndex;
for(rowIndex = 1; rowIndex <= 11; rowIndex++) {
Row row = groupSheet.getRow(rowIndex);
if(row == null)
row = groupSheet.createRow(rowIndex);
writeInt(GroupConstants.LOOKUP_REPEAT_MONTHLY_COL, row, rowIndex);
}
for(rowIndex = 1; rowIndex <= 3; rowIndex++)
writeInt(GroupConstants.LOOKUP_REPEAT_NORMAL_COL, groupSheet.getRow(rowIndex), rowIndex);
String[] days = new String[]{
TemplatePopulateImportConstants.MONDAY,
TemplatePopulateImportConstants.TUESDAY,
TemplatePopulateImportConstants.WEDNESDAY,
TemplatePopulateImportConstants.THURSDAY,
TemplatePopulateImportConstants.FRIDAY,
TemplatePopulateImportConstants.SATURDAY,
TemplatePopulateImportConstants.SUNDAY};
for(rowIndex = 1; rowIndex <= 7; rowIndex++)
writeString(GroupConstants.LOOKUP_IF_REPEAT_WEEKLY_COL, groupSheet.getRow(rowIndex), days[rowIndex-1]);
setOfficeDateLookupTable(groupSheet, officeSheetPopulator.getOffices(),GroupConstants.LOOKUP_OFFICE_NAME_COL,
GroupConstants. LOOKUP_OFFICE_OPENING_DATE_COL,dateFormat);
int rowIndex;
for(rowIndex = 1; rowIndex <= 11; rowIndex++) {
Row row = groupSheet.getRow(rowIndex);
if(row == null)
row = groupSheet.createRow(rowIndex);
writeInt(GroupConstants.LOOKUP_REPEAT_MONTHLY_COL, row, rowIndex);
}
for(rowIndex = 1; rowIndex <= 3; rowIndex++)
writeInt(GroupConstants.LOOKUP_REPEAT_NORMAL_COL, groupSheet.getRow(rowIndex), rowIndex);
String[] days = new String[]{
TemplatePopulateImportConstants.MONDAY,
TemplatePopulateImportConstants.TUESDAY,
TemplatePopulateImportConstants.WEDNESDAY,
TemplatePopulateImportConstants.THURSDAY,
TemplatePopulateImportConstants.FRIDAY,
TemplatePopulateImportConstants.SATURDAY,
TemplatePopulateImportConstants.SUNDAY};
for(rowIndex = 1; rowIndex <= 7; rowIndex++)
writeString(GroupConstants.LOOKUP_IF_REPEAT_WEEKLY_COL, groupSheet.getRow(rowIndex), days[rowIndex-1]);
}
private void setRules(Sheet worksheet,String dateFormat){
CellRangeAddressList officeNameRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(),
GroupConstants.OFFICE_NAME_COL, GroupConstants.OFFICE_NAME_COL);
CellRangeAddressList staffNameRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(),
GroupConstants.STAFF_NAME_COL, GroupConstants.STAFF_NAME_COL);
CellRangeAddressList centerNameRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(),
GroupConstants.CENTER_NAME_COL, GroupConstants.CENTER_NAME_COL);
CellRangeAddressList activeRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(),
GroupConstants.ACTIVE_COL, GroupConstants.ACTIVE_COL);
CellRangeAddressList activationDateRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(),
GroupConstants.ACTIVATION_DATE_COL,GroupConstants.ACTIVATION_DATE_COL);
CellRangeAddressList submittedOnDateRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(),
GroupConstants.SUBMITTED_ON_DATE_COL,GroupConstants.SUBMITTED_ON_DATE_COL);
CellRangeAddressList meetingStartDateRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(),
GroupConstants.MEETING_START_DATE_COL,GroupConstants.MEETING_START_DATE_COL);
CellRangeAddressList isRepeatRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(),
GroupConstants.IS_REPEATING_COL, GroupConstants.IS_REPEATING_COL);
CellRangeAddressList repeatsRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(),
GroupConstants. FREQUENCY_COL, GroupConstants.FREQUENCY_COL);
CellRangeAddressList repeatsEveryRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(),
GroupConstants.INTERVAL_COL,GroupConstants. INTERVAL_COL);
CellRangeAddressList repeatsOnRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(),
GroupConstants.REPEATS_ON_DAY_COL, GroupConstants.REPEATS_ON_DAY_COL);
DataValidationHelper validationHelper = new HSSFDataValidationHelper((HSSFSheet)worksheet);
List<OfficeData> offices = officeSheetPopulator.getOffices();
setNames(worksheet, offices);
DataValidationConstraint centerNameConstraint = validationHelper.createFormulaListConstraint("INDIRECT(CONCATENATE(\"Center_\",$B1))");
DataValidationConstraint officeNameConstraint = validationHelper.createFormulaListConstraint("Office");
DataValidationConstraint staffNameConstraint = validationHelper.createFormulaListConstraint("INDIRECT(CONCATENATE(\"Staff_\",$B1))");
DataValidationConstraint booleanConstraint = validationHelper.createExplicitListConstraint(new String[]{"True", "False"});
DataValidationConstraint activationDateConstraint = validationHelper.createDateConstraint
(DataValidationConstraint.OperatorType.BETWEEN,
"=VLOOKUP($B1,$IR$2:$IS" + (offices.size() + 1)+",2,FALSE)", "=TODAY()", dateFormat);
DataValidationConstraint submittedOnDateConstraint =
validationHelper.createDateConstraint(DataValidationConstraint.OperatorType.LESS_OR_EQUAL,
"=$G1" ,null,dateFormat);
DataValidationConstraint meetingStartDateConstraint = validationHelper.
createDateConstraint(DataValidationConstraint.OperatorType.BETWEEN,
"=$G1", "=TODAY()", dateFormat);
DataValidationConstraint repeatsConstraint = validationHelper.createExplicitListConstraint(new String[]{
TemplatePopulateImportConstants.FREQUENCY_DAILY,
TemplatePopulateImportConstants.FREQUENCY_WEEKLY,
TemplatePopulateImportConstants.FREQUENCY_MONTHLY,
TemplatePopulateImportConstants.FREQUENCY_YEARLY});
DataValidationConstraint repeatsEveryConstraint = validationHelper.createFormulaListConstraint("INDIRECT($K1)");
DataValidationConstraint repeatsOnConstraint = validationHelper.createFormulaListConstraint("INDIRECT(CONCATENATE($K1,\"_DAYS\"))");
DataValidation centerValidation=validationHelper.createValidation(centerNameConstraint, centerNameRange);
DataValidation officeValidation = validationHelper.createValidation(officeNameConstraint, officeNameRange);
DataValidation staffValidation = validationHelper.createValidation(staffNameConstraint, staffNameRange);
DataValidation activationDateValidation = validationHelper.createValidation(activationDateConstraint, activationDateRange);
DataValidation activeValidation = validationHelper.createValidation(booleanConstraint, activeRange);
DataValidation submittedOnDateValidation=validationHelper.createValidation(submittedOnDateConstraint,submittedOnDateRange);
DataValidation meetingStartDateValidation = validationHelper.createValidation(meetingStartDateConstraint, meetingStartDateRange);
DataValidation isRepeatValidation = validationHelper.createValidation(booleanConstraint, isRepeatRange);
DataValidation repeatsValidation = validationHelper.createValidation(repeatsConstraint, repeatsRange);
DataValidation repeatsEveryValidation = validationHelper.createValidation(repeatsEveryConstraint, repeatsEveryRange);
DataValidation repeatsOnValidation = validationHelper.createValidation(repeatsOnConstraint, repeatsOnRange);
worksheet.addValidationData(centerValidation);
worksheet.addValidationData(activeValidation);
CellRangeAddressList officeNameRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(),
GroupConstants.OFFICE_NAME_COL, GroupConstants.OFFICE_NAME_COL);
CellRangeAddressList staffNameRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(),
GroupConstants.STAFF_NAME_COL, GroupConstants.STAFF_NAME_COL);
CellRangeAddressList centerNameRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(),
GroupConstants.CENTER_NAME_COL, GroupConstants.CENTER_NAME_COL);
CellRangeAddressList activeRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(),
GroupConstants.ACTIVE_COL, GroupConstants.ACTIVE_COL);
CellRangeAddressList activationDateRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(),
GroupConstants.ACTIVATION_DATE_COL,GroupConstants.ACTIVATION_DATE_COL);
CellRangeAddressList submittedOnDateRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(),
GroupConstants.SUBMITTED_ON_DATE_COL,GroupConstants.SUBMITTED_ON_DATE_COL);
CellRangeAddressList meetingStartDateRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(),
GroupConstants.MEETING_START_DATE_COL,GroupConstants.MEETING_START_DATE_COL);
CellRangeAddressList isRepeatRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(),
GroupConstants.IS_REPEATING_COL, GroupConstants.IS_REPEATING_COL);
CellRangeAddressList repeatsRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(),
GroupConstants. FREQUENCY_COL, GroupConstants.FREQUENCY_COL);
CellRangeAddressList repeatsEveryRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(),
GroupConstants.INTERVAL_COL,GroupConstants. INTERVAL_COL);
CellRangeAddressList repeatsOnRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(),
GroupConstants.REPEATS_ON_DAY_COL, GroupConstants.REPEATS_ON_DAY_COL);
DataValidationHelper validationHelper = new HSSFDataValidationHelper((HSSFSheet)worksheet);
List<OfficeData> offices = officeSheetPopulator.getOffices();
setNames(worksheet, offices);
DataValidationConstraint centerNameConstraint = validationHelper.createFormulaListConstraint("INDIRECT(CONCATENATE(\"Center_\",$B1))");
DataValidationConstraint officeNameConstraint = validationHelper.createFormulaListConstraint("Office");
DataValidationConstraint staffNameConstraint = validationHelper.createFormulaListConstraint("INDIRECT(CONCATENATE(\"Staff_\",$B1))");
DataValidationConstraint booleanConstraint = validationHelper.createExplicitListConstraint(new String[]{"True", "False"});
DataValidationConstraint activationDateConstraint = validationHelper.createDateConstraint
(DataValidationConstraint.OperatorType.BETWEEN,
"=VLOOKUP($B1,$IR$2:$IS" + (offices.size() + 1)+",2,FALSE)", "=TODAY()", dateFormat);
DataValidationConstraint submittedOnDateConstraint =
validationHelper.createDateConstraint(DataValidationConstraint.OperatorType.LESS_OR_EQUAL,
"=$G1" ,null,dateFormat);
DataValidationConstraint meetingStartDateConstraint = validationHelper.
createDateConstraint(DataValidationConstraint.OperatorType.BETWEEN,
"=$G1", "=TODAY()", dateFormat);
DataValidationConstraint repeatsConstraint = validationHelper.createExplicitListConstraint(new String[]{
TemplatePopulateImportConstants.FREQUENCY_DAILY,
TemplatePopulateImportConstants.FREQUENCY_WEEKLY,
TemplatePopulateImportConstants.FREQUENCY_MONTHLY,
TemplatePopulateImportConstants.FREQUENCY_YEARLY});
DataValidationConstraint repeatsEveryConstraint = validationHelper.createFormulaListConstraint("INDIRECT($K1)");
DataValidationConstraint repeatsOnConstraint = validationHelper.createFormulaListConstraint("INDIRECT(CONCATENATE($K1,\"_DAYS\"))");
DataValidation centerValidation=validationHelper.createValidation(centerNameConstraint, centerNameRange);
DataValidation officeValidation = validationHelper.createValidation(officeNameConstraint, officeNameRange);
DataValidation staffValidation = validationHelper.createValidation(staffNameConstraint, staffNameRange);
DataValidation activationDateValidation = validationHelper.createValidation(activationDateConstraint, activationDateRange);
DataValidation activeValidation = validationHelper.createValidation(booleanConstraint, activeRange);
DataValidation submittedOnDateValidation=validationHelper.createValidation(submittedOnDateConstraint,submittedOnDateRange);
DataValidation meetingStartDateValidation = validationHelper.createValidation(meetingStartDateConstraint, meetingStartDateRange);
DataValidation isRepeatValidation = validationHelper.createValidation(booleanConstraint, isRepeatRange);
DataValidation repeatsValidation = validationHelper.createValidation(repeatsConstraint, repeatsRange);
DataValidation repeatsEveryValidation = validationHelper.createValidation(repeatsEveryConstraint, repeatsEveryRange);
DataValidation repeatsOnValidation = validationHelper.createValidation(repeatsOnConstraint, repeatsOnRange);
worksheet.addValidationData(centerValidation);
worksheet.addValidationData(activeValidation);
worksheet.addValidationData(officeValidation);
worksheet.addValidationData(staffValidation);
worksheet.addValidationData(activationDateValidation);
@@ -204,51 +204,51 @@ public class GroupsWorkbookPopulator extends AbstractWorkbookPopulator {
worksheet.addValidationData(repeatsOnValidation);
}
private void setNames(Sheet worksheet, List<OfficeData> offices) {
Workbook centerWorkbook = worksheet.getWorkbook();
Name officeCenter = centerWorkbook.createName();
officeCenter.setNameName("Office");
officeCenter.setRefersToFormula(TemplatePopulateImportConstants.OFFICE_SHEET_NAME+"!$B$2:$B$" + (offices.size() + 1));
//Repeat constraint names
Name repeatsDaily = centerWorkbook.createName();
repeatsDaily.setNameName("Daily");
repeatsDaily.setRefersToFormula(TemplatePopulateImportConstants.GROUP_SHEET_NAME+"!$IT$2:$IT$4");
Name repeatsWeekly = centerWorkbook.createName();
repeatsWeekly.setNameName("Weekly");
repeatsWeekly.setRefersToFormula(TemplatePopulateImportConstants.GROUP_SHEET_NAME+"!$IT$2:$IT$4");
Name repeatYearly = centerWorkbook.createName();
repeatYearly.setNameName("Yearly");
repeatYearly.setRefersToFormula(TemplatePopulateImportConstants.GROUP_SHEET_NAME+"!$IT$2:$IT$4");
Name repeatsMonthly = centerWorkbook.createName();
repeatsMonthly.setNameName("Monthly");
repeatsMonthly.setRefersToFormula(TemplatePopulateImportConstants.GROUP_SHEET_NAME+"!$IU$2:$IU$12");
Name repeatsOnWeekly = centerWorkbook.createName();
repeatsOnWeekly.setNameName("Weekly_Days");
repeatsOnWeekly.setRefersToFormula(TemplatePopulateImportConstants.GROUP_SHEET_NAME+"!$IV$2:$IV$8");
//Staff Names for each office & center Names for each office
for(Integer i = 0; i < offices.size(); i++) {
Integer[] officeNameToBeginEndIndexesOfCenters =centerSheetPopulator.getOfficeNameToBeginEndIndexesOfCenters().get(i);
Integer[] officeNameToBeginEndIndexesOfStaff = personnelSheetPopulator.getOfficeNameToBeginEndIndexesOfStaff().get(i);
private void setNames(Sheet worksheet, List<OfficeData> offices) {
Workbook centerWorkbook = worksheet.getWorkbook();
Name officeCenter = centerWorkbook.createName();
officeCenter.setNameName("Office");
officeCenter.setRefersToFormula(TemplatePopulateImportConstants.OFFICE_SHEET_NAME+"!$B$2:$B$" + (offices.size() + 1));
//Repeat constraint names
Name repeatsDaily = centerWorkbook.createName();
repeatsDaily.setNameName("Daily");
repeatsDaily.setRefersToFormula(TemplatePopulateImportConstants.GROUP_SHEET_NAME+"!$IT$2:$IT$4");
Name repeatsWeekly = centerWorkbook.createName();
repeatsWeekly.setNameName("Weekly");
repeatsWeekly.setRefersToFormula(TemplatePopulateImportConstants.GROUP_SHEET_NAME+"!$IT$2:$IT$4");
Name repeatYearly = centerWorkbook.createName();
repeatYearly.setNameName("Yearly");
repeatYearly.setRefersToFormula(TemplatePopulateImportConstants.GROUP_SHEET_NAME+"!$IT$2:$IT$4");
Name repeatsMonthly = centerWorkbook.createName();
repeatsMonthly.setNameName("Monthly");
repeatsMonthly.setRefersToFormula(TemplatePopulateImportConstants.GROUP_SHEET_NAME+"!$IU$2:$IU$12");
Name repeatsOnWeekly = centerWorkbook.createName();
repeatsOnWeekly.setNameName("Weekly_Days");
repeatsOnWeekly.setRefersToFormula(TemplatePopulateImportConstants.GROUP_SHEET_NAME+"!$IV$2:$IV$8");
//Staff Names for each office & center Names for each office
for(Integer i = 0; i < offices.size(); i++) {
Integer[] officeNameToBeginEndIndexesOfCenters =centerSheetPopulator.getOfficeNameToBeginEndIndexesOfCenters().get(i);
Integer[] officeNameToBeginEndIndexesOfStaff = personnelSheetPopulator.getOfficeNameToBeginEndIndexesOfStaff().get(i);
Name loanOfficerName = centerWorkbook.createName();
Name centerName=centerWorkbook.createName();
Name loanOfficerName = centerWorkbook.createName();
Name centerName=centerWorkbook.createName();
if(officeNameToBeginEndIndexesOfStaff != null) {
loanOfficerName.setNameName("Staff_" + offices.get(i).name().trim().replaceAll("[ )(]", "_"));
loanOfficerName.setRefersToFormula(TemplatePopulateImportConstants.STAFF_SHEET_NAME+
"!$B$" + officeNameToBeginEndIndexesOfStaff[0] + ":$B$" + officeNameToBeginEndIndexesOfStaff[1]);
}
if (officeNameToBeginEndIndexesOfCenters!=null) {
centerName.setNameName("Center_" + offices.get(i).name().trim().replaceAll("[ )(]", "_"));
centerName.setRefersToFormula(TemplatePopulateImportConstants.CENTER_SHEET_NAME+
"!$B$" + officeNameToBeginEndIndexesOfCenters[0] + ":$B$" + officeNameToBeginEndIndexesOfCenters[1]);
}
}
}
if(officeNameToBeginEndIndexesOfStaff != null) {
loanOfficerName.setNameName("Staff_" + offices.get(i).name().trim().replaceAll("[ )(]", "_"));
loanOfficerName.setRefersToFormula(TemplatePopulateImportConstants.STAFF_SHEET_NAME+
"!$B$" + officeNameToBeginEndIndexesOfStaff[0] + ":$B$" + officeNameToBeginEndIndexesOfStaff[1]);
}
if (officeNameToBeginEndIndexesOfCenters!=null) {
centerName.setNameName("Center_" + offices.get(i).name().trim().replaceAll("[ )(]", "_"));
centerName.setRefersToFormula(TemplatePopulateImportConstants.CENTER_SHEET_NAME+
"!$B$" + officeNameToBeginEndIndexesOfCenters[0] + ":$B$" + officeNameToBeginEndIndexesOfCenters[1]);
}
}
}
}
@@ -38,83 +38,83 @@ import java.util.HashMap;
import java.util.List;
public class GuarantorWorkbookPopulator extends AbstractWorkbookPopulator {
private OfficeSheetPopulator officeSheetPopulator;
private ClientSheetPopulator clientSheetPopulator;
private List<LoanAccountData> loans;
private List<SavingsAccountData> savings;
private List<CodeValueData>guarantorRelationshipTypes;
private OfficeSheetPopulator officeSheetPopulator;
private ClientSheetPopulator clientSheetPopulator;
private List<LoanAccountData> loans;
private List<SavingsAccountData> savings;
private List<CodeValueData>guarantorRelationshipTypes;
public GuarantorWorkbookPopulator(OfficeSheetPopulator officeSheetPopulator,
ClientSheetPopulator clientSheetPopulator,
List<LoanAccountData> loans, List<SavingsAccountData> savings,
List<CodeValueData> guarantorRelationshipTypes) {
this.officeSheetPopulator = officeSheetPopulator;
this.clientSheetPopulator = clientSheetPopulator;
this.loans = loans;
this.savings = savings;
this.guarantorRelationshipTypes=guarantorRelationshipTypes;
public GuarantorWorkbookPopulator(OfficeSheetPopulator officeSheetPopulator,
ClientSheetPopulator clientSheetPopulator,
List<LoanAccountData> loans, List<SavingsAccountData> savings,
List<CodeValueData> guarantorRelationshipTypes) {
this.officeSheetPopulator = officeSheetPopulator;
this.clientSheetPopulator = clientSheetPopulator;
this.loans = loans;
this.savings = savings;
this.guarantorRelationshipTypes=guarantorRelationshipTypes;
}
}
@Override
public void populate(Workbook workbook,String dateFormat) {
Sheet addGuarantorSheet = workbook.createSheet(TemplatePopulateImportConstants.GUARANTOR_SHEET_NAME);
setLayout(addGuarantorSheet);
officeSheetPopulator.populate(workbook,dateFormat);
clientSheetPopulator.populate(workbook,dateFormat);
populateLoansTable(addGuarantorSheet,dateFormat);
populateSavingsTable(addGuarantorSheet,dateFormat);
populateGuarantorRelationshipTypes(addGuarantorSheet,dateFormat);
setRules(addGuarantorSheet);
@Override
public void populate(Workbook workbook,String dateFormat) {
Sheet addGuarantorSheet = workbook.createSheet(TemplatePopulateImportConstants.GUARANTOR_SHEET_NAME);
setLayout(addGuarantorSheet);
officeSheetPopulator.populate(workbook,dateFormat);
clientSheetPopulator.populate(workbook,dateFormat);
populateLoansTable(addGuarantorSheet,dateFormat);
populateSavingsTable(addGuarantorSheet,dateFormat);
populateGuarantorRelationshipTypes(addGuarantorSheet,dateFormat);
setRules(addGuarantorSheet);
}
}
private void setLayout(Sheet worksheet) {
Row rowHeader = worksheet.createRow(0);
worksheet.setColumnWidth(GuarantorConstants.OFFICE_NAME_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(GuarantorConstants.CLIENT_NAME_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE);
worksheet.setColumnWidth(GuarantorConstants.LOAN_ACCOUNT_NO_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(GuarantorConstants.GUARANTO_TYPE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(GuarantorConstants.CLIENT_RELATIONSHIP_TYPE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(GuarantorConstants.ENTITY_OFFICE_NAME_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(GuarantorConstants.ENTITY_ID_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(GuarantorConstants.FIRST_NAME_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(GuarantorConstants.LAST_NAME_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(GuarantorConstants.ADDRESS_LINE_1_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(GuarantorConstants.ADDRESS_LINE_2_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(GuarantorConstants.CITY_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(GuarantorConstants.DOB_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(GuarantorConstants.ZIP_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(GuarantorConstants.SAVINGS_ID_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(GuarantorConstants.AMOUNT, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(GuarantorConstants.LOOKUP_CLIENT_NAME_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(GuarantorConstants.LOOKUP_ACCOUNT_NO_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(GuarantorConstants.LOOKUP_SAVINGS_CLIENT_NAME_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(GuarantorConstants.LOOKUP_SAVINGS_ACCOUNT_NO_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
writeString(GuarantorConstants.OFFICE_NAME_COL, rowHeader, "Office Name*");
writeString(GuarantorConstants.CLIENT_NAME_COL, rowHeader, "Client Name*");
writeString(GuarantorConstants.LOAN_ACCOUNT_NO_COL, rowHeader, " Loan Account NO");
writeString(GuarantorConstants.GUARANTO_TYPE_COL, rowHeader, "Guranter_type*");
writeString(GuarantorConstants.CLIENT_RELATIONSHIP_TYPE_COL, rowHeader, "Client Relationship type*");
writeString(GuarantorConstants.ENTITY_OFFICE_NAME_COL, rowHeader, "Guranter office");
writeString(GuarantorConstants.ENTITY_ID_COL, rowHeader, "Gurantor client id*");
writeString(GuarantorConstants.FIRST_NAME_COL, rowHeader, "First Name*");
writeString(GuarantorConstants.LAST_NAME_COL, rowHeader, "Last Name");
writeString(GuarantorConstants.ADDRESS_LINE_1_COL, rowHeader, "ADDRESS LINE 1");
writeString(GuarantorConstants.ADDRESS_LINE_2_COL, rowHeader, "ADDRESS LINE 2");
writeString(GuarantorConstants.CITY_COL, rowHeader, "City");
writeString(GuarantorConstants.DOB_COL, rowHeader, "Date of Birth");
writeString(GuarantorConstants.ZIP_COL, rowHeader, "Zip*");
writeString(GuarantorConstants.SAVINGS_ID_COL, rowHeader, "Savings Account Id");
writeString(GuarantorConstants.AMOUNT, rowHeader, "Amount");
writeString(GuarantorConstants.LOOKUP_CLIENT_NAME_COL, rowHeader, "Lookup Client");
writeString(GuarantorConstants.LOOKUP_ACCOUNT_NO_COL, rowHeader, "Lookup Loan Account");
writeString(GuarantorConstants.LOOKUP_SAVINGS_CLIENT_NAME_COL, rowHeader, "Savings Lookup Client");
writeString(GuarantorConstants.LOOKUP_SAVINGS_ACCOUNT_NO_COL, rowHeader, "Savings Lookup Account");
}
private void setLayout(Sheet worksheet) {
Row rowHeader = worksheet.createRow(0);
worksheet.setColumnWidth(GuarantorConstants.OFFICE_NAME_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(GuarantorConstants.CLIENT_NAME_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE);
worksheet.setColumnWidth(GuarantorConstants.LOAN_ACCOUNT_NO_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(GuarantorConstants.GUARANTO_TYPE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(GuarantorConstants.CLIENT_RELATIONSHIP_TYPE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(GuarantorConstants.ENTITY_OFFICE_NAME_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(GuarantorConstants.ENTITY_ID_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(GuarantorConstants.FIRST_NAME_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(GuarantorConstants.LAST_NAME_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(GuarantorConstants.ADDRESS_LINE_1_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(GuarantorConstants.ADDRESS_LINE_2_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(GuarantorConstants.CITY_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(GuarantorConstants.DOB_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(GuarantorConstants.ZIP_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(GuarantorConstants.SAVINGS_ID_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(GuarantorConstants.AMOUNT, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(GuarantorConstants.LOOKUP_CLIENT_NAME_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(GuarantorConstants.LOOKUP_ACCOUNT_NO_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(GuarantorConstants.LOOKUP_SAVINGS_CLIENT_NAME_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(GuarantorConstants.LOOKUP_SAVINGS_ACCOUNT_NO_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
writeString(GuarantorConstants.OFFICE_NAME_COL, rowHeader, "Office Name*");
writeString(GuarantorConstants.CLIENT_NAME_COL, rowHeader, "Client Name*");
writeString(GuarantorConstants.LOAN_ACCOUNT_NO_COL, rowHeader, " Loan Account NO");
writeString(GuarantorConstants.GUARANTO_TYPE_COL, rowHeader, "Guranter_type*");
writeString(GuarantorConstants.CLIENT_RELATIONSHIP_TYPE_COL, rowHeader, "Client Relationship type*");
writeString(GuarantorConstants.ENTITY_OFFICE_NAME_COL, rowHeader, "Guranter office");
writeString(GuarantorConstants.ENTITY_ID_COL, rowHeader, "Gurantor client id*");
writeString(GuarantorConstants.FIRST_NAME_COL, rowHeader, "First Name*");
writeString(GuarantorConstants.LAST_NAME_COL, rowHeader, "Last Name");
writeString(GuarantorConstants.ADDRESS_LINE_1_COL, rowHeader, "ADDRESS LINE 1");
writeString(GuarantorConstants.ADDRESS_LINE_2_COL, rowHeader, "ADDRESS LINE 2");
writeString(GuarantorConstants.CITY_COL, rowHeader, "City");
writeString(GuarantorConstants.DOB_COL, rowHeader, "Date of Birth");
writeString(GuarantorConstants.ZIP_COL, rowHeader, "Zip*");
writeString(GuarantorConstants.SAVINGS_ID_COL, rowHeader, "Savings Account Id");
writeString(GuarantorConstants.AMOUNT, rowHeader, "Amount");
writeString(GuarantorConstants.LOOKUP_CLIENT_NAME_COL, rowHeader, "Lookup Client");
writeString(GuarantorConstants.LOOKUP_ACCOUNT_NO_COL, rowHeader, "Lookup Loan Account");
writeString(GuarantorConstants.LOOKUP_SAVINGS_CLIENT_NAME_COL, rowHeader, "Savings Lookup Client");
writeString(GuarantorConstants.LOOKUP_SAVINGS_ACCOUNT_NO_COL, rowHeader, "Savings Lookup Account");
}
private void populateSavingsTable(Sheet addGuarantorSheet,String dateFormat) {
Workbook workbook = addGuarantorSheet.getWorkbook();
CellStyle dateCellStyle = workbook.createCellStyle();
@@ -154,68 +154,68 @@ public class GuarantorWorkbookPopulator extends AbstractWorkbookPopulator {
writeString(GuarantorConstants.LOOKUP_ACCOUNT_NO_COL, row, Long.parseLong(loan.getAccountNo())+"-"+loan.getStatusStringValue());
}
}
private void populateGuarantorRelationshipTypes(Sheet addGuarantorSheet, String dateFormat) {
Workbook workbook = addGuarantorSheet.getWorkbook();
CellStyle dateCellStyle = workbook.createCellStyle();
short df = workbook.createDataFormat().getFormat(dateFormat);
dateCellStyle.setDataFormat(df);
int rowIndex = 1;
Row row;
for (CodeValueData relationshipType:guarantorRelationshipTypes) {
if (addGuarantorSheet.getRow(rowIndex)==null){
row=addGuarantorSheet.createRow(rowIndex++);
}else {
row=addGuarantorSheet.getRow(rowIndex++);
}
writeString(GuarantorConstants.LOOKUP_GUARANTOR_RELATIONSHIPS,row,relationshipType.getName()+"-"+relationshipType.getId());
}
private void populateGuarantorRelationshipTypes(Sheet addGuarantorSheet, String dateFormat) {
Workbook workbook = addGuarantorSheet.getWorkbook();
CellStyle dateCellStyle = workbook.createCellStyle();
short df = workbook.createDataFormat().getFormat(dateFormat);
dateCellStyle.setDataFormat(df);
int rowIndex = 1;
Row row;
for (CodeValueData relationshipType:guarantorRelationshipTypes) {
if (addGuarantorSheet.getRow(rowIndex)==null){
row=addGuarantorSheet.createRow(rowIndex++);
}else {
row=addGuarantorSheet.getRow(rowIndex++);
}
writeString(GuarantorConstants.LOOKUP_GUARANTOR_RELATIONSHIPS,row,relationshipType.getName()+"-"+relationshipType.getId());
}
}
private void setRules(Sheet worksheet) {
}
private void setRules(Sheet worksheet) {
CellRangeAddressList officeNameRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(),
GuarantorConstants.OFFICE_NAME_COL, GuarantorConstants.OFFICE_NAME_COL);
CellRangeAddressList clientNameRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(),
GuarantorConstants.CLIENT_NAME_COL, GuarantorConstants.CLIENT_NAME_COL);
CellRangeAddressList entityofficeNameRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(),
GuarantorConstants.ENTITY_OFFICE_NAME_COL, GuarantorConstants.ENTITY_OFFICE_NAME_COL);
CellRangeAddressList entityclientNameRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(),
GuarantorConstants.ENTITY_ID_COL, GuarantorConstants.ENTITY_ID_COL);
CellRangeAddressList accountNumberRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(),
GuarantorConstants.LOAN_ACCOUNT_NO_COL, GuarantorConstants.LOAN_ACCOUNT_NO_COL);
CellRangeAddressList savingsaccountNumberRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(),
GuarantorConstants.SAVINGS_ID_COL, GuarantorConstants.SAVINGS_ID_COL);
CellRangeAddressList guranterTypeRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(),
GuarantorConstants.GUARANTO_TYPE_COL, GuarantorConstants.GUARANTO_TYPE_COL);
CellRangeAddressList guranterRelationshipTypeRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(),
GuarantorConstants.CLIENT_RELATIONSHIP_TYPE_COL, GuarantorConstants.CLIENT_RELATIONSHIP_TYPE_COL);
DataValidationHelper validationHelper = new HSSFDataValidationHelper((HSSFSheet)worksheet);
setNames(worksheet);
DataValidationConstraint officeNameConstraint = validationHelper.createFormulaListConstraint("Office");
DataValidationConstraint clientNameConstraint = validationHelper.createFormulaListConstraint("INDIRECT(CONCATENATE(\"Client_\",$A1))");
DataValidationConstraint accountNumberConstraint = validationHelper.createFormulaListConstraint("INDIRECT(CONCATENATE(\"Account_\",SUBSTITUTE(SUBSTITUTE(SUBSTITUTE($B1,\" \",\"_\"),\"(\",\"_\"),\")\",\"_\")))");
DataValidationConstraint savingsaccountNumberConstraint = validationHelper.createFormulaListConstraint("INDIRECT(CONCATENATE(\"SavingsAccount_\",SUBSTITUTE(SUBSTITUTE(SUBSTITUTE($G1,\" \",\"_\"),\"(\",\"_\"),\")\",\"_\")))");
DataValidationConstraint guranterTypeConstraint = validationHelper.createExplicitListConstraint(new String[] {
TemplatePopulateImportConstants.GUARANTOR_INTERNAL,
TemplatePopulateImportConstants.GUARANTOR_EXTERNAL});
DataValidationConstraint guarantorRelationshipConstraint = validationHelper.createFormulaListConstraint("GuarantorRelationship");
DataValidationConstraint entityofficeNameConstraint = validationHelper.createFormulaListConstraint("Office");
DataValidationConstraint entityclientNameConstraint = validationHelper.createFormulaListConstraint("INDIRECT(CONCATENATE(\"Client_\",$F1))");
DataValidation officeValidation = validationHelper.createValidation(officeNameConstraint, officeNameRange);
DataValidation clientValidation = validationHelper.createValidation(clientNameConstraint, clientNameRange);
DataValidation accountNumberValidation = validationHelper.createValidation(accountNumberConstraint, accountNumberRange);
DataValidation savingsaccountNumberValidation = validationHelper.createValidation(savingsaccountNumberConstraint, savingsaccountNumberRange);
DataValidation guranterTypeValidation = validationHelper.createValidation(guranterTypeConstraint, guranterTypeRange);
DataValidation guarantorRelationshipValidation=validationHelper.createValidation(guarantorRelationshipConstraint,guranterRelationshipTypeRange);
DataValidation entityofficeValidation = validationHelper.createValidation(entityofficeNameConstraint, entityofficeNameRange);
DataValidation entityclientValidation = validationHelper.createValidation(entityclientNameConstraint, entityclientNameRange);
worksheet.addValidationData(officeValidation);
CellRangeAddressList officeNameRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(),
GuarantorConstants.OFFICE_NAME_COL, GuarantorConstants.OFFICE_NAME_COL);
CellRangeAddressList clientNameRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(),
GuarantorConstants.CLIENT_NAME_COL, GuarantorConstants.CLIENT_NAME_COL);
CellRangeAddressList entityofficeNameRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(),
GuarantorConstants.ENTITY_OFFICE_NAME_COL, GuarantorConstants.ENTITY_OFFICE_NAME_COL);
CellRangeAddressList entityclientNameRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(),
GuarantorConstants.ENTITY_ID_COL, GuarantorConstants.ENTITY_ID_COL);
CellRangeAddressList accountNumberRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(),
GuarantorConstants.LOAN_ACCOUNT_NO_COL, GuarantorConstants.LOAN_ACCOUNT_NO_COL);
CellRangeAddressList savingsaccountNumberRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(),
GuarantorConstants.SAVINGS_ID_COL, GuarantorConstants.SAVINGS_ID_COL);
CellRangeAddressList guranterTypeRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(),
GuarantorConstants.GUARANTO_TYPE_COL, GuarantorConstants.GUARANTO_TYPE_COL);
CellRangeAddressList guranterRelationshipTypeRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(),
GuarantorConstants.CLIENT_RELATIONSHIP_TYPE_COL, GuarantorConstants.CLIENT_RELATIONSHIP_TYPE_COL);
DataValidationHelper validationHelper = new HSSFDataValidationHelper((HSSFSheet)worksheet);
setNames(worksheet);
DataValidationConstraint officeNameConstraint = validationHelper.createFormulaListConstraint("Office");
DataValidationConstraint clientNameConstraint = validationHelper.createFormulaListConstraint("INDIRECT(CONCATENATE(\"Client_\",$A1))");
DataValidationConstraint accountNumberConstraint = validationHelper.createFormulaListConstraint("INDIRECT(CONCATENATE(\"Account_\",SUBSTITUTE(SUBSTITUTE(SUBSTITUTE($B1,\" \",\"_\"),\"(\",\"_\"),\")\",\"_\")))");
DataValidationConstraint savingsaccountNumberConstraint = validationHelper.createFormulaListConstraint("INDIRECT(CONCATENATE(\"SavingsAccount_\",SUBSTITUTE(SUBSTITUTE(SUBSTITUTE($G1,\" \",\"_\"),\"(\",\"_\"),\")\",\"_\")))");
DataValidationConstraint guranterTypeConstraint = validationHelper.createExplicitListConstraint(new String[] {
TemplatePopulateImportConstants.GUARANTOR_INTERNAL,
TemplatePopulateImportConstants.GUARANTOR_EXTERNAL});
DataValidationConstraint guarantorRelationshipConstraint = validationHelper.createFormulaListConstraint("GuarantorRelationship");
DataValidationConstraint entityofficeNameConstraint = validationHelper.createFormulaListConstraint("Office");
DataValidationConstraint entityclientNameConstraint = validationHelper.createFormulaListConstraint("INDIRECT(CONCATENATE(\"Client_\",$F1))");
DataValidation officeValidation = validationHelper.createValidation(officeNameConstraint, officeNameRange);
DataValidation clientValidation = validationHelper.createValidation(clientNameConstraint, clientNameRange);
DataValidation accountNumberValidation = validationHelper.createValidation(accountNumberConstraint, accountNumberRange);
DataValidation savingsaccountNumberValidation = validationHelper.createValidation(savingsaccountNumberConstraint, savingsaccountNumberRange);
DataValidation guranterTypeValidation = validationHelper.createValidation(guranterTypeConstraint, guranterTypeRange);
DataValidation guarantorRelationshipValidation=validationHelper.createValidation(guarantorRelationshipConstraint,guranterRelationshipTypeRange);
DataValidation entityofficeValidation = validationHelper.createValidation(entityofficeNameConstraint, entityofficeNameRange);
DataValidation entityclientValidation = validationHelper.createValidation(entityclientNameConstraint, entityclientNameRange);
worksheet.addValidationData(officeValidation);
worksheet.addValidationData(clientValidation);
worksheet.addValidationData(accountNumberValidation);
worksheet.addValidationData(guranterTypeValidation);
@@ -223,92 +223,92 @@ public class GuarantorWorkbookPopulator extends AbstractWorkbookPopulator {
worksheet.addValidationData(entityofficeValidation);
worksheet.addValidationData(entityclientValidation);
worksheet.addValidationData(savingsaccountNumberValidation);
}
private void setNames(Sheet worksheet) {
Workbook addGurarantorWorkbook = worksheet.getWorkbook();
ArrayList<String> officeNames = new ArrayList<String>(officeSheetPopulator.getOfficeNames());
//Office Names
Name officeGroup = addGurarantorWorkbook.createName();
officeGroup.setNameName("Office");
officeGroup.setRefersToFormula(TemplatePopulateImportConstants.OFFICE_SHEET_NAME+"!$B$2:$B$" + (officeNames.size() + 1));
}
private void setNames(Sheet worksheet) {
Workbook addGurarantorWorkbook = worksheet.getWorkbook();
ArrayList<String> officeNames = new ArrayList<String>(officeSheetPopulator.getOfficeNames());
//Office Names
Name officeGroup = addGurarantorWorkbook.createName();
officeGroup.setNameName("Office");
officeGroup.setRefersToFormula(TemplatePopulateImportConstants.OFFICE_SHEET_NAME+"!$B$2:$B$" + (officeNames.size() + 1));
//GurantorRelationshipTypes Names
Name guarantorRelationshipsGroup = addGurarantorWorkbook.createName();
guarantorRelationshipsGroup.setNameName("GuarantorRelationship");
guarantorRelationshipsGroup.setRefersToFormula(TemplatePopulateImportConstants.GUARANTOR_SHEET_NAME+"!$CH$2:$CH$" + (guarantorRelationshipTypes.size() + 1));
//Clients Named after Offices
for(Integer i = 0; i < officeNames.size(); i++) {
Integer[] officeNameToBeginEndIndexesOfClients = clientSheetPopulator.getOfficeNameToBeginEndIndexesOfClients().get(i);
Name name = addGurarantorWorkbook.createName();
if(officeNameToBeginEndIndexesOfClients != null) {
name.setNameName("Client_" + officeNames.get(i).trim().replaceAll("[ )(]", "_"));
name.setRefersToFormula(TemplatePopulateImportConstants.CLIENT_SHEET_NAME+"!$B$" + officeNameToBeginEndIndexesOfClients[0] +
":$B$" + officeNameToBeginEndIndexesOfClients[1]);
}
}
//Counting clients with active loans and starting and end addresses of cells
HashMap<String, Integer[]> clientNameToBeginEndIndexes = new HashMap<String, Integer[]>();
ArrayList<String> clientsWithActiveLoans = new ArrayList<String>();
ArrayList<String> clientIdsWithActiveLoans = new ArrayList<String>();
int startIndex = 1, endIndex = 1;
String clientName = "";
String clientId = "";
for(int i = 0; i < loans.size(); i++){
if(!clientName.equals(loans.get(i).getClientName())) {
endIndex = i + 1;
clientNameToBeginEndIndexes.put(clientName, new Integer[]{startIndex, endIndex});
startIndex = i + 2;
clientName = loans.get(i).getClientName();
clientId = loans.get(i).getClientId().toString();
clientsWithActiveLoans.add(clientName);
clientIdsWithActiveLoans.add(clientId);
}
if(i == loans.size()-1) {
endIndex = i + 2;
clientNameToBeginEndIndexes.put(clientName, new Integer[]{startIndex, endIndex});
}
}
//Account Number Named after Clients
for(int j = 0; j < clientsWithActiveLoans.size(); j++) {
Name name = addGurarantorWorkbook.createName();
name.setNameName("Account_" + clientsWithActiveLoans.get(j).replaceAll(" ", "_") + "_" + clientIdsWithActiveLoans.get(j) + "_");
name.setRefersToFormula(TemplatePopulateImportConstants.GUARANTOR_SHEET_NAME+"!$CE$" + clientNameToBeginEndIndexes.get(clientsWithActiveLoans.get(j))[0] +
":$CE$" + clientNameToBeginEndIndexes.get(clientsWithActiveLoans.get(j))[1]);
}
///savings
//Counting clients with active savings and starting and end addresses of cells for naming
ArrayList<String> clientsWithActiveSavings = new ArrayList<String>();
ArrayList<String> clientIdsWithActiveSavings = new ArrayList<String>();
clientName="";
clientId="";
for(int i = 0; i < savings.size(); i++){
if(!clientName.equals(savings.get(i).getClientName())) {
endIndex = i + 1;
clientNameToBeginEndIndexes.put(clientName, new Integer[]{startIndex, endIndex});
startIndex = i + 2;
clientName = savings.get(i).getClientName();
clientId = savings.get(i).getClientId().toString();
clientsWithActiveSavings.add(clientName);
clientIdsWithActiveSavings.add(clientId);
}
if(i == savings.size()-1) {
endIndex = i + 2;
clientNameToBeginEndIndexes.put(clientName, new Integer[]{startIndex, endIndex});
}
}
//Account Number Named after Clients
for(int j = 0; j < clientsWithActiveSavings.size(); j++) {
Name name = addGurarantorWorkbook.createName();
name.setNameName("SavingsAccount_" + clientsWithActiveSavings.get(j).replaceAll(" ", "_") + "_" + clientIdsWithActiveSavings.get(j) + "_");
name.setRefersToFormula(TemplatePopulateImportConstants.GUARANTOR_SHEET_NAME+"!$CG$" + clientNameToBeginEndIndexes.get(clientsWithActiveSavings.get(j))[0] +
":$CG$" + clientNameToBeginEndIndexes.get(clientsWithActiveSavings.get(j))[1]);
}
}
//GurantorRelationshipTypes Names
Name guarantorRelationshipsGroup = addGurarantorWorkbook.createName();
guarantorRelationshipsGroup.setNameName("GuarantorRelationship");
guarantorRelationshipsGroup.setRefersToFormula(TemplatePopulateImportConstants.GUARANTOR_SHEET_NAME+"!$CH$2:$CH$" + (guarantorRelationshipTypes.size() + 1));
//Clients Named after Offices
for(Integer i = 0; i < officeNames.size(); i++) {
Integer[] officeNameToBeginEndIndexesOfClients = clientSheetPopulator.getOfficeNameToBeginEndIndexesOfClients().get(i);
Name name = addGurarantorWorkbook.createName();
if(officeNameToBeginEndIndexesOfClients != null) {
name.setNameName("Client_" + officeNames.get(i).trim().replaceAll("[ )(]", "_"));
name.setRefersToFormula(TemplatePopulateImportConstants.CLIENT_SHEET_NAME+"!$B$" + officeNameToBeginEndIndexesOfClients[0] +
":$B$" + officeNameToBeginEndIndexesOfClients[1]);
}
}
//Counting clients with active loans and starting and end addresses of cells
HashMap<String, Integer[]> clientNameToBeginEndIndexes = new HashMap<String, Integer[]>();
ArrayList<String> clientsWithActiveLoans = new ArrayList<String>();
ArrayList<String> clientIdsWithActiveLoans = new ArrayList<String>();
int startIndex = 1, endIndex = 1;
String clientName = "";
String clientId = "";
for(int i = 0; i < loans.size(); i++){
if(!clientName.equals(loans.get(i).getClientName())) {
endIndex = i + 1;
clientNameToBeginEndIndexes.put(clientName, new Integer[]{startIndex, endIndex});
startIndex = i + 2;
clientName = loans.get(i).getClientName();
clientId = loans.get(i).getClientId().toString();
clientsWithActiveLoans.add(clientName);
clientIdsWithActiveLoans.add(clientId);
}
if(i == loans.size()-1) {
endIndex = i + 2;
clientNameToBeginEndIndexes.put(clientName, new Integer[]{startIndex, endIndex});
}
}
//Account Number Named after Clients
for(int j = 0; j < clientsWithActiveLoans.size(); j++) {
Name name = addGurarantorWorkbook.createName();
name.setNameName("Account_" + clientsWithActiveLoans.get(j).replaceAll(" ", "_") + "_" + clientIdsWithActiveLoans.get(j) + "_");
name.setRefersToFormula(TemplatePopulateImportConstants.GUARANTOR_SHEET_NAME+"!$CE$" + clientNameToBeginEndIndexes.get(clientsWithActiveLoans.get(j))[0] +
":$CE$" + clientNameToBeginEndIndexes.get(clientsWithActiveLoans.get(j))[1]);
}
///savings
//Counting clients with active savings and starting and end addresses of cells for naming
ArrayList<String> clientsWithActiveSavings = new ArrayList<String>();
ArrayList<String> clientIdsWithActiveSavings = new ArrayList<String>();
clientName="";
clientId="";
for(int i = 0; i < savings.size(); i++){
if(!clientName.equals(savings.get(i).getClientName())) {
endIndex = i + 1;
clientNameToBeginEndIndexes.put(clientName, new Integer[]{startIndex, endIndex});
startIndex = i + 2;
clientName = savings.get(i).getClientName();
clientId = savings.get(i).getClientId().toString();
clientsWithActiveSavings.add(clientName);
clientIdsWithActiveSavings.add(clientId);
}
if(i == savings.size()-1) {
endIndex = i + 2;
clientNameToBeginEndIndexes.put(clientName, new Integer[]{startIndex, endIndex});
}
}
//Account Number Named after Clients
for(int j = 0; j < clientsWithActiveSavings.size(); j++) {
Name name = addGurarantorWorkbook.createName();
name.setNameName("SavingsAccount_" + clientsWithActiveSavings.get(j).replaceAll(" ", "_") + "_" + clientIdsWithActiveSavings.get(j) + "_");
name.setRefersToFormula(TemplatePopulateImportConstants.GUARANTOR_SHEET_NAME+"!$CG$" + clientNameToBeginEndIndexes.get(clientsWithActiveSavings.get(j))[0] +
":$CG$" + clientNameToBeginEndIndexes.get(clientsWithActiveSavings.get(j))[1]);
}
}
}
@@ -34,158 +34,158 @@ import java.util.ArrayList;
public class JournalEntriesWorkbookPopulator extends AbstractWorkbookPopulator {
private OfficeSheetPopulator officeSheetPopulator;
private GlAccountSheetPopulator glAccountSheetPopulator;
private ExtrasSheetPopulator extrasSheetPopulator;
private OfficeSheetPopulator officeSheetPopulator;
private GlAccountSheetPopulator glAccountSheetPopulator;
private ExtrasSheetPopulator extrasSheetPopulator;
public JournalEntriesWorkbookPopulator(OfficeSheetPopulator officeSheetPopulator,
GlAccountSheetPopulator glAccountSheetPopulator, ExtrasSheetPopulator extrasSheetPopulator) {
this.officeSheetPopulator = officeSheetPopulator;
this.glAccountSheetPopulator = glAccountSheetPopulator;
this.extrasSheetPopulator = extrasSheetPopulator;
}
public JournalEntriesWorkbookPopulator(OfficeSheetPopulator officeSheetPopulator,
GlAccountSheetPopulator glAccountSheetPopulator, ExtrasSheetPopulator extrasSheetPopulator) {
this.officeSheetPopulator = officeSheetPopulator;
this.glAccountSheetPopulator = glAccountSheetPopulator;
this.extrasSheetPopulator = extrasSheetPopulator;
}
@Override
public void populate(Workbook workbook,String dateFormat) {
Sheet addJournalEntriesSheet = workbook.createSheet(TemplatePopulateImportConstants.JOURNAL_ENTRY_SHEET_NAME);
officeSheetPopulator.populate(workbook,dateFormat);
glAccountSheetPopulator.populate(workbook,dateFormat);
extrasSheetPopulator.populate(workbook,dateFormat);
setRules(addJournalEntriesSheet);
setDefaults(addJournalEntriesSheet);
setLayout(addJournalEntriesSheet);
}
private void setLayout(Sheet worksheet) {
Row rowHeader = worksheet.createRow(TemplatePopulateImportConstants.ROWHEADER_INDEX);
rowHeader.setHeight(TemplatePopulateImportConstants.ROW_HEADER_HEIGHT);
worksheet.setColumnWidth(JournalEntryConstants.OFFICE_NAME_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(JournalEntryConstants.TRANSACION_ON_DATE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(JournalEntryConstants.CURRENCY_NAME_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(JournalEntryConstants.PAYMENT_TYPE_ID_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(JournalEntryConstants.TRANSACTION_ID_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(JournalEntryConstants.GL_ACCOUNT_ID_CREDIT_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(JournalEntryConstants.AMOUNT_CREDIT_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(JournalEntryConstants.GL_ACCOUNT_ID_DEBIT_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(JournalEntryConstants.AMOUNT_DEBIT_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(JournalEntryConstants.ACCOUNT_NO_COL,TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(JournalEntryConstants.CHECK_NO_COL,TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(JournalEntryConstants.ROUTING_CODE_COL,TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(JournalEntryConstants.RECEIPT_NO_COL,TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(JournalEntryConstants.BANK_NO_COL,TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(JournalEntryConstants.COMMENTS_COL,TemplatePopulateImportConstants.EXTRALARGE_COL_SIZE);
@Override
public void populate(Workbook workbook,String dateFormat) {
Sheet addJournalEntriesSheet = workbook.createSheet(TemplatePopulateImportConstants.JOURNAL_ENTRY_SHEET_NAME);
officeSheetPopulator.populate(workbook,dateFormat);
glAccountSheetPopulator.populate(workbook,dateFormat);
extrasSheetPopulator.populate(workbook,dateFormat);
setRules(addJournalEntriesSheet);
setDefaults(addJournalEntriesSheet);
setLayout(addJournalEntriesSheet);
}
private void setLayout(Sheet worksheet) {
Row rowHeader = worksheet.createRow(TemplatePopulateImportConstants.ROWHEADER_INDEX);
rowHeader.setHeight(TemplatePopulateImportConstants.ROW_HEADER_HEIGHT);
worksheet.setColumnWidth(JournalEntryConstants.OFFICE_NAME_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(JournalEntryConstants.TRANSACION_ON_DATE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(JournalEntryConstants.CURRENCY_NAME_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(JournalEntryConstants.PAYMENT_TYPE_ID_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(JournalEntryConstants.TRANSACTION_ID_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(JournalEntryConstants.GL_ACCOUNT_ID_CREDIT_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(JournalEntryConstants.AMOUNT_CREDIT_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(JournalEntryConstants.GL_ACCOUNT_ID_DEBIT_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(JournalEntryConstants.AMOUNT_DEBIT_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(JournalEntryConstants.ACCOUNT_NO_COL,TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(JournalEntryConstants.CHECK_NO_COL,TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(JournalEntryConstants.ROUTING_CODE_COL,TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(JournalEntryConstants.RECEIPT_NO_COL,TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(JournalEntryConstants.BANK_NO_COL,TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(JournalEntryConstants.COMMENTS_COL,TemplatePopulateImportConstants.EXTRALARGE_COL_SIZE);
writeString(JournalEntryConstants.OFFICE_NAME_COL, rowHeader, "Office Name*");
writeString(JournalEntryConstants.TRANSACION_ON_DATE_COL, rowHeader, "Transaction On *");
writeString(JournalEntryConstants.CURRENCY_NAME_COL, rowHeader, "Currecy Type*");
writeString(JournalEntryConstants.PAYMENT_TYPE_ID_COL, rowHeader, "Payment Type*");
writeString(JournalEntryConstants.TRANSACTION_ID_COL, rowHeader, "Transaction Id*");
writeString(JournalEntryConstants.GL_ACCOUNT_ID_CREDIT_COL, rowHeader, "Credit Account Type*");
writeString(JournalEntryConstants.AMOUNT_CREDIT_COL, rowHeader, "Amount*");
writeString(JournalEntryConstants.GL_ACCOUNT_ID_DEBIT_COL, rowHeader, "Debit Account Type*");
writeString(JournalEntryConstants.AMOUNT_DEBIT_COL, rowHeader, "Amount*");
writeString(JournalEntryConstants.ACCOUNT_NO_COL,rowHeader,"Account#");
writeString(JournalEntryConstants.CHECK_NO_COL,rowHeader,"Cheque#");
writeString(JournalEntryConstants.ROUTING_CODE_COL,rowHeader,"Routing code");
writeString(JournalEntryConstants.RECEIPT_NO_COL,rowHeader,"Receipt#");
writeString(JournalEntryConstants.BANK_NO_COL,rowHeader,"Bank#");
writeString(JournalEntryConstants.COMMENTS_COL,rowHeader,"Comments");
writeString(JournalEntryConstants.OFFICE_NAME_COL, rowHeader, "Office Name*");
writeString(JournalEntryConstants.TRANSACION_ON_DATE_COL, rowHeader, "Transaction On *");
writeString(JournalEntryConstants.CURRENCY_NAME_COL, rowHeader, "Currecy Type*");
writeString(JournalEntryConstants.PAYMENT_TYPE_ID_COL, rowHeader, "Payment Type*");
writeString(JournalEntryConstants.TRANSACTION_ID_COL, rowHeader, "Transaction Id*");
writeString(JournalEntryConstants.GL_ACCOUNT_ID_CREDIT_COL, rowHeader, "Credit Account Type*");
writeString(JournalEntryConstants.AMOUNT_CREDIT_COL, rowHeader, "Amount*");
writeString(JournalEntryConstants.GL_ACCOUNT_ID_DEBIT_COL, rowHeader, "Debit Account Type*");
writeString(JournalEntryConstants.AMOUNT_DEBIT_COL, rowHeader, "Amount*");
writeString(JournalEntryConstants.ACCOUNT_NO_COL,rowHeader,"Account#");
writeString(JournalEntryConstants.CHECK_NO_COL,rowHeader,"Cheque#");
writeString(JournalEntryConstants.ROUTING_CODE_COL,rowHeader,"Routing code");
writeString(JournalEntryConstants.RECEIPT_NO_COL,rowHeader,"Receipt#");
writeString(JournalEntryConstants.BANK_NO_COL,rowHeader,"Bank#");
writeString(JournalEntryConstants.COMMENTS_COL,rowHeader,"Comments");
// TODO Auto-generated method stub
// TODO Auto-generated method stub
}
private void setRules(Sheet worksheet) {
CellRangeAddressList officeNameRange = new CellRangeAddressList(1,
SpreadsheetVersion.EXCEL97.getLastRowIndex(),
JournalEntryConstants.OFFICE_NAME_COL,JournalEntryConstants. OFFICE_NAME_COL);
}
private void setRules(Sheet worksheet) {
CellRangeAddressList officeNameRange = new CellRangeAddressList(1,
SpreadsheetVersion.EXCEL97.getLastRowIndex(),
JournalEntryConstants.OFFICE_NAME_COL,JournalEntryConstants. OFFICE_NAME_COL);
CellRangeAddressList currencyCodeRange = new CellRangeAddressList(
1, SpreadsheetVersion.EXCEL97.getLastRowIndex(),
JournalEntryConstants.CURRENCY_NAME_COL, JournalEntryConstants.CURRENCY_NAME_COL);
CellRangeAddressList currencyCodeRange = new CellRangeAddressList(
1, SpreadsheetVersion.EXCEL97.getLastRowIndex(),
JournalEntryConstants.CURRENCY_NAME_COL, JournalEntryConstants.CURRENCY_NAME_COL);
CellRangeAddressList paymenttypeRange = new CellRangeAddressList(1,
SpreadsheetVersion.EXCEL97.getLastRowIndex(),
JournalEntryConstants.PAYMENT_TYPE_ID_COL, JournalEntryConstants.PAYMENT_TYPE_ID_COL);
CellRangeAddressList paymenttypeRange = new CellRangeAddressList(1,
SpreadsheetVersion.EXCEL97.getLastRowIndex(),
JournalEntryConstants.PAYMENT_TYPE_ID_COL, JournalEntryConstants.PAYMENT_TYPE_ID_COL);
CellRangeAddressList glaccountCreditRange = new CellRangeAddressList(
1, SpreadsheetVersion.EXCEL97.getLastRowIndex(),
JournalEntryConstants.GL_ACCOUNT_ID_CREDIT_COL, JournalEntryConstants.GL_ACCOUNT_ID_CREDIT_COL);
CellRangeAddressList glaccountCreditRange = new CellRangeAddressList(
1, SpreadsheetVersion.EXCEL97.getLastRowIndex(),
JournalEntryConstants.GL_ACCOUNT_ID_CREDIT_COL, JournalEntryConstants.GL_ACCOUNT_ID_CREDIT_COL);
CellRangeAddressList glaccountDebitRange = new CellRangeAddressList(
1, SpreadsheetVersion.EXCEL97.getLastRowIndex(),
JournalEntryConstants.GL_ACCOUNT_ID_DEBIT_COL, JournalEntryConstants.GL_ACCOUNT_ID_DEBIT_COL);
CellRangeAddressList glaccountDebitRange = new CellRangeAddressList(
1, SpreadsheetVersion.EXCEL97.getLastRowIndex(),
JournalEntryConstants.GL_ACCOUNT_ID_DEBIT_COL, JournalEntryConstants.GL_ACCOUNT_ID_DEBIT_COL);
DataValidationHelper validationHelper = new HSSFDataValidationHelper(
(HSSFSheet) worksheet);
DataValidationHelper validationHelper = new HSSFDataValidationHelper(
(HSSFSheet) worksheet);
setNames(worksheet);
setNames(worksheet);
DataValidationConstraint officeNameConstraint = validationHelper
.createFormulaListConstraint("Office");
DataValidationConstraint currencyCodeConstraint = validationHelper
.createFormulaListConstraint("Currency");
DataValidationConstraint paymentTypeConstraint = validationHelper
.createFormulaListConstraint("PaymentType");
DataValidationConstraint officeNameConstraint = validationHelper
.createFormulaListConstraint("Office");
DataValidationConstraint currencyCodeConstraint = validationHelper
.createFormulaListConstraint("Currency");
DataValidationConstraint paymentTypeConstraint = validationHelper
.createFormulaListConstraint("PaymentType");
DataValidationConstraint glaccountConstraint = validationHelper
.createFormulaListConstraint("GlAccounts");
DataValidationConstraint glaccountConstraint = validationHelper
.createFormulaListConstraint("GlAccounts");
DataValidation officeValidation = validationHelper
.createValidation(officeNameConstraint, officeNameRange);
DataValidation currencyCodeValidation = validationHelper
.createValidation(currencyCodeConstraint, currencyCodeRange);
DataValidation paymentTypeValidation = validationHelper
.createValidation(paymentTypeConstraint, paymenttypeRange);
DataValidation officeValidation = validationHelper
.createValidation(officeNameConstraint, officeNameRange);
DataValidation currencyCodeValidation = validationHelper
.createValidation(currencyCodeConstraint, currencyCodeRange);
DataValidation paymentTypeValidation = validationHelper
.createValidation(paymentTypeConstraint, paymenttypeRange);
DataValidation glaccountCreditValidation = validationHelper
.createValidation(glaccountConstraint, glaccountCreditRange);
DataValidation glaccountDebitValidation = validationHelper
.createValidation(glaccountConstraint, glaccountDebitRange);
DataValidation glaccountCreditValidation = validationHelper
.createValidation(glaccountConstraint, glaccountCreditRange);
DataValidation glaccountDebitValidation = validationHelper
.createValidation(glaccountConstraint, glaccountDebitRange);
worksheet.addValidationData(officeValidation);
worksheet.addValidationData(currencyCodeValidation);
worksheet.addValidationData(paymentTypeValidation);
worksheet.addValidationData(officeValidation);
worksheet.addValidationData(currencyCodeValidation);
worksheet.addValidationData(paymentTypeValidation);
worksheet.addValidationData(glaccountCreditValidation);
worksheet.addValidationData(glaccountDebitValidation);
}
private void setNames(Sheet worksheet) {
Workbook addJournalEntriesWorkbook = worksheet.getWorkbook();
ArrayList<String> officeNames = new ArrayList<>(officeSheetPopulator.getOfficeNames());
// Office Names
Name officeGroup = addJournalEntriesWorkbook.createName();
officeGroup.setNameName("Office");
officeGroup.setRefersToFormula(TemplatePopulateImportConstants.OFFICE_SHEET_NAME+"!$B$2:$B$"
+ (officeNames.size() + 1));
// Payment Type Name
Name paymentTypeGroup = addJournalEntriesWorkbook.createName();
paymentTypeGroup.setNameName("PaymentType");
paymentTypeGroup.setRefersToFormula(TemplatePopulateImportConstants.EXTRAS_SHEET_NAME+"!$D$2:$D$"
+ (extrasSheetPopulator.getPaymentTypesSize() + 1));
// Currency Type Name
Name currencyGroup = addJournalEntriesWorkbook.createName();
currencyGroup.setNameName("Currency");
currencyGroup.setRefersToFormula(TemplatePopulateImportConstants.EXTRAS_SHEET_NAME+"!$F$2:$F$"
+ (extrasSheetPopulator.getCurrenciesSize() + 1));
worksheet.addValidationData(glaccountCreditValidation);
worksheet.addValidationData(glaccountDebitValidation);
}
private void setNames(Sheet worksheet) {
Workbook addJournalEntriesWorkbook = worksheet.getWorkbook();
ArrayList<String> officeNames = new ArrayList<>(officeSheetPopulator.getOfficeNames());
// Office Names
Name officeGroup = addJournalEntriesWorkbook.createName();
officeGroup.setNameName("Office");
officeGroup.setRefersToFormula(TemplatePopulateImportConstants.OFFICE_SHEET_NAME+"!$B$2:$B$"
+ (officeNames.size() + 1));
// Payment Type Name
Name paymentTypeGroup = addJournalEntriesWorkbook.createName();
paymentTypeGroup.setNameName("PaymentType");
paymentTypeGroup.setRefersToFormula(TemplatePopulateImportConstants.EXTRAS_SHEET_NAME+"!$D$2:$D$"
+ (extrasSheetPopulator.getPaymentTypesSize() + 1));
// Currency Type Name
Name currencyGroup = addJournalEntriesWorkbook.createName();
currencyGroup.setNameName("Currency");
currencyGroup.setRefersToFormula(TemplatePopulateImportConstants.EXTRAS_SHEET_NAME+"!$F$2:$F$"
+ (extrasSheetPopulator.getCurrenciesSize() + 1));
// Account Name
Name glaccountGroup = addJournalEntriesWorkbook.createName();
glaccountGroup.setNameName("GlAccounts");
glaccountGroup.setRefersToFormula(TemplatePopulateImportConstants.GL_ACCOUNTS_SHEET_NAME+"!$B$2:$B$"
+ (glAccountSheetPopulator.getGlAccountNamesSize() + 1));
}
private void setDefaults(Sheet worksheet) {
for (Integer rowNo = 1; rowNo < 1000; rowNo++) {
Row row = worksheet.createRow(rowNo);
}
// Account Name
Name glaccountGroup = addJournalEntriesWorkbook.createName();
glaccountGroup.setNameName("GlAccounts");
glaccountGroup.setRefersToFormula(TemplatePopulateImportConstants.GL_ACCOUNTS_SHEET_NAME+"!$B$2:$B$"
+ (glAccountSheetPopulator.getGlAccountNamesSize() + 1));
}
private void setDefaults(Sheet worksheet) {
for (Integer rowNo = 1; rowNo < 1000; rowNo++) {
Row row = worksheet.createRow(rowNo);
}
}
}
}
@@ -38,262 +38,262 @@ import java.text.SimpleDateFormat;
import java.util.*;
public class LoanRepaymentWorkbookPopulator extends AbstractWorkbookPopulator {
private OfficeSheetPopulator officeSheetPopulator;
private ClientSheetPopulator clientSheetPopulator;
private ExtrasSheetPopulator extrasSheetPopulator;
private List<LoanAccountData> allloans;
private Map<Long,String> clientIdToClientExternalId;
private OfficeSheetPopulator officeSheetPopulator;
private ClientSheetPopulator clientSheetPopulator;
private ExtrasSheetPopulator extrasSheetPopulator;
private List<LoanAccountData> allloans;
private Map<Long,String> clientIdToClientExternalId;
public LoanRepaymentWorkbookPopulator(List<LoanAccountData> loans, OfficeSheetPopulator officeSheetPopulator,
ClientSheetPopulator clientSheetPopulator, ExtrasSheetPopulator extrasSheetPopulator) {
this.allloans = loans;
this.officeSheetPopulator = officeSheetPopulator;
this.clientSheetPopulator = clientSheetPopulator;
this.extrasSheetPopulator = extrasSheetPopulator;
}
public LoanRepaymentWorkbookPopulator(List<LoanAccountData> loans, OfficeSheetPopulator officeSheetPopulator,
ClientSheetPopulator clientSheetPopulator, ExtrasSheetPopulator extrasSheetPopulator) {
this.allloans = loans;
this.officeSheetPopulator = officeSheetPopulator;
this.clientSheetPopulator = clientSheetPopulator;
this.extrasSheetPopulator = extrasSheetPopulator;
}
@Override
public void populate(Workbook workbook,String dateFormat) {
Sheet loanRepaymentSheet = workbook.createSheet(TemplatePopulateImportConstants.LOAN_REPAYMENT_SHEET_NAME);
setLayout(loanRepaymentSheet);
officeSheetPopulator.populate(workbook,dateFormat);
clientSheetPopulator.populate(workbook,dateFormat);
extrasSheetPopulator.populate(workbook,dateFormat);
setClientIdToClientExternalId();
populateLoansTable(loanRepaymentSheet,dateFormat);
setRules(loanRepaymentSheet,dateFormat);
setDefaults(loanRepaymentSheet,dateFormat);
}
@Override
public void populate(Workbook workbook,String dateFormat) {
Sheet loanRepaymentSheet = workbook.createSheet(TemplatePopulateImportConstants.LOAN_REPAYMENT_SHEET_NAME);
setLayout(loanRepaymentSheet);
officeSheetPopulator.populate(workbook,dateFormat);
clientSheetPopulator.populate(workbook,dateFormat);
extrasSheetPopulator.populate(workbook,dateFormat);
setClientIdToClientExternalId();
populateLoansTable(loanRepaymentSheet,dateFormat);
setRules(loanRepaymentSheet,dateFormat);
setDefaults(loanRepaymentSheet,dateFormat);
}
private void setClientIdToClientExternalId() {
clientIdToClientExternalId =new HashMap<>();
List<ClientData>allclients=clientSheetPopulator.getClients();
for (ClientData client: allclients) {
if (client.getExternalId()!=null)
clientIdToClientExternalId.put(client.getId(),client.getExternalId());
}
}
private void setClientIdToClientExternalId() {
clientIdToClientExternalId =new HashMap<>();
List<ClientData>allclients=clientSheetPopulator.getClients();
for (ClientData client: allclients) {
if (client.getExternalId()!=null)
clientIdToClientExternalId.put(client.getId(),client.getExternalId());
}
}
private void setDefaults(Sheet worksheet,String dateFormat) {
for (Integer rowNo = 1; rowNo < 3000; rowNo++) {
Row row = worksheet.getRow(rowNo);
if (row == null)
row = worksheet.createRow(rowNo);
writeFormula(LoanRepaymentConstants.CLIENT_EXTERNAL_ID, row,
"IF(ISERROR(VLOOKUP($B"+(rowNo+1)+",$R$2:$S$"+(allloans.size()+1)+",2,FALSE))," +
"\"\",(VLOOKUP($B"+(rowNo+1)+",$R$2:$S$"+(allloans.size()+1)+",2,FALSE)))");
writeFormula(LoanRepaymentConstants.PRODUCT_COL, row,
"IF(ISERROR(VLOOKUP($D" + (rowNo + 1) + ",$T$2:$X$" + (allloans.size() + 1)
+ ",2,FALSE)),\"\",VLOOKUP($D" + (rowNo + 1) + ",$T$2:$X$" + (allloans.size() + 1)
+ ",2,FALSE))");
writeFormula(LoanRepaymentConstants.PRINCIPAL_COL, row,
"IF(ISERROR(VLOOKUP($D" + (rowNo + 1) + ",$T$2:$X$" + (allloans.size() + 1)
+ ",3,FALSE)),\"\",VLOOKUP($D" + (rowNo + 1) + ",$T$2:$X$" + (allloans.size() + 1)
+ ",3,FALSE))");
writeFormula(LoanRepaymentConstants.TOTAL_OUTSTANDING_AMOUNT_COL, row,
"IF(ISERROR(VLOOKUP($D" + (rowNo + 1) + ",$T$2:$X$" + (allloans.size() + 1)
+ ",4,FALSE)),\"\",VLOOKUP($D" + (rowNo + 1) + ",$T$2:$X$" + (allloans.size() + 1)
+ ",4,FALSE))");
private void setDefaults(Sheet worksheet,String dateFormat) {
for (Integer rowNo = 1; rowNo < 3000; rowNo++) {
Row row = worksheet.getRow(rowNo);
if (row == null)
row = worksheet.createRow(rowNo);
writeFormula(LoanRepaymentConstants.CLIENT_EXTERNAL_ID, row,
"IF(ISERROR(VLOOKUP($B"+(rowNo+1)+",$R$2:$S$"+(allloans.size()+1)+",2,FALSE))," +
"\"\",(VLOOKUP($B"+(rowNo+1)+",$R$2:$S$"+(allloans.size()+1)+",2,FALSE)))");
writeFormula(LoanRepaymentConstants.PRODUCT_COL, row,
"IF(ISERROR(VLOOKUP($D" + (rowNo + 1) + ",$T$2:$X$" + (allloans.size() + 1)
+ ",2,FALSE)),\"\",VLOOKUP($D" + (rowNo + 1) + ",$T$2:$X$" + (allloans.size() + 1)
+ ",2,FALSE))");
writeFormula(LoanRepaymentConstants.PRINCIPAL_COL, row,
"IF(ISERROR(VLOOKUP($D" + (rowNo + 1) + ",$T$2:$X$" + (allloans.size() + 1)
+ ",3,FALSE)),\"\",VLOOKUP($D" + (rowNo + 1) + ",$T$2:$X$" + (allloans.size() + 1)
+ ",3,FALSE))");
writeFormula(LoanRepaymentConstants.TOTAL_OUTSTANDING_AMOUNT_COL, row,
"IF(ISERROR(VLOOKUP($D" + (rowNo + 1) + ",$T$2:$X$" + (allloans.size() + 1)
+ ",4,FALSE)),\"\",VLOOKUP($D" + (rowNo + 1) + ",$T$2:$X$" + (allloans.size() + 1)
+ ",4,FALSE))");
writeFormula(LoanRepaymentConstants.LOAN_DISBURSEMENT_DATE_COL, row,
"IF(ISERROR(VLOOKUP($D" + (rowNo + 1) + ",$T$2:$X$" + (allloans.size() + 1)
+ ",5,FALSE)),\"\",VLOOKUP($D" + (rowNo + 1) + ",$T$2:$X$" + (allloans.size() + 1)
+ ",5,FALSE))");
Workbook workbook=worksheet.getWorkbook();
CellStyle dateCellStyle = workbook.createCellStyle();
short df = workbook.createDataFormat().getFormat(dateFormat);
dateCellStyle.setDataFormat(df);
row.getCell(LoanRepaymentConstants.LOAN_DISBURSEMENT_DATE_COL).setCellStyle(dateCellStyle);
}
}
writeFormula(LoanRepaymentConstants.LOAN_DISBURSEMENT_DATE_COL, row,
"IF(ISERROR(VLOOKUP($D" + (rowNo + 1) + ",$T$2:$X$" + (allloans.size() + 1)
+ ",5,FALSE)),\"\",VLOOKUP($D" + (rowNo + 1) + ",$T$2:$X$" + (allloans.size() + 1)
+ ",5,FALSE))");
Workbook workbook=worksheet.getWorkbook();
CellStyle dateCellStyle = workbook.createCellStyle();
short df = workbook.createDataFormat().getFormat(dateFormat);
dateCellStyle.setDataFormat(df);
row.getCell(LoanRepaymentConstants.LOAN_DISBURSEMENT_DATE_COL).setCellStyle(dateCellStyle);
}
}
private void setRules(Sheet worksheet,String dateFormat) {
CellRangeAddressList officeNameRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(),
LoanRepaymentConstants.OFFICE_NAME_COL, LoanRepaymentConstants.OFFICE_NAME_COL);
CellRangeAddressList clientNameRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(),
LoanRepaymentConstants.CLIENT_NAME_COL, LoanRepaymentConstants.CLIENT_NAME_COL);
CellRangeAddressList accountNumberRange = new CellRangeAddressList(1,
SpreadsheetVersion.EXCEL97.getLastRowIndex(), LoanRepaymentConstants.LOAN_ACCOUNT_NO_COL, LoanRepaymentConstants.LOAN_ACCOUNT_NO_COL);
CellRangeAddressList repaymentTypeRange = new CellRangeAddressList(1,
SpreadsheetVersion.EXCEL97.getLastRowIndex(), LoanRepaymentConstants.REPAYMENT_TYPE_COL, LoanRepaymentConstants.REPAYMENT_TYPE_COL);
CellRangeAddressList repaymentDateRange = new CellRangeAddressList(1,
SpreadsheetVersion.EXCEL97.getLastRowIndex(), LoanRepaymentConstants.REPAID_ON_DATE_COL, LoanRepaymentConstants.REPAID_ON_DATE_COL);
private void setRules(Sheet worksheet,String dateFormat) {
CellRangeAddressList officeNameRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(),
LoanRepaymentConstants.OFFICE_NAME_COL, LoanRepaymentConstants.OFFICE_NAME_COL);
CellRangeAddressList clientNameRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL97.getLastRowIndex(),
LoanRepaymentConstants.CLIENT_NAME_COL, LoanRepaymentConstants.CLIENT_NAME_COL);
CellRangeAddressList accountNumberRange = new CellRangeAddressList(1,
SpreadsheetVersion.EXCEL97.getLastRowIndex(), LoanRepaymentConstants.LOAN_ACCOUNT_NO_COL, LoanRepaymentConstants.LOAN_ACCOUNT_NO_COL);
CellRangeAddressList repaymentTypeRange = new CellRangeAddressList(1,
SpreadsheetVersion.EXCEL97.getLastRowIndex(), LoanRepaymentConstants.REPAYMENT_TYPE_COL, LoanRepaymentConstants.REPAYMENT_TYPE_COL);
CellRangeAddressList repaymentDateRange = new CellRangeAddressList(1,
SpreadsheetVersion.EXCEL97.getLastRowIndex(), LoanRepaymentConstants.REPAID_ON_DATE_COL, LoanRepaymentConstants.REPAID_ON_DATE_COL);
DataValidationHelper validationHelper = new HSSFDataValidationHelper((HSSFSheet) worksheet);
DataValidationHelper validationHelper = new HSSFDataValidationHelper((HSSFSheet) worksheet);
setNames(worksheet);
setNames(worksheet);
DataValidationConstraint officeNameConstraint = validationHelper.createFormulaListConstraint("Office");
DataValidationConstraint clientNameConstraint = validationHelper
.createFormulaListConstraint("INDIRECT(CONCATENATE(\"Client_\",$A1))");
DataValidationConstraint accountNumberConstraint = validationHelper.createFormulaListConstraint(
"INDIRECT(CONCATENATE(\"Account_\",SUBSTITUTE(SUBSTITUTE(SUBSTITUTE($B1,\" \",\"_\"),\"(\",\"_\"),\")\",\"_\")))");
DataValidationConstraint paymentTypeConstraint = validationHelper.createFormulaListConstraint("PaymentTypes");
DataValidationConstraint repaymentDateConstraint = validationHelper.createDateConstraint(
DataValidationConstraint.OperatorType.BETWEEN,
"=VLOOKUP($D1,$T$2:$X$" + (allloans.size() + 1) + ",4,FALSE)", "=TODAY()", dateFormat);
DataValidationConstraint officeNameConstraint = validationHelper.createFormulaListConstraint("Office");
DataValidationConstraint clientNameConstraint = validationHelper
.createFormulaListConstraint("INDIRECT(CONCATENATE(\"Client_\",$A1))");
DataValidationConstraint accountNumberConstraint = validationHelper.createFormulaListConstraint(
"INDIRECT(CONCATENATE(\"Account_\",SUBSTITUTE(SUBSTITUTE(SUBSTITUTE($B1,\" \",\"_\"),\"(\",\"_\"),\")\",\"_\")))");
DataValidationConstraint paymentTypeConstraint = validationHelper.createFormulaListConstraint("PaymentTypes");
DataValidationConstraint repaymentDateConstraint = validationHelper.createDateConstraint(
DataValidationConstraint.OperatorType.BETWEEN,
"=VLOOKUP($D1,$T$2:$X$" + (allloans.size() + 1) + ",4,FALSE)", "=TODAY()", dateFormat);
DataValidation officeValidation = validationHelper.createValidation(officeNameConstraint, officeNameRange);
DataValidation clientValidation = validationHelper.createValidation(clientNameConstraint, clientNameRange);
DataValidation accountNumberValidation = validationHelper.createValidation(accountNumberConstraint,
accountNumberRange);
DataValidation repaymentTypeValidation = validationHelper.createValidation(paymentTypeConstraint,
repaymentTypeRange);
DataValidation repaymentDateValidation = validationHelper.createValidation(repaymentDateConstraint,
repaymentDateRange);
DataValidation officeValidation = validationHelper.createValidation(officeNameConstraint, officeNameRange);
DataValidation clientValidation = validationHelper.createValidation(clientNameConstraint, clientNameRange);
DataValidation accountNumberValidation = validationHelper.createValidation(accountNumberConstraint,
accountNumberRange);
DataValidation repaymentTypeValidation = validationHelper.createValidation(paymentTypeConstraint,
repaymentTypeRange);
DataValidation repaymentDateValidation = validationHelper.createValidation(repaymentDateConstraint,
repaymentDateRange);
worksheet.addValidationData(officeValidation);
worksheet.addValidationData(clientValidation);
worksheet.addValidationData(accountNumberValidation);
worksheet.addValidationData(repaymentTypeValidation);
worksheet.addValidationData(repaymentDateValidation);
worksheet.addValidationData(officeValidation);
worksheet.addValidationData(clientValidation);
worksheet.addValidationData(accountNumberValidation);
worksheet.addValidationData(repaymentTypeValidation);
worksheet.addValidationData(repaymentDateValidation);
}
}
private void setNames(Sheet worksheet) {
ArrayList<String> officeNames = new ArrayList<>(officeSheetPopulator.getOfficeNames());
Workbook loanRepaymentWorkbook = worksheet.getWorkbook();
// Office Names
Name officeGroup = loanRepaymentWorkbook.createName();
officeGroup.setNameName("Office");
officeGroup.setRefersToFormula(TemplatePopulateImportConstants.OFFICE_SHEET_NAME+"!$B$2:$B$" + (officeNames.size() + 1));
private void setNames(Sheet worksheet) {
ArrayList<String> officeNames = new ArrayList<>(officeSheetPopulator.getOfficeNames());
Workbook loanRepaymentWorkbook = worksheet.getWorkbook();
// Office Names
Name officeGroup = loanRepaymentWorkbook.createName();
officeGroup.setNameName("Office");
officeGroup.setRefersToFormula(TemplatePopulateImportConstants.OFFICE_SHEET_NAME+"!$B$2:$B$" + (officeNames.size() + 1));
// Clients Named after Offices
for (Integer i = 0; i < officeNames.size(); i++) {
Integer[] officeNameToBeginEndIndexesOfClients = clientSheetPopulator
.getOfficeNameToBeginEndIndexesOfClients().get(i);
Name name = loanRepaymentWorkbook.createName();
if (officeNameToBeginEndIndexesOfClients != null) {
name.setNameName("Client_" + officeNames.get(i).trim().replaceAll("[ )(]", "_"));
name.setRefersToFormula(TemplatePopulateImportConstants.CLIENT_SHEET_NAME+"!$B$" + officeNameToBeginEndIndexesOfClients[0] + ":$B$"
+ officeNameToBeginEndIndexesOfClients[1]);
}
}
// Clients Named after Offices
for (Integer i = 0; i < officeNames.size(); i++) {
Integer[] officeNameToBeginEndIndexesOfClients = clientSheetPopulator
.getOfficeNameToBeginEndIndexesOfClients().get(i);
Name name = loanRepaymentWorkbook.createName();
if (officeNameToBeginEndIndexesOfClients != null) {
name.setNameName("Client_" + officeNames.get(i).trim().replaceAll("[ )(]", "_"));
name.setRefersToFormula(TemplatePopulateImportConstants.CLIENT_SHEET_NAME+"!$B$" + officeNameToBeginEndIndexesOfClients[0] + ":$B$"
+ officeNameToBeginEndIndexesOfClients[1]);
}
}
// Counting clients with active loans and starting and end addresses of
// cells
HashMap<String, Integer[]> clientNameToBeginEndIndexes = new HashMap<String, Integer[]>();
ArrayList<String> clientsWithActiveLoans = new ArrayList<String>();
ArrayList<String> clientIdsWithActiveLoans = new ArrayList<String>();
int startIndex = 1, endIndex = 1;
String clientName = "";
String clientId = "";
for (int i = 0; i < allloans.size(); i++) {
if (!clientName.equals(allloans.get(i).getClientName())) {
endIndex = i + 1;
clientNameToBeginEndIndexes.put(clientName, new Integer[] { startIndex, endIndex });
startIndex = i + 2;
clientName = allloans.get(i).getClientName();
clientId = allloans.get(i).getClientId().toString();
if (!clientsWithActiveLoans.contains(clientName)) {
clientsWithActiveLoans.add(clientName);
clientIdsWithActiveLoans.add(clientId);
}
}
if (i == allloans.size() - 1) {
endIndex = i + 2;
clientNameToBeginEndIndexes.put(clientName, new Integer[] { startIndex, endIndex });
}
}
// Counting clients with active loans and starting and end addresses of
// cells
HashMap<String, Integer[]> clientNameToBeginEndIndexes = new HashMap<String, Integer[]>();
ArrayList<String> clientsWithActiveLoans = new ArrayList<String>();
ArrayList<String> clientIdsWithActiveLoans = new ArrayList<String>();
int startIndex = 1, endIndex = 1;
String clientName = "";
String clientId = "";
for (int i = 0; i < allloans.size(); i++) {
if (!clientName.equals(allloans.get(i).getClientName())) {
endIndex = i + 1;
clientNameToBeginEndIndexes.put(clientName, new Integer[] { startIndex, endIndex });
startIndex = i + 2;
clientName = allloans.get(i).getClientName();
clientId = allloans.get(i).getClientId().toString();
if (!clientsWithActiveLoans.contains(clientName)) {
clientsWithActiveLoans.add(clientName);
clientIdsWithActiveLoans.add(clientId);
}
}
if (i == allloans.size() - 1) {
endIndex = i + 2;
clientNameToBeginEndIndexes.put(clientName, new Integer[] { startIndex, endIndex });
}
}
// Account Number Named after Clients
for (int j = 0; j < clientsWithActiveLoans.size(); j++) {
Name name = loanRepaymentWorkbook.createName();
name.setNameName("Account_" + clientsWithActiveLoans.get(j).replace(" ", "_") + "_"
+ clientIdsWithActiveLoans.get(j) + "_");
name.setRefersToFormula(
TemplatePopulateImportConstants.LOAN_REPAYMENT_SHEET_NAME+"!$T$" + clientNameToBeginEndIndexes.get(clientsWithActiveLoans.get(j))[0] + ":$T$"
+ clientNameToBeginEndIndexes.get(clientsWithActiveLoans.get(j))[1]);
}
// Account Number Named after Clients
for (int j = 0; j < clientsWithActiveLoans.size(); j++) {
Name name = loanRepaymentWorkbook.createName();
name.setNameName("Account_" + clientsWithActiveLoans.get(j).replace(" ", "_") + "_"
+ clientIdsWithActiveLoans.get(j) + "_");
name.setRefersToFormula(
TemplatePopulateImportConstants.LOAN_REPAYMENT_SHEET_NAME+"!$T$" + clientNameToBeginEndIndexes.get(clientsWithActiveLoans.get(j))[0] + ":$T$"
+ clientNameToBeginEndIndexes.get(clientsWithActiveLoans.get(j))[1]);
}
// Payment Type Name
Name paymentTypeGroup = loanRepaymentWorkbook.createName();
paymentTypeGroup.setNameName("PaymentTypes");
paymentTypeGroup.setRefersToFormula(TemplatePopulateImportConstants.EXTRAS_SHEET_NAME+"!$D$2:$D$" + (extrasSheetPopulator.getPaymentTypesSize() + 1));
}
// Payment Type Name
Name paymentTypeGroup = loanRepaymentWorkbook.createName();
paymentTypeGroup.setNameName("PaymentTypes");
paymentTypeGroup.setRefersToFormula(TemplatePopulateImportConstants.EXTRAS_SHEET_NAME+"!$D$2:$D$" + (extrasSheetPopulator.getPaymentTypesSize() + 1));
}
private void populateLoansTable(Sheet loanRepaymentSheet,String dateFormat) {
int rowIndex = 1;
Row row;
Workbook workbook = loanRepaymentSheet.getWorkbook();
CellStyle dateCellStyle = workbook.createCellStyle();
short df = workbook.createDataFormat().getFormat(dateFormat);
dateCellStyle.setDataFormat(df);
SimpleDateFormat outputFormat = new SimpleDateFormat(dateFormat);
SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date = null;
Collections.sort(allloans,new LoanComparatorByStatusActive());
for (LoanAccountData loan : allloans) {
row = loanRepaymentSheet.createRow(rowIndex++);
writeString(LoanRepaymentConstants.LOOKUP_CLIENT_NAME_COL, row, loan.getClientName() + "(" + loan.getClientId() + ")");
writeString(LoanRepaymentConstants.LOOKUP_CLIENT_EXTERNAL_ID,row, clientIdToClientExternalId.get(loan.getClientId()));
writeString(LoanRepaymentConstants.LOOKUP_ACCOUNT_NO_COL, row, loan.getAccountNo()+"-"+loan.getStatusStringValue());
writeString(LoanRepaymentConstants.LOOKUP_PRODUCT_COL, row, loan.getLoanProductName());
writeDouble(LoanRepaymentConstants.LOOKUP_PRINCIPAL_COL, row, loan.getPrincipal().doubleValue());
if (loan.getTotalOutstandingAmount() != null)
writeBigDecimal(LoanRepaymentConstants.LOOKUP_TOTAL_OUTSTANDING_AMOUNT_COL, row, loan.getTotalOutstandingAmount());
if (loan.getDisbursementDate() != null) {
try {
date = inputFormat.parse(loan.getDisbursementDate().toString());
} catch (ParseException e) {
e.printStackTrace();
}
writeDate(LoanRepaymentConstants.LOOKUP_LOAN_DISBURSEMENT_DATE_COL, row,
outputFormat.format(date), dateCellStyle,dateFormat);
}
}
}
private void populateLoansTable(Sheet loanRepaymentSheet,String dateFormat) {
int rowIndex = 1;
Row row;
Workbook workbook = loanRepaymentSheet.getWorkbook();
CellStyle dateCellStyle = workbook.createCellStyle();
short df = workbook.createDataFormat().getFormat(dateFormat);
dateCellStyle.setDataFormat(df);
SimpleDateFormat outputFormat = new SimpleDateFormat(dateFormat);
SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date = null;
Collections.sort(allloans,new LoanComparatorByStatusActive());
for (LoanAccountData loan : allloans) {
row = loanRepaymentSheet.createRow(rowIndex++);
writeString(LoanRepaymentConstants.LOOKUP_CLIENT_NAME_COL, row, loan.getClientName() + "(" + loan.getClientId() + ")");
writeString(LoanRepaymentConstants.LOOKUP_CLIENT_EXTERNAL_ID,row, clientIdToClientExternalId.get(loan.getClientId()));
writeString(LoanRepaymentConstants.LOOKUP_ACCOUNT_NO_COL, row, loan.getAccountNo()+"-"+loan.getStatusStringValue());
writeString(LoanRepaymentConstants.LOOKUP_PRODUCT_COL, row, loan.getLoanProductName());
writeDouble(LoanRepaymentConstants.LOOKUP_PRINCIPAL_COL, row, loan.getPrincipal().doubleValue());
if (loan.getTotalOutstandingAmount() != null)
writeBigDecimal(LoanRepaymentConstants.LOOKUP_TOTAL_OUTSTANDING_AMOUNT_COL, row, loan.getTotalOutstandingAmount());
if (loan.getDisbursementDate() != null) {
try {
date = inputFormat.parse(loan.getDisbursementDate().toString());
} catch (ParseException e) {
e.printStackTrace();
}
writeDate(LoanRepaymentConstants.LOOKUP_LOAN_DISBURSEMENT_DATE_COL, row,
outputFormat.format(date), dateCellStyle,dateFormat);
}
}
}
private void setLayout(Sheet worksheet) {
Row rowHeader = worksheet.createRow(TemplatePopulateImportConstants.ROWHEADER_INDEX);
rowHeader.setHeight(TemplatePopulateImportConstants.ROW_HEADER_HEIGHT);
worksheet.setColumnWidth(LoanRepaymentConstants.OFFICE_NAME_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(LoanRepaymentConstants.CLIENT_NAME_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE);
worksheet.setColumnWidth(LoanRepaymentConstants.CLIENT_EXTERNAL_ID,TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(LoanRepaymentConstants.LOAN_ACCOUNT_NO_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(LoanRepaymentConstants.PRODUCT_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(LoanRepaymentConstants.PRINCIPAL_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(LoanRepaymentConstants.TOTAL_OUTSTANDING_AMOUNT_COL,TemplatePopulateImportConstants.MEDIUM_COL_SIZE);
worksheet.setColumnWidth(LoanRepaymentConstants.LOAN_DISBURSEMENT_DATE_COL,TemplatePopulateImportConstants.MEDIUM_COL_SIZE);
worksheet.setColumnWidth(LoanRepaymentConstants.AMOUNT_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(LoanRepaymentConstants.REPAID_ON_DATE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(LoanRepaymentConstants.REPAYMENT_TYPE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(LoanRepaymentConstants.ACCOUNT_NO_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(LoanRepaymentConstants.CHECK_NO_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(LoanRepaymentConstants.RECEIPT_NO_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(LoanRepaymentConstants.ROUTING_CODE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(LoanRepaymentConstants.BANK_NO_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(LoanRepaymentConstants.LOOKUP_CLIENT_NAME_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE);
worksheet.setColumnWidth(LoanRepaymentConstants.LOOKUP_CLIENT_EXTERNAL_ID,TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(LoanRepaymentConstants.LOOKUP_ACCOUNT_NO_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(LoanRepaymentConstants.LOOKUP_PRODUCT_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(LoanRepaymentConstants.LOOKUP_PRINCIPAL_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(LoanRepaymentConstants.LOOKUP_TOTAL_OUTSTANDING_AMOUNT_COL,TemplatePopulateImportConstants.LARGE_COL_SIZE);
worksheet.setColumnWidth(LoanRepaymentConstants.LOOKUP_LOAN_DISBURSEMENT_DATE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
writeString(LoanRepaymentConstants.OFFICE_NAME_COL, rowHeader, "Office Name*");
writeString(LoanRepaymentConstants.CLIENT_NAME_COL, rowHeader, "Client Name*");
writeString(LoanRepaymentConstants.CLIENT_EXTERNAL_ID,rowHeader,"Client Ext.Id");
writeString(LoanRepaymentConstants.LOAN_ACCOUNT_NO_COL, rowHeader, "Loan Account No.*");
writeString(LoanRepaymentConstants.PRODUCT_COL, rowHeader, "Product Name");
writeString(LoanRepaymentConstants.PRINCIPAL_COL, rowHeader, "Principal");
writeString(LoanRepaymentConstants.TOTAL_OUTSTANDING_AMOUNT_COL,rowHeader,"Total Outstanding Amount");
writeString(LoanRepaymentConstants.LOAN_DISBURSEMENT_DATE_COL,rowHeader,"Loan Disbursement Date");
writeString(LoanRepaymentConstants.AMOUNT_COL, rowHeader, "Amount Repaid*");
writeString(LoanRepaymentConstants.REPAID_ON_DATE_COL, rowHeader, "Date*");
writeString(LoanRepaymentConstants.REPAYMENT_TYPE_COL, rowHeader, "Type*");
writeString(LoanRepaymentConstants.ACCOUNT_NO_COL, rowHeader, "Account No");
writeString(LoanRepaymentConstants.CHECK_NO_COL, rowHeader, "Check No");
writeString(LoanRepaymentConstants.RECEIPT_NO_COL, rowHeader, "Receipt No");
writeString(LoanRepaymentConstants.ROUTING_CODE_COL, rowHeader, "Routing Code");
writeString(LoanRepaymentConstants.BANK_NO_COL, rowHeader, "Bank No");
writeString(LoanRepaymentConstants.LOOKUP_CLIENT_NAME_COL, rowHeader, "Lookup Client");
writeString(LoanRepaymentConstants.LOOKUP_CLIENT_EXTERNAL_ID,rowHeader,"Lookup ClientExtId");
writeString(LoanRepaymentConstants.LOOKUP_ACCOUNT_NO_COL, rowHeader, "Lookup Account");
writeString(LoanRepaymentConstants.LOOKUP_PRODUCT_COL, rowHeader, "Lookup Product");
writeString(LoanRepaymentConstants.LOOKUP_PRINCIPAL_COL, rowHeader, "Lookup Principal");
writeString(LoanRepaymentConstants.LOOKUP_TOTAL_OUTSTANDING_AMOUNT_COL,rowHeader,"Lookup Total Outstanding amount");
writeString(LoanRepaymentConstants.LOOKUP_LOAN_DISBURSEMENT_DATE_COL, rowHeader, "Lookup Loan Disbursement Date");
private void setLayout(Sheet worksheet) {
Row rowHeader = worksheet.createRow(TemplatePopulateImportConstants.ROWHEADER_INDEX);
rowHeader.setHeight(TemplatePopulateImportConstants.ROW_HEADER_HEIGHT);
worksheet.setColumnWidth(LoanRepaymentConstants.OFFICE_NAME_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(LoanRepaymentConstants.CLIENT_NAME_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE);
worksheet.setColumnWidth(LoanRepaymentConstants.CLIENT_EXTERNAL_ID,TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(LoanRepaymentConstants.LOAN_ACCOUNT_NO_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(LoanRepaymentConstants.PRODUCT_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(LoanRepaymentConstants.PRINCIPAL_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(LoanRepaymentConstants.TOTAL_OUTSTANDING_AMOUNT_COL,TemplatePopulateImportConstants.MEDIUM_COL_SIZE);
worksheet.setColumnWidth(LoanRepaymentConstants.LOAN_DISBURSEMENT_DATE_COL,TemplatePopulateImportConstants.MEDIUM_COL_SIZE);
worksheet.setColumnWidth(LoanRepaymentConstants.AMOUNT_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(LoanRepaymentConstants.REPAID_ON_DATE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(LoanRepaymentConstants.REPAYMENT_TYPE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(LoanRepaymentConstants.ACCOUNT_NO_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(LoanRepaymentConstants.CHECK_NO_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(LoanRepaymentConstants.RECEIPT_NO_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(LoanRepaymentConstants.ROUTING_CODE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(LoanRepaymentConstants.BANK_NO_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(LoanRepaymentConstants.LOOKUP_CLIENT_NAME_COL, TemplatePopulateImportConstants.MEDIUM_COL_SIZE);
worksheet.setColumnWidth(LoanRepaymentConstants.LOOKUP_CLIENT_EXTERNAL_ID,TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(LoanRepaymentConstants.LOOKUP_ACCOUNT_NO_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(LoanRepaymentConstants.LOOKUP_PRODUCT_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(LoanRepaymentConstants.LOOKUP_PRINCIPAL_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
worksheet.setColumnWidth(LoanRepaymentConstants.LOOKUP_TOTAL_OUTSTANDING_AMOUNT_COL,TemplatePopulateImportConstants.LARGE_COL_SIZE);
worksheet.setColumnWidth(LoanRepaymentConstants.LOOKUP_LOAN_DISBURSEMENT_DATE_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);
writeString(LoanRepaymentConstants.OFFICE_NAME_COL, rowHeader, "Office Name*");
writeString(LoanRepaymentConstants.CLIENT_NAME_COL, rowHeader, "Client Name*");
writeString(LoanRepaymentConstants.CLIENT_EXTERNAL_ID,rowHeader,"Client Ext.Id");
writeString(LoanRepaymentConstants.LOAN_ACCOUNT_NO_COL, rowHeader, "Loan Account No.*");
writeString(LoanRepaymentConstants.PRODUCT_COL, rowHeader, "Product Name");
writeString(LoanRepaymentConstants.PRINCIPAL_COL, rowHeader, "Principal");
writeString(LoanRepaymentConstants.TOTAL_OUTSTANDING_AMOUNT_COL,rowHeader,"Total Outstanding Amount");
writeString(LoanRepaymentConstants.LOAN_DISBURSEMENT_DATE_COL,rowHeader,"Loan Disbursement Date");
writeString(LoanRepaymentConstants.AMOUNT_COL, rowHeader, "Amount Repaid*");
writeString(LoanRepaymentConstants.REPAID_ON_DATE_COL, rowHeader, "Date*");
writeString(LoanRepaymentConstants.REPAYMENT_TYPE_COL, rowHeader, "Type*");
writeString(LoanRepaymentConstants.ACCOUNT_NO_COL, rowHeader, "Account No");
writeString(LoanRepaymentConstants.CHECK_NO_COL, rowHeader, "Check No");
writeString(LoanRepaymentConstants.RECEIPT_NO_COL, rowHeader, "Receipt No");
writeString(LoanRepaymentConstants.ROUTING_CODE_COL, rowHeader, "Routing Code");
writeString(LoanRepaymentConstants.BANK_NO_COL, rowHeader, "Bank No");
writeString(LoanRepaymentConstants.LOOKUP_CLIENT_NAME_COL, rowHeader, "Lookup Client");
writeString(LoanRepaymentConstants.LOOKUP_CLIENT_EXTERNAL_ID,rowHeader,"Lookup ClientExtId");
writeString(LoanRepaymentConstants.LOOKUP_ACCOUNT_NO_COL, rowHeader, "Lookup Account");
writeString(LoanRepaymentConstants.LOOKUP_PRODUCT_COL, rowHeader, "Lookup Product");
writeString(LoanRepaymentConstants.LOOKUP_PRINCIPAL_COL, rowHeader, "Lookup Principal");
writeString(LoanRepaymentConstants.LOOKUP_TOTAL_OUTSTANDING_AMOUNT_COL,rowHeader,"Lookup Total Outstanding amount");
writeString(LoanRepaymentConstants.LOOKUP_LOAN_DISBURSEMENT_DATE_COL, rowHeader, "Lookup Loan Disbursement Date");
}
}
}
@@ -131,12 +131,12 @@ public class BulkImportWorkbookPopulatorServiceImpl implements BulkImportWorkboo
final LoanReadPlatformService loanReadPlatformService,
final GLAccountReadPlatformService glAccountReadPlatformService,
final SavingsAccountReadPlatformService savingsAccountReadPlatformService,
final CodeValueReadPlatformService codeValueReadPlatformService,
final SavingsProductReadPlatformService savingsProductReadPlatformService,
final ProductReadPlatformService productReadPlatformService,
final ChargeReadPlatformService chargeReadPlatformService,
final DepositProductReadPlatformService depositProductReadPlatformService,
final RoleReadPlatformService roleReadPlatformService) {
final CodeValueReadPlatformService codeValueReadPlatformService,
final SavingsProductReadPlatformService savingsProductReadPlatformService,
final ProductReadPlatformService productReadPlatformService,
final ChargeReadPlatformService chargeReadPlatformService,
final DepositProductReadPlatformService depositProductReadPlatformService,
final RoleReadPlatformService roleReadPlatformService) {
this.officeReadPlatformService = officeReadPlatformService;
this.staffReadPlatformService = staffReadPlatformService;
this.context = context;
@@ -158,84 +158,84 @@ public class BulkImportWorkbookPopulatorServiceImpl implements BulkImportWorkboo
this.roleReadPlatformService=roleReadPlatformService;
}
@Override
public Response getTemplate(String entityType, Long officeId, Long staffId,final String dateFormat) {
WorkbookPopulator populator=null;
final Workbook workbook=new HSSFWorkbook();
if(entityType!=null){
if (entityType.trim().equalsIgnoreCase(GlobalEntityType.CLIENTS_PERSON.toString())||
entityType.trim().equalsIgnoreCase(GlobalEntityType.CLIENTS_ENTTTY.toString())) {
populator = populateClientWorkbook(entityType,officeId, staffId);
}else if (entityType.trim().equalsIgnoreCase(GlobalEntityType.CENTERS.toString())) {
populator=populateCenterWorkbook(officeId,staffId);
}else if (entityType.trim().equalsIgnoreCase(GlobalEntityType.GROUPS.toString())) {
populator = populateGroupsWorkbook(officeId, staffId);
}else if (entityType.trim().equalsIgnoreCase(GlobalEntityType.LOANS.toString())) {
populator = populateLoanWorkbook(officeId, staffId);
}else if (entityType.trim().equalsIgnoreCase(GlobalEntityType.LOAN_TRANSACTIONS.toString())) {
populator = populateLoanRepaymentWorkbook(officeId);
}else if (entityType.trim().equalsIgnoreCase(GlobalEntityType.GL_JOURNAL_ENTRIES.toString())) {
populator = populateJournalEntriesWorkbook(officeId);
}else if (entityType.trim().equalsIgnoreCase(GlobalEntityType.GUARANTORS.toString())) {
populator = populateGuarantorWorkbook(officeId);
}else if (entityType.trim().equalsIgnoreCase(GlobalEntityType.OFFICES.toString())) {
populator=populateOfficeWorkbook();
}else if (entityType.trim().equalsIgnoreCase(GlobalEntityType.CHART_OF_ACCOUNTS.toString())) {
populator=populateChartOfAccountsWorkbook();
}else if (entityType.trim().equalsIgnoreCase(GlobalEntityType.STAFF.toString())) {
populator=populateStaffWorkbook(officeId);
}else if (entityType.trim().equalsIgnoreCase(GlobalEntityType.SHARE_ACCOUNTS.toString())) {
populator=populateSharedAcountsWorkbook(officeId);
}else if (entityType.trim().equalsIgnoreCase(GlobalEntityType.SAVINGS_ACCOUNT.toString())) {
populator=populateSavingsAccountWorkbook(officeId,staffId);
}else if (entityType.trim().equalsIgnoreCase(GlobalEntityType.SAVINGS_TRANSACTIONS.toString())) {
populator=populateSavingsTransactionWorkbook(officeId);
}else if (entityType.trim().equalsIgnoreCase(GlobalEntityType.RECURRING_DEPOSIT_ACCOUNTS.toString())) {
populator=populateRecurringDepositWorkbook(officeId,staffId);
}else if (entityType.trim().equalsIgnoreCase(GlobalEntityType.RECURRING_DEPOSIT_ACCOUNTS_TRANSACTIONS.toString())) {
populator=populateRecurringDepositTransactionWorkbook(officeId);
}else if (entityType.trim().equalsIgnoreCase(GlobalEntityType.FIXED_DEPOSIT_ACCOUNTS.toString())) {
populator = populateFixedDepositWorkbook(officeId, staffId);
}else if (entityType.trim().equalsIgnoreCase(GlobalEntityType.FIXED_DEPOSIT_TRANSACTIONS.toString())){
populator=populateFixedDepositTransactionsWorkbook(officeId);
}else if (entityType.trim().equalsIgnoreCase(GlobalEntityType.USERS.toString())){
populator=populateUserWorkbook(officeId,staffId);
}else {
throw new GeneralPlatformDomainRuleException("error.msg.unable.to.find.resource",
"Unable to find requested resource");
}
populator.populate(workbook,dateFormat);
return buildResponse(workbook, entityType);
}else {
throw new GeneralPlatformDomainRuleException("error.msg.given.entity.type.null",
"Given Entity type is null");
}
}
@Override
public Response getTemplate(String entityType, Long officeId, Long staffId,final String dateFormat) {
WorkbookPopulator populator=null;
final Workbook workbook=new HSSFWorkbook();
if(entityType!=null){
if (entityType.trim().equalsIgnoreCase(GlobalEntityType.CLIENTS_PERSON.toString())||
entityType.trim().equalsIgnoreCase(GlobalEntityType.CLIENTS_ENTTTY.toString())) {
populator = populateClientWorkbook(entityType,officeId, staffId);
}else if (entityType.trim().equalsIgnoreCase(GlobalEntityType.CENTERS.toString())) {
populator=populateCenterWorkbook(officeId,staffId);
}else if (entityType.trim().equalsIgnoreCase(GlobalEntityType.GROUPS.toString())) {
populator = populateGroupsWorkbook(officeId, staffId);
}else if (entityType.trim().equalsIgnoreCase(GlobalEntityType.LOANS.toString())) {
populator = populateLoanWorkbook(officeId, staffId);
}else if (entityType.trim().equalsIgnoreCase(GlobalEntityType.LOAN_TRANSACTIONS.toString())) {
populator = populateLoanRepaymentWorkbook(officeId);
}else if (entityType.trim().equalsIgnoreCase(GlobalEntityType.GL_JOURNAL_ENTRIES.toString())) {
populator = populateJournalEntriesWorkbook(officeId);
}else if (entityType.trim().equalsIgnoreCase(GlobalEntityType.GUARANTORS.toString())) {
populator = populateGuarantorWorkbook(officeId);
}else if (entityType.trim().equalsIgnoreCase(GlobalEntityType.OFFICES.toString())) {
populator=populateOfficeWorkbook();
}else if (entityType.trim().equalsIgnoreCase(GlobalEntityType.CHART_OF_ACCOUNTS.toString())) {
populator=populateChartOfAccountsWorkbook();
}else if (entityType.trim().equalsIgnoreCase(GlobalEntityType.STAFF.toString())) {
populator=populateStaffWorkbook(officeId);
}else if (entityType.trim().equalsIgnoreCase(GlobalEntityType.SHARE_ACCOUNTS.toString())) {
populator=populateSharedAcountsWorkbook(officeId);
}else if (entityType.trim().equalsIgnoreCase(GlobalEntityType.SAVINGS_ACCOUNT.toString())) {
populator=populateSavingsAccountWorkbook(officeId,staffId);
}else if (entityType.trim().equalsIgnoreCase(GlobalEntityType.SAVINGS_TRANSACTIONS.toString())) {
populator=populateSavingsTransactionWorkbook(officeId);
}else if (entityType.trim().equalsIgnoreCase(GlobalEntityType.RECURRING_DEPOSIT_ACCOUNTS.toString())) {
populator=populateRecurringDepositWorkbook(officeId,staffId);
}else if (entityType.trim().equalsIgnoreCase(GlobalEntityType.RECURRING_DEPOSIT_ACCOUNTS_TRANSACTIONS.toString())) {
populator=populateRecurringDepositTransactionWorkbook(officeId);
}else if (entityType.trim().equalsIgnoreCase(GlobalEntityType.FIXED_DEPOSIT_ACCOUNTS.toString())) {
populator = populateFixedDepositWorkbook(officeId, staffId);
}else if (entityType.trim().equalsIgnoreCase(GlobalEntityType.FIXED_DEPOSIT_TRANSACTIONS.toString())){
populator=populateFixedDepositTransactionsWorkbook(officeId);
}else if (entityType.trim().equalsIgnoreCase(GlobalEntityType.USERS.toString())){
populator=populateUserWorkbook(officeId,staffId);
}else {
throw new GeneralPlatformDomainRuleException("error.msg.unable.to.find.resource",
"Unable to find requested resource");
}
populator.populate(workbook,dateFormat);
return buildResponse(workbook, entityType);
}else {
throw new GeneralPlatformDomainRuleException("error.msg.given.entity.type.null",
"Given Entity type is null");
}
}
private WorkbookPopulator populateClientWorkbook(final String entityType ,final Long officeId, final Long staffId) {
private WorkbookPopulator populateClientWorkbook(final String entityType ,final Long officeId, final Long staffId) {
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.OFFICE_ENTITY_TYPE);
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.STAFF_ENTITY_TYPE);
List<OfficeData> offices = fetchOffices(officeId);
List<StaffData> staff = fetchStaff(staffId);
List<CodeValueData> clientTypeCodeValues =fetchCodeValuesByCodeName("ClientType");
List<CodeValueData> clientClassification=fetchCodeValuesByCodeName("ClientClassification");
List<CodeValueData> addressTypesCodeValues=fetchCodeValuesByCodeName("ADDRESS_TYPE");
List<CodeValueData> stateProvinceCodeValues=fetchCodeValuesByCodeName("STATE");
List<CodeValueData> countryCodeValues=fetchCodeValuesByCodeName("COUNTRY");
if(entityType.trim().equalsIgnoreCase(GlobalEntityType.CLIENTS_PERSON.toString())) {
List<CodeValueData> genderCodeValues = fetchCodeValuesByCodeName("Gender");
return new ClientPersonWorkbookPopulator(new OfficeSheetPopulator(offices),
new PersonnelSheetPopulator(staff, offices), clientTypeCodeValues, genderCodeValues, clientClassification
, addressTypesCodeValues, stateProvinceCodeValues, countryCodeValues);
}else if(entityType.trim().equalsIgnoreCase(GlobalEntityType.CLIENTS_ENTTTY.toString())){
List<CodeValueData> constitutionCodeValues=fetchCodeValuesByCodeName("Constitution");
List<CodeValueData> mainBusinessline=fetchCodeValuesByCodeName("Main Business Line");
return new ClientEntityWorkbookPopulator(new OfficeSheetPopulator(offices),
new PersonnelSheetPopulator(staff, offices), clientTypeCodeValues, constitutionCodeValues,mainBusinessline,
clientClassification, addressTypesCodeValues, stateProvinceCodeValues, countryCodeValues);
}
return null;
List<CodeValueData> clientClassification=fetchCodeValuesByCodeName("ClientClassification");
List<CodeValueData> addressTypesCodeValues=fetchCodeValuesByCodeName("ADDRESS_TYPE");
List<CodeValueData> stateProvinceCodeValues=fetchCodeValuesByCodeName("STATE");
List<CodeValueData> countryCodeValues=fetchCodeValuesByCodeName("COUNTRY");
if(entityType.trim().equalsIgnoreCase(GlobalEntityType.CLIENTS_PERSON.toString())) {
List<CodeValueData> genderCodeValues = fetchCodeValuesByCodeName("Gender");
return new ClientPersonWorkbookPopulator(new OfficeSheetPopulator(offices),
new PersonnelSheetPopulator(staff, offices), clientTypeCodeValues, genderCodeValues, clientClassification
, addressTypesCodeValues, stateProvinceCodeValues, countryCodeValues);
}else if(entityType.trim().equalsIgnoreCase(GlobalEntityType.CLIENTS_ENTTTY.toString())){
List<CodeValueData> constitutionCodeValues=fetchCodeValuesByCodeName("Constitution");
List<CodeValueData> mainBusinessline=fetchCodeValuesByCodeName("Main Business Line");
return new ClientEntityWorkbookPopulator(new OfficeSheetPopulator(offices),
new PersonnelSheetPopulator(staff, offices), clientTypeCodeValues, constitutionCodeValues,mainBusinessline,
clientClassification, addressTypesCodeValues, stateProvinceCodeValues, countryCodeValues);
}
return null;
}
private Response buildResponse(final Workbook workbook, final String entity) {
@@ -279,395 +279,395 @@ public class BulkImportWorkbookPopulatorServiceImpl implements BulkImportWorkboo
return staff;
}
private List<CodeValueData> fetchCodeValuesByCodeName(String codeName){
List<CodeValueData> codeValues=null;
if (codeName!=null){
codeValues=(List)codeValueReadPlatformService.retrieveCodeValuesByCode(codeName);
}else {
throw new NullPointerException();
}
return codeValues;
List<CodeValueData> codeValues=null;
if (codeName!=null){
codeValues=(List)codeValueReadPlatformService.retrieveCodeValuesByCode(codeName);
}else {
throw new NullPointerException();
}
return codeValues;
}
private List<SavingsProductData>fetchSavingsProducts(){
List<SavingsProductData> savingsProducts=(List)savingsProductReadPlatformService.retrieveAll();
return savingsProducts;
List<SavingsProductData> savingsProducts=(List)savingsProductReadPlatformService.retrieveAll();
return savingsProducts;
}
private WorkbookPopulator populateCenterWorkbook(Long officeId,Long staffId){
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.OFFICE_ENTITY_TYPE);
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.STAFF_ENTITY_TYPE);
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.GROUP_ENTITY_TYPE);
List<OfficeData> offices = fetchOffices(officeId);
List<StaffData> staff = fetchStaff(staffId);
List<GroupGeneralData> groups = fetchGroups(officeId);
return new CentersWorkbookPopulator(new OfficeSheetPopulator(offices),
new PersonnelSheetPopulator(staff, offices),new GroupSheetPopulator(groups,offices));
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.OFFICE_ENTITY_TYPE);
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.STAFF_ENTITY_TYPE);
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.GROUP_ENTITY_TYPE);
List<OfficeData> offices = fetchOffices(officeId);
List<StaffData> staff = fetchStaff(staffId);
List<GroupGeneralData> groups = fetchGroups(officeId);
return new CentersWorkbookPopulator(new OfficeSheetPopulator(offices),
new PersonnelSheetPopulator(staff, offices),new GroupSheetPopulator(groups,offices));
}
private WorkbookPopulator populateGroupsWorkbook(Long officeId, Long staffId) {
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.OFFICE_ENTITY_TYPE);
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.STAFF_ENTITY_TYPE);
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.CENTER_ENTITY_TYPE);
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.CLIENT_ENTITY_TYPE);
List<OfficeData> offices = fetchOffices(officeId);
List<StaffData> staff = fetchStaff(staffId);
List<CenterData> centers = fetchCenters(officeId);
List<ClientData> clients = fetchClients(officeId);
return new GroupsWorkbookPopulator(new OfficeSheetPopulator(offices),
new PersonnelSheetPopulator(staff, offices), new CenterSheetPopulator(centers, offices),
new ClientSheetPopulator(clients, offices));
}
private List<CenterData> fetchCenters(Long officeId) {
List<CenterData>centers=null;
if (officeId==null) {
centers=(List<CenterData>) this.centerReadPlatformService.retrieveAll(null, null);
} else {
SearchParameters searchParameters = SearchParameters.from(null, officeId, null, null, null);
centers = (List<CenterData>)centerReadPlatformService.retrieveAll(searchParameters,null);
}
return centers;
}
private List<ClientData> fetchClients(Long officeId) {
List<ClientData> clients=null;
if (officeId==null) {
Page<ClientData> clientDataPage =this.clientReadPlatformService.retrieveAll(null);
if (clientDataPage!=null){
clients=new ArrayList<>();
for (ClientData client: clientDataPage.getPageItems()) {
clients.add(client);
}
}
} else {
SearchParameters searchParameters = SearchParameters.from(null, officeId, null, null, null);
Page<ClientData> clientDataPage =this.clientReadPlatformService.retrieveAll(searchParameters);
if (clientDataPage!=null){
clients=new ArrayList<>();
for (ClientData client: clientDataPage.getPageItems()) {
clients.add(client);
}
}
}
return clients;
}
private WorkbookPopulator populateGroupsWorkbook(Long officeId, Long staffId) {
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.OFFICE_ENTITY_TYPE);
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.STAFF_ENTITY_TYPE);
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.CENTER_ENTITY_TYPE);
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.CLIENT_ENTITY_TYPE);
List<OfficeData> offices = fetchOffices(officeId);
List<StaffData> staff = fetchStaff(staffId);
List<CenterData> centers = fetchCenters(officeId);
List<ClientData> clients = fetchClients(officeId);
return new GroupsWorkbookPopulator(new OfficeSheetPopulator(offices),
new PersonnelSheetPopulator(staff, offices), new CenterSheetPopulator(centers, offices),
new ClientSheetPopulator(clients, offices));
}
private List<CenterData> fetchCenters(Long officeId) {
List<CenterData>centers=null;
if (officeId==null) {
centers=(List<CenterData>) this.centerReadPlatformService.retrieveAll(null, null);
} else {
SearchParameters searchParameters = SearchParameters.from(null, officeId, null, null, null);
centers = (List<CenterData>)centerReadPlatformService.retrieveAll(searchParameters,null);
}
return centers;
}
private List<ClientData> fetchClients(Long officeId) {
List<ClientData> clients=null;
if (officeId==null) {
Page<ClientData> clientDataPage =this.clientReadPlatformService.retrieveAll(null);
if (clientDataPage!=null){
clients=new ArrayList<>();
for (ClientData client: clientDataPage.getPageItems()) {
clients.add(client);
}
}
} else {
SearchParameters searchParameters = SearchParameters.from(null, officeId, null, null, null);
Page<ClientData> clientDataPage =this.clientReadPlatformService.retrieveAll(searchParameters);
if (clientDataPage!=null){
clients=new ArrayList<>();
for (ClientData client: clientDataPage.getPageItems()) {
clients.add(client);
}
}
}
return clients;
}
private WorkbookPopulator populateLoanWorkbook(Long officeId, Long staffId) {
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.OFFICE_ENTITY_TYPE);
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.STAFF_ENTITY_TYPE);
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.GROUP_ENTITY_TYPE);
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.CLIENT_ENTITY_TYPE);
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.LOAN_PRODUCT_ENTITY_TYPE);
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.FUNDS_ENTITY_TYPE);
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.PAYMENT_TYPE_ENTITY_TYPE);
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.CURRENCY_ENTITY_TYPE);
List<OfficeData> offices = fetchOffices(officeId);
List<StaffData> staff = fetchStaff(staffId);
List<ClientData> clients = fetchClients(officeId);
List<GroupGeneralData> groups = fetchGroups(officeId);
List<LoanProductData> loanproducts = fetchLoanProducts();
List<FundData> funds = fetchFunds();
List<PaymentTypeData> paymentTypes = fetchPaymentTypes();
List<CurrencyData> currencies = fetchCurrencies();
return new LoanWorkbookPopulator(new OfficeSheetPopulator(offices), new ClientSheetPopulator(clients, offices),
new GroupSheetPopulator(groups, offices), new PersonnelSheetPopulator(staff, offices),
new LoanProductSheetPopulator(loanproducts), new ExtrasSheetPopulator(funds, paymentTypes, currencies));
}
private WorkbookPopulator populateLoanWorkbook(Long officeId, Long staffId) {
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.OFFICE_ENTITY_TYPE);
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.STAFF_ENTITY_TYPE);
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.GROUP_ENTITY_TYPE);
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.CLIENT_ENTITY_TYPE);
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.LOAN_PRODUCT_ENTITY_TYPE);
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.FUNDS_ENTITY_TYPE);
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.PAYMENT_TYPE_ENTITY_TYPE);
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.CURRENCY_ENTITY_TYPE);
List<OfficeData> offices = fetchOffices(officeId);
List<StaffData> staff = fetchStaff(staffId);
List<ClientData> clients = fetchClients(officeId);
List<GroupGeneralData> groups = fetchGroups(officeId);
List<LoanProductData> loanproducts = fetchLoanProducts();
List<FundData> funds = fetchFunds();
List<PaymentTypeData> paymentTypes = fetchPaymentTypes();
List<CurrencyData> currencies = fetchCurrencies();
return new LoanWorkbookPopulator(new OfficeSheetPopulator(offices), new ClientSheetPopulator(clients, offices),
new GroupSheetPopulator(groups, offices), new PersonnelSheetPopulator(staff, offices),
new LoanProductSheetPopulator(loanproducts), new ExtrasSheetPopulator(funds, paymentTypes, currencies));
}
private List<CurrencyData> fetchCurrencies() {
List<CurrencyData> currencies =(List<CurrencyData>) this.currencyReadPlatformService.
retrieveAllPlatformCurrencies();
return currencies;
}
private List<CurrencyData> fetchCurrencies() {
List<CurrencyData> currencies =(List<CurrencyData>) this.currencyReadPlatformService.
retrieveAllPlatformCurrencies();
return currencies;
}
private List<PaymentTypeData> fetchPaymentTypes() {
List<PaymentTypeData> paymentTypeData =(List<PaymentTypeData>) this.paymentTypeReadPlatformService
.retrieveAllPaymentTypes();
return paymentTypeData;
}
private List<PaymentTypeData> fetchPaymentTypes() {
List<PaymentTypeData> paymentTypeData =(List<PaymentTypeData>) this.paymentTypeReadPlatformService
.retrieveAllPaymentTypes();
return paymentTypeData;
}
private List<FundData> fetchFunds() {
List<FundData> funds =(List<FundData>) this.fundReadPlatformService.retrieveAllFunds();
return funds;
}
private List<FundData> fetchFunds() {
List<FundData> funds =(List<FundData>) this.fundReadPlatformService.retrieveAllFunds();
return funds;
}
private List<LoanProductData> fetchLoanProducts() {
List<LoanProductData>loanproducts =(List<LoanProductData>) this.loanProductReadPlatformService
.retrieveAllLoanProducts();
return loanproducts;
}
private List<LoanProductData> fetchLoanProducts() {
List<LoanProductData>loanproducts =(List<LoanProductData>) this.loanProductReadPlatformService
.retrieveAllLoanProducts();
return loanproducts;
}
private List<GroupGeneralData> fetchGroups(Long officeId) {
List<GroupGeneralData> groups = null;
if (officeId == null) {
groups = (List<GroupGeneralData>) this.groupReadPlatformService.retrieveAll(null, null);
} else {
SearchParameters searchParameters = SearchParameters.from(null, officeId, null, null, null);
groups = (List<GroupGeneralData>)groupReadPlatformService.retrieveAll(searchParameters,null);
}
private List<GroupGeneralData> fetchGroups(Long officeId) {
List<GroupGeneralData> groups = null;
if (officeId == null) {
groups = (List<GroupGeneralData>) this.groupReadPlatformService.retrieveAll(null, null);
} else {
SearchParameters searchParameters = SearchParameters.from(null, officeId, null, null, null);
groups = (List<GroupGeneralData>)groupReadPlatformService.retrieveAll(searchParameters,null);
}
return groups;
}
return groups;
}
private WorkbookPopulator populateLoanRepaymentWorkbook(Long officeId) {
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.OFFICE_ENTITY_TYPE);
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.CLIENT_ENTITY_TYPE);
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.FUNDS_ENTITY_TYPE);
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.PAYMENT_TYPE_ENTITY_TYPE);
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.CURRENCY_ENTITY_TYPE);
List<OfficeData> offices = fetchOffices(officeId);
List<ClientData> clients = fetchClients(officeId);
List<FundData> funds = fetchFunds();
List<PaymentTypeData> paymentTypes = fetchPaymentTypes();
List<CurrencyData> currencies = fetchCurrencies();
List<LoanAccountData> loans = fetchLoanAccounts(officeId);
return new LoanRepaymentWorkbookPopulator(loans, new OfficeSheetPopulator(offices),
new ClientSheetPopulator(clients, offices), new ExtrasSheetPopulator(funds, paymentTypes, currencies));
}
private WorkbookPopulator populateLoanRepaymentWorkbook(Long officeId) {
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.OFFICE_ENTITY_TYPE);
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.CLIENT_ENTITY_TYPE);
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.FUNDS_ENTITY_TYPE);
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.PAYMENT_TYPE_ENTITY_TYPE);
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.CURRENCY_ENTITY_TYPE);
List<OfficeData> offices = fetchOffices(officeId);
List<ClientData> clients = fetchClients(officeId);
List<FundData> funds = fetchFunds();
List<PaymentTypeData> paymentTypes = fetchPaymentTypes();
List<CurrencyData> currencies = fetchCurrencies();
List<LoanAccountData> loans = fetchLoanAccounts(officeId);
return new LoanRepaymentWorkbookPopulator(loans, new OfficeSheetPopulator(offices),
new ClientSheetPopulator(clients, offices), new ExtrasSheetPopulator(funds, paymentTypes, currencies));
}
private List<LoanAccountData> fetchLoanAccounts(final Long officeId) {
List<LoanAccountData> loanAccounts = null;
if(officeId==null){
loanAccounts= loanReadPlatformService.retrieveAll(null).getPageItems();
}else {
SearchParameters searchParameters = SearchParameters.from(null, officeId, null, null, null);
loanAccounts = loanReadPlatformService.retrieveAll(searchParameters).getPageItems();
}
return loanAccounts;
}
private List<LoanAccountData> fetchLoanAccounts(final Long officeId) {
List<LoanAccountData> loanAccounts = null;
if(officeId==null){
loanAccounts= loanReadPlatformService.retrieveAll(null).getPageItems();
}else {
SearchParameters searchParameters = SearchParameters.from(null, officeId, null, null, null);
loanAccounts = loanReadPlatformService.retrieveAll(searchParameters).getPageItems();
}
return loanAccounts;
}
private WorkbookPopulator populateJournalEntriesWorkbook(Long officeId) {
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.OFFICE_ENTITY_TYPE);
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.GL_ACCOUNT_ENTITY_TYPE);
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.FUNDS_ENTITY_TYPE);
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.PAYMENT_TYPE_ENTITY_TYPE);
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.CURRENCY_ENTITY_TYPE);
List<OfficeData> offices = fetchOffices(officeId);
List<GLAccountData> glAccounts = fetchGLAccounts();
List<FundData> funds = fetchFunds();
List<PaymentTypeData> paymentTypes = fetchPaymentTypes();
List<CurrencyData> currencies = fetchCurrencies();
return new JournalEntriesWorkbookPopulator(new OfficeSheetPopulator(offices),
new GlAccountSheetPopulator(glAccounts), new ExtrasSheetPopulator(funds, paymentTypes, currencies));
}
private WorkbookPopulator populateJournalEntriesWorkbook(Long officeId) {
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.OFFICE_ENTITY_TYPE);
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.GL_ACCOUNT_ENTITY_TYPE);
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.FUNDS_ENTITY_TYPE);
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.PAYMENT_TYPE_ENTITY_TYPE);
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.CURRENCY_ENTITY_TYPE);
List<OfficeData> offices = fetchOffices(officeId);
List<GLAccountData> glAccounts = fetchGLAccounts();
List<FundData> funds = fetchFunds();
List<PaymentTypeData> paymentTypes = fetchPaymentTypes();
List<CurrencyData> currencies = fetchCurrencies();
return new JournalEntriesWorkbookPopulator(new OfficeSheetPopulator(offices),
new GlAccountSheetPopulator(glAccounts), new ExtrasSheetPopulator(funds, paymentTypes, currencies));
}
private List<GLAccountData> fetchGLAccounts() {
List<GLAccountData> glaccounts = (List<GLAccountData>) this.glAccountReadPlatformService.
retrieveAllGLAccounts(null, null, null,
null, null, null);
return glaccounts;
}
private List<GLAccountData> fetchGLAccounts() {
List<GLAccountData> glaccounts = (List<GLAccountData>) this.glAccountReadPlatformService.
retrieveAllGLAccounts(null, null, null,
null, null, null);
return glaccounts;
}
private WorkbookPopulator populateGuarantorWorkbook(Long officeId) {
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.OFFICE_ENTITY_TYPE);
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.STAFF_ENTITY_TYPE);
List<OfficeData> offices = fetchOffices(officeId);
List<ClientData>clients=fetchClients(officeId);
List<LoanAccountData> loans = fetchLoanAccounts(officeId);
List<SavingsAccountData> savingsaccounts = fetchSavingsAccounts(officeId);
List<CodeValueData> guarantorRelationshipTypes=fetchCodeValuesByCodeName("GuarantorRelationship");
return new GuarantorWorkbookPopulator(new OfficeSheetPopulator(offices),
new ClientSheetPopulator(clients, offices),loans,savingsaccounts,guarantorRelationshipTypes);
}
private WorkbookPopulator populateGuarantorWorkbook(Long officeId) {
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.OFFICE_ENTITY_TYPE);
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.STAFF_ENTITY_TYPE);
List<OfficeData> offices = fetchOffices(officeId);
List<ClientData>clients=fetchClients(officeId);
List<LoanAccountData> loans = fetchLoanAccounts(officeId);
List<SavingsAccountData> savingsaccounts = fetchSavingsAccounts(officeId);
List<CodeValueData> guarantorRelationshipTypes=fetchCodeValuesByCodeName("GuarantorRelationship");
return new GuarantorWorkbookPopulator(new OfficeSheetPopulator(offices),
new ClientSheetPopulator(clients, offices),loans,savingsaccounts,guarantorRelationshipTypes);
}
private List<SavingsAccountData> fetchSavingsAccounts(Long officeId) {
List<SavingsAccountData> savingsAccounts=null;
if (officeId!=null) {
String activeAccounts="sa.status_enum = 300";
SearchParameters searchParameters = SearchParameters.from(activeAccounts, officeId, null, null, null);
savingsAccounts = savingsAccountReadPlatformService.retrieveAll(searchParameters).getPageItems();;
}else {
savingsAccounts= savingsAccountReadPlatformService.retrieveAll(null).getPageItems();
}
return savingsAccounts;
}
private List<SavingsAccountData> fetchSavingsAccounts(Long officeId) {
List<SavingsAccountData> savingsAccounts=null;
if (officeId!=null) {
String activeAccounts="sa.status_enum = 300";
SearchParameters searchParameters = SearchParameters.from(activeAccounts, officeId, null, null, null);
savingsAccounts = savingsAccountReadPlatformService.retrieveAll(searchParameters).getPageItems();;
}else {
savingsAccounts= savingsAccountReadPlatformService.retrieveAll(null).getPageItems();
}
return savingsAccounts;
}
private WorkbookPopulator populateOfficeWorkbook() {
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.OFFICE_ENTITY_TYPE);
List<OfficeData> offices = fetchOffices(null);
return new OfficeWorkbookPopulator(offices);
}
private WorkbookPopulator populateOfficeWorkbook() {
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.OFFICE_ENTITY_TYPE);
List<OfficeData> offices = fetchOffices(null);
return new OfficeWorkbookPopulator(offices);
}
private WorkbookPopulator populateChartOfAccountsWorkbook() {
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.GL_ACCOUNT_ENTITY_TYPE);
List<GLAccountData> glAccounts = fetchGLAccounts();
return new ChartOfAccountsWorkbook(glAccounts);
}
private WorkbookPopulator populateChartOfAccountsWorkbook() {
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.GL_ACCOUNT_ENTITY_TYPE);
List<GLAccountData> glAccounts = fetchGLAccounts();
return new ChartOfAccountsWorkbook(glAccounts);
}
private WorkbookPopulator populateStaffWorkbook(Long officeId) {
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.OFFICE_ENTITY_TYPE);
List<OfficeData> offices=fetchOffices(officeId);
return new StaffWorkbookPopulator(new OfficeSheetPopulator(offices));
}
private WorkbookPopulator populateStaffWorkbook(Long officeId) {
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.OFFICE_ENTITY_TYPE);
List<OfficeData> offices=fetchOffices(officeId);
return new StaffWorkbookPopulator(new OfficeSheetPopulator(offices));
}
private WorkbookPopulator populateSharedAcountsWorkbook(Long officeId) {
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.CLIENT_ENTITY_TYPE);
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.SHARED_ACCOUNT_ENTITY_TYPE);
List<ShareProductData> shareProductDataList=fetchSharedProducts();
List<ChargeData> chargesForShares=fetchChargesForShares();
List<ClientData> clientDataList=fetchClients(officeId);
List<OfficeData>officeDataList=fetchOffices(officeId);
List<SavingsAccountData> savingsAccounts = fetchSavingsAccounts(officeId);
return new SharedAccountWorkBookPopulator(new SharedProductsSheetPopulator(shareProductDataList,chargesForShares),
new ClientSheetPopulator(clientDataList,officeDataList),new SavingsAccountSheetPopulator(savingsAccounts));
}
private WorkbookPopulator populateSharedAcountsWorkbook(Long officeId) {
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.CLIENT_ENTITY_TYPE);
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.SHARED_ACCOUNT_ENTITY_TYPE);
List<ShareProductData> shareProductDataList=fetchSharedProducts();
List<ChargeData> chargesForShares=fetchChargesForShares();
List<ClientData> clientDataList=fetchClients(officeId);
List<OfficeData>officeDataList=fetchOffices(officeId);
List<SavingsAccountData> savingsAccounts = fetchSavingsAccounts(officeId);
return new SharedAccountWorkBookPopulator(new SharedProductsSheetPopulator(shareProductDataList,chargesForShares),
new ClientSheetPopulator(clientDataList,officeDataList),new SavingsAccountSheetPopulator(savingsAccounts));
}
private List<ChargeData> fetchChargesForShares() {
List<ChargeData>chargesForShares=(List<ChargeData>) chargeReadPlatformService.retrieveSharesApplicableCharges();
return chargesForShares;
}
private List<ChargeData> fetchChargesForShares() {
List<ChargeData>chargesForShares=(List<ChargeData>) chargeReadPlatformService.retrieveSharesApplicableCharges();
return chargesForShares;
}
private List<ShareProductData> fetchSharedProducts() {
List<ProductData> productDataList = productReadPlatformService.retrieveAllProducts(0,50).getPageItems() ;
List<ShareProductData> sharedProductDataList=new ArrayList<>();
if(productDataList!=null) {
for (ProductData data : productDataList) {
ShareProductData shareProduct = (ShareProductData) data;
sharedProductDataList.add(shareProduct);
}
}
return sharedProductDataList;
}
private List<ShareProductData> fetchSharedProducts() {
List<ProductData> productDataList = productReadPlatformService.retrieveAllProducts(0,50).getPageItems() ;
List<ShareProductData> sharedProductDataList=new ArrayList<>();
if(productDataList!=null) {
for (ProductData data : productDataList) {
ShareProductData shareProduct = (ShareProductData) data;
sharedProductDataList.add(shareProduct);
}
}
return sharedProductDataList;
}
private WorkbookPopulator populateSavingsAccountWorkbook(Long officeId, Long staffId) {
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.OFFICE_ENTITY_TYPE);
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.STAFF_ENTITY_TYPE);
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.GROUP_ENTITY_TYPE);
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.CLIENT_ENTITY_TYPE);
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.SAVINGS_PRODUCT_ENTITY_TYPE);
List<OfficeData> offices = fetchOffices(officeId);
List<StaffData> staff = fetchStaff(staffId);
List<ClientData> clients = fetchClients(officeId);
List<GroupGeneralData> groups = fetchGroups(officeId);
List<SavingsProductData> savingsProducts=fetchSavingsProducts();
return new SavingsWorkbookPopulator(new OfficeSheetPopulator(offices), new ClientSheetPopulator(clients, offices),
new GroupSheetPopulator(groups, offices), new PersonnelSheetPopulator(staff, offices),
new SavingsProductSheetPopulator(savingsProducts));
}
private WorkbookPopulator populateSavingsAccountWorkbook(Long officeId, Long staffId) {
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.OFFICE_ENTITY_TYPE);
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.STAFF_ENTITY_TYPE);
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.GROUP_ENTITY_TYPE);
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.CLIENT_ENTITY_TYPE);
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.SAVINGS_PRODUCT_ENTITY_TYPE);
List<OfficeData> offices = fetchOffices(officeId);
List<StaffData> staff = fetchStaff(staffId);
List<ClientData> clients = fetchClients(officeId);
List<GroupGeneralData> groups = fetchGroups(officeId);
List<SavingsProductData> savingsProducts=fetchSavingsProducts();
return new SavingsWorkbookPopulator(new OfficeSheetPopulator(offices), new ClientSheetPopulator(clients, offices),
new GroupSheetPopulator(groups, offices), new PersonnelSheetPopulator(staff, offices),
new SavingsProductSheetPopulator(savingsProducts));
}
private WorkbookPopulator populateSavingsTransactionWorkbook(Long officeId) {
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.OFFICE_ENTITY_TYPE);
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.CLIENT_ENTITY_TYPE);
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.FUNDS_ENTITY_TYPE);
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.PAYMENT_TYPE_ENTITY_TYPE);
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.CURRENCY_ENTITY_TYPE);
List<OfficeData> offices = fetchOffices(officeId);
List<ClientData> clients = fetchClients(officeId);
List<FundData> funds = fetchFunds();
List<PaymentTypeData> paymentTypes = fetchPaymentTypes();
List<CurrencyData> currencies = fetchCurrencies();
List<SavingsAccountData> savingsAccounts=fetchSavingsAccounts(officeId);
return new SavingsTransactionsWorkbookPopulator(new OfficeSheetPopulator(offices), new ClientSheetPopulator(clients, offices),
new ExtrasSheetPopulator(funds, paymentTypes, currencies),savingsAccounts);
}
private WorkbookPopulator populateSavingsTransactionWorkbook(Long officeId) {
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.OFFICE_ENTITY_TYPE);
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.CLIENT_ENTITY_TYPE);
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.FUNDS_ENTITY_TYPE);
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.PAYMENT_TYPE_ENTITY_TYPE);
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.CURRENCY_ENTITY_TYPE);
List<OfficeData> offices = fetchOffices(officeId);
List<ClientData> clients = fetchClients(officeId);
List<FundData> funds = fetchFunds();
List<PaymentTypeData> paymentTypes = fetchPaymentTypes();
List<CurrencyData> currencies = fetchCurrencies();
List<SavingsAccountData> savingsAccounts=fetchSavingsAccounts(officeId);
return new SavingsTransactionsWorkbookPopulator(new OfficeSheetPopulator(offices), new ClientSheetPopulator(clients, offices),
new ExtrasSheetPopulator(funds, paymentTypes, currencies),savingsAccounts);
}
private WorkbookPopulator populateRecurringDepositWorkbook(Long officeId,Long staffId) {
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.OFFICE_ENTITY_TYPE);
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.CLIENT_ENTITY_TYPE);
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.STAFF_ENTITY_TYPE);
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.RECURRING_DEPOSIT_PRODUCT_ENTITY_TYPE);
List<OfficeData> offices = fetchOffices(officeId);
List<ClientData> clients = fetchClients(officeId);
List<StaffData> staff = fetchStaff(staffId);
List<RecurringDepositProductData> recurringDepositProducts = fetchRecurringDepositProducts();
return new RecurringDepositWorkbookPopulator(new OfficeSheetPopulator(offices), new ClientSheetPopulator(clients, offices),
new PersonnelSheetPopulator(staff,offices),new RecurringDepositProductSheetPopulator(recurringDepositProducts));
}
private WorkbookPopulator populateRecurringDepositWorkbook(Long officeId,Long staffId) {
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.OFFICE_ENTITY_TYPE);
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.CLIENT_ENTITY_TYPE);
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.STAFF_ENTITY_TYPE);
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.RECURRING_DEPOSIT_PRODUCT_ENTITY_TYPE);
List<OfficeData> offices = fetchOffices(officeId);
List<ClientData> clients = fetchClients(officeId);
List<StaffData> staff = fetchStaff(staffId);
List<RecurringDepositProductData> recurringDepositProducts = fetchRecurringDepositProducts();
return new RecurringDepositWorkbookPopulator(new OfficeSheetPopulator(offices), new ClientSheetPopulator(clients, offices),
new PersonnelSheetPopulator(staff,offices),new RecurringDepositProductSheetPopulator(recurringDepositProducts));
}
private List<RecurringDepositProductData> fetchRecurringDepositProducts() {
List<DepositProductData> depositProducts=(List<DepositProductData>)depositProductReadPlatformService
.retrieveAll(DepositAccountType.RECURRING_DEPOSIT);
List<RecurringDepositProductData> recurringDepositProducts=new ArrayList<>();
for (DepositProductData depositproduct: depositProducts) {
RecurringDepositProductData recurringDepositProduct= (RecurringDepositProductData) depositproduct;
recurringDepositProducts.add(recurringDepositProduct);
}
return recurringDepositProducts;
}
private List<RecurringDepositProductData> fetchRecurringDepositProducts() {
List<DepositProductData> depositProducts=(List<DepositProductData>)depositProductReadPlatformService
.retrieveAll(DepositAccountType.RECURRING_DEPOSIT);
List<RecurringDepositProductData> recurringDepositProducts=new ArrayList<>();
for (DepositProductData depositproduct: depositProducts) {
RecurringDepositProductData recurringDepositProduct= (RecurringDepositProductData) depositproduct;
recurringDepositProducts.add(recurringDepositProduct);
}
return recurringDepositProducts;
}
private WorkbookPopulator populateRecurringDepositTransactionWorkbook(Long officeId) {
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.OFFICE_ENTITY_TYPE);
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.CLIENT_ENTITY_TYPE);
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.FUNDS_ENTITY_TYPE);
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.PAYMENT_TYPE_ENTITY_TYPE);
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.CURRENCY_ENTITY_TYPE);
List<OfficeData> offices = fetchOffices(officeId);
List<ClientData> clients = fetchClients(officeId);
List<FundData> funds = fetchFunds();
List<PaymentTypeData> paymentTypes = fetchPaymentTypes();
List<CurrencyData> currencies = fetchCurrencies();
List<SavingsAccountData> savingsAccounts=fetchSavingsAccounts(officeId);
return new RecurringDepositTransactionWorkbookPopulator(new OfficeSheetPopulator(offices), new ClientSheetPopulator(clients, offices),
new ExtrasSheetPopulator(funds, paymentTypes, currencies),savingsAccounts);
}
private WorkbookPopulator populateRecurringDepositTransactionWorkbook(Long officeId) {
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.OFFICE_ENTITY_TYPE);
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.CLIENT_ENTITY_TYPE);
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.FUNDS_ENTITY_TYPE);
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.PAYMENT_TYPE_ENTITY_TYPE);
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.CURRENCY_ENTITY_TYPE);
List<OfficeData> offices = fetchOffices(officeId);
List<ClientData> clients = fetchClients(officeId);
List<FundData> funds = fetchFunds();
List<PaymentTypeData> paymentTypes = fetchPaymentTypes();
List<CurrencyData> currencies = fetchCurrencies();
List<SavingsAccountData> savingsAccounts=fetchSavingsAccounts(officeId);
return new RecurringDepositTransactionWorkbookPopulator(new OfficeSheetPopulator(offices), new ClientSheetPopulator(clients, offices),
new ExtrasSheetPopulator(funds, paymentTypes, currencies),savingsAccounts);
}
private WorkbookPopulator populateFixedDepositWorkbook(Long officeId, Long staffId) {
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.OFFICE_ENTITY_TYPE);
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.CLIENT_ENTITY_TYPE);
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.STAFF_ENTITY_TYPE);
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.FIXED_DEPOSIT_PRODUCT_ENTITY_TYPE);
List<OfficeData> offices = fetchOffices(officeId);
List<ClientData> clients = fetchClients(officeId);
List<StaffData> staff = fetchStaff(staffId);
List<FixedDepositProductData> fixedDepositProducts = fetchFixedDepositProducts();
return new FixedDepositWorkbookPopulator(new OfficeSheetPopulator(offices), new ClientSheetPopulator(clients, offices),
new PersonnelSheetPopulator(staff,offices),new FixedDepositProductSheetPopulator(fixedDepositProducts));
private WorkbookPopulator populateFixedDepositWorkbook(Long officeId, Long staffId) {
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.OFFICE_ENTITY_TYPE);
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.CLIENT_ENTITY_TYPE);
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.STAFF_ENTITY_TYPE);
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.FIXED_DEPOSIT_PRODUCT_ENTITY_TYPE);
List<OfficeData> offices = fetchOffices(officeId);
List<ClientData> clients = fetchClients(officeId);
List<StaffData> staff = fetchStaff(staffId);
List<FixedDepositProductData> fixedDepositProducts = fetchFixedDepositProducts();
return new FixedDepositWorkbookPopulator(new OfficeSheetPopulator(offices), new ClientSheetPopulator(clients, offices),
new PersonnelSheetPopulator(staff,offices),new FixedDepositProductSheetPopulator(fixedDepositProducts));
}
}
private List<FixedDepositProductData> fetchFixedDepositProducts() {
List<DepositProductData> depositProducts=(List<DepositProductData>)depositProductReadPlatformService
.retrieveAll(DepositAccountType.FIXED_DEPOSIT);
List<FixedDepositProductData> fixedDepositProducts=new ArrayList<>();
for (DepositProductData depositproduct: depositProducts) {
FixedDepositProductData fixedDepositProduct= (FixedDepositProductData) depositproduct;
fixedDepositProducts.add(fixedDepositProduct);
}
return fixedDepositProducts;
private List<FixedDepositProductData> fetchFixedDepositProducts() {
List<DepositProductData> depositProducts=(List<DepositProductData>)depositProductReadPlatformService
.retrieveAll(DepositAccountType.FIXED_DEPOSIT);
List<FixedDepositProductData> fixedDepositProducts=new ArrayList<>();
for (DepositProductData depositproduct: depositProducts) {
FixedDepositProductData fixedDepositProduct= (FixedDepositProductData) depositproduct;
fixedDepositProducts.add(fixedDepositProduct);
}
return fixedDepositProducts;
}
}
private WorkbookPopulator populateUserWorkbook(Long officeId, Long staffId) {
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.USER_ENTITY_TYPE);
List<OfficeData> offices = fetchOffices(officeId);
List<StaffData> staff = fetchStaff(staffId);
List<RoleData> roles=fetchRoles();
return new UserWorkbookPopulator(new OfficeSheetPopulator(offices), new PersonnelSheetPopulator(staff,offices),
new RoleSheetPopulator(roles));
}
private WorkbookPopulator populateUserWorkbook(Long officeId, Long staffId) {
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.USER_ENTITY_TYPE);
List<OfficeData> offices = fetchOffices(officeId);
List<StaffData> staff = fetchStaff(staffId);
List<RoleData> roles=fetchRoles();
return new UserWorkbookPopulator(new OfficeSheetPopulator(offices), new PersonnelSheetPopulator(staff,offices),
new RoleSheetPopulator(roles));
}
private List<RoleData> fetchRoles() {
List<RoleData> rolesList= (List<RoleData>) roleReadPlatformService.retrieveAllActiveRoles();
return rolesList;
}
private List<RoleData> fetchRoles() {
List<RoleData> rolesList= (List<RoleData>) roleReadPlatformService.retrieveAllActiveRoles();
return rolesList;
}
private WorkbookPopulator populateFixedDepositTransactionsWorkbook(Long officeId) {
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.OFFICE_ENTITY_TYPE);
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.CLIENT_ENTITY_TYPE);
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.FUNDS_ENTITY_TYPE);
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.PAYMENT_TYPE_ENTITY_TYPE);
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.CURRENCY_ENTITY_TYPE);
List<OfficeData> offices = fetchOffices(officeId);
List<ClientData> clients = fetchClients(officeId);
List<FundData> funds = fetchFunds();
List<PaymentTypeData> paymentTypes = fetchPaymentTypes();
List<CurrencyData> currencies = fetchCurrencies();
List<SavingsAccountData> savingsAccounts=fetchSavingsAccounts(officeId);
return new FixedDepositTransactionWorkbookPopulator(new OfficeSheetPopulator(offices), new ClientSheetPopulator(clients, offices),
new ExtrasSheetPopulator(funds, paymentTypes, currencies),savingsAccounts);
}
private WorkbookPopulator populateFixedDepositTransactionsWorkbook(Long officeId) {
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.OFFICE_ENTITY_TYPE);
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.CLIENT_ENTITY_TYPE);
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.FUNDS_ENTITY_TYPE);
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.PAYMENT_TYPE_ENTITY_TYPE);
this.context.authenticatedUser().validateHasReadPermission(TemplatePopulateImportConstants.CURRENCY_ENTITY_TYPE);
List<OfficeData> offices = fetchOffices(officeId);
List<ClientData> clients = fetchClients(officeId);
List<FundData> funds = fetchFunds();
List<PaymentTypeData> paymentTypes = fetchPaymentTypes();
List<CurrencyData> currencies = fetchCurrencies();
List<SavingsAccountData> savingsAccounts=fetchSavingsAccounts(officeId);
return new FixedDepositTransactionWorkbookPopulator(new OfficeSheetPopulator(offices), new ClientSheetPopulator(clients, offices),
new ExtrasSheetPopulator(funds, paymentTypes, currencies),savingsAccounts);
}
}
@@ -115,9 +115,9 @@ public class EmailCampaignValidator {
final Long businessRuleId = this.fromApiJsonHelper.extractLongNamed(EmailCampaignValidator.businessRuleId,element);
baseDataValidator.reset().parameter(EmailCampaignValidator.businessRuleId).value(businessRuleId).notNull().integerGreaterThanZero();
final String emailSubject = this.fromApiJsonHelper.extractStringNamed(EmailCampaignValidator.emailSubject, element);
final String emailSubject = this.fromApiJsonHelper.extractStringNamed(EmailCampaignValidator.emailSubject, element);
baseDataValidator.reset().parameter(EmailCampaignValidator.emailSubject).value(emailSubject).notBlank().notExceedingLengthOf(50);
final String emailMessage = this.fromApiJsonHelper.extractStringNamed(EmailCampaignValidator.emailMessage, element);
baseDataValidator.reset().parameter(EmailCampaignValidator.emailMessage).value(emailMessage).notBlank().notExceedingLengthOf(480);
@@ -22,42 +22,42 @@ package org.apache.fineract.infrastructure.campaigns.email.data;
* Immutable data object representing an Email configuration.
*/
public class EmailConfigurationData {
@SuppressWarnings("unused")
private final Long id;
private final String name;
@SuppressWarnings("unused")
private final Long id;
private final String name;
private final String value;
/**
* @return an instance of the EmailConfigurationData class
**/
public static EmailConfigurationData instance(Long id, String name, String value) {
return new EmailConfigurationData(id, name, value);
}
/**
* EmailConfigurationData constructor
**/
private EmailConfigurationData(Long id, String name, String value) {
this.id = id;
this.name = name;
this.value = value;
}
/**
* @return an instance of the EmailConfigurationData class
**/
public static EmailConfigurationData instance(Long id, String name, String value) {
return new EmailConfigurationData(id, name, value);
}
/**
* EmailConfigurationData constructor
**/
private EmailConfigurationData(Long id, String name, String value) {
this.id = id;
this.name = name;
this.value = value;
}
/**
* @return the id
*/
public Long getId() {
return id;
}
/**
* @return the id
*/
public Long getId() {
return id;
}
public String getName() {
return name;
}
public String getName() {
return name;
}
public String getValue() {
return value;
}
public String getValue() {
return value;
}
}
@@ -35,126 +35,126 @@ public class EmailData {
private final Long staffId;
private final EnumOptionData status;
private final String emailAddress;
private final String emailSubject;
private final String emailSubject;
private final String emailMessage;
private final EnumOptionData emailAttachmentFileFormat;
private final ReportData stretchyReport;
private final String stretchyReportParamMap;
private final List<EnumOptionData> emailAttachmentFileFormatOptions;
private final List<EnumOptionData> stretchyReportParamDateOptions;
private final EnumOptionData emailAttachmentFileFormat;
private final ReportData stretchyReport;
private final String stretchyReportParamMap;
private final List<EnumOptionData> emailAttachmentFileFormatOptions;
private final List<EnumOptionData> stretchyReportParamDateOptions;
private final String campaignName;
private final LocalDate sentDate;
private final String errorMessage;
private final LocalDate sentDate;
private final String errorMessage;
public static EmailData instance(final Long id,final Long groupId, final Long clientId, final Long staffId, final EnumOptionData status,
final String emailAddress, final String emailSubject,
final String message, final EnumOptionData emailAttachmentFileFormat, final ReportData stretchyReport,
final String stretchyReportParamMap, final List<EnumOptionData> emailAttachmentFileFormatOptions,
final List<EnumOptionData> stretchyReportParamDateOptions, final String campaignName, final LocalDate sentDate,final String errorMessage) {
public static EmailData instance(final Long id,final Long groupId, final Long clientId, final Long staffId, final EnumOptionData status,
final String emailAddress, final String emailSubject,
final String message, final EnumOptionData emailAttachmentFileFormat, final ReportData stretchyReport,
final String stretchyReportParamMap, final List<EnumOptionData> emailAttachmentFileFormatOptions,
final List<EnumOptionData> stretchyReportParamDateOptions, final String campaignName, final LocalDate sentDate,final String errorMessage) {
return new EmailData(id, groupId, clientId, staffId, status, emailAddress, emailSubject, message,
emailAttachmentFileFormat,stretchyReport,stretchyReportParamMap,emailAttachmentFileFormatOptions,
stretchyReportParamDateOptions,campaignName,sentDate,errorMessage);
emailAttachmentFileFormat,stretchyReport,stretchyReportParamMap,emailAttachmentFileFormatOptions,
stretchyReportParamDateOptions,campaignName,sentDate,errorMessage);
}
private EmailData(final Long id,final Long groupId, final Long clientId, final Long staffId, final EnumOptionData status, final String emailAddress, final String emailSubject, final String message,
final EnumOptionData emailAttachmentFileFormat, final ReportData stretchyReport, final String stretchyReportParamMap,
final List<EnumOptionData> emailAttachmentFileFormatOptions, final List<EnumOptionData> stretchyReportParamDateOptions,
final String campaignName,final LocalDate sentDate,final String errorMessage) {
final EnumOptionData emailAttachmentFileFormat, final ReportData stretchyReport, final String stretchyReportParamMap,
final List<EnumOptionData> emailAttachmentFileFormatOptions, final List<EnumOptionData> stretchyReportParamDateOptions,
final String campaignName,final LocalDate sentDate,final String errorMessage) {
this.id = id;
this.groupId = groupId;
this.clientId = clientId;
this.staffId = staffId;
this.status = status;
this.emailAddress = emailAddress;
this.emailSubject = emailSubject;
this.emailSubject = emailSubject;
this.emailMessage = message;
this.emailAttachmentFileFormat = emailAttachmentFileFormat;
this.stretchyReport = stretchyReport;
this.stretchyReportParamMap = stretchyReportParamMap;
this.emailAttachmentFileFormatOptions = emailAttachmentFileFormatOptions;
this.stretchyReportParamDateOptions = stretchyReportParamDateOptions;
this.emailAttachmentFileFormat = emailAttachmentFileFormat;
this.stretchyReport = stretchyReport;
this.stretchyReportParamMap = stretchyReportParamMap;
this.emailAttachmentFileFormatOptions = emailAttachmentFileFormatOptions;
this.stretchyReportParamDateOptions = stretchyReportParamDateOptions;
this.campaignName = campaignName;
this.sentDate = sentDate;
this.errorMessage = errorMessage;
this.sentDate = sentDate;
this.errorMessage = errorMessage;
}
/**
* @return the id
*/
public Long getId() {
return id;
}
/**
* @return the id
*/
public Long getId() {
return id;
}
/**
* @return the groupId
*/
public Long getGroupId() {
return groupId;
}
/**
* @return the groupId
*/
public Long getGroupId() {
return groupId;
}
/**
* @return the clientId
*/
public Long getClientId() {
return clientId;
}
/**
* @return the clientId
*/
public Long getClientId() {
return clientId;
}
/**
* @return the staffId
*/
public Long getStaffId() {
return staffId;
}
/**
* @return the staffId
*/
public Long getStaffId() {
return staffId;
}
/**
* @return the status
*/
public EnumOptionData getStatus() {
return status;
}
/**
* @return the status
*/
public EnumOptionData getStatus() {
return status;
}
public String getErrorMessage() {return this.errorMessage;}
public String getErrorMessage() {return this.errorMessage;}
/**
* @return the emailAddress
*/
public String getEmailAddress() {
return emailAddress;
}
/**
* @return the emailAddress
*/
public String getEmailAddress() {
return emailAddress;
}
/**
* @return the message
*/
public String getMessage() {
return emailMessage;
}
/**
* @return the message
*/
public String getMessage() {
return emailMessage;
}
public String getCampaignName() {return this.campaignName;}
public String getCampaignName() {return this.campaignName;}
public LocalDate getSentDate() { return this.sentDate; }
public LocalDate getSentDate() { return this.sentDate; }
public String getEmailSubject() {
return emailSubject;
}
public String getEmailSubject() {
return emailSubject;
}
public EnumOptionData getEmailAttachmentFileFormat() {
return emailAttachmentFileFormat;
}
public EnumOptionData getEmailAttachmentFileFormat() {
return emailAttachmentFileFormat;
}
public ReportData getStretchyReport() {
return stretchyReport;
}
public ReportData getStretchyReport() {
return stretchyReport;
}
public String getStretchyReportParamMap() {
return stretchyReportParamMap;
}
public String getStretchyReportParamMap() {
return stretchyReportParamMap;
}
public List<EnumOptionData> getEmailAttachmentFileFormatOptions() {
return emailAttachmentFileFormatOptions;
}
public List<EnumOptionData> getEmailAttachmentFileFormatOptions() {
return emailAttachmentFileFormatOptions;
}
public List<EnumOptionData> getStretchyReportParamDateOptions() {
return stretchyReportParamDateOptions;
}
public List<EnumOptionData> getStretchyReportParamDateOptions() {
return stretchyReportParamDateOptions;
}
}
@@ -27,34 +27,34 @@ import javax.persistence.Table;
@Entity
@Table(name = "scheduled_email_configuration")
public class EmailConfiguration extends AbstractPersistableCustom<Long> {
@Column(name = "name", nullable = false)
@Column(name = "name", nullable = false)
private String name;
@Column(name = "value", nullable = false)
@Column(name = "value", nullable = false)
private String value;
/**
* EmailConfiguration constructor
**/
protected EmailConfiguration() {}
/**
* EmailConfiguration constructor
**/
public EmailConfiguration(String name, String value) {
this.name = name;
this.value = value;
}
public void setValue(String value) {
this.value = value;
}
/**
* EmailConfiguration constructor
**/
protected EmailConfiguration() {}
/**
* EmailConfiguration constructor
**/
public EmailConfiguration(String name, String value) {
this.name = name;
this.value = value;
}
public void setValue(String value) {
this.value = value;
}
public String getName() {
return this.name;
}
public String getName() {
return this.name;
}
public String getValue() {
return this.value;
}
public String getValue() {
return this.value;
}
}
@@ -22,5 +22,5 @@ import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
public interface EmailConfigurationRepository extends JpaRepository<EmailConfiguration, Long>, JpaSpecificationExecutor<EmailConfiguration> {
EmailConfiguration findByName(String name);
EmailConfiguration findByName(String name);
}
@@ -82,7 +82,7 @@ public class EmailMessage extends AbstractPersistableCustom<Long> {
public static EmailMessage instance(final Group group, final Client client, final Staff staff, final EmailCampaign emailCampaign, final EmailMessageStatusType statusType,
final String emailSubject, final String message, final String sourceAddress, final String emailAddress, final String campaignName) {
return new EmailMessage(group, client, staff,emailCampaign, statusType, emailSubject, message, emailAddress, campaignName);
return new EmailMessage(group, client, staff,emailCampaign, statusType, emailSubject, message, emailAddress, campaignName);
}
protected EmailMessage() {
@@ -91,7 +91,7 @@ public class EmailMessage extends AbstractPersistableCustom<Long> {
private EmailMessage(final Group group, final Client client, final Staff staff, final EmailCampaign emailCampaign, final EmailMessageStatusType statusType,
final String emailSubject, final String message, final String emailAddress, final String campaignName) {
this.group = group;
this.group = group;
this.client = client;
this.staff = staff;
this.emailCampaign = emailCampaign;
@@ -118,19 +118,19 @@ public class EmailMessage extends AbstractPersistableCustom<Long> {
public Group getGroup() {
return group;
return group;
}
public Client getClient() {
return client;
return client;
}
public Staff getStaff() {
return staff;
return staff;
}
public Integer getStatusType() {
return statusType;
return statusType;
}
@@ -139,12 +139,12 @@ public class EmailMessage extends AbstractPersistableCustom<Long> {
public String getEmailSubject() {return emailSubject; }
public String getMessage() {
return message;
return message;
}
public void setStatusType(final Integer statusType) {
this.statusType = statusType;
this.statusType = statusType;
}
public String getCampaignName() {
@@ -25,7 +25,7 @@ import org.apache.fineract.infrastructure.core.exception.AbstractPlatformResourc
*/
public class EmailConfigurationNotFoundException extends AbstractPlatformResourceNotFoundException {
public EmailConfigurationNotFoundException(final String name) {
super("error.msg.email.configuration.name.not.found", "Email configuration with name " + name + " does not exist", name);
}
public EmailConfigurationNotFoundException(final String name) {
super("error.msg.email.configuration.name.not.found", "Email configuration with name " + name + " does not exist", name);
}
}
@@ -23,8 +23,8 @@ import org.apache.fineract.infrastructure.campaigns.email.data.EmailConfiguratio
import java.util.Collection;
public interface EmailConfigurationReadPlatformService {
Collection<EmailConfigurationData> retrieveAll();
Collection<EmailConfigurationData> retrieveAll();
EmailConfigurationData retrieveOne(String name);
EmailConfigurationData retrieveOne(String name);
}
@@ -34,66 +34,66 @@ import java.util.Collection;
@Service
public class EmailConfigurationReadPlatformServiceImpl implements EmailConfigurationReadPlatformService {
private final JdbcTemplate jdbcTemplate;
private final JdbcTemplate jdbcTemplate;
private final EmailConfigurationRowMapper emailConfigurationRowMapper;
@Autowired
public EmailConfigurationReadPlatformServiceImpl(final RoutingDataSource dataSource) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
this.emailConfigurationRowMapper = new EmailConfigurationRowMapper();
this.jdbcTemplate = new JdbcTemplate(dataSource);
this.emailConfigurationRowMapper = new EmailConfigurationRowMapper();
}
private static final class EmailConfigurationRowMapper implements RowMapper<EmailConfigurationData> {
final String schema;
public EmailConfigurationRowMapper() {
final StringBuilder sql = new StringBuilder(300);
sql.append("cnf.id as id, ");
sql.append("cnf.name as name, ");
sql.append("cnf.value as value ");
sql.append("from scheduled_email_configuration cnf");
this.schema = sql.toString();
}
public String schema() {
private static final class EmailConfigurationRowMapper implements RowMapper<EmailConfigurationData> {
final String schema;
public EmailConfigurationRowMapper() {
final StringBuilder sql = new StringBuilder(300);
sql.append("cnf.id as id, ");
sql.append("cnf.name as name, ");
sql.append("cnf.value as value ");
sql.append("from scheduled_email_configuration cnf");
this.schema = sql.toString();
}
public String schema() {
return this.schema;
}
@Override
public EmailConfigurationData mapRow(ResultSet rs, @SuppressWarnings("unused") int rowNum) throws SQLException {
final Long id = JdbcSupport.getLong(rs, "id");
final String name = rs.getString("name");
final String value = rs.getString("value");
return EmailConfigurationData.instance(id, name, value);
}
}
@Override
public EmailConfigurationData mapRow(ResultSet rs, @SuppressWarnings("unused") int rowNum) throws SQLException {
final Long id = JdbcSupport.getLong(rs, "id");
final String name = rs.getString("name");
final String value = rs.getString("value");
return EmailConfigurationData.instance(id, name, value);
}
}
@Override
public Collection<EmailConfigurationData> retrieveAll() {
final String sql = "select " + this.emailConfigurationRowMapper.schema();
@Override
public Collection<EmailConfigurationData> retrieveAll() {
final String sql = "select " + this.emailConfigurationRowMapper.schema();
return this.jdbcTemplate.query(sql, this.emailConfigurationRowMapper, new Object[] {});
}
}
@Override
public EmailConfigurationData retrieveOne(String name) {
try {
final String sql = "select " + this.emailConfigurationRowMapper.schema() + " where cnf.name = ?";
@Override
public EmailConfigurationData retrieveOne(String name) {
try {
final String sql = "select " + this.emailConfigurationRowMapper.schema() + " where cnf.name = ?";
return this.jdbcTemplate.queryForObject(sql, this.emailConfigurationRowMapper, name);
}
catch(final EmptyResultDataAccessException e) {
throw new EmailConfigurationNotFoundException(name);
}
}
return this.jdbcTemplate.queryForObject(sql, this.emailConfigurationRowMapper, name);
}
catch(final EmptyResultDataAccessException e) {
throw new EmailConfigurationNotFoundException(name);
}
}
}
@@ -83,7 +83,7 @@ public class EmailReadPlatformServiceImpl implements EmailReadPlatformService {
}
public String tableName() {
return "scheduled_email_messages_outbound";
return "scheduled_email_messages_outbound";
}
@Override
@@ -130,31 +130,31 @@ public class EmailReadPlatformServiceImpl implements EmailReadPlatformService {
}
@Override
public Collection<EmailData> retrieveAllPending(final SearchParameters searchParameters) {
final String sqlPlusLimit = (searchParameters.getLimit() > 0) ? " limit 0, " + searchParameters.getLimit() : "";
final String sql = "select " + this.emailRowMapper.schema() + " where emo.status_enum = "
+ EmailMessageStatusType.PENDING.getValue() + sqlPlusLimit;
public Collection<EmailData> retrieveAllPending(final SearchParameters searchParameters) {
final String sqlPlusLimit = (searchParameters.getLimit() > 0) ? " limit 0, " + searchParameters.getLimit() : "";
final String sql = "select " + this.emailRowMapper.schema() + " where emo.status_enum = "
+ EmailMessageStatusType.PENDING.getValue() + sqlPlusLimit;
return this.jdbcTemplate.query(sql, this.emailRowMapper, new Object[] {});
}
@Override
public Collection<EmailData> retrieveAllSent(final SearchParameters searchParameters) {
final String sqlPlusLimit = (searchParameters.getLimit() > 0) ? " limit 0, " + searchParameters.getLimit() : "";
final String sql = "select " + this.emailRowMapper.schema() + " where emo.status_enum = "
+ EmailMessageStatusType.SENT.getValue() + sqlPlusLimit;
@Override
public Collection<EmailData> retrieveAllSent(final SearchParameters searchParameters) {
final String sqlPlusLimit = (searchParameters.getLimit() > 0) ? " limit 0, " + searchParameters.getLimit() : "";
final String sql = "select " + this.emailRowMapper.schema() + " where emo.status_enum = "
+ EmailMessageStatusType.SENT.getValue() + sqlPlusLimit;
return this.jdbcTemplate.query(sql, this.emailRowMapper, new Object[] {});
}
}
@Override
public List<Long> retrieveExternalIdsOfAllSent(final Integer limit) {
final String sqlPlusLimit = (limit > 0) ? " limit 0, " + limit : "";
final String sql = "select external_id from " + this.emailRowMapper.tableName() + " where status_enum = "
+ EmailMessageStatusType.SENT.getValue() + sqlPlusLimit;
return this.jdbcTemplate.queryForList(sql, Long.class);
}
@Override
public List<Long> retrieveExternalIdsOfAllSent(final Integer limit) {
final String sqlPlusLimit = (limit > 0) ? " limit 0, " + limit : "";
final String sql = "select external_id from " + this.emailRowMapper.tableName() + " where status_enum = "
+ EmailMessageStatusType.SENT.getValue() + sqlPlusLimit;
return this.jdbcTemplate.queryForList(sql, Long.class);
}
@Override
public Collection<EmailData> retrieveAllDelivered(final Integer limit) {
@@ -165,14 +165,14 @@ public class EmailReadPlatformServiceImpl implements EmailReadPlatformService {
return this.jdbcTemplate.query(sql, this.emailRowMapper, new Object[] {});
}
@Override
public Collection<EmailData> retrieveAllFailed(final SearchParameters searchParameters) {
final String sqlPlusLimit = (searchParameters.getLimit() > 0) ? " limit 0, " + searchParameters.getLimit() : "";
@Override
public Collection<EmailData> retrieveAllFailed(final SearchParameters searchParameters) {
final String sqlPlusLimit = (searchParameters.getLimit() > 0) ? " limit 0, " + searchParameters.getLimit() : "";
final String sql = "select " + this.emailRowMapper.schema() + " where emo.status_enum = "
+ EmailMessageStatusType.FAILED.getValue() + sqlPlusLimit;
return this.jdbcTemplate.query(sql, this.emailRowMapper, new Object[] {});
}
}
@Override
public Page<EmailData> retrieveEmailByStatus(final Integer limit, final Integer status,final Date dateFrom, final Date dateTo) {
@@ -38,10 +38,10 @@ import org.springframework.stereotype.Component;
@Component
public class SmsConfigUtils {
@Autowired
private ExternalServicesPropertiesReadPlatformService propertiesReadPlatformService;
//This method will return uri and HttpEntry objects with keys as uri and entity
@Autowired
private ExternalServicesPropertiesReadPlatformService propertiesReadPlatformService;
//This method will return uri and HttpEntry objects with keys as uri and entity
public Map<String, Object> getMessageGateWayRequestURI(final String apiEndPoint, String apiQueueResourceDatas) {
Map<String, Object> httpRequestdetails = new HashMap<>();
MessageGatewayConfigurationData messageGatewayConfigurationData = this.propertiesReadPlatformService.getSMSGateway();
@@ -72,5 +72,5 @@ public class SmsConfigUtils {
return httpRequestdetails;
}
}
@@ -86,11 +86,11 @@ public class SmsCampaignEnumerations {
public static List<EnumOptionData> calendarPeriodFrequencyTypes(final PeriodFrequencyType[] periodFrequencyTypes) {
final List<EnumOptionData> optionDatas = new ArrayList<>();
for (final PeriodFrequencyType periodFrequencyType : periodFrequencyTypes) {
if(!periodFrequencyType.getValue().equals(PeriodFrequencyType.INVALID.getValue())) {
final EnumOptionData optionData = new EnumOptionData(periodFrequencyType.getValue().longValue(), periodFrequencyType.getCode(),
if(!periodFrequencyType.getValue().equals(PeriodFrequencyType.INVALID.getValue())) {
final EnumOptionData optionData = new EnumOptionData(periodFrequencyType.getValue().longValue(), periodFrequencyType.getCode(),
periodFrequencyType.toString());
optionDatas.add(optionData);
}
optionDatas.add(optionData);
}
}
return optionDatas;
}
@@ -207,8 +207,8 @@ public class SmsCampaignData {
return this.providerId;
}
public boolean isNotification() {
return this.isNotification;
}
public boolean isNotification() {
return this.isNotification;
}
}
@@ -162,11 +162,11 @@ public class SmsCampaign extends AbstractPersistableCustom<Long> {
final Long triggerType = command.longValueOfParameterNamed(SmsCampaignValidator.triggerType);
boolean isNotification = false;
if(command.parameterExists(SmsCampaignValidator.isNotificationParamName)){
isNotification = command.booleanPrimitiveValueOfParameterNamed(SmsCampaignValidator.isNotificationParamName);
isNotification = command.booleanPrimitiveValueOfParameterNamed(SmsCampaignValidator.isNotificationParamName);
}
Long providerId = null;
if(!isNotification){
providerId = command.longValueOfParameterNamed(SmsCampaignValidator.providerId);
providerId = command.longValueOfParameterNamed(SmsCampaignValidator.providerId);
}
final String paramValue = command.jsonFragment(SmsCampaignValidator.paramValue);
@@ -577,13 +577,13 @@ public class SmsCampaign extends AbstractPersistableCustom<Long> {
return recurrenceBuilder.toString();
}
public boolean isNotification() {
return this.isNotification;
}
public boolean isNotification() {
return this.isNotification;
}
public void setNotification(boolean isNotification) {
this.isNotification = isNotification;
}
public void setNotification(boolean isNotification) {
this.isNotification = isNotification;
}
}
@@ -321,16 +321,16 @@ public class SmsCampaignValidator {
if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); }
}
public boolean isValidNotificationOrSms(Client client, SmsCampaign smsCampaign, Object mobileNo) {
if (smsCampaign.isNotification()) {
if (client != null) {
DeviceRegistration deviceRegistration = this.deviceRegistrationRepository
.findDeviceRegistrationByClientId(client.getId());
return (deviceRegistration != null);
}
return false;
}
return (mobileNo != null);
}
public boolean isValidNotificationOrSms(Client client, SmsCampaign smsCampaign, Object mobileNo) {
if (smsCampaign.isNotification()) {
if (client != null) {
DeviceRegistration deviceRegistration = this.deviceRegistrationRepository
.findDeviceRegistrationByClientId(client.getId());
return (deviceRegistration != null);
}
return false;
}
return (mobileNo != null);
}
}
@@ -66,10 +66,10 @@ import org.springframework.stereotype.Service;
@Service
public class SmsCampaignDomainServiceImpl implements SmsCampaignDomainService {
private static final Logger logger = LoggerFactory.getLogger(SmsCampaignDomainServiceImpl.class);
//private final static int POOL_SIZE = 5 ;
private static final Logger logger = LoggerFactory.getLogger(SmsCampaignDomainServiceImpl.class);
//private final static int POOL_SIZE = 5 ;
private final SmsCampaignRepository smsCampaignRepository;
private final SmsMessageRepository smsMessageRepository;
private final OfficeRepository officeRepository;
@@ -110,198 +110,198 @@ public class SmsCampaignDomainServiceImpl implements SmsCampaignDomainService {
this.businessEventNotifierService.addBusinessEventPostListners(BUSINESS_EVENTS.SAVINGS_WITHDRAWAL, new SavingsAccountTransactionListener(false));
}
private void notifyRejectedLoanOwner(Loan loan) {
List<SmsCampaign> smsCampaigns = retrieveSmsCampaigns("Loan Rejected");
if (smsCampaigns.size() > 0) {
for (SmsCampaign campaign : smsCampaigns) {
if (campaign.isActive()) {
SmsCampaignDomainServiceImpl.this.smsCampaignWritePlatformCommandHandler
.insertDirectCampaignIntoSmsOutboundTable(loan, campaign);
}
}
}
}
private void notifyRejectedLoanOwner(Loan loan) {
List<SmsCampaign> smsCampaigns = retrieveSmsCampaigns("Loan Rejected");
if (smsCampaigns.size() > 0) {
for (SmsCampaign campaign : smsCampaigns) {
if (campaign.isActive()) {
SmsCampaignDomainServiceImpl.this.smsCampaignWritePlatformCommandHandler
.insertDirectCampaignIntoSmsOutboundTable(loan, campaign);
}
}
}
}
private void notifyAcceptedLoanOwner(Loan loan) {
List<SmsCampaign> smsCampaigns = retrieveSmsCampaigns("Loan Approved");
if(smsCampaigns.size()>0){
for (SmsCampaign campaign:smsCampaigns){
this.smsCampaignWritePlatformCommandHandler.insertDirectCampaignIntoSmsOutboundTable(loan, campaign);
this.smsCampaignWritePlatformCommandHandler.insertDirectCampaignIntoSmsOutboundTable(loan, campaign);
}
}
}
private void notifyClientActivated(final Client client) {
List<SmsCampaign> smsCampaigns = retrieveSmsCampaigns("Client Activated");
if(smsCampaigns.size()>0){
List<SmsCampaign> smsCampaigns = retrieveSmsCampaigns("Client Activated");
if(smsCampaigns.size()>0){
for (SmsCampaign campaign:smsCampaigns){
this.smsCampaignWritePlatformCommandHandler.insertDirectCampaignIntoSmsOutboundTable(client, campaign);
this.smsCampaignWritePlatformCommandHandler.insertDirectCampaignIntoSmsOutboundTable(client, campaign);
}
}
}
private void notifyClientRejected(final Client client) {
List<SmsCampaign> smsCampaigns = retrieveSmsCampaigns("Client Rejected");
if(smsCampaigns.size()>0){
List<SmsCampaign> smsCampaigns = retrieveSmsCampaigns("Client Rejected");
if(smsCampaigns.size()>0){
for (SmsCampaign campaign:smsCampaigns){
this.smsCampaignWritePlatformCommandHandler.insertDirectCampaignIntoSmsOutboundTable(client, campaign);
this.smsCampaignWritePlatformCommandHandler.insertDirectCampaignIntoSmsOutboundTable(client, campaign);
}
}
}
private void notifySavingsAccountActivated(final SavingsAccount savingsAccount) {
List<SmsCampaign> smsCampaigns = retrieveSmsCampaigns("Savings Activated");
if (smsCampaigns.size() > 0) {
for (SmsCampaign campaign : smsCampaigns) {
this.smsCampaignWritePlatformCommandHandler.insertDirectCampaignIntoSmsOutboundTable(savingsAccount,
campaign);
}
}
private void notifySavingsAccountActivated(final SavingsAccount savingsAccount) {
List<SmsCampaign> smsCampaigns = retrieveSmsCampaigns("Savings Activated");
if (smsCampaigns.size() > 0) {
for (SmsCampaign campaign : smsCampaigns) {
this.smsCampaignWritePlatformCommandHandler.insertDirectCampaignIntoSmsOutboundTable(savingsAccount,
campaign);
}
}
}
}
private void notifySavingsAccountRejected(final SavingsAccount savingsAccount) {
List<SmsCampaign> smsCampaigns = retrieveSmsCampaigns("Savings Rejected");
if (smsCampaigns.size() > 0) {
for (SmsCampaign campaign : smsCampaigns) {
this.smsCampaignWritePlatformCommandHandler.insertDirectCampaignIntoSmsOutboundTable(savingsAccount,
campaign);
}
}
private void notifySavingsAccountRejected(final SavingsAccount savingsAccount) {
List<SmsCampaign> smsCampaigns = retrieveSmsCampaigns("Savings Rejected");
if (smsCampaigns.size() > 0) {
for (SmsCampaign campaign : smsCampaigns) {
this.smsCampaignWritePlatformCommandHandler.insertDirectCampaignIntoSmsOutboundTable(savingsAccount,
campaign);
}
}
}
private void sendSmsForLoanRepayment(LoanTransaction loanTransaction) {
List<SmsCampaign> smsCampaigns = retrieveSmsCampaigns("Loan Repayment");
if (smsCampaigns.size() > 0) {
for (SmsCampaign smsCampaign : smsCampaigns) {
try {
Loan loan = loanTransaction.getLoan();
final Set<Client> groupClients = new HashSet<>();
if (loan.hasInvalidLoanType()) {
throw new InvalidLoanTypeException(
"Loan Type cannot be Invalid for the Triggered Sms Campaign");
}
if (loan.isGroupLoan()) {
Group group = this.groupRepository.findById(loan.getGroupId()).orElse(null);
groupClients.addAll(group.getClientMembers());
} else {
groupClients.add(loan.client());
}
HashMap<String, String> campaignParams = new ObjectMapper().readValue(smsCampaign.getParamValue(),
new TypeReference<HashMap<String, String>>() {
});
}
private void sendSmsForLoanRepayment(LoanTransaction loanTransaction) {
List<SmsCampaign> smsCampaigns = retrieveSmsCampaigns("Loan Repayment");
if (smsCampaigns.size() > 0) {
for (SmsCampaign smsCampaign : smsCampaigns) {
try {
Loan loan = loanTransaction.getLoan();
final Set<Client> groupClients = new HashSet<>();
if (loan.hasInvalidLoanType()) {
throw new InvalidLoanTypeException(
"Loan Type cannot be Invalid for the Triggered Sms Campaign");
}
if (loan.isGroupLoan()) {
Group group = this.groupRepository.findById(loan.getGroupId()).orElse(null);
groupClients.addAll(group.getClientMembers());
} else {
groupClients.add(loan.client());
}
HashMap<String, String> campaignParams = new ObjectMapper().readValue(smsCampaign.getParamValue(),
new TypeReference<HashMap<String, String>>() {
});
if (groupClients.size() > 0) {
for (Client client : groupClients) {
HashMap<String, Object> smsParams = processRepaymentDataForSms(loanTransaction, client);
for (String key : campaignParams.keySet()) {
String value = campaignParams.get(key);
String spvalue = null;
boolean spkeycheck = smsParams.containsKey(key);
if (spkeycheck) {
spvalue = smsParams.get(key).toString();
}
if (spkeycheck && !(value.equals("-1") || spvalue.equals(value))) {
if (key.equals("officeId")) {
Office campaignOffice = this.officeRepository.findById(Long.valueOf(value)).orElse(null);
if (campaignOffice
.doesNotHaveAnOfficeInHierarchyWithId(client.getOffice().getId())) {
throw new SmsRuntimeException("error.msg.no.office",
"Office not found for the id");
}
} else {
throw new SmsRuntimeException("error.msg.no.id.attribute",
"Office Id attribute is notfound");
}
}
}
String message = this.smsCampaignWritePlatformCommandHandler.compileSmsTemplate(
smsCampaign.getMessage(), smsCampaign.getCampaignName(), smsParams);
Object mobileNo = smsParams.get("mobileNo");
if (this.smsCampaignValidator.isValidNotificationOrSms(client, smsCampaign, mobileNo)) {
String mobileNumber = null;
if(mobileNo != null){
mobileNumber = mobileNo.toString();
}
SmsMessage smsMessage = SmsMessage.pendingSms(null, null, client, null, message,
mobileNumber, smsCampaign, smsCampaign.isNotification());
Collection<SmsMessage> messages = new ArrayList<>();
messages.add(smsMessage);
Map<SmsCampaign, Collection<SmsMessage>> smsDataMap = new HashMap<>();
smsDataMap.put(smsCampaign, messages);
this.smsMessageScheduledJobService.sendTriggeredMessages(smsDataMap);
}
}
}
} catch (final IOException e) {
logger.error("smsParams does not contain the key: " + e.getMessage());
} catch (final RuntimeException e) {
logger.debug("Client Office Id and SMS Campaign Office id doesn't match");
}
}
}
}
if (groupClients.size() > 0) {
for (Client client : groupClients) {
HashMap<String, Object> smsParams = processRepaymentDataForSms(loanTransaction, client);
for (String key : campaignParams.keySet()) {
String value = campaignParams.get(key);
String spvalue = null;
boolean spkeycheck = smsParams.containsKey(key);
if (spkeycheck) {
spvalue = smsParams.get(key).toString();
}
if (spkeycheck && !(value.equals("-1") || spvalue.equals(value))) {
if (key.equals("officeId")) {
Office campaignOffice = this.officeRepository.findById(Long.valueOf(value)).orElse(null);
if (campaignOffice
.doesNotHaveAnOfficeInHierarchyWithId(client.getOffice().getId())) {
throw new SmsRuntimeException("error.msg.no.office",
"Office not found for the id");
}
} else {
throw new SmsRuntimeException("error.msg.no.id.attribute",
"Office Id attribute is notfound");
}
}
}
String message = this.smsCampaignWritePlatformCommandHandler.compileSmsTemplate(
smsCampaign.getMessage(), smsCampaign.getCampaignName(), smsParams);
Object mobileNo = smsParams.get("mobileNo");
if (this.smsCampaignValidator.isValidNotificationOrSms(client, smsCampaign, mobileNo)) {
String mobileNumber = null;
if(mobileNo != null){
mobileNumber = mobileNo.toString();
}
SmsMessage smsMessage = SmsMessage.pendingSms(null, null, client, null, message,
mobileNumber, smsCampaign, smsCampaign.isNotification());
Collection<SmsMessage> messages = new ArrayList<>();
messages.add(smsMessage);
Map<SmsCampaign, Collection<SmsMessage>> smsDataMap = new HashMap<>();
smsDataMap.put(smsCampaign, messages);
this.smsMessageScheduledJobService.sendTriggeredMessages(smsDataMap);
}
}
}
} catch (final IOException e) {
logger.error("smsParams does not contain the key: " + e.getMessage());
} catch (final RuntimeException e) {
logger.debug("Client Office Id and SMS Campaign Office id doesn't match");
}
}
}
}
private void sendSmsForSavingsTransaction(final SavingsAccountTransaction savingsTransaction, boolean isDeposit) {
String campaignName = isDeposit ? "Savings Deposit" : "Savings Withdrawal";
List<SmsCampaign> smsCampaigns = retrieveSmsCampaigns(campaignName);
if (smsCampaigns.size() > 0) {
for (SmsCampaign smsCampaign : smsCampaigns) {
try {
final SavingsAccount savingsAccount = savingsTransaction.getSavingsAccount();
final Client client = savingsAccount.getClient();
HashMap<String, String> campaignParams = new ObjectMapper().readValue(smsCampaign.getParamValue(),
new TypeReference<HashMap<String, String>>() {
});
HashMap<String, Object> smsParams = processSavingsTransactionDataForSms(savingsTransaction, client);
for (String key : campaignParams.keySet()) {
String value = campaignParams.get(key);
String spvalue = null;
boolean spkeycheck = smsParams.containsKey(key);
if (spkeycheck) {
spvalue = smsParams.get(key).toString();
}
if (spkeycheck && !(value.equals("-1") || spvalue.equals(value))) {
if (key.equals("officeId")) {
Office campaignOffice = this.officeRepository.findById(Long.valueOf(value)).orElse(null);
if (campaignOffice.doesNotHaveAnOfficeInHierarchyWithId(client.getOffice().getId())) {
throw new SmsRuntimeException("error.msg.no.office",
"Office not found for the id");
}
} else {
throw new SmsRuntimeException("error.msg.no.id.attribute",
"Office Id attribute is notfound");
}
}
}
String message = this.smsCampaignWritePlatformCommandHandler
.compileSmsTemplate(smsCampaign.getMessage(), smsCampaign.getCampaignName(), smsParams);
Object mobileNo = smsParams.get("mobileNo");
if (this.smsCampaignValidator.isValidNotificationOrSms(client, smsCampaign, mobileNo)) {
String mobileNumber = null;
if(mobileNo != null){
mobileNumber = mobileNo.toString();
}
SmsMessage smsMessage = SmsMessage.pendingSms(null, null, client, null, message,
mobileNumber, smsCampaign, smsCampaign.isNotification());
this.smsMessageRepository.save(smsMessage);
Collection<SmsMessage> messages = new ArrayList<>();
messages.add(smsMessage);
Map<SmsCampaign, Collection<SmsMessage>> smsDataMap = new HashMap<>();
smsDataMap.put(smsCampaign, messages);
this.smsMessageScheduledJobService.sendTriggeredMessages(smsDataMap);
}
} catch (final IOException e) {
logger.error("smsParams does not contain the key: " + e.getMessage());
} catch (final RuntimeException e) {
logger.debug("Client Office Id and SMS Campaign Office id doesn't match");
}
}
}
}
private void sendSmsForSavingsTransaction(final SavingsAccountTransaction savingsTransaction, boolean isDeposit) {
String campaignName = isDeposit ? "Savings Deposit" : "Savings Withdrawal";
List<SmsCampaign> smsCampaigns = retrieveSmsCampaigns(campaignName);
if (smsCampaigns.size() > 0) {
for (SmsCampaign smsCampaign : smsCampaigns) {
try {
final SavingsAccount savingsAccount = savingsTransaction.getSavingsAccount();
final Client client = savingsAccount.getClient();
HashMap<String, String> campaignParams = new ObjectMapper().readValue(smsCampaign.getParamValue(),
new TypeReference<HashMap<String, String>>() {
});
HashMap<String, Object> smsParams = processSavingsTransactionDataForSms(savingsTransaction, client);
for (String key : campaignParams.keySet()) {
String value = campaignParams.get(key);
String spvalue = null;
boolean spkeycheck = smsParams.containsKey(key);
if (spkeycheck) {
spvalue = smsParams.get(key).toString();
}
if (spkeycheck && !(value.equals("-1") || spvalue.equals(value))) {
if (key.equals("officeId")) {
Office campaignOffice = this.officeRepository.findById(Long.valueOf(value)).orElse(null);
if (campaignOffice.doesNotHaveAnOfficeInHierarchyWithId(client.getOffice().getId())) {
throw new SmsRuntimeException("error.msg.no.office",
"Office not found for the id");
}
} else {
throw new SmsRuntimeException("error.msg.no.id.attribute",
"Office Id attribute is notfound");
}
}
}
String message = this.smsCampaignWritePlatformCommandHandler
.compileSmsTemplate(smsCampaign.getMessage(), smsCampaign.getCampaignName(), smsParams);
Object mobileNo = smsParams.get("mobileNo");
if (this.smsCampaignValidator.isValidNotificationOrSms(client, smsCampaign, mobileNo)) {
String mobileNumber = null;
if(mobileNo != null){
mobileNumber = mobileNo.toString();
}
SmsMessage smsMessage = SmsMessage.pendingSms(null, null, client, null, message,
mobileNumber, smsCampaign, smsCampaign.isNotification());
this.smsMessageRepository.save(smsMessage);
Collection<SmsMessage> messages = new ArrayList<>();
messages.add(smsMessage);
Map<SmsCampaign, Collection<SmsMessage>> smsDataMap = new HashMap<>();
smsDataMap.put(smsCampaign, messages);
this.smsMessageScheduledJobService.sendTriggeredMessages(smsDataMap);
}
} catch (final IOException e) {
logger.error("smsParams does not contain the key: " + e.getMessage());
} catch (final RuntimeException e) {
logger.debug("Client Office Id and SMS Campaign Office id doesn't match");
}
}
}
}
private List<SmsCampaign> retrieveSmsCampaigns(String paramValue){
List<SmsCampaign> smsCampaigns = smsCampaignRepository.findActiveSmsCampaigns("%"+paramValue+"%", SmsCampaignTriggerType.TRIGGERED.getValue());
@@ -337,9 +337,9 @@ public class SmsCampaignDomainServiceImpl implements SmsCampaignDomainService {
smsParams.put("officeId", client.getOffice().getId());
if(client.getStaff() != null) {
smsParams.put("loanOfficerId", client.getStaff().getId());
smsParams.put("loanOfficerId", client.getStaff().getId());
}else {
smsParams.put("loanOfficerId", -1);
smsParams.put("loanOfficerId", -1);
}
smsParams.put("repaymentAmount", loanTransaction.getAmount(loan.getCurrency()));
@@ -347,18 +347,18 @@ public class SmsCampaignDomainServiceImpl implements SmsCampaignDomainService {
smsParams.put("RepaymentTime", loanTransaction.getCreatedDateTime().toLocalTime().toString(timeFormatter));
if(loanTransaction.getPaymentDetail() != null) {
smsParams.put("receiptNumber", loanTransaction.getPaymentDetail().getReceiptNumber());
smsParams.put("receiptNumber", loanTransaction.getPaymentDetail().getReceiptNumber());
}else {
smsParams.put("receiptNumber", -1);
smsParams.put("receiptNumber", -1);
}
return smsParams;
}
private HashMap<String, Object> processSavingsTransactionDataForSms(final SavingsAccountTransaction savingsAccountTransaction, Client client){
// {{savingsId}} {{id}} {{firstname}} {{middlename}} {{lastname}} {{FullName}} {{mobileNo}} {{savingsAccountId}} {{depositAmount}} {{balance}}
//transactionDate
// {{savingsId}} {{id}} {{firstname}} {{middlename}} {{lastname}} {{FullName}} {{mobileNo}} {{savingsAccountId}} {{depositAmount}} {{balance}}
//transactionDate
HashMap<String, Object> smsParams = new HashMap<String, Object>();
SavingsAccount savingsAccount = savingsAccountTransaction.getSavingsAccount() ;
DateTimeFormatter dateFormatter = DateTimeFormat.forPattern("MMM:d:yyyy");
@@ -378,25 +378,25 @@ public class SmsCampaignDomainServiceImpl implements SmsCampaignDomainService {
smsParams.put("savingsTransactionId", savingsAccountTransaction.getId()) ;
if(client.getStaff() != null) {
smsParams.put("loanOfficerId", client.getStaff().getId());
smsParams.put("loanOfficerId", client.getStaff().getId());
}else {
smsParams.put("loanOfficerId", -1);
smsParams.put("loanOfficerId", -1);
}
if(savingsAccountTransaction.getPaymentDetail() != null) {
smsParams.put("receiptNumber", savingsAccountTransaction.getPaymentDetail().getReceiptNumber());
smsParams.put("receiptNumber", savingsAccountTransaction.getPaymentDetail().getReceiptNumber());
}else {
smsParams.put("receiptNumber", -1);
smsParams.put("receiptNumber", -1);
}
return smsParams;
}
private abstract class SmsBusinessEventAdapter implements BusinessEventListner {
@Override
public void businessEventToBeExecuted(Map<BUSINESS_ENTITY, Object> businessEventEntity) {
//Nothing to do
}
@Override
public void businessEventToBeExecuted(Map<BUSINESS_ENTITY, Object> businessEventEntity) {
//Nothing to do
}
}
private class SendSmsOnLoanApproved extends SmsBusinessEventAdapter{
@@ -437,79 +437,79 @@ public class SmsCampaignDomainServiceImpl implements SmsCampaignDomainService {
private class ClientActivatedListener extends SmsBusinessEventAdapter {
@Override
public void businessEventWasExecuted(Map<BUSINESS_ENTITY, Object> businessEventEntity) {
Object entity = businessEventEntity.get(BusinessEventNotificationConstants.BUSINESS_ENTITY.CLIENT);
if(entity instanceof Client) {
notifyClientActivated((Client)entity);
}
}
@Override
public void businessEventWasExecuted(Map<BUSINESS_ENTITY, Object> businessEventEntity) {
Object entity = businessEventEntity.get(BusinessEventNotificationConstants.BUSINESS_ENTITY.CLIENT);
if(entity instanceof Client) {
notifyClientActivated((Client)entity);
}
}
}
private class ClientRejectedListener extends SmsBusinessEventAdapter {
@Override
public void businessEventWasExecuted(Map<BUSINESS_ENTITY, Object> businessEventEntity) {
Object entity = businessEventEntity.get(BusinessEventNotificationConstants.BUSINESS_ENTITY.CLIENT);
if(entity instanceof Client) {
notifyClientRejected((Client)entity);
}
}
@Override
public void businessEventWasExecuted(Map<BUSINESS_ENTITY, Object> businessEventEntity) {
Object entity = businessEventEntity.get(BusinessEventNotificationConstants.BUSINESS_ENTITY.CLIENT);
if(entity instanceof Client) {
notifyClientRejected((Client)entity);
}
}
}
private class SavingsAccountActivatedListener extends SmsBusinessEventAdapter{
@Override
public void businessEventWasExecuted(Map<BUSINESS_ENTITY, Object> businessEventEntity) {
Object entity = businessEventEntity.get(BusinessEventNotificationConstants.BUSINESS_ENTITY.SAVING);
if(entity instanceof SavingsAccount) {
notifySavingsAccountActivated((SavingsAccount)entity);
}
}
@Override
public void businessEventWasExecuted(Map<BUSINESS_ENTITY, Object> businessEventEntity) {
Object entity = businessEventEntity.get(BusinessEventNotificationConstants.BUSINESS_ENTITY.SAVING);
if(entity instanceof SavingsAccount) {
notifySavingsAccountActivated((SavingsAccount)entity);
}
}
}
private class SavingsAccountRejectedListener extends SmsBusinessEventAdapter {
@Override
public void businessEventWasExecuted(Map<BUSINESS_ENTITY, Object> businessEventEntity) {
Object entity = businessEventEntity.get(BusinessEventNotificationConstants.BUSINESS_ENTITY.SAVING);
if(entity instanceof SavingsAccount) {
notifySavingsAccountRejected((SavingsAccount)entity);
}
}
@Override
public void businessEventWasExecuted(Map<BUSINESS_ENTITY, Object> businessEventEntity) {
Object entity = businessEventEntity.get(BusinessEventNotificationConstants.BUSINESS_ENTITY.SAVING);
if(entity instanceof SavingsAccount) {
notifySavingsAccountRejected((SavingsAccount)entity);
}
}
}
private class SavingsAccountTransactionListener extends SmsBusinessEventAdapter {
final boolean isDeposit ;
public SavingsAccountTransactionListener(final boolean isDeposit) {
this.isDeposit = isDeposit ;
}
final boolean isDeposit ;
public SavingsAccountTransactionListener(final boolean isDeposit) {
this.isDeposit = isDeposit ;
}
@Override
public void businessEventWasExecuted(Map<BUSINESS_ENTITY, Object> businessEventEntity) {
Object entity = businessEventEntity.get(BusinessEventNotificationConstants.BUSINESS_ENTITY.SAVINGS_TRANSACTION);
if(entity instanceof SavingsAccountTransaction) {
sendSmsForSavingsTransaction((SavingsAccountTransaction)entity, this.isDeposit);
}
}
@Override
public void businessEventWasExecuted(Map<BUSINESS_ENTITY, Object> businessEventEntity) {
Object entity = businessEventEntity.get(BusinessEventNotificationConstants.BUSINESS_ENTITY.SAVINGS_TRANSACTION);
if(entity instanceof SavingsAccountTransaction) {
sendSmsForSavingsTransaction((SavingsAccountTransaction)entity, this.isDeposit);
}
}
}
/*private abstract class Task implements Runnable {
protected final FineractPlatformTenant tenant;
protected final String reportName ;
private final Object entity ;
public Task(final FineractPlatformTenant tenant, final String reportName, final Object entity) {
protected final FineractPlatformTenant tenant;
protected final String reportName ;
private final Object entity ;
public Task(final FineractPlatformTenant tenant, final String reportName, final Object entity) {
this.tenant = tenant;
this.reportName = reportName ;
this.entity = entity ;
}
}
}*/
}
@@ -232,10 +232,10 @@ public class SmsCampaignWritePlatformServiceJpaImpl implements SmsCampaignWriteP
Client client = this.clientRepositoryWrapper.findOneWithNotFoundDetection(clientId.longValue());
if (this.smsCampaignValidator.isValidNotificationOrSms(client, smsCampaign, mobileNo)) {
// String countryCode = this.smsReadPlatformService.retrieveCountryCode(client.getOffice().getId()).getCountryCode();
String mobileNumber = null;
if(mobileNo != null){
mobileNumber = mobileNo.toString();
}
String mobileNumber = null;
if(mobileNo != null){
mobileNumber = mobileNo.toString();
}
SmsMessage smsMessage = SmsMessage.pendingSms(null, null, client, null, textMessage, mobileNumber,
smsCampaign, smsCampaign.isNotification());
this.smsMessageRepository.save(smsMessage);
@@ -243,7 +243,7 @@ public class SmsCampaignWritePlatformServiceJpaImpl implements SmsCampaignWriteP
}
}
} catch (final IOException e) {
logger.error(e.getMessage());
logger.error(e.getMessage());
}
}
@@ -287,10 +287,10 @@ public class SmsCampaignWritePlatformServiceJpaImpl implements SmsCampaignWriteP
Object mobileNo = entry.get("mobileNo");
if (this.smsCampaignValidator.isValidNotificationOrSms(client, smsCampaign, mobileNo)) {
String mobileNumber = null;
if(mobileNo != null){
mobileNumber = mobileNo.toString();
}
String mobileNumber = null;
if(mobileNo != null){
mobileNumber = mobileNo.toString();
}
SmsMessage smsMessage = SmsMessage.pendingSms(null, null, client, null, textMessage, mobileNumber,
smsCampaign, smsCampaign.isNotification());
smsMessage.setStatusType(SmsMessageStatusType.WAITING_FOR_DELIVERY_REPORT.getValue());
@@ -305,9 +305,9 @@ public class SmsCampaignWritePlatformServiceJpaImpl implements SmsCampaignWriteP
}
}
} catch (final IOException e) {
logger.error(e.getMessage()) ;
logger.error(e.getMessage()) ;
} catch (final RuntimeException e) {
logger.error(e.getMessage()) ;
logger.error(e.getMessage()) ;
}
}
@@ -320,39 +320,39 @@ public class SmsCampaignWritePlatformServiceJpaImpl implements SmsCampaignWriteP
HashMap<String, String> queryParamForRunReport = new ObjectMapper().readValue(smsCampaign.getParamValue(),
new TypeReference<HashMap<String, String>>() {});
campaignParams.put("clientId", client.getId().toString());
queryParamForRunReport.put("clientId", client.getId().toString());
List<HashMap<String, Object>> runReportObject = this
.getRunReportByServiceImpl(campaignParams.get("reportName"), queryParamForRunReport);
campaignParams.put("clientId", client.getId().toString());
queryParamForRunReport.put("clientId", client.getId().toString());
List<HashMap<String, Object>> runReportObject = this
.getRunReportByServiceImpl(campaignParams.get("reportName"), queryParamForRunReport);
if (runReportObject != null && runReportObject.size() > 0) {
for (HashMap<String, Object> entry : runReportObject) {
String textMessage = this.compileSmsTemplate(smsCampaign.getMessage(),
smsCampaign.getCampaignName(), entry);
Object mobileNo = entry.get("mobileNo");
if (runReportObject != null && runReportObject.size() > 0) {
for (HashMap<String, Object> entry : runReportObject) {
String textMessage = this.compileSmsTemplate(smsCampaign.getMessage(),
smsCampaign.getCampaignName(), entry);
Object mobileNo = entry.get("mobileNo");
if (this.smsCampaignValidator.isValidNotificationOrSms(client, smsCampaign, mobileNo)) {
String mobileNumber = null;
if(mobileNo != null){
mobileNumber = mobileNo.toString();
}
SmsMessage smsMessage = SmsMessage.pendingSms(null, null, client, null, textMessage,
mobileNumber, smsCampaign, smsCampaign.isNotification());
smsMessage.setStatusType(SmsMessageStatusType.WAITING_FOR_DELIVERY_REPORT.getValue());
this.smsMessageRepository.save(smsMessage);
Collection<SmsMessage> messages = new ArrayList<>();
messages.add(smsMessage);
Map<SmsCampaign, Collection<SmsMessage>> smsDataMap = new HashMap<>();
smsDataMap.put(smsCampaign, messages);
this.smsMessageScheduledJobService.sendTriggeredMessages(smsDataMap);
}
}
}
if (this.smsCampaignValidator.isValidNotificationOrSms(client, smsCampaign, mobileNo)) {
String mobileNumber = null;
if(mobileNo != null){
mobileNumber = mobileNo.toString();
}
SmsMessage smsMessage = SmsMessage.pendingSms(null, null, client, null, textMessage,
mobileNumber, smsCampaign, smsCampaign.isNotification());
smsMessage.setStatusType(SmsMessageStatusType.WAITING_FOR_DELIVERY_REPORT.getValue());
this.smsMessageRepository.save(smsMessage);
Collection<SmsMessage> messages = new ArrayList<>();
messages.add(smsMessage);
Map<SmsCampaign, Collection<SmsMessage>> smsDataMap = new HashMap<>();
smsDataMap.put(smsCampaign, messages);
this.smsMessageScheduledJobService.sendTriggeredMessages(smsDataMap);
}
}
}
} catch (final IOException e) {
logger.error(e.getMessage()) ;
logger.error(e.getMessage()) ;
} catch (final RuntimeException e) {
logger.error(e.getMessage()) ;
logger.error(e.getMessage()) ;
}
}
@@ -367,36 +367,36 @@ public class SmsCampaignWritePlatformServiceJpaImpl implements SmsCampaignWriteP
queryParamForRunReport.put("savingsId", savingsAccount.getId().toString());
Client client = savingsAccount.getClient() ;
List<HashMap<String, Object>> runReportObject = this
.getRunReportByServiceImpl(campaignParams.get("reportName"), queryParamForRunReport);
List<HashMap<String, Object>> runReportObject = this
.getRunReportByServiceImpl(campaignParams.get("reportName"), queryParamForRunReport);
if (runReportObject != null && runReportObject.size() > 0) {
for (HashMap<String, Object> entry : runReportObject) {
String textMessage = this.compileSmsTemplate(smsCampaign.getMessage(),
smsCampaign.getCampaignName(), entry);
Object mobileNo = entry.get("mobileNo");
if (runReportObject != null && runReportObject.size() > 0) {
for (HashMap<String, Object> entry : runReportObject) {
String textMessage = this.compileSmsTemplate(smsCampaign.getMessage(),
smsCampaign.getCampaignName(), entry);
Object mobileNo = entry.get("mobileNo");
if (this.smsCampaignValidator.isValidNotificationOrSms(client, smsCampaign, mobileNo)) {
String mobileNumber = null;
if(mobileNo != null){
mobileNumber = mobileNo.toString();
}
SmsMessage smsMessage = SmsMessage.pendingSms(null, null, client, null, textMessage,
mobileNumber, smsCampaign, smsCampaign.isNotification());
smsMessage.setStatusType(SmsMessageStatusType.WAITING_FOR_DELIVERY_REPORT.getValue());
this.smsMessageRepository.save(smsMessage);
Collection<SmsMessage> messages = new ArrayList<>();
messages.add(smsMessage);
Map<SmsCampaign, Collection<SmsMessage>> smsDataMap = new HashMap<>();
smsDataMap.put(smsCampaign, messages);
this.smsMessageScheduledJobService.sendTriggeredMessages(smsDataMap);
}
}
}
if (this.smsCampaignValidator.isValidNotificationOrSms(client, smsCampaign, mobileNo)) {
String mobileNumber = null;
if(mobileNo != null){
mobileNumber = mobileNo.toString();
}
SmsMessage smsMessage = SmsMessage.pendingSms(null, null, client, null, textMessage,
mobileNumber, smsCampaign, smsCampaign.isNotification());
smsMessage.setStatusType(SmsMessageStatusType.WAITING_FOR_DELIVERY_REPORT.getValue());
this.smsMessageRepository.save(smsMessage);
Collection<SmsMessage> messages = new ArrayList<>();
messages.add(smsMessage);
Map<SmsCampaign, Collection<SmsMessage>> smsDataMap = new HashMap<>();
smsDataMap.put(smsCampaign, messages);
this.smsMessageScheduledJobService.sendTriggeredMessages(smsDataMap);
}
}
}
} catch (final IOException e) {
logger.error(e.getMessage()) ;
logger.error(e.getMessage()) ;
} catch (final RuntimeException e) {
logger.error(e.getMessage()) ;
logger.error(e.getMessage()) ;
}
}
@@ -76,9 +76,9 @@ public class CodeWritePlatformServiceJpaRepositoryImpl implements CodeWritePlatf
handleCodeDataIntegrityIssues(command, dve.getMostSpecificCause(), dve);
return CommandProcessingResult.empty();
}catch (final PersistenceException ee) {
Throwable throwable = ExceptionUtils.getRootCause(ee.getCause()) ;
handleCodeDataIntegrityIssues(command, throwable, ee);
return CommandProcessingResult.empty();
Throwable throwable = ExceptionUtils.getRootCause(ee.getCause()) ;
handleCodeDataIntegrityIssues(command, throwable, ee);
return CommandProcessingResult.empty();
}
}
@@ -108,9 +108,9 @@ public class CodeWritePlatformServiceJpaRepositoryImpl implements CodeWritePlatf
handleCodeDataIntegrityIssues(command, dve.getMostSpecificCause(), dve);
return CommandProcessingResult.empty();
}catch (final PersistenceException ee) {
Throwable throwable = ExceptionUtils.getRootCause(ee.getCause()) ;
handleCodeDataIntegrityIssues(command, throwable, ee);
return CommandProcessingResult.empty();
Throwable throwable = ExceptionUtils.getRootCause(ee.getCause()) ;
handleCodeDataIntegrityIssues(command, throwable, ee);
return CommandProcessingResult.empty();
}
}
@@ -45,10 +45,10 @@ import com.google.gson.reflect.TypeToken;
public class GlobalConfigurationDataValidator {
private final FromJsonHelper fromApiJsonHelper;
private static final Set<String> UPDATE_CONFIGURATION_DATA_PARAMETERS = new HashSet<>(
Arrays.asList(GlobalConfigurationApiConstant.localeParamName,
GlobalConfigurationApiConstant.dateFormatParamName, GlobalConfigurationApiConstant.ENABLED,
GlobalConfigurationApiConstant.VALUE, GlobalConfigurationApiConstant.DATE_VALUE));
private static final Set<String> UPDATE_CONFIGURATION_DATA_PARAMETERS = new HashSet<>(
Arrays.asList(GlobalConfigurationApiConstant.localeParamName,
GlobalConfigurationApiConstant.dateFormatParamName, GlobalConfigurationApiConstant.ENABLED,
GlobalConfigurationApiConstant.VALUE, GlobalConfigurationApiConstant.DATE_VALUE));
@Autowired
public GlobalConfigurationDataValidator(final FromJsonHelper fromApiJsonHelper) {
@@ -63,29 +63,29 @@ public class GlobalConfigurationDataValidator {
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, UPDATE_CONFIGURATION_DATA_PARAMETERS);
final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors)
.resource(GlobalConfigurationApiConstant.CONFIGURATION_RESOURCE_NAME);
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors)
.resource(GlobalConfigurationApiConstant.CONFIGURATION_RESOURCE_NAME);
final JsonElement element = this.fromApiJsonHelper.parse(json);
if (this.fromApiJsonHelper.parameterExists(GlobalConfigurationApiConstant.ENABLED, element)) {
final boolean enabledBool = this.fromApiJsonHelper
.extractBooleanNamed(GlobalConfigurationApiConstant.ENABLED, element);
baseDataValidator.reset().parameter(GlobalConfigurationApiConstant.ENABLED).value(enabledBool)
.validateForBooleanValue();
}
if (this.fromApiJsonHelper.parameterExists(GlobalConfigurationApiConstant.ENABLED, element)) {
final boolean enabledBool = this.fromApiJsonHelper
.extractBooleanNamed(GlobalConfigurationApiConstant.ENABLED, element);
baseDataValidator.reset().parameter(GlobalConfigurationApiConstant.ENABLED).value(enabledBool)
.validateForBooleanValue();
}
if (this.fromApiJsonHelper.parameterExists(GlobalConfigurationApiConstant.VALUE, element)) {
final Long valueStr = this.fromApiJsonHelper.extractLongNamed(GlobalConfigurationApiConstant.VALUE,
element);
baseDataValidator.reset().parameter(GlobalConfigurationApiConstant.ENABLED).value(valueStr)
.zeroOrPositiveAmount();
}
if (this.fromApiJsonHelper.parameterExists(GlobalConfigurationApiConstant.VALUE, element)) {
final Long valueStr = this.fromApiJsonHelper.extractLongNamed(GlobalConfigurationApiConstant.VALUE,
element);
baseDataValidator.reset().parameter(GlobalConfigurationApiConstant.ENABLED).value(valueStr)
.zeroOrPositiveAmount();
}
if (this.fromApiJsonHelper.parameterExists(GlobalConfigurationApiConstant.DATE_VALUE, element)) {
final LocalDate dateValue = this.fromApiJsonHelper
.extractLocalDateNamed(GlobalConfigurationApiConstant.DATE_VALUE, element);
baseDataValidator.reset().parameter(GlobalConfigurationApiConstant.DATE_VALUE).value(dateValue).notNull();
}
if (this.fromApiJsonHelper.parameterExists(GlobalConfigurationApiConstant.DATE_VALUE, element)) {
final LocalDate dateValue = this.fromApiJsonHelper
.extractLocalDateNamed(GlobalConfigurationApiConstant.DATE_VALUE, element);
baseDataValidator.reset().parameter(GlobalConfigurationApiConstant.DATE_VALUE).value(dateValue).notNull();
}
if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); }
@@ -61,33 +61,33 @@ public class GlobalConfigurationPropertyData {
this.trapDoor = isTrapDoor;
}
public String getName() {
return this.name;
}
public String getName() {
return this.name;
}
public boolean isEnabled() {
return this.enabled;
}
public boolean isEnabled() {
return this.enabled;
}
public Long getValue() {
return this.value;
}
public Long getValue() {
return this.value;
}
public Date getDateValue() {
return this.dateValue;
}
public Date getDateValue() {
return this.dateValue;
}
public Long getId() {
return this.id;
}
public Long getId() {
return this.id;
}
public String getDescription() {
return this.description;
}
public String getDescription() {
return this.description;
}
public boolean isTrapDoor() {
return this.trapDoor;
}
public boolean isTrapDoor() {
return this.trapDoor;
}
}
@@ -232,13 +232,13 @@ public class ConfigurationDomainServiceJpa implements ConfigurationDomainService
return property.getDateValue();
}
@Override
public boolean isPaymnetypeApplicableforDisbursementCharge() {
final String propertyName = "paymenttype-applicable-for-disbursement-charges";
@Override
public boolean isPaymnetypeApplicableforDisbursementCharge() {
final String propertyName = "paymenttype-applicable-for-disbursement-charges";
final GlobalConfigurationPropertyData property = getGlobalConfigurationPropertyData(propertyName);
return property.isEnabled();
}
}
@Override
public boolean isSkippingMeetingOnFirstDayOfMonthEnabled() {
return getGlobalConfigurationPropertyData("skip-repayment-on-first-day-of-month").isEnabled();
@@ -266,19 +266,19 @@ public class ConfigurationDomainServiceJpa implements ConfigurationDomainService
return property.isEnabled();
}
@Override
public boolean isDailyTPTLimitEnabled() {
@Override
public boolean isDailyTPTLimitEnabled() {
final String propertyName = "daily-tpt-limit";
final GlobalConfigurationPropertyData property = getGlobalConfigurationPropertyData(propertyName);
return property.isEnabled();
}
}
@Override
public Long getDailyTPTLimit() {
@Override
public Long getDailyTPTLimit() {
final String propertyName = "daily-tpt-limit";
final GlobalConfigurationPropertyData property = getGlobalConfigurationPropertyData(propertyName);
return property.getValue();
}
}
@Override
public void removeGlobalConfigurationPropertyDataFromCache(final String propertyName) {
@@ -53,22 +53,22 @@ public class ExternalServicePropertiesPK implements Serializable {
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (obj == this) {
return true;
}
if (obj.getClass() != getClass()) {
return false;
}
final ExternalServicePropertiesPK rhs = (ExternalServicePropertiesPK) obj;
return new EqualsBuilder() //
.append(this.externalServiceId, rhs.externalServiceId) //
.append(this.name, rhs.name) //
.isEquals();
}
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (obj == this) {
return true;
}
if (obj.getClass() != getClass()) {
return false;
}
final ExternalServicePropertiesPK rhs = (ExternalServicePropertiesPK) obj;
return new EqualsBuilder() //
.append(this.externalServiceId, rhs.externalServiceId) //
.append(this.name, rhs.name) //
.isEquals();
}
@Override
public int hashCode() {

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