﻿"""
Jeu de tests principal de l'application facturation.

Ce fichier couvre des scenarios critiques autour des ventes, du POS, des
paiements, des droits d'acces, des calculs et des flux fiscaux.
"""



import json
import zipfile
from datetime import datetime, timedelta
from decimal import Decimal
from io import BytesIO
from unittest.mock import patch

from django.contrib.auth import get_user_model
from django.core.cache import cache
from django.core.exceptions import ValidationError
from django.db import OperationalError
from django.test import SimpleTestCase, TestCase
from django.urls import reverse
from django.utils import timezone

from dgi.models import ClientType, ItemType, TaxGroup
from dgi.emcf_adapter import EmcfAdapter
from mcf.models import MCFDevice, MCFInvoiceLog
from mcf.services_mcf import MCFInvoiceServiceError

from .forms import (
    RoleMenuPermissionMatrixForm,
    UserMenuPermissionMatrixForm,
    UserUIElementPermissionForm,
)
from .fiscal_cancellation import FiscalCancellationService
from .fiscal_exceptions import FiscalBusinessError, FiscalTechnicalError
from .fiscal_preparation import FiscalPayloadBuilder
from .fiscal_rules import (
    build_mcf_item_type_candidates,
    compute_line_tax_breakdown,
    normalize_mcf_tax_rate,
)
from .models import (
    Client,
    Commande,
    Configuration,
    LigneCommande,
    MouvementStock,
    PointDeVente,
    Produit,
    RoleMenuPermission,
    StockPointDeVente,
    UserMenuPermission,
    UserPermissionBouton,
    UserPrintPreference,
)
from .services_dgi import DGIService
from .menu_permissions import get_default_menu_permission_map, save_user_menu_permissions
from .templatetags.custom_filters import format_def_code


class FiscalDisplayFilterTests(SimpleTestCase):
    """Verifie les filtres d'affichage fiscal utilises sur les factures."""


    def test_format_def_code_groups_mcf_platform_code(self):
        """Verifie qu'un code DEF MCF est affiche comme sur la plateforme."""

        self.assertEqual(
            format_def_code("BMALXPL6JUZMF5HSTQJKOTPR"),
            "BMAL-XPL6-JUZM-F5HS-TQJK-OTPR",
        )
        self.assertEqual(
            format_def_code("BMAL-XPL6 JUZM-F5HS TQJK-OTPR"),
            "BMAL-XPL6-JUZM-F5HS-TQJK-OTPR",
        )
        self.assertEqual(format_def_code("SIG-CORR-DET"), "SIG-CORR-DET")


class EmailAuthenticationTests(TestCase):
    """Regroupe les tests du flux d'authentification par identifiant."""


    def test_login_page_uses_identifier_wording(self):
        """Verifie que la page de connexion accepte un e-mail ou un username."""

        response = self.client.get(reverse("facturation:login"))

        self.assertEqual(response.status_code, 200)
        self.assertContains(response, 'type="text"', html=False)
        self.assertContains(response, "Entrez votre e-mail ou nom d'utilisateur")

    def test_login_accepts_email_and_username(self):
        """Verifie que la connexion accepte un e-mail ou un nom d'utilisateur."""

        user = get_user_model().objects.create_user(
            username="vendeur-auth",
            email="vendeur-auth@test.com",
            password="secret123",
        )

        response = self.client.post(
            reverse("facturation:login"),
            {"email": user.email, "password": "secret123"},
        )
        self.assertEqual(response.status_code, 302)
        self.assertEqual(int(self.client.session["_auth_user_id"]), user.pk)

        self.client.logout()

        response = self.client.post(
            reverse("facturation:login"),
            {"email": user.username, "password": "secret123"},
        )
        self.assertEqual(response.status_code, 302)
        self.assertEqual(int(self.client.session["_auth_user_id"]), user.pk)

    def test_api_token_login_uses_identifier(self):
        """Verifie que l'authentification par jeton utilise e-mail ou username."""

        user = get_user_model().objects.create_user(
            username="vendeur-api",
            email="vendeur-api@test.com",
            password="secret123",
        )

        response = self.client.post(
            reverse("api_login"),
            {"email": user.email, "password": "secret123"},
        )

        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.json()["email"], user.email)

        response = self.client.post(
            reverse("api_login"),
            {"email": user.username, "password": "secret123"},
        )

        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.json()["email"], user.email)

    def test_user_creation_requires_email(self):
        """Verifie que la creation d'utilisateur exige un e-mail."""

        with self.assertRaises(ValidationError):
            get_user_model().objects.create_user(
                username="sans-email",
                password="secret123",
            )

    def test_user_email_must_be_unique_case_insensitively(self):
        """Verifie que l'e-mail utilisateur reste unique sans tenir compte de la casse."""

        get_user_model().objects.create_user(
            username="vendeur-1",
            email="vendeur-unique@test.com",
            password="secret123",
        )

        with self.assertRaises(ValidationError):
            get_user_model().objects.create_user(
                username="vendeur-2",
                email="VENDEUR-UNIQUE@test.com",
                password="secret123",
            )


