Search in sources :

Example 1 with JsonCommand

use of org.apache.fineract.infrastructure.core.api.JsonCommand in project fineract by apache.

the class ThitsaWorksCreditBureauIntegrationWritePlatformServiceImpl method createToken.

@Transactional
@Override
public CreditBureauToken createToken(Long bureauID) {
    CreditBureauToken creditBureauToken = this.tokenRepositoryWrapper.getToken();
    // check the expiry date of the previous token.
    if (creditBureauToken != null) {
        Date current = new Date();
        Date getExpiryDate = creditBureauToken.getTokenExpiryDate();
        if (getExpiryDate.before(current)) {
            this.tokenRepositoryWrapper.delete(creditBureauToken);
            creditBureauToken = null;
        }
    }
    if (creditBureauToken != null) {
        creditBureauToken = this.tokenRepositoryWrapper.getToken();
    }
    String userName = getCreditBureauConfiguration(bureauID.intValue(), CreditBureauConfigurations.USERNAME.toString());
    String password = getCreditBureauConfiguration(bureauID.intValue(), CreditBureauConfigurations.PASSWORD.toString());
    String subscriptionId = getCreditBureauConfiguration(bureauID.intValue(), CreditBureauConfigurations.SUBSCRIPTIONID.toString());
    String subscriptionKey = getCreditBureauConfiguration(bureauID.intValue(), CreditBureauConfigurations.SUBSCRIPTIONKEY.toString());
    if (creditBureauToken == null) {
        String url = getCreditBureauConfiguration(bureauID.intValue(), CreditBureauConfigurations.TOKENURL.toString());
        String process = "token";
        String nrcId = null;
        Long uniqueID = 0L;
        String result = this.okHttpConnectionMethod(userName, password, subscriptionKey, subscriptionId, url, null, null, null, uniqueID, nrcId, process);
        // created token will be storing it into database
        final CommandWrapper wrapper = new CommandWrapperBuilder().withJson(result).build();
        final String json = wrapper.getJson();
        JsonCommand apicommand = null;
        final JsonElement parsedCommand = this.fromApiJsonHelper.parse(json);
        apicommand = JsonCommand.from(json, parsedCommand, this.fromApiJsonHelper, wrapper.getEntityName(), wrapper.getEntityId(), wrapper.getSubentityId(), wrapper.getGroupId(), wrapper.getClientId(), wrapper.getLoanId(), wrapper.getSavingsId(), wrapper.getTransactionId(), wrapper.getHref(), wrapper.getProductId(), wrapper.getCreditBureauId(), wrapper.getOrganisationCreditBureauId());
        this.fromApiJsonDeserializer.validateForCreate(apicommand.json());
        final CreditBureauToken generatedtoken = CreditBureauToken.fromJson(apicommand);
        final CreditBureauToken credittoken = this.tokenRepositoryWrapper.getToken();
        if (credittoken != null) {
            this.tokenRepositoryWrapper.delete(credittoken);
        }
        this.tokenRepositoryWrapper.save(generatedtoken);
        creditBureauToken = this.tokenRepositoryWrapper.getToken();
    }
    return creditBureauToken;
}
Also used : CommandWrapperBuilder(org.apache.fineract.commands.service.CommandWrapperBuilder) JsonCommand(org.apache.fineract.infrastructure.core.api.JsonCommand) JsonElement(com.google.gson.JsonElement) CommandWrapper(org.apache.fineract.commands.domain.CommandWrapper) CreditBureauToken(org.apache.fineract.infrastructure.creditbureau.domain.CreditBureauToken) Date(java.util.Date) Transactional(org.springframework.transaction.annotation.Transactional)

Example 2 with JsonCommand

use of org.apache.fineract.infrastructure.core.api.JsonCommand in project fineract by apache.

the class ShareProductCommandsServiceImpl method handleCommand.

@Override
public Object handleCommand(Long productId, String command, String jsonBody) {
    final JsonElement parsedCommand = this.fromApiJsonHelper.parse(jsonBody);
    final JsonCommand jsonCommand = JsonCommand.from(jsonBody, parsedCommand, this.fromApiJsonHelper, null, null, null, null, null, null, null, null, null, null, null, null);
    if (ShareProductApiConstants.PREIEW_DIVIDENDS_COMMAND_STRING.equals(command)) {
        return null;
    } else if (ShareProductApiConstants.POST_DIVIDENdS_COMMAND_STRING.equals(command)) {
        return postDividends(productId, jsonCommand);
    }
    // throw unknow commandexception
    return CommandProcessingResult.empty();
}
Also used : JsonElement(com.google.gson.JsonElement) JsonCommand(org.apache.fineract.infrastructure.core.api.JsonCommand)

