<commit_before># @ 2020 Akretion - www.akretion.com.br -
#   <NAME> <<EMAIL>>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html)

import os
import sys
import traceback

from odoo import _, fields, models
from odoo.exceptions import UserError, ValidationError

from odoo.addons.account_move_base_import.parser.parser import new_move_parser


class AccountJournal(models.Model):
    _inherit = "account.journal"

    import_type = fields.Selection(
        selection_add=[("cnab400", "CNAB 400"), ("cnab240", "CNAB 240")]
    )

    return_auto_reconcile = fields.Boolean(
        string="Automatic Reconcile payment returns",
        help="Enable automatic payment return reconciliation.",
        default=False,
    )

    def multi_move_import(self, file_stream, ftype="csv"):
        """Create multiple bank statements from values given by the parser for
        the given profile.

        :param int/long profile_id: ID of the profile used to import the file
        :param filebuffer file_stream: binary of the provided file
        :param char: ftype represent the file extension (csv by default)
        :return: list: list of ids of the created account.bank.statement
        """
        filename = self._context.get("file_name", None)
        if filename:
            (filename, __) = os.path.splitext(filename)
        parser = new_move_parser(self, ftype=ftype, move_ref=filename)
        res_move = self.env["account.move"]
        res_cnab_log = self.env["l10n_br_cnab.return.log"]
        for result_row_list in parser.parse(file_stream):
            result = self._move_import(
                parser,
                file_stream,
                result_row_list=result_row_list,
                ftype=ftype,
            )

            if len(result) > 1 or hasattr(result, "journal_id"):
                res_move |= result
            if hasattr(result, "filename"):
                res_cnab_log |= result
        if res_move:
            return res_move
        else:
            return res_cnab_log

    def _move_import(self, parser, file_stream, result_row_list=None, ftype="csv"):

        # Overwrite this method to create the CNAB Return Log and change
        # the warning message when the file don't has any line to create
        # the Journal Entry, because in CNAB exist the case where
        # the file just has only Log information.

        # Call super when file is not CNAB
        if ftype == "csv":
            super()._move_import(parser, file_stream, result_row_list=None, ftype="csv")

        attachment_obj = self.env["ir.attachment"]
        if result_row_list is None:
            result_row_list = parser.result_row_list

        # Original Method
        # Check all key are present in account.bank.statement.line!!
        # if not result_row_list:
        #    raise UserError(_("Nothing to import: " "The file is empty"))
        if not result_row_list and not parser.cnab_return_events:
            raise UserError(_("Nothing to import: " "The file is empty"))

        # Creation of CNAB Return Log
        cnab_return_log, file_name = self._create_cnab_return_log(parser)

        attachment_data = {
            "name": file_name,
            "datas": file_stream,
            "store_fname": file_name,
            "res_model": "l10n_br_cnab.return.log",
            "res_id": cnab_return_log.id,
        }
        attachment_obj.create(attachment_data)

        if not result_row_list:
            return cnab_return_log

        moves = self._get_moves(parser, result_row_list)

        cnab_return_log.move_ids = moves.ids
        for move in moves:
            # CNAB Return Log
            move.cnab_return_log_id = cnab_return_log.id
            # Lançamento Automatico do Diário
            if self.return_auto_reconcile:
                move.post()

        return moves

    def _create_cnab_return_log(self, parser):
        context = self.env.context
        cnab_return_log = self.env["l10n_br_cnab.return.log"].create(
            {
                "name": "Banco "
                + parser.bank.short_name
                + " - Conta "
                + parser.journal.bank_account_id.acc_number,
                "filename": context.get("file_name"),
                "cnab_date_import": fields.Datetime.now(),
                "bank_account_id": parser.journal.bank_account_id.id,
            }
        )
        qty_cnab_return_events = (
            amount_total_title
        ) = (
            amount_total_received
        ) = (
            amount_total_tariff_charge
        ) = (
            amount_total_interest_fee
        ) = amount_total_discount = amount_total_rebate = 0.0

        for cnab_return_event in parser.cnab_return_events:
            amount_total_title += cnab_return_event.get("title_value")
            if cnab_return_event.get("payment_value"):
                amount_total_received += cnab_return_event.get("payment_value")
            if cnab_return_event.get("tariff_charge"):<commit_msg>[MIG] l10n_br_account_payment_brcobranca: Method post become action_post.<commit_after># @ 2020 Akretion - www.akretion.com.br -
#   <NAME> <<EMAIL>>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html)

import os
import sys
import traceback