class POSMenuPermissionTests(TestCase):
    """Regroupe les tests des permissions de menu et d'administration du POS."""


    def setUp(self):
        """Prepare les donnees communes necessaires a ce scenario de test."""

        cache.clear()
        self.point_de_vente = PointDeVente.objects.create(nom="PDV Test")
        self.second_point_de_vente = PointDeVente.objects.create(nom="PDV Second")
        self.super_admin = get_user_model().objects.create_superuser(
            username="super-pos",
            email="super-pos@test.com",
            password="secret123",
            role="ADMIN",
            point_de_vente=self.point_de_vente,
        )
        self.admin_user = get_user_model().objects.create_user(
            username="admin-pos",
            email="admin-pos@test.com",
            password="secret123",
            role="ADMIN",
            is_staff=True,
            point_de_vente=self.point_de_vente,
            created_by=self.super_admin,
        )
        self.other_admin = get_user_model().objects.create_user(
            username="admin-pos-2",
            email="admin-pos-2@test.com",
            password="secret123",
            role="ADMIN",
            is_staff=True,
            point_de_vente=self.second_point_de_vente,
            created_by=self.super_admin,
        )
        self.point_de_vente.assigned_admin = self.admin_user
        self.point_de_vente.save(update_fields=["assigned_admin"])
        self.second_point_de_vente.assigned_admin = self.other_admin
        self.second_point_de_vente.save(update_fields=["assigned_admin"])
        self.vendeur_user = get_user_model().objects.create_user(
            username="vendeur-pos",
            email="vendeur-pos@test.com",
            password="secret123",
            role="VENDEUR",
            point_de_vente=self.point_de_vente,
            created_by=self.admin_user,
        )
        self.admin_owned_user = get_user_model().objects.create_user(
            username="vendeur-admin-cree",
            email="vendeur-admin-cree@test.com",
            password="secret123",
            role="VENDEUR",
            point_de_vente=self.point_de_vente,
            created_by=self.admin_user,
        )
        self.foreign_user = get_user_model().objects.create_user(
            username="vendeur-autre-admin",
            email="vendeur-autre-admin@test.com",
            password="secret123",
            role="VENDEUR",
            point_de_vente=self.second_point_de_vente,
            created_by=self.other_admin,
        )

    def _get_sidebar_keys(self, response):
        """Extrait les cles de menu visibles dans la barre laterale pour simplifier les assertions."""

        return [
            item["key"]
            for section in response.context["sidebar_sections"]
            for item in section["items"]
        ]

    def _get_sidebar_section(self, response, section_key):
        """Retourne une section de sidebar par sa cle pour faciliter les assertions UI."""

        # Ce helper evite de dupliquer dans plusieurs tests la meme logique
        # de recherche de section dans le contexte de la sidebar.
        # On garde ainsi des tests plus courts et plus lisibles sur le
        # comportement specifique du bloc Administration repliable.
        return next(
            section
            for section in response.context["sidebar_sections"]
            if section["key"] == section_key
        )

    def test_super_admin_sees_global_menu_including_admin_django(self):
        """Verifie que le super administrateur voit le menu global, y compris l'administration Django."""

        self.client.force_login(self.super_admin)

        response = self.client.get(reverse("facturation:dashboard"))

        self.assertEqual(response.status_code, 200)
        sidebar_keys = self._get_sidebar_keys(response)
        self.assertEqual(
            set(sidebar_keys),
            {
                "dashboard",
                "pos",
                "produits",
                "ventes_factures",
                "proformas",
                "clients",
                "fournisseurs",
                "achats",
                "receptions",
                "paiements_fournisseurs",
                "dettes_fournisseurs",
                "retours_fournisseurs",
                "avoirs_fournisseurs",
                "inventaires",
                "stocks",
                "transferts",
                "mouvements_stock",
                "rapports_gestion",
                "rapport_journalier",
                "rapport_mensuel",
                "rapport_chiffre_affaires",
                "rapport_vendeurs",
                "rapports_dgi_session",
                "rapport_x",
                "rapport_a",
                "configuration",
                "tax_groups",
                "client_types",
                "item_types",
                "categories",
                "modes_paiement",
                "points_de_vente",
                "utilisateurs",
                "appareils_mcf",
                "backup_ventes",
                "journal_audit",
                "tickets_prix",
                "menu_permissions",
                "admin_django",
                "mcf_sync_status",
                "mcf_sync_restart",
            },
        )

    def test_scoped_admin_sees_pos_admin_menu_without_admin_django(self):
        """Verifie qu'un administrateur borne voit le menu d'administration POS sans l'admin Django."""

        self.client.force_login(self.admin_user)

        response = self.client.get(reverse("facturation:dashboard"))

        self.assertEqual(response.status_code, 200)
        sidebar_keys = self._get_sidebar_keys(response)
        self.assertEqual(
            set(sidebar_keys),
            {
                "dashboard",
                "pos",
                "produits",
                "ventes_factures",
                "proformas",
                "clients",
                "fournisseurs",
                "achats",
                "receptions",
                "paiements_fournisseurs",
                "dettes_fournisseurs",
                "retours_fournisseurs",
                "avoirs_fournisseurs",
                "inventaires",
                "stocks",
                "transferts",
                "mouvements_stock",
                "rapports_gestion",
                "rapport_journalier",
                "rapport_mensuel",
                "rapport_chiffre_affaires",
                "rapport_vendeurs",
                "rapports_dgi_session",
                "rapport_x",
                "rapport_a",
                "configuration",
                "tax_groups",
                "client_types",
                "item_types",
                "categories",
                "modes_paiement",
                "points_de_vente",
                "utilisateurs",
                "appareils_mcf",
                "backup_ventes",
                "journal_audit",
                "tickets_prix",
                "menu_permissions",
                "mcf_sync_status",
                "mcf_sync_restart",
            },
        )
        self.assertNotIn("admin_django", sidebar_keys)

    def test_mcf_sync_action_is_rendered_as_success_sidebar_post(self):
        """Verifie que la synchronisation MCF est une action POST verte dans la sidebar."""

        self.client.force_login(self.admin_user)

        response = self.client.get(reverse("facturation:dashboard"))

        self.assertContains(response, "Synchroniser MCF via DGI")
        self.assertContains(
            response,
            f'action="{reverse("facturation:mcf-sync-restart")}"',
            html=False,
        )
        self.assertContains(response, 'method="post"', html=False)
        self.assertContains(response, "sidebar-action-link--success")

    def test_mcf_sync_status_page_displays_cached_service_details(self):
        """Verifie que la page statut MCF affiche les details du service existant."""

        self.client.force_login(self.admin_user)
        service_status = {
            "success": True,
            "machine_connected": True,
            "machine_status_label": "Connecte",
            "server_status": "CON",
            "server_status_label": "Connecte",
            "last_connection_display": "03/05/2026 12:00:00",
            "age_days": 2,
            "device_name": "MCF Principal",
            "port": "COM8",
            "checked_at_display": "03/05/2026 12:05:00",
            "message": "Derniere connexion DGI le 03/05/2026 12:00:00.",
        }

        with patch("facturation.views.MCFSynchronizationService") as mock_service_cls:
            mock_service_cls.return_value.read_connection_status.return_value = service_status

            response = self.client.get(reverse("facturation:mcf-sync-status"))

        self.assertEqual(response.status_code, 200)
        self.assertContains(response, "Statut Synchronisation MCF")
        self.assertContains(response, "03/05/2026 12:00:00")
        self.assertContains(response, "2 jour(s)")
        self.assertContains(response, "MCF Principal")
        self.assertContains(response, "COM8")
        self.assertContains(response, "bg-success")

    def test_mcf_sync_status_badge_uses_machine_connection_not_dgi_state(self):
        """Verifie que le badge vert depend du branchement MCF, meme si le statut DGI est DIS."""

        self.client.force_login(self.admin_user)
        service_status = {
            "success": True,
            "machine_connected": True,
            "machine_status_label": "Connecte",
            "server_status": "DIS",
            "server_status_label": "Deconnecte",
            "last_connection_display": "03/05/2026 12:00:00",
            "age_days": 0,
            "device_name": "MCF Principal",
            "port": "COM8",
            "checked_at_display": "03/05/2026 12:05:00",
            "message": "MCF joignable.",
        }

        with patch("facturation.views.MCFSynchronizationService") as mock_service_cls:
            mock_service_cls.return_value.read_connection_status.return_value = service_status

            response = self.client.get(reverse("facturation:mcf-sync-status"))

        self.assertContains(response, "bg-success")
        self.assertContains(response, "Connecté")
        self.assertContains(response, "DIS")

    def test_administration_sidebar_is_collapsed_when_no_admin_page_is_active(self):
        """Verifie que le parent Administration reste replie hors navigation d'administration."""

        self.client.force_login(self.admin_user)

        response = self.client.get(reverse("facturation:dashboard"))

        # Sur le dashboard, aucun ecran d'administration n'est actif :
        # le parent doit donc rester ferme au chargement pour economiser
        # l'espace vertical dans la sidebar.
        administration_section = self._get_sidebar_section(response, "administration")
        self.assertFalse(administration_section["is_active"])
        self.assertContains(response, 'data-bs-target="#sidebar-section-administration-menu"', html=False)
        self.assertContains(response, "sidebar-section-toggle collapsed")

    def test_administration_sidebar_opens_when_child_page_is_active(self):
        """Verifie que le parent Administration s'ouvre automatiquement sur une page enfant."""

        self.client.force_login(self.admin_user)

        response = self.client.get(reverse("facturation:configuration"))

        # Des qu'une page enfant appartient a la section Administration,
        # le parent doit apparaitre ouvert automatiquement afin que
        # l'utilisateur garde un repere visuel clair dans la navigation.
        administration_section = self._get_sidebar_section(response, "administration")
        self.assertTrue(administration_section["is_active"])
        self.assertContains(response, 'aria-expanded="true"')
        self.assertContains(response, "nav-content collapse sidebar-submenu show")

    def test_gestion_sidebar_is_collapsed_when_no_gestion_page_is_active(self):
        """Verifie que le parent Gestion reste replie tant qu'aucune page gestion n'est active."""

        self.client.force_login(self.admin_user)

        response = self.client.get(reverse("facturation:dashboard"))

        # Depuis le dashboard, la section Gestion ne doit pas monopoliser
        # l'espace vertical de la sidebar puisqu'aucun de ses enfants n'est
        # selectionne a l'ecran.
        gestion_section = self._get_sidebar_section(response, "gestion")
        self.assertFalse(gestion_section["is_active"])
        self.assertContains(response, 'data-bs-target="#sidebar-section-gestion-menu"', html=False)

    def test_gestion_sidebar_opens_when_child_page_is_active(self):
        """Verifie que le parent Gestion s'ouvre automatiquement sur une page de gestion."""

        self.client.force_login(self.admin_user)

        response = self.client.get(reverse("facturation:commande-list"))

        # Une page fille de Gestion doit ouvrir automatiquement son parent
        # pour conserver un repere de navigation clair dans la sidebar.
        gestion_section = self._get_sidebar_section(response, "gestion")
        self.assertTrue(gestion_section["is_active"])
        self.assertContains(response, 'aria-controls="sidebar-section-gestion-menu"')
        self.assertContains(response, "nav-content collapse sidebar-submenu show")

    def test_rapports_dgi_sidebar_is_collapsed_when_no_report_page_is_active(self):
        """Verifie que le parent Rapports DGI reste replie hors navigation de rapport DGI."""

        self.client.force_login(self.admin_user)

        response = self.client.get(reverse("facturation:dashboard"))

        # Comme pour les autres groupes repliables, Rapports DGI reste ferme
        # tant qu'aucune de ses pages enfants n'est la page courante.
        rapports_section = self._get_sidebar_section(response, "rapports_dgi")
        self.assertFalse(rapports_section["is_active"])
        self.assertContains(response, 'data-bs-target="#sidebar-section-rapports_dgi-menu"', html=False)

    def test_rapports_dgi_sidebar_opens_when_child_page_is_active(self):
        """Verifie que le parent Rapports DGI s'ouvre automatiquement sur une page enfant."""

        self.client.force_login(self.admin_user)

        response = self.client.get(reverse("facturation:rapport-x"))

        # Lorsqu'un rapport DGI est consulte, le bloc parent doit se
        # deplier automatiquement pour garder l'item actif visible.
        rapports_section = self._get_sidebar_section(response, "rapports_dgi")
        self.assertTrue(rapports_section["is_active"])
        self.assertContains(response, 'aria-controls="sidebar-section-rapports_dgi-menu"')
        self.assertContains(response, "nav-content collapse sidebar-submenu show")

    def test_vendeur_sees_only_requested_default_menu_items(self):
        """Verifie qu'un vendeur ne voit que les entrees de menu par defaut autorisees."""

        self.client.force_login(self.vendeur_user)

        response = self.client.get(reverse("facturation:dashboard"))

        self.assertEqual(response.status_code, 200)
        sidebar_keys = self._get_sidebar_keys(response)
        self.assertEqual(
            set(sidebar_keys),
            {
                "dashboard",
                "pos",
                "produits",
                "ventes_factures",
                "proformas",
                "clients",
                "stocks",
                "mouvements_stock",
                "rapport_journalier",
                "rapport_mensuel",
            },
        )
        self.assertNotContains(response, "Configuration")
        self.assertNotContains(response, "Groupes de taxation")
        self.assertNotContains(response, "Types de client")
        self.assertNotContains(response, "Types d'article")
        self.assertNotContains(response, "Categories")
        self.assertNotContains(response, "Modes de paiement")
        self.assertNotContains(response, "Utilisateurs")
        self.assertNotContains(response, "Appareils MCF")
        self.assertNotContains(response, "Back-up ventes")
        self.assertNotContains(response, "Statut Synchronisation MCF")
        self.assertNotContains(response, "Synchroniser MCF via DGI")
        self.assertNotContains(response, "Permissions menus")
        self.assertNotContains(response, "Performance Vendeurs")
        self.assertNotContains(response, "X-Rapport (Journal)")
        self.assertNotContains(response, "Z-Rapport (Cloture)")
        self.assertNotContains(response, "A-Rapport (Periodique)")

    def test_vendeur_is_blocked_from_admin_urls_even_by_direct_access(self):
        """Verifie qu'un vendeur reste bloque sur les URLs d'administration meme en acces direct."""

        self.client.force_login(self.vendeur_user)

        forbidden_urls = (
            reverse("facturation:configuration"),
            reverse("facturation:tax-group-list"),
            reverse("facturation:client-type-list"),
            reverse("facturation:item-type-list"),
            reverse("facturation:categorie-list"),
            reverse("facturation:mode-paiement-list"),
            reverse("facturation:point-de-vente-list"),
            reverse("facturation:user-list"),
            reverse("facturation:mcf-device-list"),
            reverse("facturation:backup-ventes"),
            reverse("facturation:menu-permissions"),
            reverse("facturation:rapport-vendeurs"),
            reverse("facturation:rapport-x"),
        )

        for url in forbidden_urls:
            response = self.client.get(url)
            self.assertIn(response.status_code, (302, 403))
            self.assertNotEqual(response.status_code, 200)

    def test_scoped_admin_can_manage_dgi_references_from_pos(self):
        """Verifie qu'un administrateur borne peut gerer les trois referentiels DGI depuis le POS."""

        self.client.force_login(self.admin_user)

        # On controle d'abord l'ouverture des listes pour s'assurer que les
        # nouveaux menus sont bien relies a de vraies pages du back-office.
        self.assertEqual(
            self.client.get(reverse("facturation:tax-group-list")).status_code,
            200,
        )
        self.assertEqual(
            self.client.get(reverse("facturation:client-type-list")).status_code,
            200,
        )
        self.assertEqual(
            self.client.get(reverse("facturation:item-type-list")).status_code,
            200,
        )

        # Chaque creation passe ensuite par la vue POS correspondante pour
        # valider que les formulaires, routes et redirections sont bien
        # fonctionnels de bout en bout.
        tax_group_create_response = self.client.post(
            reverse("facturation:tax-group-create"),
            {
                "code": "TG1",
                "name": "TVA test",
                "description": "Groupe cree depuis le POS",
                "tax": "12.50",
                "is_active": "on",
            },
        )
        self.assertEqual(tax_group_create_response.status_code, 302)
        tax_group = TaxGroup.objects.get(code="TG1")
        self.assertEqual(tax_group.name, "TVA test")

        client_type_create_response = self.client.post(
            reverse("facturation:client-type-create"),
            {
                "code": "CT1",
                "name": "Client test",
                "description": "Type cree depuis le POS",
                "is_active": "on",
            },
        )
        self.assertEqual(client_type_create_response.status_code, 302)
        client_type = ClientType.objects.get(code="CT1")
        self.assertEqual(client_type.name, "Client test")

        item_type_create_response = self.client.post(
            reverse("facturation:item-type-create"),
            {
                "code": "ITMTEST",
                "name": "Article test",
                "description": "Type article cree depuis le POS",
                "is_active": "on",
            },
        )
        self.assertEqual(item_type_create_response.status_code, 302)
        item_type = ItemType.objects.get(code="ITMTEST")
        self.assertEqual(item_type.name, "Article test")

        # On valide enfin qu'une modification de chaque referentiel suit
        # bien le meme circuit applicatif et persiste correctement.
        tax_group_update_response = self.client.post(
            reverse("facturation:tax-group-update", args=[tax_group.pk]),
            {
                "code": "TG1",
                "name": "TVA test modifiee",
                "description": "Groupe modifie depuis le POS",
                "tax": "15.00",
                "is_active": "on",
            },
        )
        self.assertEqual(tax_group_update_response.status_code, 302)
        tax_group.refresh_from_db()
        self.assertEqual(tax_group.tax, Decimal("15.00"))

        client_type_update_response = self.client.post(
            reverse("facturation:client-type-update", args=[client_type.pk]),
            {
                "code": "CT1",
                "name": "Client test modifie",
                "description": "Type modifie depuis le POS",
                "is_active": "on",
            },
        )
        self.assertEqual(client_type_update_response.status_code, 302)
        client_type.refresh_from_db()
        self.assertEqual(client_type.name, "Client test modifie")

        item_type_update_response = self.client.post(
            reverse("facturation:item-type-update", args=[item_type.pk]),
            {
                "code": "ITMTEST",
                "name": "Article test modifie",
                "description": "Type article modifie depuis le POS",
                "is_active": "on",
            },
        )
        self.assertEqual(item_type_update_response.status_code, 302)
        item_type.refresh_from_db()
        self.assertEqual(item_type.name, "Article test modifie")

    def test_dashboard_forbidden_page_uses_popup_and_pos_redirect(self):
        """Verifie que le dashboard interdit affiche un popup puis prepare un retour vers le POS."""

        # On simule le cas remonte en production : l'utilisateur peut se
        # connecter, mais son droit d'acces au dashboard a ete retire.
        UserMenuPermission.objects.create(
            user=self.vendeur_user,
            permission_key="dashboard",
            is_allowed=False,
        )
        self.client.force_login(self.vendeur_user)

        response = self.client.get(reverse("facturation:dashboard"))

        self.assertEqual(response.status_code, 302)
        self.assertEqual(response["Location"], reverse("facturation:pos-view"))

    def test_login_lands_on_dashboard_forbidden_popup_when_dashboard_is_forbidden(self):
        """Verifie que la connexion aboutit sur la page 403 popup si le dashboard n'est pas accessible."""

        # Ici on couvre le flux complet de connexion : Django redirige
        # d'abord vers LOGIN_REDIRECT_URL, puis notre logique doit detecter
        # que "/" est interdit et basculer automatiquement vers le premier
        # ecran accessible.
        UserMenuPermission.objects.create(
            user=self.vendeur_user,
            permission_key="dashboard",
            is_allowed=False,
        )

        response = self.client.post(
            reverse("facturation:login"),
            {
                "email": self.vendeur_user.email,
                "password": "secret123",
            },
            follow=True,
        )

        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.request["PATH_INFO"], reverse("facturation:pos-view"))

    def test_forbidden_menu_page_uses_popup_and_redirect_to_authorized_interface(self):
        """Verifie qu'une page interdite affiche le popup FacControl et propose un retour autorise."""

        self.client.force_login(self.vendeur_user)

        response = self.client.get(reverse("facturation:rapport-x"))

        self.assertEqual(response.status_code, 302)
        self.assertEqual(response["Location"], reverse("facturation:dashboard"))

    def test_proforma_access_can_be_revoked_by_role_override(self):
        """Verifie qu'un override de role peut retirer l'acces aux proformas."""

        RoleMenuPermission.objects.create(
            role="VENDEUR",
            menu_key="proformas",
            is_allowed=False,
        )
        self.client.force_login(self.vendeur_user)

        response = self.client.get(reverse("proforma:list"))

        self.assertIn(response.status_code, (302, 403))
        self.assertNotEqual(response.status_code, 200)

    def test_role_override_can_grant_extra_menu_access_to_vendeur(self):
        """Verifie qu'un override de role peut accorder un acces menu supplementaire a un vendeur."""

        RoleMenuPermission.objects.create(
            role="VENDEUR",
            menu_key="rapport_vendeurs",
            is_allowed=True,
        )
        self.client.force_login(self.vendeur_user)

        response = self.client.get(reverse("facturation:dashboard"))

        self.assertEqual(response.status_code, 200)
        self.assertIn("rapport_vendeurs", self._get_sidebar_keys(response))

        report_response = self.client.get(reverse("facturation:rapport-vendeurs"))
        self.assertEqual(report_response.status_code, 200)

    def test_user_override_can_grant_specific_admin_module(self):
        """Verifie qu'un override utilisateur peut autoriser un module d'administration precis."""

        UserMenuPermission.objects.create(
            user=self.vendeur_user,
            permission_key="categories",
            is_allowed=True,
        )
        self.client.force_login(self.vendeur_user)

        response = self.client.get(reverse("facturation:dashboard"))

        self.assertEqual(response.status_code, 200)
        self.assertIn("categories", self._get_sidebar_keys(response))

        category_response = self.client.get(reverse("facturation:categorie-list"))
        self.assertEqual(category_response.status_code, 200)

    def test_user_override_can_remove_default_action_permission(self):
        """Verifie qu'un override utilisateur peut retirer une permission d'action par defaut."""

        produit = Produit.objects.create(
            nom="Produit permission",
            code_sku="PERM-001",
            prix_vente=Decimal("10.00"),
            actif=True,
        )
        UserMenuPermission.objects.create(
            user=self.vendeur_user,
            permission_key="produits_update",
            is_allowed=False,
        )
        self.client.force_login(self.vendeur_user)

        list_response = self.client.get(reverse("facturation:produit-list"))
        self.assertEqual(list_response.status_code, 200)

        update_response = self.client.get(
            reverse("facturation:produit-update", args=[produit.pk])
        )
        self.assertIn(update_response.status_code, (302, 403))
        self.assertNotEqual(update_response.status_code, 200)

    def test_configuration_view_and_update_permissions_are_separated(self):
        """Verifie que les droits de consultation et de modification de la configuration sont distincts."""

        UserMenuPermission.objects.create(
            user=self.vendeur_user,
            permission_key="configuration",
            is_allowed=True,
        )
        self.client.force_login(self.vendeur_user)

        get_response = self.client.get(reverse("facturation:configuration"))
        self.assertEqual(get_response.status_code, 200)
        self.assertContains(get_response, "acces en consultation")

        post_response = self.client.post(
            reverse("facturation:configuration"),
            {"taux_change": "3000.00"},
        )
        self.assertIn(post_response.status_code, (302, 403))
        self.assertNotEqual(post_response.status_code, 200)

    def test_scoped_admin_is_blocked_from_django_admin(self):
        """Verifie qu'un administrateur borne ne peut pas acceder a l'administration Django."""

        self.client.force_login(self.admin_user)

        response = self.client.get("/admin/")

        self.assertIn(response.status_code, (302, 403))
        self.assertNotEqual(response.status_code, 200)

    def test_scoped_admin_user_list_shows_all_non_superusers(self):
        """Verifie qu'un administrateur voit tous les utilisateurs hors super administrateurs."""

        self.client.force_login(self.admin_user)

        response = self.client.get(reverse("facturation:user-list"))

        self.assertEqual(response.status_code, 200)
        self.assertContains(response, self.admin_owned_user.username)
        self.assertContains(response, self.vendeur_user.username)
        self.assertContains(response, self.other_admin.username)
        self.assertContains(response, self.foreign_user.username)
        self.assertNotContains(response, self.super_admin.username)

    def test_scoped_admin_can_edit_non_superusers_but_not_super_admin(self):
        """Verifie qu'un administrateur peut modifier tout utilisateur non super administrateur."""

        self.client.force_login(self.admin_user)

        foreign_response = self.client.get(
            reverse("facturation:user-update", args=[self.foreign_user.pk])
        )
        admin_response = self.client.get(
            reverse("facturation:user-update", args=[self.other_admin.pk])
        )
        super_response = self.client.get(
            reverse("facturation:user-update", args=[self.super_admin.pk])
        )

        self.assertEqual(foreign_response.status_code, 200)
        self.assertEqual(admin_response.status_code, 200)
        self.assertEqual(super_response.status_code, 404)

        deactivate_response = self.client.post(
            reverse("facturation:user-update", args=[self.other_admin.pk]),
            {
                "username": self.other_admin.username,
                "first_name": self.other_admin.first_name,
                "last_name": self.other_admin.last_name,
                "email": self.other_admin.email,
                "role": "ADMIN",
                "points_de_vente": [self.second_point_de_vente.pk],
                "new_password": "",
            },
        )

        self.assertEqual(deactivate_response.status_code, 302)
        self.other_admin.refresh_from_db()
        self.assertFalse(self.other_admin.is_active)

    def test_scoped_admin_can_create_admin_with_capped_permissions(self):
        """Verifie qu'un admin cree un autre admin sans lui transmettre un droit absent."""

        permissions = get_default_menu_permission_map("ADMIN")
        permissions["rapport_a"] = False
        save_user_menu_permissions(self.admin_user, permissions)
        self.client.force_login(self.admin_user)

        response = self.client.post(
            reverse("facturation:user-create"),
            {
                "username": "admin-cree",
                "first_name": "Admin",
                "last_name": "Cree",
                "email": "admin-cree@test.com",
                "role": "ADMIN",
                "points_de_vente": [self.point_de_vente.pk],
                "is_active": "on",
                "password1": "secret123456",
                "password2": "secret123456",
            },
        )

        self.assertEqual(response.status_code, 302)
        created_admin = get_user_model().objects.get(username="admin-cree")
        self.assertEqual(created_admin.role, "ADMIN")
        self.assertEqual(created_admin.created_by, self.admin_user)
        self.assertFalse(
            UserMenuPermission.objects.get(
                user=created_admin,
                permission_key="rapport_a",
            ).is_allowed
        )
        self.assertTrue(
            UserMenuPermission.objects.get(
                user=created_admin,
                permission_key="dashboard",
            ).is_allowed
        )

    def test_created_user_is_attached_to_creator(self):
        """Verifie qu'un utilisateur cree reste rattache a son createur."""

        self.client.force_login(self.admin_user)

        response = self.client.post(
            reverse("facturation:user-create"),
            {
                "username": "vendeur-cree",
                "first_name": "Vendeur",
                "last_name": "Cree",
                "email": "vendeur-cree@test.com",
                "role": "VENDEUR",
                "points_de_vente": [self.point_de_vente.pk],
                "is_active": "on",
                "password1": "secret123456",
                "password2": "secret123456",
            },
        )

        self.assertEqual(response.status_code, 302)
        created_user = get_user_model().objects.get(username="vendeur-cree")
        self.assertEqual(created_user.created_by, self.admin_user)

    def test_scoped_admin_permissions_page_shows_all_non_superusers(self):
        """Verifie que la page de permissions d'un administrateur exclut seulement les super administrateurs."""

        self.client.force_login(self.admin_user)

        response = self.client.get(
            f"{reverse('facturation:menu-permissions')}?target_type=user"
        )
        admin_response = self.client.get(
            f"{reverse('facturation:menu-permissions')}?target_type=admin"
        )

        self.assertEqual(response.status_code, 200)
        self.assertContains(response, self.admin_owned_user.username)
        self.assertContains(response, self.vendeur_user.username)
        self.assertContains(response, self.foreign_user.username)
        self.assertNotContains(response, self.super_admin.username)
        self.assertNotContains(response, 'value="super_admin"')
        self.assertNotContains(response, "Super Administrateur")
        self.assertEqual(admin_response.status_code, 200)
        self.assertContains(admin_response, self.other_admin.username)
        self.assertNotContains(admin_response, self.super_admin.username)
        self.assertNotContains(admin_response, 'value="super_admin"')
        self.assertNotContains(admin_response, "Super Administrateur")

        forced_super_type_response = self.client.get(
            f"{reverse('facturation:menu-permissions')}?target_type=super_admin"
        )
        self.assertEqual(forced_super_type_response.status_code, 200)
        self.assertNotContains(forced_super_type_response, 'value="super_admin"')
        self.assertNotContains(forced_super_type_response, "Super Administrateur")

        allowed_response = self.client.get(
            f"{reverse('facturation:menu-permissions')}?user={self.foreign_user.pk}"
        )
        forbidden_response = self.client.get(
            f"{reverse('facturation:menu-permissions')}?user={self.super_admin.pk}"
        )
        self.assertEqual(allowed_response.status_code, 200)
        self.assertEqual(forbidden_response.status_code, 403)
        self.assertTemplateUsed(forbidden_response, "facturation/access_denied.html")
        self.assertContains(
            forbidden_response,
            "Vous ne pouvez pas gerer cet utilisateur depuis cet espace.",
            status_code=403,
        )
        self.assertContains(
            forbidden_response,
            reverse("facturation:dashboard"),
            status_code=403,
        )

    def test_menu_permissions_access_is_dynamic_for_scoped_admin(self):
        """Verifie que l'acces aux permissions peut etre retire a un administrateur POS."""

        permissions = get_default_menu_permission_map("ADMIN")
        permissions["menu_permissions"] = False
        save_user_menu_permissions(self.admin_user, permissions)
        self.client.force_login(self.admin_user)

        response = self.client.get(reverse("facturation:menu-permissions"))

        self.assertIn(response.status_code, (302, 403))
        self.assertNotEqual(response.status_code, 200)

    def test_permissions_page_can_save_user_ui_controls(self):
        """Verifie que la page Permissions POS enregistre aussi les elements UI utilisateur."""

        self.client.force_login(self.admin_user)

        page_response = self.client.get(
            f"{reverse('facturation:menu-permissions')}?target_type=user&target=user-{self.admin_owned_user.pk}"
        )

        self.assertEqual(page_response.status_code, 200)
        self.assertContains(page_response, "Boutons, exports")
        self.assertContains(page_response, "Bouton Modifier produit depuis POS")

        response = self.client.post(
            reverse("facturation:menu-permissions"),
            {
                "scope": "user_ui",
                "selected_user_id": self.admin_owned_user.pk,
                "target_type": "user",
                "target": f"user-{self.admin_owned_user.pk}",
                UserUIElementPermissionForm.build_field_name(
                    "point_de_vente",
                    "show_add_product_button",
                ): "on",
                UserUIElementPermissionForm.build_field_name(
                    "point_de_vente",
                    "show_edit_product_button",
                ): "on",
            },
        )

        self.assertEqual(response.status_code, 302)
        self.assertTrue(
            UserPermissionBouton.objects.get(
                user=self.admin_owned_user,
                module="point_de_vente",
                bouton="show_add_product_button",
            ).autorise
        )
        self.assertFalse(
            UserPermissionBouton.objects.filter(
                user=self.admin_owned_user,
                module="point_de_vente",
                bouton="show_stock_button",
            ).exists()
        )

    def test_permissions_page_lists_button_and_export_controls(self):
        """Verifie que l'onglet UI expose les boutons et exports configurables."""

        self.client.force_login(self.admin_user)

        response = self.client.get(
            f"{reverse('facturation:menu-permissions')}?target_type=user&target=user-{self.admin_owned_user.pk}"
        )

        self.assertEqual(response.status_code, 200)
        self.assertContains(response, "Boutons")
        self.assertContains(response, "Exports")
        self.assertContains(response, "Exporter dashboard Excel")
        self.assertContains(response, "Bouton Exporter stock")
        self.assertContains(response, "Telecharger le CSV des ventes")
        self.assertContains(response, "Cartes statistiques utilisateurs")
        self.assertContains(response, "Bouton Nouveau client")
        self.assertContains(response, "Formulaire prix par point de vente")
        self.assertContains(response, "Colonne adresse IP")
        self.assertContains(response, "Bloc lignes existantes facture")
        self.assertContains(response, "Export")

    def test_product_page_access_does_not_grant_export_action(self):
        """Verifie qu'un utilisateur peut voir Produits sans voir ni appeler l'export."""

        self.client.force_login(self.vendeur_user)

        page_response = self.client.get(reverse("facturation:produit-list"))
        export_response = self.client.get(reverse("facturation:produit-export-excel"))

        self.assertEqual(page_response.status_code, 200)
        self.assertNotContains(page_response, "Exporter les résultats")
        self.assertNotEqual(export_response.status_code, 200)

    def test_client_page_access_does_not_grant_create_action(self):
        """Verifie que la creation client peut etre retiree sans masquer la liste."""

        permissions = get_default_menu_permission_map("ADMIN")
        permissions["clients_create"] = False
        save_user_menu_permissions(self.admin_user, permissions)
        self.client.force_login(self.admin_user)

        page_response = self.client.get(reverse("facturation:client-list"))
        create_response = self.client.get(reverse("facturation:client-create"))

        self.assertEqual(page_response.status_code, 200)
        self.assertNotContains(page_response, "Nouveau Client")
        self.assertNotEqual(create_response.status_code, 200)

    def test_report_page_access_does_not_grant_excel_export(self):
        """Verifie que le rapport reste consultable quand l'export est interdit."""

        self.client.force_login(self.vendeur_user)

        page_response = self.client.get(reverse("facturation:rapport-journalier"))
        export_response = self.client.get(reverse("facturation:rapport-journalier-export-excel"))

        self.assertEqual(page_response.status_code, 200)
        self.assertNotContains(page_response, "Exporter Excel")
        self.assertNotEqual(export_response.status_code, 200)

    def test_scoped_admin_cannot_grant_permission_he_does_not_have(self):
        """Verifie que le POST ne peut pas forcer un droit absent chez l'acteur."""

        actor_permissions = get_default_menu_permission_map("ADMIN")
        actor_permissions["rapport_a"] = False
        save_user_menu_permissions(self.admin_user, actor_permissions)

        target_permissions = get_default_menu_permission_map("ADMIN")
        target_permissions["rapport_a"] = False
        save_user_menu_permissions(self.other_admin, target_permissions)

        self.client.force_login(self.admin_user)
        response = self.client.post(
            reverse("facturation:user-update", args=[self.other_admin.pk]),
            {
                "username": self.other_admin.username,
                "first_name": self.other_admin.first_name,
                "last_name": self.other_admin.last_name,
                "email": self.other_admin.email,
                "role": "ADMIN",
                "points_de_vente": [self.second_point_de_vente.pk],
                "is_active": "on",
                "new_password": "",
                UserMenuPermissionMatrixForm.build_field_name("rapport_a"): "on",
            },
        )

        self.assertEqual(response.status_code, 302)
        self.assertFalse(
            UserMenuPermission.objects.get(
                user=self.other_admin,
                permission_key="rapport_a",
            ).is_allowed
        )

    def test_scoped_admin_cannot_update_role_matrix(self):
        """Verifie qu'un administrateur borne ne peut pas modifier la matrice des roles."""

        self.client.force_login(self.admin_user)

        response = self.client.post(
            reverse("facturation:menu-permissions"),
            {
                "scope": "role",
                RoleMenuPermissionMatrixForm.build_field_name("VENDEUR", "dashboard"): "on",
            },
        )

        self.assertEqual(response.status_code, 403)

    def test_scoped_admin_can_view_and_manage_points_de_vente(self):
        """Verifie qu'un administrateur peut voir et gerer les points de vente du POS."""

        self.client.force_login(self.admin_user)

        list_response = self.client.get(reverse("facturation:point-de-vente-list"))
        create_response = self.client.get(reverse("facturation:point-de-vente-create"))
        update_response = self.client.get(
            reverse("facturation:point-de-vente-update", args=[self.point_de_vente.pk])
        )

        self.assertEqual(list_response.status_code, 200)
        self.assertContains(list_response, self.point_de_vente.nom)
        self.assertContains(list_response, self.second_point_de_vente.nom)
        self.assertEqual(create_response.status_code, 200)
        self.assertEqual(update_response.status_code, 200)

        self.client.force_login(self.super_admin)
        super_create_response = self.client.get(reverse("facturation:point-de-vente-create"))
        self.assertEqual(super_create_response.status_code, 200)


