You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@fineract.apache.org by "budaidev (via GitHub)" <gi...@apache.org> on 2025/07/15 07:19:13 UTC

[PR] FINERACT-2181: Moneyhelper multitenant configuration fix [fineract]

budaidev opened a new pull request, #4861:
URL: https://github.com/apache/fineract/pull/4861

   ## Description
   
   There were possible rounding issue during the multitenant configuration, when different tenants use different rounding modes. This fix targets to fix that
   
   Ignore if these details are present on the associated [Apache Fineract JIRA ticket](https://github.com/apache/fineract/pull/1284).
   
   ## Checklist
   
   Please make sure these boxes are checked before submitting your pull request - thanks!
   
   - [ ] Write the commit message as per https://github.com/apache/fineract/#pull-requests
   - [ ] Acknowledge that we will not review PRs that are not passing the build _("green")_ - it is your responsibility to get a proposed PR to pass the build, not primarily the project's maintainers.
   - [ ] Create/update unit or integration tests for verifying the changes made.
   - [ ] Follow coding conventions at https://cwiki.apache.org/confluence/display/FINERACT/Coding+Conventions.
   - [ ] Add required Swagger annotation and update API documentation at fineract-provider/src/main/resources/static/legacy-docs/apiLive.htm with details of any API changes
   - [ ] Submission is not a "code dump".  (Large changes can be made "in repository" via a branch.  Ask on the developer mailing list for guidance, if required.)
   
   FYI our guidelines for code reviews are at https://cwiki.apache.org/confluence/display/FINERACT/Code+Review+Guide.
   


-- 
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: commits-unsubscribe@fineract.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] FINERACT-2181: Moneyhelper multitenant configuration fix [fineract]

Posted by "adamsaghy (via GitHub)" <gi...@apache.org>.
adamsaghy commented on code in PR #4861:
URL: https://github.com/apache/fineract/pull/4861#discussion_r2218614351