Example 3 with JsonCommand

use of org.apache.fineract.infrastructure.core.api.JsonCommand in project fineract by apache.

the class LoanWritePlatformServiceJpaRepositoryImpl method applyOverdueChargesForLoan.

@Override
@Transactional
public void applyOverdueChargesForLoan(final Long loanId, Collection<OverdueLoanScheduleData> overdueLoanScheduleDatas) {
    Loan loan = null;
    final List<Long> existingTransactionIds = new ArrayList<>();
    final List<Long> existingReversedTransactionIds = new ArrayList<>();
    boolean runInterestRecalculation = false;
    LocalDate recalculateFrom = DateUtils.getLocalDateOfTenant();
    LocalDate lastChargeDate = null;
    for (final OverdueLoanScheduleData overdueInstallment : overdueLoanScheduleDatas) {
        final JsonElement parsedCommand = this.fromApiJsonHelper.parse(overdueInstallment.toString());
        final JsonCommand command = JsonCommand.from(overdueInstallment.toString(), parsedCommand, this.fromApiJsonHelper, null, null, null, null, null, loanId, null, null, null, null, null, null);
        LoanOverdueDTO overdueDTO = applyChargeToOverdueLoanInstallment(loanId, overdueInstallment.getChargeId(), overdueInstallment.getPeriodNumber(), command, loan, existingTransactionIds, existingReversedTransactionIds);
        loan = overdueDTO.getLoan();
        runInterestRecalculation = runInterestRecalculation || overdueDTO.isRunInterestRecalculation();
        if (recalculateFrom.isAfter(overdueDTO.getRecalculateFrom())) {
            recalculateFrom = overdueDTO.getRecalculateFrom();
        }
        if (lastChargeDate == null || overdueDTO.getLastChargeAppliedDate().isAfter(lastChargeDate)) {
            lastChargeDate = overdueDTO.getLastChargeAppliedDate();
        }
    }
    if (loan != null) {
        boolean reprocessRequired = true;
        LocalDate recalculatedTill = loan.fetchInterestRecalculateFromDate();
        if (recalculateFrom.isAfter(recalculatedTill)) {
            recalculateFrom = recalculatedTill;
        }
        if (loan.repaymentScheduleDetail().isInterestRecalculationEnabled()) {
            if (runInterestRecalculation && loan.isFeeCompoundingEnabledForInterestRecalculation()) {
                runScheduleRecalculation(loan, recalculateFrom);
                reprocessRequired = false;
            }
            updateOriginalSchedule(loan);
        }
        if (reprocessRequired) {
            addInstallmentIfPenaltyAppliedAfterLastDueDate(loan, lastChargeDate);
            ChangedTransactionDetail changedTransactionDetail = loan.reprocessTransactions();
            if (changedTransactionDetail != null) {
                for (final Map.Entry<Long, LoanTransaction> mapEntry : changedTransactionDetail.getNewTransactionMappings().entrySet()) {
                    this.loanTransactionRepository.save(mapEntry.getValue());
                    // update loan with references to the newly created
                    // transactions
                    loan.addLoanTransaction(mapEntry.getValue());
                    this.accountTransfersWritePlatformService.updateLoanTransaction(mapEntry.getKey(), mapEntry.getValue());
                }
            }
            saveLoanWithDataIntegrityViolationChecks(loan);
        }
        postJournalEntries(loan, existingTransactionIds, existingReversedTransactionIds);
        if (loan.repaymentScheduleDetail().isInterestRecalculationEnabled() && runInterestRecalculation && loan.isFeeCompoundingEnabledForInterestRecalculation()) {
            this.loanAccountDomainService.recalculateAccruals(loan);
        }
        this.businessEventNotifierService.notifyBusinessEventWasExecuted(BusinessEvents.LOAN_APPLY_OVERDUE_CHARGE, constructEntityMap(BusinessEntity.LOAN, loan));
    }
}
Also used : ChangedTransactionDetail(org.apache.fineract.portfolio.loanaccount.domain.ChangedTransactionDetail) JsonCommand(org.apache.fineract.infrastructure.core.api.JsonCommand) ArrayList(java.util.ArrayList) LocalDate(java.time.LocalDate) Loan(org.apache.fineract.portfolio.loanaccount.domain.Loan) JsonElement(com.google.gson.JsonElement) LoanTransaction(org.apache.fineract.portfolio.loanaccount.domain.LoanTransaction) OverdueLoanScheduleData(org.apache.fineract.portfolio.loanaccount.loanschedule.data.OverdueLoanScheduleData) LoanOverdueDTO(org.apache.fineract.portfolio.loanproduct.data.LoanOverdueDTO) Map(java.util.Map) LinkedHashMap(java.util.LinkedHashMap) HashMap(java.util.HashMap) Transactional(org.springframework.transaction.annotation.Transactional)