class POSMCFFiscalFlowTests(TestCase):
    """Regroupe les tests du flux POS avec fiscalisation MCF."""


    def setUp(self):
        """Prepare les donnees communes necessaires a ce scenario de test."""

        cache.clear()
        self.point_de_vente = PointDeVente.objects.create(nom="Boutique Test")
        self.user = get_user_model().objects.create_user(
            username="vendeur_test",
            email="vendeur_test@test.com",
            password="secret",
            point_de_vente=self.point_de_vente,
        )
        self.tax_group, _ = TaxGroup.objects.update_or_create(
            code="B",
            defaults={"name": "GROUPE B (TAXABLE 16%)", "tax": Decimal("16.00")},
        )
        self.item_type = ItemType.objects.create(code="BIE", name="Bien")
        self.product = Produit.objects.create(
            nom="Latacer 80g",
            code_sku="LATACER-80G",
            prix_vente=Decimal("64400.00"),
            taxgroup=self.tax_group,
            typeart=self.item_type,
            actif=True,
        )
        self.product_specific = Produit.objects.create(
            nom="Produit TS",
            code_sku="TS-001",
            prix_vente=Decimal("100.00"),
            taxgroup=self.tax_group,
            typeart=self.item_type,
            actif=True,
            est_taxe_specifique=True,
            taxe_specifique_valeur="10",
        )
        self.stock = StockPointDeVente.objects.create(
            point_de_vente=self.point_de_vente,
            produit=self.product,
            quantite=Decimal("100.000"),
        )
        self.stock_specific = StockPointDeVente.objects.create(
            point_de_vente=self.point_de_vente,
            produit=self.product_specific,
            quantite=Decimal("100.000"),
        )
        self.customer = Client.objects.create(nom_complet="Client Test POS")
        self.client_type_pp = ClientType.objects.create(code="PP", name="Personne physique")
        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",
        )
        MCFDevice.objects.create(
            name="MCF Principal",
            port="COM9",
            company_nif="A1234567Q",
            company_isf="CD01004241-1",
            is_active=True,
            is_default=True,
        )
        self.client.force_login(self.user)

    def test_pos_page_renders_empty_client_option_first(self):
        """Verifie que le POS affiche d'abord une option client vide."""

        response = self.client.get(reverse("facturation:pos-view"))

        self.assertEqual(response.status_code, 200)
        self.assertContains(response, "Point de vente actif / Boutique Test")
        self.assertContains(response, 'id="productSearchInput"')
        self.assertContains(response, "Scanner un code-barres ou rechercher par nom ou code")
        self.assertContains(response, "-- Sélectionner un client --")
        self.assertNotContains(response, self.customer.nom_complet)
        results = self.client.get(reverse("facturation:search"),
            {"entity": "client", "context": "pos", "q": self.customer.nom_complet}).json()["results"]
        self.assertIn(self.customer.pk, [row["id"] for row in results])

    def test_pos_page_does_not_render_mcf_sync_alert(self):
        """Verifie que l'alerte de synchronisation MCF reste absente du POS."""

        response = self.client.get(reverse("facturation:pos-view"))

        self.assertEqual(response.status_code, 200)
        self.assertNotContains(response, "Synchronisation DGI du MCF")
        self.assertNotIn("mcf_sync_status", response.context)

    def test_pos_page_exposes_point_de_vente_stock_price(self):
        """Verifie que le catalogue POS expose le prix stock du point de vente."""

        self.stock.prix_vente = Decimal("70000.00")
        self.stock.save(update_fields=["prix_vente", "updated_at"])

        response = self.client.get(reverse("facturation:pos-view"), {"billing": "visual"})

        self.assertEqual(response.status_code, 200)
        produits = json.loads(response.context["produits_json"])
        produit = next(item for item in produits if item["sku"] == "LATACER-80G")
        self.assertEqual(produit["prix_point_de_vente"], 70000.0)
        self.assertEqual(produit["prix"], 70000.0)

    def test_pos_invoice_uses_active_point_de_vente_in_a4_and_ticket(self):
        """Verifie que la facture imprimee affiche le PDV actif de la vente."""

        magasin_central = PointDeVente.objects.create(
            nom="Magasin Central",
            adresse="Adresse Magasin Central",
        )
        self.user.points_de_vente.add(self.point_de_vente, magasin_central)
        StockPointDeVente.objects.create(
            point_de_vente=magasin_central,
            produit=self.product,
            quantite=Decimal("10.000"),
            prix_vente=Decimal("880.00"),
        )
        session = self.client.session
        session["active_pos_id"] = magasin_central.pk
        session.save()
        payload = {
            "panier": [
                {
                    "id": self.product.pk,
                    "qty": 1,
                    "remise": 0,
                }
            ],
            "paiement": {
                "montant_verse": 880,
                "devise": "CDF",
                "taux": 1,
                "mode": "ESPECES",
            },
        }

        with patch(
            "facturation.views.FiscalOrchestrator.fiscalize_commande",
            return_value={
                "success": True,
                "channel": "MCF",
                "commande_id": 1,
                "fiscal_transaction_id": "active-pdv-pos-001",
            },
        ):
            response = self.client.post(
                reverse("facturation:pos-view"),
                data=json.dumps(payload),
                content_type="application/json",
            )

        self.assertEqual(response.status_code, 200)
        commande = Commande.objects.get(pk=response.json()["commande_id"])
        self.assertEqual(commande.point_de_vente, magasin_central)
        self.assertEqual(commande.lignes.get().prix_unitaire, Decimal("880.00"))

        a4_response = self.client.get(reverse("facturation:facture-detail", args=[commande.pk]))
        ticket_response = self.client.get(
            f"{reverse('facturation:facture-detail', args=[commande.pk])}?format=TICKET_80MM"
        )

        self.assertContains(a4_response, "Point de vente : Magasin Central")
        self.assertContains(a4_response, "Adresse : Adresse Magasin Central")
        self.assertContains(ticket_response, "PDV : Magasin Central")
        self.assertContains(ticket_response, "Adresse : Adresse Magasin Central")
        self.assertEqual(a4_response.context["document_point_de_vente"], magasin_central)
        self.assertEqual(ticket_response.context["document_point_de_vente"], magasin_central)

    def test_pos_page_exposes_rrr_controls(self):
        """Verifie que le POS expose les controles necessaires au mode RRR."""

        response = self.client.get(reverse("facturation:pos-view"))

        self.assertEqual(response.status_code, 200)
        self.assertContains(response, "Avoir commercial RRR (FA)")
        self.assertContains(response, "Référence facture de vente")

    def test_pos_respects_user_ui_overrides_for_action_buttons(self):
        """Verifie que les overrides UI utilisateur pilotent les boutons POS visibles."""

        permissions = get_default_menu_permission_map("VENDEUR")
        permissions["categories_create"] = True
        save_user_menu_permissions(self.user, permissions)
        if hasattr(self.user, "_cached_pos_permission_map"):
            delattr(self.user, "_cached_pos_permission_map")

        for button_key in (
            "show_add_product_button",
            "show_category_quick_create_button",
            "show_edit_product_button",
        ):
            UserPermissionBouton.objects.update_or_create(
                user=self.user,
                module="point_de_vente",
                bouton=button_key,
                defaults={
                    "label": button_key,
                    "autorise": False,
                    "created_by": self.user,
                },
            )
        cache.clear()

        response = self.client.get(reverse("facturation:pos-view"))

        self.assertEqual(response.status_code, 200)
        self.assertFalse(response.context["show_add_product_button"])
        self.assertFalse(response.context["can_add_product_from_pos"])
        self.assertFalse(response.context["can_add_category_from_pos"])
        self.assertFalse(response.context["can_edit_product_from_pos"])

    def test_pos_rrr_creates_credit_note_without_source_and_does_not_touch_stock(self):
        """Verifie qu'un RRR cree un avoir sans source et sans mouvement de stock."""

        payload = {
            "document_mode": "RRR",
            "panier": [
                {
                    "id": self.product.pk,
                    "qty": 1,
                    "rrr_unit_price": 5000,
                }
            ],
            "client_id": self.customer.pk,
            "commentaires": ["Ristourne de fin de mois"],
            "reference_facture_vente": "",
        }

        with patch(
            "facturation.views.FiscalOrchestrator.fiscalize_commande",
            return_value={
                "success": True,
                "channel": "EMCF",
                "commande_id": 1,
                "fiscal_transaction_id": "rrr-pos-001",
            },
        ) as mock_fiscalize:
            response = self.client.post(
                reverse("facturation:pos-view"),
                data=json.dumps(payload),
                content_type="application/json",
            )

        self.assertEqual(response.status_code, 200)
        data = response.json()
        commande = Commande.objects.get(pk=data["commande_id"])
        expected_breakdown = compute_line_tax_breakdown(
            Decimal("5000.00"),
            Decimal("16.00"),
            "ttc",
            "B",
        )

        self.assertEqual(commande.type_facture, "FA")
        self.assertEqual(commande.nature_avoir, "RRR")
        self.assertEqual(commande.reference_avoir, "RRR")
        self.assertEqual(commande.commentaire, "Ristourne de fin de mois")
        self.assertEqual(commande.motif_annulation, "Rabais, Remise, Ristourne")
        self.assertEqual(commande.montant_total.quantize(Decimal("0.01")), expected_breakdown["ttc_amount"].quantize(Decimal("0.01")))
        self.assertEqual(commande.tva_montant.quantize(Decimal("0.01")), expected_breakdown["tax_amount"].quantize(Decimal("0.01")))
        self.assertEqual(commande.montant_paye.quantize(Decimal("0.01")), commande.montant_total.quantize(Decimal("0.01")))
        self.assertEqual(commande.paiements.count(), 0)
        self.assertIn(
            str(commande.pk),
            self.client.session.get("fresh_credit_note_original_views", []),
        )
        self.stock.refresh_from_db()
        self.assertEqual(self.stock.quantite, Decimal("100.000"))
        self.assertFalse(MouvementStock.objects.filter(commande_associee=commande).exists())
        mock_fiscalize.assert_called_once()

        first_detail = self.client.get(reverse("facturation:facture-detail", args=[commande.pk]))
        second_detail = self.client.get(reverse("facturation:facture-detail", args=[commande.pk]))
        self.assertFalse(first_detail.context["is_duplicata"])
        self.assertTrue(second_detail.context["is_duplicata"])

    def test_pos_rrr_uses_source_reference_when_provided(self):
        """Verifie qu'un RRR reutilise la reference source lorsqu'elle est fournie."""

        payload = {
            "document_mode": "RRR",
            "panier": [
                {
                    "id": self.product.pk,
                    "qty": 1,
                    "rrr_unit_price": 3200,
                }
            ],
            "client_id": self.customer.pk,
            "reference_facture_vente": "FV-2026-00999",
        }

        with patch(
            "facturation.views.FiscalOrchestrator.fiscalize_commande",
            return_value={
                "success": True,
                "channel": "EMCF",
                "commande_id": 1,
                "fiscal_transaction_id": "rrr-pos-002",
            },
        ):
            response = self.client.post(
                reverse("facturation:pos-view"),
                data=json.dumps(payload),
                content_type="application/json",
            )

        self.assertEqual(response.status_code, 200)
        commande = Commande.objects.get(pk=response.json()["commande_id"])
        self.assertEqual(commande.reference_avoir, "FV-2026-00999")
        self.assertIsNone(commande.facture_origine)

    def test_fiscal_payload_builder_builds_rrr_credit_note_payload(self):
        """Verifie que le constructeur fiscal genere correctement le payload d'avoir RRR."""

        commande = Commande.objects.create(
            point_de_vente=self.point_de_vente,
            vendeur=self.user,
            client=self.customer,
            montant_total=Decimal("5000.00"),
            montant_paye=Decimal("5000.00"),
            tva_montant=Decimal("689.66"),
            taux_change_applique=Decimal("1.00"),
            type_facture="FA",
            nature_avoir="RRR",
            reference_avoir="RRR",
            motif_annulation="Rabais, Remise, Ristourne",
            commentaire="Ajustement commercial global",
            mode_dgi="ttc",
        )
        LigneCommande.objects.create(
            commande=commande,
            produit=self.product,
            quantite=Decimal("1.000"),
            prix_unitaire=Decimal("5000.00"),
            remise=Decimal("0.00"),
            sous_total=Decimal("5000.00"),
        )

        prepared_payload = FiscalPayloadBuilder(fiscal_transaction_id="rrrpayload1").build(commande)
        request_payload = EmcfAdapter()._build_request_payload(prepared_payload)

        self.assertEqual(prepared_payload["commande"]["type_facture"], "FA")
        self.assertEqual(prepared_payload["commande"]["rr"], "RRR")
        self.assertEqual(prepared_payload["commande"]["rn"], "RRR")
        self.assertEqual(request_payload["type"], "FA")
        self.assertEqual(request_payload["reference"], "RRR")
        self.assertEqual(request_payload["referenceType"], "RRR")
        # referenceDesc = mention officielle de la nature (tableau de parametrage DGI III).
        self.assertEqual(request_payload["referenceDesc"], "RRR")

    def test_commande_list_displays_rrr_badge(self):
        """Verifie que la liste des commandes affiche le badge RRR approprie."""

        commande = Commande.objects.create(
            point_de_vente=self.point_de_vente,
            vendeur=self.user,
            client=self.customer,
            montant_total=Decimal("2500.00"),
            montant_paye=Decimal("2500.00"),
            tva_montant=Decimal("344.83"),
            taux_change_applique=Decimal("1.00"),
            type_facture="FA",
            nature_avoir="RRR",
            reference_avoir="RRR",
            motif_annulation="Rabais, Remise, Ristourne",
        )

        response = self.client.get(reverse("facturation:commande-list"))

        self.assertEqual(response.status_code, 200)
        self.assertContains(response, commande.numero)
        self.assertContains(response, "FA / RRR")

    def test_commande_list_filters_invoices_between_two_dates(self):
        """Verifie que l'historique filtre les factures sur une periode precise."""

        def create_commande_at(day, hour):
            commande = Commande.objects.create(
                point_de_vente=self.point_de_vente,
                vendeur=self.user,
                client=self.customer,
                montant_total=Decimal("2500.00"),
                montant_paye=Decimal("2500.00"),
                tva_montant=Decimal("344.83"),
                taux_change_applique=Decimal("1.00"),
                type_facture="FV",
            )
            date_value = timezone.make_aware(
                datetime(2026, 6, day, hour, 0),
                timezone.get_current_timezone(),
            )
            Commande.objects.filter(pk=commande.pk).update(date_commande=date_value)
            commande.date_commande = date_value
            return commande

        before_period = create_commande_at(1, 23)
        inside_period = create_commande_at(2, 9)
        inside_period_late = create_commande_at(2, 22)
        after_period = create_commande_at(3, 0)

        response = self.client.get(
            reverse("facturation:commande-list"),
            {
                "date_debut": "2026-06-02",
                "date_fin": "2026-06-02",
            },
        )

        self.assertEqual(response.status_code, 200)
        self.assertContains(response, 'name="date_debut"', html=False)
        self.assertContains(response, 'name="date_fin"', html=False)
        self.assertNotContains(response, "Mois / Année")
        self.assertContains(response, inside_period.numero)
        self.assertContains(response, inside_period_late.numero)
        self.assertNotContains(response, before_period.numero)
        self.assertNotContains(response, after_period.numero)

    def test_commande_list_filters_invoices_by_fiscal_channel(self):
        """Verifie le filtre e-MCF / MCF de l'historique, de son export et la valeur invalide."""

        def create_commande(channel):
            return Commande.objects.create(
                point_de_vente=self.point_de_vente,
                vendeur=self.user,
                client=self.customer,
                montant_total=Decimal("116.00"),
                montant_paye=Decimal("116.00"),
                tva_montant=Decimal("16.00"),
                taux_change_applique=Decimal("1.00"),
                type_facture="FV",
                fiscal_channel=channel,
            )

        emcf = create_commande("EMCF")
        mcf = create_commande("MCF")
        non_fiscalisee = create_commande(None)

        response = self.client.get(reverse("facturation:commande-list"), {"canal": "EMCF"})
        self.assertEqual(response.status_code, 200)
        self.assertEqual([c.pk for g in response.context["commande_groups"] for c in g["commandes"]], [emcf.pk])
        self.assertContains(response, 'name="canal"', html=False)
        self.assertContains(response, '<option value="EMCF" selected>', html=False)
        self.assertContains(response, "e-MCF / FV")

        response = self.client.get(reverse("facturation:commande-list"), {"canal": "mcf"})
        self.assertEqual([c.pk for g in response.context["commande_groups"] for c in g["commandes"]], [mcf.pk])

        response = self.client.get(reverse("facturation:commande-list"))
        self.assertEqual(
            {c.pk for g in response.context["commande_groups"] for c in g["commandes"]},
            {emcf.pk, mcf.pk, non_fiscalisee.pk},
        )

        response = self.client.get(reverse("facturation:commande-list"), {"canal": "PAPIER"})
        self.assertIn("Filtre canal fiscal invalide.", response.context["commande_filter_errors"])
        self.assertEqual(response.context["commande_groups"], [])

        from openpyxl import load_workbook

        self.client.force_login(
            get_user_model().objects.create_superuser(
                username="admin-canal", email="admin-canal@test.com", password="secret123"
            )
        )
        export_response = self.client.get(reverse("facturation:commande-export-excel"), {"canal": "MCF"})
        self.assertEqual(export_response.status_code, 200)
        worksheet = load_workbook(BytesIO(export_response.content), data_only=True).active
        numeros = [worksheet.cell(row=row, column=1).value for row in range(2, worksheet.max_row + 1)]
        self.assertIn(mcf.numero, numeros)
        self.assertNotIn(emcf.numero, numeros)
        self.assertEqual(worksheet.cell(row=2, column=12).value, "MCF physique")

    def test_commande_list_shows_newest_invoices_first_whatever_store_or_channel(self):
        """Verifie le tri du plus recent au plus ancien, sans ordre alphabetique des magasins."""

        self.client.force_login(
            get_user_model().objects.create_superuser(
                username="admin-tri", email="admin-tri@test.com", password="secret123"
            )
        )
        premier_magasin = PointDeVente.objects.create(nom="AAA Magasin")
        now = timezone.now()

        def create_commande(point_de_vente, channel, days_ago):
            commande = Commande.objects.create(
                point_de_vente=point_de_vente,
                vendeur=self.user,
                client=self.customer,
                montant_total=Decimal("116.00"),
                montant_paye=Decimal("116.00"),
                tva_montant=Decimal("16.00"),
                taux_change_applique=Decimal("1.00"),
                type_facture="FV",
                fiscal_channel=channel,
            )
            Commande.objects.filter(pk=commande.pk).update(date_commande=now - timedelta(days=days_ago))
            return commande

        ancienne = create_commande(premier_magasin, "EMCF", 30)
        recente = create_commande(self.point_de_vente, "MCF", 0)
        intermediaire = create_commande(premier_magasin, "EMCF", 10)

        response = self.client.get(reverse("facturation:commande-list"))

        groups = response.context["commande_groups"]
        self.assertEqual([group["point_de_vente"] for group in groups], ["Boutique Test", "AAA Magasin"])
        self.assertEqual([c.pk for c in groups[0]["commandes"]], [recente.pk])
        self.assertEqual([c.pk for c in groups[1]["commandes"]], [intermediaire.pk, ancienne.pk])

        from openpyxl import load_workbook

        export_response = self.client.get(reverse("facturation:commande-export-excel"))
        worksheet = load_workbook(BytesIO(export_response.content), data_only=True).active
        self.assertEqual(worksheet.cell(row=2, column=1).value, recente.numero)

    def test_commande_list_displays_store_subtotals_and_exports_them(self):
        """Verifie les sous-totaux par magasin dans l'historique et l'export."""

        other_point_de_vente = PointDeVente.objects.create(nom="Magasin Bis")
        admin = get_user_model().objects.create_superuser(
            username="admin-historique",
            email="admin-historique@test.com",
            password="secret123",
        )
        self.client.force_login(admin)

        commandes_payload = (
            (self.point_de_vente, Decimal("116.00"), Decimal("100.00"), Decimal("16.00")),
            (self.point_de_vente, Decimal("232.00"), Decimal("232.00"), Decimal("32.00")),
            (other_point_de_vente, Decimal("58.00"), Decimal("50.00"), Decimal("8.00")),
        )
        for point_de_vente, total, paye, tva in commandes_payload:
            Commande.objects.create(
                point_de_vente=point_de_vente,
                vendeur=self.user,
                client=self.customer,
                montant_total=total,
                montant_paye=paye,
                tva_montant=tva,
                taux_change_applique=Decimal("1.00"),
                type_facture="FV",
            )

        response = self.client.get(reverse("facturation:commande-list"))

        self.assertEqual(response.status_code, 200)
        self.assertContains(response, "commande-history-table-wrap")
        self.assertContains(response, "commande-subtotal-row")
        self.assertContains(response, "commande-history-footer")
        self.assertContains(response, "SOUS-TOTAL")
        self.assertContains(response, "Boutique Test")
        self.assertContains(response, "Magasin Bis")
        self.assertContains(response, "TOTAL GENERAL")
        store_totals = {
            group["point_de_vente"]: group["total"]
            for group in response.context["commande_groups"]
        }
        store_ht_totals = {
            group["point_de_vente"]: group["ht"]
            for group in response.context["commande_groups"]
        }
        self.assertEqual(store_totals["Boutique Test"], Decimal("348.00"))
        self.assertEqual(store_totals["Magasin Bis"], Decimal("58.00"))
        self.assertEqual(store_ht_totals["Boutique Test"], Decimal("300.00"))
        self.assertEqual(store_ht_totals["Magasin Bis"], Decimal("50.00"))
        # Le tableau compact conserve le HT dans ses totaux de contexte et
        # dans Excel, mais affiche Date + heure dans une seule colonne.
        self.assertNotContains(response, "Montant Hors taxe")
        self.assertContains(response, '<th scope="col">Date</th>', html=False)
        self.assertNotContains(response, '<th scope="col">Heure</th>', html=False)
        first_commande = response.context["commande_groups"][0]["commandes"][0]
        local_commande_datetime = timezone.localtime(first_commande.date_commande)
        self.assertContains(response, local_commande_datetime.strftime("%d/%m/%Y"))
        self.assertContains(response, local_commande_datetime.strftime("%H:%M"))

        from openpyxl import load_workbook

        export_response = self.client.get(reverse("facturation:commande-export-excel"))
        self.assertEqual(export_response.status_code, 200)
        workbook = load_workbook(BytesIO(export_response.content), data_only=True)
        worksheet = workbook.active
        first_column_values = [cell.value for cell in worksheet["A"] if cell.value]
        self.assertTrue(any(str(value).startswith("SOUS-TOTAL — Boutique Test") for value in first_column_values))
        self.assertTrue(any(str(value).startswith("SOUS-TOTAL — Magasin Bis") for value in first_column_values))
        self.assertIn("TOTAL GENERAL", first_column_values)
        merged_ranges = {str(cell_range) for cell_range in worksheet.merged_cells.ranges}

        def find_excel_row(label_prefix):
            for row_index in range(1, worksheet.max_row + 1):
                value = worksheet.cell(row=row_index, column=1).value
                if value and str(value).startswith(label_prefix):
                    return row_index
            return None

        boutique_subtotal_row = find_excel_row("SOUS-TOTAL — Boutique Test")
        magasin_subtotal_row = find_excel_row("SOUS-TOTAL — Magasin Bis")
        total_row = find_excel_row("TOTAL GENERAL")
        self.assertIsNotNone(boutique_subtotal_row)
        self.assertIsNotNone(magasin_subtotal_row)
        self.assertIsNotNone(total_row)
        self.assertEqual([cell.value for cell in worksheet[1]], [
            "Numéro", "Client", "Date", "Heure", "Montant Hors taxe", "TVA", "Montant Total",
            "Montant Payé", "Reste", "Statut", "Vendeur", "Canal fiscal",
        ])
        self.assertEqual(worksheet.cell(row=2, column=3).number_format, "dd/mm/yyyy")
        self.assertEqual(worksheet.cell(row=2, column=4).number_format, "hh:mm")
        self.assertIn(f"A{boutique_subtotal_row}:D{boutique_subtotal_row}", merged_ranges)
        self.assertIn(f"A{magasin_subtotal_row}:D{magasin_subtotal_row}", merged_ranges)
        self.assertIn(f"A{total_row}:D{total_row}", merged_ranges)
        self.assertEqual(worksheet.cell(row=boutique_subtotal_row, column=5).value, 300)
        self.assertEqual(worksheet.cell(row=boutique_subtotal_row, column=6).value, 48)
        self.assertEqual(worksheet.cell(row=boutique_subtotal_row, column=7).value, 348)
        self.assertEqual(worksheet.cell(row=boutique_subtotal_row, column=8).value, 332)
        self.assertEqual(worksheet.cell(row=boutique_subtotal_row, column=9).value, 16)
        self.assertEqual(worksheet.cell(row=magasin_subtotal_row, column=5).value, 50)
        self.assertEqual(worksheet.cell(row=magasin_subtotal_row, column=6).value, 8)
        self.assertEqual(worksheet.cell(row=magasin_subtotal_row, column=7).value, 58)
        self.assertEqual(worksheet.cell(row=magasin_subtotal_row, column=8).value, 50)
        self.assertEqual(worksheet.cell(row=magasin_subtotal_row, column=9).value, 8)
        self.assertEqual(worksheet.cell(row=total_row, column=5).value, 350)
        self.assertEqual(worksheet.cell(row=total_row, column=7).value, 406)
        self.assertEqual(worksheet.freeze_panes, "A2")

        pdf_export_response = self.client.get(reverse("facturation:commande-export-pdf"))
        self.assertEqual(pdf_export_response.status_code, 200)
        self.assertEqual(pdf_export_response["Content-Type"], "application/zip")
        self.assertIn("factures_", pdf_export_response["Content-Disposition"])
        with zipfile.ZipFile(BytesIO(pdf_export_response.content)) as archive:
            pdf_names = archive.namelist()
            self.assertEqual(len(pdf_names), 3)
            self.assertTrue(all(name.endswith(".pdf") for name in pdf_names))
            self.assertTrue(all(self.customer.nom_complet.replace(" ", "_") in name for name in pdf_names))
            self.assertTrue(all(archive.read(name).startswith(b"%PDF-1.4") for name in pdf_names))

        UserPrintPreference.objects.update_or_create(
            user=admin,
            defaults={"format_impression_defaut": "TICKET_80MM"},
        )
        ticket_export_response = self.client.get(reverse("facturation:commande-export-pdf"))
        self.assertEqual(ticket_export_response.status_code, 200)
        from pypdf import PdfReader
        with zipfile.ZipFile(BytesIO(ticket_export_response.content)) as archive:
            first_ticket_pdf = BytesIO(archive.read(archive.namelist()[0]))
            ticket_page_width = float(PdfReader(first_ticket_pdf).pages[0].mediabox.width)
        self.assertLess(ticket_page_width, 300)  # 80 mm ~= 227 points; A4 ~= 595 points.

        one_commande = response.context["commande_groups"][0]["commandes"][0]
        single_pdf_response = self.client.get(
            reverse("facturation:commande-download-pdf", args=[one_commande.pk])
        )
        self.assertEqual(single_pdf_response.status_code, 200)
        self.assertEqual(single_pdf_response["Content-Type"], "application/pdf")
        self.assertTrue(single_pdf_response.content.startswith(b"%PDF"))
        self.assertIn(one_commande.numero, single_pdf_response["Content-Disposition"])
        self.assertContains(
            response,
            reverse("facturation:commande-download-pdf", args=[one_commande.pk]),
        )
    def test_ca_report_uses_dynamic_tax_columns_from_sales_lines(self):
        """Verifie que le rapport CA n'affiche que les groupes taxe réellement vendus."""

        UserMenuPermission.objects.create(
            user=self.user,
            permission_key="rapport_chiffre_affaires",
            is_allowed=True,
        )
        UserMenuPermission.objects.create(
            user=self.user,
            permission_key="rapports_export",
            is_allowed=True,
        )
        tax_group_c, _ = TaxGroup.objects.update_or_create(
            code="C",
            defaults={"name": "Groupe C", "tax": Decimal("5.00")},
        )
        tax_group_f, _ = TaxGroup.objects.update_or_create(
            code="F",
            defaults={"name": "Groupe F", "tax": Decimal("16.00")},
        )
        TaxGroup.objects.update_or_create(
            code="Z",
            defaults={"name": "Groupe sans vente", "tax": Decimal("8.00")},
        )
        product_c = Produit.objects.create(
            nom="Produit groupe C",
            code_sku="PROD-C-CA",
            prix_vente=Decimal("1050.00"),
            taxgroup=tax_group_c,
            typeart=self.item_type,
            actif=True,
        )
        product_f = Produit.objects.create(
            nom="Produit groupe F",
            code_sku="PROD-F-CA",
            prix_vente=Decimal("580.00"),
            taxgroup=tax_group_f,
            typeart=self.item_type,
            actif=True,
        )
        commande = Commande.objects.create(
            point_de_vente=self.point_de_vente,
            vendeur=self.user,
            client=self.customer,
            montant_total=Decimal("2790.00"),
            montant_paye=Decimal("2500.00"),
            tva_montant=Decimal("290.00"),
            taux_change_applique=Decimal("1.00"),
            type_facture="FV",
            mode_dgi="ttc",
        )
        LigneCommande.objects.create(
            commande=commande,
            produit=self.product,
            quantite=Decimal("1.000"),
            prix_unitaire=Decimal("1160.00"),
            remise=Decimal("0.00"),
            sous_total=Decimal("1160.00"),
        )
        LigneCommande.objects.create(
            commande=commande,
            produit=product_c,
            quantite=Decimal("1.000"),
            prix_unitaire=Decimal("1050.00"),
            remise=Decimal("0.00"),
            sous_total=Decimal("1050.00"),
        )
        LigneCommande.objects.create(
            commande=commande,
            produit=product_f,
            quantite=Decimal("1.000"),
            prix_unitaire=Decimal("580.00"),
            remise=Decimal("0.00"),
            sous_total=Decimal("580.00"),
        )

        response = self.client.get(reverse("facturation:rapport-chiffre-affaires"))

        self.assertEqual(response.status_code, 200)
        tax_labels = [
            column["label"]
            for column in response.context["ca_report_dynamic_tax_columns"]
        ]
        self.assertEqual(tax_labels, ["16%", "5%"])
        self.assertEqual(tax_labels.count("16%"), 1)
        self.assertContains(response, "MONTANT TVA")
        self.assertContains(response, "16%")
        self.assertContains(response, "5%")
        self.assertNotContains(response, "16% (B)")
        self.assertNotContains(response, "16% (F)")
        self.assertNotContains(response, "5% (C)")
        self.assertNotContains(response, "8% (Z)")
        row = response.context["ca_report_rows"][0]
        self.assertEqual(row["point_de_vente"], self.point_de_vente.nom)
        self.assertEqual(
            [value["amount"] for value in row["tva_values"]],
            [Decimal("240.00"), Decimal("50.00")],
        )
        self.assertEqual(response.context["ca_report_totals"]["tva"], Decimal("290.00"))

        export_response = self.client.get(
            reverse("facturation:rapport-chiffre-affaires-export-excel")
        )
        self.assertEqual(export_response.status_code, 200)
        self.assertEqual(
            export_response["Content-Type"],
            "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
        )
        from openpyxl import load_workbook

        workbook = load_workbook(BytesIO(export_response.content), data_only=True)
        header_values = [cell.value for cell in workbook.active[2] if cell.value]
        self.assertIn("16%", header_values)
        self.assertIn("5%", header_values)
        self.assertNotIn("16% (B)", header_values)
        self.assertNotIn("16% (F)", header_values)
        self.assertNotIn("5% (C)", header_values)

    def test_pos_sale_returns_clear_error_when_client_nif_format_is_invalid_for_mcf(self):
        """Verifie qu'une vente POS renvoie une erreur claire quand le NIF client est invalide pour le MCF."""

        invalid_client = Client.objects.create(
            nom_complet="Client NIF KO",
            nif="12345",
            client_type=self.client_type_pp,
        )
        payload = {
            "panier": [
                {
                    "id": self.product.pk,
                    "qty": 1,
                    "remise": 0,
                }
            ],
            "client_id": invalid_client.pk,
            "paiement": {
                "montant_verse": 64400,
                "devise": "CDF",
                "taux": 1,
                "mode": "ESPECES",
            },
        }

        with patch("mcf.mcf_adapter.MCFAdapter._ensure_device_is_ready", return_value=None):
            response = self.client.post(
                reverse("facturation:pos-view"),
                data=json.dumps(payload),
                content_type="application/json",
            )

        self.assertEqual(response.status_code, 400)
        self.assertIn("format du NIF", response.json()["error"])
        self.assertFalse(Commande.objects.filter(client=invalid_client).exists())

    def test_pos_sale_persists_mcf_security_elements(self):
        """Verifie qu'une vente POS persiste bien les elements de securite MCF."""

        security = {
            "date_time": "26/03/2026 18:10:27",
            "code_def_dgi": "SIG-38",
            "counters": "FC001/TC002 FT003",
            "nim": "NIM-38",
            "qr_code": "RDCDEF01;NIM-38;SIG-38;A1234567Q;20260326181027",
        }
        payload = {
            "panier": [
                {
                    "id": self.product.pk,
                    "qty": 1,
                    "remise": 0,
                }
            ],
            "paiement": {
                "montant_verse": 64400,
                "devise": "CDF",
                "taux": 1,
                "mode": "ESPECES",
            },
            "commentaire": "Test MCF 38h",
        }

        with patch("mcf.mcf_adapter.MCFAdapter._ensure_device_is_ready", return_value=None), patch(
            "mcf.services_mcf.MCFInvoiceService.send_invoice",
            return_value={
                "success": True,
                "device": "MCF Principal",
                "port": "COM9",
                "security": security,
                "response": {"security": security},
            },
        ) as mock_send_invoice:
            response = self.client.post(
                reverse("facturation:pos-view"),
                data=json.dumps(payload),
                content_type="application/json",
            )

        self.assertEqual(response.status_code, 200)
        data = response.json()
        self.assertTrue(data["success"])
        self.assertEqual(data["fiscal_channel"], "MCF")
        mock_send_invoice.assert_called_once()

        commande = Commande.objects.get(pk=data["commande_id"])
        self.assertEqual(commande.fiscal_channel, "MCF")
        self.assertEqual(commande.codedefdgi, "SIG-38")
        self.assertEqual(commande.counters, "FC001/TC002 FT003")
        self.assertEqual(commande.nim, "NIM-38")
        self.assertEqual(commande.qrCode, "RDCDEF01;NIM-38;SIG-38;A1234567Q;20260326181027")
        self.assertEqual(commande.dateTimedgi, "26/03/2026 18:10:27")

    def test_pos_sale_uses_point_de_vente_stock_price(self):
        """Verifie que la vente POS fige le prix de vente du point de vente courant."""

        self.stock.prix_vente = Decimal("70000.00")
        self.stock.save(update_fields=["prix_vente", "updated_at"])
        payload = {
            "panier": [
                {
                    "id": self.product.pk,
                    "qty": 1,
                    "remise": 0,
                }
            ],
            "paiement": {
                "montant_verse": 70000,
                "devise": "CDF",
                "taux": 1,
                "mode": "ESPECES",
            },
        }

        with patch(
            "facturation.views.FiscalOrchestrator.fiscalize_commande",
            return_value={
                "success": True,
                "channel": "MCF",
                "commande_id": 1,
                "fiscal_transaction_id": "prix-pdv-pos-001",
            },
        ):
            response = self.client.post(
                reverse("facturation:pos-view"),
                data=json.dumps(payload),
                content_type="application/json",
            )

        self.assertEqual(response.status_code, 200)
        commande = Commande.objects.get(pk=response.json()["commande_id"])
        ligne = commande.lignes.get()
        self.assertEqual(ligne.prix_unitaire, Decimal("70000.00"))
        self.assertEqual(ligne.sous_total, Decimal("70000.00"))

    def test_pos_sale_accepts_grouped_payment_string_from_browser_locale(self):
        """Verifie qu'une vente POS accepte une chaine de paiement groupee provenant du navigateur."""

        security = {
            "date_time": "26/03/2026 18:20:27",
            "code_def_dgi": "SIG-39",
            "counters": "FC004/TC005 FT006",
            "nim": "NIM-39",
            "qr_code": "RDCDEF01;NIM-39;SIG-39;A1234567Q;20260326182027",
        }
        payload = {
            "panier": [
                {
                    "id": self.product.pk,
                    "qty": 1,
                    "remise": 0,
                }
            ],
            "paiement": {
                "montant_verse": "64,400",
                "devise": "CDF",
                "taux": 1,
                "mode": "ESPECES",
            },
            "commentaire": "Test montant avec separateur",
        }

        with patch("mcf.mcf_adapter.MCFAdapter._ensure_device_is_ready", return_value=None), patch(
            "mcf.services_mcf.MCFInvoiceService.send_invoice",
            return_value={
                "success": True,
                "device": "MCF Principal",
                "port": "COM9",
                "security": security,
                "response": {"security": security},
            },
        ):
            response = self.client.post(
                reverse("facturation:pos-view"),
                data=json.dumps(payload),
                content_type="application/json",
            )

        self.assertEqual(response.status_code, 200)
        commande = Commande.objects.get(pk=response.json()["commande_id"])
        paiement = commande.paiements.get()
        self.assertEqual(commande.montant_paye.quantize(Decimal("0.01")), Decimal("64400.00"))
        self.assertEqual(paiement.montant_verse.quantize(Decimal("0.01")), Decimal("64400.00"))

    def test_pos_sale_prorates_vat_after_global_discount_in_ht_mode(self):
        """Verifie qu'une vente POS prorate la TVA apres remise globale en mode HT."""

        Configuration.objects.update(mode_dgi="ht")
        security = {
            "date_time": "26/03/2026 20:10:27",
            "code_def_dgi": "SIG-HT",
            "counters": "FC010/TC010 FT010",
            "nim": "NIM-HT",
            "qr_code": "RDCDEF01;NIM-HT;SIG-HT;A1234567Q;20260326201027",
        }
        payload = {
            "panier": [
                {
                    "id": self.product.pk,
                    "qty": 1,
                    "remise": 0,
                }
            ],
            "paiement": {
                "montant_verse": 70000,
                "devise": "CDF",
                "taux": 1,
                "mode": "ESPECES",
            },
            "remise_globale": 7470.4,
            "commentaire": "Test HT remise globale",
        }

        with patch("mcf.mcf_adapter.MCFAdapter._ensure_device_is_ready", return_value=None), patch(
            "mcf.services_mcf.MCFInvoiceService.send_invoice",
            return_value={
                "success": True,
                "device": "MCF Principal",
                "port": "COM9",
                "security": security,
                "response": {"security": security},
            },
        ):
            response = self.client.post(
                reverse("facturation:pos-view"),
                data=json.dumps(payload),
                content_type="application/json",
            )

        self.assertEqual(response.status_code, 200)
        commande = Commande.objects.get(pk=response.json()["commande_id"])
        self.assertEqual(commande.montant_total.quantize(Decimal("0.01")), Decimal("67233.60"))
        self.assertEqual(commande.tva_montant.quantize(Decimal("0.01")), Decimal("9273.60"))

    def test_pos_sale_at_zero_stock_records_negative_history(self):
        """Une vente sans stock reste tracee par une sortie et un solde negatif."""

        self.stock.quantite = Decimal("0.000")
        self.stock.save(update_fields=["quantite", "updated_at"])

        payload = {
            "panier": [
                {
                    "id": self.product.pk,
                    "qty": 1,
                    "remise": 0,
                }
            ],
            "paiement": {
                "montant_verse": 64400,
                "devise": "CDF",
                "taux": 1,
                "mode": "ESPECES",
            },
        }

        with patch(
            "facturation.views.FiscalOrchestrator.fiscalize_commande",
            return_value={
                "success": True,
                "channel": "MCF",
                "commande_id": 1,
                "fiscal_transaction_id": "zero-stock-pos-001",
            },
        ):
            response = self.client.post(
                reverse("facturation:pos-view"),
                data=json.dumps(payload),
                content_type="application/json",
            )

        self.assertEqual(response.status_code, 200, response.content)
        commande = Commande.objects.get(pk=response.json()["commande_id"])
        mouvement = MouvementStock.objects.get(commande_associee=commande)
        self.assertEqual(mouvement.quantite, Decimal("-1.000"))
        self.assertEqual(mouvement.stock_avant, Decimal("0.000"))
        self.assertEqual(mouvement.stock_apres, Decimal("-1.000"))
        self.stock.refresh_from_db()
        self.assertEqual(self.stock.quantite, Decimal("-1.000"))

    def test_pos_sale_creates_missing_stock_line_and_records_negative_history(self):
        """Le POS cree le support d'historique si le produit n'a aucune ligne de stock."""

        product_without_stock = Produit.objects.create(
            nom="Produit sans stock",
            code_sku="NOSTOCK-001",
            prix_vente=Decimal("2500.00"),
            taxgroup=self.tax_group,
            typeart=self.item_type,
            actif=True,
        )
        payload = {
            "panier": [
                {
                    "id": product_without_stock.pk,
                    "qty": 1,
                    "remise": 0,
                }
            ],
            "paiement": {
                "montant_verse": 2500,
                "devise": "CDF",
                "taux": 1,
                "mode": "ESPECES",
            },
        }

        with patch(
            "facturation.views.FiscalOrchestrator.fiscalize_commande",
            return_value={
                "success": True,
                "channel": "MCF",
                "commande_id": 1,
                "fiscal_transaction_id": "no-stock-row-pos-001",
            },
        ):
            response = self.client.post(
                reverse("facturation:pos-view"),
                data=json.dumps(payload),
                content_type="application/json",
            )

        self.assertEqual(response.status_code, 200, response.content)
        stock = StockPointDeVente.objects.get(
            point_de_vente=self.point_de_vente,
            produit=product_without_stock,
        )
        self.assertEqual(stock.quantite, Decimal("-1.000"))
        mouvement = MouvementStock.objects.get(
            commande_associee_id=response.json()["commande_id"],
            stock=stock,
        )
        self.assertEqual(mouvement.quantite, Decimal("-1.000"))
        self.assertEqual(mouvement.stock_avant, Decimal("0.000"))
        self.assertEqual(mouvement.stock_apres, Decimal("-1.000"))

    def test_pos_sale_above_available_stock_records_every_negative_movement(self):
        """Chaque ligne vendue reste dans l'historique meme si le total depasse le stock."""

        payload = {
            "panier": [
                {
                    "id": self.product.pk,
                    "qty": 60,
                    "remise": 0,
                },
                {
                    "id": self.product.pk,
                    "qty": 50,
                    "remise": 0,
                },
            ],
            "paiement": {
                "montant_verse": 1000,
                "devise": "CDF",
                "taux": 1,
                "mode": "ESPECES",
            },
        }

        with patch(
            "facturation.views.FiscalOrchestrator.fiscalize_commande",
            return_value={
                "success": True,
                "channel": "MCF",
                "commande_id": 1,
                "fiscal_transaction_id": "partial-stock-pos-001",
            },
        ):
            response = self.client.post(
                reverse("facturation:pos-view"),
                data=json.dumps(payload),
                content_type="application/json",
            )

        self.assertEqual(response.status_code, 200, response.content)
        commande = Commande.objects.get(pk=response.json()["commande_id"])
        mouvements = list(
            MouvementStock.objects.filter(commande_associee=commande)
            .order_by("pk")
            .values_list("quantite", flat=True)
        )
        self.assertEqual(mouvements, [Decimal("-60.000"), Decimal("-50.000")])
        self.stock.refresh_from_db()
        self.assertEqual(self.stock.quantite, Decimal("-10.000"))

    def test_pos_sale_includes_vat_on_specific_tax_in_totals(self):
        """Verifie qu'une vente POS inclut la TVA appliquee a la taxe specifique dans les totaux."""

        payload = {
            "panier": [
                {
                    "id": self.product_specific.pk,
                    "qty": 1,
                    "remise": 0,
                }
            ],
            "paiement": {
                "montant_verse": 111.6,
                "devise": "CDF",
                "taux": 1,
                "mode": "ESPECES",
            },
        }

        with patch(
            "facturation.views.FiscalOrchestrator.fiscalize_commande",
            return_value={
                "success": True,
                "channel": "EMCF",
                "commande_id": 1,
                "fiscal_transaction_id": "ts-pos-001",
            },
        ):
            response = self.client.post(
                reverse("facturation:pos-view"),
                data=json.dumps(payload),
                content_type="application/json",
            )

        self.assertEqual(response.status_code, 200)
        commande = Commande.objects.get(pk=response.json()["commande_id"])
        self.assertEqual(commande.montant_total.quantize(Decimal("0.01")), Decimal("111.60"))
        self.assertEqual(commande.tva_montant.quantize(Decimal("0.01")), Decimal("15.39"))