from odoo import _, fields, models
from odoo.exceptions import UserError, ValidationError

from odoo.addons.account_move_base_import.parser.parser import new_move_parser


class AccountJournal(models.Model):
    _inherit = "account.journal"

    import_type = fields.Selection(
        selection_add=[("cnab400", "CNAB 400"), ("cnab240", "CNAB 240")]
    )

    return_auto_reconcile = fields.Boolean(
        string="Automatic Reconcile payment returns",
        help="Enable automatic payment return reconciliation.",
        default=False,
    )

    def multi_move_import(self, file_stream, ftype="csv"):
        """Create multiple bank statements from values given by the parser for
        the given profile.

        :param int/long profile_id: ID of the profile used to import the file
        :param filebuffer file_stream: binary of the provided file
        :param char: ftype represent the file extension (csv by default)
        :return: list: list of ids of the created account.bank.statement
        """
        filename = self._context.get("file_name", None)
        if filename:
            (filename, __) = os.path.splitext(filename)
        parser = new_move_parser(self, ftype=ftype, move_ref=filename)
        res_move = self.env["account.move"]
        res_cnab_log = self.env["l10n_br_cnab.return.log"]
        for result_row_list in parser.parse(file_stream):
            result = self._move_import(
                parser,
                file_stream,
                result_row_list=result_row_list,
                ftype=ftype,
            )

            if len(result) > 1 or hasattr(result, "journal_id"):
                res_move |= result
            if hasattr(result, "filename"):
                res_cnab_log |= result
        if res_move:
            return res_move
        else:
            return res_cnab_log

    def _move_import(self, parser, file_stream, result_row_list=None, ftype="csv"):

        # Overwrite this method to create the CNAB Return Log and change
        # the warning message when the file don't has any line to create
        # the Journal Entry, because in CNAB exist the case where
        # the file just has only Log information.

        # Call super when file is not CNAB
        if ftype == "csv":
            super()._move_import(parser, file_stream, result_row_list=None, ftype="csv")

        attachment_obj = self.env["ir.attachment"]
        if result_row_list is None:
            result_row_list = parser.result_row_list

        # Original Method
        # Check all key are present in account.bank.statement.line!!
        # if not result_row_list:
        #    raise UserError(_("Nothing to import: " "The file is empty"))
        if not result_row_list and not parser.cnab_return_events:
            raise UserError(_("Nothing to import: " "The file is empty"))

        # Creation of CNAB Return Log
        cnab_return_log, file_name = self._create_cnab_return_log(parser)

        attachment_data = {
            "name": file_name,
            "datas": file_stream,
            "store_fname": file_name,
            "res_model": "l10n_br_cnab.return.log",
            "res_id": cnab_return_log.id,
        }
        attachment_obj.create(attachment_data)

        if not result_row_list:
            return cnab_return_log

        moves = self._get_moves(parser, result_row_list)

        cnab_return_log.move_ids = moves.ids
        for move in moves:
            # CNAB Return Log
            move.cnab_return_log_id = cnab_return_log.id
            # Lançamento Automatico do Diário
            if self.return_auto_reconcile:
                move.action_post()

        return moves

    def _create_cnab_return_log(self, parser):
        context = self.env.context
        cnab_return_log = self.env["l10n_br_cnab.return.log"].create(
            {
                "name": "Banco "
                + parser.bank.short_name
                + " - Conta "
                + parser.journal.bank_account_id.acc_number,
                "filename": context.get("file_name"),
                "cnab_date_import": fields.Datetime.now(),
                "bank_account_id": parser.journal.bank_account_id.id,
            }
        )
        qty_cnab_return_events = (
            amount_total_title
        ) = (
            amount_total_received
        ) = (
            amount_total_tariff_charge
        ) = (
            amount_total_interest_fee
        ) = amount_total_discount = amount_total_rebate = 0.0

        for cnab_return_event in parser.cnab_return_events:
            amount_total_title += cnab_return_event.get("title_value")
            if cnab_return_event.get("payment_value"):
                amount_total_received += cnab_return_event.get("payment_value")
            if cnab_return_event.get("tariff_charge"):
{'fraction_non_alphanumeric': 0.08459934465296395, 'fraction_numerical': 0.005560520305828617, 'mean_word_length': 2.2209785737128236, 'pattern_counts': {'":': 20, '<': 9, '<?xml version=': 0, '>': 11, 'https://': 0, 'lorem ipsum': 0, 'www.': 4, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4553494', 'n_tokens_mistral': 3017, 'n_tokens_neox': 2926, 'n_words': 694}