﻿"""
Tests de l'integration MCF et des services materiels.
"""



from datetime import datetime
from decimal import Decimal
from types import SimpleNamespace
from unittest.mock import Mock, patch

from django.contrib.auth import get_user_model
from django.test import TestCase

from dgi.models import ClientType
from facturation.fiscal_exceptions import FiscalBusinessError, FiscalTechnicalError
from facturation.models import Client, Commande, Configuration, PointDeVente

from .client import MCFClient, MCFClientError
from .commands import MCFCommands, MCFTaxRateMismatchError
from .mcf_adapter import MCFAdapter
from .models import MCFDevice, MCFInvoiceLog, MCFStatusSnapshot
from .services_mcf import (
    MCFInvalidNIFError,
    MCFInvoiceService,
    MCFInvoiceServiceError,
    MCFPortLocator,
    MCFRejectedNIFError,
    MCFSynchronizationService,
    MCFTaxConfigurationError,
)


class MCFCloseResponseTests(TestCase):
    """Regroupe les tests de lecture des reponses de cloture MCF."""


    def test_parse_close_response_returns_canonical_security_fields(self):
        """Verifie que l'analyse de la reponse de cloture retourne les champs de securite canoniques."""

        service = MCFInvoiceService(
            device=MCFDevice(
                name="MCF Test",
                port="COM9",
                company_nif="A1234567Q",
                company_isf="CD01004241-1",
            )
        )

        security = service._parse_close_response(
            "R:FC001,TC002,FT003,20260326181122,NIM123,A1234567Q,FV-2026-00001,SIGABC123"
        )

        self.assertEqual(security["date_time"], "26/03/2026 18:11:22")
        self.assertEqual(security["code_def_dgi"], "SIGABC123")
        self.assertEqual(security["counters"], "FC001/TC002 FT003")
        self.assertEqual(security["nim"], "NIM123")
        self.assertEqual(
            security["qr_code"],
            "RDCDEF01;NIM123;SIGABC123;A1234567Q;20260326181122",
        )
        self.assertEqual(security["def_time"], security["date_time"])
        self.assertEqual(security["def_counters"], security["counters"])
        self.assertEqual(security["def_nim"], security["nim"])
        self.assertEqual(security["qr_payload"], security["qr_code"])


class MCFSynchronizationServiceTests(TestCase):
    """Verifie le suivi C2 de synchronisation DGI du MCF."""

    def setUp(self):
        """Prepare un appareil MCF factice pour les tests de synchronisation."""

        self.device = MCFDevice.objects.create(
            name="MCF Sync",
            port="COM9",
            company_nif="A1234567Q",
            company_isf="CD01004241-1",
            is_active=True,
            is_default=True,
        )

    def test_restart_server_connection_sends_c2_restart(self):
        """Verifie que la relance utilise C2 avec la donnee RESTART."""

        client = Mock()
        client.send_command.return_value = {"ok": True, "response": {"data_text": ""}}

        result = MCFCommands(client).restart_server_connection()

        self.assertTrue(result["ok"])
        client.send_command.assert_called_once_with("C2", "RESTART")

    def test_daily_status_executes_c2_and_flags_stale_connection(self):
        """Verifie la lecture C2 et l'alerte au-dela de sept jours."""

        service = MCFSynchronizationService(device=self.device)
        response = {
            "ok": True,
            "response": {
                "data_text": "49,49,20200101000000,DIS",
                "status_hex": "C080C080C0D8",
                "syn_count": 1,
            },
        }

        with patch("mcf.services_mcf.MCFClient") as mock_client_cls, patch(
            "mcf.services_mcf.MCFCommands"
        ) as mock_commands_cls:
            mock_client_cls.available_ports.return_value = [{"device": "COM9"}]
            mock_commands_cls.return_value.get_server_connection_status.return_value = response

            status = service.get_daily_connection_status()

        self.assertTrue(status["success"])
        self.assertTrue(status["machine_connected"])
        self.assertEqual(status["machine_status_label"], "Connecte")
        self.assertTrue(status["needs_alert"])
        self.assertEqual(status["server_status"], "DIS")
        self.assertEqual(MCFStatusSnapshot.objects.count(), 1)
        mock_client_cls.return_value.close.assert_called_once()

    def test_daily_status_reuses_today_snapshot_without_opening_serial_port(self):
        """Verifie le cache journalier pour ne pas interroger le MCF a chaque page."""

        MCFStatusSnapshot.objects.create(
            device=self.device,
            raw_data="49,49,20990101000000,CON",
            success=True,
            message=f"{MCFSynchronizationService.SNAPSHOT_PREFIX} CHECK: OK",
        )
        service = MCFSynchronizationService(device=self.device)

        with patch("mcf.services_mcf.MCFClient") as mock_client_cls:
            status = service.get_daily_connection_status()

        self.assertEqual(status["source"], "cache")
        self.assertEqual(status["server_status"], "CON")
        mock_client_cls.assert_not_called()

    def test_connection_error_is_displayed_as_unplugged_mcf(self):
        """Verifie que les erreurs serie techniques restent lisibles cote UI."""

        service = MCFSynchronizationService(device=self.device)

        status = service._build_error_status(
            "Impossible d'ouvrir le port COM8 du MCF : could not open port 'COM8': "
            "FileNotFoundError(2, 'Le fichier specifie est introuvable.', None, 2)"
        )

        self.assertEqual(status["message"], "Le MCF n'est pas branche dans l'ordinateur.")
        self.assertEqual(status["error"], "Le MCF n'est pas branche dans l'ordinateur.")

    def _restart_with_serial_error(self, *, listed_ports, open_error=None, command_error=None):
        """Relance la synchronisation avec une erreur serie simulee a l'ouverture ou pendant C2."""

        service = MCFSynchronizationService(device=self.device)
        with patch("mcf.services_mcf.MCFClient") as mock_client_cls, patch(
            "mcf.services_mcf.MCFCommands"
        ) as mock_commands_cls:
            mock_client_cls.available_ports.return_value = [{"device": port} for port in listed_ports]
            if open_error:
                mock_client_cls.side_effect = MCFClientError(open_error)
            if command_error:
                mock_commands_cls.return_value.restart_server_connection.side_effect = MCFClientError(command_error)
            with self.assertLogs("mcf.services_mcf", "WARNING") as logs:
                status = service.restart_synchronization()
        self.assertIn(open_error or command_error, "\n".join(logs.output))
        return status

    def test_restart_interrupted_on_listed_port_is_not_reported_as_unplugged(self):
        """Verifie qu'une coupure pendant C2/RESTART n'est pas confondue avec un MCF debranche."""

        status = self._restart_with_serial_error(
            listed_ports=["COM9"],
            command_error=(
                "Erreur de lecture du MCF : ClearCommError failed "
                "(OSError(22, 'Le périphérique ne reconnaît pas la commande.', None, 22))"
            ),
        )

        self.assertFalse(status["success"])
        self.assertEqual(status["message"], MCFSynchronizationService.PORT_INTERRUPTED_MESSAGE.format(port="COM9"))

    def test_restart_on_busy_port_explains_the_port_is_in_use(self):
        """Verifie le message quand un autre programme tient deja le port du MCF."""

        status = self._restart_with_serial_error(
            listed_ports=["COM9"],
            open_error=(
                "Impossible d'ouvrir le port COM9 du MCF : could not open port 'COM9': "
                "PermissionError(13, 'Accès refusé.', None, 5)"
            ),
        )

        self.assertEqual(status["message"], MCFSynchronizationService.PORT_BUSY_MESSAGE.format(port="COM9"))

    def test_restart_without_listed_port_reports_unplugged_mcf(self):
        """Verifie que le message debranche reste reserve a un port absent de Windows."""

        status = self._restart_with_serial_error(
            listed_ports=[],
            open_error="Impossible d'ouvrir le port COM9 du MCF : could not open port 'COM9': FileNotFoundError(2)",
        )

        self.assertEqual(status["message"], MCFSynchronizationService.MACHINE_UNPLUGGED_MESSAGE)

    def test_restart_synchronization_uses_protocol_command(self):
        """Verifie la relance DGI via le service centralise MCF."""

        service = MCFSynchronizationService(device=self.device)
        response = {
            "ok": True,
            "response": {
                "data_text": "49,49,20260503120000,RES",
                "status_hex": "C080C080C0D8",
            },
        }

        with patch("mcf.services_mcf.MCFClient") as mock_client_cls, patch(
            "mcf.services_mcf.MCFCommands"
        ) as mock_commands_cls:
            mock_client_cls.available_ports.return_value = [{"device": "COM9"}]
            mock_commands_cls.return_value.restart_server_connection.return_value = response

            status = service.restart_synchronization()

        self.assertTrue(status["success"])
        self.assertTrue(status["restart_requested"])
        self.assertEqual(status["server_status"], "RES")
        mock_commands_cls.return_value.restart_server_connection.assert_called_once_with()
        mock_client_cls.return_value.close.assert_called_once()


