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

from odoo.addons.l10n_br_fiscal.constants.fiscal import (
    MODELO_FISCAL_NFCE,
    MODELO_FISCAL_NFE,
    PROCESSADOR_OCA,
)


def filter_processador_edoc_nfe(record):
    if (
        record.fiscal_document_id.processador_edoc == PROCESSADOR_OCA
        and record.fiscal_document_id.document_type_id.code
        in [
            MODELO_FISCAL_NFE,
            MODELO_FISCAL_NFCE,
        ]
    ):
        return True
    return False


class AccountInvoice(models.Model):
    _inherit = "account.invoice"

    def action_invoice_open(self):
        super(AccountInvoice, self).action_invoice_open()

        for inv in self.filtered(filter_processador_edoc_nfe):
            if inv.amount_financial_total > 0:
                self.generate_payment_info(inv)

    def generate_payment_info(self, inv):
        if not inv.payment_mode_id.fiscal_payment_mode:
            raise UserError(_("Document without Fiscal Payment Mode!"))

        moves_terms = inv.financial_move_line_ids.filtered(
            lambda move_line: move_line.date_maturity > move_line.date
        )
        indPag = "1" if len(moves_terms) > 0 else "0"

        inv.nfe40_detPag = [
            (5, 0, 0),
            (
                0,
                0,
                inv.fiscal_document_id._prepare_amount_financial(
                    indPag,
                    inv.payment_mode_id.fiscal_payment_mode,
                    inv.amount_financial_total,
                ),
            ),
        ]

@@ -822,16 +822,65 @@
 nfo(inv)
+%0A                self.generate_cobranca_info(inv)
 %0A%0A    de
@@ -1579,20 +1579,1052 @@
        ),%0A        %5D%0A
+%0A    def generate_cobranca_info(self, inv):%0A%0A        fat_id = self.env%5B%22nfe.40.fat%22%5D.create(%0A            %7B%0A                %22nfe40_nFat%22: inv.number,%0A                %22nfe40_vOrig%22: inv.amount_financial_total_gross,%0A                %22nfe40_vDesc%22: inv.amount_financial_discount_value,%0A                %22nfe40_vLiq%22: inv.amount_financial_total,%0A            %7D%0A        )%0A%0A        duplicatas = self.env%5B%22nfe.40.dup%22%5D%0A        count = 1%0A        for mov in inv.financial_move_line_ids:%0A            duplicatas += duplicatas.create(%0A                %7B%0A                    %22nfe40_nDup%22: str(count).zfill(3),%0A                    %22nfe40_dVenc%22: mov.date_maturity,%0A                    %22nfe40_vDup%22: mov.debit,%0A                %7D%0A            )%0A            count += 1%0A%0A        cobr_id = self.env%5B%22nfe.40.cobr%22%5D.create(%0A            %7B%0A                %22nfe40_fat%22: fat_id.id,%0A                %22nfe40_dup%22: %5B(6, 0, duplicatas.ids)%5D,%0A            %7D%0A        )%0A%0A        inv.update(%0A            %7B%0A                %22nfe40_cobr%22: cobr_id.id,%0A            %7D%0A        )%0A

add cobrança info nfe