class CommandeNumeroGenerationTests(TestCase):
    """Regroupe les tests de generation des numeros de commande."""


    def setUp(self):
        """Prepare les donnees communes necessaires a ce scenario de test."""

        self.point_de_vente = PointDeVente.objects.create(nom="Boutique Numero")
        self.user = get_user_model().objects.create_user(
            username="vendeur_numero",
            email="vendeur_numero@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",
        )

    def test_new_commande_uses_max_sequence_instead_of_count(self):
        """Verifie que la numerotation des commandes utilise la sequence maximale existante plutot qu'un simple comptage."""

        cmd1 = 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",
        )
        cmd2 = Commande.objects.create(
            point_de_vente=self.point_de_vente,
            vendeur=self.user,
            montant_total=Decimal("200.00"),
            tva_montant=Decimal("32.00"),
            taux_change_applique=Decimal("1.00"),
            type_facture="FV",
        )
        cmd3 = Commande.objects.create(
            point_de_vente=self.point_de_vente,
            vendeur=self.user,
            montant_total=Decimal("300.00"),
            tva_montant=Decimal("48.00"),
            taux_change_applique=Decimal("1.00"),
            type_facture="FV",
        )

        cmd2.delete()

        cmd4 = Commande.objects.create(
            point_de_vente=self.point_de_vente,
            vendeur=self.user,
            montant_total=Decimal("400.00"),
            tva_montant=Decimal("64.00"),
            taux_change_applique=Decimal("1.00"),
            type_facture="FV",
        )

        self.assertTrue(cmd1.numero.endswith("00001"))
        self.assertTrue(cmd2.numero.endswith("00002"))
        self.assertTrue(cmd3.numero.endswith("00003"))
        self.assertTrue(cmd4.numero.endswith("00004"))


