<commit_before>/*
 * Copyright 2003 - 2016 The eFaps Team
 *
 * Licensed 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.efaps.esjp.sales.payment;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.ArrayUtils;
import org.efaps.admin.datamodel.Status;
import org.efaps.admin.dbproperty.DBProperties;
import org.efaps.admin.event.Parameter;
import org.efaps.admin.event.Return;
import org.efaps.admin.event.Return.ReturnValues;
import org.efaps.admin.program.esjp.EFapsApplication;
import org.efaps.admin.program.esjp.EFapsUUID;
import org.efaps.ci.CIStatus;
import org.efaps.ci.CIType;
import org.efaps.db.Context;
import org.efaps.db.Insert;
import org.efaps.db.Instance;
import org.efaps.db.MultiPrintQuery;
import org.efaps.db.PrintQuery;
import org.efaps.db.QueryBuilder;
import org.efaps.db.SelectBuilder;
import org.efaps.db.Update;
import org.efaps.esjp.ci.CIERP;
import org.efaps.esjp.ci.CISales;
import org.efaps.esjp.common.tag.Tag;
import org.efaps.esjp.db.InstanceUtils;
import org.efaps.esjp.erp.CommonDocument;
import org.efaps.esjp.erp.Currency;
import org.efaps.esjp.erp.CurrencyInst;
import org.efaps.esjp.erp.Naming;
import org.efaps.esjp.erp.NumberFormatter;
import org.efaps.esjp.sales.PriceUtil;
import org.efaps.esjp.sales.util.Sales;
import org.efaps.util.EFapsException;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * The Class Settle_Base.
 *
 * @author The eFaps Team
 */
