﻿"""Tests automatises de l'application proforma."""

import json
from datetime import timedelta
from decimal import Decimal
from io import BytesIO
from unittest.mock import patch

from django.contrib.auth import get_user_model
from django.test import TestCase
from django.urls import reverse
from django.utils import timezone

from dgi.models import ItemType, TaxGroup
from facturation.models import (
    Client,
    Commande,
    ConditionnementProduit,
    Configuration,
    ModePaiement,
    PendingSale,
    PointDeVente,
    Produit,
    StockPointDeVente,
)

from .models import Proforma, ProformaItem

# Role du fichier :
# - verifier que la creation de proforma ne declenche pas la fiscalisation ;
# - controler les calculs et l'affichage des documents commerciaux non fiscalises ;
# - verifier la facturation d'une proforma depuis le POS (bouton "Facturer").


class ProformaTestDataMixin:
    """Donnees communes : PDV, vendeur, configuration, client et produit en stock."""

    def setUp(self):
        """Prepare les donnees communes necessaires a ce scenario de test."""

        self.point_de_vente = PointDeVente.objects.create(nom="PDV Central")
        self.user = get_user_model().objects.create_user(
            username="vendeur-proforma",
            email="vendeur-proforma@test.com",
            password="secret123",
            role="VENDEUR",
            point_de_vente=self.point_de_vente,
        )
        self.tax_group, _ = TaxGroup.objects.update_or_create(
            code="A",
            defaults={
                "name": "GROUPE A (EXONERE ET HORS CHAMP)",
                "tax": Decimal("16.00"),
            },
        )
        self.item_type = ItemType.objects.create(code="BIE", name="Bien")
        self.config = Configuration.objects.create(
            taux_change=Decimal("2800.00"),
            mode_dgi="ttc",
            type_dgi="FV",
            nom_entreprise="CRIS SARL",
        )
        self.client_facture = Client.objects.create(
            nom_complet="Client Test",
            telephone="+2430000000",
            adresse="Kinshasa",
            nif="A1234567B",
        )
        self.produit = Produit.objects.create(
            nom="Produit Test",
            code_sku="SKU-PF-001",
            prix_vente=Decimal("10.00"),
            taxgroup=self.tax_group,
            typeart=self.item_type,
            actif=True,
        )
        self.stock = StockPointDeVente.objects.create(
            point_de_vente=self.point_de_vente,
            produit=self.produit,
            quantite=Decimal("5.000"),
        )
        ModePaiement.objects.get_or_create(code="ESPECES", defaults={"designation": "Especes"})
        self.client.force_login(self.user)