class MCFPortLocatorTests(TestCase):
    """Verifie la relocalisation du MCF quand Windows renumerote son port USB."""

    PORTS = [
        {"device": "COM3", "description": "Lien serie sur Bluetooth standard (COM3)", "hwid": "BTHENUM\\{00001101}"},
        {"device": "COM5", "description": "USB Serial Device (COM5)", "hwid": "USB VID:PID=0403:6001"},
        {"device": "COM13", "description": "AT91 USB to Serial Converter (COM13)", "hwid": "USB VID:PID=03EB:6119"},
    ]
    C1_OWN_MCF = "ED02001705-1,A2560363Q,20261019092841,70,47,11"
    C1_OTHER_MCF = "CD01004241-1,A1234567Q,20261019092841,70,47,11"

    def setUp(self):
        """Prepare un MCF enregistre sur un port que Windows a retire."""

        self.device = MCFDevice.objects.create(
            name="MCF Eltrade",
            port="COM8",
            company_nif="A2560363Q",
            company_isf="ED02001705-1",
            is_active=True,
            is_default=True,
        )

    def _patch_c1(self, responses):
        """Simule la reponse C1 de chaque port ; un port absent ne s'ouvre pas."""

        def build_client(port):
            if port not in responses:
                raise MCFClientError(f"could not open port '{port}'")
            return Mock(port=port)

        def build_commands(client):
            commands = Mock()
            commands.get_status.return_value = {
                "ok": True,
                "response": {"type": "FRAME", "data_text": responses[client.port]},
            }
            return commands

        return (
            patch("mcf.services_mcf.MCFClient", side_effect=build_client),
            patch("mcf.services_mcf.MCFCommands", side_effect=build_commands),
        )

    def test_relocates_device_to_port_answering_with_its_identity(self):
        """Verifie que seul le boitier du meme NIF est retenu, sans sonder le Bluetooth."""

        client_patch, commands_patch = self._patch_c1(
            {"COM5": self.C1_OTHER_MCF, "COM13": self.C1_OWN_MCF}
        )
        with client_patch as mock_client_cls, commands_patch:
            found = MCFPortLocator(self.device).ensure_port(self.PORTS)

        self.assertTrue(found)
        self.assertEqual(self.device.port, "COM13")
        self.device.refresh_from_db()
        self.assertEqual(self.device.port, "COM13")
        probed_ports = [call.kwargs["port"] for call in mock_client_cls.call_args_list]
        self.assertEqual(probed_ports, ["COM5", "COM13"])

    def test_keeps_saved_port_when_no_matching_mcf_answers(self):
        """Verifie qu'un autre MCF branche ne remplace jamais l'appareil configure."""

        client_patch, commands_patch = self._patch_c1({"COM5": self.C1_OTHER_MCF})
        with client_patch, commands_patch:
            found = MCFPortLocator(self.device).ensure_port(self.PORTS)

        self.assertFalse(found)
        self.device.refresh_from_db()
        self.assertEqual(self.device.port, "COM8")

    def test_present_saved_port_is_used_without_probing(self):
        """Verifie qu'aucun port n'est ouvert quand le port enregistre existe."""

        with patch("mcf.services_mcf.MCFClient") as mock_client_cls:
            found = MCFPortLocator(self.device).ensure_port([{"device": "COM8"}])

        self.assertTrue(found)
        mock_client_cls.assert_not_called()

    def test_adapter_checks_mcf_on_relocated_port(self):
        """Verifie que la vente utilise le nouveau port retrouve par l'adaptateur."""

        client_patch, commands_patch = self._patch_c1({"COM13": self.C1_OWN_MCF})
        with patch("mcf.mcf_adapter.MCFClient") as adapter_client_cls, patch(
            "mcf.mcf_adapter.MCFCommands"
        ) as adapter_commands_cls, client_patch, commands_patch:
            adapter_client_cls.available_ports.return_value = self.PORTS
            adapter_commands_cls.return_value.get_status.return_value = {"ok": True}

            MCFAdapter()._ensure_device_is_ready(self.device)

        self.assertEqual(self.device.port, "COM13")
        adapter_client_cls.assert_called_once_with(port="COM13")

    def test_adapter_without_default_device_raises_technical_error(self):
        """Verifie qu'un MCF non configure propose le fallback au lieu d'une erreur 500."""

        self.device.delete()

        with self.assertRaises(FiscalTechnicalError):
            MCFAdapter().fiscalize(commande=None, prepared_payload={})


class MCFIdempotentReplayTests(TestCase):
    """Regroupe les tests de relecture idempotente des journaux MCF."""


    def test_existing_success_log_reuses_security_elements(self):
        """Verifie qu'un journal de succes existant reutilise ses elements de securite."""

        device = MCFDevice.objects.create(
            name="MCF Test",
            port="COM9",
            company_nif="A1234567Q",
            company_isf="CD01004241-1",
            is_active=True,
            is_default=True,
        )
        MCFInvoiceLog.objects.create(
            commande_id=42,
            device=device,
            success=True,
            response_data={
                "security": {
                    "sig": "SIG-42",
                    "def_time": "26/03/2026 18:15:00",
                    "def_counters": "FC042/TC042 FT042",
                    "def_nim": "NIM-42",
                    "qr_payload": "RDCDEF01;NIM-42;SIG-42;A1234567Q;20260326181500",
                }
            },
        )

        service = MCFInvoiceService(device=device)
        result = service.send_invoice(SimpleNamespace(pk=42))

        self.assertTrue(result["already_sent"])
        self.assertEqual(result["security"]["code_def_dgi"], "SIG-42")
        self.assertEqual(result["security"]["date_time"], "26/03/2026 18:15:00")
        self.assertEqual(result["security"]["counters"], "FC042/TC042 FT042")
        self.assertEqual(result["security"]["nim"], "NIM-42")
        self.assertEqual(
            result["security"]["qr_code"],
            "RDCDEF01;NIM-42;SIG-42;A1234567Q;20260326181500",
        )

    def test_prepared_payload_can_bypass_existing_success_log_for_correction(self):
        """Verifie qu'un payload prepare peut contourner un journal de succes existant pour une correction."""

        device = MCFDevice.objects.create(
            name="MCF Test",
            port="COM9",
            company_nif="A1234567Q",
            company_isf="CD01004241-1",
            is_active=True,
            is_default=True,
        )
        point_de_vente = PointDeVente.objects.create(nom="PDV Bypass")
        user = get_user_model().objects.create_user(
            username="mcf_bypass_user",
            email="mcf_bypass_user@test.com",
            password="secret",
            point_de_vente=point_de_vente,
        )
        commande = Commande.objects.create(
            point_de_vente=point_de_vente,
            vendeur=user,
            montant_total=Decimal("100.00"),
            tva_montant=Decimal("16.00"),
            taux_change_applique=Decimal("1.00"),
            type_facture="FV",
        )
        MCFInvoiceLog.objects.create(
            commande_id=commande.pk,
            device=device,
            success=True,
            response_data={"security": {"sig": "SIG-OLD"}},
        )
        prepared_payload = {
            "operation_type": "CORRECTION_ADD",
            "bypass_existing_log": True,
            "preserve_original_numero": True,
            "commande": {
                "numero": "FV-2026-09000",
                "type_facture": "FV",
                "source_numero": commande.numero,
            },
            "company": {
                "mode_dgi": "ttc",
                "nif": "A1234567Q",
                "isf": "CD01004241-1",
            },
            "operator": {
                "id": str(user.pk),
                "name": user.username,
            },
            "customer": {
                "type": "PP",
                "nif": "",
                "name": "CLIENT DIVERS",
                "address": "",
                "contact": "",
                "email": "",
                "rccm": "",
            },
            "items": [
                {
                    "name": "Article correction",
                    "description": "",
                    "item_type": "BIE",
                    "tax_group": "B",
                    "tax_rate": Decimal("16.00"),
                    "line_total": Decimal("100.00"),
                    "unit_price": Decimal("100.00"),
                    "quantity": Decimal("1.000"),
                }
            ],
            "payments": [
                {
                    "name": "ESPECES",
                    "amount": Decimal("100.00"),
                }
            ],
            "totals": {
                "total_ttc": Decimal("100.00"),
                "total_vat": Decimal("13.79"),
            },
        }
        success_result = {
            "steps": {
                "close": {
                    "ok": True,
                    "data": "R:FC910,TC910,FT910,20260327090000,NIM910,A1234567Q,FV-2026-09000,SIG910",
                }
            }
        }

        service = MCFInvoiceService(device=device)
        with patch("mcf.services_mcf.MCFClient"), patch(
            "mcf.services_mcf.MCFCommands"
        ) as mock_commands_cls:
            mock_commands_cls.return_value.send_invoice_flow.return_value = success_result

            result = service.send_invoice(commande, prepared_payload=prepared_payload)

        self.assertTrue(result["success"])
        self.assertFalse(result.get("already_sent", False))
        self.assertEqual(
            mock_commands_cls.return_value.send_invoice_flow.call_args.kwargs["invoice"]["fn"],
            "FV-2026-09000",
        )

    def test_unsaved_prepared_payload_returns_log_payload_without_persisting_log(self):
        """Verifie qu'une fiscalisation MCF preparee sans commande persistante ne cree pas de log orphelin."""

        device = MCFDevice.objects.create(
            name="MCF Test",
            port="COM9",
            company_nif="A1234567Q",
            company_isf="CD01004241-1",
            is_active=True,
            is_default=True,
        )
        prepared_payload = {
            "commande": {
                "numero": "FA-2026-00077",
                "type_facture": "FA",
                "rr": "RAN",
                "rn": "SIG-ORIG-777",
            },
            "company": {
                "mode_dgi": "ttc",
                "nif": "A1234567Q",
                "isf": "CD01004241-1",
            },
            "operator": {
                "id": "1",
                "name": "ADMIN",
            },
            "customer": {
                "type": "PP",
                "nif": "",
                "name": "CLIENT DIVERS",
                "address": "",
                "contact": "",
                "email": "",
                "rccm": "",
            },
            "items": [
                {
                    "name": "Article Test",
                    "description": "",
                    "item_type": "BIE",
                    "tax_group": "B",
                    "tax_rate": Decimal("16.00"),
                    "line_total": Decimal("100.00"),
                    "unit_price": Decimal("100.00"),
                    "quantity": Decimal("1.000"),
                }
            ],
            "payments": [],
            "totals": {
                "total_ttc": Decimal("100.00"),
                "total_vat": Decimal("16.00"),
            },
            "credit_note": {
                "nature": "RAN",
                "reference": "SIG-ORIG-777",
            },
        }
        success_result = {
            "steps": {
                "close": {
                    "ok": True,
                    "data": "R:FC777,TC777,FT777,20260327101010,NIM777,A1234567Q,FA-2026-00077,SIG777",
                }
            }
        }
        service = MCFInvoiceService(device=device)

        with patch("mcf.services_mcf.MCFClient"), patch(
            "mcf.services_mcf.MCFCommands"
        ) as mock_commands_cls, patch.object(service, "_create_log") as mock_create_log:
            mock_commands_cls.return_value.send_invoice_flow.return_value = success_result

            result = service.send_invoice(SimpleNamespace(pk=None), prepared_payload=prepared_payload)

        mock_create_log.assert_not_called()
        self.assertTrue(result["success"])
        self.assertIn("log_payload", result)
        self.assertEqual(result["log_payload"]["request_data"]["invoice"]["fn"], "FA-2026-00077")
        self.assertFalse(MCFInvoiceLog.objects.filter(commande_id=0).exists())

    def test_correction_credit_note_items_use_native_amount_for_mcf_command_31(self):
        """Verifie qu'une FA COR garde MON coherent avec PR*QTY pour le MCF."""

        service = MCFInvoiceService(
            device=MCFDevice(
                name="MCF Test",
                port="COM9",
                company_nif="A1234567Q",
                company_isf="CD01004241-1",
            )
        )
        prepared_payload = {
            "commande": {
                "numero": "FA-2026-00088",
                "type_facture": "FA",
                "type_facture_origine": "COR",
                "rr": "COR",
                "rn": "SIG-ORIG-COR",
            },
            "company": {
                "mode_dgi": "ht",
                "nif": "A1234567Q",
                "isf": "CD01004241-1",
            },
            "operator": {
                "id": "1",
                "name": "ADMIN",
            },
            "credit_note": {
                "nature": "COR",
                "reference": "SIG-ORIG-COR",
            },
            "items": [
                {
                    "name": "Article correction",
                    "description": "",
                    "item_type": "BIE",
                    "tax_group": "B",
                    "tax_rate": Decimal("16.00"),
                    "line_total": Decimal("174.00"),
                    "unit_price": Decimal("150.00"),
                    "quantity": Decimal("1.000"),
                }
            ],
        }

        invoice = service._build_invoice_from_prepared(
            prepared_payload,
            company_identity={"nif": "A1234567Q", "isf": "CD01004241-1"},
            commande=SimpleNamespace(facture_origine=None),
        )
        items = service._build_items_from_prepared(prepared_payload)

        self.assertEqual(invoice["reference_type"], "COR")
        self.assertEqual(invoice["rr"], "COR")
        self.assertEqual(items[0]["total_amount"], Decimal("150.00"))
        self.assertEqual(items[0]["unit_price"], Decimal("150.00"))
        self.assertEqual(items[0]["quantity"], Decimal("1.000"))