Example 4 with JsonCommand

use of org.apache.fineract.infrastructure.core.api.JsonCommand in project fineract by apache.

the class LoanWritePlatformServiceJpaRepositoryImpl method makeGLIMLoanRepayment.

@Transactional
@Override
public CommandProcessingResult makeGLIMLoanRepayment(final Long loanId, final JsonCommand command) {
    final Long parentLoanId = loanId;
    glimRepository.findById(parentLoanId).get();
    JsonArray repayments = command.arrayOfParameterNamed("formDataArray");
    JsonCommand childCommand = null;
    CommandProcessingResult result = null;
    JsonObject jsonObject = null;
    Long[] childLoanId = new Long[repayments.size()];
    for (int i = 0; i < repayments.size(); i++) {
        jsonObject = repayments.get(i).getAsJsonObject();
        LOG.info("{}", jsonObject.toString());
        childLoanId[i] = jsonObject.get("loanId").getAsLong();
    }
    int j = 0;
    for (JsonElement element : repayments) {
        childCommand = JsonCommand.fromExistingCommand(command, element);
        result = makeLoanRepayment(childLoanId[j++], childCommand, false);
    }
    return result;
}
Also used : JsonArray(com.google.gson.JsonArray) JsonCommand(org.apache.fineract.infrastructure.core.api.JsonCommand) JsonElement(com.google.gson.JsonElement) JsonObject(com.google.gson.JsonObject) CommandProcessingResult(org.apache.fineract.infrastructure.core.data.CommandProcessingResult) Transactional(org.springframework.transaction.annotation.Transactional)

Example 5 with JsonCommand

use of org.apache.fineract.infrastructure.core.api.JsonCommand in project fineract by apache.

the class SelfServiceRegistrationWritePlatformServiceImpl method createUser.