class FiscalRulesTests(TestCase):
    """Regroupe les tests des regles de calcul fiscal."""


    def test_compute_line_tax_breakdown_handles_special_tax_groups(self):
        """Verifie que le calcul fiscal gere correctement les groupes de taxe speciaux."""

        breakdown = compute_line_tax_breakdown(
            subtotal=Decimal("57500.00"),
            tax_rate=Decimal("0.00"),
            mode_dgi="ttc",
            tax_group_code="N",
        )

        self.assertEqual(breakdown["ht_amount"], Decimal("0"))
        self.assertEqual(breakdown["tax_amount"], Decimal("57500.00"))
        self.assertEqual(breakdown["ttc_amount"], Decimal("57500.00"))

    def test_compute_line_tax_breakdown_supports_ttc_and_ht_modes(self):
        """Verifie que le calcul fiscal supporte les modes TTC et HT."""

        breakdown_ttc = compute_line_tax_breakdown(
            subtotal=Decimal("103500.00"),
            tax_rate=Decimal("5.00"),
            mode_dgi="ttc",
            tax_group_code="C",
        )
        breakdown_ht = compute_line_tax_breakdown(
            subtotal=Decimal("920000.00"),
            tax_rate=Decimal("16.00"),
            mode_dgi="ht",
            tax_group_code="F",
        )

        self.assertEqual(breakdown_ttc["ht_amount"].quantize(Decimal("0.01")), Decimal("98571.43"))
        self.assertEqual(breakdown_ttc["tax_amount"].quantize(Decimal("0.01")), Decimal("4928.57"))
        self.assertEqual(breakdown_ht["ht_amount"], Decimal("920000.00"))
        self.assertEqual(breakdown_ht["tax_amount"], Decimal("147200.00"))
        self.assertEqual(breakdown_ht["ttc_amount"], Decimal("1067200.00"))

    def test_compute_line_tax_breakdown_includes_vat_on_specific_tax(self):
        """Verifie que le calcul fiscal inclut la TVA appliquee a la taxe specifique."""

        breakdown_ttc = compute_line_tax_breakdown(
            subtotal=Decimal("100.00"),
            tax_rate=Decimal("16.00"),
            mode_dgi="ttc",
            tax_group_code="B",
            specific_tax_amount=Decimal("10.00"),
        )
        breakdown_ht = compute_line_tax_breakdown(
            subtotal=Decimal("100.00"),
            tax_rate=Decimal("16.00"),
            mode_dgi="ht",
            tax_group_code="B",
            specific_tax_amount=Decimal("10.00"),
        )

        self.assertEqual(breakdown_ttc["base_ht_amount"].quantize(Decimal("0.01")), Decimal("86.21"))
        self.assertEqual(breakdown_ttc["tax_amount"].quantize(Decimal("0.01")), Decimal("15.39"))
        self.assertEqual(breakdown_ttc["ttc_amount"].quantize(Decimal("0.01")), Decimal("111.60"))
        self.assertEqual(breakdown_ht["ht_amount"].quantize(Decimal("0.01")), Decimal("110.00"))
        self.assertEqual(breakdown_ht["tax_amount"].quantize(Decimal("0.01")), Decimal("17.60"))
        self.assertEqual(breakdown_ht["ttc_amount"].quantize(Decimal("0.01")), Decimal("127.60"))

    def test_build_mcf_item_type_candidates_prioritizes_tax_for_special_groups(self):
        """Verifie que les candidats de type d'article MCF priorisent la taxe pour les groupes speciaux."""

        self.assertEqual(build_mcf_item_type_candidates("SER", "N"), ["TAX", "SER"])
        self.assertEqual(build_mcf_item_type_candidates("SER", "L"), ["TAX", "SER"])

    def test_normalize_mcf_tax_rate_zeroes_special_group_rates(self):
        """Verifie que le taux envoye au MCF est neutralise pour les groupes speciaux."""

        self.assertEqual(normalize_mcf_tax_rate("N", Decimal("100.00")), Decimal("0.00"))
        self.assertEqual(normalize_mcf_tax_rate("L", Decimal("16.00")), Decimal("0.00"))
        self.assertEqual(normalize_mcf_tax_rate("B", Decimal("16.00")), Decimal("16.00"))


class StockIntegrityTests(TestCase):
    """Regroupe les tests de protection de l'integrite du stock."""


    def setUp(self):
        """Prepare les donnees communes necessaires a ce scenario de test."""

        self.point_de_vente = PointDeVente.objects.create(nom="PDV Stock")
        self.user = get_user_model().objects.create_user(
            username="vendeur_stock",
            email="vendeur_stock@test.com",
            password="secret",
            point_de_vente=self.point_de_vente,
        )
        self.product = Produit.objects.create(
            nom="Produit Stock",
            code_sku="STOCK-001",
            prix_vente=Decimal("1000.00"),
            actif=True,
        )

    def test_stock_save_allows_negative_quantity(self):
        """Verifie que la sauvegarde du stock conserve une quantite negative."""

        stock = StockPointDeVente.objects.create(
            point_de_vente=self.point_de_vente,
            produit=self.product,
            quantite=Decimal("-12.120"),
        )

        self.assertEqual(stock.quantite, Decimal("-12.120"))

    def test_sale_movement_can_make_stock_negative(self):
        """Verifie qu'un mouvement de vente peut rendre le stock negatif."""

        stock = StockPointDeVente.objects.create(
            point_de_vente=self.point_de_vente,
            produit=self.product,
            quantite=Decimal("1.000"),
        )

        MouvementStock.objects.create(
            stock=stock,
            type_mouvement="VENTE",
            quantite=Decimal("-2.000"),
            responsable=self.user,
            description="Test stock negatif",
        )

        stock.refresh_from_db()
        self.assertEqual(stock.quantite, Decimal("-1.000"))