class MCFDuplicateInvoiceNumberRetryTests(TestCase):
    """Regroupe les tests de reprise sur numero de facture MCF duplique."""


    def setUp(self):
        """Prepare les donnees communes necessaires a ce scenario de test."""

        self.point_de_vente = PointDeVente.objects.create(nom="PDV MCF")
        self.user = get_user_model().objects.create_user(
            username="mcf_retry_user",
            email="mcf_retry_user@test.com",
            password="secret",
            point_de_vente=self.point_de_vente,
        )
        Configuration.objects.create(
            taux_change=Decimal("1.00"),
            fiscal_primary_channel="MCF",
            fiscal_fallback_mode="DISABLED",
            require_security_before_save=True,
            nif="A1234567Q",
            isf_dgi="CD01004241-1",
            mode_dgi="ttc",
            type_dgi="FV",
        )
        self.device = MCFDevice.objects.create(
            name="MCF Test",
            port="COM9",
            company_nif="A1234567Q",
            company_isf="CD01004241-1",
            is_active=True,
            is_default=True,
        )

    def test_duplicate_invoice_number_retries_with_new_numero(self):
        """Verifie qu'un numero de facture duplique declenche une reprise avec un nouveau numero."""

        commande = Commande.objects.create(
            point_de_vente=self.point_de_vente,
            vendeur=self.user,
            montant_total=Decimal("64400.00"),
            tva_montant=Decimal("8882.76"),
            taux_change_applique=Decimal("1.00"),
            type_facture="FV",
        )
        original_numero = commande.numero
        prepared_payload = {
            "fiscal_transaction_id": "tx-299",
            "commande": {
                "numero": commande.numero,
                "type_facture": "FV",
            },
            "company": {
                "mode_dgi": "ttc",
            },
            "operator": {
                "id": str(self.user.pk),
                "name": self.user.username,
            },
            "customer": {
                "type": "PP",
                "nif": "",
                "name": "CLIENT DIVERS",
                "address": "",
                "contact": "",
                "email": "",
                "rccm": "",
            },
            "items": [
                {
                    "name": "Latacer 80g",
                    "description": "",
                    "item_type": "BIE",
                    "tax_group": "B",
                    "tax_rate": Decimal("16.00"),
                    "line_total": Decimal("64400.00"),
                    "unit_price": Decimal("64400.00"),
                    "quantity": Decimal("1.000"),
                }
            ],
            "payments": [
                {
                    "name": "ESPECES",
                    "amount": Decimal("64400.00"),
                }
            ],
            "totals": {
                "total_ttc": Decimal("64400.00"),
                "total_vat": Decimal("8882.76"),
            },
        }
        duplicate_error = MCFClientError(
            "Le MCF n'a accepte aucune ouverture de facture exploitable. "
            "Tentatives: Tentative 1: Commande C0 rejetee par le MCF : "
            "E: The invoice number is already used for the previous invoice "
            "(STA=E082C080C0D8)."
        )
        success_result = {
            "steps": {
                "close": {
                    "ok": True,
                    "data": "R:FC300,TC300,FT300,20260326193000,NIM300,A1234567Q,FV-2026-00300,SIG300",
                }
            }
        }
        service = MCFInvoiceService(device=self.device)

        with patch("mcf.services_mcf.MCFClient"), patch(
            "mcf.services_mcf.MCFCommands"
        ) as mock_commands_cls:
            mock_commands_cls.return_value.send_invoice_flow.side_effect = [
                duplicate_error,
                success_result,
            ]

            result = service.send_invoice(commande, prepared_payload=prepared_payload)

        commande.refresh_from_db()
        self.assertTrue(result["success"])
        self.assertNotEqual(commande.numero, original_numero)
        self.assertEqual(prepared_payload["commande"]["numero"], commande.numero)
        self.assertEqual(
            mock_commands_cls.return_value.send_invoice_flow.call_args_list[0].kwargs["invoice"]["fn"],
            original_numero,
        )
        self.assertEqual(
            mock_commands_cls.return_value.send_invoice_flow.call_args_list[1].kwargs["invoice"]["fn"],
            commande.numero,
        )

    def test_duplicate_correction_payload_retries_without_changing_original_numero(self):
        """Verifie qu'un payload de correction duplique repart sans changer le numero d'origine."""

        commande = Commande.objects.create(
            point_de_vente=self.point_de_vente,
            vendeur=self.user,
            montant_total=Decimal("64400.00"),
            tva_montant=Decimal("8882.76"),
            taux_change_applique=Decimal("1.00"),
            type_facture="FV",
        )
        original_numero = commande.numero
        prepared_payload = {
            "operation_type": "CORRECTION_ADD",
            "bypass_existing_log": True,
            "preserve_original_numero": True,
            "commande": {
                "numero": "FV-2026-09001",
                "type_facture": "FV",
                "source_numero": commande.numero,
            },
            "company": {
                "mode_dgi": "ttc",
                "nif": "A1234567Q",
                "isf": "CD01004241-1",
            },
            "operator": {
                "id": str(self.user.pk),
                "name": self.user.username,
            },
            "customer": {
                "type": "PP",
                "nif": "",
                "name": "CLIENT DIVERS",
                "address": "",
                "contact": "",
                "email": "",
                "rccm": "",
            },
            "items": [
                {
                    "name": "Correction +1",
                    "description": "",
                    "item_type": "BIE",
                    "tax_group": "B",
                    "tax_rate": Decimal("16.00"),
                    "line_total": Decimal("64400.00"),
                    "unit_price": Decimal("64400.00"),
                    "quantity": Decimal("1.000"),
                }
            ],
            "payments": [
                {
                    "name": "ESPECES",
                    "amount": Decimal("64400.00"),
                }
            ],
            "totals": {
                "total_ttc": Decimal("64400.00"),
                "total_vat": Decimal("8882.76"),
            },
        }
        duplicate_error = MCFClientError(
            "Le MCF n'a accepte aucune ouverture de facture exploitable. "
            "Tentatives: Tentative 1: Commande C0 rejetee par le MCF : "
            "E: The invoice number is already used for the previous invoice "
            "(STA=E082C080C0D8)."
        )
        success_result = {
            "steps": {
                "close": {
                    "ok": True,
                    "data": "R:FC301,TC301,FT301,20260327100000,NIM301,A1234567Q,FV-2026-09002,SIG301",
                }
            }
        }
        service = MCFInvoiceService(device=self.device)

        with patch("mcf.services_mcf.MCFClient"), patch(
            "mcf.services_mcf.MCFCommands"
        ) as mock_commands_cls:
            mock_commands_cls.return_value.send_invoice_flow.side_effect = [
                duplicate_error,
                success_result,
            ]

            result = service.send_invoice(commande, prepared_payload=prepared_payload)

        self.assertTrue(result["success"])
        commande.refresh_from_db()
        self.assertEqual(commande.numero, original_numero)
        self.assertNotEqual(prepared_payload["commande"]["numero"], "FV-2026-09001")
        self.assertEqual(
            mock_commands_cls.return_value.send_invoice_flow.call_args_list[0].kwargs["invoice"]["fn"],
            "FV-2026-09001",
        )
        self.assertEqual(
            mock_commands_cls.return_value.send_invoice_flow.call_args_list[1].kwargs["invoice"]["fn"],
            prepared_payload["commande"]["numero"],
        )