@EFapsUUID("8e4b870d-4d52-4272-9deb-4cade067c146")
@EFapsApplication("eFapsApp-Sales")
public abstract class Settlement_Base
    extends CommonDocument
{

    /**
     * Logger for this class.
     */
    private static final Logger LOG = LoggerFactory.getLogger(Settlement.class);

    /** The out. */
    private final boolean out;

    /**
     * Instantiates a new settlement base.
     *
     * @param _out the out
     */
    public Settlement_Base(final boolean _out)
    {
        this.out = _out;
    }

    /**
     * Settle payment.
     *
     * @param _parameter Parameter as passed by the eFaps API
     * @throws EFapsException on error
     */
    public void settlePayment(final Parameter _parameter)
        throws EFapsException
    {
        final Instance settleDocInst = Instance.get(_parameter.getParameterValue("currentDocument"));
        final BigDecimal amount = getAmount4CurrentDocument(_parameter, settleDocInst, _parameter.getCallInstance());

        final String[] documents = _parameter.getParameterValues("settleDocument");
        final String[] settleTotals = _parameter.getParameterValues("settleTotal");
        boolean first = true;
        if (documents != null && documents.length > 0) {
            final Map<String, Object> infoDoc = new HashMap<>();
            int i = 0;
            for (final String doc : documents) {
                final Instance document = Instance.get(doc);
                if (document.isValid()) {
                    try {
                        final BigDecimal amount4Doc = (BigDecimal) NumberFormatter.get().getTwoDigitsFormatter().parse(
                                        settleTotals[i]);
                        if (first) {
                            replacePaymentInfo(_parameter, settleDocInst, document, amount4Doc, infoDoc);
                            first = false;
                        } else {
                            if (!infoDoc.isEmpty()) {
                                final Insert payInsert = new Insert(CISales.Payment);
                                payInsert.add(CISales.Payment.CreateDocument, document);
                                payInsert.add(CISales.Payment.TargetDocument, _parameter.getCallInstance());
                                payInsert.add(CISales.Payment.Amount, amount4Doc);
                                payInsert.add(CISales.Payment.CurrencyLink, infoDoc.get("currency"));
                                payInsert.add(CISales.Payment.Date, infoDoc.get("date"));
                                payInsert.execute();

                                final Insert transIns = new Insert(this.out ? CISales.TransactionOutbound
                                                : CISales.TransactionInbound);
                                transIns.add(CISales.TransactionOutbound.Amount, amount4Doc);
                                transIns.add(CISales.TransactionOutbound.CurrencyId, infoDoc.get("currency"));
                                transIns.add(CISales.TransactionOutbound.Payment, payInsert.getInstance());
                                transIns.add(CISales.TransactionOutbound.Date, infoDoc.get("date"));
                                transIns.add(CISales.TransactionOutbound.Account, infoDoc.get("account"));
                                transIns.execute();

                                final Insert insert = new Insert(CISales.PayableDocument2Document);
                                insert.add(CISales.PayableDocument2Document.FromLink, document);
                                insert.add(CISales.PayableDocument2Document.ToLink, settleDocInst);
                                insert.add(CISales.PayableDocument2Document.PayDocLink, payInsert);
                                insert.execute();
                            }
                        }
                    } catch (final ParseException e) {<commit_msg>- Issue #413: Settlement does not set the rate on payment <commit_after>/*
 * Copyright 2003 - 2016 The eFaps Team
 *
 * Licensed 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.efaps.esjp.sales.payment;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.ArrayUtils;
import org.efaps.admin.datamodel.Status;
import org.efaps.admin.dbproperty.DBProperties;
import org.efaps.admin.event.Parameter;
import org.efaps.admin.event.Return;
import org.efaps.admin.event.Return.ReturnValues;
import org.efaps.admin.program.esjp.EFapsApplication;
import org.efaps.admin.program.esjp.EFapsUUID;
import org.efaps.ci.CIStatus;
import org.efaps.ci.CIType;
import org.efaps.db.Context;
import org.efaps.db.Insert;
import org.efaps.db.Instance;
import org.efaps.db.MultiPrintQuery;
import org.efaps.db.PrintQuery;
import org.efaps.db.QueryBuilder;
import org.efaps.db.SelectBuilder;
import org.efaps.db.Update;
import org.efaps.esjp.ci.CIERP;
import org.efaps.esjp.ci.CISales;
import org.efaps.esjp.common.tag.Tag;
import org.efaps.esjp.db.InstanceUtils;
import org.efaps.esjp.erp.CommonDocument;
import org.efaps.esjp.erp.Currency;
import org.efaps.esjp.erp.CurrencyInst;
import org.efaps.esjp.erp.Naming;
import org.efaps.esjp.erp.NumberFormatter;
import org.efaps.esjp.sales.PriceUtil;
import org.efaps.esjp.sales.util.Sales;
import org.efaps.util.EFapsException;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * The Class Settle_Base.
 *
 * @author The eFaps Team
 */
@EFapsUUID("8e4b870d-4d52-4272-9deb-4cade067c146")
@EFapsApplication("eFapsApp-Sales")
public abstract class Settlement_Base
    extends CommonDocument
{

    /**
     * Logger for this class.
     */
    private static final Logger LOG = LoggerFactory.getLogger(Settlement.class);

    /** The out. */
    private final boolean out;

    /**
     * Instantiates a new settlement base.
     *
     * @param _out the out
     */
    public Settlement_Base(final boolean _out)
    {
        this.out = _out;
    }

    /**
     * Settle payment.
     *
     * @param _parameter Parameter as passed by the eFaps API
     * @throws EFapsException on error
     */
    public void settlePayment(final Parameter _parameter)
        throws EFapsException
    {
        final Instance settleDocInst = Instance.get(_parameter.getParameterValue("currentDocument"));
        final BigDecimal amount = getAmount4CurrentDocument(_parameter, settleDocInst, _parameter.getCallInstance());

        final String[] documents = _parameter.getParameterValues("settleDocument");
        final String[] settleTotals = _parameter.getParameterValues("settleTotal");
        boolean first = true;
        if (documents != null && documents.length > 0) {
            final Map<String, Object> infoDoc = new HashMap<>();
            int i = 0;
            for (final String doc : documents) {
                final Instance document = Instance.get(doc);
                if (document.isValid()) {
                    try {
                        final BigDecimal amount4Doc = (BigDecimal) NumberFormatter.get().getTwoDigitsFormatter().parse(
                                        settleTotals[i]);
                        if (first) {
                            replacePaymentInfo(_parameter, settleDocInst, document, amount4Doc, infoDoc);
                            first = false;
                        } else {
                            if (!infoDoc.isEmpty()) {
                                final PrintQuery print = new PrintQuery(document);
                                print.addAttribute(CISales.DocumentSumAbstract.Rate,
                                                CISales.DocumentSumAbstract.RateCurrencyId,
                                                CISales.DocumentSumAbstract.CurrencyId);
                                print.execute();
                                final Insert payInsert = new Insert(CISales.Payment);
                                payInsert.add(CISales.Payment.CreateDocument, document);
                                payInsert.add(CISales.Payment.TargetDocument, _parameter.getCallInstance());
                                payInsert.add(CISales.Payment.Amount, amount4Doc);
                                payInsert.add(CISales.Payment.Date, infoDoc.get("date"));
                                payInsert.add(CISales.Payment.RateCurrencyLink,
                                                print.<Long>getAttribute(CISales.DocumentSumAbstract.RateCurrencyId));
                                payInsert.add(CISales.Payment.CurrencyLink,
                                                print.<Long>getAttribute(CISales.DocumentSumAbstract.CurrencyId));
                                payInsert.add(CISales.Payment.Rate,
                                                print.<Object>getAttribute(CISales.DocumentSumAbstract.Rate));
                                payInsert.execute();

                                final Insert transIns = new Insert(this.out ? CISales.TransactionOutbound
                                                : CISales.TransactionInbound);
                                transIns.add(CISales.TransactionOutbound.Amount, amount4Doc);
                                transIns.add(CISales.TransactionOutbound.CurrencyId, infoDoc.get("currency"));
                                transIns.add(CISales.TransactionOutbound.Payment, payInsert.getInstance());
                                transIns.add(CISales.TransactionOutbound.Date, infoDoc.get("date"));
                                transIns.add(CISales.TransactionOutbound.Account, infoDoc.get("account"));
                                transIns.execute();

                                final Insert insert = new Insert(CISales.PayableDocument2Document);
                                insert.add(CISales.PayableDocument2Document.FromLink, document);
                                insert.add(CISales.PayableDocument2Document.ToLink, settleDocInst);
                                insert.add(CISales.PayableDocument2Document.PayDocLink, payInsert);
                                insert.execute();
                            }
                        }
                    } catch (final ParseException e) {
{'fraction_non_alphanumeric': 0.09268405618150949, 'fraction_numerical': 0.007177033492822967, 'mean_word_length': 2.080342286665082, 'pattern_counts': {'":': 0, '<': 10, '<?xml version=': 0, '>': 12, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 16, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6441052', 'n_tokens_mistral': 3537, 'n_tokens_neox': 3376, 'n_words': 724}