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

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