class MCFOriginalReferenceRetryTests(TestCase):
    """Regroupe les reprises sur reference source invalide pour les avoirs MCF."""


    def setUp(self):
        """Prepare les donnees communes necessaires a ce scenario de test."""

        self.point_de_vente = PointDeVente.objects.create(nom="PDV MCF Ref")
        self.user = get_user_model().objects.create_user(
            username="mcf_ref_retry_user",
            email="mcf_ref_retry_user@test.com",
            password="secret",
            point_de_vente=self.point_de_vente,
        )
        Configuration.objects.create(
            taux_change=Decimal("1.00"),
            fiscal_primary_channel="MCF",
            fiscal_fallback_mode="DISABLED",
            require_security_before_save=True,
            nif="A1234567Q",
            isf_dgi="CD01004241-1",
            mode_dgi="ttc",
            type_dgi="FV",
        )
        self.device = MCFDevice.objects.create(
            name="MCF Reference Retry",
            port="COM10",
            company_nif="A1234567Q",
            company_isf="CD01004241-1",
            is_active=True,
            is_default=True,
        )

    def test_credit_note_retries_with_next_source_reference_after_38h_rejection(self):
        """Verifie qu'un avoir relance le flux avec le numero source suivant apres un rejet 38h."""

        original = Commande.objects.create(
            point_de_vente=self.point_de_vente,
            vendeur=self.user,
            montant_total=Decimal("115000.00"),
            tva_montant=Decimal("0.00"),
            montant_paye=Decimal("115000.00"),
            taux_change_applique=Decimal("1.00"),
            type_facture="FV",
            codedefdgi="SIG-ORIG-306",
            fiscal_channel="MCF",
        )
        facture_avoir = Commande.objects.create(
            point_de_vente=self.point_de_vente,
            vendeur=self.user,
            montant_total=Decimal("115000.00"),
            tva_montant=Decimal("0.00"),
            montant_paye=Decimal("115000.00"),
            taux_change_applique=Decimal("1.00"),
            type_facture="FA",
            facture_origine=original,
            nature_avoir="RAM",
            reference_avoir=original.codedefdgi,
        )
        prepared_payload = {
            "commande": {
                "numero": "FA-2026-00001",
                "type_facture": "FA",
            },
            "company": {
                "mode_dgi": "ttc",
                "nif": "A1234567Q",
                "isf": "CD01004241-1",
            },
            "operator": {
                "id": str(self.user.pk),
                "name": self.user.username,
            },
            "customer": {
                "type": "PP",
                "nif": "",
                "name": "CLIENT DIVERS",
                "address": "",
                "contact": "",
                "email": "",
                "rccm": "",
            },
            "items": [
                {
                    "name": "Frais d'inscription",
                    "description": "",
                    "item_type": "BIE",
                    "tax_group": "A",
                    "tax_rate": Decimal("0.00"),
                    "line_total": Decimal("115000.00"),
                    "unit_price": Decimal("115000.00"),
                    "quantity": Decimal("1.000"),
                }
            ],
            "payments": [
                {
                    "name": "ESPECES",
                    "amount": Decimal("115000.00"),
                }
            ],
            "totals": {
                "total_ttc": Decimal("115000.00"),
                "total_vat": Decimal("0.00"),
            },
            "credit_note": {
                "nature": "RAM",
                "reference": original.codedefdgi,
            },
        }
        invalid_reference_error = MCFClientError(
            "Echec de la normalisation 38h : E: Erreur du serveur: "
            "La reference de la facture originale n'est pas valide "
            "(la facture originale est introuvable)"
        )
        success_result = {
            "steps": {
                "close": {
                    "ok": True,
                    "data": "R:FC410,TC410,FT410,20260327120000,NIM410,A1234567Q,FA-2026-00001,SIG410",
                }
            }
        }
        service = MCFInvoiceService(device=self.device)

        with patch("mcf.services_mcf.MCFClient"), patch(
            "mcf.services_mcf.MCFCommands"
        ) as mock_commands_cls:
            mock_commands_cls.return_value.send_invoice_flow.side_effect = [
                invalid_reference_error,
                success_result,
            ]

            result = service.send_invoice(facture_avoir, prepared_payload=prepared_payload)

        self.assertTrue(result["success"])
        self.assertEqual(
            mock_commands_cls.return_value.send_invoice_flow.call_args_list[0].kwargs["invoice"]["rn"],
            original.codedefdgi,
        )
        self.assertEqual(
            mock_commands_cls.return_value.send_invoice_flow.call_args_list[1].kwargs["invoice"]["rn"],
            original.numero,
        )
        self.assertEqual(
            mock_commands_cls.return_value.send_invoice_flow.call_args_list[1].kwargs["invoice"]["rr"],
            "RAM",
        )


class MCFItemTypeFallbackTests(TestCase):
    """Regroupe les tests de repli sur le type d'article attendu par le MCF."""


    def test_retry_item_with_required_type_for_tax_group(self):
        """Verifie que le repli article reutilise le type requis pour le groupe de taxe."""

        commands = MCFCommands(client=SimpleNamespace())
        error_result = {
            "response": {
                "data_text": "E: Seul le type TAX est autorise pour ce groupe de TVA!",
                "status_hex": "E082C880C0D8",
            }
        }
        success_result = {
            "response": {
                "data_text": "57500,57500,0,0",
                "status_hex": "C080C880C0D8",
            }
        }
        item = {
            "nom": "Abonnement internet mensuel",
            "desc": "",
            "itype": "SER",
            "tax_group": "N",
            "tax_rate": Decimal("0.00"),
            "total_amount": Decimal("57500.00"),
            "unit_price": Decimal("57500.00"),
            "quantity": Decimal("1.000"),
            "fallback_tax_groups": ["N"],
        }

        with patch.object(commands, "add_item", side_effect=[error_result, success_result]) as mock_add_item:
            result = commands._add_item_with_fallback(item)

        self.assertEqual(result, success_result)
        self.assertEqual(mock_add_item.call_args_list[0].kwargs["itype"], "SER")
        self.assertEqual(mock_add_item.call_args_list[1].kwargs["itype"], "TAX")

    def test_retry_item_with_next_candidate_on_generic_tr_error(self):
        """Verifie qu'un rejet TR generique essaie aussi le candidat de type suivant."""

        commands = MCFCommands(client=SimpleNamespace())
        error_result = {
            "response": {
                "data_text": "E: TR",
                "status_hex": "E082C880C0D8",
            }
        }
        success_result = {
            "response": {
                "data_text": "46000,46000,0,0",
                "status_hex": "C080C880C0D8",
            }
        }
        item = {
            "nom": "Abonnement internet",
            "desc": "",
            "itype": "TAX",
            "tax_group": "N",
            "tax_rate": Decimal("0.00"),
            "total_amount": Decimal("46000.00"),
            "unit_price": Decimal("46000.00"),
            "quantity": Decimal("1.000"),
            "fallback_tax_groups": ["N"],
            "fallback_item_types": ["TAX", "SER"],
        }

        with patch.object(commands, "add_item", side_effect=[error_result, success_result]) as mock_add_item:
            result = commands._add_item_with_fallback(item)

        self.assertEqual(result, success_result)
        self.assertEqual(mock_add_item.call_args_list[0].kwargs["itype"], "TAX")
        self.assertEqual(mock_add_item.call_args_list[1].kwargs["itype"], "SER")


class MCFCreditNoteOpenCommandTests(TestCase):
    """Regroupe les tests d'ouverture des avoirs MCF."""


    def test_open_invoice_uses_credit_note_nature_and_reference_number(self):
        """Verifie que C0 transmet bien la nature de l'avoir puis la reference du document source."""

        client = Mock()
        client.send_command.return_value = {"ok": True}
        commands = MCFCommands(client=client)

        commands.open_invoice(
            opid="1",
            opn="ADMIN",
            nif="A1234567Q",
            invoice_type="FA",
            reference_type="RAN",
            rr="RAN",
            rn="SIG-ORIG-306",
            pmode="TTC",
            isf="CD01004241-1",
            fn="FA-2026-00001",
        )

        client.send_command.assert_called_once_with(
            "C0",
            "1,ADMIN,A1234567Q,FA,RAN,SIG-ORIG-306,TTC,CD01004241-1,FA-2026-00001",
        )

    def test_credit_note_open_attempts_keep_rr_as_nature_and_try_rn_candidates_in_order(self):
        """Verifie que l'ouverture d'un avoir ne permute jamais RR/RN et essaie les RN en sequence."""

        commands = MCFCommands(client=Mock())

        attempts = commands._build_credit_note_open_attempts(
            {
                "invoice_type": "FA",
                "reference_type": "RAN",
                "reference_candidates": [
                    {"rr": "RAN", "rn": "SIG-ORIG-306"},
                    {"rr": "RAN", "rn": "FV-2026-00018"},
                ],
            }
        )

        self.assertEqual(
            [
                {
                    "invoice_type": attempt["invoice_type"],
                    "reference_type": attempt["reference_type"],
                    "rr": attempt["rr"],
                    "rn": attempt["rn"],
                }
                for attempt in attempts
            ],
            [
                {
                    "invoice_type": "FA",
                    "reference_type": "RAN",
                    "rr": "RAN",
                    "rn": "SIG-ORIG-306",
                },
                {
                    "invoice_type": "FA",
                    "reference_type": "RAN",
                    "rr": "RAN",
                    "rn": "FV-2026-00018",
                },
            ],
        )


class MCFSubtotalValidationTests(TestCase):
    """Regroupe les tests de validation des sous-totaux retournes par le MCF."""


    def test_validate_subtotal_uses_total_vat_field_from_33h_response(self):
        """Verifie que la validation du sous-total utilise le champ total VAT de la reponse 33H."""

        commands = MCFCommands(client=SimpleNamespace())
        subtotal_result = {
            "response": {
                "data_text": (
                    "7035700,338650.98,230000,85100,1943500,138000,690000,920000,69000,"
                    "11500,602600,80500,575000,782000,736000,103500,46000,23000,0,"
                    "11737.93,92547.62,0,0,126896.55,3285.71,0,0,0,0,0,0,103500,455.45,"
                    "227.72,0,0"
                ),
                "status_hex": "C080C880C0D8",
            }
        }

        result = commands.validate_subtotal(
            expected_total=Decimal("7035700.00"),
            expected_vat=Decimal("338650.98"),
            subtotal_result=subtotal_result,
        )

        self.assertTrue(result["ok"])
        self.assertEqual(result["mcf_total"], "7035700")
        self.assertEqual(result["mcf_vat"], "338650.98")
        self.assertEqual(result["mcf_vat_by_groups"], "338650.98")


