const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/BonChargeCamion-n7cMHfKp.js","assets/Echange-CksMo6mT.js","assets/primevue-CfIk0_DY.js","assets/vue-core-Di3IuVqe.js","assets/cjs-helpers-psZwOBky.js","assets/primevue-BU6TPP52.css","assets/selectDate-Dai2cu2_.js","assets/index-BxIwIJfy.js","assets/vue-cal-DKMVGERa.js","assets/vue-cal-XQZN_nJT.css","assets/moment-BeHQNF8T.js","assets/index-CQOoCaGF.css","assets/selectDate-CTQvSv6H.css","assets/FavorisSwitch-BFqqA1tj.js","assets/RapportDynamique-DI8KNc5X.js","assets/ReportViewer-BNzhW7G2.js","assets/stimulsoft-B2-Y-rC1.js","assets/stimulsoft-tn0RQdqM.css","assets/PDFButton-DhVJ6hNy.js","assets/ReportViewer-B8v1fpC8.css","assets/RapportDynamique-C0Y8I-0M.css","assets/Imprimer-DluCFs7h.js","assets/ExportPersonaliser-BLGEVT65.js","assets/export-files-DFMiSRgA.js","assets/ExportPersonaliser-BFEZ-E9Y.css","assets/OptionGrid-6kA3ogol.js","assets/OptionGrid-DTL9OoPr.css","assets/EchangeLignes-CRllVs7O.js","assets/useChampsLibreCount-CdYkrwOw.js","assets/ArticleQuickSearch-DMuL_J4J.js","assets/imageTraitements-BoTBAXYr.js","assets/ArticleQuickSearch-DBRFOh3p.css","assets/ComboDynamique-BzWI4ISP.js","assets/ComboDynamique-C40nXd8V.css","assets/RailTiers-C3DvZy3z.js","assets/HistoriqueDocument-jyEUC_ON.js","assets/HistoriqueDocument-CZWK-4O1.css","assets/PiecesJointes-BcNdv7mw.js","assets/useLienFichier-BJZ-0upj.js","assets/Commentaires-CvKsZ8LO.js","assets/Commentaires-Dpnzz08u.css","assets/RailTiers-C069toxI.css","assets/NumeroChip-QCXXOqUM.js","assets/NumeroChip-_yMpGZo8.css","assets/InfoBulle-R_p1ZfIR.js","assets/InfoBulle-CwnvsqW1.css","assets/useGammeColumn-BsgFVfy_.js","assets/usePagerDetail-BeqYPv-1.js","assets/useLigneEntryEpinglee-Bizt7YJJ.js","assets/useArticleColumnEditor-CkolSBZl.js","assets/documentBlocage-zT3KQMAM.js","assets/useAgGridConfig-Dp3DkgaV.js","assets/useAutoPiecesJointes-D0rPgWqP.js","assets/useGridContextFilter-D02dkIUR.js","assets/useControleMoisEchu-DYPI-qxH.js","assets/useStableRowId-BwuXNBwn.js","assets/useSelecteurArticlesPanier-beC68yg9.js","assets/DataGrid-CoMfrBJA.js","assets/DataGrid-BaIVe-mO.css","assets/FilterBar-B1Y-Xx7o.js","assets/FilterBar-C1MCBg3G.css"])))=>i.map(i=>d[i]);
import{b as Re,B as Ie,y as Ee,r as Ne,_ as Le}from"./primevue-CfIk0_DY.js";import{C as Te}from"./ComboDynamique-BzWI4ISP.js";import{_ as Fe,b as y,s,u as ze,w as Pe,j as Me,A as Be}from"./index-BxIwIJfy.js";import{u as je}from"./usePagerDetail-BeqYPv-1.js";import{N as qe}from"./NumeroChip-QCXXOqUM.js";import{I as Q}from"./InfoBulle-R_p1ZfIR.js";import{L as B}from"./leaflet-EmtrOWuW.js";import{o as Y,a0 as Ue,w as ee,b,c as z,d as n,ab as Oe,p as D,a as C,y as I,n as Ge,h as We,k as j,v as _,F as Ke,a7 as R,t as U,G as He,l as Ze,q as Xe,f as Je,E as Qe}from"./vue-core-Di3IuVqe.js";import{u as Ye}from"./useAgGridConfig-Dp3DkgaV.js";import{u as et}from"./useLigneEntryEpinglee-Bizt7YJJ.js";import"./cjs-helpers-psZwOBky.js";import"./vue-cal-DKMVGERa.js";import"./moment-BeHQNF8T.js";const tt={class:"carte-wrapper"},at={key:0,class:"empty-overlay"},lt={__name:"CarteTournee",props:{visites:{type:Array,default:()=>[]}},setup(E){const q=E,N=C(null);let u=null,f=null,x=null;const L=I(()=>(q.visites||[]).filter(l=>{const r=Number(l.latitude),c=Number(l.longitude);return Number.isFinite(r)&&Number.isFinite(c)&&r!==0&&c!==0})),$={visitee:"#10b981",refus:"#ef4444",absent:"#f59e0b",reportee:"#6366f1",prevue:"#94a3b8"},A={visitee:"Visitée",refus:"Refusée",absent:"Absent",reportee:"Reportée",prevue:"Prévue"},T=(l,r)=>{const h=`
    <div style="
      background: ${$[l]||$.prevue};
      color: white;
      width: 32px;
      height: 32px;
      border-radius: 50% 50% 50% 0;
      transform: rotate(-45deg);
      display: flex;
      align-items: center;
      justify-content: center;
      box-shadow: 0 2px 6px rgba(0,0,0,0.3);
      border: 2px solid white;
    ">
      <span style="transform: rotate(45deg); font-weight: 700; font-size: 13px">${r||"?"}</span>
    </div>
  `;return B.divIcon({html:h,className:"marker-tournee",iconSize:[32,32],iconAnchor:[16,32],popupAnchor:[0,-32]})},a=l=>{const r=A[l.statut_visite]||l.statut_visite,c=l.client_tel||l.client_gsm,h=l.client_ville?`<div style="color:#64748b;font-size:12px">${l.client_ville}</div>`:"",o=c?`<div style="font-size:12px">📞 <a href="tel:${c}">${c}</a></div>`:"",p=l.montant_ttc>0?`<div style="margin-top:4px;font-size:12px">CA : <strong>${Number(l.montant_ttc).toFixed(2)} MAD</strong></div>`:"",V=l.geoloc_accuracy>0?`<div style="margin-top:6px;font-size:11px;color:#94a3b8">Précision ±${Math.round(l.geoloc_accuracy)} m</div>`:"",g=l.geoloc_at?`<div style="font-size:11px;color:#94a3b8">${new Date(l.geoloc_at).toLocaleString("fr-FR")}</div>`:"";return`
    <div style="min-width: 180px">
      <div style="font-weight:600;font-size:14px">${l.client_nom||l.code_client||"?"}</div>
      ${h}
      ${o}
      <div style="margin-top:6px"><span style="background:${$[l.statut_visite]||$.prevue};color:#fff;padding:2px 6px;border-radius:4px;font-size:11px;font-weight:600">Visite ${l.ordre} · ${r}</span></div>
      ${p}
      ${V}
      ${g}
    </div>
  `},v=()=>{if(!u)return;f?f.clearLayers():f=B.layerGroup().addTo(u),x&&(u.removeLayer(x),x=null);const l=[];for(const c of L.value){const h=Number(c.latitude),o=Number(c.longitude),p=B.marker([h,o],{icon:T(c.statut_visite,c.ordre)});p.bindPopup(a(c)),p.addTo(f),l.push([h,o])}const r=L.value.slice().sort((c,h)=>(c.ordre||0)-(h.ordre||0)).map(c=>[Number(c.latitude),Number(c.longitude)]);r.length>=2&&(x=B.polyline(r,{color:"#0ea5e9",weight:3,opacity:.6,dashArray:"5, 8"}).addTo(u)),l.length>0&&u.fitBounds(B.latLngBounds(l),{padding:[40,40],maxZoom:14})};return Y(()=>{u=B.map(N.value,{center:[33.5731,-7.5898],zoom:6}),B.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",{attribution:"&copy; OpenStreetMap",maxZoom:19}).addTo(u),v()}),Ue(()=>{x&&u.removeLayer(x),f&&f.clearLayers(),u&&(u.remove(),u=null)}),ee(()=>q.visites,v,{deep:!0}),(l,r)=>(b(),z("div",tt,[n("div",{ref_key:"mapEl",ref:N,class:"map-el"},null,512),r[1]||(r[1]=Oe('<div class="legende" data-v-eba6dbe3><div class="legende-item" data-v-eba6dbe3><span class="dot dot-visitee" data-v-eba6dbe3></span> Visitée </div><div class="legende-item" data-v-eba6dbe3><span class="dot dot-refus" data-v-eba6dbe3></span> Refus </div><div class="legende-item" data-v-eba6dbe3><span class="dot dot-absent" data-v-eba6dbe3></span> Absent </div><div class="legende-item" data-v-eba6dbe3><span class="dot dot-reportee" data-v-eba6dbe3></span> Reportée </div><div class="legende-item" data-v-eba6dbe3><span class="dot dot-prevue" data-v-eba6dbe3></span> Non capturée </div></div>',1)),L.value.length===0?(b(),z("div",at,[...r[0]||(r[0]=[n("i",{class:"pi pi-map",style:{"font-size":"32px",color:"#94a3b8"}},null,-1),n("p",null,"Aucune position capturée pour les visites de cette tournée.",-1),n("p",{style:{"font-size":"13px"}},' Le vendeur doit cliquer "Capturer position" sur chaque visite côté mobile. ',-1)])])):D("",!0)]))}},ot=Fe(lt,[["__scopeId","data-v-eba6dbe3"]]);function it(E,q){const{modeModificationRef:N,gridApiRef:u,rowsRef:f,applyClient:x,canEditRow:L,fieldName:$="code_client",focusColAfter:A="commentaire",rowKey:T="id_visite",editorParams:a={}}=q,v=I(()=>{const o=new Map;for(const p of E.value||[])o.set(p.value,p.text||p.value);return o}),l=o=>!N.value||!o?!1:L?L(o):!0;return{clientFormatMap:v,columnPartialDef:{editable:o=>l(o.data),cellEditor:"agRichSelectCellEditor",cellEditorParams:()=>({values:E.value?.map(o=>o.value)||[],filterList:!0,searchType:"matchAny",highlightMatch:!0,cellHeight:38,valueListMaxHeight:320,valueListMaxWidth:480,formatValue:o=>v.value.get(o)||o||"",...a}),valueSetter:o=>{const p=o.newValue||"";return p===o.oldValue?!1:(o.data[$]=p,!0)},cellRenderer:o=>{const p=o.value||"",V=l(o.data);return`<div class="code-cell"><span class="code-cell-text">${p||(V?'<span style="color:#9ca3af;font-style:italic;">Cliquez...</span>':"")}</span><i class="pi pi-chevron-down code-cell-chevron"></i></div>`},cellStyle:o=>{const p={padding:"4px 8px",display:"flex",alignItems:"center",justifyContent:"center"};return l(o.data)?{...p,cursor:"pointer"}:p}},prewarmRichSelect:()=>{const o=()=>{const g=u.value;if(!g||!f?.value?.length||!E.value?.length)return!1;try{return g.startEditingCell({rowIndex:0,colKey:$}),g.stopEditing(!0),!0}catch{return!1}};let p=0;const V=setInterval(()=>{(o()||++p>20)&&clearInterval(V)},250)},handleClientSelected:async o=>{if(!((o?.colDef?.field||o?.column?.getColId?.())===$&&o?.newValue&&o.newValue!==o.oldValue))return!1;const g=o.data?.[T];let w=f.value.findIndex(k=>k[T]===g);if(w<0&&typeof o.node?.rowIndex=="number"&&(w=o.node.rowIndex),w<0||w>=f.value.length)return!1;let P=null;try{P=(await y.post(`${s.lienApi}/unclient/${s.db}/${encodeURIComponent(o.newValue)}`)).data||null}catch{}if(!P){const k=E.value?.find(G=>G.value===o.newValue);k&&(P={code_client:k.value,nom:(k.text||"").split(" | ").slice(1).join(" | ")||k.text})}if(!P)return!0;try{await x(P,w,o.data)}catch{}return await Ge(),u.value&&(u.value.refreshCells({force:!0}),A&&(u.value.ensureIndexVisible(w),u.value.setFocusedCell(w,A),setTimeout(()=>{u.value?.startEditingCell({rowIndex:w,colKey:A})},50))),!0}}}const st={key:0,class:"w-full flex flex-col overflow-hidden gap-1 p-1",style:{height:"calc(100vh - 108px)"}},nt={class:"w-full flex flex-wrap items-start md:flex-row justify-start gap-3"},rt={key:3},ut={key:6,class:"flex items-center",style:{"margin-left":"auto",gap:"2px","margin-right":"4px"}},ct={style:{"min-width":"54px","text-align":"center",color:"#6b7280"}},dt={class:"flex flex-col h-full"},pt={class:"p-3 bg-white rounded-lg mb-3 shrink-0"},mt={class:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-6 gap-4"},vt={class:"flex items-end sm:col-span-2 lg:col-span-2",style:{gap:"8px"}},ft={class:"field",style:{flex:"1","min-width":"0"}},gt={class:"field"},_t={class:"field"},bt={class:"field"},ht={class:"flex items-center mb-1",style:{gap:"6px"}},yt={class:"field"},xt={class:"flex items-center mb-1",style:{gap:"6px"}},wt={class:"field sm:col-span-2 lg:col-span-6"},Ct={class:"bg-white rounded-lg flex-1 flex flex-col overflow-hidden"},$t={class:"flex items-center justify-between p-3 shrink-0"},kt={class:"flex gap-2 items-center"},Dt={class:"text-omag font-semibold"},Vt={class:"flex-1 min-h-0 px-3 pb-3"},St={key:0,class:"ag-theme-quartz h-full"},At={key:1,class:"h-full"},Ut={__name:"TourneeLignes",props:{ndoc:{type:[String,Number],default:""},listeNdocs:{type:Array,default:()=>[]}},emits:["close","naviguer"],setup(E,{emit:q}){const{confirmAction:N,showError:u,showSuccess:f,showWarn:x}=ze(),{textValueSetter:L}=Ye(),$=E,A=q,T=C($.ndoc),a=C(null),v=C([]),l=C(!1),r=C(!1),c=C(null),h=C(-1),o=C(),p=C(null),V=C([]),g=Qe({lecture:!1,ajout:!1,modif:!1,supp:!1}),w=it(V,{modeModificationRef:l,gridApiRef:p,rowsRef:v,rowKey:"id_visite",applyClient:(e,t,i)=>{i.client_nom=e.nom||"",i.client_tel=e.tel||e.gsm||"",i.client_ville=""}}),P={id_visite:0,id_tournee:0,ordre:0,code_client:"",client_nom:"",client_tel:"",client_ville:"",statut_visite:"prevue",montant_ttc:0,montant_encaisse:0,commentaire:""},{pinnedTopData:k,interceptEntryRow:G,isLigneFantome:te,assurerLigneFantome:ae,filtrerPourSauvegarde:le,rowDragFn:oe,rowClassRules:ie}=et(v,P,{modeModification:l,entete:a,indexLigneRef:h,ligneSelectionneeRef:c,champCode:"code_client",chargerArticleComplet:async e=>{try{const i=await y.post(`${s.lienApi}/unclient/${s.db}/${encodeURIComponent(e)}`);if(i.data)return{...i.data,code_client:i.data.code_client||e}}catch{}const t=V.value?.find(i=>i.value===e);return t?{code_client:t.value,nom:(t.text||"").split(" | ").slice(1).join(" | ")||t.text}:{code_client:e}},appliquerArticle:e=>{const t=c.value;t&&(t.code_client=e.code_client||"",t.client_nom=e.nom||"",t.client_tel=e.tel||e.gsm||"",t.client_ville="")}}),se=[{value:"VS",label:"Vente directe (livraison immédiate)"},{value:"PV",label:"Pré-vente (livraison ultérieure)"},{value:"MIX",label:"Mixte"}],ne={planifiee:"Planifiée",chargee:"Chargée",en_cours:"En cours",cloturee:"Clôturée"},re=I(()=>ne[a.value?.statut]||a.value?.statut),ue=I(()=>v.value.filter(e=>!0).length),Z=I(()=>({planifiee:{bg:"#6c757d",text:"#ffffff"},chargee:{bg:"#0EA5E9",text:"#ffffff"},en_cours:{bg:"#F59E0B",text:"#000000"},cloturee:{bg:"#10B981",text:"#ffffff"}})[a.value?.statut]||{bg:"#64748b",text:"#ffffff"}),W=C("liste"),ce=[{value:"liste",label:"Liste",icon:"pi pi-list"},{value:"carte",label:"Carte",icon:"pi pi-map"}],de=I(()=>{const e=[];return a.value?.statut==="cloturee"&&e.push({label:"Rouvrir la tournée",icon:"pi pi-undo",command:De,disabled:!g.modif}),e.push({label:"Supprimer la tournée",icon:"pi pi-trash",command:xe,disabled:!g.supp}),e}),pe={sortable:!1,filter:!1,resizable:!0,suppressHeaderMenuButton:!0},me=I(()=>({singleClickEdit:!0,stopEditingWhenCellsLoseFocus:!0,rowClassRules:ie,rowDragManaged:l.value,rowDragEntireRow:l.value,suppressRowDrag:!l.value,onRowDragEnd:()=>{if(!p.value)return;const e=[];p.value.forEachNode((t,i)=>{t.data&&(t.data.ordre=i+1,e.push(t.data))}),v.value=e},animateRows:!0})),ve=I(()=>[{field:"ordre",headerName:"#",width:70,editable:!1,rowDrag:oe,cellRenderer:e=>e.data?._isFantome?"":e.node.rowIndex+1},{field:"code_client",headerName:"Code client",width:180,filter:"agTextColumnFilter",floatingFilter:!1,suppressHeaderFilterButton:!1,suppressMenu:!0,...w.columnPartialDef},{field:"client_nom",headerName:"Nom client",flex:1,minWidth:200},{field:"client_tel",headerName:"Téléphone",width:140},{field:"client_ville",headerName:"Ville",width:140},{field:"statut_visite",headerName:"Statut visite",width:130,valueFormatter:e=>({prevue:"Prévue",visitee:"Visitée",refus:"Refus",absent:"Absent",reportee:"Reportée"})[e.value]||e.value},{field:"montant_ttc",headerName:"CA TTC",width:110,valueFormatter:e=>(e.value||0).toFixed(2)},{field:"montant_encaisse",headerName:"Encaissé",width:110,valueFormatter:e=>(e.value||0).toFixed(2)},{field:"commentaire",headerName:"Commentaire",flex:1,minWidth:200,editable:()=>l.value,valueSetter:L}]),fe=e=>{p.value=e.api},ge=e=>{c.value=e.data,h.value=v.value.findIndex(t=>t===e.data)},_e=async e=>{await G(e)||await w.handleClientSelected(e)},M=async()=>{l.value=!1,r.value=!1;try{const[e,t]=await Promise.all([y.post(`${s.lienApi}/unetournee/${s.db}/${T.value}`),y.post(`${s.lienApi}/tourneeVisites/${s.db}/${T.value}`)]);a.value=e.data||{},v.value=t.data||[],ae()}catch(e){u("Erreur chargement tournée : "+(e.response?.data?.message||e.message))}},{totalListe:K,positionCourante:H,naviguer:X}=je({listeNdocs:I(()=>$.listeNdocs),ndoc:T,charger:M,estEnEdition:r,onNaviguer:e=>A("naviguer",e)}),be=async()=>{try{const t=(await y.post(`${s.lienApi}/verifierDroit/${s.state.dbCommun6}`,{id_utilisateur:s.userId,id_page:618,mail:s.state.userCloud.mail})).data;t&&Object.keys(t).length>0&&(g.lecture=t.lecture,g.ajout=t.ajout,g.modif=t.modif,g.supp=t.supp)}catch{}};Y(async()=>{await be();const[,e]=await Promise.all([M(),Pe("client")]);V.value=e||[],v.value.length===0&&a.value?.statut==="planifiee"&&(l.value=!0,r.value=!0),w.prewarmRichSelect()}),ee(()=>a.value?.IDcommercial,async e=>{if(!(!l.value||!e)&&!(a.value.IDsecteur_geo>0&&a.value.id_depot_camion>0))try{const i=(await y.post(`${s.lienApi}/uncommercial/${s.db}/${e}`)).data;if(!i)return;if(!a.value.id_depot_camion&&i.IDdepot){const d=await y.post(`${s.lienApi}/undepot/${s.db}/${i.IDdepot}`);(d.data?.est_mobile===!0||d.data?.est_mobile===1)&&(a.value.id_depot_camion=i.IDdepot)}if(!a.value.IDsecteur_geo){const F=((await y.post(`${s.lienApi}/secteur_geo/${s.db}`)).data||[]).find(O=>O.IDcommercial===e||O.IDcommercial==e);F&&(a.value.IDsecteur_geo=F.IDsecteur_geo)}}catch{}});const he=()=>{l.value=!0,r.value=!0},ye=async()=>{l.value=!1,r.value=!1,await M()},J=async()=>{try{s.state.afficher_in_progress=!0;const t=le(v.value).map((d,S)=>({id_tournee:a.value.id_tournee,ordre:S+1,code_client:d.code_client||"",statut_visite:d.statut_visite||"prevue",heure_arrivee:d.heure_arrivee||null,heure_depart:d.heure_depart||null,latitude:d.latitude||0,longitude:d.longitude||0,nbonc:d.nbonc||0,nbonlivr:d.nbonlivr||0,nfacturec:d.nfacturec||0,npaiementc:d.npaiementc||0,montant_ttc:d.montant_ttc||0,montant_encaisse:d.montant_encaisse||0,commentaire:d.commentaire||""})),i={id_tournee:a.value.id_tournee,date_tournee:a.value.date_tournee,IDcommercial:a.value.IDcommercial||0,IDsecteur_geo:a.value.IDsecteur_geo||0,id_depot_camion:a.value.id_depot_camion||0,mode_vente:a.value.mode_vente||"VS",statut:a.value.statut||"planifiee",nechange_charge:a.value.nechange_charge||0,nechange_retour:a.value.nechange_retour||0,km_depart:a.value.km_depart||0,km_retour:a.value.km_retour||0,observation:a.value.observation||"",id_utilisateur:a.value.id_utilisateur||0};a.value.heure_depart&&(i.heure_depart=a.value.heure_depart),a.value.heure_retour&&(i.heure_retour=a.value.heure_retour),await y.post(`${s.lienApi}/enregistrerTournee/${s.db}/${a.value.id_tournee}`,{jsonEntete:i,jsonLignes:t}),l.value=!1,r.value=!1,await M(),f("Enregistrement réussi")}catch(e){u("Erreur d'enregistrement : "+(e.response?.data?.message||e.message))}finally{s.state.afficher_in_progress=!1}},xe=async()=>{if(await N({message:"Voulez-vous vraiment supprimer cette tournée ?"}))try{await y.post(`${s.lienApi}/supprimerTournee/${s.db}/${a.value.id_tournee}`),f("Suppression réussie"),A("close")}catch(t){u("Erreur de suppression : "+(t.response?.data?.message||t.message))}},we=()=>{if(!c.value||te(c.value)){x("Sélectionner d'abord une visite");return}v.value.splice(h.value,1),c.value=null,h.value=-1},Ce=async()=>{if(!a.value.IDsecteur_geo){x("Sélectionner d'abord un secteur");return}await J();try{const e=await y.post(`${s.lienApi}/tourneeImporterClientsSecteur/${s.db}/${a.value.id_tournee}`,{id_secteur:a.value.IDsecteur_geo});f(`${e.data?.lignes_ajoutees||0} client(s) ajouté(s) à la tournée`),l.value=!0,r.value=!0,await M()}catch(e){u("Erreur import : "+(e.response?.data?.message||e.message))}},$e=async()=>{if(!a.value.id_depot_camion){x("Sélectionner d'abord un camion");return}if(await N({message:"Créer un bon de charge camion lié à cette tournée ?"}))try{const i=((await y.post(`${s.lienApi}/depot/${s.db}`)).data||[]).filter(F=>!F.est_mobile);if(i.length===0){u("Aucun dépôt central trouvé");return}const d=i[0].IDdepot,S=await y.post(`${s.lienApi}/tourneePreparerCharge/${s.db}/${a.value.id_tournee}`,{annee_fiscale:s.state.annee_fiscale,depot_source:d});S.data?.nechange?(f(S.data.message||"Bon de charge créé"),await M()):x(S.data?.message||"Aucun bon créé")}catch(t){u("Erreur préparation : "+(t.response?.data?.message||t.message))}},ke=async()=>{const e=await Le(()=>import("./BonChargeCamion-n7cMHfKp.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60]));Be({id:"BonChargeCamion",text:`Bon de charge N°${a.value.nechange_charge}`,iconFermer:!0,content:e.default})},De=async()=>{const e=Number(a.value?.nechange_retour)||0;let t="Rouvrir cette tournée clôturée ?";if(e>0?t+=`

Le bon de retour brouillon N°${e} sera supprimé, ainsi que les écarts enregistrés. Si le bon est déjà validé, la réouverture sera bloquée.`:t+=`

Les écarts enregistrés seront supprimés.`,!!await N({message:t,header:"Confirmation"}))try{const d=await y.post(`${s.lienApi}/tourneeRouvrir/${s.db}/${a.value.id_tournee}`);f(`Tournée rouverte (statut : ${d.data?.nouveau_statut||"en_cours"})`),await M()}catch(d){const S=d.response?.data?.message||d.message;u("Réouverture impossible : "+S)}},Ve=()=>{A("close")};return(e,t)=>{const i=Re,d=Ie,S=Me,F=Te,O=Ee,Se=Ne,Ae=We("ag-grid-vue");return a.value?(b(),z("div",st,[n("div",nt,[r.value?D("",!0):(b(),j(i,{key:0,label:"Modifier",text:"",icon:"pi pi-pencil mr-2",onClick:he,disabled:!g.modif||a.value.statut==="cloturee"},null,8,["disabled"])),!r.value&&a.value.statut==="planifiee"?(b(),j(i,{key:1,label:"Préparer chargement",text:"",icon:"pi pi-truck mr-2",onClick:$e,disabled:!a.value.id_depot_camion},null,8,["disabled"])):D("",!0),!r.value&&a.value.nechange_charge>0?(b(),j(i,{key:2,label:`Voir bon de charge N°${a.value.nechange_charge}`,text:"",icon:"pi pi-external-link mr-2",onClick:ke},null,8,["label"])):D("",!0),r.value?D("",!0):(b(),z("div",rt,[_(i,{label:"Actions",text:"",icon:"pi pi-cog mr-2",onClick:t[0]||(t[0]=m=>o.value.toggle(m))}),_(d,{ref_key:"menu",ref:o,model:de.value,popup:!0},null,8,["model"])])),r.value?D("",!0):(b(),j(i,{key:4,label:"Retour",text:"",icon:"pi pi-arrow-left mr-2",onClick:Ve})),r.value?(b(),z(Ke,{key:5},[_(i,{label:"Enregistrer",text:"",icon:"pi pi-save mr-2",onClick:J}),_(i,{label:"Annuler",text:"",icon:"pi pi-times mr-2",onClick:ye})],64)):D("",!0),!r.value&&R(K)>1?(b(),z("div",ut,[_(i,{icon:"pi pi-chevron-left",text:"",rounded:"",disabled:R(H)<=1,onClick:t[1]||(t[1]=m=>R(X)(-1)),title:"Tournée précédente (Alt + ←)"},null,8,["disabled"]),n("span",ct,U(R(H))+" / "+U(R(K)),1),_(i,{icon:"pi pi-chevron-right",text:"",rounded:"",disabled:R(H)>=R(K),onClick:t[2]||(t[2]=m=>R(X)(1)),title:"Tournée suivante (Alt + →)"},null,8,["disabled"])])):D("",!0)]),n("div",dt,[n("div",pt,[n("div",mt,[n("div",vt,[_(qe,{label:"N°",value:a.value.id_tournee},null,8,["value"]),n("div",ft,[t[9]||(t[9]=n("label",{class:"block mb-1"},"Date",-1)),_(S,{size:"small",modelValue:a.value.date_tournee,"onUpdate:modelValue":t[3]||(t[3]=m=>a.value.date_tournee=m),disabled:!l.value,"input-class":"w-full"},null,8,["modelValue","disabled"])])]),n("div",gt,[t[10]||(t[10]=n("label",{class:"block mb-1"},"Vendeur",-1)),_(F,{modelValue:a.value.IDcommercial,"onUpdate:modelValue":t[4]||(t[4]=m=>a.value.IDcommercial=m),table:"commercial",placeholder:"Sélectionner",size:"small",class:"w-full",disabled:!l.value},null,8,["modelValue","disabled"])]),n("div",_t,[t[11]||(t[11]=n("label",{class:"block mb-1"},"Secteur",-1)),_(F,{modelValue:a.value.IDsecteur_geo,"onUpdate:modelValue":t[5]||(t[5]=m=>a.value.IDsecteur_geo=m),table:"secteur_geo",placeholder:"Sélectionner",size:"small",class:"w-full",disabled:!l.value},null,8,["modelValue","disabled"])]),n("div",bt,[n("div",ht,[t[12]||(t[12]=n("label",null,"Camion",-1)),_(Q,{text:"Dépôt mobile (camion) où le stock de la tournée est chargé. Seuls les dépôts <b>mobiles</b> sont proposés."})]),_(F,{modelValue:a.value.id_depot_camion,"onUpdate:modelValue":t[6]||(t[6]=m=>a.value.id_depot_camion=m),table:"depot",filters:{est_mobile:1},placeholder:"Sélectionner camion",size:"small",class:"w-full",disabled:!l.value},null,8,["modelValue","disabled"])]),n("div",yt,[n("div",xt,[t[13]||(t[13]=n("label",null,"Mode",-1)),_(Q,{text:"<b>Vente directe</b> : livraison et encaissement immédiats depuis le camion. <b>Pré-vente</b> : prise de commande, livraison ultérieure. <b>Mixte</b> : les deux."})]),_(O,{modelValue:a.value.mode_vente,"onUpdate:modelValue":t[7]||(t[7]=m=>a.value.mode_vente=m),options:se,"option-label":"label","option-value":"value",size:"small",class:"w-full",disabled:!l.value},null,8,["modelValue","disabled"])]),n("div",wt,[t[14]||(t[14]=n("label",{class:"block mb-1"},"Statut",-1)),n("span",{class:"px-3 py-1 rounded font-semibold",style:He({backgroundColor:Z.value.bg,color:Z.value.text,display:"inline-block"})},U(re.value),5)])])]),n("div",Ct,[n("div",$t,[n("div",kt,[_(Se,{modelValue:W.value,"onUpdate:modelValue":t[8]||(t[8]=m=>W.value=m),options:ce,"option-label":"label","option-value":"value",size:"small","allow-empty":!1},{option:Ze(m=>[n("i",{class:Xe(m.option.icon),style:{"margin-right":"4px"}},null,2),Je(" "+U(m.option.label),1)]),_:1},8,["modelValue"]),l.value?(b(),j(i,{key:0,icon:"pi pi-trash",text:"",onClick:we,title:"Supprimer la visite sélectionnée",style:{color:"#ef4444 !important"}})):D("",!0),l.value&&a.value.IDsecteur_geo>0?(b(),j(i,{key:1,icon:"pi pi-users",text:"",label:"Importer clients du secteur",onClick:Ce})):D("",!0)]),n("div",Dt,U(ue.value)+" visite(s)",1)]),n("div",Vt,[W.value==="liste"?(b(),z("div",St,[(b(),j(Ae,{key:l.value?"edit":"view",localeText:e.$agGridLocale,rowData:v.value,pinnedTopRowData:R(k),columnDefs:ve.value,defaultColDef:pe,gridOptions:me.value,onGridReady:fe,onRowClicked:ge,onCellValueChanged:_e,class:"ag-theme-quartz",style:{height:"100%",width:"100%"}},null,8,["localeText","rowData","pinnedTopRowData","columnDefs","gridOptions"]))])):(b(),z("div",At,[_(ot,{visites:v.value},null,8,["visites"])]))])])])])):D("",!0)}}};export{Ut as default};