##########
fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/service/MoneyHelperInitializationService.java:
##########
@@ -0,0 +1,115 @@
+/**
+ * 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.infrastructure.configuration.service;
+
+import java.math.RoundingMode;
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.fineract.infrastructure.configuration.api.GlobalConfigurationConstants;
+import org.apache.fineract.infrastructure.configuration.domain.GlobalConfigurationProperty;
+import org.apache.fineract.infrastructure.configuration.domain.GlobalConfigurationRepositoryWrapper;
+import org.apache.fineract.infrastructure.core.domain.FineractPlatformTenant;
+import org.apache.fineract.infrastructure.core.service.ThreadLocalContextUtil;
+import org.apache.fineract.organisation.monetary.domain.MoneyHelper;
+import org.springframework.stereotype.Service;
+
+/**
+ * Service to initialize MoneyHelper configurations for multi-tenant environments. This service bridges the gap between
+ * global configuration and MoneyHelper's tenant-specific caching.
+ *
+ * Note: MoneyHelper rounding mode is immutable once initialized to maintain data integrity. Updates require application
+ * restart to take effect.
+ */
+@Service
+@Slf4j
+@RequiredArgsConstructor
+public class MoneyHelperInitializationService {
+
+    private final GlobalConfigurationRepositoryWrapper globalConfigurationRepository;
+
+    /**
+     * Initialize MoneyHelper for a specific tenant. This method should be called during tenant setup and whenever
+     * rounding mode configuration changes.
+     *
+     * @param tenant
+     *            the tenant to initialize
+     */
+    public void initializeTenantRoundingMode(FineractPlatformTenant tenant) {
+        if (tenant == null) {
+            throw new IllegalArgumentException("Tenant cannot be null");
+        }
+
+        String tenantIdentifier = tenant.getTenantIdentifier();
+
+        try {
+            // Set tenant context to read configuration
+            ThreadLocalContextUtil.setTenant(tenant);
+
+            // Get rounding mode from configuration with fallback to default
+            int roundingModeValue = getRoundingModeFromConfiguration();
+
+            // Initialize MoneyHelper for this tenant
+            MoneyHelper.initializeTenantRoundingMode(tenantIdentifier, roundingModeValue);
+
+            log.info("MoneyHelper initialized for tenant '{}' with rounding mode: {}", tenantIdentifier, roundingModeValue);
+
+        } catch (Exception e) {
+            log.error("Failed to initialize MoneyHelper for tenant '{}'", tenantIdentifier, e);
+            throw new RuntimeException("Failed to initialize MoneyHelper for tenant: " + tenantIdentifier, e);
+        } finally {
+            // Clear tenant context
+            ThreadLocalContextUtil.clearTenant();
+        }
+    }
+
+    /**
+     * Check if MoneyHelper is initialized for a tenant.
+     *
+     * @param tenantIdentifier
+     *            the tenant identifier
+     * @return true if initialized, false otherwise
+     */
+    public boolean isTenantInitialized(String tenantIdentifier) {
+        return MoneyHelper.isTenantInitialized(tenantIdentifier);
+    }
+
+    /**
+     * Get the rounding mode from configuration with fallback to default. This method safely handles cases where
+     * configuration might not be available.
+     *
+     * @return the rounding mode value
+     */
+    private int getRoundingModeFromConfiguration() {
+        try {
+            GlobalConfigurationProperty roundingModeProperty = globalConfigurationRepository
+                    .findOneByNameWithNotFoundDetection(GlobalConfigurationConstants.ROUNDING_MODE);
+
+            if (roundingModeProperty != null && roundingModeProperty.getValue() != null) {
+                return roundingModeProperty.getValue().intValue();
+            }
+        } catch (Exception e) {
+            log.warn("Failed to read rounding mode from configuration: {}", e.getMessage());

Review Comment:
   I am not a big fan of swallowing this error... 



-- 
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: commits-unsubscribe@fineract.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] FINERACT-2181: Moneyhelper multitenant configuration fix [fineract]

Posted by "adamsaghy (via GitHub)" <gi...@apache.org>.
adamsaghy commented on code in PR #4861:
URL: https://github.com/apache/fineract/pull/4861#discussion_r2218616887


##########
fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/service/MoneyHelperInitializationService.java:
##########
@@ -0,0 +1,115 @@
+/**
+ * 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.infrastructure.configuration.service;
+
+import java.math.RoundingMode;
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.fineract.infrastructure.configuration.api.GlobalConfigurationConstants;
+import org.apache.fineract.infrastructure.configuration.domain.GlobalConfigurationProperty;
+import org.apache.fineract.infrastructure.configuration.domain.GlobalConfigurationRepositoryWrapper;
+import org.apache.fineract.infrastructure.core.domain.FineractPlatformTenant;
+import org.apache.fineract.infrastructure.core.service.ThreadLocalContextUtil;
+import org.apache.fineract.organisation.monetary.domain.MoneyHelper;
+import org.springframework.stereotype.Service;
+
+/**
+ * Service to initialize MoneyHelper configurations for multi-tenant environments. This service bridges the gap between
+ * global configuration and MoneyHelper's tenant-specific caching.
+ *
+ * Note: MoneyHelper rounding mode is immutable once initialized to maintain data integrity. Updates require application
+ * restart to take effect.
+ */
+@Service
+@Slf4j
+@RequiredArgsConstructor
+public class MoneyHelperInitializationService {
+
+    private final GlobalConfigurationRepositoryWrapper globalConfigurationRepository;
+
+    /**
+     * Initialize MoneyHelper for a specific tenant. This method should be called during tenant setup and whenever
+     * rounding mode configuration changes.
+     *
+     * @param tenant
+     *            the tenant to initialize
+     */
+    public void initializeTenantRoundingMode(FineractPlatformTenant tenant) {
+        if (tenant == null) {
+            throw new IllegalArgumentException("Tenant cannot be null");
+        }
+
+        String tenantIdentifier = tenant.getTenantIdentifier();
+
+        try {
+            // Set tenant context to read configuration
+            ThreadLocalContextUtil.setTenant(tenant);
+
+            // Get rounding mode from configuration with fallback to default
+            int roundingModeValue = getRoundingModeFromConfiguration();
+
+            // Initialize MoneyHelper for this tenant
+            MoneyHelper.initializeTenantRoundingMode(tenantIdentifier, roundingModeValue);
+
+            log.info("MoneyHelper initialized for tenant '{}' with rounding mode: {}", tenantIdentifier, roundingModeValue);
+
+        } catch (Exception e) {
+            log.error("Failed to initialize MoneyHelper for tenant '{}'", tenantIdentifier, e);
+            throw new RuntimeException("Failed to initialize MoneyHelper for tenant: " + tenantIdentifier, e);
+        } finally {
+            // Clear tenant context
+            ThreadLocalContextUtil.clearTenant();
+        }
+    }
+
+    /**
+     * Check if MoneyHelper is initialized for a tenant.
+     *
+     * @param tenantIdentifier
+     *            the tenant identifier
+     * @return true if initialized, false otherwise
+     */
+    public boolean isTenantInitialized(String tenantIdentifier) {
+        return MoneyHelper.isTenantInitialized(tenantIdentifier);
+    }
+
+    /**
+     * Get the rounding mode from configuration with fallback to default. This method safely handles cases where
+     * configuration might not be available.
+     *
+     * @return the rounding mode value
+     */
+    private int getRoundingModeFromConfiguration() {
+        try {
+            GlobalConfigurationProperty roundingModeProperty = globalConfigurationRepository
+                    .findOneByNameWithNotFoundDetection(GlobalConfigurationConstants.ROUNDING_MODE);
+
+            if (roundingModeProperty != null && roundingModeProperty.getValue() != null) {
+                return roundingModeProperty.getValue().intValue();
+            }
+        } catch (Exception e) {
+            log.warn("Failed to read rounding mode from configuration: {}", e.getMessage());
+        }
+
+        // Default to HALF_UP if configuration is not available
+        int defaultRoundingMode = RoundingMode.HALF_UP.ordinal();

Review Comment:
   I dont think we should go with default, fallback value, but even if we would, it is inconsistent to use HALF-UP here and HALF-EVEN in the MoneyHelper... :/
   
   If we are unable to fetch the details of it, then let it fails!



-- 
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: commits-unsubscribe@fineract.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] FINERACT-2181: Moneyhelper multitenant configuration fix [fineract]

Posted by "budaidev (via GitHub)" <gi...@apache.org>.
budaidev commented on code in PR #4861:
URL: https://github.com/apache/fineract/pull/4861#discussion_r2211494409


##########
fineract-core/src/main/java/org/apache/fineract/organisation/monetary/domain/MoneyHelper.java:
##########
@@ -22,17 +22,20 @@
 import jakarta.annotation.PostConstruct;
 import java.math.MathContext;
 import java.math.RoundingMode;
+import java.util.concurrent.ConcurrentHashMap;
 import lombok.extern.slf4j.Slf4j;
 import org.apache.fineract.infrastructure.configuration.domain.ConfigurationDomainService;
+import org.apache.fineract.infrastructure.core.domain.FineractPlatformTenant;
+import org.apache.fineract.infrastructure.core.service.ThreadLocalContextUtil;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Component;
 
 @Slf4j
 @Component
 public class MoneyHelper {
 
-    private static RoundingMode roundingMode = null;
-    private static MathContext mathContext;
+    private static final ConcurrentHashMap<String, RoundingMode> roundingModeCache = new ConcurrentHashMap<>();
+    private static final ConcurrentHashMap<String, MathContext> mathContextCache = new ConcurrentHashMap<>();
     public static final int PRECISION = 19;
 
     private static ConfigurationDomainService staticConfigurationDomainService;

Review Comment:
   Agreed, I think a validation could be useful for that use case. Changing the rounding would cause troubles for previous calculation consistency
   



-- 
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: commits-unsubscribe@fineract.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] FINERACT-2181: Moneyhelper multitenant configuration fix [fineract]

Posted by "adamsaghy (via GitHub)" <gi...@apache.org>.
adamsaghy commented on PR #4861:
URL: https://github.com/apache/fineract/pull/4861#issuecomment-3084316604

   @budaidev 
   ```
   /home/runner/work/fineract/fineract/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/api/InternalConfigurationsApiResource.java:34: error: cannot find symbol
   import org.apache.fineract.organisation.monetary.service.MoneyHelperInitializationService;
                                                           ^
     symbol:   class MoneyHelperInitializationService
     location: package org.apache.fineract.organisation.monetary.service
   /home/runner/work/fineract/fineract/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/api/InternalConfigurationsApiResource.java:47: error: cannot find symbol
       private final MoneyHelperInitializationService moneyHelperInitializationService;
                     ^
     symbol:   class MoneyHelperInitializationService
     location: class InternalConfigurationsApiResource
   /home/runner/work/fineract/fineract/fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/api/InternalConfigurationsApiResource.java:42: error: cannot find symbol
   @RequiredArgsConstructor
   ^
     symbol:   class MoneyHelperInitializationService
     location: class InternalConfigurationsApiResource
   3 errors
   2 warnings


-- 
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: commits-unsubscribe@fineract.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] FINERACT-2181: Moneyhelper multitenant configuration fix [fineract]

Posted by "adamsaghy (via GitHub)" <gi...@apache.org>.
adamsaghy merged PR #4861:
URL: https://github.com/apache/fineract/pull/4861


-- 
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: commits-unsubscribe@fineract.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] FINERACT-2181: Moneyhelper multitenant configuration fix [fineract]

Posted by "adamsaghy (via GitHub)" <gi...@apache.org>.
adamsaghy commented on code in PR #4861:
URL: https://github.com/apache/fineract/pull/4861#discussion_r2218636026


##########
fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/service/MoneyHelperStartupInitializationService.java:
##########
@@ -0,0 +1,96 @@
+/**
+ * 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.infrastructure.configuration.service;
+
+import java.util.List;
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.fineract.infrastructure.core.domain.FineractPlatformTenant;
+import org.apache.fineract.infrastructure.core.service.tenant.TenantDetailsService;
+import org.springframework.boot.context.event.ApplicationReadyEvent;
+import org.springframework.context.event.EventListener;
+import org.springframework.core.annotation.Order;
+import org.springframework.stereotype.Service;
+
+/**
+ * Service to initialize MoneyHelper for all tenants during application startup. This service runs after the application
+ * is fully started to ensure all database migrations and tenant configurations are complete.
+ */
+@Service
+@Slf4j
+@RequiredArgsConstructor
+public class MoneyHelperStartupInitializationService {
+
+    private final TenantDetailsService tenantDetailsService;
+    private final MoneyHelperInitializationService moneyHelperInitializationService;
+
+    /**
+     * Initialize MoneyHelper for all tenants after the application is ready. This method runs after
+     * ApplicationReadyEvent to ensure all database migrations and tenant configurations are complete.
+     */
+    @EventListener(ApplicationReadyEvent.class)
+    @Order(1000) // Run after other startup processes
+    public void initializeMoneyHelperForAllTenants() {
+        log.info("Starting MoneyHelper initialization for all tenants...");
+
+        try {
+            List<FineractPlatformTenant> tenants = tenantDetailsService.findAllTenants();
+
+            if (tenants.isEmpty()) {
+                log.warn("No tenants found during MoneyHelper initialization");
+                return;
+            }
+
+            int successCount = 0;
+            int failureCount = 0;
+
+            for (FineractPlatformTenant tenant : tenants) {
+                try {
+                    String tenantIdentifier = tenant.getTenantIdentifier();
+
+                    // Check if already initialized (in case of restart scenarios)
+                    if (moneyHelperInitializationService.isTenantInitialized(tenantIdentifier)) {
+                        log.debug("MoneyHelper already initialized for tenant: {}", tenantIdentifier);
+                        successCount++;
+                        continue;
+                    }
+
+                    // Initialize MoneyHelper for this tenant
+                    moneyHelperInitializationService.initializeTenantRoundingMode(tenant);
+                    successCount++;
+
+                } catch (Exception e) {
+                    failureCount++;
+                    log.error("Failed to initialize MoneyHelper for tenant '{}'", tenant.getTenantIdentifier(), e);
+                }
+            }
+
+            log.info("MoneyHelper initialization completed - Success: {}, Failures: {}, Total: {}", successCount, failureCount,
+                    tenants.size());
+
+            if (failureCount > 0) {
+                log.warn("Some tenants failed MoneyHelper initialization. "
+                        + "These tenants may experience issues with rounding mode configuration.");
+            }
+
+        } catch (Exception e) {
+            log.error("Critical error during MoneyHelper initialization for all tenants", e);

Review Comment:
   Dont swallow the issue...let it fails!



##########
fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/service/MoneyHelperStartupInitializationService.java:
##########
@@ -0,0 +1,96 @@
+/**
+ * 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.infrastructure.configuration.service;
+
+import java.util.List;
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.fineract.infrastructure.core.domain.FineractPlatformTenant;
+import org.apache.fineract.infrastructure.core.service.tenant.TenantDetailsService;
+import org.springframework.boot.context.event.ApplicationReadyEvent;
+import org.springframework.context.event.EventListener;
+import org.springframework.core.annotation.Order;
+import org.springframework.stereotype.Service;
+
+/**
+ * Service to initialize MoneyHelper for all tenants during application startup. This service runs after the application
+ * is fully started to ensure all database migrations and tenant configurations are complete.
+ */
+@Service
+@Slf4j
+@RequiredArgsConstructor
+public class MoneyHelperStartupInitializationService {
+
+    private final TenantDetailsService tenantDetailsService;
+    private final MoneyHelperInitializationService moneyHelperInitializationService;
+
+    /**
+     * Initialize MoneyHelper for all tenants after the application is ready. This method runs after
+     * ApplicationReadyEvent to ensure all database migrations and tenant configurations are complete.
+     */
+    @EventListener(ApplicationReadyEvent.class)
+    @Order(1000) // Run after other startup processes
+    public void initializeMoneyHelperForAllTenants() {
+        log.info("Starting MoneyHelper initialization for all tenants...");
+
+        try {
+            List<FineractPlatformTenant> tenants = tenantDetailsService.findAllTenants();
+
+            if (tenants.isEmpty()) {
+                log.warn("No tenants found during MoneyHelper initialization");
+                return;
+            }
+
+            int successCount = 0;
+            int failureCount = 0;
+
+            for (FineractPlatformTenant tenant : tenants) {
+                try {
+                    String tenantIdentifier = tenant.getTenantIdentifier();
+
+                    // Check if already initialized (in case of restart scenarios)
+                    if (moneyHelperInitializationService.isTenantInitialized(tenantIdentifier)) {
+                        log.debug("MoneyHelper already initialized for tenant: {}", tenantIdentifier);
+                        successCount++;
+                        continue;
+                    }
+
+                    // Initialize MoneyHelper for this tenant
+                    moneyHelperInitializationService.initializeTenantRoundingMode(tenant);
+                    successCount++;
+
+                } catch (Exception e) {
+                    failureCount++;
+                    log.error("Failed to initialize MoneyHelper for tenant '{}'", tenant.getTenantIdentifier(), e);
+                }
+            }
+
+            log.info("MoneyHelper initialization completed - Success: {}, Failures: {}, Total: {}", successCount, failureCount,
+                    tenants.size());
+
+            if (failureCount > 0) {
+                log.warn("Some tenants failed MoneyHelper initialization. "
+                        + "These tenants may experience issues with rounding mode configuration.");
+            }
+
+        } catch (Exception e) {
+            log.error("Critical error during MoneyHelper initialization for all tenants", e);

Review Comment:
   Dont swallow the issue...let it fails!



##########
fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/service/MoneyHelperStartupInitializationService.java:
##########
@@ -0,0 +1,96 @@
+/**
+ * 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.infrastructure.configuration.service;
+
+import java.util.List;
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.fineract.infrastructure.core.domain.FineractPlatformTenant;
+import org.apache.fineract.infrastructure.core.service.tenant.TenantDetailsService;
+import org.springframework.boot.context.event.ApplicationReadyEvent;
+import org.springframework.context.event.EventListener;
+import org.springframework.core.annotation.Order;
+import org.springframework.stereotype.Service;
+
+/**
+ * Service to initialize MoneyHelper for all tenants during application startup. This service runs after the application
+ * is fully started to ensure all database migrations and tenant configurations are complete.
+ */
+@Service
+@Slf4j
+@RequiredArgsConstructor
+public class MoneyHelperStartupInitializationService {
+
+    private final TenantDetailsService tenantDetailsService;
+    private final MoneyHelperInitializationService moneyHelperInitializationService;
+
+    /**
+     * Initialize MoneyHelper for all tenants after the application is ready. This method runs after
+     * ApplicationReadyEvent to ensure all database migrations and tenant configurations are complete.
+     */
+    @EventListener(ApplicationReadyEvent.class)
+    @Order(1000) // Run after other startup processes
+    public void initializeMoneyHelperForAllTenants() {
+        log.info("Starting MoneyHelper initialization for all tenants...");
+
+        try {
+            List<FineractPlatformTenant> tenants = tenantDetailsService.findAllTenants();
+
+            if (tenants.isEmpty()) {
+                log.warn("No tenants found during MoneyHelper initialization");
+                return;
+            }
+
+            int successCount = 0;
+            int failureCount = 0;
+
+            for (FineractPlatformTenant tenant : tenants) {
+                try {
+                    String tenantIdentifier = tenant.getTenantIdentifier();
+
+                    // Check if already initialized (in case of restart scenarios)
+                    if (moneyHelperInitializationService.isTenantInitialized(tenantIdentifier)) {
+                        log.debug("MoneyHelper already initialized for tenant: {}", tenantIdentifier);
+                        successCount++;
+                        continue;
+                    }
+
+                    // Initialize MoneyHelper for this tenant
+                    moneyHelperInitializationService.initializeTenantRoundingMode(tenant);
+                    successCount++;
+
+                } catch (Exception e) {
+                    failureCount++;
+                    log.error("Failed to initialize MoneyHelper for tenant '{}'", tenant.getTenantIdentifier(), e);

Review Comment:
   Dont swallow the issue...let it fails!



-- 
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: commits-unsubscribe@fineract.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] FINERACT-2181: Moneyhelper multitenant configuration fix [fineract]

Posted by "adamsaghy (via GitHub)" <gi...@apache.org>.
adamsaghy commented on code in PR #4861:
URL: https://github.com/apache/fineract/pull/4861#discussion_r2218611750


##########
fineract-core/src/main/java/org/apache/fineract/organisation/monetary/domain/MoneyHelper.java:
##########
@@ -18,54 +18,176 @@
  */
 package org.apache.fineract.organisation.monetary.domain;
 
-import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
-import jakarta.annotation.PostConstruct;
 import java.math.MathContext;
 import java.math.RoundingMode;
+import java.util.concurrent.ConcurrentHashMap;
 import lombok.extern.slf4j.Slf4j;
-import org.apache.fineract.infrastructure.configuration.domain.ConfigurationDomainService;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Component;
+import org.apache.fineract.infrastructure.core.domain.FineractPlatformTenant;
+import org.apache.fineract.infrastructure.core.service.ThreadLocalContextUtil;
 
+/**
+ * Pure utility class for monetary calculations and rounding operations. This class does not depend on Spring components
+ * or configuration services. All rounding modes are initialized at startup and cached per tenant.
+ */
 @Slf4j
-@Component
-public class MoneyHelper {
+public final class MoneyHelper {
 
-    private static RoundingMode roundingMode = null;
-    private static MathContext mathContext;
     public static final int PRECISION = 19;
+    private static final RoundingMode DEFAULT_ROUNDING_MODE = RoundingMode.HALF_EVEN;

Review Comment:
   I am not a big fan of hardcoded "default" values... I would prefer throwing error if it was not set, so it will be blocker if someone tries something nasty!



-- 
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: commits-unsubscribe@fineract.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] FINERACT-2181: Moneyhelper multitenant configuration fix [fineract]

Posted by "adamsaghy (via GitHub)" <gi...@apache.org>.
adamsaghy commented on code in PR #4861:
URL: https://github.com/apache/fineract/pull/4861#discussion_r2209903796


##########
fineract-core/src/main/java/org/apache/fineract/organisation/monetary/domain/MoneyHelper.java:
##########
@@ -22,17 +22,20 @@
 import jakarta.annotation.PostConstruct;
 import java.math.MathContext;
 import java.math.RoundingMode;
+import java.util.concurrent.ConcurrentHashMap;
 import lombok.extern.slf4j.Slf4j;
 import org.apache.fineract.infrastructure.configuration.domain.ConfigurationDomainService;
+import org.apache.fineract.infrastructure.core.domain.FineractPlatformTenant;
+import org.apache.fineract.infrastructure.core.service.ThreadLocalContextUtil;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Component;
 
 @Slf4j
 @Component
 public class MoneyHelper {
 
-    private static RoundingMode roundingMode = null;
-    private static MathContext mathContext;
+    private static final ConcurrentHashMap<String, RoundingMode> roundingModeCache = new ConcurrentHashMap<>();
+    private static final ConcurrentHashMap<String, MathContext> mathContextCache = new ConcurrentHashMap<>();
     public static final int PRECISION = 19;
 
     private static ConfigurationDomainService staticConfigurationDomainService;

Review Comment:
   I was wondering whether we could remove the `ConfigurationDomainService` all together and remove `@Component` also.
   
   This could be a utility class which is instantiated with values during the startup:
   - Not managed bean
   - No any injections
   - Value holder only
   - Once instance got started, for each tenants automatically we set the value
   
   What do you think?



-- 
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: commits-unsubscribe@fineract.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] FINERACT-2181: Moneyhelper multitenant configuration fix [fineract]

Posted by "adamsaghy (via GitHub)" <gi...@apache.org>.
adamsaghy commented on code in PR #4861:
URL: https://github.com/apache/fineract/pull/4861#discussion_r2211062872


##########
fineract-core/src/main/java/org/apache/fineract/organisation/monetary/domain/MoneyHelper.java:
##########
@@ -22,17 +22,20 @@
 import jakarta.annotation.PostConstruct;
 import java.math.MathContext;
 import java.math.RoundingMode;
+import java.util.concurrent.ConcurrentHashMap;
 import lombok.extern.slf4j.Slf4j;
 import org.apache.fineract.infrastructure.configuration.domain.ConfigurationDomainService;
+import org.apache.fineract.infrastructure.core.domain.FineractPlatformTenant;
+import org.apache.fineract.infrastructure.core.service.ThreadLocalContextUtil;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Component;
 
 @Slf4j
 @Component
 public class MoneyHelper {
 
-    private static RoundingMode roundingMode = null;
-    private static MathContext mathContext;
+    private static final ConcurrentHashMap<String, RoundingMode> roundingModeCache = new ConcurrentHashMap<>();
+    private static final ConcurrentHashMap<String, MathContext> mathContextCache = new ConcurrentHashMap<>();
     public static final int PRECISION = 19;
 
     private static ConfigurationDomainService staticConfigurationDomainService;

Review Comment:
   rounding-mode is a trap door configuration, you are not allowed to change once it was set.



-- 
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: commits-unsubscribe@fineract.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] FINERACT-2181: Moneyhelper multitenant configuration fix [fineract]

Posted by "galovics (via GitHub)" <gi...@apache.org>.
galovics commented on code in PR #4861:
URL: https://github.com/apache/fineract/pull/4861#discussion_r2212496759


##########
fineract-core/src/main/java/org/apache/fineract/organisation/monetary/domain/MoneyHelper.java:
##########
@@ -22,17 +22,20 @@
 import jakarta.annotation.PostConstruct;
 import java.math.MathContext;
 import java.math.RoundingMode;
+import java.util.concurrent.ConcurrentHashMap;
 import lombok.extern.slf4j.Slf4j;
 import org.apache.fineract.infrastructure.configuration.domain.ConfigurationDomainService;
+import org.apache.fineract.infrastructure.core.domain.FineractPlatformTenant;
+import org.apache.fineract.infrastructure.core.service.ThreadLocalContextUtil;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Component;
 
 @Slf4j
 @Component
 public class MoneyHelper {
 
-    private static RoundingMode roundingMode = null;
-    private static MathContext mathContext;
+    private static final ConcurrentHashMap<String, RoundingMode> roundingModeCache = new ConcurrentHashMap<>();
+    private static final ConcurrentHashMap<String, MathContext> mathContextCache = new ConcurrentHashMap<>();
     public static final int PRECISION = 19;
 
     private static ConfigurationDomainService staticConfigurationDomainService;

Review Comment:
   good, let's proceed with it then as Adam suggested. Although please put a comment there so anybody coming after us knows why it's only fetched once at startup.



-- 
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: commits-unsubscribe@fineract.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] FINERACT-2181: Moneyhelper multitenant configuration fix [fineract]

Posted by "galovics (via GitHub)" <gi...@apache.org>.
galovics commented on code in PR #4861:
URL: https://github.com/apache/fineract/pull/4861#discussion_r2210992370


##########
fineract-core/src/main/java/org/apache/fineract/organisation/monetary/domain/MoneyHelper.java:
##########
@@ -22,17 +22,20 @@
 import jakarta.annotation.PostConstruct;
 import java.math.MathContext;
 import java.math.RoundingMode;
+import java.util.concurrent.ConcurrentHashMap;
 import lombok.extern.slf4j.Slf4j;
 import org.apache.fineract.infrastructure.configuration.domain.ConfigurationDomainService;
+import org.apache.fineract.infrastructure.core.domain.FineractPlatformTenant;
+import org.apache.fineract.infrastructure.core.service.ThreadLocalContextUtil;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Component;
 
 @Slf4j
 @Component
 public class MoneyHelper {
 
-    private static RoundingMode roundingMode = null;
-    private static MathContext mathContext;
+    private static final ConcurrentHashMap<String, RoundingMode> roundingModeCache = new ConcurrentHashMap<>();
+    private static final ConcurrentHashMap<String, MathContext> mathContextCache = new ConcurrentHashMap<>();
     public static final int PRECISION = 19;
 
     private static ConfigurationDomainService staticConfigurationDomainService;

Review Comment:
   But if we setup the values on startup, the global configuration gets kinda meaningless, doesn't it? Its whole purpose is to be able to dynamically override values in fineract without a redeployment/restart.



-- 
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: commits-unsubscribe@fineract.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] FINERACT-2181: Moneyhelper multitenant configuration fix [fineract]

Posted by "galovics (via GitHub)" <gi...@apache.org>.
galovics commented on code in PR #4861:
URL: https://github.com/apache/fineract/pull/4861#discussion_r2208428637


##########
fineract-core/src/main/java/org/apache/fineract/organisation/monetary/domain/MoneyHelper.java:
##########
@@ -49,23 +52,42 @@ public void initialize() {
     }
 
     public static RoundingMode getRoundingMode() {
-        if (roundingMode == null) {
-            roundingMode = RoundingMode.valueOf(staticConfigurationDomainService.getRoundingMode());
-        }
-        return roundingMode;
+        String tenantId = getTenantIdentifier();
+        return roundingModeCache.computeIfAbsent(tenantId, k -> RoundingMode.valueOf(staticConfigurationDomainService.getRoundingMode()));
     }
 
     public static MathContext getMathContext() {
-        if (mathContext == null) {
-            mathContext = new MathContext(PRECISION, getRoundingMode());
-        }
-        return mathContext;
+        String tenantId = getTenantIdentifier();
+        return mathContextCache.computeIfAbsent(tenantId, k -> new MathContext(PRECISION, getRoundingMode()));
     }
 
     public static void fetchRoundingModeFromGlobalConfig() {
-        roundingMode = RoundingMode.valueOf(staticConfigurationDomainService.getRoundingMode());
-        log.info("Fetch Rounding Mode from Global Config {}", roundingMode.name());
-        mathContext = null;
+        String tenantId = getTenantIdentifier();
+        RoundingMode newRoundingMode = RoundingMode.valueOf(staticConfigurationDomainService.getRoundingMode());
+        roundingModeCache.put(tenantId, newRoundingMode);
+        log.info("Fetch Rounding Mode from Global Config for tenant {}: {}", tenantId, newRoundingMode.name());
+        mathContextCache.remove(tenantId); // Force recreation with new rounding mode
+    }
+
+    private static String getTenantIdentifier() {
+        FineractPlatformTenant tenant = ThreadLocalContextUtil.getTenant();
+        if (tenant != null) {
+            return tenant.getTenantIdentifier();
+        }
+        // Fallback for cases where tenant context is not available
+        return "default";

Review Comment:
   I'd really not hardcode something like this. You can't be sure that there will be a default tenant in the system.
   
   Throw an exception if we think this is an invalid case rather than hiding the problem.



-- 
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: commits-unsubscribe@fineract.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] FINERACT-2181: Moneyhelper multitenant configuration fix [fineract]

Posted by "budaidev (via GitHub)" <gi...@apache.org>.
budaidev commented on code in PR #4861:
URL: https://github.com/apache/fineract/pull/4861#discussion_r2209556571


##########
fineract-core/src/main/java/org/apache/fineract/organisation/monetary/domain/MoneyHelper.java:
##########
@@ -49,23 +52,42 @@ public void initialize() {
     }
 
     public static RoundingMode getRoundingMode() {
-        if (roundingMode == null) {
-            roundingMode = RoundingMode.valueOf(staticConfigurationDomainService.getRoundingMode());
-        }
-        return roundingMode;
+        String tenantId = getTenantIdentifier();
+        return roundingModeCache.computeIfAbsent(tenantId, k -> RoundingMode.valueOf(staticConfigurationDomainService.getRoundingMode()));
     }
 
     public static MathContext getMathContext() {
-        if (mathContext == null) {
-            mathContext = new MathContext(PRECISION, getRoundingMode());
-        }
-        return mathContext;
+        String tenantId = getTenantIdentifier();
+        return mathContextCache.computeIfAbsent(tenantId, k -> new MathContext(PRECISION, getRoundingMode()));
     }
 
     public static void fetchRoundingModeFromGlobalConfig() {
-        roundingMode = RoundingMode.valueOf(staticConfigurationDomainService.getRoundingMode());
-        log.info("Fetch Rounding Mode from Global Config {}", roundingMode.name());
-        mathContext = null;
+        String tenantId = getTenantIdentifier();
+        RoundingMode newRoundingMode = RoundingMode.valueOf(staticConfigurationDomainService.getRoundingMode());
+        roundingModeCache.put(tenantId, newRoundingMode);
+        log.info("Fetch Rounding Mode from Global Config for tenant {}: {}", tenantId, newRoundingMode.name());
+        mathContextCache.remove(tenantId); // Force recreation with new rounding mode
+    }
+
+    private static String getTenantIdentifier() {
+        FineractPlatformTenant tenant = ThreadLocalContextUtil.getTenant();
+        if (tenant != null) {
+            return tenant.getTenantIdentifier();
+        }
+        // Fallback for cases where tenant context is not available
+        return "default";

Review Comment:
   fixed



-- 
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: commits-unsubscribe@fineract.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org