import{a5 as Xe,b as ye,B as xe,y as Ce,n as Ye,f as Qe,a6 as Ze,g as et}from"./primevue-CfIk0_DY.js";import{a as c,w as we,o as Se,y as w,b as m,c as E,k as _,l as $,v as d,d as r,p as h,f as te,a7 as y,t as R,E as _e,n as tt,j as at,H as lt,F as de}from"./vue-core-Di3IuVqe.js";import{_ as it,u as Me,w as rt,b as S,s as l,j as st,o as q,S as he}from"./index-BxIwIJfy.js";import{D as ot}from"./DataGrid-CoMfrBJA.js";import{S as nt}from"./ag-grid-B5G7j3Qp.js";import{P as ut,R as ct}from"./RailTiers-C3DvZy3z.js";import{N as dt}from"./NumeroChip-QCXXOqUM.js";import{S as pt}from"./SelectEmployes-DNkrC5Rv.js";import{a as mt}from"./useAutoPiecesJointes-D0rPgWqP.js";import{u as ft}from"./usePagerDetail-BeqYPv-1.js";import{u as vt}from"./useLigneSaisieLibre-ts6qLXeA.js";import{u as bt}from"./useStableRowId-BwuXNBwn.js";import"./cjs-helpers-psZwOBky.js";import"./vue-cal-DKMVGERa.js";import"./moment-BeHQNF8T.js";import"./useAgGridConfig-Dp3DkgaV.js";import"./HistoriqueDocument-jyEUC_ON.js";import"./PiecesJointes-BcNdv7mw.js";import"./useLienFichier-BJZ-0upj.js";import"./Commentaires-CvKsZ8LO.js";import"./ComboDynamique-BzWI4ISP.js";import"./useColonnesPreferences-DA6gXbLc.js";import"./vuedraggable.umd-D3ZCcGIp.js";const gt={class:"flex items-stretch h-full"},ht={class:"w-full"},yt={class:"sticky top-0 z-10 bg-white",style:{padding:"8px","border-bottom":"1px solid #e5e7eb"}},xt={class:"flex flex-wrap items-center",style:{gap:"8px"}},Ct={key:4,class:"flex items-center",style:{gap:"6px","background-color":"#fef9c3","border-left":"3px solid #facc15",padding:"4px 10px","border-radius":"4px",color:"#854d0e","font-size":"12px"}},wt={class:"flex items-center gap-2",style:{"margin-left":"auto"}},St={key:0,class:"flex items-center",style:{gap:"2px","margin-right":"4px"}},_t={style:{"min-width":"54px","text-align":"center",color:"#6b7280"}},Mt={class:"p-3 bg-white rounded-lg mb-2 shrink-0"},It={class:"flex flex-wrap items-end",style:{gap:"12px"}},Tt={class:"flex-none",style:{width:"220px"}},Nt={class:"flex-none",style:{width:"180px"}},kt={class:"flex-none flex items-end",style:{height:"100%"}},Dt={class:"flex flex-wrap items-center",style:{gap:"8px",padding:"0 8px","margin-top":"8px","margin-bottom":"8px"}},$t={class:"flex items-center",style:{gap:"8px"}},Rt={class:"kpi-pill",style:{"background-color":"#e0e7ff",color:"#3730a3"}},Et={class:"kpi-pill",style:{"background-color":"#dcfce7",color:"#166534"}},Lt={class:"kpi-pill",style:{"background-color":"#fef3c7",color:"#92400e"}},At={key:0,class:"kpi-pill",style:{"background-color":"#f3e8ff",color:"#6b21a8"},title:"Surprime d'option prélevée au salarié — incluse dans la Cot. totale, mais absente du fichier EDI"},Ft={style:{position:"relative",height:"calc(100vh - 300px)",width:"100%","margin-top":"12px"}},Vt={key:0,class:"filigrane-texte filigrane-danger"},jt=`
<b>Fichier de télédéclaration CIMR (.TXT)</b><br>
Format ASCII à largeur fixe : <b>190 caractères par ligne</b>, <b>1 ligne par salarié</b>,
un seul adhérent (société) par fichier.<br><br>
<b>Champs qui portent la logique métier :</b><br>
• <b>Catégorie</b> (2 car.) — encode l'option de retraite :<br>
&nbsp;&nbsp;– Régime normal : <b>00-34</b><br>
&nbsp;&nbsp;– Mousabbak (55 ans) : <b>35-39</b> / <b>45-49</b><br>
&nbsp;&nbsp;– Moubakkir (50 ans) : <b>50-59</b> / <b>60-69</b><br>
&nbsp;&nbsp;<i>(2ᵉ plage = salaire trimestriel &gt; 18 000 DH)</i><br>
• <b>Taux</b> (4 car.) — part salariale ×100 : <b>0300</b>=3 % … <b>1200</b>=12 %<br>
• <b>Salaire soumis</b> (10 car.) — brut trimestriel ×100<br>
• <b>Type ligne</b> — 2 = salarié actif, 7 = sortant (avec date de sortie)<br>
• Identité : Nom (25), Prénom (25), CNIE, Mat. CNSS, dates, GSM, e-mail…<br><br>
⚠️ La <b>surprime d'option</b> (colonnes <i>Taux surp.</i> / <i>Mt. surprime</i>) est incluse
dans la <b>Cot. totale</b> (= ce que la CIMR prélève réellement), mais n'a <b>aucun champ dans le
fichier</b> : elle n'est <b>jamais</b> écrite dans le .TXT. Seul le taux de base (champ Taux) y figure ;
la CIMR recalcule la surprime de son côté à partir de la catégorie.
`,Pt={__name:"cimrLignes",props:{ndoc:{type:[String,Number],required:!0},listeNdocs:{type:Array,default:()=>[]}},emits:["close","naviguer"],setup(pe,{emit:X}){const{showError:x,showSuccess:Y,showInfo:j,showWarn:k,confirmAction:Q}=Me(),M=pe,Z=X,A=c(M.ndoc),i=c({}),g=c([]),C=c(),F=c(),V=c(),v=c(!1),f=c(!1),J=c(!1),H=c("historique"),W=c(0);we(()=>i.value?.Id_declaration_cimr,async e=>{e==null||e===""||await mt("DeclarationCIMR",e)&&(H.value="pj")},{immediate:!0});const P=c(!1),z=c(!1),G=c(!1),O=c([]),ie=w(()=>{const e=new Map;for(const t of O.value||[])e.set(t.value,t.text||t.value);return e}),L=_e({lecture:!1,ajout:!1,modif:!1,supp:!1}),ae=[{Id:1,Libelle:"T1 (Janvier - Mars)"},{Id:2,Libelle:"T2 (Avril - Juin)"},{Id:3,Libelle:"T3 (Juillet - Septembre)"},{Id:4,Libelle:"T4 (Octobre - Décembre)"}],U={Id_declaration_cimr:0,Matricule:"",Numero_cimr:"",Nom:"",Prenom:"",TauxS:0,TauxP:0,Categorie:"",Sexe:"",DateAffiliation:null,DateNaissance:null,DateSortie:null,SituationFamiliale:"",NbEnfants:0,SalaireContribution:0,MontantSalarial:0,MontantPatronal:0,TauxSurprime:0,MontantSurprime:0,CNIE:"",MatriculeCNSS:"",NumeroGSM:"",AdresseEmail:"",TypeLigne:"2"},re=Object.keys(U),{pinnedTopData:o,onEntryKeyDown:s,isLigneFantome:b,assurerLigneFantome:I,filtrerPourSauvegarde:se,rowClassRules:oe}=vt(g,U,{modeModification:f,aDesDonnees:e=>!!(e?.Matricule||e?.Nom)}),D=bt(),ee=w(()=>g.value.filter(e=>!b(e))),ne=w(()=>ee.value.length),Ie=w(()=>ee.value.reduce((e,t)=>e+(parseFloat(t.SalaireContribution)||0),0)),me=w(()=>ee.value.reduce((e,t)=>e+(parseFloat(t.MontantSurprime)||0),0)),Te=w(()=>ee.value.reduce((e,t)=>e+(parseFloat(t.MontantSalarial)||0)+(parseFloat(t.MontantPatronal)||0)+(parseFloat(t.MontantSurprime)||0),0)),Ne={sortable:!1,filter:!1,resizable:!0,suppressHeaderMenuButton:!0},p=()=>f.value,ke=w(()=>[{field:"Matricule",headerName:"Matricule",width:170,editable:p,cellEditor:"agRichSelectCellEditor",cellEditorParams:()=>({values:O.value?.map(e=>e.value)||[],filterList:!0,searchType:"matchAny",highlightMatch:!0,cellHeight:38,valueListMaxHeight:320,valueListMaxWidth:420,formatValue:e=>ie.value.get(e)||e||""}),cellRenderer:e=>{const t=e.value||"",a=f.value&&!b(e.data);return`<div class="code-cell"><span class="code-cell-text">${t||(a?'<span style="color:#9ca3af;font-style:italic;">Choisir...</span>':"")}</span><i class="pi pi-chevron-down code-cell-chevron"></i></div>`}},{field:"Numero_cimr",headerName:"N° CIMR",width:130,editable:p},{field:"Nom",headerName:"Nom",width:150,editable:p},{field:"Prenom",headerName:"Prénom",width:150,editable:p},{field:"TauxS",headerName:"Taux S",width:90,editable:p,type:"numericColumn",valueFormatter:e=>e.value!=null&&e.value!==""?Number(e.value).toFixed(2):""},{field:"TauxP",headerName:"Taux P",width:90,editable:p,type:"numericColumn",valueFormatter:e=>e.value!=null&&e.value!==""?Number(e.value).toFixed(2):""},{field:"Categorie",headerName:"Catégorie",width:100,editable:p},{field:"Sexe",headerName:"Sexe",width:70,editable:p},{field:"DateAffiliation",headerName:"Affiliation",width:120,editable:p,valueFormatter:e=>e.value?new Date(e.value).toLocaleDateString("fr-FR"):""},{field:"DateNaissance",headerName:"Naissance",width:120,editable:p,valueFormatter:e=>e.value?new Date(e.value).toLocaleDateString("fr-FR"):""},{field:"SituationFamiliale",headerName:"Sit. fam.",width:100,editable:p},{field:"NbEnfants",headerName:"Nb enf.",width:90,editable:p,type:"numericColumn"},{field:"SalaireContribution",headerName:"Salaire contrib.",width:140,editable:p,type:"numericColumn",valueFormatter:e=>e.value!=null&&e.value!==""?q(e.value):""},{field:"MontantSalarial",headerName:"Mt. salarial",width:130,editable:p,type:"numericColumn",valueFormatter:e=>e.value!=null&&e.value!==""?q(e.value):""},{field:"MontantPatronal",headerName:"Mt. patronal",width:130,editable:p,type:"numericColumn",valueFormatter:e=>e.value!=null&&e.value!==""?q(e.value):""},{field:"TauxSurprime",headerName:"Taux surp.",width:100,editable:p,type:"numericColumn",headerTooltip:"Taux de surprime d'option (Moubakkir/Mousabbak), 100% salariale",valueFormatter:e=>e.value!=null&&e.value!==""&&Number(e.value)!==0?Number(e.value).toFixed(2):""},{field:"MontantSurprime",headerName:"Mt. surprime",width:140,editable:p,type:"numericColumn",headerTooltip:"Montant de surprime d'option prélevé au salarié (hors fichier EDI, inclus dans le total prélevé CIMR)",cellStyle:{backgroundColor:"#faf5ff"},valueFormatter:e=>e.value!=null&&e.value!==""&&Number(e.value)!==0?q(e.value):""},{field:"DateSortie",headerName:"Sortie",width:120,editable:p,valueFormatter:e=>e.value?new Date(e.value).toLocaleDateString("fr-FR"):""},{field:"CNIE",headerName:"CNIE",width:110,editable:p},{field:"MatriculeCNSS",headerName:"Mat. CNSS",width:120,editable:p},{field:"NumeroGSM",headerName:"GSM",width:120,editable:p},{field:"AdresseEmail",headerName:"Email",width:180,editable:p},{field:"TypeLigne",headerName:"Type",width:80,editable:p,valueFormatter:e=>e.value==="7"?"Sortie":"Actif"}]),De=w(()=>({rowSelection:{mode:"multiRow",checkboxes:f.value,headerCheckbox:f.value,enableClickSelection:!1},isRowSelectable:e=>f.value&&!b(e.data),singleClickEdit:!0,stopEditingWhenCellsLoseFocus:!0,rowClassRules:oe,enterNavigatesVertically:!0,enterNavigatesVerticallyAfterEdit:!0,animateRows:!0,domLayout:"normal",getRowId:D})),$e=w(()=>[{label:"Générer depuis paie",icon:"pi pi-refresh",command:()=>He(),disabled:!!i.value.Verrouille,visible:v.value},{label:"Générer EDI (fichier CIMR)",icon:"pi pi-file-export",command:()=>We(),visible:!v.value},{separator:!0,visible:!v.value},{label:i.value.Verrouille?"Déverrouiller":"Verrouiller",icon:i.value.Verrouille?"pi pi-unlock":"pi pi-lock",command:()=>qe(),visible:!v.value},{label:"Supprimer",icon:"pi pi-trash",command:()=>Ue(),disabled:!L.supp||!!i.value.Verrouille,visible:!v.value,class:"text-red-500"}]);Se(async()=>{await Re(),L.lecture&&await K();try{O.value=await rt("employe")}catch{O.value=[]}});const Re=async()=>{try{const t=(await S.post(`${l.lienApi}/verifierDroit/${l.state.dbCommun6}`,{id_utilisateur:l.userId,id_page:1505,mail:l.state.userCloud.mail},{headers:{"Content-Type":"application/json"}})).data;t&&Object.keys(t).length>0&&(L.lecture=t.lecture,L.ajout=t.ajout,L.modif=t.modif,L.supp=t.supp)}catch(e){x("Une erreur est survenue : "+(e.response?.data?.message||e.message))}},K=async()=>{l.state.afficher_in_progress=!0;try{const[e,t]=await Promise.all([S.post(`${l.lienApi}/unedeclarationCIMR/${l.db}/${A.value}`),S.post(`${l.lienApi}/LdeclarationCIMR/${l.db}/${A.value}`)]);i.value=e.data||{},g.value=(t.data||[]).map((a,u)=>({...a,nligne:u+1}))}catch(e){x("Une erreur est survenue : "+(e.response?.data?.message||e.message))}finally{l.state.afficher_in_progress=!1}},Ee=async()=>{f.value=!1,v.value=!1,await K()},{totalListe:ue,positionCourante:ce,naviguer:fe}=ft({listeNdocs:w(()=>M.listeNdocs),ndoc:A,charger:Ee,estEnEdition:v,onNaviguer:e=>Z("naviguer",e)}),Le=()=>{if(i.value.Verrouille){k("Déclaration verrouillée. Déverrouillez-la pour modifier.");return}v.value=!0,f.value=!0,I()},Ae=async()=>{f.value=!1,v.value=!1,await K()},Fe=e=>{C.value=e.api},Ve=["Numero_cimr","Nom","Prenom","TauxS","TauxP","Categorie","Sexe","DateAffiliation","DateNaissance","DateSortie","SituationFamiliale","NbEnfants","SalaireContribution","MontantSalarial","MontantPatronal","TauxSurprime","MontantSurprime","CNIE","MatriculeCNSS","NumeroGSM","AdresseEmail","TypeLigne"],ve=(e,t)=>{t.Matricule=e.Matricule;for(const a of Ve)t[a]=e[a]!==void 0&&e[a]!==null?e[a]:U[a]},je=async e=>{if(e?.data&&e.data._isFantome&&delete e.data._isFantome,(e?.colDef?.field||e?.column?.getColId?.())==="Matricule"&&e.newValue&&e.newValue!==e.oldValue)try{const u=(await S.post(`${l.lienApi}/employesPourCIMR/${l.db}`,{matricules:[e.newValue]},{headers:{"Content-Type":"application/json"}})).data?.[0];u&&(ve(u,e.data),await tt(),C.value&&C.value.refreshCells({force:!0}))}catch(a){x("Erreur récupération employé : "+(a.response?.data?.message||a.message))}I()},Pe=()=>{G.value=!0},ze=async e=>{G.value=!1;const t=Array.isArray(e)?e:[];if(t.length!==0)try{l.state.afficher_in_progress=!0;const u=(await S.post(`${l.lienApi}/employesPourCIMR/${l.db}`,{matricules:t},{headers:{"Content-Type":"application/json"}})).data||[],T=new Set(ee.value.map(N=>N.Matricule)),le=g.value.filter(N=>!b(N));for(const N of u){if(T.has(N.Matricule))continue;const B={...U,Id_declaration_cimr:i.value.Id_declaration_cimr};ve(N,B),le.push(B),T.add(N.Matricule)}g.value=le.map((N,B)=>({...N,nligne:B+1})),I()}catch(a){x("Erreur : "+(a.response?.data?.message||a.message))}finally{l.state.afficher_in_progress=!1}},Ge=()=>{if(!C.value)return;const e=C.value.getSelectedRows().filter(a=>!b(a));if(e.length===0){k("Sélectionnez au moins une ligne à supprimer.");return}const t=new Set(e.map(a=>a.nligne));g.value=g.value.filter(a=>!t.has(a.nligne)).map((a,u)=>({...a,nligne:u+1})),I()},be=()=>se(g.value).map(e=>{const t={};for(const a of re)t[a]=e[a]!==void 0&&e[a]!==null?e[a]:U[a];return t.Id_declaration_cimr=i.value.Id_declaration_cimr,t}),Oe=async()=>{try{l.state.afficher_in_progress=!0;const e=parseInt(i.value.Trimestre)||0;if(e>=1&&e<=4){const a=(e-1)*3+1;i.value.Mois=`${a},${a+1},${a+2}`}const t=be();return i.value.Nbpersonne=t.length,i.value.Sbrut=t.reduce((a,u)=>a+(parseFloat(u.SalaireContribution)||0),0),i.value.TotalSalarial=t.reduce((a,u)=>a+(parseFloat(u.MontantSalarial)||0),0),i.value.TotalPatronal=t.reduce((a,u)=>a+(parseFloat(u.MontantPatronal)||0),0),i.value.TotalSurprime=t.reduce((a,u)=>a+(parseFloat(u.MontantSurprime)||0),0),i.value.TotalCotisation=i.value.TotalSalarial+i.value.TotalPatronal+i.value.TotalSurprime,await S.post(`${l.lienApi}/enregistrerCIMR/${l.db}/${A.value}`,{jsonEntete:i.value,jsonLignes:t},{headers:{"Content-Type":"application/json"}}),Y("Enregistrement effectué avec succès"),f.value=!1,v.value=!1,await K(),!0}catch(e){const t=e.response?.data?.message||e.message;return x(`Erreur d'enregistrement : ${t}`),!1}finally{l.state.afficher_in_progress=!1}},Ue=()=>{P.value=!0},Be=async()=>{z.value=!1;try{await S.post(`${l.lienApi}/supprimerDeclarationCIMR/${l.db}/${i.value.Id_declaration_cimr}`),Z("close")}catch(e){const t=e.response?.data?.message||e.message;x(`Erreur : ${t}`)}},qe=async()=>{try{i.value.Verrouille=i.value.Verrouille?0:1,await S.post(`${l.lienApi}/enregistrerCIMR/${l.db}/${A.value}`,{jsonEntete:i.value,jsonLignes:be()},{headers:{"Content-Type":"application/json"}}),Y(i.value.Verrouille?"Déclaration verrouillée":"Déclaration déverrouillée")}catch(e){const t=e.response?.data?.message||e.message;x(`Erreur : ${t}`),await K()}},Je=()=>Z("close"),He=async()=>{if(i.value.Verrouille){k("Déclaration verrouillée — déverrouillez-la avant de régénérer.");return}if(await Q({message:ne.value>0?"Cela va remplacer les lignes existantes par celles issues du calcul de paie. Continuer ?":"Pré-remplir les lignes depuis les calculs de paie du trimestre ?"}))try{l.state.afficher_in_progress=!0;const t=await S.post(`${l.lienApi}/GenererDeclarationCIMR/${l.db}`,{id_declaration_cimr:i.value.Id_declaration_cimr,annee_fiscale:i.value.Annee,trimestre:i.value.Trimestre},{headers:{"Content-Type":"application/json"}});t.data?.success?(await K(),f.value&&I(),Y(t.data.message||"Génération réussie")):x(t.data?.message||"Erreur lors de la génération")}catch(t){const a=t.response?.data?.message||t.message;a.includes("non verrouilles")||a.includes("non verrouillés")?k(a):x(`Erreur : ${a}`)}finally{l.state.afficher_in_progress=!1}},We=async()=>{const e=l.state.enreg_option_paie?.numero_cimr;if(!e){x("Le numéro d'affiliation CIMR de la société est vide (voir Options de paie).");return}if(ne.value===0){k("Aucune ligne à exporter. Générez d'abord la déclaration depuis le calcul de paie.");return}try{l.state.afficher_in_progress=!0;const t=await S.post(`${l.lienApi}/GenererEDICIMR/${l.db}`,{id_declaration_cimr:i.value.Id_declaration_cimr,numero_cimr:e},{responseType:"blob"}),a=`CIMR_${(l.state.enreg_societe.Nom||"Societe").replace(/\s+/g,"_")}_T${i.value.Trimestre}_${i.value.Annee}.TXT`,u=window.URL.createObjectURL(new Blob([t.data])),T=document.createElement("a");T.href=u,T.setAttribute("download",a),document.body.appendChild(T),T.click(),window.URL.revokeObjectURL(u),document.body.removeChild(T),j("Génération du fichier EDI CIMR réussie.")}catch(t){let a="Erreur lors de la génération du fichier EDI.";if(t.response?.data instanceof Blob)try{const u=await t.response.data.text();a=JSON.parse(u).message||a}catch{}else t.response?.data?.message?a=t.response.data.message:t.message&&(a=t.message);x(a)}finally{l.state.afficher_in_progress=!1}};return(e,t)=>{const a=ye,u=xe,T=Ce,le=st,N=Ye,B=Qe,ge=Xe,Ke=Ze;return m(),E("div",gt,[(m(),_(Ke,{key:W.value,class:"flex-1 min-w-0 h-full"},{default:$(()=>[d(ge,{minSize:50},{default:$(()=>[r("div",ht,[r("div",yt,[r("div",xt,[v.value?h("",!0):(m(),_(a,{key:0,onClick:t[0]||(t[0]=n=>Le()),text:"",icon:"pi pi-pencil",label:"Modifier",disabled:!L.modif||i.value.Verrouille},null,8,["disabled"])),v.value?(m(),_(a,{key:1,onClick:t[1]||(t[1]=n=>Oe()),text:"",icon:"pi pi-save",label:"Enregistrer"})):h("",!0),v.value?(m(),_(a,{key:2,onClick:t[2]||(t[2]=n=>Ae()),text:"",icon:"pi pi-times",label:"Annuler"})):h("",!0),d(u,{ref_key:"actionsMenu",ref:F,model:$e.value,popup:!0},null,8,["model"]),d(a,{onClick:t[3]||(t[3]=n=>F.value.toggle(n)),text:""},{default:$(()=>[...t[21]||(t[21]=[r("i",{class:"pi pi-cog mr-2"},null,-1),te(" Actions ",-1),r("i",{class:"pi pi-chevron-down ml-2"},null,-1)])]),_:1}),v.value?h("",!0):(m(),_(a,{key:3,onClick:t[4]||(t[4]=n=>Je()),text:"",icon:"pi pi-arrow-left",label:"Retour"})),v.value?(m(),E("div",Ct,[...t[22]||(t[22]=[r("i",{class:"pi pi-pencil",style:{"font-size":"12px"}},null,-1),r("span",null,[r("strong",null,"Mode édition")],-1)])])):h("",!0),r("div",wt,[!v.value&&y(ue)>1?(m(),E("div",St,[d(a,{icon:"pi pi-chevron-left",text:"",rounded:"",disabled:y(ce)<=1,onClick:t[5]||(t[5]=n=>y(fe)(-1)),title:"Déclaration CIMR précédente (Alt + ←)"},null,8,["disabled"]),r("span",_t,R(y(ce))+" / "+R(y(ue)),1),d(a,{icon:"pi pi-chevron-right",text:"",rounded:"",disabled:y(ce)>=y(ue),onClick:t[6]||(t[6]=n=>y(fe)(1)),title:"Déclaration CIMR suivante (Alt + →)"},null,8,["disabled"])])):h("",!0)])])]),r("div",Mt,[r("div",It,[d(dt,{value:i.value.Id_declaration_cimr},null,8,["value"]),r("div",Tt,[t[23]||(t[23]=r("label",{class:"block mb-1"},"Trimestre",-1)),d(T,{modelValue:i.value.Trimestre,"onUpdate:modelValue":t[7]||(t[7]=n=>i.value.Trimestre=n),options:ae,optionLabel:"Libelle",optionValue:"Id",size:"small",disabled:!f.value,class:"w-full"},null,8,["modelValue","disabled"])]),r("div",Nt,[t[24]||(t[24]=r("label",{class:"block mb-1"},"Date",-1)),d(le,{size:"small",modelValue:i.value.Date,"onUpdate:modelValue":t[8]||(t[8]=n=>i.value.Date=n),disabled:!f.value,"input-class":"w-full"},null,8,["modelValue","disabled"])]),r("div",kt,[d(a,{type:"button",text:"",rounded:"",icon:"pi pi-question-circle",title:"Structure du fichier de télédéclaration CIMR",onClick:t[9]||(t[9]=n=>V.value.toggle(n))})])])]),d(N,{ref_key:"popoverInfo",ref:V},{default:$(()=>[r("div",{class:"text-sm",style:{width:"420px","max-height":"60vh","overflow-y":"auto","line-height":"1.5"},innerHTML:jt})]),_:1},512),r("div",Dt,[f.value?(m(),_(a,{key:0,label:"",text:"",icon:"pi pi-plus-circle",onClick:t[10]||(t[10]=n=>Pe()),title:"Ajouter une ligne (saisie manuelle)",style:{color:"#10b981 !important"}})):h("",!0),f.value?(m(),_(a,{key:1,label:"",text:"",icon:"pi pi-trash",onClick:t[11]||(t[11]=n=>Ge()),title:"Supprimer les lignes cochées",style:{color:"#ef4444 !important"}})):h("",!0),r("span",$t,[r("span",Rt,[t[25]||(t[25]=r("span",{class:"kpi-pill-label"},"Personnes",-1)),r("strong",null,R(ne.value),1)]),r("span",Et,[t[26]||(t[26]=r("span",{class:"kpi-pill-label"},"Salaire contrib.",-1)),r("strong",null,R(y(q)(Ie.value)),1)]),r("span",Lt,[t[27]||(t[27]=r("span",{class:"kpi-pill-label"},"Cot. totale",-1)),r("strong",null,R(y(q)(Te.value)),1)]),me.value>0?(m(),E("span",At,[t[28]||(t[28]=r("span",{class:"kpi-pill-label"},"dont surprime",-1)),r("strong",null,R(y(q)(me.value)),1)])):h("",!0)])]),r("div",Ft,[(m(),_(y(nt),{key:f.value?"cimr-grid-edit":"cimr-grid-read",rowData:g.value,pinnedTopRowData:y(o),columnDefs:ke.value,defaultColDef:Ne,gridOptions:De.value,theme:e.$agGridTheme,localeText:e.$agGridLocale,onGridReady:Fe,onCellValueChanged:je,onCellKeyDown:y(s),class:"ag-theme-quartz",style:{height:"100%",width:"100%"}},null,8,["rowData","pinnedTopRowData","columnDefs","gridOptions","theme","localeText","onCellKeyDown"])),i.value.Verrouille?(m(),E("div",Vt,"VERROUILLÉ")):h("",!0)]),G.value?(m(),_(pt,{key:0,show:G.value,id_affaire:0,id_site:0,onClose:t[12]||(t[12]=n=>G.value=!1),onAjouterLignes:ze},null,8,["show"])):h("",!0),d(B,{visible:P.value,"onUpdate:visible":t[15]||(t[15]=n=>P.value=n),header:"Confirmation de suppression",modal:!0,style:{width:"450px"}},{footer:$(()=>[d(a,{label:"Non",icon:"pi pi-times",onClick:t[13]||(t[13]=n=>P.value=!1),text:""}),d(a,{label:"Oui",icon:"pi pi-check",onClick:t[14]||(t[14]=n=>{P.value=!1,z.value=!0}),class:"p-button-danger",autofocus:""})]),default:$(()=>[t[29]||(t[29]=r("div",{class:"flex flex-column align-items-center p-4"},[r("i",{class:"pi pi-exclamation-triangle mb-3",style:{"font-size":"2rem",color:"var(--red-500)"}}),r("p",null,"Êtes-vous sûr de vouloir supprimer cette déclaration CIMR ?")],-1))]),_:1},8,["visible"]),d(B,{visible:z.value,"onUpdate:visible":t[17]||(t[17]=n=>z.value=n),header:"⚠️ Confirmation finale",modal:!0,style:{width:"450px"}},{footer:$(()=>[d(a,{label:"Annuler",icon:"pi pi-times",onClick:t[16]||(t[16]=n=>z.value=!1),text:""}),d(a,{label:"Supprimer définitivement",icon:"pi pi-trash",onClick:Be,class:"p-button-danger",autofocus:""})]),default:$(()=>[t[30]||(t[30]=r("div",{class:"flex flex-column align-items-center p-4"},[r("i",{class:"pi pi-exclamation-circle mb-3",style:{"font-size":"2rem",color:"#ef4444"}}),r("p",{class:"text-center font-bold",style:{color:"#ef4444"}},"Cette action est irréversible !"),r("p",{class:"text-center mt-2"}," Confirmez-vous la suppression définitive de cette déclaration et de toutes ses lignes ? ")],-1))]),_:1},8,["visible"])])]),_:1}),J.value?(m(),_(ge,{key:0,size:25,minSize:15},{default:$(()=>[d(ut,{onglet:H.value,"onUpdate:onglet":t[18]||(t[18]=n=>H.value=n),onglets:["historique","pj","commentaires"],document:{table:"DeclarationCIMR",colonne:"Id_declaration_cimr",valeur:i.value?.Id_declaration_cimr,doc:"DeclarationCIMR",composantCommentaires:"cimrLignes",titreCommentaires:"cimr"},onClose:t[19]||(t[19]=n=>{J.value=!1,W.value++})},null,8,["onglet","document"])]),_:1})):h("",!0)]),_:1})),J.value?h("",!0):(m(),_(ct,{key:0,onglets:["historique","pj","commentaires"],onOuvrir:t[20]||(t[20]=n=>{n&&(H.value=n),J.value=!0,W.value++})}))])}}},zt=it(Pt,[["__scopeId","data-v-7700aae6"]]),Gt={class:"page-wrapper"},Ot={class:"w-full flex flex-row items-center",style:{gap:"12px",padding:"8px"}},Ut={class:"flex flex-wrap items-center",style:{gap:"12px",padding:"0 8px","margin-bottom":"8px"}},Bt={class:"relative",style:{width:"280px"}},qt={class:"text-xs text-gray-500",style:{"margin-left":"auto"}},Jt={class:"grille-mobile-fix",style:{height:"calc(100vh - 220px)"}},Ht={key:1,class:"p-4 bg-yellow-100 text-yellow-800 border border-yellow-300 rounded"},ga={__name:"cimr",setup(pe){const{showError:X,showInfo:x,showWarn:Y}=Me(),j=c(!1),k=c(null),Q=c(),M=c(),Z=c(null),A=c(),i=c([]),g=c(""),C=_e({lecture:!1,ajout:!1}),F=c(""),V=c(0),v=[{Id:0,Libelle:"Tous les trimestres"},{Id:1,Libelle:"T1 (Jan-Mar)"},{Id:2,Libelle:"T2 (Avr-Jun)"},{Id:3,Libelle:"T3 (Jul-Sep)"},{Id:4,Libelle:"T4 (Oct-Dec)"}],f=w(()=>!V.value||V.value===0?i.value:i.value.filter(o=>parseInt(o.Trimestre)===V.value));we(F,o=>{M.value&&M.value.setGridOption("quickFilterText",o)});const J=w(()=>[{label:"Exporter vers Excel",icon:"pi pi-file-excel",command:()=>U()}]);Se(async()=>{await H(),C.lecture&&await W()});const H=async()=>{try{const s=(await S.post(`${l.lienApi}/verifierDroit/${l.state.dbCommun6}`,{id_utilisateur:l.userId,id_page:1505,mail:l.state.userCloud.mail},{headers:{"Content-Type":"application/json"}})).data;s&&Object.keys(s).length>0&&(C.lecture=s.lecture,C.ajout=s.ajout),C.lecture||(Y("Vous n'avez pas le droit, veuillez consulter l'administrateur"),he("cimr"))}catch(o){X("Une erreur est survenue : "+(o.response?.data?.message||o.message))}finally{l.state.afficher_in_progress=!1}},W=async()=>{l.state.afficher_in_progress=!0;try{j.value=!1;const o=await S.post(`${l.lienApi}/declarationCIMR/${l.db}/${l.state.annee_fiscale}`,{},{headers:{"Content-Type":"application/json"}});i.value=o.data}catch(o){const s=o.response?.data?.message||o.message;X(`Une erreur est survenue : ${s}`)}finally{l.state.afficher_in_progress=!1}},P=async()=>{const o=new Date().getMonth()+1,s=Math.ceil(o/3);try{const I=(await S.post(`${l.lienApi}/AjouterEtRenvoyerdeclarationCIMR/${l.db}`,{annee:l.state.annee_fiscale,trimestre:s},{headers:{"Content-Type":"application/json"}})).data;g.value=I.Id_declaration_cimr,ae()}catch(b){const I=b.response?.data?.message||b.message;X(`Une erreur est survenue : ${I}`)}},z=o=>{M.value=o.api},G=({selectedRows:o})=>{o.length>0&&(Z.value=o[0])},O=w(()=>f.value.map(o=>o.ndoc)),ie=o=>{g.value=o;const s=O.value.indexOf(o);s!==-1&&(k.value=s),l.dispatch("tabs/changeTab",{id:"cimr",newProps:{text:`Déclaration CIMR N°${g.value}`,iconFermer:!1}})},L=({ndoc:o,rowIndex:s})=>{g.value=o,k.value=s,ae()},ae=async()=>{j.value=!0,l.dispatch("tabs/changeTab",{id:"cimr",newProps:{text:`Déclaration CIMR N°${g.value}`,iconFermer:!1}})},U=()=>{if(!Q.value){x("Grille non initialisée");return}if(i.value.length===0){x("Aucune donnée à exporter");return}const s=new Date().toISOString().slice(0,19).replace(/[-:]/g,"").replace("T","_");Q.value.exportToExcel({fileName:`Liste des declarations CIMR_${l.state.enreg_societe.Nom}_Annee_${l.state.annee_fiscale}_${s}.xlsx`,sheetName:"Declarations CIMR"})},re=()=>{j.value=!1,W(),l.dispatch("tabs/changeTab",{id:"cimr",newProps:{text:"Télédéclaration CIMR",iconFermer:!0}}),k.value!=null&&M.value&&setTimeout(()=>{const o=M.value.getDisplayedRowCount();if(o>0){const s=Math.min(k.value,o-1),b=M.value.getDisplayedRowAtIndex(s);b&&(M.value.deselectAll(),b.setSelected(!0),M.value.ensureNodeVisible(b,"middle"))}},100)};return(o,s)=>{const b=ye,I=xe,se=et,oe=Ce;return m(),E(de,null,[j.value?(m(),_(zt,{key:0,ndoc:g.value,"liste-ndocs":O.value,onClose:re,onNaviguer:ie},null,8,["ndoc","liste-ndocs"])):h("",!0),at(r("div",Gt,[r("div",Ot,[d(b,{disabled:!C.ajout,icon:"pi pi-plus-circle",label:"Ajouter",text:"",onClick:s[0]||(s[0]=D=>P()),title:"Nouvelle déclaration CIMR"},null,8,["disabled"]),d(I,{ref_key:"actionsMenu",ref:A,model:J.value,popup:!0},null,8,["model"]),d(b,{onClick:s[1]||(s[1]=D=>A.value.toggle(D)),text:""},{default:$(()=>[...s[6]||(s[6]=[r("i",{class:"pi pi-cog mr-2"},null,-1),te(" Actions ",-1),r("i",{class:"pi pi-chevron-down ml-2"},null,-1)])]),_:1}),d(b,{icon:"pi pi-times",label:"Fermer",text:"",onClick:s[2]||(s[2]=D=>y(he)("cimr"))})]),r("div",Ut,[r("div",Bt,[s[7]||(s[7]=r("i",{class:"pi pi-search absolute left-3 top-1/2 -translate-y-1/2 text-gray-400",style:{"font-size":"0.85rem"}},null,-1)),d(se,{modelValue:F.value,"onUpdate:modelValue":s[3]||(s[3]=D=>F.value=D),placeholder:"Rechercher (trimestre, période...)",class:"w-full",style:{"padding-left":"2rem"},size:"small"},null,8,["modelValue"]),F.value?(m(),E("i",{key:0,class:"pi pi-times-circle absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 cursor-pointer hover:text-gray-600",style:{"font-size":"0.85rem"},onClick:s[4]||(s[4]=D=>F.value=""),title:"Effacer"})):h("",!0)]),d(oe,{modelValue:V.value,"onUpdate:modelValue":s[5]||(s[5]=D=>V.value=D),options:v,optionLabel:"Libelle",optionValue:"Id",placeholder:"Trimestre",size:"small",style:{width:"200px"}},null,8,["modelValue"]),r("span",qt,[f.value.length!==i.value.length?(m(),E(de,{key:0},[te(R(f.value.length)+" sur "+R(i.value.length),1)],64)):(m(),E(de,{key:1},[te(R(i.value.length),1)],64)),te(" déclaration"+R(i.value.length>1?"s":""),1)])]),r("div",Jt,[d(ot,{ref_key:"agGrid",ref:Q,"excel-file-name":"Declarations CIMR","excel-sheet-name":"Declarations CIMR","row-data":f.value,"excluded-columns":["ndoc"],"date-only":["Date"],"numeric-columns":["Nombre","Salaire Brut","Cotisation Salariale","Cotisation Patronale","Total"],"column-widths":{Numero:120,Date:120,Annee:100,Trimestre:100,Periode:160,Nombre:100,"Salaire Brut":150,"Cotisation Salariale":170,"Cotisation Patronale":170,Total:150,Verrouille:110},"document-number-fields":["ndoc"],"enable-totals":!1,onGridReady:z,onSelectionChanged:G,onRowClicked:L},null,8,["row-data"])])],512),[[lt,!j.value&&C.lecture]]),C.lecture?h("",!0):(m(),E("div",Ht," Vous n'avez pas le droit d'accéder à cette page, veuillez consulter l'administrateur "))],64)}}};export{ga as default};
