"""Scénarios réels Chrome : le même moteur dans les six workflows métier."""
import importlib.util
import re
from contextlib import contextmanager
from unittest import skipUnless

from django.contrib.staticfiles.testing import StaticLiveServerTestCase
from django.urls import reverse

from achats.models import Achat, LigneAchat, ReceptionAchat, LigneReceptionAchat, RetourFournisseur
from fournisseurs.models import Fournisseur
from paiements.models import PaiementFournisseur
from stock.models import InventaireStock, LigneInventaireStock, ReapprovisionnementDirect, TransfertStock
from stock import tests_reapprovisionnements_browser as direct_browser
from . import tests_quick_billing_browser as quick_browser
from .models import Categorie, PointDeVente, Produit, StockPointDeVente


@skipUnless(importlib.util.find_spec("playwright"), "Installer requirements-dev.txt pour les tests Chrome.")
class FacControlSearchBrowserTests(StaticLiveServerTestCase):
    @contextmanager
    def browser(self, **kwargs):
        with quick_browser.QuickBillingBrowserTests.browser(self, **kwargs) as page:
            try:
                yield page
            except Exception:
                print('SCENARIO', self._testMethodName, 'URL', page.url, 'ERRORS', ascii(page.locator('.errorlist,.alert-danger').all_text_contents()))
                page.screenshot(path=str(self.qa_dir / (self._testMethodName + '.png')),full_page=True)
                raise
    assert_focus = quick_browser.QuickBillingBrowserTests.assert_focus
    database = direct_browser.ReapprovisionnementDirectBrowserTests.database

    def setUp(self):
        quick_browser.QuickBillingBrowserTests.setUp(self)
        self.destination = PointDeVente.objects.create(nom="Destination")
        self.supplier = Fournisseur.objects.create(raison_sociale="ABC Trading", nif="FOU-NIF-KEYBOARD", telephone="0991230000")
        StockPointDeVente.objects.filter(produit=self.product,point_de_vente=self.pdv).update(cump=500)

    def goto(self, page, route, args=None):
        response=self.database(lambda:self.client.get(reverse(route,args=args)))
        self.assertEqual(response.status_code,200)
        page.goto(self.live_server_url + reverse(route,args=args),wait_until="load")
        page.wait_for_function("typeof FacControlSearch === 'function'")

    def choose(self, page, selector, text, key="Enter"):
        search = page.locator(selector)
        search.focus()
        page.keyboard.press("Control+a")
        page.keyboard.type(text)
        panel=page.locator('#'+search.get_attribute('aria-controls'))
        panel.locator('[role="option"]').first.wait_for(state="visible")
        page.keyboard.press("ArrowDown")
        page.keyboard.press(key)

    def draft_purchase(self, received=False):
        achat=Achat.objects.create(fournisseur=self.supplier,point_de_vente=self.pdv,created_by=self.user,reference_fournisseur="FAC-KEYBOARD")
        line=LigneAchat.objects.create(achat=achat,produit=self.product,conditionnement=self.piece,quantite=10,prix_achat_conditionnement=100,remise=0)
        achat.valider()
        if received:
            reception=ReceptionAchat.objects.create(achat=achat,point_de_vente=self.pdv,receptionne_par=self.user,reference_bon_livraison="BL-KEYBOARD")
            LigneReceptionAchat.objects.create(reception=reception,ligne_achat=line,produit=self.product,conditionnement=self.piece,quantite_commerciale_recue=10)
            reception.valider()
        return achat

    def test_common_arrows_enter_tab_space_escape_shift_tab_and_mouse(self):
        from playwright.sync_api import expect
        Produit.objects.create(nom="Jean Pierre",code_sku="GEDETEST03",prix_vente=1000)
        with self.browser() as page:
            self.goto(page,"facturation:achat-create")
            field=page.locator('#id_lignes-0-produit-search');field.focus()
            page.keyboard.type("GEDETEST")
            options=page.locator('.faccontrol-search-results:not([hidden]) [role="option"]')
            expect(options).to_have_count(3)
            first_id=options.first.get_attribute('data-value')
            page.keyboard.press("ArrowDown");page.keyboard.press("ArrowDown");page.keyboard.press("ArrowUp")
            expect(field).to_have_attribute('aria-activedescendant', options.first.get_attribute('id'))
            page.keyboard.press("Enter")
            expect(page.locator('#id_lignes-0-produit')).to_have_value(first_id)
            self.assert_focus(page,'#id_lignes-0-conditionnement')
            page.keyboard.press("Shift+Tab");self.assert_focus(page,'#id_lignes-0-produit-search')
            page.keyboard.press("Control+a");page.keyboard.type("GEDETEST02")
            expect(options).to_have_count(1)
            page.keyboard.press("ArrowDown");page.keyboard.press("Tab")
            expect(page.locator('#id_lignes-0-produit')).to_have_value(str(self.second.pk))
            self.assert_focus(page,'#id_lignes-0-conditionnement')
            field.focus();page.keyboard.press("Control+a");page.keyboard.type("Jean Pierre")
            expect(field).to_have_value("Jean Pierre")
            expect(options).to_have_count(1)
            page.keyboard.press("ArrowDown");page.keyboard.press("Space")
            expect(page.locator('#id_lignes-0-produit')).not_to_have_value('')
            self.assert_focus(page,'#id_lignes-0-conditionnement')
            field.focus();page.keyboard.press("Control+a");page.keyboard.type("GEDETEST")
            expect(options).to_have_count(3)
            page.keyboard.press("Escape")
            expect(options).to_have_count(0);expect(field).to_have_value("GEDETEST")
            self.assert_focus(page,'#id_lignes-0-produit-search')
            page.keyboard.press("Tab")
            self.assert_focus(page,'#id_lignes-0-conditionnement')
            expect(page.locator('#id_lignes-0-produit')).to_have_value('')
            page.keyboard.press("Shift+Tab")
            self.assert_focus(page,'#id_lignes-0-produit-search')
            page.keyboard.press("Shift+Tab")
            expect(field).not_to_be_focused()
            field.focus();page.keyboard.press("Control+a");page.keyboard.type("GEDETEST02")
            expect(options).to_have_count(1);options.first.click()
            expect(page.locator('#id_lignes-0-produit')).to_have_value(str(self.second.pk))
            self.assertEqual(page.locator('#id_lignes-0-produit option').count(),2)

    def test_purchase_supplier_product_pack_quantity_price_discount_next_line_without_mouse(self):
        from playwright.sync_api import expect
        with self.browser() as page:
            self.goto(page,"facturation:achat-create")
            self.choose(page,'#id_fournisseur-search',"ABC")
            self.assert_focus(page,'#id_points_de_vente-search')
            self.choose(page,'#id_points_de_vente-search',self.pdv.nom)
            for _ in range(20):
                if page.evaluate("document.activeElement.id")=="id_lignes-0-produit-search":break
                page.keyboard.press('Tab')
            self.assert_focus(page,'#id_lignes-0-produit-search')
            page.keyboard.type("GEDETEST01");page.locator('.faccontrol-search-results:not([hidden]) [role="option"]').first.wait_for(state='visible')
            page.keyboard.press('Enter');self.assert_focus(page,'#id_lignes-0-conditionnement')
            page.keyboard.press('ArrowDown');page.keyboard.press('Tab')
            self.assert_focus(page,'#id_lignes-0-quantite');page.keyboard.press('Control+a');page.keyboard.type('2');page.keyboard.press('Tab')
            self.assert_focus(page,'#id_lignes-0-prix_achat_conditionnement');page.keyboard.press('Control+a');page.keyboard.type('200');page.keyboard.press('Tab')
            self.assert_focus(page,'#id_lignes-0-remise');page.keyboard.press('Control+a');page.keyboard.type('0');page.keyboard.press('Tab')
            self.assert_focus(page,'#id_lignes-1-produit-search')
            self.choose(page,'#id_lignes-1-produit-search','GEDETEST02')
            self.assert_focus(page,'#id_lignes-1-conditionnement');page.keyboard.press('Tab')
            self.assert_focus(page,'#id_lignes-1-quantite');page.keyboard.press('Control+a');page.keyboard.type('1');page.keyboard.press('Tab')
            self.assert_focus(page,'#id_lignes-1-prix_achat_conditionnement');page.keyboard.press('Control+a');page.keyboard.type('100')
            page.locator('#achat-form button[type="submit"]').focus();page.keyboard.press('Enter')
            page.wait_for_url(re.compile(r'/achats/\d+/$'))
            self.assertEqual(self.database(lambda:Achat.objects.count()),1)
            self.assertEqual(self.database(lambda:StockPointDeVente.objects.get(produit=self.product,point_de_vente=self.pdv).quantite),80)

    def test_direct_product_pack_quantity_cost_motif_review_without_mouse(self):
        from playwright.sync_api import expect
        with self.browser() as page:
            self.goto(page,"facturation:stock-direct-create")
            self.choose(page,'#id_lignes-0-produit-search','GEDETEST01')
            self.assert_focus(page,'#id_lignes-0-conditionnement');page.keyboard.press('ArrowDown');page.keyboard.press('ArrowDown');page.keyboard.press('Tab')
            self.assert_focus(page,'#id_lignes-0-quantite_commerciale');page.keyboard.press('Control+a');page.keyboard.type('2');page.keyboard.press('Tab')
            self.assert_focus(page,'#id_lignes-0-cout_unitaire_base');page.keyboard.type('500');page.keyboard.press('Tab')
            self.assert_focus(page,'#id_lignes-0-devise_cout');page.keyboard.press('Tab')
            self.assert_focus(page,'#id_lignes-0-motif');page.keyboard.press('ArrowDown');page.keyboard.press('Tab')
            self.assert_focus(page,'#direct-replenishment-form button[type="submit"]');page.keyboard.press('Enter')
            page.wait_for_url(re.compile(r'/stocks/reapprovisionnements/\d+/$'))
            self.assertEqual(self.database(lambda:ReapprovisionnementDirect.objects.count()),1)
            expect(page.locator('main')).to_contain_text('RAP-')

    def test_transfer_source_destination_product_stock_pack_quantity_without_mouse(self):
        from playwright.sync_api import expect
        with self.browser() as page:
            self.goto(page,'facturation:transfert-stock-create')
            self.choose(page,'#id_point_de_vente_source-search',self.pdv.nom)
            expect(page.locator('#id_point_de_vente_source')).to_have_value(str(self.pdv.pk))
            self.assert_focus(page,'#id_point_de_vente_destination-search')
            self.choose(page,'#id_point_de_vente_destination-search','Destination')
            expect(page.locator('#id_point_de_vente_destination')).to_have_value(str(self.destination.pk))
            page.locator('#id_motif').focus();page.keyboard.type('Transfert clavier')
            self.choose(page,'#id_lignes-0-produit-search','GEDETEST01')
            expect(page.locator('.transfer-available')).to_contain_text('80')
            self.assert_focus(page,'#id_lignes-0-conditionnement');page.keyboard.press('ArrowDown');page.keyboard.press('Tab')
            self.assert_focus(page,'#id_lignes-0-quantite_commerciale');page.keyboard.press('Control+a');page.keyboard.type('2');page.keyboard.press('Tab')
            self.assert_focus(page,'#transfer-form button[type="submit"]');page.keyboard.press('Enter')
            page.wait_for_url(re.compile(r'/transferts-stock/\d+/$'))
            self.assertEqual(self.database(lambda:TransfertStock.objects.count()),1)

    def test_inventory_select_count_save_next_product_without_reload_or_theoretical_leak(self):
        from playwright.sync_api import expect
        inventory=InventaireStock.objects.create(point_de_vente=self.pdv,created_by=self.user,type_inventaire='PARTIEL',masquer_theorique=True)
        with self.browser() as page:
            self.goto(page,'facturation:inventaire-stock-detail',[inventory.pk])
            page.evaluate('window.searchPageMarker="unchanged"')
            self.choose(page,'#id_produit-search','GEDETEST01')
            self.assert_focus(page,'#inventory-count-panel #id_comptages-0-conditionnement')
            expect(page.locator('#inventory-count-panel #theoretical-quantity')).to_have_count(0)
            page.keyboard.press('Tab');self.assert_focus(page,'#inventory-count-panel #id_comptages-0-quantite_commerciale')
            page.keyboard.press('Control+a');page.keyboard.type('80');page.keyboard.press('Tab')
            self.assert_focus(page,'#inventory-count-panel #id_motif');page.keyboard.press('Tab');page.keyboard.press('Tab')
            page.keyboard.press('Enter')
            self.assert_focus(page,'#id_produit-search')
            self.assertEqual(page.evaluate('window.searchPageMarker'),'unchanged')
            self.assertEqual(self.database(lambda:LigneInventaireStock.objects.get(inventaire=inventory).quantite_comptee),80)
            self.choose(page,'#id_produit-search','GEDETEST02')
            self.assert_focus(page,'#inventory-count-panel #id_comptages-0-conditionnement')

    def test_supplier_payment_purchase_amount_mode_save_without_mouse(self):
        from playwright.sync_api import expect
        achat=self.draft_purchase()
        with self.browser() as page:
            self.goto(page,'facturation:paiement-fournisseur-create')
            self.choose(page,'#id_achat-search','FAC-KEYBOARD')
            self.assert_focus(page,'#id_montant');page.keyboard.type('500');page.keyboard.press('Tab')
            self.assert_focus(page,'#id_mode_paiement');page.keyboard.press('ArrowDown');page.keyboard.press('Tab');page.keyboard.type('PAY-KEYBOARD');page.keyboard.press('Tab');page.keyboard.press('Tab');page.keyboard.press('Enter')
            page.wait_for_url(re.compile(r'/paiements-fournisseurs/\d+/$'))
            self.assertEqual(self.database(lambda:PaiementFournisseur.objects.get(achat=achat).montant),500)

    def test_supplier_return_purchase_returnable_line_quantity_reason_save_without_mouse(self):
        from playwright.sync_api import expect
        achat=self.draft_purchase(received=True)
        with self.browser() as page:
            self.goto(page,'facturation:retour-fournisseur-list')
            self.choose(page,'#return-purchase-search','FAC-KEYBOARD')
            page.wait_for_url('**/achats/*/retourner/**')
            self.assert_focus(page,'#id_lignes-0-ligne_reception-search')
            page.locator('#id_motif').focus();page.keyboard.press('ArrowDown')
            self.choose(page,'#id_lignes-0-ligne_reception-search','GEDETEST01')
            self.assert_focus(page,'#id_lignes-0-quantite_commerciale');page.keyboard.type('2');page.keyboard.press('Tab')
            self.assert_focus(page,'#id_lignes-0-motif_ligne');page.keyboard.type('Emballage abîmé')
            page.locator('main form button[type="submit"]').focus();page.keyboard.press('Enter')
            page.wait_for_url(re.compile(r'/retours-fournisseurs/\d+/$'))
            self.assertEqual(self.database(lambda:RetourFournisseur.objects.get(achat=achat).lignes.get().quantite_commerciale),2)

    def test_product_and_supplier_list_search_preserve_document_and_focus(self):
        from playwright.sync_api import expect
        with self.browser(language='en') as page:
            self.goto(page,'facturation:produit-list')
            page.evaluate('window.searchPageMarker="unchanged"')
            input=page.locator('#product-live-search-input');input.focus();page.keyboard.type('GEDETEST02')
            expect(page.locator('#product-results-table tbody tr')).to_have_count(1)
            expect(page.locator('#product-results-table tbody')).to_contain_text('JUS MANGO')
            expect(page.locator('#product-results-table tbody mark').first).to_have_text(re.compile('GEDETEST02',re.I))
            self.assert_focus(page,'#product-live-search-input')
            self.assertEqual(page.evaluate('window.searchPageMarker'),'unchanged')
            self.goto(page,'facturation:fournisseur-list')
            page.evaluate('window.searchPageMarker="unchanged"')
            field=page.locator('[name="q"]');field.focus();page.keyboard.type('ABC')
            expect(page.locator('.faccontrol-search-results:not([hidden]) [role="option"]')).to_have_count(1)
            page.keyboard.press('ArrowDown');page.keyboard.press('Enter')
            expect(page.locator('[data-search-output] tbody')).to_contain_text('ABC Trading')
            self.assertEqual(page.evaluate('window.searchPageMarker'),'unchanged')

    def test_product_catalogue_large_search_filters_and_export_link_stay_synchronized(self):
        """La refonte catalogue fonctionne dans Chrome sans rechargement de page."""

        from playwright.sync_api import expect

        category = Categorie.objects.create(nom="Boissons navigateur")
        Produit.objects.filter(pk=self.product.pk).update(categorie=category, unite_mesure="BOUTEILLE")
        with self.browser(viewport={"width": 1440, "height": 900}) as page:
            self.goto(page, "facturation:produit-list")
            search = page.locator("#product-live-search-input")
            shell = page.locator(".product-search-shell")
            filter_panel = page.locator(".product-filter-panel")
            table = page.locator(".product-table-wrap")
            expect(shell).to_be_visible()
            self.assertGreater(shell.bounding_box()["width"], 700)
            filter_box = filter_panel.bounding_box()
            search_box = page.locator(".product-search-stage").bounding_box()
            table_box = table.bounding_box()
            self.assertGreaterEqual(search_box["y"], filter_box["y"] + filter_box["height"])
            self.assertLessEqual(search_box["y"] + search_box["height"], table_box["y"])
            expect(page.locator("#product-category-filter")).to_be_visible()
            expect(page.locator("#product-type-filter")).to_be_visible()
            expect(page.locator("#product-tax-filter")).to_be_visible()
            expect(page.locator("#product-unit-filter")).to_be_visible()
            expect(page.locator("#product-status-filter")).to_be_visible()

            page.locator("#product-category-filter").select_option(str(category.pk))
            expect(page.locator(".product-table-wrap tbody tr")).to_have_count(1)
            expect(page.locator(".product-table-wrap tbody")).to_contain_text(self.product.nom)
            self.assertIn(f"categorie={category.pk}", page.locator("#product-filtered-export").get_attribute("href"))

            search.fill("GEDETEST01")
            expect(page.locator(".product-table-wrap tbody tr")).to_have_count(1)
            expect(page.locator(".faccontrol-search-results:not([hidden])")).to_have_count(0)
            expect(page.locator("#product-filtered-export")).to_have_attribute("href", re.compile(r"[?&]q=GEDETEST01(?:&|$)"))
            expect(search).to_be_focused()
            page.screenshot(path=str(self.qa_dir / "product-catalogue-search-filters.png"), full_page=True)

    def test_shared_dropdown_fits_desktop_and_mobile_and_translates_empty_state(self):
        from playwright.sync_api import expect
        for width,height in ((1366,768),(1920,1080),(375,812)):
            with self.subTest(width=width), self.browser(language="en",viewport={"width":width,"height":height}) as page:
                self.goto(page,"facturation:stock-direct-create")
                search=page.locator('#id_lignes-0-produit-search');search.focus();page.keyboard.type('GEDETEST')
                options=page.locator('.faccontrol-search-results:not([hidden]) [role="option"]')
                expect(options).to_have_count(2);page.keyboard.press('ArrowDown')
                panel=page.locator('.faccontrol-search-results:not([hidden])')
                box=panel.bounding_box();self.assertGreaterEqual(box['x'],0);self.assertLessEqual(box['x']+box['width'],width)
                page.screenshot(path=str(self.qa_dir/f"common-search-en-{width}.png"))
                page.keyboard.press('Escape');expect(search).to_have_value('GEDETEST')
                page.keyboard.press('Control+a');page.keyboard.type('ZZZZ-no-result')
                expect(panel).to_contain_text('No results')
                page.keyboard.press('Enter')
                expect(search).to_be_focused()

    def test_large_admin_multiple_selector_tab_clear_and_explicit_all(self):
        from playwright.sync_api import expect
        for index in range(25):PointDeVente.objects.create(nom=f"Remote admin point {index:02}")
        with self.browser(language="en") as page:
            self.goto(page,"facturation:user-create")
            native=page.locator('#id_points_de_vente')
            self.assertEqual(native.evaluate('(select)=>[...select.selectedOptions].map(option=>option.value)'),[])
            search=page.locator('#id_points_de_vente-search');search.focus()
            panel=page.locator('#'+search.get_attribute('aria-controls'))
            expect(panel).to_be_visible()
            page.keyboard.press('Tab')
            expect(page.locator('#id_is_active')).to_be_focused()
            self.assertEqual(native.evaluate('(select)=>[...select.selectedOptions].map(option=>option.value)'),[])
            self.choose(page,'#id_points_de_vente-search','Remote admin point 05',key='Tab')
            expect(page.locator('#id_is_active')).to_be_focused()
            self.assertEqual(native.locator('option').count(),2)
            wrapper=page.locator('#id_points_de_vente-search').locator('..')
            wrapper.locator('button.faccontrol-search-chip-remove').click()
            self.assertEqual(native.evaluate('(select)=>[...select.selectedOptions].map(option=>option.value)'),[])
            panel.locator('[data-value="all"]').click()
            self.assertEqual(native.evaluate('(select)=>[...select.selectedOptions].map(option=>option.value)'),['all'])
            wrapper.locator('button.faccontrol-search-chip-remove').click()
            self.assertEqual(native.evaluate('(select)=>[...select.selectedOptions].map(option=>option.value)'),[])

    def test_point_selection_chips_inline_multiple_all_and_mobile(self):
        from playwright.sync_api import expect
        for language,width,height,all_text in (("fr",1366,768,"Tous les points de vente"),("en",375,812,"All points of sale")):
            with self.subTest(language=language,width=width),self.browser(language=language,viewport={"width":width,"height":height}) as page:
                self.goto(page,"facturation:produit-list")
                search=page.locator('#product-point-filter-search');control=search.locator('..');native=page.locator('#product-point-filter')
                expect(control).to_have_class('faccontrol-search-pdv-control')
                expect(control.locator('.faccontrol-search-chip')).to_contain_text(all_text)
                page.screenshot(path=str(self.qa_dir/f"pdv-selection-{language}-{width}.png"))
                control.locator('.faccontrol-search-chip-remove').click()
                self.assertEqual(native.evaluate('(select)=>[...select.selectedOptions].map(option=>option.value)'),[])
                panel=page.locator('#'+search.get_attribute('aria-controls'))
                expect(panel).to_be_visible()
                panel.locator(f'[data-value="{self.pdv.pk}"]').click()
                self.choose(page,'#product-point-filter-search','Destination')
                self.assertEqual(set(native.evaluate('(select)=>[...select.selectedOptions].map(option=>option.value)')),{str(self.pdv.pk),str(self.destination.pk)})
                expect(control.locator('.faccontrol-search-chip')).to_have_count(2)
                self.assertEqual(set(native.evaluate('(select)=>new FormData(select.form).getAll(select.name)')),{str(self.pdv.pk),str(self.destination.pk)})
                search.click();expect(panel).to_be_visible();panel.locator('[data-value="all"]').click()
                self.assertEqual(native.evaluate('(select)=>[...select.selectedOptions].map(option=>option.value)'),['all'])
                expect(control.locator('.faccontrol-search-chip')).to_have_count(1)
                box=control.bounding_box();self.assertGreaterEqual(box['x'],0);self.assertLessEqual(box['x']+box['width'],width)

    def test_local_point_selection_filters_rendered_points_without_search_api(self):
        """Rapport journalier : memes etiquettes, mais choix limites aux options du serveur."""
        from playwright.sync_api import expect
        with self.browser() as page:
            api_calls=[]
            page.on('request',lambda request:api_calls.append(request.url) if '/search/' in request.url else None)
            self.goto(page,'facturation:rapport-journalier')
            search=page.locator('#daily-pdv-search');control=search.locator('..');native=page.locator('#daily-pdv')
            expect(control).to_have_class('faccontrol-search-pdv-control')
            expect(control.locator('.faccontrol-search-chip')).to_contain_text('Tous les points de vente')
            control.locator('.faccontrol-search-chip-remove').click()
            panel=page.locator('#'+search.get_attribute('aria-controls'))
            expect(panel).to_be_visible()
            expect(panel.locator(f'[data-value="{self.destination.pk}"]')).to_contain_text('Destination')
            self.choose(page,'#daily-pdv-search','destin')
            self.assertEqual(native.evaluate('(select)=>select.value'),str(self.destination.pk))
            expect(control.locator('.faccontrol-search-chip')).to_contain_text('Destination')
            page.screenshot(path=str(self.qa_dir/'pdv-selection-daily-report.png'))
            self.assertEqual(api_calls,[])

    def test_turnover_report_opens_on_all_points_and_a_single_all_clients_toggle(self):
        from playwright.sync_api import expect
        with self.browser() as page:
            self.goto(page,'facturation:rapport-chiffre-affaires')
            points=page.locator('#ca-pdv-search').locator('..')
            expect(points.locator('.faccontrol-search-chip')).to_have_count(1)
            expect(points.locator('.faccontrol-search-chip')).to_contain_text('Tous les points de vente')
            clients=page.locator('#ca-client').locator('..')
            expect(clients.locator('.faccontrol-search-all')).to_have_count(1)
            expect(clients.locator('.faccontrol-search-all')).to_have_class(re.compile(r'\bis-active\b'))
            expect(clients.locator('.faccontrol-search-selected .faccontrol-search-chip')).to_have_count(0)
            page.screenshot(path=str(self.qa_dir/'ca-report-filters.png'))

    def test_point_import_all_chip_submits_existing_checkbox_contract(self):
        from playwright.sync_api import expect
        with self.browser(language='en') as page:
            self.goto(page,'facturation:produit-import-excel')
            search=page.locator('#id_points_de_vente-search');search.click()
            panel=page.locator('#'+search.get_attribute('aria-controls'))
            expect(panel).to_be_visible();panel.locator('[data-value="all"]').click()
            expect(page.locator('#id_tous_points_de_vente')).to_be_checked()
            self.assertEqual(page.locator('#id_points_de_vente').evaluate('(select)=>new FormData(select.form).getAll(select.name)'),[])
            self.assertEqual(search.evaluate('(input)=>new FormData(input.closest("form")).get("tous_points_de_vente")'),'on')
            search.locator('..').locator('.faccontrol-search-chip-remove').click()
            expect(page.locator('#id_tous_points_de_vente')).not_to_be_checked()
            self.choose(page,'#id_points_de_vente-search','Destination')
            expect(page.locator('#id_tous_points_de_vente')).not_to_be_checked()
            self.assertEqual(page.locator('#id_points_de_vente').evaluate('(select)=>new FormData(select.form).getAll(select.name)'),[str(self.destination.pk)])

    def test_client_confirmation_survives_ajax_filter_refresh(self):
        from playwright.sync_api import expect
        from .models import Client
        customer=Client.objects.create(nom_complet="Recherche confirmation",telephone="0995555555")
        with self.browser() as page:
            self.goto(page,"facturation:client-list")
            page.evaluate('window.searchPageMarker="unchanged"')
            search=page.locator('[name="q"]');search.focus();page.keyboard.type("Recherche confirmation")
            expect(page.locator('[data-search-output] tbody tr')).to_have_count(1)
            page.locator('[data-client-delete-form] button').click()
            expect(page.locator('[role="dialog"]')).to_be_visible()
            page.keyboard.press('Escape')
            expect(page.locator('[role="dialog"]')).not_to_be_visible()
            self.assertEqual(page.evaluate('window.searchPageMarker'),'unchanged')
            self.assertTrue(self.database(lambda:Client.objects.filter(pk=customer.pk).exists()))

    def test_large_pos_categories_and_point_switch_keep_real_ids_and_billing_mode(self):
        from playwright.sync_api import expect
        from .models import Categorie
        points=[]
        for index in range(25):
            points.append(PointDeVente.objects.create(nom=f"Remote POS point {index:02}"))
            Categorie.objects.create(nom=f"Remote POS category {index:02}")
        with self.browser() as page:
            button=page.locator('[data-bs-target="#quickProductModal"]').first
            button.focus();page.keyboard.press('Enter')
            expect(page.locator('#quickProductModal')).to_be_visible()
            page.wait_for_function('!bootstrap.Modal.getInstance(document.getElementById("quickProductModal"))._isTransitioning')
            self.choose(page,'#quickProductCategory-search','Remote POS category 05')
            self.assert_focus(page,'#quickProductItemType')
            self.assertEqual(page.locator('#quickProductCategory option').count(),2)
            page.evaluate('document.getElementById("quickProductForm").reset()')
            expect(page.locator('#quickProductCategory-search')).to_have_value('')
            page.keyboard.press('Escape')
            expect(page.locator('#quickProductModal')).not_to_be_visible()
            page.wait_for_function('!bootstrap.Modal.getInstance(document.getElementById("quickProductModal"))._isTransitioning && !document.querySelector(".modal-backdrop")')
            page.keyboard.press('F7')
            with page.expect_navigation(wait_until='load'):
                self.choose(page,'#posPointOfSaleSwitch-search','Remote POS point 05')
            page.wait_for_function('window.FacControlQuickBilling?.active')
            self.assertEqual(page.locator('#pos-app').get_attribute('data-active-pos'),str(points[5].pk))
            self.assertEqual(page.locator('#pos-app').get_attribute('data-billing-mode'),'quick')