class MCFSendInvoiceFlowCloseAmountTests(TestCase):
    """Regroupe les tests du montant de cloture dans le flux d'envoi MCF."""


    def test_send_invoice_flow_uses_validated_mcf_vat_for_close(self):
        """Verifie que le flux d'envoi utilise la TVA MCF validee lors de la cloture."""

        commands = MCFCommands(client=Mock())
        subtotal_result = {
            "response": {
                "data_text": (
                    "1902100,96184.57,0,62100,1840000,0,0,0,0,0,0,0,0,0,0,0,0,0,0,"
                    "8565.52,87619.05,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0"
                ),
                "status_hex": "C080C880C0D8",
            }
        }

        with patch.object(
            commands,
            "get_status",
            return_value={"response": {"status_hex": "C080C080C0D8"}},
        ), patch.object(
            commands,
            "_abort_open_invoice_if_needed",
            return_value=None,
        ), patch.object(
            commands,
            "set_customer_info",
            return_value={"ok": True},
        ), patch.object(commands, "_ensure_command_success"), patch.object(
            commands, "_ensure_command_allowed"
        ), patch.object(
            commands,
            "open_invoice",
            return_value={"ok": True},
        ), patch.object(
            commands,
            "get_subtotal",
            return_value=subtotal_result,
        ), patch.object(
            commands,
            "add_payment",
            return_value={"ok": True},
        ), patch.object(
            commands,
            "close_invoice",
            return_value={"ok": True, "data": "R:OK"},
        ) as mock_close:
            result = commands.send_invoice_flow(
                customer={
                    "ctype": "PP",
                    "cnif": "",
                    "cnom": "CLIENT TEST",
                    "cadd": "",
                    "ctel": "",
                    "ceml": "",
                    "crccm": "",
                },
                invoice={
                    "opid": "1",
                    "opn": "ADMIN",
                    "nif": "A1234567Q",
                    "invoice_type": "FV",
                    "pmode": "TTC",
                    "isf": "CD01004241-1",
                    "fn": "FV-2026-00001",
                },
                items=[],
                expected_total=Decimal("1902100.00"),
                expected_vat=Decimal("96184.56486042692939244663421"),
            )

        mock_close.assert_called_once_with(Decimal("1902100"), Decimal("96184.57"))
        self.assertEqual(
            result["steps"]["close_input"],
            {"total_ttc": "1902100", "total_tva": "96184.57"},
        )


class MCFCloseRetryTests(TestCase):
    """Regroupe les reprises de normalisation 38h sur indisponibilite temporaire."""


    def test_close_invoice_retries_temporary_server_request_before_success(self):
        """Verifie que 38h est relance quand le boitier demande explicitement de reessayer."""

        client = Mock()
        client.send_command.side_effect = [
            {
                "response": {
                    "data_text": "E: Demander l'etat du serveur avant normalisation",
                    "status_hex": "E082C880C0D8",
                }
            },
            {
                "response": {
                    "data_text": "R:FC001,TC001,FT001,20260327094500,NIM001,A1234567Q,FV-2026-00001,SIG001",
                    "status_hex": "C080C880C0D8",
                }
            },
        ]
        commands = MCFCommands(client=client)

        with patch.object(
            commands,
            "get_server_connection_status",
            return_value={"response": {"data_text": "R:CONNECTED", "status_hex": "C080C080C0D8"}},
        ) as mock_server_status, patch("mcf.commands.time.sleep") as mock_sleep:
            result = commands.close_invoice(Decimal("100.00"), Decimal("16.00"))

        self.assertTrue(result["ok"])
        self.assertEqual(result["status"], "SUCCESS")
        self.assertEqual(len(result["transient_attempts"]), 1)
        self.assertEqual(
            result["transient_attempts"][0]["server_status"]["data"],
            "R:CONNECTED",
        )
        mock_server_status.assert_called_once()
        mock_sleep.assert_called_once()

    def test_send_invoice_flow_raises_clear_message_when_close_server_stays_unavailable(self):
        """Verifie qu'un echec 38h temporaire remonte un message metier explicite."""

        commands = MCFCommands(client=Mock())
        subtotal_result = {
            "response": {
                "data_text": (
                    "116.00,16.00,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,"
                    "16.00,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0"
                ),
                "status_hex": "C080C880C0D8",
            }
        }

        with patch.object(
            commands,
            "get_status",
            return_value={"response": {"status_hex": "C080C080C0D8"}},
        ), patch.object(
            commands,
            "_abort_open_invoice_if_needed",
            return_value=None,
        ), patch.object(
            commands,
            "set_customer_info",
            return_value={"ok": True},
        ), patch.object(commands, "_ensure_command_success"), patch.object(
            commands, "_ensure_command_allowed"
        ), patch.object(
            commands,
            "open_invoice",
            return_value={"ok": True},
        ), patch.object(
            commands,
            "get_subtotal",
            return_value=subtotal_result,
        ), patch.object(
            commands,
            "add_payment",
            return_value={"ok": True},
        ), patch.object(
            commands,
            "close_invoice",
            return_value={
                "ok": False,
                "status": "SERVER_UNAVAILABLE",
                "data": "E: Demander l'etat du serveur avant normalisation",
                "server_status": {
                    "ok": False,
                    "status": "SERVER_STATUS",
                    "data": "E: Serveur indisponible",
                    "result": {},
                },
            },
        ):
            with self.assertRaises(MCFClientError) as exc:
                commands.send_invoice_flow(
                    customer={
                        "ctype": "PP",
                        "cnif": "",
                        "cnom": "CLIENT TEST",
                        "cadd": "",
                        "ctel": "",
                        "ceml": "",
                        "crccm": "",
                    },
                    invoice={
                        "opid": "1",
                        "opn": "ADMIN",
                        "nif": "A1234567Q",
                        "invoice_type": "FV",
                        "pmode": "TTC",
                        "isf": "CD01004241-1",
                        "fn": "FV-2026-00001",
                    },
                    items=[],
                    expected_total=Decimal("116.00"),
                    expected_vat=Decimal("16.00"),
                )

        self.assertIn("serveur MCF est temporairement indisponible", str(exc.exception))
        self.assertIn("Etat C2: E: Serveur indisponible", str(exc.exception))


class MCFClockChronologyTests(TestCase):
    """Couvre les rejets MCF lies a une incoherence d'horloge ou de chronologie."""


    def test_close_invoice_classifies_error_162_without_server_retry(self):
        """Verifie que l'erreur 162 n'est plus traitee comme une indisponibilite serveur."""

        client = Mock()
        client.send_command.return_value = {
            "response": {
                "data_text": "E: Demander l'etat du serveur avant normalisation. Erreur 162",
                "status_hex": "E082C880C0D8",
            }
        }
        commands = MCFCommands(client=client)

        with patch.object(commands, "get_server_connection_status") as mock_server_status:
            result = commands.close_invoice(Decimal("100.00"), Decimal("16.00"))

        self.assertFalse(result["ok"])
        self.assertEqual(result["status"], "CLOCK_INCOHERENT")
        mock_server_status.assert_not_called()

    def test_send_invoice_flow_blocks_before_close_when_clock_would_go_backwards(self):
        """Verifie qu'un garde-fou bloque avant 38h si l'heure systeme est incoherente."""

        commands = MCFCommands(client=Mock())
        subtotal_result = {
            "response": {
                "data_text": (
                    "116.00,16.00,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,"
                    "16.00,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0"
                ),
                "status_hex": "C080C880C0D8",
            }
        }

        with patch.object(
            commands,
            "get_status",
            side_effect=[
                {"response": {"status_hex": "C080C080C0D8"}},
                {"response": {"status_hex": "C080C880C0D8"}},
            ],
        ), patch.object(
            commands,
            "_abort_open_invoice_if_needed",
            return_value=None,
        ), patch.object(
            commands,
            "set_customer_info",
            return_value={"ok": True},
        ), patch.object(commands, "_ensure_command_success"), patch.object(
            commands, "_ensure_command_allowed"
        ), patch.object(
            commands,
            "open_invoice",
            return_value={"ok": True},
        ), patch.object(
            commands,
            "get_subtotal",
            return_value=subtotal_result,
        ), patch.object(
            commands,
            "get_mcf_datetime",
            return_value={
                "command": "C1",
                "ok": True,
                "raw": "R:20260327100500",
                "datetime": datetime(2026, 3, 27, 10, 5, 0),
                "result": {},
            },
        ), patch.object(
            commands,
            "add_payment",
            return_value={"ok": True},
        ) as mock_add_payment, patch.object(
            commands,
            "close_invoice",
            return_value={"ok": True},
        ) as mock_close:
            with self.assertRaises(MCFClientError) as exc:
                commands.send_invoice_flow(
                    customer={
                        "ctype": "PP",
                        "cnif": "",
                        "cnom": "CLIENT TEST",
                        "cadd": "",
                        "ctel": "",
                        "ceml": "",
                        "crccm": "",
                    },
                    invoice={
                        "opid": "1",
                        "opn": "ADMIN",
                        "nif": "A1234567Q",
                        "invoice_type": "FA",
                        "pmode": "TTC",
                        "isf": "CD01004241-1",
                        "fn": "FA-2026-00001",
                        "rr": "COR",
                        "rn": "SIG-ORIG-001",
                        "reference_type": "COR",
                    },
                    items=[],
                    expected_total=Decimal("116.00"),
                    expected_vat=Decimal("16.00"),
                    system_datetime=datetime(2026, 3, 27, 10, 0, 0),
                    minimum_finalize_datetime=datetime(2026, 3, 27, 10, 15, 0),
                )

        self.assertIn("heure superieure au dernier ticket fiscal", str(exc.exception))
        mock_add_payment.assert_not_called()
        mock_close.assert_not_called()

    def test_abort_open_invoice_treats_already_cancelled_cleanup_as_non_blocking(self):
        """Verifie que `E: Annulee` ne masque pas l'erreur principale si le boitier est deja ferme."""

        commands = MCFCommands(client=Mock())

        cleanup = commands._abort_open_invoice_if_needed(
            current_status={"response": {"status_hex": "C080C080C0D8"}},
            context="apres erreur 38h",
        )
        self.assertIsNone(cleanup)

        with patch.object(
            commands,
            "cancel_normalization",
            return_value={"ok": False, "data": "E: Annulee", "result": {}},
        ), patch.object(
            commands,
            "get_status",
            return_value={"response": {"status_hex": "C080C080C0D8"}},
        ):
            cleanup = commands._abort_open_invoice_if_needed(
                current_status={"response": {"status_hex": "C080C880C0D8"}},
                context="apres erreur 38h",
            )

        self.assertIsNotNone(cleanup)
        self.assertTrue(cleanup["cancel"]["ok"])
        self.assertEqual(cleanup["cancel"]["status"], "ALREADY_CANCELLED")