class ProformaFlowTests(ProformaTestDataMixin, TestCase):
    """Regroupe les tests lies au flux de creation et d'affichage des proformas."""

    def test_create_proforma_from_pos_without_fiscalization_and_without_stock_movement(self):
        """Verifie qu'une proforma creee depuis le POS ne fiscalise pas et ne bouge pas le stock."""

        payload = {
            "panier": [
                {
                    "id": self.produit.id,
                    "qty": 2,
                    "remise": 500,
                }
            ],
            "document_mode": "FV",
            "client_id": self.client_facture.id,
            "client_nif": self.client_facture.nif,
            "remise_globale": 250,
            "commentaires": ["Client souhaite valider plus tard"],
            "paiements": [
                {
                    "montant_verse": 5,
                    "devise": "USD",
                    "mode": "ESPECES",
                    "taux": 2800,
                }
            ],
        }

        with patch("facturation.fiscal_orchestrator.FiscalOrchestrator.fiscalize_commande") as mock_fiscalize:
            response = self.client.post(
                reverse("proforma:create"),
                data=json.dumps(payload),
                content_type="application/json",
            )

        self.assertEqual(response.status_code, 200)
        data = response.json()
        self.assertTrue(data["success"])
        self.assertEqual(Proforma.objects.count(), 1)
        self.assertEqual(Commande.objects.count(), 0)
        mock_fiscalize.assert_not_called()

        proforma = Proforma.objects.get()
        self.assertTrue(proforma.numero.startswith(f"PF-{timezone.now().year}-"))
        self.assertEqual(proforma.client, self.client_facture)
        self.assertGreater(proforma.montant_total, Decimal("0"))
        self.assertEqual(proforma.paiements.count(), 1)

        self.stock.refresh_from_db()
        self.assertEqual(self.stock.quantite, Decimal("5.000"))

    def test_create_proforma_without_stock_is_allowed_and_creates_no_stock_row(self):
        """Une proforma reste un document commercial sans réservation de stock."""

        self.stock.delete()
        payload = {
            "panier": [{"id": self.produit.id, "qty": 20, "remise": 0}],
            "document_mode": "FV",
            "client_id": self.client_facture.id,
            "remise_globale": 0,
            "paiements": [],
        }

        with patch("facturation.fiscal_orchestrator.FiscalOrchestrator.fiscalize_commande") as mock_fiscalize:
            response = self.client.post(
                reverse("proforma:create"),
                data=json.dumps(payload),
                content_type="application/json",
            )

        self.assertEqual(response.status_code, 200, response.content)
        self.assertEqual(Proforma.objects.count(), 1)
        self.assertFalse(
            StockPointDeVente.objects.filter(
                point_de_vente=self.point_de_vente,
                produit=self.produit,
            ).exists()
        )
        mock_fiscalize.assert_not_called()

    def test_proforma_detail_omits_fiscal_security_block(self):
        """Verifie que le detail proforma n'affiche pas les elements de securite fiscale."""

        proforma = Proforma.objects.create(
            point_de_vente=self.point_de_vente,
            vendeur=self.user,
            client=self.client_facture,
            montant_total=Decimal("32480.00"),
            tva_montant=Decimal("4480.00"),
            montant_paye=Decimal("0.00"),
            taux_change_applique=Decimal("2800.00"),
            mode_dgi="ttc",
            commentaire="Document commercial interne",
        )
        ProformaItem.objects.create(
            proforma=proforma,
            produit=self.produit,
            designation=self.produit.nom,
            code_sku=self.produit.code_sku,
            unite_mesure="U",
            quantite=Decimal("1.000"),
            prix_unitaire=Decimal("28000.00"),
            remise=Decimal("0.00"),
            sous_total=Decimal("28000.00"),
            tax_group_code="A",
            tax_rate=Decimal("16.00"),
        )

        response = self.client.get(reverse("proforma:detail", args=[proforma.pk]))

        self.assertEqual(response.status_code, 200)
        self.assertContains(response, "FACTURE PRO-FORMA")
        # Meme mise en page que la facture A4, sans son bloc de securite.
        self.assertContains(response, "invoice-lines-table")
        self.assertContains(response, "NET A PAYER (TTC)")
        self.assertContains(response, "<strong>ATTENTION</strong> Ce Pro-Forma n'est pas une Facture Normalisée", html=False)
        self.assertNotContains(response, "CODE DEF/DGI")
        self.assertNotContains(response, "ELEMENT SECURITE DE LA FACTURE NORMALISEE")

        # Sans Gotenberg ni navigateur local, xhtml2pdf produit encore le PDF.
        with patch("proforma.views._render_a4_with_gotenberg", return_value=None) as gotenberg, \
                patch("proforma.views._render_a4_with_browser", return_value=None):
            pdf_response = self.client.get(reverse("proforma:pdf", args=[proforma.pk]))
        pdf_html = gotenberg.call_args.args[0]
        self.assertIn("invoice_table_layout.css", pdf_html)
        self.assertIn("FACTURE PRO-FORMA", pdf_html)
        self.assertNotIn("ELEMENT SECURITE", pdf_html)
        self.assertEqual(pdf_response.status_code, 200)
        self.assertEqual(pdf_response["Content-Type"], "application/pdf")
        self.assertTrue(pdf_response.content.startswith(b"%PDF"))
        self.assertIn(proforma.numero, pdf_response["Content-Disposition"])

    def test_proforma_detail_adds_point_de_vente_under_company_identity(self):
        """Verifie que l'en-tete proforma garde la societe et ajoute le PDV."""

        self.point_de_vente.nom = "SHAHILKIN SARL - 03-LOWA"
        self.point_de_vente.adresse = "Av. Lowa No 45 C/Kinshasa KINSHASA"
        self.point_de_vente.save(update_fields=["nom", "adresse"])
        self.config.nom_entreprise = "CONFIG PROFORMA SARL"
        self.config.adresse = "Adresse configuration proforma"
        self.config.save(update_fields=["nom_entreprise", "adresse"])
        proforma = Proforma.objects.create(
            point_de_vente=self.point_de_vente,
            vendeur=self.user,
            client=self.client_facture,
            montant_total=Decimal("32480.00"),
            tva_montant=Decimal("4480.00"),
            montant_paye=Decimal("0.00"),
            taux_change_applique=Decimal("2800.00"),
            mode_dgi="ttc",
        )
        ProformaItem.objects.create(
            proforma=proforma,
            produit=self.produit,
            designation=self.produit.nom,
            code_sku=self.produit.code_sku,
            unite_mesure="U",
            quantite=Decimal("1.000"),
            prix_unitaire=Decimal("28000.00"),
            remise=Decimal("0.00"),
            sous_total=Decimal("28000.00"),
            tax_group_code="A",
            tax_rate=Decimal("16.00"),
        )

        response = self.client.get(reverse("proforma:detail", args=[proforma.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_create_proforma_rejects_rrr_mode(self):
        """Verifie que la creation refuse les modes documentaires non prevus pour la proforma."""

        payload = {
            "panier": [{"id": self.produit.id, "qty": 1, "remise": 0}],
            "document_mode": "RRR",
            "client_id": self.client_facture.id,
            "remise_globale": 0,
        }

        response = self.client.post(
            reverse("proforma:create"),
            data=json.dumps(payload),
            content_type="application/json",
        )

        self.assertEqual(response.status_code, 400)
        self.assertEqual(Proforma.objects.count(), 0)
        self.assertIn("facture de vente", response.json()["error"])

    def test_proforma_list_uses_bounded_server_pagination(self):
        """Le catalogue complet reste au serveur, avec une page de 30 documents."""

        response = self.client.get(reverse("proforma:list"))

        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.context["paginator"].per_page,30)
        self.assertContains(response, "data-history-search")
        self.assertContains(response, 'id="proforma-filter-pdv"')

    def test_proforma_list_filters_and_search_match_invoice_history(self):
        """Memes filtres que les factures : numero, client, montant, statut, periode et PDV."""

        paid = Proforma.objects.create(
            point_de_vente=self.point_de_vente, vendeur=self.user, client=self.client_facture,
            montant_total=Decimal("46000.00"), montant_paye=Decimal("46000.00"),
        )
        unpaid = Proforma.objects.create(
            point_de_vente=self.point_de_vente, vendeur=self.user, montant_total=Decimal("12500.00"),
        )

        def visible(**params):
            response = self.client.get(reverse("proforma:list"), params)
            self.assertEqual(response.status_code, 200)
            return [proforma.pk for proforma in response.context["proformas"]]

        self.assertEqual(visible(q=paid.numero), [paid.pk])
        self.assertEqual(visible(q=paid.numero.replace("-", "")), [paid.pk])
        self.assertEqual(visible(q="client test"), [paid.pk])
        self.assertEqual(visible(q="46 000"), [paid.pk])
        self.assertEqual(visible(statut="IMPAYEE"), [unpaid.pk])
        today = timezone.localdate()
        self.assertEqual(set(visible(date_debut=today.isoformat(), date_fin=today.isoformat())), {paid.pk, unpaid.pk})
        self.assertEqual(visible(date_debut=(today + timedelta(days=1)).isoformat()), [])
        self.assertEqual(visible(pdv=self.point_de_vente.pk), [unpaid.pk, paid.pk])
        other_point = PointDeVente.objects.create(nom="PDV interdit")
        self.assertEqual(visible(pdv=other_point.pk), [])

        response = self.client.get(reverse("proforma:list"), {"statut": "IMPAYEE"})
        self.assertIn("statut=IMPAYEE", response.context["proforma_filter_querystring"])
        self.assertContains(response, reverse("proforma:export-excel"))

        export = self.client.get(reverse("proforma:export-excel"), {"statut": "PAYEE"})
        self.assertEqual(export.status_code, 200)
        self.assertIn("spreadsheetml", export["Content-Type"])
        from openpyxl import load_workbook
        rows = list(load_workbook(BytesIO(export.content)).active.iter_rows(values_only=True))
        self.assertEqual([row[0] for row in rows[1:-1]], [paid.numero])


class ProformaInvoiceTests(ProformaTestDataMixin, TestCase):
    """Bouton "Facturer" : le panier de la proforma passe au POS puis a la facture."""

    FISCALIZE_PATH = "facturation.views.FiscalOrchestrator.fiscalize_commande"
    FISCAL_RESULT = {"success": True, "channel": "MCF", "commande_id": 1, "fiscal_transaction_id": "pf-invoice-001"}

    def setUp(self):
        super().setUp()
        # Un carton par defaut : la facture doit reprendre le conditionnement de
        # base (facteur 1), celui sur lequel la proforma est chiffree.
        ConditionnementProduit.objects.filter(produit=self.produit).update(par_defaut=False)
        ConditionnementProduit.objects.create(
            produit=self.produit, code="SKU-PF-001-CARTON", libelle="Carton",
            facteur_conversion=Decimal("12"), prix_vente=Decimal("110.00"), par_defaut=True,
        )
        self.base_packaging = ConditionnementProduit.objects.get(produit=self.produit, facteur_conversion=Decimal("1"))
        with patch(self.FISCALIZE_PATH) as mock_fiscalize:
            response = self.client.post(
                reverse("proforma:create"),
                data=json.dumps({
                    "panier": [{"id": self.produit.id, "qty": 2, "remise": 500}],
                    "document_mode": "FV",
                    "client_id": self.client_facture.id,
                    "remise_globale": 250,
                    "commentaires": ["Livraison samedi"],
                    "paiements": [],
                }),
                content_type="application/json",
            )
        self.assertEqual(response.status_code, 200, response.content)
        mock_fiscalize.assert_not_called()
        self.proforma = Proforma.objects.get(pk=response.json()["proforma_id"])
        self.reference = f"Réf Proforma N° {self.proforma.numero}"
        # Etablir la Pro-Forma ne sort rien du stock : seule la facture finalisee le fera.
        self.stock.refresh_from_db()
        self.assertEqual(self.stock.quantite, Decimal("5.000"))

    def invoice(self, sale):
        """Valide au POS le panier restaure, comme le bouton Valider & Facturer."""
        payload = {
            "proforma_id": self.proforma.pk,
            "panier": sale["panier"],
            "document_mode": "FV",
            "client_id": sale["client_id"],
            "client_nif": sale["client_nif"],
            "remise_globale": sale["remise_globale"],
            "commentaires": sale["commentaires"],
            "paiements": [{"montant_verse": 55250, "devise": "CDF", "mode": "ESPECES", "taux": 2800}],
        }
        with patch(self.FISCALIZE_PATH, return_value=self.FISCAL_RESULT):
            return self.client.post(reverse("facturation:pos-view"), data=json.dumps(payload), content_type="application/json")

    def test_facturer_opens_pos_with_proforma_cart_and_reference_comment(self):
        list_response = self.client.get(reverse("proforma:list"))
        invoice_url = f"{reverse('facturation:pos-view')}?proforma={self.proforma.pk}"
        self.assertContains(list_response, invoice_url)
        self.assertContains(self.client.get(reverse("proforma:detail", args=[self.proforma.pk])), invoice_url)

        response = self.client.get(reverse("facturation:pos-view"), {"proforma": self.proforma.pk, "billing": "quick"})

        self.assertEqual(response.status_code, 200)
        self.assertContains(response, 'id="proformaInvoiceData"')
        data = response.context["proforma_invoice"]
        self.assertEqual(data["proforma"], {"id": self.proforma.pk, "numero": self.proforma.numero, "montant_total": 55250.0, "mode": "invoice"})
        sale = data["sale"]
        self.assertEqual(sale["panier"], [{"id": self.produit.id, "conditionnement_id": self.base_packaging.id, "qty": 2.0, "remise": 500.0}])
        self.assertEqual(sale["commentaires"], [self.reference, "Livraison samedi"])
        self.assertEqual(sale["client_id"], self.client_facture.id)
        self.assertEqual(sale["remise_globale"], 250.0)
        self.assertEqual(data["produits_ecartes"], [])
        self.assertEqual(self.client.session["active_pos_id"], self.point_de_vente.pk)

    def test_invoice_is_linked_to_proforma_which_cannot_be_invoiced_twice(self):
        sale = self.client.get(reverse("facturation:pos-view"), {"proforma": self.proforma.pk}).context["proforma_invoice"]["sale"]
        # Ouvrir la Pro-Forma au POS ne touche pas non plus au stock.
        self.stock.refresh_from_db()
        self.assertEqual(self.stock.quantite, Decimal("5.000"))

        # Une fiscalisation qui demande le repli (409) annule toute la vente, stock compris.
        from facturation.fiscal_exceptions import FiscalFallbackRequired
        fallback = FiscalFallbackRequired("MCF indisponible", "pf-fallback", "MCF", "EMCF")
        with patch(self.FISCALIZE_PATH, side_effect=fallback):
            conflict = self.client.post(
                reverse("facturation:pos-view"),
                data=json.dumps({**sale, "proforma_id": self.proforma.pk, "paiements": []}),
                content_type="application/json",
            )
        self.assertEqual(conflict.status_code, 409, conflict.content)
        self.stock.refresh_from_db()
        self.assertEqual(self.stock.quantite, Decimal("5.000"))
        self.proforma.refresh_from_db()
        self.assertIsNone(self.proforma.facture)

        response = self.invoice(sale)

        self.assertEqual(response.status_code, 200, response.content)
        # La facture finalisee sort enfin les 2 unites du stock.
        self.stock.refresh_from_db()
        self.assertEqual(self.stock.quantite, Decimal("3.000"))
        commande = Commande.objects.get(pk=response.json()["commande_id"])
        self.proforma.refresh_from_db()
        self.assertEqual(self.proforma.facture, commande)
        self.assertIsNotNone(self.proforma.date_facturation)
        self.assertEqual(commande.commentaire, f"{self.reference}\nLivraison samedi")
        self.assertEqual(commande.montant_total, self.proforma.montant_total)
        ligne = commande.lignes.get()
        self.assertEqual((ligne.conditionnement, ligne.quantite, ligne.remise), (self.base_packaging, Decimal("2.000"), Decimal("500.00")))

        second = self.invoice(sale)
        self.assertEqual(second.status_code, 400)
        self.assertIn("deja facturee", second.json()["error"])
        self.assertEqual(Commande.objects.count(), 1)

        reopened = self.client.get(reverse("facturation:pos-view"), {"proforma": self.proforma.pk})
        self.assertIn(commande.numero, reopened.context["proforma_invoice"]["error"])
        list_response = self.client.get(reverse("proforma:list"))
        self.assertContains(list_response, "Facturée")
        self.assertContains(list_response, reverse("facturation:facture-detail", args=[commande.pk]))
        self.assertNotContains(list_response, f"?proforma={self.proforma.pk}")

    def test_proforma_of_another_point_de_vente_cannot_be_invoiced(self):
        other_point = PointDeVente.objects.create(nom="PDV voisin")
        self.proforma.point_de_vente = other_point
        self.proforma.save(update_fields=["point_de_vente"])

        response = self.client.get(reverse("facturation:pos-view"), {"proforma": self.proforma.pk})
        self.assertIn("introuvable", response.context["proforma_invoice"]["error"])

        sale = {"panier": [{"id": self.produit.id, "qty": 2, "remise": 500}], "client_id": self.client_facture.id,
                "client_nif": "", "remise_globale": 250, "commentaires": []}
        posted = self.invoice(sale)
        self.assertEqual(posted.status_code, 400)
        self.assertIn("introuvable", posted.json()["error"])
        self.assertEqual(Commande.objects.count(), 0)

    def test_inactive_products_are_left_out_and_reported(self):
        retired = Produit.objects.create(
            nom="Produit retire", code_sku="SKU-PF-002", prix_vente=Decimal("5.00"),
            taxgroup=self.tax_group, typeart=self.item_type, actif=True,
        )
        ProformaItem.objects.create(
            proforma=self.proforma, produit=retired, designation=retired.nom, quantite=Decimal("1"),
            prix_unitaire=Decimal("14000.00"), sous_total=Decimal("14000.00"),
        )
        retired.actif = False
        retired.save(update_fields=["actif"])

        data = self.client.get(reverse("facturation:pos-view"), {"proforma": self.proforma.pk}).context["proforma_invoice"]

        self.assertEqual([item["id"] for item in data["sale"]["panier"]], [self.produit.id])
        self.assertEqual(data["produits_ecartes"], ["Produit retire"])

    def test_pending_sale_keeps_the_proforma_being_invoiced(self):
        proforma_ref = {"id": self.proforma.pk, "numero": self.proforma.numero, "montant_total": 55250.0}
        response = self.client.post(
            reverse("facturation:pending-sale-save"),
            data=json.dumps({"panier": [{"id": self.produit.id, "qty": 2}], "proforma": proforma_ref}),
            content_type="application/json",
        )

        self.assertEqual(response.status_code, 200, response.content)
        self.assertEqual(response.json()["sale"]["proforma"], proforma_ref)
        self.assertEqual(PendingSale.objects.get().payload_json["proforma"], proforma_ref)

    # --- Modifier / supprimer (CRUD) --------------------------------------

    def update(self, **changes):
        payload = {
            "panier": [{"id": self.produit.id, "qty": 3, "remise": 0}],
            "document_mode": "FV",
            "client_id": self.client_facture.id,
            "remise_globale": 0,
            "commentaires": ["Livraison lundi"],
            "paiements": [{"montant_verse": 10, "devise": "USD", "mode": "ESPECES", "taux": 2800}],
            **changes,
        }
        return self.client.post(reverse("proforma:update", args=[self.proforma.pk]), data=json.dumps(payload), content_type="application/json")

    def test_modifier_opens_pos_with_comments_and_payments_and_rewrites_the_same_proforma(self):
        invoice_url = f"{reverse('facturation:pos-view')}?proforma={self.proforma.pk}&amp;mode=modifier"
        self.assertContains(self.client.get(reverse("proforma:list")), invoice_url)
        numero = self.proforma.numero

        response = self.update()

        self.assertEqual(response.status_code, 200, response.content)
        self.assertEqual(response.json()["detail_url"], f"{reverse('proforma:detail', args=[self.proforma.pk])}?updated=1")
        self.proforma.refresh_from_db()
        self.assertEqual(self.proforma.numero, numero)
        self.assertEqual(Proforma.objects.count(), 1)
        ligne = self.proforma.lignes.get()
        self.assertEqual((ligne.quantite, ligne.remise), (Decimal("3.000"), Decimal("0.00")))
        self.assertEqual(self.proforma.montant_total, Decimal("84000.00"))
        self.assertEqual(self.proforma.montant_paye, Decimal("28000.00"))
        self.assertEqual(self.proforma.commentaire, "Livraison lundi")
        self.stock.refresh_from_db()
        self.assertEqual(self.stock.quantite, Decimal("5.000"))

        data = self.client.get(reverse("facturation:pos-view"), {"proforma": self.proforma.pk, "mode": "modifier"}).context["proforma_invoice"]
        self.assertEqual(data["proforma"]["mode"], "edit")
        # En modification : commentaires d'origine (sans la reference) et paiements de la Pro-Forma.
        self.assertEqual(data["sale"]["commentaires"], ["Livraison lundi"])
        self.assertEqual(data["sale"]["paiements"], [{"raw_amount": "10", "montant_verse": 10.0, "devise": "USD", "mode": "ESPECES"}])
        self.assertContains(self.client.get(f"{reverse('proforma:detail', args=[self.proforma.pk])}?updated=1"), "La Pro-Forma a bien été modifiée.")

        # Sans paiement, le montant paye retombe a zero.
        self.assertEqual(self.update(paiements=[]).status_code, 200)
        self.proforma.refresh_from_db()
        self.assertEqual(self.proforma.montant_paye, Decimal("0.00"))
        self.assertEqual(self.proforma.statut_paiement, "IMPAYEE")

    def test_invoiced_proforma_can_no_longer_be_modified_or_deleted(self):
        sale = self.client.get(reverse("facturation:pos-view"), {"proforma": self.proforma.pk}).context["proforma_invoice"]["sale"]
        self.assertEqual(self.invoice(sale).status_code, 200)
        self.user.role = "ADMIN"
        self.user.save(update_fields=["role"])

        response = self.update()
        self.assertEqual(response.status_code, 400)
        self.assertIn("ne peut plus être modifiée ni supprimée", response.json()["error"])
        self.client.post(reverse("proforma:delete", args=[self.proforma.pk]))
        self.assertTrue(Proforma.objects.filter(pk=self.proforma.pk).exists())
        self.assertEqual(self.proforma.lignes.get().quantite, Decimal("2.000"))

        opened = self.client.get(reverse("facturation:pos-view"), {"proforma": self.proforma.pk, "mode": "modifier"})
        self.assertIn("ne peut plus être modifiée", opened.context["proforma_invoice"]["error"])
        list_response = self.client.get(reverse("proforma:list"))
        self.assertNotContains(list_response, "mode=modifier")
        self.assertNotContains(list_response, reverse("proforma:delete", args=[self.proforma.pk]))

    def test_delete_requires_the_right_and_removes_lines_and_payments(self):
        self.assertEqual(self.update().status_code, 200)
        # Vendeur : modification accordee par defaut, suppression reservee a l'administrateur.
        self.assertNotContains(self.client.get(reverse("proforma:list")), reverse("proforma:delete", args=[self.proforma.pk]))
        self.client.post(reverse("proforma:delete", args=[self.proforma.pk]))
        self.assertTrue(Proforma.objects.filter(pk=self.proforma.pk).exists())

        self.user.role = "ADMIN"
        self.user.save(update_fields=["role"])
        self.assertContains(self.client.get(reverse("proforma:list")), reverse("proforma:delete", args=[self.proforma.pk]))
        response = self.client.post(reverse("proforma:delete", args=[self.proforma.pk]), follow=True)

        self.assertRedirects(response, reverse("proforma:list"))
        self.assertIn(f"La Pro-Forma {self.proforma.numero} a été supprimée.", [str(m) for m in response.context["messages"]])
        self.assertFalse(Proforma.objects.exists())
        self.assertFalse(ProformaItem.objects.exists())