class CommandeModificationTests(TestCase):
    """Regroupe les tests de modification des commandes existantes."""


    def setUp(self):
        """Prepare les donnees communes necessaires a ce scenario de test."""

        self.point_de_vente = PointDeVente.objects.create(nom="PDV Modification")
        self.user = get_user_model().objects.create_user(
            username="vendeur_modification",
            email="vendeur_modification@test.com",
            password="secret",
            point_de_vente=self.point_de_vente,
        )
        UserMenuPermission.objects.create(
            user=self.user,
            permission_key="ventes_factures_update",
            is_allowed=True,
        )
        self.client.force_login(self.user)

        self.tax_group_b, _ = TaxGroup.objects.update_or_create(
            code="B",
            defaults={"name": "GROUPE B (TAXABLE 16%)", "tax": Decimal("16.00")},
        )
        self.tax_group_c, _ = TaxGroup.objects.update_or_create(
            code="C",
            defaults={"name": "GROUPE C (TAXABLE 5%)", "tax": Decimal("5.00")},
        )
        self.item_type = ItemType.objects.create(code="BIE", name="Bien")

        self.product_a = Produit.objects.create(
            nom="Article A",
            code_sku="ART-A",
            prix_vente=Decimal("100.00"),
            taxgroup=self.tax_group_b,
            typeart=self.item_type,
            actif=True,
        )
        self.product_b = Produit.objects.create(
            nom="Article B",
            code_sku="ART-B",
            prix_vente=Decimal("200.00"),
            taxgroup=self.tax_group_c,
            typeart=self.item_type,
            actif=True,
        )
        self.product_c = Produit.objects.create(
            nom="Article C",
            code_sku="ART-C",
            prix_vente=Decimal("150.00"),
            taxgroup=self.tax_group_b,
            typeart=self.item_type,
            actif=True,
        )

        self.stock_a = StockPointDeVente.objects.create(
            point_de_vente=self.point_de_vente,
            produit=self.product_a,
            quantite=Decimal("10.000"),
        )
        self.stock_b = StockPointDeVente.objects.create(
            point_de_vente=self.point_de_vente,
            produit=self.product_b,
            quantite=Decimal("5.000"),
        )
        self.stock_c = StockPointDeVente.objects.create(
            point_de_vente=self.point_de_vente,
            produit=self.product_c,
            quantite=Decimal("1.000"),
        )

        self.customer = Client.objects.create(nom_complet="Client Modification")
        self.config = 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 Modification",
            port="COM12",
            company_nif="A1234567Q",
            company_isf="CD01004241-1",
            is_active=True,
            is_default=True,
        )

        self.commande = Commande.objects.create(
            point_de_vente=self.point_de_vente,
            vendeur=self.user,
            client=self.customer,
            montant_total=Decimal("400.00"),
            montant_paye=Decimal("0.00"),
            tva_montant=Decimal("37.11"),
            taux_change_applique=Decimal("1.00"),
            type_facture="FV",
        )
        self.line_a = LigneCommande.objects.create(
            commande=self.commande,
            produit=self.product_a,
            quantite=Decimal("2.000"),
            prix_unitaire=Decimal("100.00"),
            remise=Decimal("20.00"),
            sous_total=Decimal("180.00"),
        )
        self.line_b = LigneCommande.objects.create(
            commande=self.commande,
            produit=self.product_b,
            quantite=Decimal("1.000"),
            prix_unitaire=Decimal("200.00"),
            remise=Decimal("0.00"),
            sous_total=Decimal("200.00"),
        )

    def test_facture_displays_net_paid_and_balance_in_order_on_a4_and_ticket(self):
        """Le récapitulatif financier garde le même ordre sur les deux formats."""

        self.commande.montant_paye = Decimal("150.00")
        self.commande.save(update_fields=["montant_paye"])

        for query in ("", "?format=TICKET_80MM"):
            with self.subTest(format=query or "A4"):
                response = self.client.get(
                    f"{reverse('facturation:facture-detail', args=[self.commande.pk])}{query}"
                )
                html = response.content.decode("utf-8")

                self.assertEqual(response.status_code, 200)
                self.assertEqual(response.context["total_paiements"], Decimal("150.00"))
                self.assertContains(response, "Total payé")
                self.assertContains(response, "150,00 FC")
                self.assertContains(response, "250,00 FC")
                self.assertLess(html.index("NET"), html.index("Total payé"))
                self.assertLess(html.index("Total payé"), html.index("Reste à payer"))

    def test_modifier_commande_allows_adding_new_article_and_recalculates_totals(self):
        """Verifie que la modification d'une commande permet d'ajouter un article et recalcule les totaux."""

        response = self.client.post(
            reverse("facturation:commande-modifier", args=[self.commande.pk]),
            data={
                f"qty_{self.line_a.id}": "2",
                f"qty_{self.line_b.id}": "1",
                "new_product_id": str(self.product_c.pk),
                "new_qty": "1",
                "motif": "COR",
            },
        )

        self.assertEqual(response.status_code, 302)
        self.commande.refresh_from_db()
        self.assertEqual(self.commande.lignes.count(), 3)

        new_line = self.commande.lignes.get(produit=self.product_c)
        self.assertEqual(new_line.quantite, Decimal("1.000"))
        self.assertEqual(new_line.prix_unitaire, Decimal("150.00"))
        self.stock_c.refresh_from_db()
        self.assertEqual(self.stock_c.quantite, Decimal("0.000"))

        total_a = compute_line_tax_breakdown(Decimal("180.00"), Decimal("16.00"), "ttc", "B")
        total_b = compute_line_tax_breakdown(Decimal("200.00"), Decimal("5.00"), "ttc", "C")
        total_c = compute_line_tax_breakdown(Decimal("150.00"), Decimal("16.00"), "ttc", "B")

        expected_total = (
            total_a["ttc_amount"]
            + total_b["ttc_amount"]
            + total_c["ttc_amount"]
        ).quantize(Decimal("0.01"))
        expected_tva = (
            total_a["tax_amount"]
            + total_b["tax_amount"]
            + total_c["tax_amount"]
        ).quantize(Decimal("0.01"))

        self.assertEqual(self.commande.montant_total, expected_total)
        self.assertEqual(self.commande.tva_montant, expected_tva)

    def test_modifier_commande_updates_existing_lines_and_calls_partial_cancellation(self):
        """Verifie que la modification met a jour les lignes existantes et declenche l'annulation partielle attendue."""

        with patch(
            "facturation.views.FiscalCancellationService.cancel_commande",
            return_value={"success": True},
        ) as mock_cancel:
            response = self.client.post(
                reverse("facturation:commande-modifier", args=[self.commande.pk]),
                data={
                    f"qty_{self.line_a.id}": "1",
                    f"qty_{self.line_b.id}": "1",
                    f"delete_{self.line_b.id}": "on",
                    "new_product_id": "",
                    "new_qty": "",
                    "motif": "COR",
                },
            )

        self.assertEqual(response.status_code, 302)
        self.commande.refresh_from_db()
        self.assertEqual(self.commande.lignes.count(), 1)

        remaining_line = self.commande.lignes.get(produit=self.product_a)
        self.assertEqual(remaining_line.quantite, Decimal("1.000"))
        self.assertEqual(remaining_line.remise, Decimal("10.00"))
        self.assertEqual(remaining_line.sous_total, Decimal("90.00"))

        mock_cancel.assert_called_once()
        cancelled_lines = mock_cancel.call_args.kwargs["lignes_a_annuler"]
        self.assertEqual(len(cancelled_lines), 2)
        cancelled_map = {line["produit"].id: line for line in cancelled_lines}
        self.assertEqual(cancelled_map[self.product_a.id]["quantite"], Decimal("1.000"))
        self.assertEqual(cancelled_map[self.product_a.id]["remise"], Decimal("10.00"))
        self.assertEqual(cancelled_map[self.product_b.id]["quantite"], Decimal("1.000"))

        expected_breakdown = compute_line_tax_breakdown(Decimal("90.00"), Decimal("16.00"), "ttc", "B")
        self.assertEqual(self.commande.montant_total, expected_breakdown["ttc_amount"].quantize(Decimal("0.01")))
        self.assertEqual(self.commande.tva_montant, expected_breakdown["tax_amount"].quantize(Decimal("0.01")))

    def test_modifier_commande_redirects_to_new_credit_note_detail_without_duplicata(self):
        """Verifie qu'une modification ouvrant un avoir redirige d'abord vers l'original, sans duplicata."""

        created_credit_note = Commande.objects.create(
            point_de_vente=self.point_de_vente,
            vendeur=self.user,
            montant_total=Decimal("100.00"),
            montant_paye=Decimal("100.00"),
            tva_montant=Decimal("13.79"),
            taux_change_applique=Decimal("1.00"),
            type_facture="FA",
            facture_origine=self.commande,
        )

        with patch(
            "facturation.views.FiscalCancellationService.cancel_commande",
            return_value={"success": True, "fa_id": created_credit_note.pk},
        ):
            response = self.client.post(
                reverse("facturation:commande-modifier", args=[self.commande.pk]),
                data={
                    f"qty_{self.line_a.id}": "1",
                    f"qty_{self.line_b.id}": "1",
                    f"delete_{self.line_b.id}": "on",
                    "new_product_id": "",
                    "new_qty": "",
                    "motif": "COR",
                },
            )

        # Cette redirection protege le besoin metier principal :
        # l'avoir fraichement cree doit s'afficher comme original a sa
        # premiere ouverture, et non comme duplicata des sa creation.
        self.assertEqual(response.status_code, 302)
        self.assertEqual(
            response.url,
            reverse("facturation:facture-detail", args=[created_credit_note.pk]),
        )
        self.assertNotIn("duplicata=1", response.url)
        self.assertIn(
            str(created_credit_note.pk),
            self.client.session.get("fresh_credit_note_original_views", []),
        )

    def test_modifier_commande_records_negative_stock_for_new_article(self):
        """Une nouvelle ligne reste vendable et historisee au-dela du stock courant."""

        with patch("facturation.views.FiscalCancellationService.cancel_commande") as mock_cancel:
            response = self.client.post(
                reverse("facturation:commande-modifier", args=[self.commande.pk]),
                data={
                    f"qty_{self.line_a.id}": "2",
                    f"qty_{self.line_b.id}": "1",
                    "new_product_id": str(self.product_c.pk),
                    "new_qty": "3",
                    "motif": "COR",
                },
            )

        self.assertEqual(response.status_code, 302)
        mock_cancel.assert_not_called()
        self.commande.refresh_from_db()
        self.assertEqual(self.commande.lignes.count(), 3)
        self.stock_c.refresh_from_db()
        self.assertEqual(self.stock_c.quantite, Decimal("-2.000"))
        mouvement = MouvementStock.objects.get(
            commande_associee=self.commande,
            stock=self.stock_c,
        )
        self.assertEqual(mouvement.quantite, Decimal("-3.000"))
        self.assertEqual(mouvement.stock_avant, Decimal("1.000"))
        self.assertEqual(mouvement.stock_apres, Decimal("-2.000"))

    def test_modifier_commande_rejects_ran_quantity_greater_than_initial_quantity(self):
        """Verifie que la modification refuse une quantite RAN superieure a la quantite initiale."""

        with patch("facturation.views.FiscalCancellationService.cancel_commande") as mock_cancel:
            response = self.client.post(
                reverse("facturation:commande-modifier", args=[self.commande.pk]),
                data={
                    f"qty_{self.line_a.id}": "3",
                    f"qty_{self.line_b.id}": "1",
                    "new_product_id": "",
                    "new_qty": "",
                    "motif": "RAN",
                },
            )

        self.assertEqual(response.status_code, 200)
        self.assertContains(response, "ne peut pas etre superieure a la quantite initiale")
        self.assertContains(response, "Article A")
        mock_cancel.assert_not_called()
        self.commande.refresh_from_db()
        self.assertEqual(self.commande.lignes.get(produit=self.product_a).quantite, Decimal("2.000"))

    def test_modifier_commande_rejects_new_article_for_ran(self):
        """Verifie que la modification refuse l'ajout d'un nouvel article dans un RAN."""

        with patch("facturation.views.FiscalCancellationService.cancel_commande") as mock_cancel:
            response = self.client.post(
                reverse("facturation:commande-modifier", args=[self.commande.pk]),
                data={
                    f"qty_{self.line_a.id}": "2",
                    f"qty_{self.line_b.id}": "1",
                    "new_product_id": str(self.product_c.pk),
                    "new_qty": "1",
                    "motif": "RAN",
                },
            )

        self.assertEqual(response.status_code, 200)
        self.assertContains(response, "un avoir RAN ne peut pas ajouter un nouvel article")
        mock_cancel.assert_not_called()
        self.commande.refresh_from_db()
        self.assertFalse(self.commande.lignes.filter(produit=self.product_c).exists())

    def test_modifier_commande_allows_ram_quantity_greater_than_initial_quantity(self):
        """Verifie que RAM accepte aussi l'ajout de quantite."""

        with patch("facturation.views.FiscalCancellationService.cancel_commande") as mock_cancel:
            response = self.client.post(
                reverse("facturation:commande-modifier", args=[self.commande.pk]),
                data={
                    f"qty_{self.line_a.id}": "3",
                    f"qty_{self.line_b.id}": "1",
                    "new_product_id": "",
                    "new_qty": "",
                    "motif": "RAM",
                },
            )

        self.assertEqual(response.status_code, 302)
        mock_cancel.assert_not_called()
        self.commande.refresh_from_db()
        self.assertEqual(self.commande.lignes.get(produit=self.product_a).quantite, Decimal("3.000"))
        self.stock_a.refresh_from_db()
        self.assertEqual(self.stock_a.quantite, Decimal("9.000"))

    def test_modifier_commande_allows_new_article_for_ram(self):
        """Verifie que RAM accepte l'ajout d'un nouvel article."""

        with patch("facturation.views.FiscalCancellationService.cancel_commande") as mock_cancel:
            response = self.client.post(
                reverse("facturation:commande-modifier", args=[self.commande.pk]),
                data={
                    f"qty_{self.line_a.id}": "2",
                    f"qty_{self.line_b.id}": "1",
                    "new_product_id": str(self.product_c.pk),
                    "new_qty": "1",
                    "motif": "RAM",
                },
            )

        self.assertEqual(response.status_code, 302)
        mock_cancel.assert_not_called()
        self.commande.refresh_from_db()
        self.assertEqual(self.commande.lignes.get(produit=self.product_c).quantite, Decimal("1.000"))
        self.stock_c.refresh_from_db()
        self.assertEqual(self.stock_c.quantite, Decimal("0.000"))

    def _post_mcf_cor_with_added_item(self, credit_note_pk, qty_a="3"):
        """Modification COR d'une facture MCF avec ajout d'un article (fiscalisation simulee)."""

        def fake_fiscalize(commande, *args, **kwargs):
            commande.codedefdgi = f"SIG-FV-COR-MCF-{commande.pk}"
            commande.counters = "10/20 FV"
            commande.nim = "NIM-MCF"
            commande.qrCode = "RDCDEF01;NIM-MCF;SIG;A1234567Q;20260510195000"
            commande.fiscal_channel = "MCF"
            commande.save(update_fields=["codedefdgi", "counters", "nim", "qrCode", "fiscal_channel"])
            return {"success": True, "channel": "MCF", "commande_id": commande.pk}

        with patch(
            "facturation.views.FiscalCancellationService.cancel_commande",
            return_value={"success": True, "fa_id": credit_note_pk},
        ) as mock_cancel, patch(
            "facturation.views.FiscalOrchestrator.fiscalize_commande",
            side_effect=fake_fiscalize,
        ), patch(
            "facturation.views.MCFInvoiceService.send_invoice",
        ) as mock_send_invoice:
            response = self.client.post(
                reverse("facturation:commande-modifier", args=[self.commande.pk]),
                data={
                    f"qty_{self.line_a.id}": qty_a,
                    f"qty_{self.line_b.id}": "1",
                    "new_product_id": str(self.product_c.pk),
                    "new_qty": "1",
                    "motif": "COR",
                },
            )
        return response, mock_cancel, mock_send_invoice

    def test_modifier_commande_mcf_cor_with_added_item_reissues_without_touching_source(self):
        """
        COR MCF avec ajout : avoir du reliquat puis nouvelle facture corrigee.

        La facture normalisee d'origine n'est jamais modifiee et l'article
        ajoute n'apparait jamais dans un avoir (il serait rembourse au lieu
        d'etre facture).
        """

        self.commande.fiscal_channel = "MCF"
        self.commande.codedefdgi = "SIG-ORIG-315"
        self.commande.save(update_fields=["fiscal_channel", "codedefdgi"])
        original_lines = {line.produit_id: line.quantite for line in self.commande.lignes.all()}
        original_total = self.commande.montant_total
        created_credit_note = Commande.objects.create(
            point_de_vente=self.point_de_vente,
            vendeur=self.user,
            client=self.customer,
            montant_total=Decimal("250.00"),
            montant_paye=Decimal("250.00"),
            tva_montant=Decimal("34.48"),
            taux_change_applique=Decimal("1.00"),
            type_facture="FA",
            facture_origine=self.commande,
            nature_avoir="COR",
        )

        response, mock_cancel, mock_send_invoice = self._post_mcf_cor_with_added_item(created_credit_note.pk)

        self.assertEqual(response.status_code, 302)
        self.assertEqual(response.url, reverse("facturation:facture-detail", args=[created_credit_note.pk]))
        self.assertNotIn("duplicata=1", response.url)
        mock_cancel.assert_called_once_with(self.commande, "COR", self.user)
        mock_send_invoice.assert_not_called()
        self.commande.refresh_from_db()
        self.assertEqual({line.produit_id: line.quantite for line in self.commande.lignes.all()}, original_lines)
        self.assertEqual(self.commande.montant_total, original_total)
        corrected_invoice = Commande.objects.filter(type_facture="FV").exclude(pk=self.commande.pk).get()
        self.assertEqual(corrected_invoice.lignes.get(produit=self.product_a).quantite, Decimal("3.000"))
        self.assertEqual(corrected_invoice.lignes.get(produit=self.product_c).quantite, Decimal("1.000"))

    def test_modifier_commande_mcf_cor_reissue_keeps_added_item_price_in_ht_mode(self):
        """En HT, la nouvelle facture reprend le prix de l'article ajoute."""

        self.commande.fiscal_channel = "MCF"
        self.commande.codedefdgi = "SIG-ORIG-HT-315"
        self.commande.save(update_fields=["fiscal_channel", "codedefdgi"])
        self.config.mode_dgi = "ht"
        self.config.save(update_fields=["mode_dgi"])

        response, mock_cancel, _mock_send = self._post_mcf_cor_with_added_item(999999, qty_a="2")

        self.assertEqual(response.status_code, 302)
        mock_cancel.assert_called_once_with(self.commande, "COR", self.user)
        corrected_invoice = Commande.objects.filter(type_facture="FV").exclude(pk=self.commande.pk).get()
        added_line = corrected_invoice.lignes.get(produit=self.product_c)
        self.assertEqual(added_line.prix_unitaire, Decimal("150.00"))
        self.assertEqual(added_line.quantite, Decimal("1.000"))
        self.assertEqual(added_line.sous_total, Decimal("150.00"))

    def test_modifier_commande_emcf_cor_with_added_item_creates_credit_note_and_new_invoice(self):
        """Verifie qu'une COR e-MCF avec ajout normalise une FA puis une nouvelle FV."""

        self.config.fiscal_primary_channel = "EMCF"
        self.config.save(update_fields=["fiscal_primary_channel"])
        self.commande.fiscal_channel = "EMCF"
        self.commande.codedefdgi = "SIG-ORIG-EMCF-COR"
        self.commande.save(update_fields=["fiscal_channel", "codedefdgi"])
        created_credit_note = Commande.objects.create(
            point_de_vente=self.point_de_vente,
            vendeur=self.user,
            client=self.customer,
            montant_total=Decimal("150.00"),
            montant_paye=Decimal("150.00"),
            tva_montant=Decimal("20.69"),
            taux_change_applique=Decimal("1.00"),
            type_facture="FA",
            facture_origine=self.commande,
            nature_avoir="COR",
            reference_avoir=self.commande.codedefdgi,
            fiscal_channel="EMCF",
        )

        def fake_fiscalize(commande, *args, **kwargs):
            commande.uid = f"UID-FV-COR-{commande.pk}"
            commande.codedefdgi = f"SIG-FV-COR-{commande.pk}"
            commande.counters = "375/466 FV"
            commande.nim = "NIM-FV-COR"
            commande.qrCode = "RDCF01;NIM-FV-COR;SIG-FV-COR;A1234567Q;20260510195000"
            commande.fiscal_channel = "EMCF"
            commande.save(
                update_fields=[
                    "uid",
                    "codedefdgi",
                    "counters",
                    "nim",
                    "qrCode",
                    "fiscal_channel",
                ]
            )
            return {"success": True, "channel": "EMCF", "commande_id": commande.pk}

        with patch(
            "facturation.views.FiscalCancellationService.cancel_commande",
            return_value={"success": True, "fa_id": created_credit_note.pk},
        ) as mock_cancel, patch(
            "facturation.views.FiscalOrchestrator.fiscalize_commande",
            side_effect=fake_fiscalize,
        ) as mock_fiscalize:
            initial_fv_count = Commande.objects.filter(type_facture="FV").count()
            response = self.client.post(
                reverse("facturation:commande-modifier", args=[self.commande.pk]),
                data={
                    f"qty_{self.line_a.id}": "1",
                    f"qty_{self.line_b.id}": "1",
                    "new_product_id": str(self.product_c.pk),
                    "new_qty": "1",
                    "motif": "COR",
                },
            )

        corrected_invoice = Commande.objects.filter(type_facture="FV").exclude(pk=self.commande.pk).get()
        self.assertEqual(response.status_code, 302)
        self.assertEqual(
            response.url,
            reverse("facturation:facture-detail", args=[created_credit_note.pk]),
        )
        self.assertEqual(Commande.objects.filter(type_facture="FV").count(), initial_fv_count + 1)
        self.assertEqual(corrected_invoice.fiscal_channel, "EMCF")
        self.assertEqual(corrected_invoice.lignes.get(produit=self.product_a).quantite, Decimal("1.000"))
        self.assertEqual(corrected_invoice.lignes.get(produit=self.product_c).quantite, Decimal("1.000"))
        self.assertEqual(created_credit_note.type_facture, "FA")
        self.assertEqual(created_credit_note.nature_avoir, "COR")
        self.assertEqual(created_credit_note.reference_avoir, "SIG-ORIG-EMCF-COR")
        mock_cancel.assert_called_once_with(self.commande, "COR", self.user)
        mock_fiscalize.assert_called_once_with(corrected_invoice)

    def test_modifier_commande_emcf_cor_add_only_still_creates_normalized_invoice(self):
        """Verifie qu'une COR e-MCF avec ajout seul genere aussi une nouvelle FV."""

        self.config.fiscal_primary_channel = "EMCF"
        self.config.save(update_fields=["fiscal_primary_channel"])
        self.commande.fiscal_channel = "EMCF"
        self.commande.codedefdgi = "SIG-ORIG-EMCF-COR-ADD"
        self.commande.save(update_fields=["fiscal_channel", "codedefdgi"])
        created_credit_note = Commande.objects.create(
            point_de_vente=self.point_de_vente,
            vendeur=self.user,
            client=self.customer,
            montant_total=Decimal("380.00"),
            montant_paye=Decimal("380.00"),
            tva_montant=Decimal("37.11"),
            taux_change_applique=Decimal("1.00"),
            type_facture="FA",
            facture_origine=self.commande,
            nature_avoir="COR",
            reference_avoir=self.commande.codedefdgi,
            fiscal_channel="EMCF",
        )

        def fake_fiscalize(commande, *args, **kwargs):
            commande.uid = f"UID-FV-COR-ADD-{commande.pk}"
            commande.codedefdgi = f"SIG-FV-COR-ADD-{commande.pk}"
            commande.fiscal_channel = "EMCF"
            commande.save(update_fields=["uid", "codedefdgi", "fiscal_channel"])
            return {"success": True, "channel": "EMCF", "commande_id": commande.pk}

        with patch(
            "facturation.views.FiscalCancellationService.cancel_commande",
            return_value={"success": True, "fa_id": created_credit_note.pk},
        ) as mock_cancel, patch(
            "facturation.views.FiscalOrchestrator.fiscalize_commande",
            side_effect=fake_fiscalize,
        ) as mock_fiscalize:
            response = self.client.post(
                reverse("facturation:commande-modifier", args=[self.commande.pk]),
                data={
                    f"qty_{self.line_a.id}": "2",
                    f"qty_{self.line_b.id}": "1",
                    "new_product_id": str(self.product_c.pk),
                    "new_qty": "1",
                    "motif": "COR",
                },
            )

        corrected_invoice = Commande.objects.filter(type_facture="FV").exclude(pk=self.commande.pk).get()
        self.assertEqual(response.status_code, 302)
        self.assertEqual(response.url, reverse("facturation:facture-detail", args=[created_credit_note.pk]))
        self.assertEqual(corrected_invoice.lignes.count(), 3)
        self.assertEqual(corrected_invoice.lignes.get(produit=self.product_c).quantite, Decimal("1.000"))
        self.assertEqual(created_credit_note.type_facture, "FA")
        self.assertEqual(created_credit_note.nature_avoir, "COR")
        self.assertEqual(created_credit_note.reference_avoir, "SIG-ORIG-EMCF-COR-ADD")
        mock_cancel.assert_called_once_with(self.commande, "COR", self.user)
        mock_fiscalize.assert_called_once_with(corrected_invoice)

    def test_modifier_commande_emcf_cor_passes_decreased_lines_as_stock_restore_only(self):
        """Verifie qu'une COR e-MCF restaure uniquement les quantites diminuees."""

        self.config.fiscal_primary_channel = "EMCF"
        self.config.save(update_fields=["fiscal_primary_channel"])
        self.commande.fiscal_channel = "EMCF"
        self.commande.codedefdgi = "SIG-ORIG-EMCF-COR-REDUCE"
        self.commande.save(update_fields=["fiscal_channel", "codedefdgi"])

        with patch(
            "facturation.views.FiscalCancellationService.cancel_commande",
            return_value={"success": True},
        ) as mock_fiscalize:
            response = self.client.post(
                reverse("facturation:commande-modifier", args=[self.commande.pk]),
                data={
                    f"qty_{self.line_a.id}": "1",
                    f"qty_{self.line_b.id}": "1",
                    "new_product_id": "",
                    "new_qty": "",
                    "motif": "COR",
                },
            )

        self.assertEqual(response.status_code, 302)
        cancel_kwargs = mock_fiscalize.call_args.kwargs
        self.assertEqual(cancel_kwargs["prepared_cancel_lines"][0]["produit"], self.product_a)
        self.assertEqual(cancel_kwargs["prepared_cancel_lines"][0]["quantite"], Decimal("1.000"))
        self.assertEqual(cancel_kwargs["stock_restore_lines"][0]["produit"], self.product_a)
        self.assertEqual(cancel_kwargs["stock_restore_lines"][0]["quantite"], Decimal("1.000"))

    def test_modifier_commande_emcf_ram_with_added_item_creates_credit_note_and_new_invoice(self):
        """Verifie qu'une RAM e-MCF avec ajout normalise une FA puis une nouvelle FV."""

        self.config.fiscal_primary_channel = "EMCF"
        self.config.save(update_fields=["fiscal_primary_channel"])
        self.commande.fiscal_channel = "EMCF"
        self.commande.codedefdgi = "SIG-ORIG-EMCF-RAM"
        self.commande.save(update_fields=["fiscal_channel", "codedefdgi"])
        created_credit_note = Commande.objects.create(
            point_de_vente=self.point_de_vente,
            vendeur=self.user,
            client=self.customer,
            montant_total=Decimal("100.00"),
            montant_paye=Decimal("100.00"),
            tva_montant=Decimal("13.79"),
            taux_change_applique=Decimal("1.00"),
            type_facture="FA",
            facture_origine=self.commande,
            nature_avoir="RAM",
            reference_avoir=self.commande.codedefdgi,
            fiscal_channel="EMCF",
        )

        def fake_fiscalize(commande, *args, **kwargs):
            commande.uid = f"UID-FV-RAM-{commande.pk}"
            commande.codedefdgi = f"SIG-FV-RAM-{commande.pk}"
            commande.counters = "376/467 FV"
            commande.nim = "NIM-FV-RAM"
            commande.qrCode = "RDCF01;NIM-FV-RAM;SIG-FV-RAM;A1234567Q;20260510195100"
            commande.fiscal_channel = "EMCF"
            commande.save(
                update_fields=[
                    "uid",
                    "codedefdgi",
                    "counters",
                    "nim",
                    "qrCode",
                    "fiscal_channel",
                ]
            )
            return {"success": True, "channel": "EMCF", "commande_id": commande.pk}

        with patch(
            "facturation.views.FiscalCancellationService.cancel_commande",
            return_value={"success": True, "fa_id": created_credit_note.pk},
        ) as mock_cancel, patch(
            "facturation.views.FiscalOrchestrator.fiscalize_commande",
            side_effect=fake_fiscalize,
        ) as mock_fiscalize:
            initial_fv_count = Commande.objects.filter(type_facture="FV").count()
            response = self.client.post(
                reverse("facturation:commande-modifier", args=[self.commande.pk]),
                data={
                    f"qty_{self.line_a.id}": "1",
                    f"qty_{self.line_b.id}": "1",
                    "new_product_id": str(self.product_c.pk),
                    "new_qty": "1",
                    "motif": "RAM",
                },
            )

        corrected_invoice = Commande.objects.filter(type_facture="FV").exclude(pk=self.commande.pk).get()
        self.assertEqual(response.status_code, 302)
        self.assertEqual(Commande.objects.filter(type_facture="FV").count(), initial_fv_count + 1)
        self.assertEqual(response.url, reverse("facturation:facture-detail", args=[created_credit_note.pk]))
        self.assertEqual(corrected_invoice.lignes.get(produit=self.product_a).quantite, Decimal("1.000"))
        self.assertEqual(corrected_invoice.lignes.get(produit=self.product_c).quantite, Decimal("1.000"))
        self.assertEqual(created_credit_note.type_facture, "FA")
        self.assertEqual(created_credit_note.nature_avoir, "RAM")
        self.assertEqual(created_credit_note.reference_avoir, "SIG-ORIG-EMCF-RAM")
        mock_cancel.assert_called_once_with(self.commande, "RAM", self.user)
        mock_fiscalize.assert_called_once_with(corrected_invoice)

    def test_modifier_commande_adds_success_message_after_valid_update(self):
        """Verifie qu'une modification valide prepare le popup de succes via Django messages."""

        response = self.client.post(
            reverse("facturation:commande-modifier", args=[self.commande.pk]),
            data={
                f"qty_{self.line_a.id}": "2",
                f"qty_{self.line_b.id}": "1",
                "new_product_id": str(self.product_c.pk),
                "new_qty": "1",
                "motif": "COR",
            },
            follow=True,
        )

        self.assertEqual(response.status_code, 200)
        self.assertContains(response, "La facture a ete modifiee avec succes.")

    def test_modifier_commande_turns_invalid_original_reference_error_into_project_popup(self):
        """Verifie qu'une erreur MCF 38h sur la facture source est reformulee et affichee en popup."""

        raw_error = (
            "Echec de la normalisation 38h : E: Erreur du serveur: "
            "La reference de la facture originale n'est pas valide "
            "(la facture originale est introuvable)"
        )

        with patch(
            "facturation.views.FiscalCancellationService.cancel_commande",
            side_effect=MCFInvoiceServiceError(raw_error),
        ):
            response = self.client.post(
                reverse("facturation:commande-modifier", args=[self.commande.pk]),
                data={
                    f"qty_{self.line_a.id}": "1",
                    f"qty_{self.line_b.id}": "1",
                    f"delete_{self.line_b.id}": "on",
                    "new_product_id": "",
                    "new_qty": "",
                    "motif": "RAM",
                },
            )

        self.assertEqual(response.status_code, 200)
        self.assertContains(response, "showFacControlAlert")
        self.assertContains(response, "Modification impossible")
        self.assertContains(response, "Le MCF n")
        self.assertContains(response, "facture d&#x27;origine necessaire pour valider cette modification")
        self.assertContains(response, "puis reessayez")
        self.assertNotContains(response, raw_error)

    def test_modifier_commande_turns_mcf_clock_not_set_error_into_project_popup(self):
        """Verifie qu'une horloge MCF non reglee est reformulee dans le popup projet."""

        raw_error = "Commande C3 rejetee par le MCF : E:Horloge non reglee! (STA=E082C080C0D8)."

        with patch(
            "facturation.views.FiscalCancellationService.cancel_commande",
            side_effect=MCFInvoiceServiceError(raw_error),
        ):
            response = self.client.post(
                reverse("facturation:commande-modifier", args=[self.commande.pk]),
                data={
                    f"qty_{self.line_a.id}": "1",
                    f"qty_{self.line_b.id}": "1",
                    f"delete_{self.line_b.id}": "on",
                    "new_product_id": "",
                    "new_qty": "",
                    "motif": "COR",
                },
            )

        self.assertEqual(response.status_code, 200)
        self.assertContains(response, "showFacControlAlert")
        self.assertContains(response, "Modification impossible")
        self.assertContains(response, "horloge du")
        self.assertContains(response, "boitier n&#x27;est pas reglee")
        self.assertContains(response, "date et l&#x27;heure du MCF")
        self.assertNotContains(response, raw_error)

    def test_modifier_commande_turns_mcf_clock_chronology_error_into_project_popup(self):
        """Verifie qu'une incoherence d'horloge MCF sur 38h est reformulee proprement."""

        raw_error = (
            "Echec de la normalisation 38h : E: Demander l'etat du serveur avant "
            "normalisation. Erreur 162. L'horloge est reglee plus tot que le "
            "dernier enregistrement."
        )

        with patch(
            "facturation.views.FiscalCancellationService.cancel_commande",
            side_effect=MCFInvoiceServiceError(raw_error),
        ):
            response = self.client.post(
                reverse("facturation:commande-modifier", args=[self.commande.pk]),
                data={
                    f"qty_{self.line_a.id}": "1",
                    f"qty_{self.line_b.id}": "1",
                    f"delete_{self.line_b.id}": "on",
                    "new_product_id": "",
                    "new_qty": "",
                    "motif": "COR",
                },
            )

        self.assertEqual(response.status_code, 200)
        self.assertContains(response, "showFacControlAlert")
        self.assertContains(response, "Modification impossible")
        self.assertContains(response, "Impossible de finaliser la facture d&#x27;avoir")
        self.assertContains(response, "dernier enregistrement fiscal")
        self.assertContains(response, "heure superieure au dernier ticket fiscal")
        self.assertNotContains(response, raw_error)

    def test_facture_detail_exposes_mcf_correction_security_logs(self):
        """Verifie que le detail facture expose les journaux de securite de correction MCF."""

        self.commande.fiscal_channel = "MCF"
        self.commande.codedefdgi = "BMALXPL6JUZMF5HSTQJKOTPR"
        self.commande.nim = "ED02000306-1"
        self.commande.save(update_fields=["fiscal_channel", "codedefdgi", "nim"])
        device = MCFDevice.objects.create(
            name="MCF Detail",
            port="COM11",
            company_nif="A1234567Q",
            company_isf="CD01004241-1",
            is_active=True,
            is_default=False,
        )
        MCFInvoiceLog.objects.create(
            commande_id=self.commande.pk,
            device=device,
            success=True,
            request_data={
                "operation_type": "CORRECTION_ADD",
                "invoice": {
                    "fn": "FV-2026-00999",
                },
            },
            response_data={
                "security": {
                    "date_time": "27/03/2026 08:45:00",
                    "code_def_dgi": "YJQJOK4IS47DBYLOI4C7OMH6",
                    "counters": "FC999/TC999 FT999",
                    "nim": "NIM-999",
                    "qr_code": "RDCDEF01;NIM-999;YJQJOK4IS47DBYLOI4C7OMH6;A1234567Q;20260327084500",
                }
            },
        )

        response = self.client.get(reverse("facturation:facture-detail", args=[self.commande.pk]))

        self.assertEqual(response.status_code, 200)
        self.assertContains(response, "ELEMENTS DE SECURITE DES CORRECTIONS MCF")
        self.assertContains(response, "BMAL-XPL6-JUZM-F5HS-TQJK-OTPR")
        self.assertContains(response, "YJQJ-OK4I-S47D-BYLO-I4C7-OMH6")
        self.assertContains(response, "DEF NID")
        self.assertNotContains(response, "DEF NIM")
        self.assertContains(response, "FV-2026-00999")

    def test_facture_detail_adds_point_de_vente_under_company_identity(self):
        """Verifie que l'en-tete facture garde la societe et ajoute le PDV."""

        self.point_de_vente.nom = "SHAHILKIN SARL - 02-NGABA"
        self.point_de_vente.adresse = "41/4 Av Lukala, Q/Kemi Righini, C/Lemba KINSHASA"
        self.point_de_vente.save(update_fields=["nom", "adresse"])
        self.config.nom_entreprise = "CONFIG GENERALE SARL"
        self.config.adresse = "Adresse configuration centrale"
        self.config.save(update_fields=["nom_entreprise", "adresse"])

        response = self.client.get(reverse("facturation:facture-detail", args=[self.commande.pk]))

        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.context["document_point_de_vente"], self.point_de_vente)
        self.assertContains(response, self.config.nom_entreprise)
        self.assertContains(response, "point de vente :")
        self.assertContains(response, self.point_de_vente.nom)
        self.assertContains(response, self.point_de_vente.adresse)
        self.assertNotContains(response, self.config.adresse)

    def test_credit_note_cor_detail_hides_extra_mcf_correction_security_block(self):
        """Verifie qu'un avoir COR n'affiche qu'un seul bloc de securite fiscale."""

        avoir = Commande.objects.create(
            point_de_vente=self.point_de_vente,
            vendeur=self.user,
            client=self.customer,
            montant_total=Decimal("116.00"),
            montant_paye=Decimal("116.00"),
            tva_montant=Decimal("16.00"),
            taux_change_applique=Decimal("1.00"),
            type_facture="FA",
            facture_origine=self.commande,
            nature_avoir="COR",
            fiscal_channel="MCF",
            codedefdgi="SIG-FA-COR-DET",
            counters="FC555/TC555 FT555",
            nim="NIM-555",
            qrCode="RDCDEF01;NIM-555;SIG-FA-COR-DET;A1234567Q;20260327101500",
            dateTimedgi="27/03/2026 10:15:00",
        )
        LigneCommande.objects.create(
            commande=avoir,
            produit=self.product_a,
            quantite=Decimal("1.000"),
            prix_unitaire=Decimal("100.00"),
            remise=Decimal("0.00"),
            sous_total=Decimal("100.00"),
        )
        MCFInvoiceLog.objects.create(
            commande_id=avoir.pk,
            device=self.device,
            success=True,
            request_data={
                "operation_type": "CORRECTION_ADD",
                "invoice": {
                    "fn": "FA-2026-00555",
                },
            },
            response_data={
                "security": {
                    "date_time": "27/03/2026 10:15:00",
                    "code_def_dgi": "SIG-FA-COR-DET",
                    "counters": "FC555/TC555 FT555",
                    "nim": "NIM-555",
                    "qr_code": "RDCDEF01;NIM-555;SIG-FA-COR-DET;A1234567Q;20260327101500",
                }
            },
        )

        response = self.client.get(reverse("facturation:facture-detail", args=[avoir.pk]))

        self.assertEqual(response.status_code, 200)
        self.assertContains(response, "CORRECTION (COR)")
        self.assertContains(response, "ELEMENT SECURITE DE LA FACTURE NORMALISEE")
        self.assertContains(response, "SIG-FA-COR-DET")
        self.assertNotContains(response, "ELEMENTS DE SECURITE DES CORRECTIONS MCF")
        self.assertEqual(response.context["mcf_modification_security_logs"], [])

    def test_facture_avoir_detail_prefers_source_mode_dgi_for_labels_and_amounts(self):
        """Verifie que le detail/PDF d'un avoir reutilise le mode fiscal de la facture source."""

        self.commande.mode_dgi = "ht"
        self.commande.save(update_fields=["mode_dgi"])
        avoir = Commande.objects.create(
            point_de_vente=self.point_de_vente,
            vendeur=self.user,
            client=self.customer,
            montant_total=Decimal("116.00"),
            montant_paye=Decimal("116.00"),
            tva_montant=Decimal("16.00"),
            taux_change_applique=Decimal("1.00"),
            type_facture="FA",
            facture_origine=self.commande,
            # On simule ici un ancien avoir enregistre avec le fallback TTC.
            # Le detail doit quand meme retrouver le vrai mode via la
            # facture source pour corriger l'affichage du PDF.
            mode_dgi="ttc",
        )
        LigneCommande.objects.create(
            commande=avoir,
            produit=self.product_a,
            quantite=Decimal("1.000"),
            prix_unitaire=Decimal("100.00"),
            remise=Decimal("0.00"),
            sous_total=Decimal("100.00"),
        )

        response = self.client.get(reverse("facturation:facture-detail", args=[avoir.pk]))
        ligne = response.context["lignes_facture"][0]
        expected_breakdown = compute_line_tax_breakdown(
            subtotal=Decimal("100.00"),
            tax_rate=Decimal("16.00"),
            mode_dgi="ht",
            tax_group_code="B",
        )

        # L'avoir doit heriter visuellement du mode fiscal de la facture
        # source, meme s'il a ete sauvegarde autrefois avec un mode TTC
        # par defaut.
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.context["mode_dgi_display"], "HT")
        self.assertEqual(ligne.montant_affiche, expected_breakdown["ht_amount"])
        self.assertContains(response, "Prix unitaire (HT)")
        self.assertContains(response, "Montant (HT)")

    def test_facture_avoir_cor_ht_detail_calculates_vat_from_ht_base(self):
        """Verifie qu'une FA COR en HT calcule la TVA sur la base HT corrigee."""

        self.commande.mode_dgi = "ht"
        self.commande.codedefdgi = "SIG-ORIG-COR-HT"
        self.commande.save(update_fields=["mode_dgi", "codedefdgi"])
        produit = Produit.objects.create(
            nom="Latacer 80g",
            code_sku="LAT-80",
            prix_vente=Decimal("64400.00"),
            taxgroup=self.tax_group_b,
            typeart=self.item_type,
            actif=True,
        )
        avoir = Commande.objects.create(
            point_de_vente=self.point_de_vente,
            vendeur=self.user,
            client=self.customer,
            montant_total=Decimal("74704.00"),
            montant_paye=Decimal("74704.00"),
            tva_montant=Decimal("10304.00"),
            taux_change_applique=Decimal("1.00"),
            type_facture="FA",
            facture_origine=self.commande,
            nature_avoir="COR",
            reference_avoir=self.commande.codedefdgi,
            mode_dgi="ht",
        )
        LigneCommande.objects.create(
            commande=avoir,
            produit=produit,
            quantite=Decimal("1.000"),
            prix_unitaire=Decimal("64400.00"),
            remise=Decimal("0.00"),
            sous_total=Decimal("64400.00"),
        )

        response = self.client.get(reverse("facturation:facture-detail", args=[avoir.pk]))
        ligne = response.context["lignes_facture"][0]
        tax_detail = next(tax for tax in response.context["tax_details"] if tax["code"] == "B")

        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.context["mode_dgi_display"], "HT")
        self.assertEqual(ligne.montant_affiche, Decimal("64400.00"))
        self.assertEqual(tax_detail["ht"].quantize(Decimal("0.01")), Decimal("64400.00"))
        self.assertEqual(tax_detail["tva"].quantize(Decimal("0.01")), Decimal("10304.00"))
        self.assertContains(response, "Type :</strong> COR", html=False)
        self.assertContains(response, "Réf. :</strong> SIG-ORIG-COR-HT", html=False)
        self.assertContains(response, f"Facture source :</strong> {self.commande.numero}", html=False)
        self.assertContains(response, "Motif :</strong> Correction", html=False)
        self.assertContains(response, '<td class="quantity">-1,000</td>', html=False)
        self.assertContains(response, "-64 400,00 FC")
        self.assertContains(response, "-10 304,00 FC")
        self.assertContains(response, "-74 704,00")
        self.assertContains(response, '<span class="payment-badge">ESPECES</span>', html=False)

    def test_facture_detail_displays_special_groups_with_fiscal_labels(self):
        """Verifie que les groupes speciaux affichent HT et TVA avec leur libelle fiscal."""

        self.config.mode_dgi = "ht"
        self.config.save(update_fields=["mode_dgi"])
        commande = Commande.objects.create(
            point_de_vente=self.point_de_vente,
            vendeur=self.user,
            client=self.customer,
            montant_total=Decimal("900000.00"),
            montant_paye=Decimal("900000.00"),
            tva_montant=Decimal("0.00"),
            taux_change_applique=Decimal("1.00"),
            type_facture="FV",
            mode_dgi="ht",
        )

        for code, name, description, tax_rate, amount in (
            ("A", "Produit exonere", "GROUPE A (EXONERE ET HORS CHAMP)", Decimal("0.00"), Decimal("60000.00")),
            ("J", "Frais portuaires payes", "GROUPE J (DÉBOURS)", Decimal("0.00"), Decimal("161000.00")),
            (
                "K",
                "Vente occasionnelle",
                "GROUPE K (OPERATIONS REALISEES PAR LES NON ASSUJETTIS)",
                Decimal("0.00"),
                Decimal("460000.00"),
            ),
            ("L", "Autre groupe L", "GROUPE L (PRELEVEMENTS SUR VENTES)", Decimal("0.00"), Decimal("69000.00")),
            (
                "M",
                "Vente reglementee",
                "GROUPE M (VENTES RÉGLEMENTÉES AVEC TVA SPÉCIFIQUE)",
                Decimal("0.00"),
                Decimal("120000.00"),
            ),
            ("N", "TVA specifique", "GROUPE N (TVA SPECIFIQUE)", Decimal("16.00"), Decimal("90000.00")),
            (
                "P",
                "Marche public",
                "GROUPE P (TVA MARCHE PUBLIC À FINANCEMENT EXTERIEUR 1%)",
                Decimal("1.00"),
                Decimal("70000.00"),
            ),
        ):
            tax_group, _ = TaxGroup.objects.update_or_create(
                code=code,
                defaults={
                    "name": f"Groupe {code}",
                    "description": description,
                    "tax": tax_rate,
                },
            )
            produit = Produit.objects.create(
                nom=name,
                code_sku=f"PRD-{code}",
                prix_vente=amount,
                taxgroup=tax_group,
                typeart=self.item_type,
                actif=True,
            )
            LigneCommande.objects.create(
                commande=commande,
                produit=produit,
                quantite=Decimal("1.000"),
                prix_unitaire=amount,
                remise=Decimal("0.00"),
                sous_total=amount,
            )

        response = self.client.get(reverse("facturation:facture-detail", args=[commande.pk]))

        self.assertEqual(response.status_code, 200)
        for code, rate in (
            ("A", "0,00"),
            ("J", "0,00"),
            ("K", "0,00"),
            ("L", "0,00"),
            ("M", "0,00"),
            ("N", "16,00"),
            ("P", "1,00"),
        ):
            self.assertContains(response, f"H.T. [{code}] Taxable {rate}%")
            self.assertContains(response, f"TVA [{code}] Taxable {rate}%")
            self.assertNotContains(response, f"Total [{code}]")
        self.assertNotContains(response, "Régimes dérogatoires TVA")

    def test_facture_detail_marks_duplicata_only_when_query_parameter_is_present(self):
        """Verifie que le detail reste original par defaut et ne passe en duplicata que sur demande explicite."""

        original_response = self.client.get(
            reverse("facturation:facture-detail", args=[self.commande.pk])
        )
        duplicata_response = self.client.get(
            f"{reverse('facturation:facture-detail', args=[self.commande.pk])}?duplicata=1"
        )

        # Le filigrane duplicata ne doit jamais apparaitre par defaut.
        # Il n'est active que lorsqu'une URL l'exprime volontairement.
        self.assertFalse(original_response.context["is_duplicata"])
        self.assertTrue(duplicata_response.context["is_duplicata"])

    def test_credit_note_detail_opens_once_as_original_then_defaults_to_duplicata(self):
        """Verifie qu'un avoir cree s'affiche une fois en original puis repasse en duplicata."""

        avoir = Commande.objects.create(
            point_de_vente=self.point_de_vente,
            vendeur=self.user,
            montant_total=Decimal("100.00"),
            montant_paye=Decimal("100.00"),
            tva_montant=Decimal("13.79"),
            taux_change_applique=Decimal("1.00"),
            type_facture="FA",
            facture_origine=self.commande,
        )

        session = self.client.session
        session["fresh_credit_note_original_views"] = [str(avoir.pk)]
        session.save()

        first_response = self.client.get(reverse("facturation:facture-detail", args=[avoir.pk]))
        second_response = self.client.get(reverse("facturation:facture-detail", args=[avoir.pk]))

        self.assertFalse(first_response.context["is_duplicata"])
        self.assertTrue(second_response.context["is_duplicata"])