class MCFClockChronologyServiceTests(TestCase):
    """Verifie le reclassement des erreurs d'horloge cote service MCF."""


    def setUp(self):
        """Prepare les donnees du service MCF."""

        self.device = MCFDevice.objects.create(
            name="MCF Clock Service",
            port="COM13",
            company_nif="A1234567Q",
            company_isf="CD01004241-1",
            is_active=True,
            is_default=False,
        )
        self.service = MCFInvoiceService(device=self.device)

    def test_temporary_server_detection_ignores_clock_incoherence(self):
        """Verifie qu'une incoherence d'horloge n'est pas reclassee en indisponibilite temporaire."""

        message = (
            "Echec de la normalisation 38h : L'horloge du MCF est incoherente "
            "avec le dernier enregistrement fiscal. Veuillez synchroniser le "
            "boitier avec une heure superieure au dernier ticket fiscal."
        )

        self.assertFalse(self.service._is_temporary_server_unavailable_mcf_error(message))


class MCFCustomerNifNormalizationTests(TestCase):
    """Regroupe les tests de normalisation du NIF client avant envoi MCF."""


    def setUp(self):
        """Prepare les donnees communes necessaires a ce scenario de test."""

        self.device = MCFDevice.objects.create(
            name="MCF Test",
            port="COM9",
            company_nif="A2560363Q",
            company_isf="CD01004241-1",
            is_active=True,
            is_default=True,
        )
        self.service = MCFInvoiceService(device=self.device)

    def test_prepared_customer_maps_non_pp_pm_type_to_pm_and_normalizes_nif(self):
        """Verifie que le client prepare mappe les types non PP/PM vers PM et normalise le NIF."""

        customer = self.service._build_customer_from_prepared(
            {
                "customer": {
                    "type": "AO",
                    "nif": "A 1922432-E",
                    "name": "ETS BAMAKO",
                    "address": "Kinshasa",
                    "contact": "0999999999",
                    "email": "",
                    "rccm": "",
                }
            }
        )

        self.assertEqual(customer["ctype"], "PM")
        self.assertEqual(customer["cnif"], "A1922432E")

    def test_prepared_pm_customer_with_invalid_nif_is_blocked_before_mcf(self):
        """Verifie qu'un client PM avec NIF invalide est bloque avant l'envoi MCF."""

        with self.assertRaises(MCFInvoiceServiceError):
            self.service._build_customer_from_prepared(
                {
                    "customer": {
                        "type": "PM",
                        "nif": "12345",
                        "name": "Client Invalide",
                        "address": "",
                        "contact": "",
                        "email": "",
                        "rccm": "",
                    }
                }
            )

    def test_prepared_pp_customer_with_invalid_nif_is_blocked_before_mcf(self):
        """Verifie qu'un client PP avec NIF invalide est bloque avant l'envoi MCF."""

        with self.assertRaises(MCFInvalidNIFError):
            self.service._build_customer_from_prepared(
                {
                    "customer": {
                        "type": "PP",
                        "nif": "12345",
                        "name": "Client PP Invalide",
                        "address": "",
                        "contact": "",
                        "email": "",
                        "rccm": "",
                    }
                }
            )


class MCFAdapterNifBusinessErrorTests(TestCase):
    """Regroupe les tests de traduction des erreurs NIF cote adaptateur MCF."""


    def setUp(self):
        """Prepare les donnees communes necessaires a ce scenario de test."""

        self.point_de_vente = PointDeVente.objects.create(nom="PDV NIF")
        self.user = get_user_model().objects.create_user(
            username="mcf_nif_user",
            email="mcf_nif_user@test.com",
            password="secret",
            point_de_vente=self.point_de_vente,
        )
        self.client_type_pp = ClientType.objects.create(code="PP", name="Personne physique")
        self.client_record = Client.objects.create(
            nom_complet="Client NIF Invalide",
            nif="12345",
            client_type=self.client_type_pp,
        )
        self.commande = Commande.objects.create(
            point_de_vente=self.point_de_vente,
            vendeur=self.user,
            client=self.client_record,
            montant_total=Decimal("100.00"),
            tva_montant=Decimal("16.00"),
            taux_change_applique=Decimal("1.00"),
            type_facture="FV",
        )
        self.device = MCFDevice.objects.create(
            name="MCF Test",
            port="COM9",
            company_nif="A1234567Q",
            company_isf="CD01004241-1",
            is_active=True,
            is_default=True,
        )
        self.prepared_payload = {
            "fiscal_transaction_id": "tx-nif-001",
            "commande": {
                "numero": self.commande.numero,
                "type_facture": "FV",
            },
            "company": {
                "mode_dgi": "ttc",
            },
            "operator": {
                "id": str(self.user.pk),
                "name": self.user.username,
            },
            "customer": {
                "type": "PP",
                "nif": "12345",
                "name": "Client NIF Invalide",
                "address": "",
                "contact": "",
                "email": "",
                "rccm": "",
            },
            "items": [
                {
                    "name": "Article Test",
                    "description": "",
                    "item_type": "BIE",
                    "tax_group": "B",
                    "tax_rate": Decimal("16.00"),
                    "line_total": Decimal("100.00"),
                    "unit_price": Decimal("100.00"),
                    "quantity": Decimal("1.000"),
                }
            ],
            "payments": [
                {
                    "name": "ESPECES",
                    "amount": Decimal("100.00"),
                }
            ],
            "totals": {
                "total_ttc": Decimal("100.00"),
                "total_vat": Decimal("16.00"),
            },
        }

    def test_adapter_turns_invalid_nif_into_business_error(self):
        """Verifie que l'adaptateur transforme un NIF invalide en erreur metier."""

        adapter = MCFAdapter()

        with patch.object(adapter, "_ensure_device_is_ready", return_value=None):
            with self.assertRaises(FiscalBusinessError) as exc:
                adapter.fiscalize(self.commande, self.prepared_payload)

        self.assertIn("format du NIF", str(exc.exception))