@Override
public AppUser createUser(String apiRequestBodyAsJson) {
    JsonCommand command = null;
    String username = null;
    try {
        Gson gson = new Gson();
        final Type typeOfMap = new TypeToken<Map<String, Object>>() {
        }.getType();
        final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
        final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("user");
        this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, apiRequestBodyAsJson, SelfServiceApiConstants.CREATE_USER_REQUEST_DATA_PARAMETERS);
        JsonElement element = gson.fromJson(apiRequestBodyAsJson.toString(), JsonElement.class);
        Long id = this.fromApiJsonHelper.extractLongNamed(SelfServiceApiConstants.requestIdParamName, element);
        baseDataValidator.reset().parameter(SelfServiceApiConstants.requestIdParamName).value(id).notNull().integerGreaterThanZero();
        command = JsonCommand.fromJsonElement(id, element);
        String authenticationToken = this.fromApiJsonHelper.extractStringNamed(SelfServiceApiConstants.authenticationTokenParamName, element);
        baseDataValidator.reset().parameter(SelfServiceApiConstants.authenticationTokenParamName).value(authenticationToken).notBlank().notNull().notExceedingLengthOf(100);
        if (!dataValidationErrors.isEmpty()) {
            throw new PlatformApiDataValidationException(dataValidationErrors);
        }
        SelfServiceRegistration selfServiceRegistration = this.selfServiceRegistrationRepository.getRequestByIdAndAuthenticationToken(id, authenticationToken);
        if (selfServiceRegistration == null) {
            throw new SelfServiceRegistrationNotFoundException(id, authenticationToken);
        }
        username = selfServiceRegistration.getUsername();
        Client client = selfServiceRegistration.getClient();
        final boolean passwordNeverExpire = true;
        final boolean isSelfServiceUser = true;
        final Collection<SimpleGrantedAuthority> authorities = new ArrayList<>();
        authorities.add(new SimpleGrantedAuthority("DUMMY_ROLE_NOT_USED_OR_PERSISTED_TO_AVOID_EXCEPTION"));
        final Set<Role> allRoles = new HashSet<>();
        Role role = this.roleRepository.getRoleByName(SelfServiceApiConstants.SELF_SERVICE_USER_ROLE);
        if (role != null) {
            allRoles.add(role);
        } else {
            throw new RoleNotFoundException(SelfServiceApiConstants.SELF_SERVICE_USER_ROLE);
        }
        List<Client> clients = new ArrayList<>(Arrays.asList(client));
        User user = new User(selfServiceRegistration.getUsername(), selfServiceRegistration.getPassword(), authorities);
        AppUser appUser = new AppUser(client.getOffice(), user, allRoles, selfServiceRegistration.getEmail(), client.getFirstname(), client.getLastname(), null, passwordNeverExpire, isSelfServiceUser, clients, null);
        this.userDomainService.create(appUser, true);
        return appUser;
    } catch (final JpaSystemException | DataIntegrityViolationException dve) {
        handleDataIntegrityIssues(command, dve.getMostSpecificCause(), dve, username);
        return null;
    } catch (final PersistenceException | AuthenticationServiceException dve) {
        Throwable throwable = ExceptionUtils.getRootCause(dve.getCause());
        handleDataIntegrityIssues(command, throwable, dve, username);
        return null;
    }
}
Also used : User(org.springframework.security.core.userdetails.User) AppUser(org.apache.fineract.useradministration.domain.AppUser) JsonCommand(org.apache.fineract.infrastructure.core.api.JsonCommand) ArrayList(java.util.ArrayList) Gson(com.google.gson.Gson) SelfServiceRegistration(org.apache.fineract.portfolio.self.registration.domain.SelfServiceRegistration) RoleNotFoundException(org.apache.fineract.useradministration.exception.RoleNotFoundException) AppUser(org.apache.fineract.useradministration.domain.AppUser) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) Client(org.apache.fineract.portfolio.client.domain.Client) HashSet(java.util.HashSet) PlatformApiDataValidationException(org.apache.fineract.infrastructure.core.exception.PlatformApiDataValidationException) SelfServiceRegistrationNotFoundException(org.apache.fineract.portfolio.self.registration.exception.SelfServiceRegistrationNotFoundException) DataValidatorBuilder(org.apache.fineract.infrastructure.core.data.DataValidatorBuilder) ApiParameterError(org.apache.fineract.infrastructure.core.data.ApiParameterError) AuthenticationServiceException(org.springframework.security.authentication.AuthenticationServiceException) DataIntegrityViolationException(org.springframework.dao.DataIntegrityViolationException) Role(org.apache.fineract.useradministration.domain.Role) JpaSystemException(org.springframework.orm.jpa.JpaSystemException) SmsMessageStatusType(org.apache.fineract.infrastructure.sms.domain.SmsMessageStatusType) Type(java.lang.reflect.Type) JsonElement(com.google.gson.JsonElement) PersistenceException(javax.persistence.PersistenceException) Map(java.util.Map)

Aggregations

JsonCommand (org.apache.fineract.infrastructure.core.api.JsonCommand)13 JsonElement (com.google.gson.JsonElement)10 JsonObject (com.google.gson.JsonObject)6 JsonArray (com.google.gson.JsonArray)5 Transactional (org.springframework.transaction.annotation.Transactional)5 BigDecimal (java.math.BigDecimal)4 HashMap (java.util.HashMap)4 CommandProcessingResult (org.apache.fineract.infrastructure.core.data.CommandProcessingResult)4 ArrayList (java.util.ArrayList)3 Map (java.util.Map)3 Type (java.lang.reflect.Type)2 HashSet (java.util.HashSet)2 LinkedHashMap (java.util.LinkedHashMap)2 Locale (java.util.Locale)2 CommandWrapper (org.apache.fineract.commands.domain.CommandWrapper)2 ApiParameterError (org.apache.fineract.infrastructure.core.data.ApiParameterError)2 DataValidatorBuilder (org.apache.fineract.infrastructure.core.data.DataValidatorBuilder)2 PlatformApiDataValidationException (org.apache.fineract.infrastructure.core.exception.PlatformApiDataValidationException)2 Loan (org.apache.fineract.portfolio.loanaccount.domain.Loan)2 Gson (com.google.gson.Gson)1