class MCFCancellationTests(TestCase):
    """Regroupe les tests d'annulation et d'avoir cote MCF."""


    def setUp(self):
        """Prepare les donnees communes necessaires a ce scenario de test."""

        self.point_de_vente = PointDeVente.objects.create(nom="PDV Annulation")
        self.user = get_user_model().objects.create_user(
            username="vendeur_annulation",
            email="vendeur_annulation@test.com",
            password="secret",
            point_de_vente=self.point_de_vente,
        )
        UserMenuPermission.objects.create(
            user=self.user,
            permission_key="ventes_factures_cancel",
            is_allowed=True,
        )
        self.tax_group, _ = TaxGroup.objects.update_or_create(
            code="B",
            defaults={"name": "GROUPE B (TAXABLE 16%)", "tax": Decimal("16.00")},
        )
        self.item_type = ItemType.objects.create(code="BIE", name="Bien")
        self.product = Produit.objects.create(
            nom="Latacer 80g",
            code_sku="LATACER-80G",
            prix_vente=Decimal("64400.00"),
            taxgroup=self.tax_group,
            typeart=self.item_type,
            actif=True,
        )
        StockPointDeVente.objects.create(
            point_de_vente=self.point_de_vente,
            produit=self.product,
            quantite=Decimal("0"),
        )
        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",
        )
        MCFDevice.objects.create(
            name="MCF Annulation",
            port="COM9",
            company_nif="A1234567Q",
            company_isf="CD01004241-1",
            is_active=True,
            is_default=True,
        )
        self.commande = Commande.objects.create(
            point_de_vente=self.point_de_vente,
            vendeur=self.user,
            montant_total=Decimal("64400.00"),
            montant_paye=Decimal("64400.00"),
            tva_montant=Decimal("8882.76"),
            taux_change_applique=Decimal("1.00"),
            type_facture="FV",
            fiscal_channel="MCF",
            codedefdgi="SIG-ORIG-306",
            counters="13/18 FV",
            nim="ED02000306-1",
            qrCode="RDCDEF01;ED02000306-1;SIG-ORIG-306;A1234567Q;20260326210849",
        )
        LigneCommande.objects.create(
            commande=self.commande,
            produit=self.product,
            quantite=Decimal("1.000"),
            prix_unitaire=Decimal("64400.00"),
            remise=Decimal("0.00"),
            sous_total=Decimal("64400.00"),
        )
        self.client.force_login(self.user)

    def test_invoice_list_uses_reversed_cancellation_url(self):
        """Verifie que le bouton d'annulation utilise l'URL racine du projet."""

        response = self.client.get(reverse("facturation:commande-list"))
        cancel_url = reverse(
            "facturation:commande-annuler",
            args=[self.commande.pk],
        )

        self.assertEqual(response.status_code, 200)
        self.assertEqual(cancel_url, f"/facture/{self.commande.pk}/annuler/")
        self.assertContains(
            response,
            f'data-cancel-url="{cancel_url}"',
            html=False,
        )
        self.assertContains(response, "fetch(cancelUrl, {", html=False)
        self.assertNotContains(
            response,
            "fetch(`/facture/${id}/annuler/`, {",
            html=False,
        )

    def test_service_cancels_mcf_invoice_with_credit_note_reference(self):
        """Verifie que l'annulation MCF reutilise la reference fiscale canonique de la facture source."""

        success_result = {
            "steps": {
                "close": {
                    "ok": True,
                    "data": "R:FC400,TC400,FT400,20260326211500,NIM400,A1234567Q,FA-2026-00001,SIG-FA-400",
                }
            }
        }

        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 = FiscalCancellationService().cancel_commande(
                self.commande,
                "Annulation test MCF",
                self.user,
            )

        self.commande.refresh_from_db()
        facture_avoir = Commande.objects.get(facture_origine=self.commande, type_facture="FA")
        stock = StockPointDeVente.objects.get(point_de_vente=self.point_de_vente, produit=self.product)
        invoice_payload = mock_commands_cls.return_value.send_invoice_flow.call_args.kwargs["invoice"]

        self.assertTrue(result["success"])
        self.assertTrue(self.commande.est_annulee)
        self.assertEqual(facture_avoir.fiscal_channel, "MCF")
        self.assertEqual(facture_avoir.codedefdgi, "SIG-FA-400")
        self.assertEqual(facture_avoir.type_facture, "FA")
        self.assertEqual(result["fa_id"], facture_avoir.pk)
        self.assertEqual(invoice_payload["invoice_type"], "FA")
        self.assertEqual(invoice_payload["reference_type"], "RAN")
        self.assertEqual(invoice_payload["rr"], "RAN")
        self.assertEqual(invoice_payload["rn"], self.commande.codedefdgi)
        self.assertEqual(stock.quantite, Decimal("1.000"))

    def test_service_does_not_create_credit_note_when_mcf_fails(self):
        """Verifie qu'aucun avoir local n'est cree si la fiscalisation MCF echoue."""

        with patch(
            "facturation.fiscal_cancellation.MCFInvoiceService.send_invoice",
            side_effect=MCFInvoiceServiceError("MCF indisponible"),
        ):
            with self.assertRaises(FiscalTechnicalError) as exc:
                FiscalCancellationService().cancel_commande(
                    self.commande,
                    "RAN",
                    self.user,
                )

        self.commande.refresh_from_db()
        self.assertEqual(str(exc.exception), "MCF indisponible")
        self.assertFalse(self.commande.est_annulee)
        self.assertFalse(
            Commande.objects.filter(facture_origine=self.commande, type_facture="FA").exists()
        )

    def test_service_retries_credit_note_db_create_once_after_lock_wait(self):
        """Verifie qu'une creation d'avoir MCF est relancee une fois apres un lock wait MySQL."""

        service = FiscalCancellationService()
        original_create = Commande.objects.create
        attempts = {"count": 0}

        def flaky_create(*args, **kwargs):
            if kwargs.get("type_facture") == "FA":
                attempts["count"] += 1
                if attempts["count"] == 1:
                    raise OperationalError(1205, "Lock wait timeout exceeded; try restarting transaction")
            return original_create(*args, **kwargs)

        with patch(
            "facturation.fiscal_cancellation.MCFInvoiceService.send_invoice",
            return_value={
                "success": True,
                "security": {
                    "date_time": "27/03/2026 09:12:00",
                    "code_def_dgi": "SIG-FA-LOCK-OK",
                    "counters": "FC440/TC440 FT440",
                    "nim": "NIM-440",
                    "qr_code": "RDCDEF01;NIM-440;SIG-FA-LOCK-OK;A1234567Q;20260327091200",
                },
            },
        ), patch(
            "facturation.fiscal_cancellation.Commande.objects.create",
            side_effect=flaky_create,
        ), patch("facturation.fiscal_cancellation.time.sleep") as mock_sleep:
            result = service.cancel_commande(
                self.commande,
                "RAN",
                self.user,
            )

        self.commande.refresh_from_db()
        facture_avoir = Commande.objects.get(facture_origine=self.commande, type_facture="FA")
        self.assertTrue(result["success"])
        self.assertTrue(self.commande.est_annulee)
        self.assertEqual(facture_avoir.codedefdgi, "SIG-FA-LOCK-OK")
        self.assertEqual(attempts["count"], 2)
        mock_sleep.assert_called_once()

    def test_service_returns_generic_message_when_credit_note_db_create_keeps_locking(self):
        """Verifie qu'un lock persistant cote DB remonte un message utilisateur stable."""

        service = FiscalCancellationService()
        db_error = OperationalError(1205, "Lock wait timeout exceeded; try restarting transaction")

        with patch(
            "facturation.fiscal_cancellation.MCFInvoiceService.send_invoice",
            return_value={
                "success": True,
                "security": {
                    "date_time": "27/03/2026 09:13:00",
                    "code_def_dgi": "SIG-FA-LOCK-KO",
                    "counters": "FC441/TC441 FT441",
                    "nim": "NIM-441",
                    "qr_code": "RDCDEF01;NIM-441;SIG-FA-LOCK-KO;A1234567Q;20260327091300",
                },
            },
        ), patch(
            "facturation.fiscal_cancellation.Commande.objects.create",
            side_effect=db_error,
        ), patch("facturation.fiscal_cancellation.time.sleep") as mock_sleep:
            with self.assertRaises(FiscalTechnicalError) as exc:
                service.cancel_commande(
                    self.commande,
                    "RAN",
                    self.user,
                )

        self.commande.refresh_from_db()
        self.assertEqual(str(exc.exception), service.DB_ERROR_MESSAGE)
        self.assertFalse(self.commande.est_annulee)
        self.assertFalse(
            Commande.objects.filter(facture_origine=self.commande, type_facture="FA").exists()
        )
        mock_sleep.assert_called_once()

    def test_cancel_view_mcf_stays_successful_when_snapshot_and_log_fail(self):
        """Verifie qu'une panne de snapshot/log MCF ne casse pas l'annulation cote vue."""

        success_result = {
            "steps": {
                "status": {
                    "ok": True,
                    "response": {
                        "raw": b"",
                        "status_hex": "C080C080C0D8",
                        "syn_count": 0,
                        "data_text": "",
                    },
                },
                "close": {
                    "ok": True,
                    "data": "R:FC401,TC401,FT401,20260326211600,NIM401,A1234567Q,FA-2026-00002,SIG-FA-401",
                },
            }
        }

        with patch("mcf.services_mcf.MCFClient"), patch(
            "mcf.services_mcf.MCFCommands"
        ) as mock_commands_cls, patch(
            "mcf.services_mcf.MCFInvoiceService._save_status_snapshot",
            side_effect=RuntimeError("snapshot indisponible"),
        ), patch(
            "mcf.services_mcf.MCFInvoiceService._create_log",
            side_effect=RuntimeError("log indisponible"),
        ):
            mock_commands_cls.return_value.send_invoice_flow.return_value = success_result

            response = self.client.post(
                reverse("facturation:commande-annuler", args=[self.commande.pk]),
                data=json.dumps({"motif": "Erreur client"}),
                content_type="application/json",
            )

        payload = response.json()
        self.commande.refresh_from_db()
        facture_avoir = Commande.objects.get(facture_origine=self.commande, type_facture="FA")

        self.assertEqual(response.status_code, 200)
        self.assertTrue(payload["success"])
        self.assertTrue(self.commande.est_annulee)
        self.assertEqual(payload["fa_id"], facture_avoir.pk)
        self.assertEqual(payload["redirect_url"], reverse("facturation:facture-detail", args=[facture_avoir.pk]))
        self.assertEqual(facture_avoir.codedefdgi, "SIG-FA-401")
        self.assertFalse(MCFInvoiceLog.objects.filter(commande_id=facture_avoir.pk).exists())

    def test_service_preserves_cor_and_ram_nature_for_mcf_credit_notes(self):
        """Verifie que le MCF conserve la nature COR/RAM d'une modification ayant cree un avoir."""

        cancel_line = {
            "produit": self.product,
            "quantite": Decimal("1.000"),
            "prix_unitaire": Decimal("64400.00"),
            "remise": Decimal("0.00"),
            "sous_total": Decimal("64400.00"),
        }

        for nature in ("COR", "RAM"):
            with self.subTest(nature=nature):
                self.commande.est_annulee = False
                self.commande.motif_annulation = ""
                self.commande.save(update_fields=["est_annulee", "motif_annulation"])
                Commande.objects.filter(facture_origine=self.commande, type_facture="FA").delete()

                with patch(
                    "facturation.fiscal_cancellation.MCFInvoiceService.send_invoice",
                    return_value={
                        "success": True,
                        "security": {
                            "date_time": "27/03/2026 09:20:00",
                            "code_def_dgi": f"SIG-FA-{nature}",
                            "counters": f"FC{nature}/TC{nature} FT{nature}",
                            "nim": f"NIM-{nature}",
                            "qr_code": f"RDCDEF01;NIM-{nature};SIG-FA-{nature};A1234567Q;20260327092000",
                        },
                    },
                ) as mock_send_invoice:
                    result = FiscalCancellationService().cancel_commande(
                        self.commande,
                        nature,
                        self.user,
                        lignes_a_annuler=[cancel_line],
                    )

                self.assertTrue(result["success"])
                facture_avoir = Commande.objects.get(facture_origine=self.commande, type_facture="FA")
                prepared_payload = mock_send_invoice.call_args.kwargs["prepared_payload"]
                self.assertEqual(facture_avoir.nature_avoir, nature)
                self.assertEqual(facture_avoir.reference_avoir, self.commande.codedefdgi)
                self.assertEqual(prepared_payload["credit_note"]["nature"], nature)
                self.assertEqual(prepared_payload["credit_note"]["reference"], self.commande.codedefdgi)

    def test_service_creates_mcf_credit_note_from_explicit_correction_lines_without_annulling_source(self):
        """Verifie qu'une correction MCF explicite cree une FA COR sans annuler la facture source."""

        correction_line = {
            "produit": self.product,
            "quantite": Decimal("1.000"),
            "prix_unitaire": Decimal("64400.00"),
            "remise": Decimal("0.00"),
            "sous_total": Decimal("64400.00"),
        }

        with patch(
            "facturation.fiscal_cancellation.MCFInvoiceService.send_invoice",
            return_value={
                "success": True,
                "security": {
                    "date_time": "27/03/2026 09:30:00",
                    "code_def_dgi": "SIG-FA-COR-EXPL",
                    "counters": "FC450/TC450 FT450",
                    "nim": "NIM-450",
                    "qr_code": "RDCDEF01;NIM-450;SIG-FA-COR-EXPL;A1234567Q;20260327093000",
                },
            },
        ), patch(
            "facturation.fiscal_cancellation.FiscalCancellationService._restore_stock_for_credit_note",
        ) as mock_restore_stock:
            result = FiscalCancellationService().cancel_commande(
                self.commande,
                "COR",
                self.user,
                prepared_cancel_lines=[correction_line],
                stock_restore_lines=[],
            )

        self.commande.refresh_from_db()
        facture_avoir = Commande.objects.get(facture_origine=self.commande, type_facture="FA")
        self.assertTrue(result["success"])
        self.assertFalse(self.commande.est_annulee)
        self.assertEqual(facture_avoir.nature_avoir, "COR")
        self.assertEqual(facture_avoir.codedefdgi, "SIG-FA-COR-EXPL")
        self.assertEqual(facture_avoir.reference_avoir, self.commande.codedefdgi)
        mock_restore_stock.assert_called_once()
        self.assertEqual(mock_restore_stock.call_args.kwargs["cancel_lines"], [])

    def test_service_preserves_source_mode_dgi_on_mcf_credit_note(self):
        """Verifie qu'un avoir MCF conserve le mode HT/TTC de la facture source."""

        self.commande.mode_dgi = "ht"
        self.commande.save(update_fields=["mode_dgi"])

        with patch(
            "facturation.fiscal_cancellation.MCFInvoiceService.send_invoice",
            return_value={
                "success": True,
                "security": {
                    "date_time": "27/03/2026 09:25:00",
                    "code_def_dgi": "SIG-FA-HT",
                    "counters": "FC430/TC430 FT430",
                    "nim": "NIM-430",
                    "qr_code": "RDCDEF01;NIM-430;SIG-FA-HT;A1234567Q;20260327092500",
                },
            },
        ):
            result = FiscalCancellationService().cancel_commande(
                self.commande,
                "Annulation HT",
                self.user,
            )

        facture_avoir = Commande.objects.get(facture_origine=self.commande, type_facture="FA")

        # Le mode fiscal est persiste sur l'avoir afin que son detail/PDF
        # affiche plus tard les bons libelles et montants HT/TTC.
        self.assertTrue(result["success"])
        self.assertEqual(facture_avoir.mode_dgi, "ht")

    def test_service_allows_multiple_partial_credit_notes_for_same_sale(self):
        """Verifie que le service autorise plusieurs avoirs partiels pour une meme vente."""

        ligne = self.commande.lignes.get()
        ligne.quantite = Decimal("3.000")
        ligne.sous_total = Decimal("193200.00")
        ligne.save()
        self.commande.montant_total = Decimal("193200.00")
        self.commande.montant_paye = Decimal("193200.00")
        self.commande.tva_montant = Decimal("26648.28")
        self.commande.save(update_fields=["montant_total", "montant_paye", "tva_montant"])

        success_results = [
            {
                "steps": {
                    "close": {
                        "ok": True,
                        "data": "R:FC410,TC410,FT410,20260326211700,NIM410,A1234567Q,FA-2026-00003,SIG-FA-410",
                    }
                }
            },
            {
                "steps": {
                    "close": {
                        "ok": True,
                        "data": "R:FC411,TC411,FT411,20260326211800,NIM411,A1234567Q,FA-2026-00004,SIG-FA-411",
                    }
                }
            },
        ]

        cancel_line = {
            "produit": self.product,
            "quantite": Decimal("1.000"),
            "prix_unitaire": Decimal("64400.00"),
            "remise": Decimal("0.00"),
            "sous_total": Decimal("64400.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 = success_results

            first = FiscalCancellationService().cancel_commande(
                self.commande,
                "Retour partiel 1",
                self.user,
                lignes_a_annuler=[cancel_line],
            )
            second = FiscalCancellationService().cancel_commande(
                self.commande,
                "Retour partiel 2",
                self.user,
                lignes_a_annuler=[cancel_line],
            )

        self.commande.refresh_from_db()
        self.assertTrue(first["success"])
        self.assertTrue(second["success"])
        self.assertFalse(self.commande.est_annulee)
        self.assertEqual(
            Commande.objects.filter(facture_origine=self.commande, type_facture="FA").count(),
            2,
        )

    def test_service_full_cancel_uses_only_remaining_lines_after_prior_credit_note(self):
        """Verifie qu'une annulation totale ne reprend que les lignes restantes apres un avoir precedent."""

        ligne = self.commande.lignes.get()
        ligne.quantite = Decimal("3.000")
        ligne.sous_total = Decimal("193200.00")
        ligne.save()
        self.commande.montant_total = Decimal("193200.00")
        self.commande.montant_paye = Decimal("193200.00")
        self.commande.tva_montant = Decimal("26648.28")
        self.commande.save(update_fields=["montant_total", "montant_paye", "tva_montant"])

        prior_credit = Commande.objects.create(
            point_de_vente=self.point_de_vente,
            vendeur=self.user,
            montant_total=Decimal("64400.00"),
            montant_paye=Decimal("64400.00"),
            tva_montant=Decimal("8882.76"),
            taux_change_applique=Decimal("1.00"),
            type_facture="FA",
            facture_origine=self.commande,
            fiscal_channel="MCF",
            codedefdgi="SIG-FA-PRIOR",
        )
        LigneCommande.objects.create(
            commande=prior_credit,
            produit=self.product,
            quantite=Decimal("1.000"),
            prix_unitaire=Decimal("64400.00"),
            remise=Decimal("0.00"),
            sous_total=Decimal("64400.00"),
        )

        with patch(
            "facturation.fiscal_cancellation.MCFInvoiceService.send_invoice",
            return_value={
                "success": True,
                "security": {
                    "date_time": "27/03/2026 09:10:00",
                    "code_def_dgi": "SIG-FA-RESTE",
                    "counters": "FC420/TC420 FT420",
                    "nim": "NIM420",
                    "qr_code": "RDCDEF01;NIM420;SIG-FA-RESTE;A1234567Q;20260327091000",
                },
            },
        ):
            result = FiscalCancellationService().cancel_commande(
                self.commande,
                "Annulation du reliquat",
                self.user,
            )

        self.assertTrue(result["success"])
        self.commande.refresh_from_db()
        self.assertTrue(self.commande.est_annulee)
        latest_credit = Commande.objects.filter(
            facture_origine=self.commande,
            type_facture="FA",
        ).exclude(pk=prior_credit.pk).latest("pk")
        self.assertEqual(latest_credit.lignes.count(), 1)
        remaining_line = latest_credit.lignes.get()
        self.assertEqual(remaining_line.quantite, Decimal("2.000"))
        self.assertEqual(remaining_line.sous_total, Decimal("128800.00"))
        self.assertEqual(latest_credit.montant_total, Decimal("128800.00"))

    def test_service_rejects_partial_cancel_beyond_remaining_quantities(self):
        """Verifie que le service refuse une annulation partielle au-dela des quantites restantes."""

        ligne = self.commande.lignes.get()
        ligne.quantite = Decimal("2.000")
        ligne.sous_total = Decimal("128800.00")
        ligne.save()
        self.commande.montant_total = Decimal("128800.00")
        self.commande.montant_paye = Decimal("128800.00")
        self.commande.tva_montant = Decimal("17765.52")
        self.commande.save(update_fields=["montant_total", "montant_paye", "tva_montant"])

        prior_credit = Commande.objects.create(
            point_de_vente=self.point_de_vente,
            vendeur=self.user,
            montant_total=Decimal("64400.00"),
            montant_paye=Decimal("64400.00"),
            tva_montant=Decimal("8882.76"),
            taux_change_applique=Decimal("1.00"),
            type_facture="FA",
            facture_origine=self.commande,
            fiscal_channel="MCF",
            codedefdgi="SIG-FA-PART",
        )
        LigneCommande.objects.create(
            commande=prior_credit,
            produit=self.product,
            quantite=Decimal("1.000"),
            prix_unitaire=Decimal("64400.00"),
            remise=Decimal("0.00"),
            sous_total=Decimal("64400.00"),
        )

        with self.assertRaises(FiscalBusinessError):
            FiscalCancellationService().cancel_commande(
                self.commande,
                "Tentative d'annulation excessive",
                self.user,
                lignes_a_annuler=[
                    {
                        "produit": self.product,
                        "quantite": Decimal("2.000"),
                        "prix_unitaire": Decimal("64400.00"),
                        "remise": Decimal("0.00"),
                        "sous_total": Decimal("128800.00"),
                    }
                ],
            )

    def test_cancel_view_routes_mcf_invoice_to_fiscal_cancellation_service(self):
        """Verifie que la vue d'annulation route bien une facture MCF vers le service fiscal dedie."""

        with patch(
            "facturation.views.FiscalCancellationService.cancel_commande",
            return_value={"success": True, "channel": "MCF"},
        ) as mock_cancel:
            response = self.client.post(
                reverse("facturation:commande-annuler", args=[self.commande.pk]),
                data=json.dumps({"motif": "Erreur client"}),
                content_type="application/json",
            )

        self.assertEqual(response.status_code, 200)
        mock_cancel.assert_called_once()

    def test_cancel_view_returns_credit_note_redirect_url_without_duplicata(self):
        """Verifie que la vue d'annulation fournit une redirection vers l'avoir original nouvellement cree."""

        created_credit_note = Commande.objects.create(
            point_de_vente=self.point_de_vente,
            vendeur=self.user,
            montant_total=Decimal("64400.00"),
            montant_paye=Decimal("64400.00"),
            tva_montant=Decimal("8882.76"),
            taux_change_applique=Decimal("1.00"),
            type_facture="FA",
            facture_origine=self.commande,
        )

        with patch(
            "facturation.views.FiscalCancellationService.cancel_commande",
            return_value={"success": True, "channel": "MCF", "fa_id": created_credit_note.pk},
        ):
            response = self.client.post(
                reverse("facturation:commande-annuler", args=[self.commande.pk]),
                data=json.dumps({"motif": "Erreur client"}),
                content_type="application/json",
            )

        payload = response.json()

        # La vue AJAX expose explicitement l'URL "originale" pour que le
        # front puisse ouvrir la facture d'avoir sans le mode duplicata lors
        # de la premiere consultation juste apres creation.
        self.assertEqual(response.status_code, 200)
        self.assertEqual(
            payload["redirect_url"],
            reverse("facturation:facture-detail", args=[created_credit_note.pk]),
        )
        self.assertNotIn("duplicata=1", payload["redirect_url"])


class DGICancellationTests(TestCase):
    """Regroupe les tests d'annulation et d'avoir cote DGI/e-MCF."""


    def setUp(self):
        """Prepare les donnees communes necessaires a ce scenario de test."""

        self.point_de_vente = PointDeVente.objects.create(nom="PDV DGI")
        self.user = get_user_model().objects.create_user(
            username="vendeur_dgi_annulation",
            email="vendeur_dgi_annulation@test.com",
            password="secret",
            point_de_vente=self.point_de_vente,
        )
        UserMenuPermission.objects.create(
            user=self.user,
            permission_key="ventes_factures_cancel",
            is_allowed=True,
        )
        self.tax_group, _ = TaxGroup.objects.update_or_create(
            code="B",
            defaults={"name": "GROUPE B (TAXABLE 16%)", "tax": Decimal("16.00")},
        )
        self.item_type = ItemType.objects.create(code="BIE", name="Bien")
        self.product = Produit.objects.create(
            nom="Produit DGI",
            code_sku="PROD-DGI-001",
            prix_vente=Decimal("100.00"),
            taxgroup=self.tax_group,
            typeart=self.item_type,
            actif=True,
        )
        Configuration.objects.create(
            taux_change=Decimal("1.00"),
            fiscal_primary_channel="EMCF",
            fiscal_fallback_mode="DISABLED",
            require_security_before_save=True,
            nif="A1234567Q",
            isf_dgi="CD01004241-1",
            mode_dgi="ht",
            type_dgi="FV",
        )
        self.commande = Commande.objects.create(
            point_de_vente=self.point_de_vente,
            vendeur=self.user,
            montant_total=Decimal("116.00"),
            montant_paye=Decimal("116.00"),
            tva_montant=Decimal("16.00"),
            taux_change_applique=Decimal("1.00"),
            type_facture="FV",
            mode_dgi="ht",
            codedefdgi="SIG-DGI-001",
        )
        LigneCommande.objects.create(
            commande=self.commande,
            produit=self.product,
            quantite=Decimal("1.000"),
            prix_unitaire=Decimal("100.00"),
            remise=Decimal("0.00"),
            sous_total=Decimal("100.00"),
        )

    def test_cancel_commande_dgi_preserves_source_mode_dgi_on_credit_note(self):
        """Verifie qu'un avoir DGI conserve le mode HT/TTC de la facture source."""

        with patch("dgi.emcf_adapter.EdefClient") as mock_client_cls, patch("dgi.emcf_adapter.time.sleep"):
            mock_client = mock_client_cls.return_value
            mock_client.info_status.return_value = {"status": True, "nif": "A1234567Q"}
            mock_client.create_invoice.return_value = {
                "uid": "UID-FA-DGI-001",
                "total": 116,
                "vtotal": 16,
            }
            mock_client.confirm_invoice.return_value = {
                "dateTime": "27/03/2026 10:00:00",
                "codeDEFDGI": "SIG-FA-DGI-001",
                "counters": "FC500/TC500 FT500",
                "nim": "NIM-DGI-500",
                "qrCode": "RDCDEF01;NIM-DGI-500;SIG-FA-DGI-001;A1234567Q;20260327100000",
            }

            result = DGIService.cancel_commande_dgi(
                self.commande,
                "RAN",
                self.user,
            )

        facture_avoir = Commande.objects.get(facture_origine=self.commande, type_facture="FA")

        # Le mode fiscal est memorise sur l'avoir DGI lui-meme afin que son
        # detail/PDF puisse afficher plus tard les bons libelles HT/TTC,
        # independamment des evolutions de configuration.
        self.assertTrue(result["success"])
        self.assertEqual(facture_avoir.mode_dgi, "ht")
        self.assertEqual(facture_avoir.nature_avoir, "RAN")
        self.assertEqual(facture_avoir.reference_avoir, self.commande.codedefdgi)
        self.assertEqual(facture_avoir.fiscal_channel, "EMCF")
        request_payload = mock_client.create_invoice.call_args.args[0]
        self.assertTrue(facture_avoir.numero.startswith("FA-"))
        self.assertIn(facture_avoir.numero, request_payload["rn"])
        self.assertEqual(request_payload["reference"], self.commande.codedefdgi)
        self.assertEqual(request_payload["referenceType"], "RAN")
        self.assertEqual(request_payload["referenceDesc"], "Annulation")

    def test_cancel_commande_dgi_creates_explicit_cor_credit_note_without_annulling_source(self):
        """Verifie qu'une correction COR DGI cree une FA propre sans nouvelle FV."""

        correction_line = {
            "produit": self.product,
            "quantite": Decimal("1.000"),
            "prix_unitaire": Decimal("100.00"),
            "remise": Decimal("0.00"),
            "sous_total": Decimal("100.00"),
        }

        with patch("dgi.emcf_adapter.EdefClient") as mock_client_cls, patch("dgi.emcf_adapter.time.sleep"):
            mock_client = mock_client_cls.return_value
            mock_client.info_status.return_value = {"status": True, "nif": "A1234567Q"}
            mock_client.create_invoice.return_value = {
                "uid": "UID-FA-DGI-COR",
                "total": 116,
                "vtotal": 16,
            }
            mock_client.confirm_invoice.return_value = {
                "dateTime": "27/03/2026 10:10:00",
                "codeDEFDGI": "SIG-FA-DGI-COR",
                "counters": "FC501/TC501 FA",
                "nim": "NIM-DGI-501",
                "qrCode": "RDCDEF01;NIM-DGI-501;SIG-FA-DGI-COR;A1234567Q;20260327101000",
            }

            result = DGIService.cancel_commande_dgi(
                self.commande,
                "COR",
                self.user,
                prepared_cancel_lines=[correction_line],
                stock_restore_lines=[],
            )

        self.commande.refresh_from_db()
        facture_avoir = Commande.objects.get(facture_origine=self.commande, type_facture="FA")
        request_payload = mock_client.create_invoice.call_args.args[0]

        self.assertTrue(result["success"])
        self.assertFalse(self.commande.est_annulee)
        self.assertEqual(Commande.objects.filter(type_facture="FV").count(), 1)
        self.assertTrue(facture_avoir.numero.startswith("FA-"))
        self.assertIn(facture_avoir.numero, request_payload["rn"])
        self.assertEqual(facture_avoir.nature_avoir, "COR")
        self.assertEqual(facture_avoir.reference_avoir, self.commande.codedefdgi)
        self.assertEqual(facture_avoir.fiscal_channel, "EMCF")
        self.assertEqual(facture_avoir.codedefdgi, "SIG-FA-DGI-COR")
        self.assertEqual(request_payload["type"], "FA")
        self.assertEqual(request_payload["reference"], self.commande.codedefdgi)
        self.assertEqual(request_payload["referenceType"], "COR")
        self.assertEqual(request_payload["referenceDesc"], "Correction")
        self.assertEqual(request_payload["items"][0]["quantity"], 1.0)
        self.assertFalse(MouvementStock.objects.filter(commande_associee=facture_avoir).exists())

    def test_cancel_commande_dgi_prefers_compact_original_reference_when_available(self):
        """Verifie qu'une reference DEF/DGI avec tirets est envoyee au format canonique."""

        self.commande.codedefdgi = "TEST-FACT-URES-GADG-NIYS-7NLX"
        self.commande.save(update_fields=["codedefdgi"])
        correction_line = {
            "produit": self.product,
            "quantite": Decimal("1.000"),
            "prix_unitaire": Decimal("100.00"),
            "remise": Decimal("0.00"),
            "sous_total": Decimal("100.00"),
        }

        with patch("dgi.emcf_adapter.EdefClient") as mock_client_cls, patch("dgi.emcf_adapter.time.sleep"):
            mock_client = mock_client_cls.return_value
            mock_client.info_status.return_value = {"status": True, "nif": "A1234567Q"}
            mock_client.create_invoice.return_value = {
                "uid": "UID-FA-DGI-COR",
                "total": 116,
                "vtotal": 16,
            }
            mock_client.confirm_invoice.return_value = {
                "dateTime": "27/03/2026 10:10:00",
                "codeDEFDGI": "SIG-FA-DGI-COR",
                "counters": "FC501/TC501 FA",
                "nim": "NIM-DGI-501",
                "qrCode": "RDCDEF01;NIM-DGI-501;SIG-FA-DGI-COR;A1234567Q;20260327101000",
            }

            DGIService.cancel_commande_dgi(
                self.commande,
                "COR",
                self.user,
                prepared_cancel_lines=[correction_line],
                stock_restore_lines=[],
            )

        request_payload = mock_client.create_invoice.call_args.args[0]
        self.assertEqual(request_payload["reference"], "TESTFACTURESGADGNIYS7NLX")

    def test_cancel_commande_dgi_retries_hyphenated_reference_after_compact_refusal(self):
        """Verifie qu'un refus de reference relance avec la valeur brute conservee."""

        self.commande.codedefdgi = "TEST-FACT-URES-GADG-NIYS-7NLX"
        self.commande.save(update_fields=["codedefdgi"])
        correction_line = {
            "produit": self.product,
            "quantite": Decimal("1.000"),
            "prix_unitaire": Decimal("100.00"),
            "remise": Decimal("0.00"),
            "sous_total": Decimal("100.00"),
        }

        with patch("dgi.emcf_adapter.EdefClient") as mock_client_cls, patch("dgi.emcf_adapter.time.sleep"):
            mock_client = mock_client_cls.return_value
            mock_client.info_status.return_value = {"status": True, "nif": "A1234567Q"}
            mock_client.create_invoice.side_effect = [
                {
                    "errorCode": "11",
                    "errorDesc": (
                        "La reference de la facture originale n'est pas valide "
                        "(la facture originale est introuvable)"
                    ),
                },
                {
                    "uid": "UID-FA-DGI-COR",
                    "total": 116,
                    "vtotal": 16,
                },
            ]
            mock_client.confirm_invoice.return_value = {
                "dateTime": "27/03/2026 10:10:00",
                "codeDEFDGI": "SIG-FA-DGI-COR",
                "counters": "FC501/TC501 FA",
                "nim": "NIM-DGI-501",
                "qrCode": "RDCDEF01;NIM-DGI-501;SIG-FA-DGI-COR;A1234567Q;20260327101000",
            }

            result = DGIService.cancel_commande_dgi(
                self.commande,
                "COR",
                self.user,
                prepared_cancel_lines=[correction_line],
                stock_restore_lines=[],
            )

        first_payload = mock_client.create_invoice.call_args_list[0].args[0]
        second_payload = mock_client.create_invoice.call_args_list[1].args[0]
        self.assertTrue(result["success"])
        self.assertEqual(first_payload["reference"], "TESTFACTURESGADGNIYS7NLX")
        self.assertEqual(second_payload["reference"], "TEST-FACT-URES-GADG-NIYS-7NLX")

    def test_fiscal_cancellation_wraps_dgi_refusal_for_modifier_view(self):
        """Verifie qu'un refus DGI remonte comme erreur affichable, pas comme 500."""

        with patch(
            "facturation.fiscal_cancellation.FiscalCancellationService._cancel_commande_fiscal",
            side_effect=ValueError("Refus DGI: Facture d'avoir incoherente"),
        ):
            with self.assertRaises(FiscalTechnicalError) as exc:
                FiscalCancellationService().cancel_commande(
                    self.commande,
                    "COR",
                    self.user,
                    prepared_cancel_lines=[
                        {
                            "produit": self.product,
                            "quantite": Decimal("1.000"),
                            "prix_unitaire": Decimal("100.00"),
                            "remise": Decimal("0.00"),
                            "sous_total": Decimal("100.00"),
                        }
                    ],
                    stock_restore_lines=[],
                )

        self.assertIn("Refus DGI", str(exc.exception))
