Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@
import org.apache.fineract.baseteller.data.ServicePaymentReceiptData;
import org.apache.fineract.baseteller.data.ServicePaymentRequest;
import org.apache.fineract.baseteller.data.ServicePaymentServiceData;
import org.apache.fineract.baseteller.data.ServicePaymentServiceRegistrationData;
import org.apache.fineract.baseteller.data.ServicePaymentServiceRegistrationRequest;
import org.apache.fineract.baseteller.service.ServicePaymentCatalogWritePlatformService;
import org.apache.fineract.baseteller.service.ServicePaymentReadPlatformService;
import org.apache.fineract.baseteller.service.ServicePaymentWritePlatformService;
import org.apache.fineract.infrastructure.security.service.PlatformSecurityContext;
Expand All @@ -34,6 +37,7 @@ public class ServicePaymentsApiResource {
private final PlatformSecurityContext context;
private final ServicePaymentReadPlatformService readService;
private final ServicePaymentWritePlatformService writeService;
private final ServicePaymentCatalogWritePlatformService catalogService;

@GET
@Path("/services")
Expand All @@ -44,6 +48,23 @@ public List<ServicePaymentServiceData> services() {
return readService.services();
}

@POST
@Path("/services")
@Produces(MediaType.APPLICATION_JSON)
@Operation(
summary = "Register a bill and service payment service",
description =
"Tenant-level catalog administration. Requires CREATE_BASE_TELLER_SERVICE_CATALOG;"
+ " teller payment permissions do not authorize registration. Performs no"
+ " financial posting.")
public ServicePaymentServiceRegistrationData registerService(final String jsonRequestBody) {
context
.authenticatedUser()
.validateHasCreatePermission(ServicePaymentCatalogWritePlatformService.RESOURCE);
return catalogService.register(
GSON.fromJson(jsonRequestBody, ServicePaymentServiceRegistrationRequest.class));
}

@GET
@Path("/clients/{clientId}")
@Produces(MediaType.APPLICATION_JSON)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
/**
* Copyright since 2026 Mifos Initiative
*
* <p>This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy
* of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package org.apache.fineract.baseteller.data;

import java.math.BigDecimal;
import java.time.OffsetDateTime;

/** Persisted service configuration returned after an authoritative registration. */
public record ServicePaymentServiceRegistrationData(
Long id,
String code,
String name,
boolean active,
String currencyCode,
ServicePaymentCommissionType commissionType,
BigDecimal commissionValue,
BigDecimal commissionVatRate,
Long cashGlAccountId,
Long settlementGlAccountId,
Long commissionGlAccountId,
Long vatGlAccountId,
Long createdBy,
OffsetDateTime createdOnUtc) {}
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
/**
* Copyright since 2026 Mifos Initiative
*
* <p>This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy
* of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package org.apache.fineract.baseteller.data;

import java.math.BigDecimal;

/**
* Administrative registration of one {@code m_service_payment_service} row. Percentages are
* expressed in percent units (2.5 means 2.5%), exactly as {@code ServicePaymentCalculator} applies
* them. A null {@code active} registers an active service.
*/
public record ServicePaymentServiceRegistrationRequest(
String code,
String name,
Boolean active,
String currencyCode,
ServicePaymentCommissionType commissionType,
BigDecimal commissionValue,
BigDecimal commissionVatRate,
Long cashGlAccountId,
Long settlementGlAccountId,
Long commissionGlAccountId,
Long vatGlAccountId) {}
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
/**
* Copyright since 2026 Mifos Initiative
*
* <p>This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy
* of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package org.apache.fineract.baseteller.service;

import org.apache.fineract.baseteller.data.ServicePaymentServiceRegistrationData;
import org.apache.fineract.baseteller.data.ServicePaymentServiceRegistrationRequest;

/** Tenant-level administration of the bill and service payment service catalog. */
public interface ServicePaymentCatalogWritePlatformService {

/** Permission entity checked at the write boundary; distinct from teller payment permissions. */
String RESOURCE = "BASE_TELLER_SERVICE_CATALOG";

ServicePaymentServiceRegistrationData register(ServicePaymentServiceRegistrationRequest request);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,238 @@
/**
* Copyright since 2026 Mifos Initiative
*
* <p>This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy
* of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package org.apache.fineract.baseteller.service;

import java.sql.Timestamp;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import lombok.RequiredArgsConstructor;
import org.apache.fineract.baseteller.data.ServicePaymentCommissionType;
import org.apache.fineract.baseteller.data.ServicePaymentServiceRegistrationData;
import org.apache.fineract.baseteller.data.ServicePaymentServiceRegistrationRequest;
import org.apache.fineract.baseteller.validation.ServicePaymentCatalogValidator;
import org.apache.fineract.baseteller.validation.ServicePaymentCatalogValidator.GlAccount;
import org.apache.fineract.baseteller.validation.ServicePaymentCatalogValidator.Registration;
import org.apache.fineract.infrastructure.core.data.ApiParameterError;
import org.apache.fineract.infrastructure.security.service.PlatformSecurityContext;
import org.apache.fineract.useradministration.domain.AppUser;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
* Registers services in the existing WEB-1236 catalog ({@code m_service_payment_service}).
*
* <p>Registration only writes catalog configuration. It never posts journals or cashier
* transactions, and it cannot change historical payments, which keep their own service snapshot and
* journal references for receipts and reversals.
*/
@Service
@RequiredArgsConstructor
public class ServicePaymentCatalogWritePlatformServiceImpl
implements ServicePaymentCatalogWritePlatformService {

private final NamedParameterJdbcTemplate jdbc;
private final PlatformSecurityContext context;
private final ServicePaymentCatalogValidator validator;

@Override
@Transactional
public ServicePaymentServiceRegistrationData register(
final ServicePaymentServiceRegistrationRequest request) {
final AppUser user = context.authenticatedUser();
user.validateHasCreatePermission(RESOURCE);
final Registration registration = validator.validate(request);

final List<ApiParameterError> errors = new ArrayList<>();
if (codeExists(registration.code())) {
errors.add(duplicate());
}
final Integer decimalPlaces = enabledCurrencyDecimalPlaces(registration.currencyCode());
if (decimalPlaces == null) {
errors.add(
ServicePaymentCatalogValidator.error(
"currencyCode",
"not.enabled",
"Currency is not enabled for this organization.",
registration.currencyCode()));
} else {
errors.addAll(validator.currencyPrecisionErrors(registration, decimalPlaces));
if (registration.active()) {
errors.addAll(prerequisiteErrors(registration.currencyCode()));
}
}
errors.addAll(validator.accountErrors(registration, accounts(registration)));
if (!errors.isEmpty()) throw ServicePaymentCatalogValidator.failure(errors);

try {
insert(registration, user);
} catch (DuplicateKeyException concurrentDuplicate) {
// The unique code constraint is the final arbiter when registrations race.
throw ServicePaymentCatalogValidator.failure(List.of(duplicate()));
} catch (DataIntegrityViolationException changedReference) {
throw ServicePaymentCatalogValidator.failure(
List.of(
ServicePaymentCatalogValidator.error(
"request",
"reference.changed",
"A referenced currency or GL account changed during registration.")));
}
return retrieve(registration.code());
}

private boolean codeExists(final String code) {
final Long count =
jdbc.queryForObject(
"SELECT COUNT(*) FROM m_service_payment_service WHERE UPPER(code)=:code",
Map.of("code", code),
Long.class);
return count != null && count > 0;
}

/** Uses the same {@code m_currency} precision that payment quotes apply. */
private Integer enabledCurrencyDecimalPlaces(final String currency) {
final List<Integer> rows =
jdbc.query(
"SELECT c.decimal_places FROM m_currency c JOIN m_organisation_currency o"
+ " ON o.code=c.code WHERE c.code=:currency",
Map.of("currency", currency),
(rs, row) -> rs.getInt(1));
return rows.isEmpty() ? null : rows.getFirst();
}

/**
* An active service must be payable immediately: tellers need at least one active denomination
* for its currency and at least one cash payment type. Neither is generated here; both belong to
* existing shared Base Teller configuration.
*/
private List<ApiParameterError> prerequisiteErrors(final String currency) {
final List<ApiParameterError> errors = new ArrayList<>();
final Long denominations =
jdbc.queryForObject(
"SELECT COUNT(*) FROM m_service_payment_denomination"
+ " WHERE UPPER(currency_code)=:currency AND active=true AND value>0",
Map.of("currency", currency),
Long.class);
if (denominations == null || denominations == 0) {
errors.add(
ServicePaymentCatalogValidator.error(
"currencyCode",
"denominations.missing",
"No active cash denominations are configured for this currency.",
currency));
}
final Long cashPaymentTypes =
jdbc.queryForObject(
"SELECT COUNT(*) FROM m_payment_type WHERE is_cash_payment=true", Map.of(), Long.class);
if (cashPaymentTypes == null || cashPaymentTypes == 0) {
errors.add(
ServicePaymentCatalogValidator.error(
"active",
"cash.payment.type.missing",
"No cash payment type is configured, so an active service could not be paid."));
}
return errors;
}

private Map<Long, GlAccount> accounts(final Registration registration) {
final Set<Long> ids =
Stream.of(
registration.cashGlAccountId(),
registration.settlementGlAccountId(),
registration.commissionGlAccountId(),
registration.vatGlAccountId())
.filter(id -> id != null)
.collect(Collectors.toCollection(LinkedHashSet::new));
if (ids.isEmpty()) return Map.of();
return jdbc
.query(
"SELECT id,classification_enum,account_usage,disabled,manual_journal_entries_allowed"
+ " FROM acc_gl_account WHERE id IN (:ids)",
Map.of("ids", ids),
(rs, row) ->
new GlAccount(
rs.getLong("id"),
rs.getInt("classification_enum"),
rs.getInt("account_usage"),
rs.getBoolean("disabled"),
rs.getBoolean("manual_journal_entries_allowed")))
.stream()
.collect(Collectors.toMap(GlAccount::id, Function.identity()));
}

private void insert(final Registration registration, final AppUser user) {
final Map<String, Object> values = new HashMap<>();
values.put("code", registration.code());
values.put("name", registration.name());
values.put("active", registration.active());
values.put("currency", registration.currencyCode());
values.put("type", registration.commissionType().name());
values.put("commission", registration.commissionValue());
values.put("vat", registration.commissionVatRate());
values.put("cash", registration.cashGlAccountId());
values.put("settlement", registration.settlementGlAccountId());
values.put("commissionGl", registration.commissionGlAccountId());
values.put("vatGl", registration.vatGlAccountId());
values.put("createdBy", user.getId());
jdbc.update(
"INSERT INTO m_service_payment_service"
+ " (code,name,active,currency_code,commission_type,commission_value,commission_vat_rate,"
+ "cash_gl_account_id,settlement_gl_account_id,commission_gl_account_id,vat_gl_account_id,"
+ "created_by,created_on_utc) VALUES (:code,:name,:active,:currency,:type,:commission,:vat,"
+ ":cash,:settlement,:commissionGl,:vatGl,:createdBy,CURRENT_TIMESTAMP)",
Comment thread
AnvayKharb marked this conversation as resolved.
Resolved
values);
}

private ServicePaymentServiceRegistrationData retrieve(final String code) {
return jdbc.queryForObject(
"SELECT id,code,name,active,currency_code,commission_type,commission_value,"
+ "commission_vat_rate,cash_gl_account_id,settlement_gl_account_id,"
+ "commission_gl_account_id,vat_gl_account_id,created_by,created_on_utc"
+ " FROM m_service_payment_service WHERE code=:code",
Map.of("code", code),
(rs, row) ->
new ServicePaymentServiceRegistrationData(
rs.getLong("id"),
rs.getString("code"),
rs.getString("name"),
rs.getBoolean("active"),
rs.getString("currency_code"),
ServicePaymentCommissionType.valueOf(rs.getString("commission_type")),
rs.getBigDecimal("commission_value"),
rs.getBigDecimal("commission_vat_rate"),
nullableLong(rs.getObject("cash_gl_account_id")),
nullableLong(rs.getObject("settlement_gl_account_id")),
nullableLong(rs.getObject("commission_gl_account_id")),
nullableLong(rs.getObject("vat_gl_account_id")),
nullableLong(rs.getObject("created_by")),
offset(rs.getTimestamp("created_on_utc"))));
}

private static ApiParameterError duplicate() {
return ServicePaymentCatalogValidator.error(
"code", "duplicate", "A service with this code is already registered.");
}

private static Long nullableLong(final Object value) {
return value == null ? null : ((Number) value).longValue();
}

private static OffsetDateTime offset(final Timestamp value) {
return value == null ? null : value.toInstant().atOffset(ZoneOffset.UTC);
}
}
Loading
Loading