sayhaed commented on code in PR #4885:
URL: https://github.com/apache/fineract/pull/4885#discussion_r2279477756


##########
fineract-savings/src/main/java/org/apache/fineract/portfolio/savings/data/SavingsProductDataValidator.java:
##########
@@ -89,7 +90,7 @@ public class SavingsProductDataValidator {
     private final SavingsProductAccountingDataValidator 
savingsProductAccountingDataValidator;
     private static final Set<String> SAVINGS_PRODUCT_REQUEST_DATA_PARAMETERS = 
new HashSet<>(Arrays.asList(
             SavingsApiConstants.localeParamName, 
SavingsApiConstants.monthDayFormatParamName, nameParamName, shortNameParamName,
-            descriptionParamName, currencyCodeParamName, 
digitsAfterDecimalParamName, inMultiplesOfParamName,
+            interestReceivableAccount, descriptionParamName, 
currencyCodeParamName, digitsAfterDecimalParamName, inMultiplesOfParamName,

Review Comment:
   Done, thanks for the suggestion. I moved INTEREST_RECEIVABLE to be grouped 
with the other GL account fields. The change is applied.



##########
fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/SavingsAccrualWritePlatformServiceImpl.java:
##########
@@ -0,0 +1,184 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.fineract.portfolio.savings.service;
+
+import java.math.BigDecimal;
+import java.math.MathContext;
+import java.time.LocalDate;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.function.Function;
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+import 
org.apache.fineract.infrastructure.configuration.domain.ConfigurationDomainService;
+import org.apache.fineract.infrastructure.core.domain.LocalDateInterval;
+import org.apache.fineract.infrastructure.core.service.DateUtils;
+import org.apache.fineract.infrastructure.core.service.MathUtil;
+import org.apache.fineract.infrastructure.jobs.exception.JobExecutionException;
+import org.apache.fineract.organisation.monetary.domain.MonetaryCurrency;
+import org.apache.fineract.organisation.monetary.domain.Money;
+import org.apache.fineract.organisation.monetary.domain.MoneyHelper;
+import 
org.apache.fineract.portfolio.savings.SavingsCompoundingInterestPeriodType;
+import 
org.apache.fineract.portfolio.savings.SavingsInterestCalculationDaysInYearType;
+import org.apache.fineract.portfolio.savings.SavingsInterestCalculationType;
+import org.apache.fineract.portfolio.savings.SavingsPostingInterestPeriodType;
+import org.apache.fineract.portfolio.savings.data.SavingsAccrualData;
+import org.apache.fineract.portfolio.savings.domain.SavingsAccount;
+import org.apache.fineract.portfolio.savings.domain.SavingsAccountAssembler;
+import 
org.apache.fineract.portfolio.savings.domain.SavingsAccountRepositoryWrapper;
+import org.apache.fineract.portfolio.savings.domain.SavingsAccountTransaction;
+import org.apache.fineract.portfolio.savings.domain.SavingsHelper;
+import 
org.apache.fineract.portfolio.savings.domain.interest.CompoundInterestValues;
+import org.apache.fineract.portfolio.savings.domain.interest.PostingPeriod;
+import 
org.apache.fineract.portfolio.savings.domain.interest.SavingsAccountTransactionDetailsForPostingPeriod;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+@Slf4j
+@Service
+@RequiredArgsConstructor
+public class SavingsAccrualWritePlatformServiceImpl implements 
SavingsAccrualWritePlatformService {
+
+    private final SavingsAccountReadPlatformService 
savingsAccountReadPlatformService;
+    private final SavingsAccountAssembler savingsAccountAssembler;
+    private final SavingsAccountRepositoryWrapper savingsAccountRepository;
+    private final SavingsHelper savingsHelper;
+    private final ConfigurationDomainService configurationDomainService;
+    private final SavingsAccountDomainService savingsAccountDomainService;
+
+    @Transactional
+    @Override
+    public void addAccrualEntries(LocalDate tillDate) throws 
JobExecutionException {
+        final Collection<SavingsAccrualData> savingsAccrualData = 
savingsAccountReadPlatformService.retrievePeriodicAccrualData(tillDate,
+                null);
+        final Integer financialYearBeginningMonth = 
configurationDomainService.retrieveFinancialYearBeginningMonth();
+        final boolean isSavingsInterestPostingAtCurrentPeriodEnd = 
this.configurationDomainService
+                .isSavingsInterestPostingAtCurrentPeriodEnd();
+        final MathContext mc = MoneyHelper.getMathContext();
+
+        List<Throwable> errors = new ArrayList<>();
+        for (SavingsAccrualData savingsAccrual : savingsAccrualData) {
+            try {
+                if (savingsAccrual.getIsAllowOverdraft()) {
+                    if (!savingsAccrual.getIsTypeInterestReceivable()) {
+                        continue;
+                    }
+                }
+                SavingsAccount savingsAccount = 
savingsAccountAssembler.assembleFrom(savingsAccrual.getId(), false);
+                LocalDate fromDate = savingsAccrual.getAccruedTill();
+                if (fromDate == null) {
+                    fromDate = savingsAccount.getActivationDate();
+                }
+                log.debug("Processing savings account {} from date {} till 
date {}", savingsAccrual.getAccountNo(), fromDate, tillDate);
+                addAccrualTransactions(savingsAccount, fromDate, tillDate, 
financialYearBeginningMonth,
+                        isSavingsInterestPostingAtCurrentPeriodEnd, mc, null);
+            } catch (Exception e) {
+                log.error("Failed to add accrual transaction for savings {} : 
{}", savingsAccrual.getAccountNo(), e.getMessage());
+                errors.add(e.getCause());
+            }
+        }
+        if (!errors.isEmpty()) {
+            throw new JobExecutionException(errors);
+        }
+    }
+
+    private void addAccrualTransactions(SavingsAccount savingsAccount, final 
LocalDate fromDate, final LocalDate tillDate,
+            final Integer financialYearBeginningMonth, final boolean 
isSavingsInterestPostingAtCurrentPeriodEnd, final MathContext mc,
+            final Function<LocalDate, String> refNoProvider) {
+        final Set<Long> existingTransactionIds = new HashSet<>();
+        final Set<Long> existingReversedTransactionIds = new HashSet<>();
+
+        
existingTransactionIds.addAll(savingsAccount.findExistingTransactionIds());
+        
existingReversedTransactionIds.addAll(savingsAccount.findExistingReversedTransactionIds());
+
+        List<LocalDate> postedAsOnTransactionDates = 
savingsAccount.getManualPostingDates();
+        final SavingsPostingInterestPeriodType postingPeriodType = 
SavingsPostingInterestPeriodType
+                .fromInt(savingsAccount.getInterestCalculationType());
+
+        final SavingsCompoundingInterestPeriodType compoundingPeriodType = 
SavingsCompoundingInterestPeriodType
+                .fromInt(savingsAccount.getInterestPostingPeriodType());
+
+        final SavingsInterestCalculationDaysInYearType daysInYearType = 
SavingsInterestCalculationDaysInYearType
+                
.fromInt(savingsAccount.getInterestCalculationDaysInYearType());
+
+        final List<LocalDateInterval> postingPeriodIntervals = 
this.savingsHelper.determineInterestPostingPeriods(fromDate, tillDate,
+                postingPeriodType, financialYearBeginningMonth, 
postedAsOnTransactionDates);
+
+        final List<PostingPeriod> allPostingPeriods = new ArrayList<>();
+        final MonetaryCurrency currency = savingsAccount.getCurrency();
+        Money periodStartingBalance = Money.zero(currency);
+
+        final SavingsInterestCalculationType interestCalculationType = 
SavingsInterestCalculationType
+                .fromInt(savingsAccount.getInterestCalculationType());
+        final BigDecimal interestRateAsFraction = 
savingsAccount.getEffectiveInterestRateAsFractionAccrual(mc, tillDate);
+        final Collection<Long> interestPostTransactions = 
this.savingsHelper.fetchPostInterestTransactionIds(savingsAccount.getId());
+        boolean isInterestTransfer = false;
+        final Money minBalanceForInterestCalculation = Money.of(currency, 
savingsAccount.getMinBalanceForInterestCalculation());
+        List<SavingsAccountTransactionDetailsForPostingPeriod> 
savingsAccountTransactionDetailsForPostingPeriodList = savingsAccount
+                .toSavingsAccountTransactionDetailsForPostingPeriodList();
+        for (final LocalDateInterval periodInterval : postingPeriodIntervals) {
+            if (DateUtils.isDateInTheFuture(periodInterval.endDate())) {
+                continue;
+            }
+            final boolean isUserPosting = 
postedAsOnTransactionDates.contains(periodInterval.endDate());
+
+            final PostingPeriod postingPeriod = 
PostingPeriod.createFrom(periodInterval, periodStartingBalance,
+                    savingsAccountTransactionDetailsForPostingPeriodList, 
currency, compoundingPeriodType, interestCalculationType,
+                    interestRateAsFraction, daysInYearType.getValue(), 
tillDate, interestPostTransactions, isInterestTransfer,
+                    minBalanceForInterestCalculation, 
isSavingsInterestPostingAtCurrentPeriodEnd, isUserPosting,
+                    financialYearBeginningMonth);
+
+            postingPeriod.setOverdraftInterestRateAsFraction(

Review Comment:
   Done, thanks. I've added the MathContext



##########
fineract-savings/src/main/java/org/apache/fineract/portfolio/savings/domain/SavingsAccount.java:
##########
@@ -337,6 +338,9 @@ public class SavingsAccount extends 
AbstractAuditableWithUTCDateTimeCustom<Long>
     @JoinColumn(name = "tax_group_id")
     private TaxGroup taxGroup;
 
+    @Column(name = "accrued_till_date")
+    protected LocalDate accruedTillDate;

Review Comment:
   I've changed it, thanks 



##########
integration-tests/src/test/java/org/apache/fineract/integrationtests/SavingsAccrualAccountingIntegrationTest.java:
##########
@@ -0,0 +1,208 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.fineract.integrationtests;
+
+import io.restassured.builder.RequestSpecBuilder;
+import io.restassured.builder.ResponseSpecBuilder;
+import io.restassured.http.ContentType;
+import io.restassured.specification.RequestSpecification;
+import io.restassured.specification.ResponseSpecification;
+import java.math.BigDecimal;
+import java.time.LocalDate;
+import java.time.format.DateTimeFormatter;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import org.apache.fineract.integrationtests.common.ClientHelper;
+import org.apache.fineract.integrationtests.common.CommonConstants;
+import org.apache.fineract.integrationtests.common.SchedulerJobHelper;
+import org.apache.fineract.integrationtests.common.Utils;
+import org.apache.fineract.integrationtests.common.accounting.Account;
+import org.apache.fineract.integrationtests.common.accounting.AccountHelper;
+import 
org.apache.fineract.integrationtests.common.accounting.JournalEntryHelper;
+import 
org.apache.fineract.integrationtests.common.savings.SavingsAccountHelper;
+import 
org.apache.fineract.integrationtests.common.savings.SavingsProductHelper;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class SavingsAccrualAccountingIntegrationTest {
+
+    private static final Logger LOG = 
LoggerFactory.getLogger(SavingsAccrualAccountingIntegrationTest.class);
+    private ResponseSpecification responseSpec;
+    private RequestSpecification requestSpec;
+    private SavingsAccountHelper savingsAccountHelper;
+    private SchedulerJobHelper schedulerJobHelper;
+    private JournalEntryHelper journalEntryHelper;
+    private AccountHelper accountHelper;
+
+    @BeforeEach
+    public void setup() {
+        Utils.initializeRESTAssured();
+        this.requestSpec = new 
RequestSpecBuilder().setContentType(ContentType.JSON).build();
+        this.requestSpec.header("Authorization", "Basic " + 
Utils.loginIntoServerAndGetBase64EncodedAuthenticationKey());
+        this.responseSpec = new 
ResponseSpecBuilder().expectStatusCode(200).build();
+        this.savingsAccountHelper = new SavingsAccountHelper(this.requestSpec, 
this.responseSpec);
+        this.schedulerJobHelper = new SchedulerJobHelper(this.requestSpec);
+        this.journalEntryHelper = new JournalEntryHelper(this.requestSpec, 
this.responseSpec);
+        this.accountHelper = new AccountHelper(this.requestSpec, 
this.responseSpec);
+    }
+
+    @Test
+    public void testPositiveAccrualPostsCorrectJournalEntries() {
+        // --- ARRANGE ---
+        LOG.info("------------------------- INITIATING POSITIVE ACCRUAL 
ACCOUNTING TEST -------------------------");
+        final int daysToSubtract = 10;
+
+        // 1. Create GL accounts
+        final Account assetAccount = this.accountHelper.createAssetAccount();
+        final Account liabilityAccount = 
this.accountHelper.createLiabilityAccount();
+        final Account incomeAccount = this.accountHelper.createIncomeAccount();
+        final Account expenseAccount = 
this.accountHelper.createExpenseAccount();
+
+        // 2. Create savings product
+        final String interestRate = "10.0";
+        final Integer savingsProductId = 
this.savingsAccountHelper.createSavingsProductWithAccrualAccounting(assetAccount,
 liabilityAccount,
+                incomeAccount, expenseAccount, interestRate);
+        Assertions.assertNotNull(savingsProductId, "Failed to create savings 
product.");
+
+        // 3. Create client and savings account
+        final Integer clientId = ClientHelper.createClient(this.requestSpec, 
this.responseSpec, "01 January 2020");
+        final LocalDate startDate = 
LocalDate.now(Utils.getZoneIdOfTenant()).minusDays(daysToSubtract);
+        final String startDateString = DateTimeFormatter.ofPattern("dd MMMM 
yyyy", Locale.US).format(startDate);
+        final Integer savingsAccountId = 
this.savingsAccountHelper.applyForSavingsApplicationOnDate(clientId, 
savingsProductId,
+                SavingsAccountHelper.ACCOUNT_TYPE_INDIVIDUAL, startDateString);
+        this.savingsAccountHelper.approveSavingsOnDate(savingsAccountId, 
startDateString);
+        this.savingsAccountHelper.activateSavings(savingsAccountId, 
startDateString);
+        this.savingsAccountHelper.depositToSavingsAccount(savingsAccountId, 
"1000", startDateString, CommonConstants.RESPONSE_RESOURCE_ID);
+
+        // --- ACT ---
+        schedulerJobHelper.executeAndAwaitJob("Add Accrual Transactions For 
Savings");
+
+        // --- ASSERT ---
+        List<HashMap> accrualTransactions = 
getAccrualTransactions(savingsAccountId);
+        Assertions.assertFalse(accrualTransactions.isEmpty(), "No accrual 
transactions were found.");
+
+        Number firstTransactionIdNumber = (Number) 
accrualTransactions.get(0).get("id");
+        ArrayList<HashMap> journalEntries = 
journalEntryHelper.getJournalEntriesByTransactionId("S" + 
firstTransactionIdNumber.intValue());
+        Assertions.assertFalse(journalEntries.isEmpty(), "No journal entries 
found for positive accrual.");
+
+        boolean debitFound = false;
+        boolean creditFound = false;
+        for (Map<String, Object> entry : journalEntries) {
+            String entryType = (String) ((HashMap) 
entry.get("entryType")).get("value");
+            Integer accountId = ((Number) entry.get("glAccountId")).intValue();
+            if ("DEBIT".equals(entryType) && 
accountId.equals(expenseAccount.getAccountID())) {
+                debitFound = true;
+            }
+            if ("CREDIT".equals(entryType) && 
accountId.equals(liabilityAccount.getAccountID())) {
+                creditFound = true;
+            }
+        }
+
+        Assertions.assertTrue(debitFound, "DEBIT to Expense Account not found 
for positive accrual.");
+        Assertions.assertTrue(creditFound, "CREDIT to Liability Account not 
found for positive accrual.");
+    }
+
+    @Test
+    public void testNegativeAccrualPostsCorrectJournalEntries() {

Review Comment:
   You're right. This test focuses only on the accounting side. The actual 
amount calculation is covered in SavingsAccrualIntegrationTest.



##########
fineract-savings/src/main/java/org/apache/fineract/portfolio/savings/service/SavingsAccountReadPlatformService.java:
##########
@@ -69,4 +71,6 @@ List<SavingsAccountData> 
retrieveAllSavingsDataForInterestPosting(boolean backda
     List<SavingsAccountTransactionData> 
retrieveAllTransactionData(List<String> refNo);
 
     Long retrieveAccountIdByExternalId(ExternalId externalId);
+
+    Collection<SavingsAccrualData> retrievePeriodicAccrualData(LocalDate 
tillDate, SavingsAccount savings);

Review Comment:
   We change it to a list, thanks 



##########
integration-tests/src/test/java/org/apache/fineract/integrationtests/common/SchedulerJobHelper.java:
##########
@@ -271,7 +271,7 @@ public <T extends Serializable> void executeAndAwaitJob(T 
jobParam, Consumer<T>
     }
 
     private void awaitJob(Instant beforeExecuteTime, 
Supplier<Callable<Map<String, String>>> retrieveLastRunHistory) {
-        final Duration timeout = Duration.ofMinutes(2);
+        final Duration timeout = Duration.ofMinutes(5);

Review Comment:
   Changed 



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to