class MCFNifRetryStrategyTests(TestCase):
    """Regroupe les tests de strategie de reprise sur rejet NIF par le MCF."""


    def setUp(self):
        """Prepare les donnees communes necessaires a ce scenario de test."""

        self.point_de_vente = PointDeVente.objects.create(nom="PDV Retry NIF")
        self.user = get_user_model().objects.create_user(
            username="mcf_nif_retry_user",
            email="mcf_nif_retry_user@test.com",
            password="secret",
            point_de_vente=self.point_de_vente,
        )
        Configuration.objects.create(
            taux_change=Decimal("1.00"),
            fiscal_primary_channel="MCF",
            fiscal_fallback_mode="DISABLED",
            require_security_before_save=True,
            nif="B1234567R",
            isf_dgi="CD01004241-1",
            mode_dgi="ttc",
            type_dgi="FV",
        )
        self.device = MCFDevice.objects.create(
            name="MCF Test",
            port="COM9",
            company_nif="A1234567Q",
            company_isf="CD01004241-1",
            is_active=True,
            is_default=True,
        )

    def test_send_invoice_retries_without_nif_for_pp_customer_when_c3_rejects_it(self):
        """Verifie que l'envoi reprend sans NIF pour un client PP lorsque le code C3 le rejette."""

        commande = Commande.objects.create(
            point_de_vente=self.point_de_vente,
            vendeur=self.user,
            montant_total=Decimal("100.00"),
            tva_montant=Decimal("16.00"),
            taux_change_applique=Decimal("1.00"),
            type_facture="FV",
        )
        prepared_payload = {
            "fiscal_transaction_id": "tx-pp-nif-001",
            "commande": {
                "numero": commande.numero,
                "type_facture": "FV",
            },
            "company": {
                "nif": "A1234567Q",
                "isf": "CD01004241-1",
                "mode_dgi": "ttc",
            },
            "operator": {
                "id": str(self.user.pk),
                "name": self.user.username,
            },
            "customer": {
                "type": "PP",
                "nif": "A1922432E",
                "name": "Client PP",
                "address": "",
                "contact": "",
                "email": "",
                "rccm": "",
            },
            "items": [
                {
                    "name": "Article Test",
                    "description": "",
                    "item_type": "BIE",
                    "tax_group": "B",
                    "tax_rate": Decimal("16.00"),
                    "line_total": Decimal("100.00"),
                    "unit_price": Decimal("100.00"),
                    "quantity": Decimal("1.000"),
                }
            ],
            "payments": [
                {
                    "name": "ESPECES",
                    "amount": Decimal("100.00"),
                }
            ],
            "totals": {
                "total_ttc": Decimal("100.00"),
                "total_vat": Decimal("16.00"),
            },
        }
        c3_error = MCFClientError(
            "Le MCF n'a accepte aucune ouverture de facture exploitable. "
            "Tentatives: Tentative 1: Commande C3 rejetée par le MCF : "
            "E: NIF invalide! (STA=E082C080C0D8)."
        )
        success_result = {
            "steps": {
                "close": {
                    "ok": True,
                    "data": "R:FC301,TC301,FT301,20260327004000,NIM301,A1234567Q,FV-2026-00301,SIG301",
                }
            }
        }
        service = MCFInvoiceService(device=self.device)

        with patch("mcf.services_mcf.MCFClient"), patch(
            "mcf.services_mcf.MCFCommands"
        ) as mock_commands_cls:
            mock_commands_cls.return_value.send_invoice_flow.side_effect = [
                c3_error,
                success_result,
            ]

            result = service.send_invoice(commande, prepared_payload=prepared_payload)

        self.assertTrue(result["success"])
        self.assertEqual(
            mock_commands_cls.return_value.send_invoice_flow.call_args_list[0].kwargs["customer"]["cnif"],
            "A1922432E",
        )
        self.assertEqual(
            mock_commands_cls.return_value.send_invoice_flow.call_args_list[1].kwargs["customer"]["cnif"],
            "",
        )

    def test_send_invoice_retries_with_configuration_company_nif_when_c0_rejects_device_nif(self):
        """Verifie que l'envoi reprend avec le NIF entreprise de configuration lorsque C0 rejette le NIF du device."""

        commande = Commande.objects.create(
            point_de_vente=self.point_de_vente,
            vendeur=self.user,
            montant_total=Decimal("100.00"),
            tva_montant=Decimal("16.00"),
            taux_change_applique=Decimal("1.00"),
            type_facture="FV",
        )
        prepared_payload = {
            "fiscal_transaction_id": "tx-company-nif-001",
            "commande": {
                "numero": commande.numero,
                "type_facture": "FV",
            },
            "company": {
                "nif": "B1234567R",
                "isf": "CD01004241-1",
                "mode_dgi": "ttc",
            },
            "operator": {
                "id": str(self.user.pk),
                "name": self.user.username,
            },
            "customer": {
                "type": "PP",
                "nif": "",
                "name": "CLIENT DIVERS",
                "address": "",
                "contact": "",
                "email": "",
                "rccm": "",
            },
            "items": [
                {
                    "name": "Article Test",
                    "description": "",
                    "item_type": "BIE",
                    "tax_group": "B",
                    "tax_rate": Decimal("16.00"),
                    "line_total": Decimal("100.00"),
                    "unit_price": Decimal("100.00"),
                    "quantity": Decimal("1.000"),
                }
            ],
            "payments": [
                {
                    "name": "ESPECES",
                    "amount": Decimal("100.00"),
                }
            ],
            "totals": {
                "total_ttc": Decimal("100.00"),
                "total_vat": Decimal("16.00"),
            },
        }
        c0_error = MCFClientError(
            "Le MCF n'a accepte aucune ouverture de facture exploitable. "
            "Tentatives: Tentative 1: Commande C0 rejetée par le MCF : "
            "E: NIF invalide! (STA=E082C080C0D8)."
        )
        success_result = {
            "steps": {
                "close": {
                    "ok": True,
                    "data": "R:FC302,TC302,FT302,20260327004500,NIM302,B1234567R,FV-2026-00302,SIG302",
                }
            }
        }
        service = MCFInvoiceService(device=self.device)

        with patch("mcf.services_mcf.MCFClient"), patch(
            "mcf.services_mcf.MCFCommands"
        ) as mock_commands_cls:
            mock_commands_cls.return_value.send_invoice_flow.side_effect = [
                c0_error,
                success_result,
            ]

            result = service.send_invoice(commande, prepared_payload=prepared_payload)

        self.assertTrue(result["success"])
        self.assertEqual(
            mock_commands_cls.return_value.send_invoice_flow.call_args_list[0].kwargs["invoice"]["nif"],
            "A1234567Q",
        )
        self.assertEqual(
            mock_commands_cls.return_value.send_invoice_flow.call_args_list[1].kwargs["invoice"]["nif"],
            "B1234567R",
        )


class MCFPreparedItemOptimizationTests(TestCase):
    """Regroupe les tests d'optimisation des articles prepares pour le MCF."""


    def setUp(self):
        """Prepare les donnees communes necessaires a ce scenario de test."""

        self.device = MCFDevice.objects.create(
            name="MCF Test",
            port="COM9",
            company_nif="A2560363Q",
            company_isf="CD01004241-1",
            is_active=True,
            is_default=True,
        )
        self.service = MCFInvoiceService(device=self.device)

    def test_build_items_from_prepared_prefers_tax_for_special_group(self):
        """Verifie que la construction des articles prepares privilegie la taxe pour les groupes speciaux."""

        items = self.service._build_items_from_prepared(
            {
                "items": [
                    {
                        "name": "Abonnement internet",
                        "description": "",
                        "item_type": "SER",
                        "tax_group": "N",
                        "tax_rate": Decimal("0.00"),
                        "line_total": Decimal("46000.00"),
                        "unit_price": Decimal("46000.00"),
                        "quantity": Decimal("1.000"),
                    }
                ]
            }
        )

        self.assertEqual(items[0]["itype"], "TAX")
        self.assertEqual(items[0]["fallback_item_types"], ["TAX", "SER"])

    def test_build_items_from_prepared_normalizes_special_group_rate_for_mcf(self):
        """Verifie que les groupes speciaux n'envoient pas un taux 100% brut au MCF."""

        items = self.service._build_items_from_prepared(
            {
                "items": [
                    {
                        "name": "Abonnement internet",
                        "description": "",
                        "item_type": "SER",
                        "tax_group": "N",
                        "tax_rate": Decimal("100.00"),
                        "line_total": Decimal("46000.00"),
                        "unit_price": Decimal("46000.00"),
                        "quantity": Decimal("1.000"),
                    }
                ]
            }
        )

        self.assertEqual(items[0]["tax_rate"], Decimal("0.00"))


class MCFCreditNoteReferenceTests(TestCase):
    """Regroupe les tests de reference des avoirs MCF."""


    def setUp(self):
        """Prepare les donnees communes necessaires a ce scenario de test."""

        self.point_de_vente = PointDeVente.objects.create(nom="PDV Avoir")
        self.user = get_user_model().objects.create_user(
            username="mcf_credit_ref_user",
            email="mcf_credit_ref_user@test.com",
            password="secret",
            point_de_vente=self.point_de_vente,
        )
        Configuration.objects.create(
            taux_change=Decimal("1.00"),
            fiscal_primary_channel="MCF",
            fiscal_fallback_mode="DISABLED",
            require_security_before_save=True,
            nif="A1234567Q",
            isf_dgi="CD01004241-1",
            mode_dgi="ttc",
            type_dgi="FV",
        )
        self.device = MCFDevice.objects.create(
            name="MCF Test",
            port="COM9",
            company_nif="A1234567Q",
            company_isf="CD01004241-1",
            is_active=True,
            is_default=True,
        )

    def test_build_credit_note_reference_uses_credit_note_nature_and_canonical_reference(self):
        """Verifie que RR porte la nature et RN la reference canonique du document source."""

        original = Commande.objects.create(
            point_de_vente=self.point_de_vente,
            vendeur=self.user,
            montant_total=Decimal("100.00"),
            tva_montant=Decimal("16.00"),
            taux_change_applique=Decimal("1.00"),
            type_facture="FV",
            counters="13/18 FV",
            codedefdgi="SIG-ORIG-306",
            fiscal_channel="MCF",
        )
        MCFInvoiceLog.objects.create(
            commande_id=original.pk,
            device=self.device,
            success=True,
            response_data={
                "security": {
                    "fc": "13",
                    "tc": "18",
                    "sig": "SIG-ORIG-306",
                    "counters": "13/18 FV",
                }
            },
        )

        service = MCFInvoiceService(device=self.device)
        reference = service._build_credit_note_reference(
            original,
            preferred_nature="RAN",
            canonical_reference=original.codedefdgi,
        )

        self.assertEqual(reference["reference_type"], "RAN")
        self.assertEqual(reference["rr"], "RAN")
        self.assertEqual(reference["rn"], original.codedefdgi)
        self.assertIn({"rr": "RAN", "rn": original.numero}, reference["reference_candidates"])


class MCFClientRetryTests(TestCase):
    """Regroupe les tests de reprise du client technique MCF."""


    def test_send_command_retries_once_on_invalid_bcc(self):
        """Verifie que le client MCF relance une fois l'envoi en cas de BCC invalide."""

        client = object.__new__(MCFClient)
        client.port = "COM9"
        client.flush = Mock()
        client.send_raw = Mock()
        client.read_frame = Mock(side_effect=[b"raw-1", b"raw-2"])
        client.protocol = Mock()
        client.protocol.build_frame.return_value = b"frame-33"
        client.protocol.parse_response.side_effect = [
            {
                "type": "FRAME",
                "bcc_valid": False,
            },
            {
                "type": "FRAME",
                "bcc_valid": True,
                "data_text": "OK",
            },
        ]

        result = MCFClient.send_command(client, "33", "", retries=1)

        self.assertTrue(result["ok"])
        self.assertEqual(client.read_frame.call_count, 2)
        self.assertEqual(client.protocol.parse_response.call_count, 2)


