static void createAndAssignProductLossAllowanceAccountIfNecessary()

in service/src/main/java/org/apache/fineract/cn/portfolio/service/internal/command/handler/ProductCommandHandler.java [181:222]


  static void createAndAssignProductLossAllowanceAccountIfNecessary(
      final ProductEntity productEntity,
      final AccountingAdapter accountingAdapter) {
    final Map<String, ProductAccountAssignmentEntity> accountAssignmentEntityMap
        = productEntity.getAccountAssignments().stream()
        .collect(Collectors.toMap(ProductAccountAssignmentEntity::getDesignator, Function.identity()));
    final Optional<ProductAccountAssignmentEntity> productLossAllowanceMapping
        = Optional.ofNullable(accountAssignmentEntityMap.get(AccountDesignators.PRODUCT_LOSS_ALLOWANCE));

    final boolean productLossAccountIsMappedToAccount = productLossAllowanceMapping
        .map(x -> x.getType() == AccountingAdapter.IdentifierType.ACCOUNT)
        .orElse(false);
    if (productLossAccountIsMappedToAccount)
      return; //Already done.

    final boolean productLossAccountIsMappedToLedger = productLossAllowanceMapping
        .map(x -> x.getType() == AccountingAdapter.IdentifierType.LEDGER)
        .orElse(false);
    if (productLossAccountIsMappedToLedger)
      throw ServiceException.conflict("Not ready to enable product ''{0}''.  The account assignment for product loss allowance is mapped to a ledger.",
          productEntity.getIdentifier());

    final String loanPrincipalLedgerMapping
        = Optional.ofNullable(accountAssignmentEntityMap.get(AccountDesignators.CUSTOMER_LOAN_PRINCIPAL))
        .flatMap(x -> {
            if (x.getType() != AccountingAdapter.IdentifierType.LEDGER)
              return Optional.empty();
            else
              return Optional.of(x.getIdentifier());
        })
        .orElseThrow(() ->
            ServiceException.conflict("Not ready to enable product ''{0}''.  The customer loan principal account is not mapped to a ledger.",
                productEntity.getIdentifier()));

    final String accountIdentifier = accountingAdapter.createProductAccountForLedgerAssignment(
        productEntity.getIdentifier(),
        AccountDesignators.PRODUCT_LOSS_ALLOWANCE,
        loanPrincipalLedgerMapping);

    final AccountAssignment productLossAccountAssignment = new AccountAssignment(AccountDesignators.PRODUCT_LOSS_ALLOWANCE, accountIdentifier);
    productEntity.getAccountAssignments().add(ProductMapper.map(productLossAccountAssignment, productEntity));
  }