class MCFTaxGroupProtocolTests(TestCase):
    """Verifie la TVA par groupe A-P selon le manuel du protocole MCF-SFE."""

    # Reponse C1 reelle : 11 champs d'etat puis TAXA...TAXP.
    C1_DATA = (
        "ED02001705-1,A2560363Q,20261019092841,70,47,11,20260520200054,FV,"
        "YWUA2Q3ERHQOGBGFESGDGXMM,FV-2026-00512,127600.00,0.00,16.00,5.00,0.00,0.00,"
        "16.00,5.00,0.00,0.00,0.00,0.00,0.00,0.00,0.00,1.00,1.00"
    )

    def _item(self, group, rate, sfe_rate):
        """Construit un article 31h minimal."""

        return {
            "nom": "Article",
            "itype": "BIE",
            "tax_group": group,
            "tax_rate": rate,
            "sfe_tax_rate": sfe_rate,
            "total_amount": Decimal("100.00"),
            "unit_price": Decimal("100.00"),
            "quantity": Decimal("1.000"),
        }

    def test_c1_rates_are_read_for_every_tax_group(self):
        """Verifie que les taux des 16 groupes viennent du boitier."""

        rates = MCFCommands(client=Mock()).parse_status_tax_rates(
            {"response": {"data_text": self.C1_DATA}}
        )

        self.assertEqual(len(rates), 16)
        self.assertEqual(rates["B"], Decimal("16.00"))
        self.assertEqual(rates["C"], Decimal("5.00"))
        self.assertEqual(rates["N"], Decimal("0.00"))
        self.assertEqual(rates["P"], Decimal("1.00"))

    def test_device_rate_is_sent_and_special_groups_follow_the_mcf(self):
        """Verifie que TR suit le MCF, y compris pour un groupe sans taux SFE (N)."""

        commands = MCFCommands(client=Mock())
        rates = commands.parse_status_tax_rates({"response": {"data_text": self.C1_DATA}})

        items = commands.apply_device_tax_rates(
            [self._item("O", Decimal("1.00"), Decimal("1.00")), self._item("N", Decimal("100.00"), None)],
            rates,
        )

        self.assertEqual(items[0]["tax_rate"], Decimal("1.00"))
        self.assertEqual(items[1]["tax_rate"], Decimal("0.00"))

    def test_flow_stops_before_opening_invoice_when_group_rate_differs(self):
        """Verifie qu'un taux SFE different du MCF bloque avant C3/C0."""

        commands = MCFCommands(client=Mock())
        with patch.object(
            commands,
            "get_status",
            return_value={"response": {"data_text": self.C1_DATA, "status_hex": "C080C080C0D8"}},
        ), patch.object(commands, "set_customer_info") as mock_customer:
            with self.assertRaisesMessage(MCFTaxRateMismatchError, "groupe de taxation C est a 8.00%"):
                commands.send_invoice_flow(
                    customer={"ctype": "PP"},
                    invoice={"invoice_type": "FV"},
                    items=[self._item("C", Decimal("8.00"), Decimal("8.00"))],
                    expected_total=Decimal("108.00"),
                    expected_vat=Decimal("8.00"),
                )

        mock_customer.assert_not_called()

    def test_subtotal_accepts_manual_layout_and_sums_group_vat(self):
        """Verifie le format 33h du manuel (35 champs, sans TVA totale)."""

        fields = ["4100.00", "3600.00", "500.00"] + ["0"] * 14 + ["0", "69.00"] + ["0"] * 14 + ["0", "0"]
        subtotal = MCFCommands(client=Mock()).parse_subtotal(
            {"response": {"data_text": ",".join(fields)}}
        )

        self.assertEqual(subtotal["total"], Decimal("4100.00"))
        self.assertEqual(subtotal["vat"], Decimal("69.00"))
        self.assertEqual(subtotal["groups"]["A"]["amount"], Decimal("3600.00"))
        self.assertEqual(subtotal["groups"]["B"]["vat"], Decimal("69.00"))

    def test_subtotal_reports_amounts_registered_in_another_group(self):
        """Verifie qu'un article enregistre dans le mauvais groupe est detecte."""

        # Format Eltrade : MV, TVA totale, MVA..MVP, MTA..MTP, MTS, MCUR.
        fields = ["116.00", "16.00", "0", "116.00"] + ["0"] * 14 + ["0", "16.00"] + ["0"] * 14 + ["0", "0"]
        result = MCFCommands(client=Mock()).validate_subtotal(
            expected_total=Decimal("116.00"),
            expected_vat=Decimal("16.00"),
            subtotal_result={"response": {"data_text": ",".join(fields)}},
            expected_groups={"F": {"amount": Decimal("116.00"), "vat": Decimal("16.00"), "items": 1}},
        )

        self.assertFalse(result["ok"])
        self.assertEqual([gap["group"] for gap in result["group_differences"]], ["B", "F"])

    def test_prepared_item_carries_specific_tax_and_price_change_in_ht_mode(self):
        """Verifie MON, ;T{TSR},{TS} et {PRORIG},{PRDESC} comme l'API e-MCF les recoit."""

        service = MCFInvoiceService(device=MCFDevice(name="MCF", port="COM9"))
        items = service._build_items_from_prepared(
            {
                "company": {"mode_dgi": "ht"},
                "commande": {"type_facture": "FV"},
                "items": [
                    {
                        "name": "EAU",
                        "item_type": "BIE",
                        "tax_group": "B",
                        "tax_rate": Decimal("16.00"),
                        "line_total": Decimal("1000.00"),
                        "unit_price": Decimal("250.00"),
                        "quantity": Decimal("4.000"),
                        "specific_tax_value": "10%",
                        "specific_tax_amount": Decimal("100.00"),
                        "original_price": Decimal("300.00"),
                        "price_modification": "Remise de 200.00",
                    }
                ],
            }
        )

        item = items[0]
        self.assertEqual(item["total_amount"], Decimal("1100.00"))
        self.assertEqual(item["specific_tax_rate"], "10%")
        self.assertEqual(item["specific_tax_total"], Decimal("100.00"))
        self.assertEqual(item["original_price"], Decimal("300.00"))
        self.assertEqual(item["expected_amount"], Decimal("1276.00"))
        self.assertEqual(item["expected_vat"], Decimal("176.00"))
        self.assertEqual(
            service._build_expected_groups(items),
            {"B": {"amount": Decimal("1276.00"), "vat": Decimal("176.00"), "items": 1}},
        )

    def test_ttc_frame_31_includes_specific_tax_with_its_vat(self):
        """Verifie la trame 31h TTC du manuel : MON = PR*QT + T.S. TTC."""

        service = MCFInvoiceService(device=MCFDevice(name="MCF", port="COM9"))
        item = service._build_items_from_prepared(
            {
                "company": {"mode_dgi": "ttc"},
                "commande": {"type_facture": "FV"},
                "items": [
                    {
                        "name": "SPEC",
                        "item_type": "BIE",
                        "tax_group": "B",
                        "tax_rate": Decimal("16.00"),
                        "line_total": Decimal("2000.00"),
                        "unit_price": Decimal("500.00"),
                        "quantity": Decimal("4.000"),
                        "specific_tax_value": "75",
                        "specific_tax_amount": Decimal("300.00"),
                    }
                ],
            }
        )[0]
        client = Mock()
        client.send_command.return_value = {"ok": True, "response": {"data_text": "2348.00,1724.14,324.14,300"}}

        MCFCommands(client)._add_item_with_fallback(item)

        client.send_command.assert_called_once_with(
            "31",
            "SPEC\tBIE,B16.00%2348.00\t500.00*4.000;T75,300.00",
        )

    def test_rate_mismatch_is_a_business_error_for_the_sale(self):
        """Verifie qu'un taux incoherent n'est pas propose en fallback technique."""

        device = MCFDevice.objects.create(
            name="MCF",
            port="COM9",
            company_nif="A1234567Q",
            company_isf="CD01004241-1",
            is_active=True,
            is_default=True,
        )
        service = MCFInvoiceService(device=device)
        prepared_payload = {
            "commande": {"numero": "FV-2026-00001", "type_facture": "FV"},
            "company": {"mode_dgi": "ht", "nif": "A1234567Q", "isf": "CD01004241-1"},
            "operator": {"id": "1", "name": "ADMIN"},
            "customer": {"type": "PP", "nif": "", "name": "CLIENT"},
            "items": [
                {
                    "name": "Brique",
                    "item_type": "BIE",
                    "tax_group": "C",
                    "tax_rate": Decimal("8.00"),
                    "line_total": Decimal("100.00"),
                    "unit_price": Decimal("100.00"),
                    "quantity": Decimal("1.000"),
                }
            ],
            "payments": [],
            "totals": {"total_ttc": Decimal("108.00"), "total_vat": Decimal("8.00")},
        }

        with patch("mcf.services_mcf.MCFClient"), patch("mcf.services_mcf.MCFCommands") as mock_commands_cls:
            mock_commands_cls.return_value.send_invoice_flow.side_effect = MCFTaxRateMismatchError(
                "Le groupe de taxation C est a 8.00% dans FacControl mais a 5.00% dans le MCF."
            )
            with self.assertRaises(MCFTaxConfigurationError):
                service.send_invoice(SimpleNamespace(pk=None), prepared_payload=prepared_payload)


class MCFSfeIdentifierTests(TestCase):
    """Verifie que l'ISF de la commande C0 est l'identifiant du SFE (Configuration)."""

    def setUp(self):
        """Prepare un appareil dont le champ ISF contient le MID du boitier."""

        self.service = MCFInvoiceService(
            device=MCFDevice(
                name="MCF",
                port="COM9",
                company_nif="A2560363Q",
                company_isf="ED02001705-1",
            )
        )

    def test_c0_uses_configuration_isf_like_the_emcf_json(self):
        """Verifie que C0 recoit l'ISF des settings et non le MID du boitier."""

        identities = self.service._build_company_identity_candidates(
            prepared_payload={"company": {"nif": "A2560363Q", "isf": "GBM-WEB-01"}}
        )

        self.assertEqual([identity["isf"] for identity in identities], ["GBM-WEB-01"])

    def test_device_isf_is_only_a_fallback_without_configuration_isf(self):
        """Verifie le repli sur l'ISF de l'appareil quand la Configuration n'en a pas."""

        identities = self.service._build_company_identity_candidates(
            prepared_payload={"company": {"nif": "A2560363Q", "isf": ""}}
        )

        self.assertEqual([identity["isf"] for identity in identities], ["ED02001705-1"])
