1const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/passwordReset-080KLpMW.js","assets/evento-comune-FmQYl2SX.js","assets/vendor-firebase-AOn3Fvmd.js","assets/firebase-config-Dn2Tu_JL.js","assets/vendor-react-B4BIr4_A.js","assets/jszip.min-DN5-FNYE.js","assets/VisoreFile-3lweNgSX.js","assets/VisorePdf-KxB0VBqT.js","assets/icone-sito-BiOTxGdK.js","assets/zoom-out-DadMln1Y.js","assets/scaling-lBaaXAmx.js","assets/VisorePdf-0m-l7aq3.css","assets/crashBlackBox-NHteRanH.js","assets/file-BrKS755W.js","assets/music-CiHXzpfq.js","assets/index-CeY7slSg.js","assets/jspdf.es.min-27wbmQzZ.js","assets/browser-Bsacji25.js"])))=>i.map(i=>d[i]); 2import{_ as Ae}from"./evento-comune-FmQYl2SX.js";import{j as e,r as f,b as ra,L as Gs,N as sc}from"./vendor-react-B4BIr4_A.js";import{n as ni,a as oc,U as rc}from"./UnifiedTeamPage-CFdOc0AB.js";import{u as X}from"./portalLang-BNZe-O9I.js";import{aN as yt,aE as mi,M as We,C as at,a as tt,aV as on,L as me,F as Ue,dm as lc,ar as Tt,X as Ce,aM as rn,D as Ot,aB as cc,at as qt,ap as dc,p as ln,P as wa,w as ke,aA as cn,aJ as qa,T as $e,d8 as ts,t as ba,am as uc,bJ as Ua,aR as dn,q as mc,r as Ws,B as Vs,n as xr,o as pc,a2 as br,aW as hc,cl as fc,aG as gc,aL as Le,H as ta,A as Wa,af as pi,e as xc,b2 as bc,a$ as vr,ay as Ui,j as hi,N as as,ao as fi,ad as ia,i as gi,c4 as Bi,aH as Ut,ac as jr,aI as vc,cS as is,m as li,dl as jc,cy as Gi,aF as ns,cw as yc,bW as _c,z as Nc,ck as na,cA as Hs,a5 as _a,b as sa,bu as xi,bl as yr,aq as Ri,cE as wc,al as zc,bg as Cc,a1 as _r,dE as kc,cu as Sc,K as Ks,h as Dc,bA as Tc,bB as Ic}from"./icone-sito-BiOTxGdK.js";import{a as Nr,S as Pc,R as wr,M as un,b as _s}from"./square-kanban-BoXdjk74.js";import{F as st}from"./file-pen-line-Dk8NXwFk.js";import{R as Ba}from"./receipt-CZywGgWF.js";import{P as Js,a as Ys}from"./portalGuides-_xcnfsW5.js";import{M as Ec,e as Ac,d as $c}from"./McpGuideMask-CyK79Lzo.js";import{a as Je,i as Rc,y as Mc}from"./crashBlackBox-NHteRanH.js";import{L as Fc,M as Lc,P as ci,f as zi,at as zr,h as xe,bv as Zs,bR as Oc,u as qc,bV as Uc,aG as Xs,bW as Bc,ba as Gc}from"./app-BCfwVS8x.js";import{P as Wc,M as Vc}from"./PastiglieLegali-4pV9UuOB.js";import{S as Cr,b as Hc,e as Ja,f as In}from"./publicUrls-C1QEMgMu.js";import{P as Kc}from"./PortalLangToggle-DLBhOozE.js";import{P as Jc}from"./PortalTopBar-f9WKRycI.js";import{E as Ns}from"./EmailComposerDialog-Dj02tENp.js";import{u as ze,d as de,b as Ra,w as Wi,A as Vi,v as Yc,n as Zc,c as Xc,e as Qc,f as ed,g as td,i as ad,j as id,k as nd,l as sd,o as od,p as rd,q as ld,r as Qs}from"./inbox-C018GtDj.js";import{tplMissionRequestReminder as cd,tplMissionAuthorized as dd,tplTimesheetReminder as ud,tplGeneralAnnouncement as md}from"./composerTemplates-Bcl86RH8.js";import{s as pd,r as kr,b as Sr,a as Dr,N as hd}from"./missionBundle-BsqumrbL.js";/* empty css *//* empty css *//* empty css */import{b as ye,d as te,e as fd}from"./firebase-config-Dn2Tu_JL.js";import{p as gd}from"./portalAuthGate-CGdEgjWa.js";import{j as oe,h as Ye,G as _e,f as ie,q as ft,w as Bt,e as Ie,u as la,d as ca,r as xd,n as vi,m as gt,l as mn,k as ss,a0 as bd,a1 as vd,a2 as jd,o as yd,U as _d}from"./vendor-firebase-AOn3Fvmd.js";import{u as Nd}from"./useMfaAwareSignIn-BNvFLkPm.js";import wd from"./MailRulesAdmin-B877nOP1.js";import{D as Pe}from"./DateField-DGkagWyk.js";import{S as se}from"./StableInput-BbjW5fuM.js";import{p as za,v as Ca,l as Pt,F as fe,S as Ne,f as Mi,R as Oe,C as Pn,h as zd,s as ka,i as Gt,d as Wt,B as Me,D as aa,L as je,j as jt,P as Zt,e as ee,k as ji,n as Ma,o as Tr,q as ws,m as da,r as zs,t as Cs,H as eo,u as Ir,w as bi,b as Hi,c as ks,x as Cd,y as Fi,z as Pr,A as Ht,E as kd,G as to,g as Sd}from"./guestExpensesSummaryPdf-ByBwENFQ.js";import{importWithRetry as Sa}from"./chunkRetry-BKj2uQJe.js";import{openPdfPreview as Er,eUnPdf as Dd}from"./pdfPreview-DS1a05Qa.js";import{aa as Ge,cI as Td,cJ as pn,a9 as ua,aC as Ke,cK as Ar,cL as La,cM as Id,cN as Pd,cO as Ed,a8 as $r,bq as Ad,cP as Rr,cQ as ao}from"./eventsStore-DaNHU_lI.js";import{u as Mr,D as Fr}from"./DraftNotice-BSfIUT-t.js";import{c as $d,D as En,s as Rd,H as io,k as Md,n as Ci,f as Fd,C as no}from"./CampoCitta-B5TAyw7S.js";import{T as so}from"./tram-front-QEVHM0gH.js";import{H as Ld}from"./hotel-Bb4eEtQ9.js";import{C as Od}from"./cloud-upload-w1mKMgbA.js";import{F as qd}from"./file-plus-CrNIhBlk.js";import{c as Na}from"./confirmAsync-BwVq95Zo.js";import{F as hn}from"./file-check-C4Th0oaM.js";import{u as Va,M as Ud}from"./MaskManager-BXhAbLxx.js";import{r as Bd}from"./maskRoutes-FWhvLhcU.js";import{F as Gd}from"./folder-input-8KLCu4Yy.js";import{S as xa}from"./Skeleton-D4wgIOh6.js";import{A as Wd}from"./analysisService-DVngNxob.js";import{blobPdfVerificabile as Vd,pdfVerificabile as Hd,scaricaBytes as Kd}from"./verificaPdf-DWFxPAYW.js";import{m as Ha,l as oo,g as Jd,s as Yd,K as Zd,L as ro,r as Xd,c as Qd,M as eu,j as tu,N as au,O as iu,e as nu,P as su,Q as lo}from"./meetingsStore-B9tgmTQl.js";import{R as Lr}from"./RichTextField.events-BmW-0SyC.js";import{I as Or}from"./IdentityColorField-DG-NyNK2.js";/* empty css */import{c as Ss,d as fn,e as ou,m as co,a as uo}from"./meetingTint-3jSDtHGc.js";import{listRecordings as qr,fmtBytes as Ur,deleteRecording as Br,fetchTranscriptText as ru,loadCaptions as lu,fmtDuration as cu}from"./meetRecordings-C5hgE_z9.js";import{C as du}from"./circle-play-Cf5sTpPg.js";import{a as Gr}from"./emailBlocks-CtZk6XmE.js";import{n as uu,m as mu}from"./unifiedInbox-BXSxNyns.js";import{C as pu}from"./circle-dot-D3e1uUId.js";import{l as hu,i as fu}from"./codiciDocumenti-IUFx9Dup.js";import{A as gu}from"./AvatarUploadCard-CtYiZKrH.js";import{P as xu}from"./PortalLegalView-BZ2yuZ27.js";import{u as bu,C as vu}from"./Canvas2Mask-BKGCXgdr.js";import{P as ju}from"./wrench-DBalDvnd.js";function yu(t){return[{id:"events",label:t("Conferenze e workshop","Conferences & workshops"),icon:mi,desc:t("Eventi, partecipanti, lettere di incarico in PDF.","Events, participants, assignment letters in PDF.")},{id:"purchases",label:t("Acquisti","Procurement"),icon:Nr,desc:t("Richieste di beni/servizi â PDF generato automaticamente.","Goods/services requests â auto-generated PDF.")},{id:"contracts",label:t("Consulenze e contratti","Consultancies & contracts"),icon:st,desc:t("Attivazione procedura di selezione â PDF generato automaticamente.","Selection procedure activation â auto-generated PDF.")},{id:"guests",label:t("Ospiti â rimborsi","Guests â reimbursements"),icon:Ba,desc:t("Spese degli ospiti invitati: portale pubblico per il caricamento delle ricevute.","Invited guestsâ expenses: public portal for receipt uploads.")}]}function _u({onOpenTool:t}){const{t:a}=X(),i=yu(a);return e.jsx("section",{className:"mt-admin-tools",children:e.jsx("div",{className:"mt-admin-tools-grid",children:i.map(n=>{const o=n.icon;return e.jsxs("button",{type:"button",className:"mt-admin-tool",style:{fontFamily:"inherit"},onClick:()=>t&&t(n.id),children:[e.jsx("span",{className:"mt-admin-tool-icon",children:e.jsx(o,{size:20})}),e.jsxs("span",{className:"mt-admin-tool-text",children:[e.jsx("strong",{children:n.label}),e.jsx("span",{className:"muted text-xs",children:n.desc})]}),e.jsx(yt,{size:16,className:"muted"})]},n.id)})})})}function Nu(t){return function(i){var o;const n=i.map(s=>s.id);return n.includes("activity")||n.includes("minutes")||n.includes("dashboard")?t("Progetto","Project"):n.includes("events")||n.includes("purchases")||n.includes("contracts")||n.includes("guests")?t("Strumenti","Tools"):n.includes("mail-rules")?t("Amministrazione","Administration"):n.includes("settings")?t("Impostazioni","Settings"):((o=i[0])==null?void 0:o.label)||t("Menu","Menu")}}function wu(t){return t.includes("team")||t.includes("missions")||t.includes("timesheet")}function zu(t){return t.includes("settings")||t.includes("canvas2")}function Cu({brand:t,portalName:a="Research Team Area",portalKey:i="management_team",items:n,me:o,isAdmin:s,onCompose:l,n
2otifications:r,addMember:d,onLogout:m,mobileOpen:c=!1,onMobileOpen:g,onMobileClose:h}){const{t:p}=X();return e.jsx(Jc,{ariaLabel:"Climpact "+a,brand:t,product:a,portalKey:i,items:n,plusGroup:zu,groupLabel:Nu(p),directGroup:wu,me:o,isAdmin:s,roleLabel:s?p("Admin","Admin"):p("Ricercatore","Researcher"),lang:i==="management_team"?e.jsx(Kc,{}):null,bell:r,addMember:d,compose:s&&l?{label:p("Scrivi","Compose"),title:p("Scrivi email al team","Compose email to team"),icon:e.jsx(We,{size:13}),onClick:l}:null,onLogout:m,mobileOpen:c,onMobileOpen:g,onMobileClose:h,t:p})}function ku(){const{t}=X(),a=Nd("mt-login-recaptcha"),[i,n]=f.useState(""),[o,s]=f.useState(""),[l,r]=f.useState(null),[d,m]=f.useState(null),[c,g]=f.useState(!1);async function h(u){u.preventDefault(),r(null),m(null),g(!0);try{await a.signIn(i.trim(),o)}catch(w){r(zi(w.code,t))}finally{g(!1)}}async function p(u){r(null),g(!0);try{await a.confirmCode(u)}catch(w){r(zi(w.code,t))}finally{g(!1)}}async function x(){r(null),g(!0);try{await a.resendCode()}catch(u){r(zi(u.code,t))}finally{g(!1)}}async function b(){if(!i){r(t("Inserisci prima la tua email qui sopra, poi clicca su reimposta.","Enter your email above first, then click reset."));return}r(null);try{const{requestBrandedPasswordReset:u}=await Ae(async()=>{const{requestBrandedPasswordReset:w}=await import("./passwordReset-080KLpMW.js");return{requestBrandedPasswordReset:w}},__vite__mapDeps([0,1,2,3,4]));await u({email:i.trim(),portal:"management_team"}),m(t("Se esiste un account per questa email, il link di reimpostazione è in arrivo.","If an account exists for that email, a reset link is on its way."))}catch(u){r(zi(u.code,t))}}return e.jsxs(Fc,{tool:"management-team",eyebrow:"Climpact Platform",title:"Research Team Area",lead:t("Accedi per registrare le missioni di ricerca e i timesheet â ogni ricercatore vede solo i propri dati.","Sign in to log research trips and timesheets â every researcher sees their own data."),children:[a.step==="mfa-code"?e.jsx(Lc,{busy:c,error:l,onSubmit:p,onResend:x,onCancel:a.cancel,t}):e.jsxs("form",{onSubmit:h,className:"login-form",children:[e.jsxs("div",{className:"field",children:[e.jsx("label",{className:"label",htmlFor:"mt-email",children:"Email"}),e.jsx("input",{id:"mt-email",className:"input",type:"email",autoComplete:"email",required:!0,value:i,onChange:u=>n(u.target.value)})]}),e.jsx(ci,{id:"mt-password",value:o,onChange:u=>s(u.target.value)}),l&&e.jsxs("div",{className:"login-alert login-alert-error",role:"alert",children:[e.jsx(at,{size:16})," ",e.jsx("span",{children:l})]}),d&&e.jsxs("div",{className:"login-alert login-alert-info",role:"status",children:[e.jsx(tt,{size:16})," ",e.jsx("span",{children:d})]}),e.jsx("button",{type:"submit",className:"login-submit",disabled:c,children:c?t("Accesso in corsoâ¦","Signing inâ¦"):t("Entra in Research Team","Enter Research Team")}),e.jsx("button",{type:"button",className:"login-reset",onClick:b,children:t("Password dimenticata?","Forgot password?")})]}),e.jsx("div",{id:"mt-login-recaptcha",style:{width:0,height:0,overflow:"hidden"}}),e.jsx("p",{className:"login-foot-line",children:t("Accesso personale â ogni ricercatore vede solo i propri dati. Le credenziali sono rilasciate dal PI.","Personal access only â every researcher sees their own data. Credentials are issued by the PI.")})]})}function Su(){const t=new URLSearchParams(window.location.search);if(t.get("mcp_authorize")!=="1")return null;const a=t.get("mcp_base")||"",i=t.get("client_id")||"",n=t.get("redirect_uri")||"",o=t.get("code_challenge")||"";if(!a||!i||!n||!o)return null;try{if(new URL(a).protocol!=="https:")return null}catch{return null}return{mcpBase:a,clientId:i,redirectUri:n,state:t.get("state")||"",codeChallenge:o}}function Du({request:t}){const{t:a}=X(),[i,n]=f.useState(null),o=f.useRef(!1);return f.useEffect(()=>{o.current||(o.current=!0,(async()=>{try{const s=ye.currentUser;if(!s)throw new Error(a("Sessione non trovata: ricarica la pagina.","No session found: reload the page."));const l=await s.getIdToken(),r=await fetch(`${t.mcpBase}/authorize/complete`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({id_token:l,client_id:t.clientId,redirect_uri:t.redirectUri,state:t.state,code_challenge:t.codeChallenge})}),d=await r.json();if(!r.ok)throw new Error(d.error_description||a("Autorizzazione non riuscita.","Authorisation failed."));window.location.href=d.redirect_to}catch(s){n(s.message||String(s))}})())},[t,a]),i?e.jsx("div",{style:{minHeight:"100vh",display:"grid",placeItems:"center",padding:"2rem"},children:e.jsxs("div",{style:{maxWidth:"26rem",textAlign:"center"},children:[e.jsx(at,{size:28,style:{marginBottom:".75rem",color:"#c0392b"}}),e.jsx("p",{style:{margin:0},children:i})]})}):e.jsx(zr,{portal:"Research Team",message:a("Autorizzazione in corsoâ¦","Authorisingâ¦")})}function Wr(t){let a="";for(let n=0;n<t.length;n+=32768)a+=String.fromCharCode.apply(null,t.subarray(n,n+32768));return btoa(a)}function Vr(t){return Wr(new TextEncoder().encode(String(t||"")))}function mo(t){return(t.match(/.{1,76}/g)||[""]).join(`\r 3`)}function Tu(t){const a=String(t||"");return/^[\x20-\x7e]*$/.test(a)?a:`=?UTF-8?B?${Vr(a)}?=`}function Iu(t){const a=String(t||"allegato").replace(/["\\\r\n]/g,"_");return/^[\x20-\x7e]*$/.test(a)?`filename="${a}"`:`filename="${a.normalize("NFD").replace(/[Ì-ͯ]/g,"").replace(/[^\x20-\x7e]/g,"_")}"; filename*=UTF-8''${encodeURIComponent(a)}`}function Pu({to:t="",cc:a="",subject:i="",body:n="",allegati:o=[]}){const s=`----=_climpact_${Math.random().toString(36).slice(2)}${Date.now().toString(36)}`,l=["MIME-Version: 1.0","X-Unsent: 1",...t?[`To: ${t}`]:[],...a?[`Cc: ${a}`]:[],`Subject: ${Tu(i)}`,`Content-Type: multipart/mixed; boundary="${s}"`,"",`--${s}`,"Content-Type: text/plain; charset=UTF-8","Content-Transfer-Encoding: base64","",mo(Vr(String(n||"").replace(/\r?\n/g,`\r 4`)))];for(const r of o)l.push(`--${s}`,`Content-Type: ${r.type||"application/octet-stream"}; name="${String(r.name||"allegato").replace(/["\\\r\n]/g,"_")}"`,"Content-Transfer-Encoding: base64",`Content-Disposition: attachment; ${Iu(r.name)}`,"",mo(Wr(r.bytes)));return l.push(`--${s}--`,""),l.join(`\r 5`)}let si=null;function Eu(){var o;if(si)return si;const a=`climpact.casella.chiave.v1.${((o=ye.currentUser)==null?void 0:o.uid)||"anon"}`;try{const s=localStorage.getItem(a);if(s)return si=s,s}catch{}const i=new Uint8Array(32);crypto.getRandomValues(i);const n=btoa(String.fromCharCode(...i));try{localStorage.setItem(a,n)}catch{}return si=n,n}async function yi(t){const{getFunctions:a,httpsCallable:i}=await Ae(async()=>{const{getFunctions:r,httpsCallable:d}=await import("./vendor-firebase-AOn3Fvmd.js").then(m=>m.ah);return{getFunctions:r,httpsCallable:d}},[]),{app:n}=await Ae(async()=>{const{app:r}=await import("./firebase-config-Dn2Tu_JL.js").then(d=>d.c);return{app:r}},__vite__mapDeps([3,2])),o=i(a(n,"europe-west1"),"casellaPosta",{timeout:18e4});let s=null;try{s=Eu()}catch{s=si}return(await o({...t,chiave:s})).data}const Au=()=>yi({action:"stato"}),$u=(t,a)=>yi({action:"collega",email:t,password:a}),Ru=()=>yi({action:"scollega"}),Mu=()=>yi({action:"coda"});async function Fu(t,{to:a,cc:i,subject:n,body:o,files:s=[],contesto:l=null}){var c;const r=(c=ye.currentUser)==null?void 0:c.uid;if(!r)throw new Error("not-signed-in");const d=`${Date.now().toString(36)}${Math.random().toString(36).slice(2,7)}`,m=[];for(const g of s){const h=(g.name||"allegato").replace(/[/\\]/g,"_"),p=await ze(`team-missions/${r}/posta-uscita/${d}/${h}`,g);m.push({path:p.path,name:h,type:g.type||void 0})}return yi({action:t,to:a,cc:i,subject:n,body:o,allegati:m,contesto:l})}let os=null;const rs=new Set;
5function Ki(t){os=t,rs.forEach(a=>a(t))}function Ds(){const[t,a]=f.useState(os);return f.useEffect(()=>(rs.add(a),os||Au().then(Ki).catch(()=>Ki({collegata:!1,email:null,errore:!0})),()=>{rs.delete(a)}),[]),t}function ls(t,a){const i=String((t==null?void 0:t.message)||t||"");return/altro-dispositivo/.test(i)?a("Su questo dispositivo la casella non risulta collegata: per ragioni di sicurezza occorre ripetere il collegamento una volta.","The mailbox is not connected on this device: for security reasons it needs to be connected once here."):/password/.test(i)?a("Il server dellâUniversità non ha accettato lâindirizzo o la password.","The University server did not accept the address or the password."):/rete/.test(i)?a("Il server di posta dellâUniversità non risponde. Riprova tra qualche minuto.","The University mail server is not responding. Please try again in a few minutes."):/troppo-grande/.test(i)?a("Gli allegati superano il limite consentito dalla posta (24 MB).","The attachments exceed the mail size limit (24 MB)."):/not-uniba/.test(i)?a("à necessario un indirizzo @uniba.it.","A @uniba.it address is required."):/not-connected/.test(i)?a("La casella non è collegata.","The mailbox is not connected."):/no-recipient/.test(i)?a("Indica almeno un destinatario.","Please enter at least one recipient."):a("Operazione non riuscita: ","The operation failed: ")+i}function Lu(){const{t,lang:a}=X(),[i,n]=f.useState(null),[o,s]=f.useState("");async function l(){s("");try{const m=await Mu();n(m.righe||[])}catch(m){s(String((m==null?void 0:m.message)||m)),n([])}}f.useEffect(()=>{l()},[]);const r=m=>{if(!m)return"";try{return new Date(m).toLocaleString(a==="en"?"en-GB":"it-IT",{day:"numeric",month:"short",year:"numeric",hour:"2-digit",minute:"2-digit"})}catch{return m}},d=m=>m.stato==="inviata"?{icona:tt,cls:"is-ok",testo:m.in_inviata?t("Inviato, copia in Posta inviata","Sent, copy filed in Sent"):t("Inviato","Sent")}:m.stato==="bozza"?{icona:Ue,cls:"is-bozza",testo:t("Salvato in Bozze","Saved to Drafts")}:{icona:at,cls:"is-errore",testo:t("Non inviato","Not sent")};return e.jsxs("div",{className:"mt-posta-inviata",children:[e.jsxs("div",{className:"mt-posta-inviata-h",children:[e.jsx("span",{children:t("Messaggi inviati tramite la piattaforma","Messages sent through the platform")}),e.jsx("button",{type:"button",className:"btn btn-ghost btn-sm",onClick:l,"aria-label":t("Aggiorna","Refresh"),children:e.jsx(on,{size:13})})]}),i===null&&e.jsxs("div",{className:"muted text-sm",children:[e.jsx(me,{size:13,className:"spin"})," ",t("Caricamentoâ¦","Loadingâ¦")]}),o&&e.jsx("div",{className:"muted text-sm",children:o}),i&&i.length===0&&!o&&e.jsx("div",{className:"muted text-sm",children:t("Qui compaiono i messaggi inviati o salvati in Bozze tramite la piattaforma.","Messages sent or saved to Drafts through the platform appear here.")}),i&&i.length>0&&e.jsx("ul",{className:"mt-posta-inviata-lista",children:i.map(m=>{var h;const c=d(m),g=c.icona;return e.jsxs("li",{className:`mt-posta-riga ${c.cls}`,children:[e.jsxs("div",{className:"mt-posta-riga-top",children:[e.jsx("span",{className:"mt-posta-riga-oggetto",children:m.subject||t("(senza oggetto)","(no subject)")}),e.jsx("span",{className:"mt-posta-riga-quando",children:r(m.at)})]}),e.jsxs("div",{className:"mt-posta-riga-meta",children:[e.jsxs("span",{className:"mt-posta-riga-esito",children:[e.jsx(g,{size:12})," ",c.testo]}),e.jsxs("span",{children:[t("A","To")," ",m.to,m.cc?`, Cc ${m.cc}`:""]}),((h=m.allegati)==null?void 0:h.length)>0&&e.jsx("span",{children:m.allegati.join(", ")})]})]},m.id)})})]})}function gn({dove:t="impostazioni",onCollegata:a}){var v;const{t:i}=X(),n=Ds(),o=String(((v=ye.currentUser)==null?void 0:v.email)||""),[s,l]=f.useState((n==null?void 0:n.email)||(/uniba\.it$/i.test(o)?o:"")),r=!!(n!=null&&n.collegata&&(n!=null&&n.questo_dispositivo)),[d,m]=f.useState(""),[c,g]=f.useState(!1),[h,p]=f.useState(""),[x,b]=f.useState(!1);async function u(j){if(j.preventDefault(),!c){g(!0),p(""),b(!1);try{const _=await $u(s.trim(),d);m(""),b(!0),Ki({collegata:!0,questo_dispositivo:!0,email:_.email}),a==null||a(_)}catch(_){p(ls(_,i))}finally{g(!1)}}}async function w(){if(window.confirm(i("Vuoi scollegare la casella? La password sarà eliminata dalla piattaforma.","Disconnect the mailbox? The password will be deleted from the platform."))){g(!0);try{await Ru(),Ki({collegata:!1,questo_dispositivo:!1,email:null})}catch(j){p(ls(j,i))}finally{g(!1)}}}return n?r&&t==="home"?null:r?e.jsxs("section",{className:`mt-card mt-settings-card mt-casella mt-casella-${t}`,children:[e.jsxs("div",{className:"mt-card-icon-head",children:[e.jsx(We,{size:16,className:"muted"}),e.jsx("h3",{children:i("Casella di posta istituzionale","Institutional mailbox")})]}),e.jsxs("p",{className:"muted text-sm",style:{margin:"0 0 12px"},children:[i("Casella collegata: ","Connected mailbox: "),e.jsx("strong",{className:"mono",children:n.email}),"."," ",i("Le comunicazioni relative a missioni, contratti e acquisti vengono inviate da questo indirizzo e archiviate nella cartella Posta inviata.","Communications on missions, contracts and purchases are sent from this address and filed in your Sent folder.")]}),h&&e.jsxs("div",{className:"login-alert login-alert-error mt-pw-alert",children:[e.jsx(at,{size:16})," ",e.jsx("span",{children:h})]}),e.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:w,disabled:c,
5children:[e.jsx(lc,{size:13})," ",i("Scollega","Disconnect")]}),e.jsx(po,{t:i}),t==="impostazioni"&&e.jsx(Lu,{})]}):e.jsxs("section",{className:`mt-card mt-settings-card mt-casella mt-casella-${t}`,children:[e.jsxs("div",{className:"mt-card-icon-head",children:[e.jsx(Tt,{size:16,className:"muted"}),e.jsx("h3",{children:i("Collega la casella di posta istituzionale","Connect your institutional mailbox")})]}),n.collegata&&!n.questo_dispositivo&&e.jsx("p",{className:"text-sm",style:{margin:"0 0 8px"},children:i(`La casella ${n.email} risulta collegata da un altro dispositivo. Per ragioni di sicurezza la chiave è conservata soltanto sul dispositivo in cui è stato effettuato il collegamento: su questo occorre ripeterlo una volta.`,`The mailbox ${n.email} is connected from another device. For security reasons the key is kept only on the device where it was connected: on this one you need to connect it once.`)}),e.jsx("p",{className:"muted text-sm",style:{margin:"0 0 12px"},children:t==="invio"?i("Il collegamento si effettua una sola volta. Da quel momento i messaggi partono dal tuo indirizzo @uniba.it, con i documenti allegati, e restano archiviati nella cartella Posta inviata.","You connect it only once. From then on messages leave from your @uniba.it address, with the documents attached, and remain filed in your Sent folder."):i("Collegando una sola volta la tua casella @uniba.it, le comunicazioni relative a missioni, contratti e acquisti vengono inviate dal tuo indirizzo, con i documenti allegati, e restano archiviate nella cartella Posta inviata.","By connecting your @uniba.it mailbox once, communications on missions, contracts and purchases are sent from your own address, with the documents attached, and remain filed in your Sent folder.")}),e.jsxs("form",{onSubmit:u,className:"mt-pw-form",children:[e.jsxs("div",{className:"field",children:[e.jsx("label",{className:"label",htmlFor:`casella-email-${t}`,children:i("Indirizzo istituzionale","Institutional address")}),e.jsx("input",{id:`casella-email-${t}`,className:"input",type:"email",autoComplete:"username",placeholder:"[email protected]",required:!0,value:s,onChange:j=>l(j.target.value)})]}),e.jsx(ci,{id:`casella-pw-${t}`,label:i("Password della casella","Mailbox password"),autoComplete:"current-password",value:d,onChange:j=>m(j.target.value)}),h&&e.jsxs("div",{className:"login-alert login-alert-error mt-pw-alert",children:[e.jsx(at,{size:16})," ",e.jsx("span",{children:h})]}),x&&e.jsxs("div",{className:"login-alert login-alert-success mt-pw-alert mt-pw-alert-success",children:[e.jsx(tt,{size:16})," ",e.jsx("span",{children:i("La casella è stata collegata.","The mailbox has been connected.")})]}),e.jsx(po,{t:i}),e.jsx("div",{children:e.jsxs("button",{type:"submit",className:"btn btn-primary anim-shimmer",disabled:c||!s||!d,children:[c?e.jsx(me,{size:14,className:"spin"}):e.jsx(Tt,{size:14})," ",c?i("Verifica dellâaccesso in corsoâ¦","Verifying accessâ¦"):i("Collega","Connect")]})})]})]}):t==="home"?null:e.jsx("section",{className:`mt-card mt-settings-card mt-casella mt-casella-${t}`,children:e.jsxs("div",{className:"muted text-sm",children:[e.jsx(me,{size:14,className:"spin"})," ",i("Verifica della casella in corsoâ¦","Checking the mailboxâ¦")]})})}function po({t}){return e.jsxs("ul",{className:"mt-casella-garanzie",children:[e.jsx("li",{children:t("La piattaforma utilizza la casella esclusivamente per inviare i messaggi da te confermati e per archiviarne una copia in Posta inviata o in Bozze. Nessun messaggio presente nella casella viene aperto o letto.","The platform uses the mailbox solely to send the messages you confirm and to file a copy in Sent or Drafts. No message in the mailbox is ever opened or read.")}),e.jsx("li",{children:t("La password è cifrata con due chiavi distinte, una conservata sul server e lâaltra esclusivamente su questo dispositivo. Nessuna delle due, da sola, consente di decifrarla, neppure agli amministratori della piattaforma.","The password is encrypted with two separate keys, one kept on the server and the other only on this device. Neither key alone can decrypt it, not even for the platform administrators.")}),e.jsx("li",{children:t("Puoi scollegare la casella in qualsiasi momento; la password viene contestualmente eliminata.","You can disconnect the mailbox at any time; the password is deleted at once.")})]})}function Ou(){const t=Ds();return!t||t.collegata&&t.questo_dispositivo?null:e.jsx("section",{className:"mt-band mt-band-tight",children:e.jsx("div",{className:"mt-wrap",children:e.jsx(gn,{dove:"home"})})})}const Hr="climpact.posta.v1";function qu(){try{return localStorage.getItem(Hr)||""}catch{return""}}function ho(t){try{localStorage.setItem(Hr,t)}catch{}}function An(t,a){const i=URL.createObjectURL(t),n=document.createElement("a");n.href=i,n.download=a,document.body.appendChild(n),n.click(),n.remove(),setTimeout(()=>URL.revokeObjectURL(i),6e4)}function Da({info:t,onClose:a}){const{t:i}=X(),{to:n,cc:o,subject:s,body:l,files:r=[],contesto:d=null}=t,m=Ds(),[c,g]=f.useState(!1),[h,p]=f.useState(n||""),[x,b]=f.useState(o||""),[u,w]=f.useState(s||""),[v,j]=f.useState(l||""),[_,C]=f.useState(()=>new Set),[y,z]=f.useState([]),[T,I]=f.useState(!1),[D,$]=f.useState(null),q=f.useRef(null);function R(ae){const he=[...ae||[]].filter(be=>be&&be.size>0);he.length&&z(be=>[...be,...he])}function O(ae){$(he=>(he&&URL.revokeObjectURL(he.url),{name:ae.name,type:ae.type||"",url:URL.createObjectURL(ae)}))}function k(){$(ae=>(ae&&URL.revokeObjectURL(ae.url),null))}const[N,L]=f.useState(null),[B,P]=f.useState(null),[E,Y]=f.useState(""),S=encodeURIComponent,W=`https://mail.google.com/mail/?view=cm&fs=1&to=${S(n)}&cc=${S(o)}&su=${S(s)}&body=${S(l)}`,[M,J]=f.useState(r.length?null:[]);f.useEffect(()=>{if(!r.length)return;let ae=!0;return(async()=>{const he=[];for(const be of r)try{const A=await fetch(be.url);if(!A.ok)continue;const H=await A.blob();he.push(new File([H],be.name||"allegato.pdf",{type:H.type||"application/pdf"}))}catch{}ae&&J(he)})(),()=>{ae=!1}},[]);const V=M===null,K=!V&&M.length<r.length,Q=!V&&typeof navigator<"u"&&typeof navigator.canShare=="function"&&(()=>{try{return navigator.canShare({files:M.length?M:[new File(["x"],"x.pdf",{type:"application/pdf"})]})}catch{return!1}})(),le=[...Q?[{id:"condividi",it:"iPhone, iPad o Safari",en:"iPhone, iPad or Safari"}]:[],{id:"app",it:"Mail del Mac o Outlook",en:"Mac Mail or Outlook"},{id:"gmail",it:"Gmail nel browser",en:"Gmail in the browser"},{id:"uniba",it:"Webmail dellâUniversità ",en:"University webmail"}],[U,G]=f.useState(()=>qu()),ne=le.some(ae=>ae.id===U)?U:Q?"condividi":"app";function ue(ae){G(ae),ho(ae)}const ge=`A: ${n} 6Cc: ${o} 7Oggetto: ${s} 8 9${l}`;async function we(ae){try{return await navigator.clipboard.writeText(ae),!0}catch{return!1}}async function Se(){for(const ae of M)An(ae,ae.name),await new Promise(he=>setTimeout(he,700))}async function ot(){ho(ne);
9try{if(ne==="condividi")await we([n,o].filter(Boolean).join(", ")),await navigator.share({files:M,title:s,text:l}),a();else if(ne==="app"){const ae=await Promise.all(M.map(async A=>({name:A.name,type:A.type,bytes:new Uint8Array(await A.arrayBuffer())}))),he=Pu({to:n,cc:o,subject:s,body:l,allegati:ae}),be=`${String(s||"Mail").replace(/[\\/:*?"<>|]+/g," ").replace(/\s+/g," ").trim().slice(0,80)}.eml`;An(new Blob([he],{type:"message/rfc822"}),be)}else ne==="gmail"?(window.open(W,"_blank","noopener"),await Se()):(await we(ge),await Se())}catch(ae){if(ae&&ae.name==="AbortError")return;alert(i("Non riuscito: ","Failed: ")+(ae.message||ae))}}async function it(ae){var he;if(!N){L(ae),Y("");try{const be=[...(M||[]).filter((H,Z)=>!_.has(Z)),...y],A=await Fu(ae,{to:h,cc:x,subject:u,body:v,files:be,contesto:d});P(A);try{await((he=t.onEsito)==null?void 0:he.call(t,{at:new Date().toISOString(),stato:A.stato,da:(m==null?void 0:m.email)||"",a:h,cc:x,oggetto:u,allegati:be.map(H=>H.name)}))}catch{}}catch(be){Y(ls(be,i))}finally{L(null)}}}const mt={condividi:i("Apri il messaggio con gli allegati","Open the message with the attachments"),app:i("Apri il messaggio con gli allegati","Open the message with the attachments"),gmail:i("Apri Gmail e scarica gli allegati","Open Gmail and download the attachments"),uniba:i("Copia il testo e scarica gli allegati","Copy the text and download the attachments")}[ne],Vt={condividi:i("Seleziona Mail o Gmail. Lâindirizzo del destinatario è già stato copiato e va incollato nel campo «A».","Choose Mail or Gmail. The recipientâs address has already been copied: paste it into the âToâ field."),app:i("Apri il file scaricato. In Outlook è sufficiente premere Invia; in Mail del Mac occorre scegliere «Invia di nuovo» dal menu Messaggio.","Open the downloaded file. In Outlook just press Send; in Mac Mail choose âSend Againâ from the Message menu."),gmail:i("Il messaggio si apre già compilato. Gli allegati, appena scaricati, vanno trascinati nel messaggio: Gmail nel browser non accetta allegati provenienti da altri siti.","The message opens already filled in. Drag in the attachments just downloaded: Gmail in the browser does not accept attachments from other sites."),uniba:i("Destinatari, oggetto e testo sono stati copiati: incollali nella webmail e aggiungi gli allegati appena scaricati.","Recipients, subject and text have been copied: paste them into the webmail and add the attachments just downloaded.")}[ne],Et=ne==="condividi"?Pc:ne==="app"?We:Ot;return ra.createPortal(e.jsx("div",{className:"modal-backdrop anim-scrim mt-dialog-host",role:"dialog","aria-modal":"true",onClick:ae=>{ae.target===ae.currentTarget&&a()},children:e.jsxs("div",{className:`modal-panel anim-pop portal-site mt-mailpicker-panel${m!=null&&m.collegata&&(m!=null&&m.questo_dispositivo)&&!c?" is-composer":""}`,children:[e.jsx("h2",{className:"mt-mailpicker-title",children:i("Invio del messaggio","Send the message")}),(d==null?void 0:d.titolo)&&e.jsx("p",{className:"mt-composer-contesto",children:d.titolo}),m===null&&e.jsxs("p",{className:"mt-mailpicker-lead",children:[e.jsx(me,{size:13,className:"spin"})," ",i("Verifica della casella in corsoâ¦","Checking your mailboxâ¦")]}),(m==null?void 0:m.collegata)&&(m==null?void 0:m.questo_dispositivo)&&!c&&B&&e.jsxs("div",{className:"mt-composer-esito",children:[B.stato==="inviata"?e.jsx(tt,{size:20}):e.jsx(Ue,{size:20}),e.jsx("p",{children:B.stato==="inviata"?B.in_inviata?i(`Messaggio inviato da ${m.email}. Una copia è archiviata nella cartella Posta inviata.`,`Message sent from ${m.email}. A copy is filed in your Sent folder.`):i(`Messaggio inviato da ${m.email}. Non è stato possibile archiviarne una copia in Posta inviata, ma lâinvio è avvenuto regolarmente.`,`Message sent from ${m.email}. A copy could not be filed in Sent, but the message was sent.`):i("Il messaggio è stato salvato nelle Bozze della tua casella, da cui potrai inviarlo.","The message has been saved to your mailbox Drafts, from where you can send it.")})]}),(m==null?void 0:m.collegata)&&(m==null?void 0:m.questo_dispositivo)&&!c&&!B&&e.jsxs("div",{className:"mt-composer",children:[e.jsxs("div",{className:"mt-composer-campi",children:[e.jsxs("div",{className:"mt-composer-riga mt-composer-riga-da",children:[e.jsx("span",{children:i("Da","From")}),e.jsxs("span",{className:"mt-composer-mittente",children:[e.jsx(We,{size:13})," ",m.email]})]}),e.jsxs("label",{className:"mt-composer-riga",children:[e.jsx("span",{children:i("A","To")}),e.jsx("input",{value:h,onChange:ae=>p(ae.target.value),spellCheck:!1})]}),e.jsxs("label",{className:"mt-composer-riga",children:[e.jsx("span",{children:"Cc"}),e.jsx("input",{value:x,onChange:ae=>b(ae.target.value),spellCheck:!1})]}),e.jsxs("label",{className:"mt-composer-riga mt-composer-riga-oggetto",children:[e.jsx("span",{children:i("Oggetto","Subject")}),e.jsx("textarea",{rows:Math.max(1,Math.ceil((u||"").length/62)),value:u,onChange:ae=>w(ae.target.value.replace(/\n/g," "))})]})]}),e.jsx("textarea",{className:"mt-composer-testo",rows:Math.max(8,(v||"").split(`
10`).length+2),value:v,onChange:ae=>j(ae.target.value)}),e.jsxs("div",{className:`mt-composer-allegati${T?" is-sopra":""}`,onDragOver:ae=>{ae.preventDefault(),I(!0)},onDragLeave:()=>I(!1),onDrop:ae=>{var he;ae.preventDefault(),I(!1),R((he=ae.dataTransfer)==null?void 0:he.files)},children:[V&&e.jsxs("span",{className:"muted text-sm",children:[e.jsx(me,{size:13,className:"spin"})," ",i("Preparazione degli allegatiâ¦","Preparing the attachmentsâ¦")]}),!V&&M.map((ae,he)=>e.jsxs("span",{className:`mt-composer-allegato${_.has(he)?" is-tolto":""}`,children:[e.jsxs("button",{type:"button",className:"mt-composer-allegato-apri",onClick:()=>O(ae),title:i("Apri lâanteprima","Open preview"),children:[e.jsx(Ue,{size:13})," ",ae.name]}),e.jsx("button",{type:"button",className:"mt-composer-allegato-x","aria-label":_.has(he)?i("Rimetti","Put back"):i("Togli","Remove"),onClick:()=>C(be=>{const A=new Set(be);return A.has(he)?A.delete(he):A.add(he),A}),children:e.jsx(Ce,{size:12})})]},`p${he}`)),y.map((ae,he)=>e.jsxs("span",{className:"mt-composer-allegato",children:[e.jsxs("button",{type:"button",className:"mt-composer-allegato-apri",onClick:()=>O(ae),title:i("Apri lâanteprima","Open preview"),children:[e.jsx(Ue,{size:13})," ",ae.name]}),e.jsx("button",{type:"button",className:"mt-composer-allegato-x","aria-label":i("Togli","Remove"),onClick:()=>z(be=>be.filter((A,H)=>H!==he)),children:e.jsx(Ce,{size:12})})]},`a${he}`)),e.jsxs("button",{type:"button",className:"mt-composer-aggiungi",onClick:()=>{var ae;return(ae=q.current)==null?void 0:ae.click()},children:[e.jsx(rn,{size:13})," ",i("Aggiungi allegato","Add attachment")]}),e.jsx("input",{ref:q,type:"file",multiple:!0,hidden:!0,onChange:ae=>{R(ae.target.files),ae.target.value=""}}),K&&e.jsx("span",{className:"muted text-sm",children:i("Non è stato possibile recuperare uno degli allegati.","One of the attachments could not be retrieved.")})]}),E&&e.jsxs("div",{className:"login-alert login-alert-error mt-pw-alert",children:[e.jsx(at,{size:16})," ",e.jsx("span",{children:E})]}),e.jsxs("div",{className:"mt-composer-azioni",children:[e.jsx("button",{type:"button",className:"btn btn-ghost",onClick:a,disabled:!!N,children:i("Annulla","Cancel")}),e.jsx("span",{className:"mt-composer-spazio"}),e.jsxs("button",{type:"button",className:"btn btn-secondary",disabled:V||!!N,onClick:()=>it("bozza"),children:[N==="bozza"?e.jsx(me,{size:14,className:"spin"}):e.jsx(Ue,{size:14})," ",i("Salva in Bozze","Save to Drafts")]}),e.jsxs("button",{type:"button",className:"btn btn-primary anim-shimmer",disabled:V||!!N||!h.trim(),onClick:()=>it("invia"),children:[N==="invia"?e.jsx(me,{size:14,className:"spin"}):e.jsx(Ot,{size:14})," ",N==="invia"?i("Invio in corsoâ¦","Sendingâ¦"):i("Invia","Send")]})]}),e.jsx("button",{type:"button",className:"btn btn-ghost btn-sm mt-composer-altro",onClick:()=>g(!0),children:i("Preferisci inviarlo dal tuo programma di posta?","Prefer to send it from your mail app?")})]}),D&&e.jsxs("div",{className:"mt-composer-anteprima",role:"dialog","aria-label":D.name,children:[e.jsxs("div",{className:"mt-composer-anteprima-testa",children:[e.jsxs("span",{children:[e.jsx(cc,{size:14})," ",D.name]}),e.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:k,children:[e.jsx(Ce,{size:13})," ",i("Chiudi anteprima","Close preview")]})]}),/^image\//.test(D.type)?e.jsx("img",{src:D.url,alt:D.name}):/pdf|^text\//.test(D.type)||/\.pdf$/i.test(D.name)?e.jsx("iframe",{src:D.url,title:D.name}):e.jsxs("p",{className:"mt-composer-anteprima-vuota",children:[i("Per questo file lâanteprima non è disponibile.","No preview is available for this file.")," ",e.jsx("a",{href:D.url,download:D.name,children:i("Scarica il file","Download the file")})]})]}),m&&!(m.collegata&&m.questo_dispositivo)&&!c&&e.jsxs(e.Fragment,{children:[e.jsx(gn,{dove:"invio"}),e.jsx("button",{type:"button",className:"btn btn-ghost btn-sm mt-composer-altro",onClick:()=>g(!0),children:i("Invia invece dal tuo programma di posta","Send from your mail app instead")})]}),m&&c&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"mt-mailpicker-poste",role:"group","aria-label":i("La tua posta","Your email"),children:[e.jsx("span",{className:"mt-mailpicker-poste-h",children:i("La tua posta","Your email")}),le.map(ae=>e.jsx("button",{type:"button",className:`mt-mailpicker-posta${ne===ae.id?" is-on":""}`,"aria-pressed":ne===ae.id,onClick:()=>ue(ae.id),children:i(ae.it,ae.en)},ae.id))]}),e.jsx("button",{type:"button",className:"btn btn-primary anim-shimmer mt-mailpicker-go",disabled:V,onClick:ot,children:V?e.jsxs(e.Fragment,{children:[e.jsx(me,{size:15,className:"spin"})," ",i("Preparazione degli allegatiâ¦","Preparing the attachmentsâ¦")]}):e.jsxs(e.Fragment,{children:[e.jsx(Et,{size:15})," ",mt]})}),e.jsx("p",{className:"mt-mailpicker-lead",children:Vt}),K&&e.jsx("p",{className:"mt-mailpicker-lead",children:i("Non è stato possibile recuperare uno degli allegati: puoi scaricarlo qui sotto e aggiungerlo manualmente.","One of the attachments could not be retrieved: you can download it below and add it manually.")}),r.length>0&&e.jsxs("div",{className:"mt-mailpicker-note",children:[e.jsxs("div",{className:"mt-mailpicker-note-h mt-mailpicker-note-row",children:[i("Allegati","Attachments"),e.jsxs("button",{type:"button",className:"btn btn-ghost btn-sm mt-mailpicker-tutti",disabled:V||!M.length,onClick:Se,children:[e.jsx(qt,{size:13})," ",i("Scarica tutti","Download all")]})]}),e.jsx("div",{className:"mt-mailpicker-list",children:r.map((ae,he)=>e.jsxs("button",{type:"button",className:"btn btn-ghost btn-sm mt-mailpicker-attach",onClick:async()=>{try{const be=await fetch(ae.url);if(!be.ok)throw new Error(`HTTP ${be.status}`);An(await be.blob(),ae.name)}catch(be){alert(i("Download non riuscito: ","Download failed: ")+(be.message||be))}},children:[e.jsx(qt,{size:13})," ",ae.name]},he))})]}),e.jsxs("details",{className:"mt-mailpicker-preview-wrap",children:[e.jsx("summary",{className:"mt-mailpicker-preview-summary",children:i("Anteprima del messaggio","Message preview")}),e.jsxs("div",{className:"mt-mailpicker-preview",children:[e.jsxs("div",{children:[e.jsx("strong",{children:i("A:","To:")})," ",n]}),e.jsxs("div",{children:[e.jsx("strong",{children:"Cc:"})," ",o]}),e.jsxs("div",{className:"mt-mailpicker-preview-subj",children:[e.jsx("strong",{children:i("Oggetto:","Subject:")})," ",s]}),e.jsx("div",{className:"mt-mailpicker-preview-body",children:l})]})]})]}),!(m!=null&&m.collegata&&(m!=null&&m.questo_dispositivo)&&!c&&!B)&&e.jsx("div",{className:"mt-mailpicker-foot",children:e.jsx("button",{type:"button",className:"btn btn-secondary",onClick:a,children:i("Chiudi","Close")})})]})}),document.body)}function _i({invio:t,destinatario:a}){const{t:i,lang:n}=X();if(!t||!t.at)return null;const o=(()=>
10{try{return new Date(t.at).toLocaleString(n==="en"?"en-GB":"it-IT",{day:"numeric",month:"long",year:"numeric",hour:"2-digit",minute:"2-digit"})}catch{return t.at}})(),s=t.stato==="inviata",l=Array.isArray(t.allegati)?t.allegati.length:0,r=a||t.a||"";return e.jsxs("div",{className:`mt-invio-fatto${s?" is-inviata":" is-bozza"}`,role:"status",children:[e.jsx("span",{className:"mt-invio-fatto-icona",children:s?e.jsx(tt,{size:18}):e.jsx(Ue,{size:18})}),e.jsxs("span",{className:"mt-invio-fatto-testo",children:[e.jsx("strong",{children:s?i(`Inviata il ${o}`,`Sent on ${o}`):i(`Salvata nelle Bozze il ${o}`,`Saved to Drafts on ${o}`)}),e.jsx("span",{children:[t.da?i(`da ${t.da}`,`from ${t.da}`):"",r?i(`a ${r}`,`to ${r}`):"",l?l===1?i("1 allegato","1 attachment"):i(`${l} allegati`,`${l} attachments`):""].filter(Boolean).join(", ")})]})]})}function Kr({configKey:t,title:a,isAdmin:i,defaultText:n=""}){const{t:o}=X(),[s,l]=f.useState(""),[r,d]=f.useState(""),[m,c]=f.useState(!1),[g,h]=f.useState(!1),[p,x]=f.useState(!1),b="istruzioni-aperte:"+t,[u,w]=f.useState(()=>{try{return localStorage.getItem(b)==="1"}catch{return!1}}),v=()=>w(y=>{try{localStorage.setItem(b,y?"0":"1")}catch{}return!y});f.useEffect(()=>{const y=oe(te,"team_config",t),z=Ye(y,T=>{const I=T.exists()&&T.data().text||"";l(I),x(!0)},T=>{console.warn("[instructions] subscribe",T),x(!0)});return()=>z()},[t]);function j(){d(s||n),c(!0)}async function _(){h(!0);try{await _e(oe(te,"team_config",t),{text:r,updated_at:ie()},{merge:!0}),c(!1)}catch(y){alert(o("Salvataggio non riuscito: ","Save failed: ")+(y.message||y))}finally{h(!1)}}if(p&&!s&&!n&&!i&&!m)return null;const C=s||n;return e.jsxs("div",{className:"mt-instructions card",children:[e.jsxs("div",{className:"mt-instructions-head",children:[e.jsxs("button",{type:"button",className:"mt-instructions-toggle",onClick:v,"aria-expanded":u||m,children:[e.jsx(dc,{size:16,className:"mt-instructions-icon"}),e.jsx("strong",{children:a}),e.jsx(ln,{size:16,className:"mt-instructions-chevron"+(u||m?" is-open":"")})]}),i&&!m&&u&&e.jsxs("button",{className:"btn btn-ghost btn-sm mt-ml-auto",onClick:j,children:[e.jsx(wa,{size:12})," ",o("Modifica","Edit")]})]}),m?e.jsxs(e.Fragment,{children:[e.jsx("textarea",{className:"textarea",rows:6,value:r,onChange:y=>d(y.target.value),placeholder:o("Istruzioni e scadenze. Le interruzioni di riga sono supportate.","Instructions and deadlines. Line breaks are supported.")}),e.jsxs("div",{className:"mt-instructions-actions",children:[e.jsxs("button",{className:"btn btn-primary btn-sm",onClick:_,disabled:g,children:[e.jsx(ke,{size:12})," ",o("Salva","Save")]}),e.jsxs("button",{className:"btn btn-secondary btn-sm",onClick:()=>{c(!1),d(s)},children:[e.jsx(Ce,{size:12})," ",o("Annulla","Cancel")]})]})]}):u&&e.jsx("div",{className:"mt-instructions-body",children:C.split(` 11`).map((y,z)=>e.jsx("p",{style:{margin:0},children:y||" "},z))})]})}const Uu="TKuaPxLsEobzv43Bdj7jrzyaVjs2",Bu=Date.parse("2026-09-26T00:00:00Z");function Gu(t){if(!t)return 0;if(typeof t.toMillis=="function")return t.toMillis();if(typeof t.seconds=="number")return t.seconds*1e3;const a=Date.parse(t);return Number.isFinite(a)?a:0}const Fe=t=>!!(t&&t.url);function kt(t){return(t==null?void 0:t.team_uid)===Uu}function Ji(t){if(["request_signed_person_pdf","request_signed_pi_pdf","assignment_signed_person_pdf","assignment_signed_pi_pdf"].some(n=>Fe(t==null?void 0:t[n])))return!1;const i=Gu(t==null?void 0:t.created_at);return Fe(t==null?void 0:t.request_pdf)&&Fe(t==null?void 0:t.assignment_pdf)&&i>0&&i<Bu}function fo(t,a){return kt(t)?(t==null?void 0:t[`${a}_signed_pi_pdf`])||(t==null?void 0:t[`${a}_signed_person_pdf`])||null:(t==null?void 0:t[`${a}_signed_pi_pdf`])||null}function Wu(t){if(Ji(t))return{pronto:!0,mancano:[],files:[t.request_pdf,t.assignment_pdf,t.advance_signed_pdf||t.advance_pdf].filter(Fe),precedente:!0};const a=kt(t),i=[],n=[["request",{it:"la richiesta",en:"the request"}],["assignment",{it:"la lettera di incarico",en:"the assignment letter"}]];for(const[s,l]of n){const r=t==null?void 0:t[`${s}_signed_person_pdf`],d=t==null?void 0:t[`${s}_signed_pi_pdf`];a?!Fe(r)&&!Fe(d)&&i.push({it:`${l.it} firmata`,en:`${l.en} signed`}):(Fe(r)||i.push({it:`${l.it} firmata da te`,en:`${l.en} signed by you`}),Fe(d)||i.push({it:`${l.it} firmata dal PI`,en:`${l.en} signed by the PI`}))}Fe(t==null?void 0:t.advance_pdf)&&!Fe(t==null?void 0:t.advance_signed_pdf)&&i.push({it:"la richiesta di anticipo firmata",en:"the signed advance request"});const o=[fo(t,"request"),fo(t,"assignment"),t==null?void 0:t.advance_signed_pdf].filter(Fe);return{pronto:i.length===0,mancano:i,files:o,precedente:!1}}function cs(t){return Fe(t==null?void 0:t.request_signed_person_pdf)&&Fe(t==null?void 0:t.assignment_signed_person_pdf)}function ds(t){return Fe(t==null?void 0:t.request_signed_pi_pdf)&&Fe(t==null?void 0:t.assignment_signed_pi_pdf)}function Vu(t){const a=[];Fe(t==null?void 0:t.prospetto_signed_pdf)||a.push({it:"il prospetto firmato",en:"the signed statement"}),Fe(t==null?void 0:t.end_declaration_signed_pdf)||a.push({it:"la dichiarazione di fine missione firmata",en:"the signed end-of-mission declaration"});const i=[t==null?void 0:t.prospetto_signed_pdf,t==null?void 0:t.end_declaration_signed_pdf].filter(Fe),n=[t==null?void 0:t.authorized_pdf,t==null?void 0:t.assignment_signed_pdf].filter(Fe),o=[t==null?void 0:t.authorized_pdf,t==null?void 0:t.request_signed_pi_pdf,t==null?void 0:t.request_signed_person_pdf,t==null?void 0:t.request_pdf].find(Fe)||null;return{pronto:a.length===0,mancano:a,firmati:i,direttore:n,richiesta:o}}function Yi(t,a="it"){const i=t.map(s=>a==="en"?s.en:s.it);if(!i.length)return"";const n=a==="en"?" and ":" e ",o=i.length===1?i[0]:`${i.slice(0,-1).join(", ")}${n}${i[i.length-1]}`;return a==="en"?`Still missing: ${o}.`:`${i.length===1?"Manca":"Mancano"} ${o}.`}function Dt({title:t,subtitle:a,file:i,canUpload:n,canRemove:o,locked:s,onUpload:l,onRemove:r,emptyText:d}){const{t:m}=X(),c=f.useRef(null),[g,h]=f.useState(!1),[p,x]=f.useState(!1);async function b(_){var C;if(_){if(_.type&&_.type!=="application/pdf"&&!((C=_.name)!=null&&C.toLowerCase().endsWith(".pdf"))){alert(m("In questo slot sono accettati solo file PDF.","Only PDF files are accepted in this slot."));return}h(!0);try{await l(_)}catch(y){alert(m("Caricamento non riuscito: ","Upload failed: ")+(y.message||y))}finally{h(!1)}}}async function u(_){var y;const C=(y=_.target.files)==null?void 0:y[0];_.target.value="",await b(C)}function w(_){!n||g||(_.preventDefault(),_.stopPropagation(),x(!0))}function v(_){_.preventDefault(),_.stopPropagation(),x(!1)}async function j(_){var y,z;if(!n||g)return;_.preventDefault(),_.stopPropagation(),x(!1);const C=(z=(y=_.dataTransfer)==null?void 0:y.files)==null?void 0:z[0];await b(C)}return e.jsxs("div",{className:"mt-pdf-slot"+(i?" has-file":"")+(s?" is-locked":""),children:[e.jsxs("div",{className:"mt-pdf-head",children:[e.jsxs("div",{children:[e.jsx("strong",{children:t}),e.jsx("div",{className:"muted text-xs",children:a})]}),s&&!n&&e.jsx(cn,{size:14,className:"muted"})]}),i?e.jsxs("div",{className:"mt-pdf-file",children:[e.jsxs("a",{href:Je(i.url),target:"_blank",rel:"noreferrer",className:"mt-pdf-file-link",children:[e.jsx(qt,{size:14})," ",i.name||"file.pdf"]}),e.jsx("span",{className:"muted text-xs",children:i.size?Math.round(i.size/1024)+" KB":""}),e.jsxs("div",{className:"mt-pdf-file-actions",children:[n&&e.jsxs("button",{type:"button",className:"mt-pill mt-pill-sm anim-shimmer",disabled:g,onClick:()=>{var _;return(_=c.current)==null?void 0:_.click()},children:[e.jsx(qa,{size:12})," ",g?m("Caricamentoâ¦","Uploadingâ¦"):m("Sostituisci","Replace")]}),o&&e.jsxs("button",{type:"button",className:"mt-pill mt-pill-sm is-danger",onClick:r,children:[e.jsx($e,{size:12})," ",m("Rimuovi","Remove")]})]})]}
11):n?e.jsxs("div",{className:"mt-pdf-drop"+(p?" is-drag-over":""),onClick:()=>{var _;return!g&&((_=c.current)==null?void 0:_.click())},onDragOver:w,onDragEnter:w,onDragLeave:v,onDrop:j,role:"button",tabIndex:0,onKeyDown:_=>{var C;(_.key==="Enter"||_.key===" ")&&(_.preventDefault(),(C=c.current)==null||C.click())},"aria-disabled":g,"data-busy":g?"1":void 0,children:[e.jsx(qa,{size:18}),e.jsx("span",{className:"mt-pdf-drop-hl",children:g?m("Caricamentoâ¦","Uploadingâ¦"):m("Trascina qui il PDF o clicca per scegliere","Drag the PDF here or click to choose")}),e.jsx("span",{className:"mt-pdf-drop-hint",children:m("Solo file PDF","PDF files only")})]}):e.jsx("div",{className:"mt-pdf-empty",children:d||m("Non ancora caricato dal PI.","Not yet uploaded by the PI.")}),e.jsx("input",{ref:c,type:"file",accept:"application/pdf",className:"mt-hidden-input",onChange:u})]})}const us=[{key:"iscrizione",it:"Iscrizione convegno",en:"Conference fee"},{key:"aereo",it:"Aereo",en:"Flight"},{key:"ferrovia",it:"Ferrovia",en:"Rail"},{key:"piroscafi",it:"Nave / traghetto",en:"Ferry"},{key:"urbano",it:"Mezzi urbani",en:"Urban transport"},{key:"extraurbano",it:"Mezzi extraurbani",en:"Intercity transport"},{key:"taxi_nolo",it:"Taxi / mezzi a nolo",en:"Taxi / rental"},{key:"km_pedaggio",it:"Rimborso km / pedaggio",en:"Mileage / toll"},{key:"pernottamento",it:"Pernottamento",en:"Accommodation"},{key:"pasti",it:"Pasti",en:"Meals"},{key:"altro",it:"Altre spese",en:"Other"}],xn=[{key:"iscrizione_convegno",it:"Iscrizione convegno",en:"Conference fee",group:"iscrizione",travel:!1,file:"Iscrizione"},{key:"volo",it:"Volo",en:"Flight",group:"aereo",travel:!0,file:"Volo"},{key:"treno",it:"Treno",en:"Train",group:"ferrovia",travel:!0,file:"Treno"},{key:"traghetto",it:"Nave / traghetto",en:"Ferry",group:"piroscafi",travel:!0,file:"Nave"},{key:"bus_urbano",it:"Bus urbano",en:"City bus",group:"urbano",travel:!1,file:"Bus"},{key:"metro",it:"Metro / tram",en:"Metro / tram",group:"urbano",travel:!1,file:"Metro"},{key:"pullman",it:"Pullman / extraurbano",en:"Coach",group:"extraurbano",travel:!0,file:"Pullman"},{key:"taxi",it:"Taxi / NCC",en:"Taxi / NCC",group:"taxi_nolo",travel:!1,file:"Taxi"},{key:"noleggio",it:"Noleggio auto",en:"Car rental",group:"taxi_nolo",travel:!1,file:"Noleggio"},{key:"carburante",it:"Carburante (mezzo proprio)",en:"Fuel",group:"km_pedaggio",travel:!1,file:"Carburante"},{key:"pedaggio",it:"Pedaggio autostrada",en:"Toll",group:"km_pedaggio",travel:!1,file:"Pedaggio"},{key:"pernottamento",it:"Pernottamento",en:"Accommodation",group:"pernottamento",travel:!1,file:"Pernotto"},{key:"colazione",it:"Colazione",en:"Breakfast",group:"pasti",travel:!1,file:"Colazione"},{key:"pranzo",it:"Pranzo",en:"Lunch",group:"pasti",travel:!1,file:"Pranzo"},{key:"cena",it:"Cena",en:"Dinner",group:"pasti",travel:!1,file:"Cena"},{key:"bar_snack",it:"Bar / snack",en:"Bar / snack",group:"pasti",travel:!1,file:"Bar"},{key:"supermercato",it:"Supermercato / spesa alimentare",en:"Supermarket",group:"pasti",travel:!1,file:"Supermercato"},{key:"parcheggio",it:"Parcheggio",en:"Parking",group:"altro",travel:!1,file:"Parcheggio"},{key:"acquisto",it:"Acquisto / materiale",en:"Purchase",group:"altro",travel:!1,file:"Acquisto"},{key:"visto",it:"Visto / documenti",en:"Visa / documents",group:"altro",travel:!1,file:"Visto"},{key:"altro",it:"Altro",en:"Other",group:"altro",travel:!1,file:"Spesa"}],ki=Object.fromEntries(xn.map(t=>[t.key,t])),Hu={bus:"bus_urbano",taxi_trasporto:"taxi",aereo:"volo",ferrovia:"treno",piroscafi:"traghetto",urbano:"bus_urbano",extraurbano:"pullman",taxi_nolo:"taxi",km_pedaggio:"carburante",km:"carburante",fs:"treno"};function oa(t){if(ki[t])return ki[t];const a=Hu[t];return a&&ki[a]||ki.altro}function Jr(t,a="it"){const i=oa(t);return a==="en"?i.en:i.it}function Ku(t){return!!oa(t).travel}function Ts(){try{if(typeof crypto<"u"&&crypto.randomUUID)return crypto.randomUUID().slice(0,8)}catch{}return Math.random().toString(36).slice(2,10)}function $n(t,a){const i={},n=xn.some(o=>o.key===i.category)?i.category:"altro";return{id:Ts(),category:n,date:String(i.date||"").slice(0,10),time:String(i.time||"").slice(0,5),amount:Number(i.amount)||0,currency:(i.currency||"EUR").toUpperCase().slice(0,3),rate:Number(i.rate)||1,merchant:String(i.merchant||"").slice(0,80),direction:i.direction==="andata"||i.direction==="ritorno"?i.direction:"",kind:i.kind==="pos"||i.kind==="ticket"?i.kind:"receipt",files:t?[{...t,kind:i.kind==="pos"?"pos":"receipt"}]:[],source:"manual",confidence:Number(i.confidence)||0}}const Ju=.01;function go(t){return String(t||"").toLowerCase().normalize("NFKD").replace(/[Ì-ͯ]/g,"").replace(/[^a-z0-9]+/g," ").trim()}function Yu(t,a){const i=go(t),n=go(a);if(!i||!n)return 0;if(i===n)return 1;if(i.includes(n)||n.includes(i))return .85;const o=new Set(i.split(" ").filter(r=>r.length>2)),s=new Set(n.split(" ").filter(r=>r.length>2));if(!o.size||!s.size)return 0;let l=0;for(const r of o)s.has(r)&&(l+=1);return l/Math.max(o.size,s.size)}function Zu(t,a){const i=Number(t==null?void 0:t.amount)||0,n=(t==null?void 0:t.currency)||"EUR",o=(t==null?void 0:t.date)||"";if(!(i>0)||!o)return[];const s=[];for(const l of a||[]){if(!l||l.id===t.id||(l.currency||"EUR")!==n||Math.abs((Number(l.amount)||0)-i)>Ju||(l.date||"")!==o||!t.merchant&&!l.merchant)continue;const r=Yu(l.merchant,t.merchant);r<.5||s.push({expense_id:l.id,confidence:r>=.85?"high":"medium",why:`Same amount (${n} ${i.toFixed(2)}) and date (${o}); merchant "${l.merchant||"(none)"}" vs "${t.merchant||"(none)"}".`})}return s.sort((l,r)=>(r.confidence==="high"?1:0)-(l.confidence==="high"?1:0))}const xo=["iscrizione","aereo","ferrovia","piroscafi","urbano","extraurbano","taxi_nolo","km_pedaggio","pernottamento","pasti","altro"],bo=Object.fromEntries(xn.map((t,a)=>[t.key,a]));function Oa(t){return[...t].sort((a,i)=>{const n=a.date||"9999-12-31",o=i.date||"9999-12-31";if(n!==o)return n.localeCompare(o);const s=xo.indexOf(oa(a.category).group),l=xo.indexOf(oa(i.category).group);return s!==l?s-l:(bo[a.category]??99)-(bo[i.category]??99)})}function Zi(t){const a=Number(t&&t.amount)||0;if(!t||!t.currency||t.currency==="EUR")return a;const i=Number(t.rate)||0;return a*i}function Li(t){const a={};let i=0;for(const n of t){const o=oa(n.category).group;a[o]||(a[o]={total:0,items:[]});const s=Zi(n);a[o].total+=s,a[o].items.push(n),i+=s}return{byGroup:a,grand:i}}function Xu(t){const a=oa(t.category);let i=a.file;a.travel&&t.direction&&(i+=t.direction==="andata"?"_andata":"_ritorno");const n=(t.date||"").slice(0,10)||"senza-data";return`${i}_${n}`}function Qu(t,a="it"){const i=oa(t.category),n=a==="en"?i.en:i.it,o=i.travel&&t.direction?t.direction==="andata"?a==="en"?" (outbound)":" andata":a==="en"?" (return)":" ritorno":"",s=t.date?ms(t.date):a==="en"?"no date":"senza data",l=a==="en"?" of ":" del ",r=t.merchant?`, ${t.merchant}`:"";return`${n}${o}${l}${s}${r}`}function ms(t){if(!t)return"";const a=/^(\d{4})-(\d{2})-(\d{2})$/.exec(t);return a?`${a[3]}/${a[2]}/${a[1]}`:t}function ut(t,a="EUR"){const i=Number(t)||0;return`${a==="EUR"?"â¬":`${a} `}
11${i.toLocaleString("de-DE",{minimumFractionDigits:2,maximumFractionDigits:2})}`}const vo=20,em=zd-16,bt=5.4,tm=32;function am(){try{const t=new Date;return`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}-${String(t.getDate()).padStart(2,"0")}`}catch{return""}}async function im({mission:t,member:a,expenses:i}){const n=await Pt(),o=new n({unit:"mm",format:"a4"});o.setTextColor("#1d1d1f");let s=vo;const l=u=>{s+u>em&&(o.addPage(),s=vo)},r=(u,w,v,j={})=>{const{size:_=10.5,font:C="normal",color:y="#1d1d1f",gap:z=0}=j;o.setFont(fe,C),o.setFontSize(_),o.setTextColor(y);const T=o.splitTextToSize(Mi(u),v);for(const I of T)l(bt),o.text(I,w,s),s+=bt;z&&(s+=z)};o.setFont(fe,"bold"),o.setFontSize(15),l(bt),o.text("Elenco spese missione",Ne,s),s+=bt+1,r("Documento informale a uso interno â supporto alla compilazione del prospetto riepilogativo ufficiale. Non ha valore fiscale né sostituisce le ricevute originali.",Ne,Pn,{size:9.5,font:"italic",color:"#6b7280",gap:3});const d=(a==null?void 0:a.name)||(t==null?void 0:t.person)||"",m=(t==null?void 0:t.place)||"",c=[t==null?void 0:t.date,t==null?void 0:t.date_end].filter(Boolean).map(ms).join(" â "),g=[d&&`Persona: ${d}`,m&&`Destinazione: ${m}`,c&&`Periodo: ${c}`,(t==null?void 0:t.code)&&`Codice: ${t.code}`].filter(Boolean);o.setFont(fe,"normal"),o.setFontSize(10.5),o.setTextColor("#1d1d1f");for(const u of g)l(bt),o.text(Mi(u),Ne,s),s+=bt;s+=2,o.setDrawColor("#d1d5db"),l(2),o.line(Ne,s,Oe,s),s+=6;const h=Oa(i||[]),{byGroup:p,grand:x}=Li(h),b="EUR";for(const u of us){const w=p[u.key];if(!(!w||!w.items.length)){l(bt+3),o.setFont(fe,"bold"),o.setFontSize(11.5),o.setTextColor("#111827"),o.text(u.it,Ne,s),o.text(ut(w.total,b),Oe,s,{align:"right"}),s+=2,o.setDrawColor("#e5e7eb"),o.line(Ne,s,Oe,s),s+=4,o.setFontSize(10.5),o.setTextColor("#1d1d1f");for(const v of Oa(w.items)){l(bt),o.setFont(fe,"normal");const j=o.splitTextToSize(Mi(Qu(v,"it")),Pn-tm)[0];o.text(j,Ne+2,s);const _=v.currency&&v.currency!=="EUR"?`${ut(Zi(v),"EUR")} (${ut(v.amount,v.currency)})`:ut(Zi(v),"EUR");o.text(_,Oe,s,{align:"right"}),s+=bt}s+=3}}return l(bt+6),o.setDrawColor("#9ca3af"),o.setLineWidth(.4),o.line(Ne,s,Oe,s),o.setLineWidth(.2),s+=6,o.setFont(fe,"bold"),o.setFontSize(12.5),o.setTextColor("#111827"),o.text("Totale complessivo",Ne,s),o.text(ut(x,b),Oe,s,{align:"right"}),s+=bt+3,r(`${h.length} ${h.length===1?"voce di spesa":"voci di spesa"}, generato il ${ms(am())}`,Ne,Pn,{size:9,font:"italic",color:"#6b7280"}),o}async function Is(t){var i,n;const a=await im(t);return za(a,Ca("Elenco spese missione",((i=t==null?void 0:t.member)==null?void 0:i.name)||((n=t==null?void 0:t.mission)==null?void 0:n.person)))}function Xi(t){return String(t||"").replace(/[^A-Za-z0-9]+/g,"_").replace(/^_+|_+$/g,"").slice(0,40)||"missione"}function Yr(t,a){return`Ricevute_${Xi((a==null?void 0:a.name)||(t==null?void 0:t.person))}${t!=null&&t.place?"_"+Xi(t.place):""}.zip`}async function Zr({mission:t,member:a,expenses:i}){const{default:n}=await Sa(()=>Ae(()=>import("./jszip.min-DN5-FNYE.js").then(r=>r.j),__vite__mapDeps([5,4]))),o=new n,s=o.folder("ricevute");try{const r=await Is({mission:t,member:a,expenses:i});o.file(`Elenco_spese_${Xi((a==null?void 0:a.name)||(t==null?void 0:t.person))}.pdf`,r)}catch{}const l={};for(const r of Oa(i)){const d=Xu(r),m=r.files||[];for(let c=0;c<m.length;c++){const g=m[c],h=(String(g.name).split(".").pop()||"pdf").toLowerCase().replace(/[^a-z0-9]/g,"").slice(0,5)||"pdf";let p=d;m.length>1&&(p+=`_${c+1}`);let x=`${p}.${h}`,b=2;for(;l[x];)x=`${p}_${b}.${h}`,b+=1;l[x]=!0;try{s.file(x,await pd(g.url))}catch(u){throw new Error(`«${g.name||x}» non si e' scaricato (${(u==null?void 0:u.message)||u}). Lo ZIP non e' stato creato: riprova tra poco.`)}}}return o.generateAsync({type:"blob"})}function jo(t){const a=URL.createObjectURL(t);return setTimeout(()=>URL.revokeObjectURL(a),10*6e4),a}function yo(t){if(!t)return"";try{return new Date(t).toLocaleDateString("it-IT",{day:"2-digit",month:"long",year:"numeric"})}catch{return t}}function _o({mission:t,member:a,isAdmin:i,onUpdate:n,parte:o=null}){var w,v,j;const{t:s,lang:l}
11=X(),[r,d]=f.useState(!1),[m,c]=f.useState(null),g=Vu(t),h=((w=ye.currentUser)==null?void 0:w.uid)===t.team_uid,p=Array.isArray(t.expense_items)?t.expense_items:[];async function x(_){if(!t.team_uid)throw new Error("team_uid missing on the mission (id="+t.id+").");const C=await ze(`team-missions/${t.team_uid}/${t.id}/dichiarazione_fine_firmata.pdf`,_);await n("end_declaration_signed_pdf",{url:C.url,path:C.path,name:_.name,size:_.size})}async function b(){if(g.pronto){d(!0),n("chiusura_inviata_at",new Date().toISOString());try{const _=Xi((a==null?void 0:a.name)||t.person),C=[];g.richiesta&&C.push({url:g.richiesta.url,name:`Richiesta_missione_${_}.pdf`});for(const y of g.firmati)C.push({url:y.url,name:y.name||"documento.pdf"});if(p.length){const y=await Is({mission:t,member:a,expenses:p}),z=`Elenco_spese_${_}.pdf`;C.push({url:jo(y),name:z});const T=await Zr({mission:t,member:a,expenses:p}),I=Yr(t,a);C.push({url:jo(T),name:I})}c({contesto:{tipo:"missione",id:t.id,titolo:`Chiusura missione a ${t.place||""}`},onEsito:y=>n("invio_chiusura",y),to:"[email protected]",cc:"[email protected]",subject:`Rendicontazione missione â ${t.place||""} â dal ${yo(t.date)} al ${yo(t.date_end||t.date)}`,body:`Gentile Segreteria DJSGE, 12 13allego la documentazione della missione in oggetto: richiesta di autorizzazione alla missione, prospetto riepilogativo delle spese e dichiarazione di fine missione firmati, elenco delle spese e ricevute. 14 15Cordiali saluti, 16${t.person||(a==null?void 0:a.name)||""}`,files:C})}catch(_){alert(s("Preparazione dellâinvio non riuscita: ","Preparing the email failed: ")+(_.message||_))}finally{d(!1)}}}const u=[{ok:!!g.richiesta,it:"Richiesta di autorizzazione alla missione",en:"Mission authorisation request",facoltativa:!0},{ok:!!((v=t.prospetto_signed_pdf)!=null&&v.url),it:"Prospetto firmato (passo 3)",en:"Signed statement (step 3)"},{ok:!!((j=t.end_declaration_signed_pdf)!=null&&j.url),it:"Dichiarazione di fine missione firmata (passo 4)",en:"Signed end-of-mission declaration (step 4)"},{ok:p.length>0,it:"Elenco spese e ZIP delle ricevute (li prepara il sistema)",en:"Expense list and receipts ZIP (prepared by the system)",facoltativa:!0}];return e.jsxs("div",{className:"mt-chiusura",children:[o!=="invio"&&e.jsx(Dt,{title:s("Dichiarazione di fine missione â firmata","End-of-mission declaration â signed"),subtitle:s("il PDF generato qui sopra, firmato","the PDF generated above, signed"),file:t.end_declaration_signed_pdf,canUpload:h||i,canRemove:h||i,emptyText:s("Non ancora caricata.","Not uploaded yet."),onUpload:x,onRemove:async()=>{var _;(_=t.end_declaration_signed_pdf)!=null&&_.path&&await de(t.end_declaration_signed_pdf.path),await n("end_declaration_signed_pdf",null)}}),o!=="dichiarazione"&&e.jsxs("div",{className:"mt-chiusura-invio",children:[e.jsx(_i,{invio:t.invio_chiusura}),e.jsx("ul",{className:"mt-chiusura-lista",children:u.map(_=>e.jsxs("li",{className:_.ok?"is-ok":"",children:[_.ok?e.jsx(ke,{size:14}):e.jsx(ts,{size:14}),e.jsx("span",{children:l==="en"?_.en:_.it})]},_.it))}),e.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:!g.pronto||r,onClick:b,title:g.pronto?s("Scarica i documenti finali e prepara la mail","Downloads the final documents and drafts the email"):Yi(g.mancano,l),children:[e.jsx(Ot,{size:12})," ",r?s("Preparo i fileâ¦","Preparing the filesâ¦"):s("Invia la chiusura alla Segreteria DJSGE","Send the closing to the DJSGE Secretariat")]}),!g.pronto&&e.jsx("span",{className:"mt-firme-manca",children:Yi(g.mancano,l)})]}),m&&e.jsx(Da,{info:m,onClose:()=>c(null)})]})}function Ga(t){let a=!1;return t.map(i=>i?"fatto":a?"dopo":(a=!0,"adesso"))}function va({n:t,titolo:a,sotto:i,stato:n="dopo",facoltativo:o=!1}){return e.jsxs("div",{className:`passo-testa is-${n}${o?" is-facoltativo":""}`,children:[e.jsx("span",{className:"passo-num","aria-hidden":"true",children:n==="fatto"?e.jsx(ke,{size:14,strokeWidth:3}):t}),e.jsxs("span",{className:"passo-testi",children:[e.jsxs("span",{className:"passo-titolo",children:[a,o&&e.jsx("span",{className:"passo-facoltativo",children:"facoltativo"})]}),i&&e.jsx("span",{className:"passo-sotto",children:i})]})]})}function dt({children:t,...a}){return e.jsxs("section",{className:`passo is-${a.stato||"dopo"}`,children:[e.jsx(va,{...a}),e.jsx("div",{className:"passo-corpo",children:t})]})}const pa=t=>
16`${Number(t||0).toLocaleString("de-DE",{minimumFractionDigits:2,maximumFractionDigits:2})} â¬`;function Xr({pratica:t,acquisto:a=!1}){const{t:i}=X(),n=t==null?void 0:t.costo_effettivo;if(!n||!(Number(n.totale)>0))return null;const o=t.confronto_costo,s=a?n.fatture===1?i("1 fattura","1 invoice"):i(`${n.fatture} fatture`,`${n.fatture} invoices`):n.mandati===1?i("1 mandato","1 payment order"):i(`${n.mandati} mandati`,`${n.mandati} payment orders`);return e.jsxs("div",{className:`mt-costo${o?o.corrisponde?" is-ok":" is-diff":""}`,children:[e.jsx("span",{className:"mt-costo-icona",children:o?o.corrisponde?e.jsx(tt,{size:18}):e.jsx(ba,{size:18}):e.jsx(uc,{size:18})}),e.jsxs("span",{className:"mt-costo-testo",children:[e.jsxs("strong",{children:[i("Costo effettivo: ","Actual cost: "),pa(n.totale)]}),e.jsxs("span",{children:[i(`dai ${s} caricati`,`from the ${s} uploaded`),o&&(o.corrisponde?i(`, corrisponde alla cifra prevista (${pa(o.atteso)})`,`, matches the expected amount (${pa(o.atteso)})`):i(`, prevista ${pa(o.atteso)}: differenza ${o.differenza>0?"+":""}${pa(o.differenza)}`,`, expected ${pa(o.atteso)}: difference ${o.differenza>0?"+":""}${pa(o.differenza)}`)),n.incerti>0&&i(`. Lettura incerta su ${n.incerti}: da controllare sul documento.`,`. Uncertain reading on ${n.incerti}: check the document.`)]})]})]})}const Oi=t=>/pdf/i.test((t==null?void 0:t.mime)||"")||/\.pdf$/i.test((t==null?void 0:t.name)||"")||/\.pdf$/i.test(decodeURIComponent(String((t==null?void 0:t.url)||"").split("?")[0])),oi=t=>/^image\//.test((t==null?void 0:t.mime)||"")||/\.(jpe?g|png|webp|gif|heic)$/i.test((t==null?void 0:t.name)||"");function nm({file:t}){const a=f.useRef(null),i=f.useRef(null),[n,o]=f.useState(!1),[s,l]=f.useState(!1);return f.useEffect(()=>{const r=a.current;if(!r||n)return;if(typeof IntersectionObserver>"u"){o(!0);return}const d=new IntersectionObserver(m=>{m.some(c=>c.isIntersecting)&&(o(!0),d.disconnect())},{rootMargin:"200px"});return d.observe(r),()=>d.disconnect()},[n]),f.useEffect(()=>{if(!n||!Oi(t)||oi(t))return;let r=!1;return(async()=>{try{const d=await Ae(()=>import("./pdf-C2NMrW9w.js"),[]),m=(await Ae(async()=>{const{default:x}=await import("./pdf.worker.min-Dz6j0T0P.js");return{default:x}},[])).default;d.GlobalWorkerOptions.workerSrc=m;const g=await(await d.getDocument({url:t.url}).promise).getPage(1);if(r||!i.current)return;const h=g.getViewport({scale:1}),p=g.getViewport({scale:220/h.width*2});i.current.width=p.width,i.current.height=p.height,await g.render({canvasContext:i.current.getContext("2d"),viewport:p}).promise}catch{r||l(!0)}})(),()=>{r=!0}},[n,t]),e.jsxs("span",{ref:a,className:"mfd-thumb",children:[n&&oi(t)&&e.jsx("img",{src:Rc(t.url),alt:"",loading:"lazy"}),n&&!oi(t)&&Oi(t)&&!s&&e.jsx("canvas",{ref:i,"aria-hidden":"true"}),(!n||s||!oi(t)&&!Oi(t))&&e.jsx(Ue,{size:28})]})}function sm({voce:t}){const a=()=>{const i=t.file.mime||(oi(t.file)?"image":Oi(t.file)?"application/pdf":null);Er(t.file.url,t.file.name,i)};return e.jsxs("button",{type:"button",className:"mfd-card",onClick:a,title:t.file.name,children:[e.jsx(nm,{file:t.file}),e.jsxs("span",{className:"mfd-card-txt",children:[e.jsx("strong",{children:t.titolo}),t.sotto&&e.jsx("span",{children:t.sotto})]})]})}function Si({titolo:t,voci:a,vuota:i}){const n=f.useRef(null),o=s=>{const l=n.current;l&&l.scrollBy({left:s*l.clientWidth*.85,behavior:"smooth"})};return e.jsxs("section",{className:"mfd-fila",children:[e.jsxs("div",{className:"mfd-fila-head",children:[e.jsxs("h4",{children:[t," ",e.jsx("span",{className:"mfd-conta",children:a.length})]}),a.length>2&&e.jsxs("span",{className:"mfd-frecce",children:[e.jsx("button",{type:"button",onClick:()=>o(-1),"aria-label":"Indietro",children:e.jsx(dn,{size:16})}),e.jsx("button",{type:"button",onClick:()=>o(1),"aria-label":"Avanti",children:e.jsx(yt,{size:16})})]})]}),a.length?e.jsx("div",{className:"mfd-riga",ref:n,children:a.map(s=>e.jsx(sm,{voce:s},s.key))}):e.jsx("p",{className:"mfd-vuota",children:i})]})}const Kt=t=>!!(t&&t.url);function om({mission:t,member:a}){var O,k;const{t:i,lang:n}=X(),[o,s]=f.useState(null),[l,r]=f.useState(null),[d,m]=f.useState(!1),c={autorizzazione:i("Autorizzazione firmata dal Direttore","Authorisation signed by the Director"),lettera:i("Lettera di incarico firmata dal Direttore","Assignment letter signed by the Director"),mandato:i("Mandato di pagamento","Payment order"),altro:i("Documento della Direzione","Document from the Direction")},g=[];Kt(t.authorized_pdf)&&g.push({key:"aut",titolo:c.autorizzazione,file:t.authorized_pdf}),Kt(t.assignment_signed_pdf)&&g.push({key:"let",titolo:c.lettera,file:t.assignment_signed_pdf}
16),(Array.isArray(t.direzione_docs)?t.direzione_docs:[]).forEach(N=>{var L,B;N.kind==="autorizzazione"&&((L=t.authorized_pdf)==null?void 0:L.path)===N.path||N.kind==="lettera"&&((B=t.assignment_signed_pdf)==null?void 0:B.path)===N.path||g.push({key:`dir-${N.id}`,titolo:c[N.kind]||c.altro,sotto:N.name,file:N})});const h=[];Kt(t.prospetto_signed_pdf)&&h.push({key:"pro",titolo:i("Prospetto firmato","Signed statement"),file:t.prospetto_signed_pdf}),Kt(t.end_declaration_signed_pdf)&&h.push({key:"dic",titolo:i("Dichiarazione di fine missione firmata","Signed end-of-mission declaration"),file:t.end_declaration_signed_pdf});const p=[],x=t.request_signed_pi_pdf||t.request_signed_person_pdf||t.request_pdf,b=t.assignment_signed_pi_pdf||t.assignment_signed_person_pdf||t.assignment_pdf;Kt(x)&&p.push({key:"req",titolo:i("Richiesta di missione","Mission request"),file:x}),Kt(b)&&p.push({key:"asg",titolo:i("Lettera di incarico","Assignment letter"),file:b});const u=t.advance_signed_pdf||t.advance_pdf;Kt(u)&&p.push({key:"adv",titolo:i("Richiesta di anticipazione","Advance request"),file:u});const w=[];(Array.isArray(t.expense_items)?t.expense_items:[]).forEach(N=>{(N.files||[]).forEach((L,B)=>{if(!Kt(L))return;const P=String(N.date||"").slice(0,10).split("-").reverse().join("/");w.push({key:`${N.id}-${B}`,titolo:`${Jr(N.category,n)} ${ut(N.amount,N.currency)}`,sotto:[P,N.merchant].filter(Boolean).join(", "),file:L})})});const v=Array.isArray(t.direzione_richieste)?t.direzione_richieste:[];async function j(N,L){const{getFunctions:B,httpsCallable:P}=await Ae(async()=>{const{getFunctions:W,httpsCallable:M}=await import("./vendor-firebase-AOn3Fvmd.js").then(J=>J.ah);return{getFunctions:W,httpsCallable:M}},[]),{app:E}=await Ae(async()=>{const{app:W}=await import("./firebase-config-Dn2Tu_JL.js").then(M=>M.c);return{app:W}},__vite__mapDeps([3,2]));return(await P(B(E,"europe-west1"),"direzioneLinkMissione")({missionId:t.id,invia:N,fase:L})).data}const[_,C]=f.useState(null);function y(N){const L=Date.parse(String(N||"").slice(0,10));return Number.isFinite(L)?new Date(L).toLocaleDateString("it-IT",{day:"numeric",month:"long",year:"numeric",timeZone:"UTC"}):""}async function z(){s("mail"),r(null);try{const{url:N}=await j(!1),L=t.date_end&&t.date_end!==t.date?`dal ${y(t.date)} al ${y(t.date_end)}`:y(t.date);C({url:N,subject:`Missione di ${t.person||""} a ${t.place||""}: documentazione da caricare`,body:`Gentile Dott. Vizzielli, 17 18con riferimento alla missione di ${t.person||""} a ${t.place||""} (${L}), come da accordi Le chiedo cortesemente di voler caricare lâautorizzazione alla missione e la lettera di incarico sottoscritte dal Direttore, i mandati di pagamento e lâulteriore documentazione relativa alla missione tramite il collegamento riportato di seguito. 19 20La raccolta consente di conservare in un unico archivio digitale, in modo ordinato e completo, tutta la documentazione della missione ai fini della rendicontazione del progetto. 21 22Il collegamento è riservato a questa missione e non richiede credenziali di accesso. Resta attivo anche successivamente, per eventuali integrazioni della documentazione. 23 24Dalla stessa pagina è possibile consultare tutte le missioni del progetto e i documenti già caricati, inserendo il codice di accesso 04052026. 25 26La ringrazio per la collaborazione. 27 28Cordiali saluti, 29Giuseppe Naglieri 30Principal Investigator del progetto CLIMPACT (FIS 3) 31Università degli Studi di Bari Aldo Moro`})}catch(N){r({ok:!1,testo:i("Non riesco a preparare il collegamento: ","Could not prepare the link: ")+((N==null?void 0:N.message)||N)})}finally{s(null)}}async function T(){C(null);try{const{getFunctions:N,httpsCallable:L}=await Ae(async()=>{const{getFunctions:P,httpsCallable:E}=await import("./vendor-firebase-AOn3Fvmd.js").then(Y=>Y.ah);return{getFunctions:P,httpsCallable:E}},[]),{app:B}=await Ae(async()=>{const{app:P}=await import("./firebase-config-Dn2Tu_JL.js").then(E=>E.c);return{app:P}},__vite__mapDeps([3,2]));await L(N(B,"europe-west1"),"direzioneLinkMissione")({missionId:t.id,registra:!0})}catch(N){console.warn("[direzione] registra",N)}r({ok:!0,testo:i("Mail partita. I file che la Direzione carica arr
31ivano qui.","Email sent. The files the Direction uploads arrive here.")})}async function I(){s("link"),r(null);try{const{url:N}=await j(!1);await navigator.clipboard.writeText(N),r({ok:!0,testo:i("Collegamento copiato: si apre senza accesso.","Link copied: it opens without signing in.")})}catch(N){r({ok:!1,testo:i("Non riesco a preparare il collegamento: ","Could not prepare the link: ")+((N==null?void 0:N.message)||N)})}finally{s(null)}}async function D(){m(!0);try{const{default:N}=await Sa(()=>Ae(()=>import("./jszip.min-DN5-FNYE.js").then(Y=>Y.j),__vite__mapDeps([5,4]))),L=new N;await kr(L,Sr(t));const B=await L.generateAsync({type:"blob"}),P=URL.createObjectURL(B),E=document.createElement("a");E.href=P,E.download=Dr(t,a==null?void 0:a.name),document.body.appendChild(E),E.click(),E.remove(),setTimeout(()=>URL.revokeObjectURL(P),6e4)}catch(N){r({ok:!1,testo:i("ZIP non riuscito: ","ZIP failed: ")+((N==null?void 0:N.message)||N)})}finally{m(!1)}}const $=(()=>{const N=v.map(L=>L.at).sort().pop();return N?new Date(N).toLocaleDateString("it-IT",{day:"numeric",month:"long"}):null})(),q=(O=t.closed_at)!=null&&O.toMillis?t.closed_at.toMillis():(k=t.closed_at)!=null&&k.seconds?t.closed_at.seconds*1e3:0,R=q>=Date.parse("2026-09-23T00:00:00Z")&&!t.direzione_auto_chiusura_at&&!$?new Date(q+7*24*3600*1e3).toLocaleDateString("it-IT",{day:"numeric",month:"long"}):null;return e.jsxs("div",{className:"mfd",children:[e.jsxs("div",{className:"mfd-azioni",children:[e.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:!!o,onClick:z,children:[o==="mail"?e.jsx(me,{size:12,className:"spin"}):e.jsx(We,{size:12})," ",i("Chiedi i documenti alla Direzione","Ask the Direction for the documents")]}),e.jsxs("button",{type:"button",className:"btn btn-ghost btn-sm",disabled:!!o,onClick:I,title:i("Copia lâindirizzo della pagina dove la Direzione carica i documenti, senza mandare nessuna mail: per incollarlo tu dove vuoi.","Copies the address of the page where the Direction uploads the documents, without sending any email: to paste it wherever you like."),children:[e.jsx(Tt,{size:12})," ",i("Copia il collegamento (senza mail)","Copy the link (no email)")]}),e.jsxs("button",{type:"button",className:"btn btn-ghost btn-sm",disabled:d,onClick:D,children:[d?e.jsx(me,{size:12,className:"spin"}):e.jsx(Ua,{size:12})," ",i("Scarica tutto (ZIP)","Download all (ZIP)")]})]}),$&&e.jsx("p",{className:"mfd-nota",children:i(`Documenti chiesti alla Direzione il ${$}.`,`Documents requested from the Direction on ${$}.`)}),R&&e.jsx("p",{className:"mfd-nota",children:i(`La richiesta dei documenti a Vizzielli parte da sola il ${R}, una settimana dopo la chiusura.`,`The document request to Vizzielli goes out on its own on ${R}, a week after closing.`)}),l&&e.jsxs("p",{className:"mfd-esito"+(l.ok?" is-ok":""),children:[l.ok&&e.jsx(ke,{size:14})," ",l.testo]}),e.jsx(Xr,{pratica:t}),e.jsx(Si,{titolo:i("Dalla Direzione","From the Direction"),voci:g,vuota:i("Ancora niente: autorizzazione, lettera firmata dal Direttore e mandati arrivano qui quando la Direzione li carica.","Nothing yet: the authorisation, the letter signed by the Director and the payment orders arrive here once the Direction uploads them.")}),e.jsx(Si,{titolo:i("Chiusura della missione","Mission closing"),voci:h,vuota:i("Il prospetto e la dichiarazione firmati si caricano nella scheda del prospetto.","The signed statement and declaration are uploaded in the statement tab.")}),e.jsx(Si,{titolo:i("Partenza","Departure"),voci:p,vuota:i("Richiesta e lettera si caricano nei dati della missione.","The signed request and letter are uploaded in the mission data.")}),e.jsx(Si,{titolo:i("Ricevute","Receipts"),voci:w,vuota:i("Nessuna ricevuta registrata.","No receipt filed.")}),_&&e.jsx(Ns,{open:!0,assetsPrivate:!0,onClose:()=>C(null),onSent:T,sendMail:Ra,loadRecipients:async()=>[],portalLabel:"Research Team",initialAudience:{mode:"custom",emails:"[email protected]"},templates:[{id:"direzione",label:i("Richiesta documenti alla Direzione","Document request to the Direction"),build:()=>_}],initialPrefill:{templateId:"direzione"},wrapHtml:(N,L,B)=>Wi({heading:L,bodyHtml:N,headerGradient:B==null?void 0:B.headerGradient,ctaLabel:"Carica i documenti",ctaHref:_.url,manualLabel:"In alternativa, copiare questo indirizzo nel browser:",policyHref:"https://www.climpact.it/privacy"})})]})}const rm=[{key:"bus",label:"Bus"},{key:"treno",label:"Treno"},{key:"aereo",label:"Aereo"},{key:"proprio",label:"Mezzo proprio (preventiva autorizzazione)"},{key:"altro",label:"Altro"}],lm=[{key:"economica",label:"Convenienza economica"},{key:"non_servito",label:"Luogo missione non servito da ferrovia né da altri mezz
31i ordinari"},{key:"orario",label:"Orario dei mezzi incompatibile con lo svolgimento della missione"},{key:"materiali",label:"Trasporto materiali delicati, pesanti o ingombranti"}];function No(t,a,i,n,o={}){const{gap:s=6,size:l=Me,font:r="normal",boxSize:d=3,labelGap:m=1.5,rowGap:c=1.6}=o;t.setFont(fe,r),t.setFontSize(l),t.setTextColor("#1d1d1f"),t.setDrawColor("#1d1d1f"),a.needSpace(je);let g=a.y,h=Ne;for(const p of i){const x=t.getTextWidth(p.label),b=d+m+x;h+b>Oe&&h>Ne&&(g+=je+c,h=Ne,a.needSpace(je+c));const u=g-d+.6;t.rect(h,u,d,d),n.includes(p.key)&&(t.setLineWidth(.5),t.line(h+.4,u+.4,h+d-.4,u+d-.4),t.line(h+d-.4,u+.4,h+.4,u+d-.4),t.setLineWidth(.2)),t.text(p.label,h+d+m,g),h+=b+s}a.y=g+je*.4}async function cm(t,a){const i=await Pt(),n=new i({unit:"mm",format:"a4"}),o=await Gt();Wt(n,o);const s=da(n,o);n.setFont(fe,"normal"),n.setFontSize(Me),n.setTextColor("#1d1d1f"),n.text(`Taranto, ${Ge(new Date)}`,Ne,s.y),n.setFont(fe,"bold"),n.text(`Al Direttore del ${aa}`,Oe,s.y,{align:"right"}),s.advance(je+10),jt(n,s,"RICHIESTA AUTORIZZAZIONE MISSIONE",{gap:.5}),n.setFont(fe,"italic"),n.setFontSize(Me-1),n.text("(presentare allâufficio contabilità almeno 5 giorni prima della partenza)",Zt/2,s.y,{align:"center"}),s.advance(je+8);const l=((a==null?void 0:a.name)||"").trim()||"[Nome Cognome]",r=((t==null?void 0:t.qualifica)||(a==null?void 0:a.qualifica)||"").trim()||"[qualifica]";ee(n,s,`Il sottoscritto ${l}`,{gap:3}),ee(n,s,`qualifica ${r}`,{gap:3}),ee(n,s,"chiede lâautorizzazione a compiere la missione a",{gap:2});const d=((t==null?void 0:t.title)||(t==null?void 0:t.destination)||"").trim()||"[descrizione missione: destinazione, scopo, sede]";ee(n,s,d,{bold:!0,gap:3});const m=t!=null&&t.date_start?Ge(t.date_start):"___________",c=t!=null&&t.date_end?Ge(t.date_end):"___________";ee(n,s,`dal ${m} al ${c}`,{gap:6}),ee(n,s,"Mezzo di trasporto:",{gap:1});const g=((t==null?void 0:t.transport)||"").trim();No(n,s,rm,g?[g]:[]),s.advance(4),ee(n,s,"Giustifica uso mezzo proprio:",{gap:1});const h=Array.isArray(t==null?void 0:t.own_transport_reasons)?t.own_transport_reasons:[];No(n,s,lm,h,{gap:5}),s.advance(6),ee(n,s,"La spesa deve gravare sul fondo UPB",{gap:2});const p=((t==null?void 0:t.upb)||"").trim()||ji;return Ma(n,s,p,{font:"bold"}),s.advance(14),Tr(n,s,{role:"Il/La richiedente",name:l},{role:"Il/La Responsabile dei fondi",name:""},{sigGap:16,gap:10}),s.advance(6),ws(n,s,"Si autorizza",`Il Direttore del ${aa}`,{font:"bold",sigGap:je,gap:4}),n}const dm=t=>Ca("Richiesta autorizzazione missione",t==null?void 0:t.name);async function um({mission:t,member:a}){const i=await cm(t||{},a||{}),n=((t==null?void 0:t.title)||(t==null?void 0:t.destination)||"missione").slice(0,40),o=((a==null?void 0:a.name)||"membro").replace(/[^A-Za-z0-9]+/g,"_").slice(0,30);await ka(i,["Richiesta_autorizzazione_missione",o,n],dm(a))}async function mm(t,a){const i=await Pt(),n=new i({unit:"mm",format:"a4"}),o=await Gt();Wt(n,o);const s=da(n,o);zs(n,s,[`Al Direttore del ${aa}`],{font:"bold",gap:10}),ee(n,s,"Oggetto: Richiesta di autorizzazione allâuso del mezzo proprio.",{bold:!0,gap:6});const l=((a==null?void 0:a.name)||"").trim()||"[Nome Cognome]",r=((t==null?void 0:t.title)||(t==null?void 0:t.destination)||(t==null?void 0:t.description)||"").trim()||"[destinazione e descrizione missione]";ee(n,s,`Il/la sottoscritto/a ${l}`,{gap:3}),ee(n,s,`In esecuzione dellâincarico conferitogli/le per lâattività di servizio fuori sede â missione a ${r}`,{gap:6,align:"justify"}),jt(n,s,"CHIEDE",{size:Me+1,gap:4}),ee(n,s,"di essere autorizzato/a a servirsi del mezzo proprio di trasporto per la seguente motivazione:",{gap:3,align:"justify"});const d=((t==null?void 0:t.own_vehicle_motivation)||"").trim()||"[motivazione dellâuso del mezzo proprio â es. orari treni incompatibili, assenza di collegamenti diretti, esigenze di trasporto materiali, ecc.]";ee(n,s,d,{gap:6,align:"justify"}),ee(n,s,"Comunica, a tal proposito, quanto segue:",{gap:2});const m=((t==null?void 0:t.own_vehicle_make_model)||"").trim()||"_______________________",c=((t==null?void 0:t.own_vehicle_plate)||"").trim()||"_______________",g=((t==null?void 0:t.own_license_number)||"").trim()||"_______________",h=((t==null?void 0:t.own_license_issued_by)||"").trim()||"_______________________",p=t!=null&&t.own_license_issued_date?Ge(t.own_license_issued_date):"__________",x=((t==null?void 0:t.own_insurance_company)||"").trim()||"_______________",b=((t==null?void 0:t.own_insurance_policy_number)||"").trim()||"_______________";return ee(n,s,`Autovettura tipo ${m}`,{gap:1}),ee(n,s,`Targata ${c};`,{gap:1}),ee(n,s,`Patente di guida n. ${g};`,{gap:1}),ee(n,s,`Rilasciata da ${h} il ${p};`,{gap:1}),ee(n,s,`Che il mezzo di cui sopra è coperto da polizza RCA obbligatoria con la compagnia assicurativa ${x} n. ${b}.`,{gap:4,align:"justify"}),ee(n,s,"Dichiara di sollevare lâAmministrazione universitaria da qualsiasi responsabilità diretta e indiretta poiché il veicolo sopra citato è stato sottoposto a revisione e collaudo periodico in osservanza delle norme riguardanti la circolazione stradale.",{gap:8,align:"justify"}),n.setFont(fe,"normal"),n.setFontSize(Me),n.setTextColor("#1d1d1f"),n.text(`Taranto, ${Ge(new Date)}`,Ne,s.y),s.advance(je),Cs(n,s,"Il/la richiedente",l,{sigGap:14}),s.advance(8),ee(n,s,"Vista la motivazione citata e sottoscritta;",{gap:1}),ee(n,s,"vista la dichiarazione resa dallâinteressato/a ai fini della responsabilità civile e penale;",{gap:1}),ee(n,s,"visto il regolamento per il trattamento economico dellâUniversità di Bari,",{gap:4}),jt(n,s,"A U T O R I Z Z A",{size:Me+1,gap:4}),ee(n,s,"Il/la richiedente a compiere la missione di cui sopra nei tempi determinati nel provvedimento di incarico.",{gap:14,align:"justify"}),ws(n,s,`Il Direttore del ${aa}`,"",{font:"bold",sigGap:0,gap:4}),n}async function pm({mission:t,member:a}){const i=await mm(t||{},a||{}
31),n=((t==null?void 0:t.title)||(t==null?void 0:t.destination)||"missione").slice(0,40),o=((a==null?void 0:a.name)||"membro").replace(/[^A-Za-z0-9]+/g,"_").slice(0,30);await ka(i,["Autorizzazione_mezzo_proprio",o,n],Ca("Richiesta di autorizzazione allâuso del mezzo proprio",a==null?void 0:a.name))}function rt(t,a="____________"){return String(t??"").trim()||a}function Di(t){if(!t)return"____________";try{const a=t instanceof Date?t:new Date(t);return Number.isNaN(a.getTime())?String(t):a.toLocaleDateString("it-IT",{day:"2-digit",month:"2-digit",year:"numeric"})}catch{return String(t)}}async function Qr(t){const a=await Pt(),i=new a({unit:"mm",format:"a4"}),n=await Gt();Wt(i,n);const o=da(i,n);o.advance(10),jt(i,o,"DICHIARAZIONE DI FINE MISSIONE",{gap:.5}),o.advance(je+6),i.setFont(fe,"normal"),i.setFontSize(Me),i.setTextColor("#1d1d1f");const s=((t==null?void 0:t.gender)||"f").toLowerCase(),l=s==="m"?"Il sottoscritto":"La sottoscritta",r=s==="m"?"nato":"nata",d=rt(t.full_name,"[Nome Cognome]"),m=rt(t.birth_place,"[luogo di nascita]"),c=Di(t.birth_date),g=rt(t.fiscal_code,"[codice fiscale]"),h=rt(t.qualifica,"[qualifica]"),p=rt(t.subject,"[materia]"),x=rt(t.department,'Dipartimento Jonico in "Sistemi Giuridici ed Economici del Mediterraneo: società , ambiente, culture"'),b=rt(t.university,'Università degli Studi di Bari "Aldo Moro"'),u=rt(t.destination,"[destinazione]"),w=Di(t.assignment_date),v=rt(t.purpose,"[motivo della missione]"),j=rt(t.project,"[titolo del progetto]"),_=rt(t.project_code,"[codice progetto]"),C=rt(t.cup,"[CUP]"),y=Di(t.date_start),z=Di(t.date_end),T=String(t.notes||"").trim();let I=`${l} ${d} ${r} a ${m} il ${c}, C.F. ${g}, ${h} in â${p}â presso il ${x} dellâ${b}, in esecuzione dellâincarico di missione a ${u} del ${w}, per ${v}, nellâambito dello svolgimento di attività istituzionale di ricerca relativa al progetto ${j} â CODICE PROGETTO: ${_} â CUP ${C}`;T&&(I+=`. ${T}`),ee(i,o,I,{gap:6}),jt(i,o,"DICHIARA",{gap:.5,size:Me}),o.advance(je+2),ee(i,o,`che la missione ha avuto inizio il ${y} e si è conclusa il ${z}.`,{gap:14});const D=rt(t.signature_place,"Taranto"),$=t.signature_date?Ge(t.signature_date):Ge(new Date);i.setFont(fe,"normal"),i.setFontSize(Me),i.text(`${D}, ${$}`,Ne,o.y),o.advance(je+16);const q=/prof/i.test(h),R=String(t.signature_title||"").trim()||(q?s==="m"?"Prof.":"Prof.ssa":s==="m"?"Dott.":"Dott.ssa");return i.setFont(fe,"italic"),i.setFontSize(Me),i.text(`${R} ${d}`.trim(),Oe-4,o.y,{align:"right"}),i}const el=t=>Ca("Dichiarazione di fine missione",t==null?void 0:t.full_name);async function hm(t){const a=await Qr(t||{}),i=((t==null?void 0:t.full_name)||"membro").replace(/[^A-Za-z0-9]+/g,"_").slice(0,40),n=((t==null?void 0:t.destination)||"").replace(/[^A-Za-z0-9]+/g,"_").slice(0,30);await ka(a,["Dichiarazione_fine_missione",i,n].filter(Boolean),el(t))}async function fm(t){const a=await Qr(t||{});return za(a,el(t))}const gm="CLIMPACT â Charting the Landscape of Climate Litigation Impacts: An Interdisciplinary Framework and Open Access Database (FIS 3 Starting Grant)",xm="FIS-03396",bm="H53C25000820001",vm='Dipartimento Jonico in "Sistemi Giuridici ed Economici del Mediterraneo: società , ambiente, culture"',jm='Università degli Studi di Bari "Aldo Moro"';function Ia(t){if(!t)return"";if(typeof t=="string")return t.slice(0,10);try{const a=t instanceof Date?t:new Date(t);if(Number.isNaN(a.getTime()))return"";const i=a.getFullYear(),n=String(a.getMonth()+1).padStart(2,"0"),o=String(a.getDate()).padStart(2,"0");return`${i}-${n}-${o}`}catch{return""}}function ym({mission:t,member:a,onClose:i,onPatch:n}){const{t:o}=X(),s=f.useMemo(()=>({...{gender:(a==null?void 0:a.gender)||"f",full_name:(a==null?void 0:a.name)||(t==null?void 0:t.person)||"",birth_place:(a==null?void 0:a.birth_place)||"",birth_date:Ia(a==null?void 0:a.birth_date),fiscal_code:(a==null?void 0:a.fiscal_code)||"",qualifica:(t==null?void 0:t.qualifica)||(a==null?void 0:a.qualifica)||"",signature_title:(a==null?void 0:a.signature_title)||"",subject:(a==null?void 0:a.subject)||(a==null?void 0:a.job_title)||"",department:(a==null?void 0:a.department)||vm,university:(a==null?void 0:a.university)||jm,destination:(t==null?void 0:t.place)||"",assignment_date:Ia((t==null?void 0:t.authorized_at)||(t==null?void 0:t.created_at))||Ia(t==null?void 0:t.date),purpose:(t==null?void 0:t.description)||"",project:(t==null?void 0:t.project_title)||gm,project_code:(t==null?void 0:t.project_code)||xm,cup:(t==null?void 0:t.cup)||bm,date_start:Ia(t==null?void 0:t.date),date_end:Ia(t==null?void 0:t.date_end),notes:"",signature_place:(a==null?void 0:a.signature_place)||"Taranto",signature_date:Ia(new Date)},...(t==null?void 0:t.end_declaration_data)||{}}),[t,a]),[l,r]=f.useState(s),[d,m]=f.useState(!1),[c,g]=f.useState(null);f.useEffect(()=>{r(s)},[s]);const h=Mr({scope:"rt-end-declaration",id:t==null?void 0:t.id,uid:a==null?void 0:a.uid},l);function p(b){return u=>r(w=>({...w,[b]:u.target.value}))}async function x(){m(!0),g(null);try{await hm(l),h.clear(l);try{if(typeof n=="function"&&(t!=null&&t.team_uid)&&(t!=null&&t.id)){const b=await fm(l),u=(l.full_name||(a==null?void 0:a.name)||"membro").replace(/[^A-Za-z0-9]+/g,"_").slice(0,30),w=(l.destination||(t==null?void 0:t.place)||"").replace(/[^A-Za-z0-9]+/g,"_").slice(0,30),v=`Dichiarazione_fine_missione_${u}_${w}.pdf`,j=new File([b],v,{type:"application/pdf"}),_=`team-missions/${t.team_uid}/${t.id}/end_declaration.pdf`,C=await ze(_,j);await n({end_declaration_pdf:{url:C.url,path:C.path,name:j.name,size:j.size},end_declaration_data:l})}}catch(b){console.warn("[end-declaration] auto-upload failed",b)}i==null||i()}catch(b){g((b==null?void 0:b.message)||String(b))}finally{m(!1)}}return ra.createPortal(e.jsxs("div",{className:"modal-backdrop anim-scrim mt-dialog-host",role:"dialog","aria-modal":"true","aria-labelledby":"med-title",onClick:b=>{b.target===b.currentTarget&&(i==null||i())},children:[e.jsxs("div",{className:"modal-panel anim-pop med-panel portal-site",children:[e.jsxs("header",{className:"med-head",children:[e.jsxs("div",{children:[e.jsx("div",{className:"med-eyebrow",children:o("Research team","Research team")}),e.jsx("h2",{id:"med-title",className:"med-title",children:o("Dichiarazione di fine missione","End-of-mission declaration")}),e.jsx("p",{className:"med-sub",children:o("I campi sono pre-compilati dai dati del profilo e della missione. Puoi modificare ogni campo prima di generare il PDF. Lâheader MUR ufficiale è inserito automaticamente.","The fields are pre-filled from the profile and mission data. You can edit each field before generating the PDF. The official MUR header is inserted automatically.")})]}),e.jsx("button",{type:"button",className:"med-close",onClick:i,"aria-label":o("Chiudi","Close"),children:e.jsx(Ce,{size:16})})]}),e.jsxs("div",{className:"med-body",children:[h.pending&&e.jsx(Fr,{at:h.pendingAt,onRestore:()=>
31{const b=h.restore();b&&r(u=>({...u,...b}))},onDiscard:h.discard,labels:{title:o("Hai delle modifiche non salvate","You have unsaved changes"),from:o("delle","from"),hint:o("Erano rimaste solo su questo dispositivo. Riprendendole tornano esattamente come le avevi lasciate.","They were kept on this device only. Restoring puts them back exactly as you left them."),restore:o("Riprendi","Restore"),discard:o("Butta","Discard")}}),e.jsxs("section",{className:"med-section",children:[e.jsx("h3",{className:"med-section-head",children:"Dichiarante"}),e.jsxs("div",{className:"med-grid",children:[e.jsxs("label",{className:"med-field",children:[e.jsx("span",{children:"Genere"}),e.jsx(xe,{tone:"inherit",value:l.gender,onChange:b=>r(u=>({...u,gender:b})),ariaLabel:"Genere",options:[{value:"f",label:"Femminile (La sottoscritta)"},{value:"m",label:"Maschile (Il sottoscritto)"}]})]}),e.jsxs("label",{className:"med-field med-field-wide",children:[e.jsx("span",{children:"Nome e cognome"}),e.jsx("input",{type:"text",value:l.full_name,onChange:p("full_name")})]}),e.jsxs("label",{className:"med-field",children:[e.jsx("span",{children:"Luogo di nascita"}),e.jsx("input",{type:"text",value:l.birth_place,onChange:p("birth_place")})]}),e.jsxs("label",{className:"med-field",children:[e.jsx("span",{children:"Data di nascita"}),e.jsx(Pe,{value:l.birth_date,onChange:p("birth_date")})]}),e.jsxs("label",{className:"med-field",children:[e.jsx("span",{children:"Codice fiscale"}),e.jsx("input",{type:"text",value:l.fiscal_code,onChange:p("fiscal_code")})]}),e.jsxs("label",{className:"med-field",children:[e.jsx("span",{children:"Qualifica (nel testo)"}),e.jsx("input",{type:"text",value:l.qualifica,onChange:p("qualifica"),placeholder:"Professore Ordinario, Ricercatore, Assegnista, Dottorandaâ¦"})]}),e.jsxs("label",{className:"med-field",children:[e.jsx("span",{children:"Titolo per la firma"}),e.jsx(xe,{tone:"inherit",matchWidth:!1,value:["Prof.","Prof.ssa","Dott.","Dott.ssa","Dr.","Dr.ssa","Ing.","Ing.ssa"].includes(l.signature_title)?l.signature_title:l.signature_title?"__custom":"",onChange:b=>{r(b==="__custom"?u=>({...u,signature_title:u.signature_title||""}):u=>({...u,signature_title:b}))},ariaLabel:"Titolo per la firma",options:[{value:"",label:"(automatico: Prof. se docente, altrimenti Dott.)"},{value:"Prof.",label:"Prof."},{value:"Prof.ssa",label:"Prof.ssa"},{value:"Dott.",label:"Dott."},{value:"Dott.ssa",label:"Dott.ssa"},{value:"Dr.",label:"Dr."},{value:"Dr.ssa",label:"Dr.ssa"},{value:"Ing.",label:"Ing."},{value:"Ing.ssa",label:"Ing.ssa"},{value:"__custom",label:"Altroâ¦"}]})]}),l.signature_title&&!["Prof.","Prof.ssa","Dott.","Dott.ssa","Dr.","Dr.ssa","Ing.","Ing.ssa"].includes(l.signature_title)&&e.jsxs("label",{className:"med-field",children:[e.jsx("span",{children:"Titolo personalizzato"}),e.jsx("input",{type:"text",value:l.signature_title,onChange:p("signature_title"),placeholder:"es. Avv., Arch., â¦"})]}),e.jsxs("label",{className:"med-field med-field-wide",children:[e.jsx("span",{children:"Materia / settore"}),e.jsx("input",{type:"text",value:l.subject,onChange:p("subject"),placeholder:"Diritto Commerciale"})]}),e.jsxs("label",{className:"med-field med-field-wide",children:[e.jsx("span",{children:"Dipartimento"}),e.jsx("input",{type:"text",value:l.department,onChange:p("department")})]}),e.jsxs("label",{className:"med-field med-field-wide",children:[e.jsx("span",{children:"Università "}),e.jsx("input",{type:"text",value:l.university,onChange:p("university")})]})]})]}),e.jsxs("section",{className:"med-section",children:[e.jsx("h3",{className:"med-section-head",children:"Missione"}),e.jsxs("div",{className:"med-grid",children:[e.jsxs("label",{className:"med-field",children:[e.jsx("span",{children:"Destinazione"}),e.jsx("input",{type:"text",value:l.destination,onChange:p("destination")})]}),e.jsxs("label",{className:"med-field",children:[e.jsx("span",{children:"Data incarico missione"}),e.jsx(Pe,{value:l.assignment_date,onChange:p("assignment_date")})]}),e.jsxs("label",{className:"med-field med-field-wide",children:[e.jsx("span",{children:"Finalità della missione"}),e.jsx("input",{type:"text",value:l.purpose,onChange:p("purpose"),placeholder:"es. visiting research al Max Planck; partecipazione al convegno X; riunioni di progetto; fieldwork; workshop; â¦"}),e.jsx("em",{className:"med-hint",children:"Testo libero. Può descrivere visiting, convegni, workshop, riunioni di progetto, fieldwork, public engagement, ecc."})]}),e.jsxs("label",{className:"med-field",children:[e.jsx("span",{children:"Data inizio missione"}
31),e.jsx(Pe,{value:l.date_start,onChange:p("date_start")})]}),e.jsxs("label",{className:"med-field",children:[e.jsx("span",{children:"Data fine missione"}),e.jsx(Pe,{value:l.date_end,onChange:p("date_end")})]}),e.jsxs("label",{className:"med-field med-field-wide",children:[e.jsx("span",{children:"Note aggiuntive (opzionale)"}),e.jsx("textarea",{rows:3,value:l.notes,onChange:p("notes"),placeholder:'es. "in qualità di relatore invitato", "rappresentanza dellâAteneo", "in lingua inglese", o altre precisazioni'}),e.jsx("em",{className:"med-hint",children:"Verrà aggiunto in coda al paragrafo principale della dichiarazione."})]})]})]}),e.jsxs("section",{className:"med-section",children:[e.jsx("h3",{className:"med-section-head",children:"Progetto di ricerca"}),e.jsxs("div",{className:"med-grid",children:[e.jsxs("label",{className:"med-field med-field-wide",children:[e.jsx("span",{children:"Titolo progetto"}),e.jsx("input",{type:"text",value:l.project,onChange:p("project")})]}),e.jsxs("label",{className:"med-field",children:[e.jsx("span",{children:"Codice progetto"}),e.jsx("input",{type:"text",value:l.project_code,onChange:p("project_code")})]}),e.jsxs("label",{className:"med-field",children:[e.jsx("span",{children:"CUP"}),e.jsx("input",{type:"text",value:l.cup,onChange:p("cup")})]})]})]}),e.jsxs("section",{className:"med-section",children:[e.jsx("h3",{className:"med-section-head",children:"Firma"}),e.jsxs("div",{className:"med-grid",children:[e.jsxs("label",{className:"med-field",children:[e.jsx("span",{children:"Luogo di firma"}),e.jsx("input",{type:"text",value:l.signature_place,onChange:p("signature_place")})]}),e.jsxs("label",{className:"med-field",children:[e.jsx("span",{children:"Data di firma"}),e.jsx(Pe,{value:l.signature_date,onChange:p("signature_date")})]})]})]}),c&&e.jsxs("div",{className:"med-error",role:"alert",children:[o("Generazione PDF non riuscita: ","PDF generation failed: "),c]})]}),e.jsxs("footer",{className:"med-foot",children:[e.jsx("button",{type:"button",className:"btn btn-secondary",onClick:i,disabled:d,children:o("Annulla","Cancel")}),e.jsxs("button",{type:"button",className:"btn btn-primary anim-shimmer",onClick:x,disabled:d,children:[d?e.jsx(me,{size:14,className:"spin"}):e.jsx(st,{size:14}),d?o("Generazioneâ¦","Generatingâ¦"):o("Genera PDF","Generate PDF")]})]})]}),e.jsx("style",{children:` 32 /* CENTERED MODAL (the PI found the right-edge slide-over jarring). 33 The backdrop centres the card in the viewport; the card is rounded 34 all around with a soft drop shadow. Scoped with :has(.med-panel) 35 so ONLY the mission dialogs are affected, not other
36 .modal-backdrop modals. */ 37 .modal-backdrop:has(.med-panel) { 38 position: fixed; 39 inset: 0; 40 z-index: 1000; 41 display: flex; 42 align-items: center; 43 justify-content: center; 44 padding: 24px; 45 } 46 /* Public-site LIGHT look. The platform is forced to dark mode and 47 this modal renders over <body>, so the shared .modal-panel base 48 paints a dark frost â override it here to a light site card 49 (WHITE, hairline, soft shadow). The accent stays the portal's own 50 --space-tint (indigo for Research Team). */ 51 .modal-panel.med-panel { 52 background: #ffffff; 53 -webkit-backdrop-filter: none; 54 backdrop-filter: none; 55 /* Centered modal card â rounded all around, soft drop shadow. */ 56 border: 1px solid rgba(26, 35, 48, 0.12); 57 border-radius: 18px; 58 box-shadow: 0 24px 70px rgba(26, 35, 48, 0.28), 0 2px 8px rgba(26, 35, 48, 0.08); 59 color: #1a2330; 60 /* Redeclare the DRP tokens used by token-driven descendants 61 (the footer .btn-secondary / .btn-primary) so they render 62 light on the white panel instead of the inherited dark theme. */ 63 --bg-surface: #ffffff; 64 --bg-hover: rgba(26, 35, 48, 0.05); 65 --text-primary: #1a2330; 66 --text-secondary:#5a6678; 67 --text-tertiary: #8a94a3; 68 --border: rgba(26, 35, 48, 0.12); 69 --border-strong: rgba(26, 35, 48, 0.20); 70 } 71 .med-panel { 72 width: min(720px, 96vw); 73 /* Centered modal â auto height, capped so the body scrolls inside. */ 74 max-height: 90vh; 75 display: flex; 76 flex-direction: column; 77 font-family: inherit; 78 animation: med-pop 200ms cubic-bezier(0.32, 0.72, 0, 1) both; 79 } 80 @keyframes med-pop { 81 from { transform: translateY(10px) scale(0.985); opacity: 0; } 82 to { transform: none; opacity: 1; } 83 } 84 @media (prefers-reduced-motion: reduce) { 85 .med-panel { animation: none; } 86 } 87 .med-head { 88 padding: 22px 26px 18px; 89 background: #ffffff; 90 border-bottom: 1px solid rgba(26, 35, 48, 0.12); 91 display: flex; 92 align-items: flex-start; 93 gap: 16px; 94 } 95 .med-eyebrow { 96 font-family: var(--font-display); 97 font-size: 11px; 98 font-weight: 400; 99 letter-spacing: 0.16em; 100 text-transform: uppercase; 101 color: var(--space-tint, #2e84ff); 102 margin-bottom: 6px; 103 } 104 .med-title { 105 margin: 0; 106 font-family: var(--font-display); 107 font-size: 22px; 108 font-weight: 400; 109 letter-spacing: -0.01em; 110 color: #1a2330; 111 } 112 .med-sub { 113 margin: 8px 0 0; 114 font-size: 12.5px; 115 line-height: 1.55; 116 color: #5a6678; 117 max-width: 560px; 118 } 119 .med-close { 120 margin-left: auto; 121 background: #ffffff; 122 border: 1px solid rgba(26, 35, 48, 0.12); 123 border-radius: 999px; 124 width: 32px; 125 height: 32px; 126 display: inline-flex; 127 align-items: center; 128 justify-content: center; 129 color: #5a6678; 130 cursor: pointer; 131 transition: color 0.18s ease, border-color 0.18s ease; 132 } 133 .med-close:hover { color: #1a2330; border-color: rgba(26, 35, 48, 0.20); } 134 .med-body { 135 padding: 18px 26px 22px; 136 overflow-y: auto; 137 flex: 1 1 auto; 138 background: #ffffff; 139 } 140 .med-section { 141 margin-bottom: 22px; 142 } 143 .med-section:last-child { margin-bottom: 0; } 144 .med-section-head { 145 margin: 0 0 12px; 146 font-family: var(--font-display); 147 font-size: 11px; 148 font-weight: 400; 149 letter-spacing: 0.14em; 150 text-transform: uppercase; 151 color: var(--space-tint, #2e84ff); 152 } 153 .med-grid { 154 display: grid; 155 grid-template-columns: repeat(2, 1fr); 156 gap: 12px 14px; 157 } 158 .med-field { 159 display: flex; 160 flex-direction: column; 161 gap: 5px; 162 font-family: inherit; 163 } 164 .med-field-wide { grid-column: 1 / -1; } 165 .med-field > span { 166 font-family: var(--font-display); 167 font-size: 10.5px; 168 font-weight: 400; 169 letter-spacing: 0.1em; 170 text-transform: uppercase; 171 color: #5a6678; 172 } 173 .med-field input, 174 .med-field select, 175 .med-field textarea { 176 font-family: var(--site-body-font, inherit); 177 font-size: 13px; 178 padding: 10px 12px; 179 background: #ffffff; 180 color: #1a2330; 181 border: 1px solid rgba(26, 35, 48, 0.20); 182 border-radius: 12px; 183 outline: none; 184 transition: border-color 120ms ease, box-shadow 120ms ease; 185 width: 100%; 186 box-sizing: border-box; 187 } 188 .med-field input::placeholder, 189 .med-field textarea::placeholder { color: #5a6678; opacity: 0.7; } 190 .med-field textarea { 191 resize: vertical; 192 min-height: 64px; 193 line-height: 1.5; 194 } 195 .med-field input:focus, 196 .med-field select:focus, 197 .med-field textarea:focus { 198 border-color: var(--space-tint, #2e84ff); 199 box-shadow: 0 0 0 3px color-mix(in srgb, var(--space-tint, #2e84ff) 20%, transparent); 200 } 201 .med-hint { 202 font-style: normal; 203 font-size: 10.5px; 204 color: #8a94a3; 205 letter-spacing: 0; 206 text-transform: none; 207 } 208 .med-error { 209 margin-top: 14px; 210 padding: 10px 13px; 211 background: color-mix(in srgb, #ef4444 8%, transparent); 212 border: 1px solid color-mix(in srgb, #ef4444 28%, transparent); 213 border-radius: 12px; 214 font-size: 12.5px; 215 color: #b91c1c; 216 } 217 /* Nessuna striscia in fondo: vedi la nota su .modal-foot in global.css. */ 218 .med-foot { 219 padding: 16px 26px 20px; 220 background: transparent; 221 border-top: 0; 222 display: flex; 223 justify-content: flex-end; 224 gap: 10px; 225 } 226 @media (max-width: 640px) { 227 .med-grid { grid-template-columns: 1fr; } 228 .med-head, .med-body, .med-foot { padding-left: 18px; padding-right: 18px; } 229 /* Full-screen on narrow viewports â drop the radius + hairline. */
230 .modal-backdrop:has(.med-panel) { padding: 0; } 231 .med-panel { width: 100vw; max-height: 100vh; } 232 .modal-panel.med-panel { border: none; border-radius: 0; } 233 } 234 `})]}),document.body)}function At(t,a="____________"){return String(t??"").trim()||a}function wo(t){if(!t)return"____________";try{const a=t instanceof Date?t:new Date(t);return Number.isNaN(a.getTime())?String(t):a.toLocaleDateString("it-IT",{day:"2-digit",month:"2-digit",year:"numeric"})}catch{return String(t)}}async function tl(t){const a=await Pt(),i=new a({unit:"mm",format:"a4"}),n=await Gt();Wt(i,n);const o=da(i,n);i.setFont(fe,"normal"),i.setFontSize(Me),i.setTextColor("#1d1d1f");const s=t.letter_date?Ge(t.letter_date):Ge(new Date);i.text(`Taranto, ${s}`,Ne,o.y),i.setFont(fe,"bold"),i.text(`Al Direttore del ${aa}`,Oe,o.y,{align:"right"}),o.advance(je+10),jt(i,o,"LETTERA DI INCARICO DI MISSIONE",{gap:.5}),o.advance(je+6);const l=String(t.recipient_title||"").trim(),r=At(t.recipient_name,"[Nome Cognome]"),d=l?`${l} ${r}`:r,m=String(t.recipient_qualifica||"").trim(),c=At(t.destination,"[destinazione]"),g=wo(t.date_start),h=wo(t.date_end),p=At(t.purpose,"[finalità della missione]"),x=At(t.project,"[titolo del progetto]"),b=At(t.project_code,"[codice progetto]"),u=At(t.cup,"[CUP]"),w=At(t.upb,ji),v=At(t.pi_name,"[Responsabile scientifico]"),j=String(t.pi_title||"Il Responsabile scientifico del progetto").trim(),_=String(t.notes||"").trim();i.setFont(fe,"bold"),i.setFontSize(Me),i.text(`Oggetto: incarico di missione â ${r}, ${c}, ${g} â ${h}`,Ne,o.y),o.advance(je+6),i.setFont(fe,"normal"),i.setFontSize(Me);const C=String(t.reimbursement_method||"")==="estero_forfait",y=m?`, ${m}`:"",z=`Con la presente, ${v}, in qualità di Responsabile scientifico e titolare del fondo relativo al progetto â${x}â (codice progetto ${b} â CUP ${u}), accertata la coerenza della missione rispetto alle tipologie di spesa eleggibili a finanziamento, ai sensi dellâart. 9, comma 5, del Regolamento Missioni di Ateneo conferisce a ${d}${y} lâincarico di compiere una missione presso ${c}, dal ${g} al ${h}, per le seguenti finalità di ricerca:`;if(ee(i,o,z,{gap:3}),i.setFont(fe,"italic"),ee(i,o,p,{gap:5}),i.setFont(fe,"normal"),C){const $=At(t.matricola,"____________"),q=String(t.reddito_lordo||"").trim();ee(i,o,`Ai fini della liquidazione della missione allâestero con il metodo alternativo (art. 9, comma 6, del Regolamento): matricola n. ${$}; reddito annuo lordo ${q?`⬠${q}`:"____________"}.`,{gap:5})}const T=`Come da Regolamento delle missioni di Ateneo, allâincaricato/a sarà corrisposto, nei limiti e secondo le modalità ivi previsti, il rimborso delle spese di viaggio, vitto e alloggio sostenute durante la missione, a valere sul fondo UPB ${w} relativo al progetto sopra indicato.`;ee(i,o,T,{gap:3}),ee(i,o,"La presente lettera autorizza altresì lâassenza dalla sede di servizio per il periodo della missione e ogni adempimento connesso.",{gap:3});const D=`Lo svolgimento della missione è comunque subordinato allâautorizzazione del Direttore del ${aa}, Responsabile del Centro ordinatore di spesa, che ne accerta la copertura finanziaria (art. 9, comma 5, del Regolamento).`;return ee(i,o,D,{gap:3}),_&&ee(i,o,_,{gap:3}),o.advance(8),Tr(i,o,{role:j,name:v},{role:`Per autorizzazione, il Direttore del ${aa}`,name:""},{sigGap:18,gap:10}),i}const al=t=>Ca("Lettera di incarico di missione",t==null?void 0:t.recipient_name);async function _m(t){const a=await tl(t||{}),i=((t==null?void 0:t.recipient_name)||"membro").replace(/[^A-Za-z0-9]+/g,"_").slice(0,40),n=((t==null?void 0:t.destination)||"").replace(/[^A-Za-z0-9]+/g,"_").slice(0,30);await ka(a,["Lettera_incarico_missione",i,n].filter(Boolean),al(t))}async function Nm(t){const a=await tl(t||{});return za(a,al(t))}const wm="CLIMPACT â Charting the Landscape of Climate Litigation Impacts: An Interdisciplinary Framework and Open Access Database (FIS 3 Starting Grant)",zm="FIS-03396",Cm="H53C25000820001",km="Giuseppe Naglieri",Sm="Il Principal Investigator â Responsabile dei fondi";function Rn(t){if(!t)return"";if(typeof t=="string")return t.slice(0,10);try{const a=t instanceof Date?t:new Date(t);if(Number.isNaN(a.getTime()))return"";const i=a.getFullYear(),n=String(a.getMonth()+1).padStart(2,"0"),o=String(a.getDate()).padStart(2,"0");return`${i}-${n}-${o}`}catch{return""}}function Dm({mission:t,member:a,onClose:i,onPatch:n}
234){const{t:o}=X(),s=f.useMemo(()=>{if(a!=null&&a.signature_title)return a.signature_title;const w=((a==null?void 0:a.gender)||"").toLowerCase(),v=/prof/i.test(String((t==null?void 0:t.qualifica)||(a==null?void 0:a.qualifica)||""));return w==="f"?v?"Prof.ssa":"Dott.ssa":v?"Prof.":"Dott."},[a,t]),l=f.useMemo(()=>{var v,j;return{...{recipient_title:s,recipient_name:(a==null?void 0:a.name)||(t==null?void 0:t.person)||"",recipient_qualifica:(t==null?void 0:t.qualifica)||(a==null?void 0:a.qualifica)||"",destination:(t==null?void 0:t.place)||"",date_start:Rn(t==null?void 0:t.date),date_end:Rn(t==null?void 0:t.date_end),purpose:(t==null?void 0:t.description)||"",project:(t==null?void 0:t.project_title)||wm,project_code:(t==null?void 0:t.project_code)||zm,cup:(t==null?void 0:t.cup)||Cm,upb:(t==null?void 0:t.upb)||"",matricola:((v=t==null?void 0:t.advance_data)==null?void 0:v.matricola)||"",reddito_lordo:((j=t==null?void 0:t.advance_data)==null?void 0:j.reddito_lordo)||"",notes:"",pi_name:km,pi_title:Sm,letter_date:Rn(new Date)},...(t==null?void 0:t.assignment_letter_data)||{}}},[t,a,s]),[r,d]=f.useState(l),[m,c]=f.useState(!1),[g,h]=f.useState(null);f.useEffect(()=>{d(l)},[l]);const p=Mr({scope:"rt-assignment-letter",id:t==null?void 0:t.id,uid:a==null?void 0:a.uid},r);function x(w){return v=>d(j=>({...j,[w]:v.target.value}))}async function b(){c(!0),h(null);const w={...r,reimbursement_method:(t==null?void 0:t.reimbursement_method)||"estero_documentato"};try{await _m(w),p.clear(r);try{if(typeof n=="function"&&(t!=null&&t.team_uid)&&(t!=null&&t.id)){const v=await Nm(w),j=(r.re
234cipient_name||(a==null?void 0:a.name)||"membro").replace(/[^A-Za-z0-9]+/g,"_").slice(0,30),_=(r.destination||(t==null?void 0:t.place)||"").replace(/[^A-Za-z0-9]+/g,"_").slice(0,30),C=`Lettera_incarico_missione_${j}_${_}.pdf`,y=new File([v],C,{type:"application/pdf"}),z=`team-missions/${t.team_uid}/${t.id}/assignment.pdf`,T=await ze(z,y);await n({assignment_pdf:{url:T.url,path:T.path,name:y.name,size:y.size},assignment_letter_data:r})}else typeof n=="function"&&await n({assignment_letter_data:r})}catch(v){console.warn("[assignment-letter] auto-upload failed",v)}i==null||i()}catch(v){h((v==null?void 0:v.message)||String(v))}finally{c(!1)}}const u=["Prof.","Prof.ssa","Dott.","Dott.ssa","Dr.","Dr.ssa","Ing.","Ing.ssa"];return ra.createPortal(e.jsxs("div",{className:"modal-backdrop anim-scrim mt-dialog-host",role:"dialog","aria-modal":"true","aria-labelledby":"mal-title",onClick:w=>{w.target===w.currentTarget&&(i==null||i())},children:[e.jsxs("div",{className:"modal-panel anim-pop med-panel portal-site",children:[e.jsxs("header",{className:"med-head",children:[e.jsxs("div",{children:[e.jsx("div",{className:"med-eyebrow",children:o("Research team","Research team")}),e.jsx("h2",{id:"mal-title",className:"med-title",children:o("Lettera di incarico di missione","Mission assignment letter")}),e.jsx("p",{className:"med-sub",children:o("Lettera firmata dal Responsabile dei fondi (PI) e controfirmata dal Direttore del Dipartimento. Lâheader MUR è inserito automaticamente. I campi sono pre-compilati dalla missione e dal profilo del ricercatore; modifica ciò che serve prima di generare.","Letter signed by the funds manager (PI) and countersigned by the Director of the Department. The MUR header is inserted automatically. The fields are pre-filled from the mission and the researcher profile; edit what you need before generating.")})]}),e.jsx("button",{type:"button",className:"med-close",onClick:i,"aria-label":o("Chiudi","Close"),children:e.jsx(Ce,{size:16})})]}),e.jsxs("div",{className:"med-body",children:[p.pending&&e.jsx(Fr,{at:p.pendingAt,onRestore:()=>{const w=p.restore();w&&d(v=>({...v,...w}))},onDiscard:p.discard,labels:{title:o("Hai delle modifiche non salvate","You have unsaved changes"),from:o("delle","from"),hint:o("Erano rimaste solo su questo dispositivo. Riprendendole tornano esattamente come le avevi lasciate.","They were kept on this device only. Restoring puts them back exactly as you left them."),restore:o("Riprendi","Restore"),discard:o("Butta","Discard")}}),e.jsxs("section",{className:"med-section",children:[e.jsx("h3",{className:"med-section-head",children:"Destinatario dellâincarico"}),e.jsxs("div",{className:"med-grid",children:[e.jsxs("label",{className:"med-field",children:[e.jsx("span",{children:"Titolo"}),e.jsx(xe,{tone:"inherit",matchWidth:!1,value:u.includes(r.recipient_title)?r.recipient_title:r.recipient_title?"__custom":"",onChange:w=>{d(w==="__custom"?v=>({...v,recipient_title:v.recipient_title||""}):v=>({...v,recipient_title:w}))},ariaLabel:"Titolo",options:[{value:"",label:"(nessun titolo)"},...u,{value:"__custom",label:"Altroâ¦"}]})]}),r.recipient_title&&!u.includes(r.recipient_title)&&e.jsxs("label",{className:"med-field",children:[e.jsx("span",{children:"Titolo personalizzato"}),e.jsx("input",{type:"text",value:r.recipient_title,onChange:x("recipient_title"),placeholder:"es. Avv., Arch., â¦"})]}),e.jsxs("label",{className:"med-field med-field-wide",children:[e.jsx("span",{children:"Nome e cognome"}),e.jsx("input",{type:"text",value:r.recipient_name,onChange:x("recipient_name")})]}),e.jsxs("label",{className:"med-field med-field-wide",children:[e.jsx("span",{children:"Qualifica / settore (opzionale)"}),e.jsx("input",{type:"text",value:r.recipient_qualifica,onChange:x("recipient_qualifica"),placeholder:"es. Ricercatore di Diritto Internazionale, Dottoranda di ricerca, Assegnista di ricercaâ¦"})]})]})]}),e.jsxs("section",{className:"med-section",children:[e.jsx("h3",{className:"med-section-head",children:"Missione"}),e.jsxs("div",{className:"med-grid",children:[e.jsxs("label",{className:"med-field",children:[e.jsx("span",{children:"Destinazione"}),e.jsx("input",{type:"text",value:r.destination,onChange:x("destination")})]}),e.jsxs("label",{className:"med-field med-field-wide",children:[e.jsx("span",{children:"Finalità della missione"}),e.jsx("textarea",{rows:3,value:r.purpose,onChange:x("purpose"),placeholder:"es. visiting research presso il Max Planck Institute; partecipazione al convegno X come relatore; riunioni di coordinamento del consorzio; fieldwork; workshop; â¦"}),e.jsx("em",{className:"med-hint",children:"Testo libero â può descrivere visiting research, convegni, workshop, riunioni di progetto, fieldwork, public engagement, ecc."})]}),e.jsxs("label",{className:"med-field",children:[e.jsx("span",{children:"Data inizio"}
234),e.jsx(Pe,{value:r.date_start,onChange:x("date_start")})]}),e.jsxs("label",{className:"med-field",children:[e.jsx("span",{children:"Data fine"}),e.jsx(Pe,{value:r.date_end,onChange:x("date_end")})]}),e.jsxs("label",{className:"med-field med-field-wide",children:[e.jsx("span",{children:"Note aggiuntive (opzionale)"}),e.jsx("textarea",{rows:3,value:r.notes,onChange:x("notes"),placeholder:'es. "su invito formale", "in rappresentanza dellâAteneo", "in lingua inglese", â¦'}),e.jsx("em",{className:"med-hint",children:'Verrà aggiunto in coda al paragrafo "Vista la richiesta â¦" della lettera.'})]})]})]}),e.jsxs("section",{className:"med-section",children:[e.jsx("h3",{className:"med-section-head",children:"Progetto e fondi"}),e.jsxs("div",{className:"med-grid",children:[e.jsxs("label",{className:"med-field med-field-wide",children:[e.jsx("span",{children:"Titolo progetto"}),e.jsx("input",{type:"text",value:r.project,onChange:x("project")})]}),e.jsxs("label",{className:"med-field",children:[e.jsx("span",{children:"Codice progetto"}),e.jsx("input",{type:"text",value:r.project_code,onChange:x("project_code")})]}),e.jsxs("label",{className:"med-field",children:[e.jsx("span",{children:"CUP"}),e.jsx("input",{type:"text",value:r.cup,onChange:x("cup")})]}),e.jsxs("label",{className:"med-field med-field-wide",children:[e.jsx("span",{children:"Fondo UPB"}),e.jsx("input",{type:"text",value:r.upb,onChange:x("upb"),placeholder:"es. UPB CLIMPACT-FIS3"})]})]})]}),(t==null?void 0:t.reimbursement_method)==="estero_forfait"&&e.jsxs("section",{className:"med-section",children:[e.jsx("h3",{className:"med-section-head",children:"Estero, metodo forfait (art. 9 c.6)"}),e.jsxs("div",{className:"med-grid",children:[e.jsxs("label",{className:"med-field",children:[e.jsx("span",{children:"Matricola"}),e.jsx("input",{type:"text",value:r.matricola,onChange:x("matricola"),placeholder:"es. 012345"})]}),e.jsxs("label",{className:"med-field",children:[e.jsx("span",{children:"Reddito annuo lordo (â¬)"}),e.jsx("input",{type:"text",inputMode:"decimal",value:r.reddito_lordo,onChange:x("reddito_lordo"),placeholder:"es. 35.000,00"})]})]}),e.jsx("p",{style:{fontSize:"10.5px",color:"#8a94a3",margin:"8px 0 0",lineHeight:1.5},children:"Richiesti dal Regolamento (art. 9 c.6) solo per le missioni allâestero liquidate col metodo alternativo (forfait); compaiono nella lettera di incarico."})]}),e.jsxs("section",{className:"med-section",children:[e.jsx("h3",{className:"med-section-head",children:"Firma del Responsabile dei fondi"}),e.jsxs("div",{className:"med-grid",children:[e.jsxs("label",{className:"med-field med-field-wide",children:[e.jsx("span",{children:"Responsabile dei fondi (nome)"}),e.jsx("input",{type:"text",value:r.pi_name,onChange:x("pi_name")})]}),e.jsxs("label",{className:"med-field med-field-wide",children:[e.jsx("span",{children:"Titolo per la firma"}),e.jsx("input",{type:"text",value:r.pi_title,onChange:x("pi_title")})]}),e.jsxs("label",{className:"med-field",children:[e.jsx("span",{children:"Data della lettera"}),e.jsx(Pe,{value:r.letter_date,onChange:x("letter_date")})]})]})]}),g&&e.jsxs("div",{className:"med-error",role:"alert",children:[o("Generazione PDF non riuscita: ","PDF generation failed: "),g]})]}),e.jsxs("footer",{className:"med-foot",children:[e.jsx("button",{type:"button",className:"btn btn-secondary",onClick:i,disabled:m,children:o("Annulla","Cancel")}),e.jsxs("button",{type:"button",className:"btn btn-primary anim-shimmer",onClick:b,disabled:m,children:[m?e.jsx(me,{size:14,className:"spin"}):e.jsx(st,{size:14}),m?o("Generazioneâ¦","Generatingâ¦"):o("Genera PDF","Generate PDF")]})]})]}),e.jsx("style",{children:` 235 /* CENTERED MODAL (the PI found the right-edge slide-over jarring). 236 The backdrop centres the card in the viewport; the card is rounded 237 all around with a soft drop shadow. Scoped with :has(.med-panel) 238 so ONLY the mission dialogs are affected, not other
239 .modal-backdrop modals. */ 240 .modal-backdrop:has(.med-panel) { 241 position: fixed; 242 inset: 0; 243 z-index: 1000; 244 display: flex; 245 align-items: center; 246 justify-content: center; 247 padding: 24px; 248 } 249 /* Public-site LIGHT look. The platform is forced to dark mode and 250 this modal renders over <body>, so the shared .modal-panel base 251 paints a dark frost â override it here to a light site card 252 (WHITE, hairline, soft shadow). The accent stays the portal's own 253 --space-tint (indigo for Research Team). */ 254 .modal-panel.med-panel { 255 background: #ffffff; 256 -webkit-backdrop-filter: none; 257 backdrop-filter: none; 258 /* Centered modal card â rounded all around, soft drop shadow. */ 259 border: 1px solid rgba(26, 35, 48, 0.12); 260 border-radius: 18px; 261 box-shadow: 0 24px 70px rgba(26, 35, 48, 0.28), 0 2px 8px rgba(26, 35, 48, 0.08); 262 color: #1a2330; 263 /* Redeclare the DRP tokens used by token-driven descendants 264 (the footer .btn-secondary / .btn-primary) so they render 265 light on the white panel instead of the inherited dark theme. */ 266 --bg-surface: #ffffff; 267 --bg-hover: rgba(26, 35, 48, 0.05); 268 --text-primary: #1a2330; 269 --text-secondary:#5a6678; 270 --text-tertiary: #8a94a3; 271 --border: rgba(26, 35, 48, 0.12); 272 --border-strong: rgba(26, 35, 48, 0.20); 273 } 274 .med-panel { 275 width: min(720px, 96vw); 276 /* Centered modal â auto height, capped so the body scrolls inside. */ 277 max-height: 90vh; 278 display: flex; 279 flex-direction: column; 280 font-family: inherit; 281 animation: med-pop 200ms cubic-bezier(0.32, 0.72, 0, 1) both; 282 } 283 @keyframes med-pop { 284 from { transform: translateY(10px) scale(0.985); opacity: 0; } 285 to { transform: none; opacity: 1; } 286 } 287 @media (prefers-reduced-motion: reduce) { 288 .med-panel { animation: none; } 289 } 290 .med-head { 291 padding: 22px 26px 18px; 292 background: #ffffff; 293 border-bottom: 1px solid rgba(26, 35, 48, 0.12); 294 display: flex; 295 align-items: flex-start; 296 gap: 16px; 297 } 298 .med-eyebrow { 299 font-family: var(--font-display); 300 font-size: 11px; 301 font-weight: 400; 302 letter-spacing: 0.16em; 303 text-transform: uppercase; 304 color: var(--space-tint, #2e84ff); 305 margin-bottom: 6px; 306 } 307 .med-title { 308 margin: 0; 309 font-family: var(--font-display); 310 font-size: 22px; 311 font-weight: 400; 312 letter-spacing: -0.01em; 313 color: #1a2330; 314 } 315 .med-sub { 316 margin: 8px 0 0; 317 font-size: 12.5px; 318 line-height: 1.55; 319 color: #5a6678; 320 max-width: 560px; 321 } 322 .med-close { 323 margin-left: auto; 324 background: #ffffff; 325 border: 1px solid rgba(26, 35, 48, 0.12); 326 border-radius: 999px; 327 width: 32px; 328 height: 32px; 329 display: inline-flex; 330 align-items: center; 331 justify-content: center; 332 color: #5a6678; 333 cursor: pointer; 334 transition: color 0.18s ease, border-color 0.18s ease; 335 } 336 .med-close:hover { color: #1a2330; border-color: rgba(26, 35, 48, 0.20); } 337 .med-body { 338 padding: 18px 26px 22px; 339 overflow-y: auto; 340 flex: 1 1 auto; 341 background: #ffffff; 342 } 343 .med-section { margin-bottom: 22px; } 344 .med-section:last-child { margin-bottom: 0; } 345 .med-section-head { 346 margin: 0 0 12px; 347 font-family: var(--font-display); 348 font-size: 11px; 349 font-weight: 400; 350 letter-spacing: 0.14em; 351 text-transform: uppercase; 352 color: var(--space-tint, #2e84ff); 353 } 354 .med-grid { 355 display: grid; 356 grid-template-columns: repeat(2, 1fr); 357 gap: 12px 14px; 358 } 359 .med-field { display: flex; flex-direction: column; gap: 5px; font-family: inherit; } 360 .med-field-wide { grid-column: 1 / -1; } 361 .med-field > span { 362 font-family: var(--font-display); 363 font-size: 10.5px; 364 font-weight: 400; 365 letter-spacing: 0.1em; 366 text-transform: uppercase; 367 color: #5a6678; 368 } 369 .med-field input, 370 .med-field select, 371 .med-field textarea { 372 font-family: var(--site-body-font, inherit); 373 font-size: 13px; 374 padding: 10px 12px; 375 background: #ffffff; 376 color: #1a2330; 377 border: 1px solid rgba(26, 35, 48, 0.20); 378 border-radius: 12px; 379 outline: none; 380 transition: border-color 120ms ease, box-shadow 120ms ease; 381 width: 100%; 382 box-sizing: border-box; 383 } 384 .med-field input::placeholder, 385 .med-field textarea::placeholder { color: #5a6678; opacity: 0.7; } 386 .med-field textarea { resize: vertical; min-height: 64px; line-height: 1.5; } 387 .med-field input:focus, 388 .med-field select:focus, 389 .med-field textarea:focus { 390 border-color: var(--space-tint, #2e84ff); 391 box-shadow: 0 0 0 3px color-mix(in srgb, var(--space-tint, #2e84ff) 20%, transparent); 392 } 393 .med-hint { 394 font-style: normal; 395 font-size: 10.5px; 396 color: #8a94a3; 397 letter-spacing: 0; 398 text-transform: none; 399 } 400 .med-error { 401 margin-top: 14px; 402 padding: 10px 13px; 403 background: color-mix(in srgb, #ef4444 8%, transparent); 404 border: 1px solid color-mix(in srgb, #ef4444 28%, transparent); 405 border-radius: 12px; 406 font-size: 12.5px; 407 color: #b91c1c; 408 } 409 /* Nessuna striscia in fondo: vedi la nota su .modal-foot in global.css. */ 410 .med-foot { 411 padding: 16px 26px 20px; 412 background: transparent; 413 border-top: 0; 414 display: flex; 415 justify-content: flex-end; 416 gap: 10px; 417 } 418 @media (max-width: 640px) { 419 .med-grid { grid-template-columns: 1fr; } 420 .med-head, .med-body, .med-foot { padding-left: 18px; padding-right: 18px; } 421 /* Full-screen on narrow viewports â drop the radius + hairline. */
422 .modal-backdrop:has(.med-panel) { padding: 0; } 423 .med-panel { width: 100vw; max-height: 100vh; } 424 .modal-panel.med-panel { border: none; border-radius: 0; } 425 } 426 `})]}),document.body)}const Qi="#1d1d1f",Tm="#e9e9ec",Ti="#f6f6f7",ps=t=>t==null||t===""?0:typeof t=="number"?t:parseFloat(String(t).replace(/\./g,"").replace(",","."))||0,Jt=t=>{const a=ps(t);return!isFinite(a)||a===0?"":a.toLocaleString("de-DE",{minimumFractionDigits:2,maximumFractionDigits:2})};function en(t,a,i,n,o,s={}){s.fill&&(t.setFillColor(s.fill),t.rect(a,i,n,o,"F")),t.setDrawColor("#1d1d1f"),t.setLineWidth(.2),t.rect(a,i,n,o)}function ha(t,a,i,n,o,s,l={}){if(en(t,a,i,n,o,l),s==null||s==="")return;const{align:r="left",font:d="normal",size:m=9,color:c=Qi,padX:g=1.4}=l;t.setFont(fe,d),t.setFontSize(m),t.setTextColor(c);const h=r==="right"?a+n-g:r==="center"?a+n/2:a+g,p=i+o/2+m*.32;t.text(String(s),h,p,{align:r==="left"?"left":r})}function Mn(t,a,i,n,o,s,l={}){if(en(t,a,i,n,o,l),!(s!=null&&s.length))return;const{font:r="normal",size:d=8,color:m=Qi,padX:c=1.4,padY:g=1.6,lineH:h=3.4}=l;t.setFont(fe,r),t.setFontSize(d),t.setTextColor(m);let p=i+g+d*.32;for(const x of s)if(t.text(String(x),a+c,p),p+=h,p>i+o-.4)break}const Ze=Ne,il=Zt-2*Ne,zo=[{key:"day",label:".giorno",w:14},{key:"month",label:"mese",w:14},{key:"year",label:"anno",w:16},{key:"dep",label:"Località e ora partenza",w:61},{key:"arr",label:"Località e ora rientro",w:61}],Co=6.5,ko=7,So=7,et=110,pt=(il-et)/2,lt=8,Im=[{key:"cod9907",desc:"Cod. 9907 quota iscrizione a congressi, versata direttamente dal comandato in missione",label:"TOTALE SUB 1",sub:1},{key:"codOtherIscr",desc:"Cod._____ quota iscrizione a congressi, versata in nome e/o per conto dellâUniversità .",codField:"codOtherIscrCode"},{key:"ferrovia",desc:"Ferrovia numero ____ biglietti nr ____",detailField:"ferroviaDetail"},{key:"fs",desc:"F.S. (Posto letto /Singolo, Speciale, T2, T3, T4, CC)",detailField:"fsDetail"},{key:"piroscafi",desc:"Piroscafi",detailField:"piroscafiDetail"},{key:"aereo",desc:"Aereo tariffa intera/ridotta â convenzioni / last minute ecc. + polizza vita"},{key:"urbano",desc:"Mezzi trasporto urbano",detailField:"urbanoDetail"},{key:"extraurbano",desc:"Mezzi trasporto extraurbano",detailField:"extraurbanoDetail"},{key:"taxi",desc:"Mezzi trasporto a nolo (all. contratto per fornitura di servizio) taxi (autorizzato)"},{key:"km",desc:"Rimborso chilometrico (equivalente a 1/5 costo benzina super riferito a inizio missione) â¬__ X __Km + Pedaggio autostrada (numero __ documenti)"},{key:"pernottamento",desc:"Fatture o r/fiscali pernottamento (numero __ documenti)"},{key:"pasti",desc:"Ricevute fiscali o scontrini fiscali pasti (numero __ documenti)"},{key:"sub2",desc:"Cod. 9910 / 9911 spese Nazionali / Estere",label:"TOTALE SUB 2",sub:2,computed:!0},{key:"tot12",desc:"",label:"TOTALE (1+2)",sub:"tot",computed:!0}],Pm={desc:"RISERVATO ALLA RAGIONERIA"},Em=[{key:"diaria",desc:"DIARIA ESTERA Riduzione del 20%. Modifica DL 4 luglio 2006 n. 223",greyVal:!0},{key:"cod9908",desc:"Cod. 9908 Quota esente Estero"},{key:"cod9909",desc:"Cod. 9909 Quota imponibile Estero"},{key:"totCompl",desc:"",label:"TOTALE COMPL.",computed:!0},{key:"cod9913",desc:"Cod. 9913 Recupero Anticipazione"},{key:"ritenute",desc:"Ritenute C/Amm.ne 24.20% su Cod. 9909 â¬__________ quota imp.le estero"},{key:"totGen",desc:"",label:"TOTALE GEN.",computed:!0,bold:!0}];function Am(t){const a=x=>{var b;return ps((b=t==null?void 0:t[x])==null?void 0:b.richiesta)},i=x=>{var b;return ps((b=t==null?void 0:t[x])==null?void 0:b.dovuta)},n=a("cod9907")+a("codOtherIscr"),o=i("cod9907")+i("codOtherIscr"),s=["ferrovia","fs","piroscafi","aereo","urbano","extraurbano","taxi","km","pernottamento","pasti"],l=s.reduce((x,b)=>x+a(b),0),r=s.reduce((x,b)=>x+i(b),0),d=n+l,m=o+r,c=d+a("cod9908")+a("cod9909"),g=m+i("cod9908")+i("cod9909"),h=c-a("cod9913")-a("ritenute"),p=g-i("cod9913")-i("ritenute");return{sub1:{richiesta:n,dovuta:o},sub2:{richiesta:l,dovuta:r},tot12:{richiesta:d,dovuta:m},totCompl:{richiesta:c,dovuta:g},totGen:{richiesta:h,dovuta:p}}}async function nl(t){var d,m,c,g;const a=await Pt(),i=new a({unit:"mm",format:"a4"}),n=await Gt();Wt(i,n),i.setFont(fe,"bold"),i.setFontSize(13),i.setTextColor(Qi),i.text("PROSPETTO RIEPILOGATIVO SPESE PER LIQUIDAZIONE MISSIONE",Zt/2,eo+10,{align:"center"});let o=eo+16,s=Ze;for(const h of zo)ha(i,s,o,h.w,ko,h.label,{font:"bold",size:8.5}),s+=h.w;o+=ko;const l=((t==null?void 0:t.travel_rows)||[]).slice(0,So);for(let h=0;h<So;h++){const p=l[h]||{};s=Ze;for(const x of zo){const b=x.key==="day"?p.day:x.key==="month"?p.month:x.key==="year"?p.year:x.key==="dep"?p.departure:x.key==="arr"?p.arrival:"";ha(i,s,o,x.w,Co,b,{size:9,padX:1.4}),s+=x.w}o+=Co}o+=4,i.setFont(fe,"bold"),i.setFontSize(10),i.text("DISTINTA ANALITICA DELLA SPESA",Ze,o),i.text("RICHIESTA",Ze+et+pt/2,o,{align:"center"}),i.text("DOVUTA",Ze+et+pt+pt/2,o,{align:"center"}),o+=2.4;const r=Am(t);for(const h of Im){const p=!!h.computed,x=!!h.sub,b=x?Ti:null;let u=h.desc;if(h.codField&&(t!=null&&t[h.codField])&&(u=u.replace("Cod._____",`Cod. ${t[h.codField]}`)),h.detailField&&(t!=null&&t[h.detailField])&&(u=`${u} «${t[h.detailField]}»`),h.label){const j=`${u} ${h.label}`;Mn(i,Ze,o,et,lt,Fn(i,j,et-3,8,x?"bold":"normal"),{font:x?"bold":"normal",size:8,fill:b,lineH:3.4})}else Mn(i,Ze,o,et,lt,Fn(i,u,et-3,8,"normal"),{font:"normal",size:8,fill:b,lineH:3.4});let w="",v="";if(p){const j=r[h.key==="sub2"?"sub2":h.key==="tot12"?"tot12":h.key];w=Jt(j==null?void 0:j.richiesta),v=Jt(j==null?void 0:j.dovuta)}else w=Jt((d=t==null?void 0:t[h.key])==null?void 0:d.richiesta),v=Jt((m=t==null?void 0:t[h.key])==null?void 0:m.dovuta);ha(i,Ze+et,o,pt,lt,w?`⬠${w}`:"â¬",{align:"right",size:9,font:p?"bold":"normal",fill:b}),ha(i,Ze+et+pt,o,pt,lt,v?`⬠${v}`:"â¬",{align:"right",size:9,font:p?"bold":"normal",fill:b}),o+=lt}ha(i,Ze,o,il,lt,Pm.desc,{align:"center",font:"bold",size:9.5,fill:Tm}),o+=lt;for(const h of Em){const p=h.desc;if(Mn(i,Ze,o,et,lt,Fn(i,h.label?` ${h.label}`:p,et-3,8,h.bold?"bold":"normal"),{font:h.bold?"bold":"normal",size:8,fill:h.label?Ti:null,lineH:3.4}),h.greyVal)en(i,Ze+et,o,pt,lt,{fill:"#1d1d1f"}),en(i,Ze+et+pt,o,pt,lt,{fill:"#1d1d1f"});else{let x="",b="";if(h.computed){const u=r[h.key];x=Jt(u==null?void 0:u.richiesta),b=Jt(u==null?void 0:u.dovuta)}else x=Jt((c=t==null?void 0:t[h.key])==null?void 0:c.richiesta),b=Jt((g=t==null?void 0:t[h.key])==null?void 0:g.dovuta);ha(i,Ze+et,o,pt,lt,x?`⬠${x}`:"â¬",{align:"right",size:9,font:h.bold?"bold":"normal",fill:h.label?Ti:null}),ha(i,Ze+et+pt,o,pt,lt,b?`⬠${b}`:"â¬",{align:"right",size:9,font:h.bold?"bold":"normal",fill:h.label?Ti:null})}o+=lt}
426return o+=14,i.setFont(fe,"normal"),i.setFontSize(11),i.text("In fede",Zt/2,o,{align:"center"}),o+=10,i.setDrawColor(Qi),i.setLineWidth(.3),i.line(Zt/2-36,o,Zt/2+36,o),t!=null&&t.signer_name&&(i.setFontSize(9),i.text(t.signer_name,Zt/2,o+4.6,{align:"center"})),i}function Fn(t,a,i,n,o){return t.setFont(fe,o||"normal"),t.setFontSize(n),t.splitTextToSize(String(a||""),i)}const sl=t=>Ca("Prospetto riepilogativo spese per liquidazione missione",t.signer_name);async function $m({mission:t,member:a,data:i}){const n={...i||{},signer_name:(i==null?void 0:i.signer_name)||(a==null?void 0:a.name)||(t==null?void 0:t.person)||""},o=await nl(n),s=((t==null?void 0:t.code)||(t==null?void 0:t.place)||"missione").replace(/[^A-Za-z0-9]+/g,"_").slice(0,40);await ka(o,["Prospetto_riepilogativo",s],sl(n))}async function Rm({mission:t,member:a,data:i}){const n={...i||{},signer_name:(i==null?void 0:i.signer_name)||(a==null?void 0:a.name)||(t==null?void 0:t.person)||""},o=await nl(n);return za(o,sl(n))}function Mm(){const t={richiesta:"",dovuta:""};return{travel_rows:[],cod9907:{...t},codOtherIscrCode:"",codOtherIscr:{...t},ferroviaDetail:"",ferrovia:{...t},fsDetail:"",fs:{...t},piroscafiDetail:"",piroscafi:{...t},aereo:{...t},urbanoDetail:"",urbano:{...t},extraurbanoDetail:"",extraurbano:{...t},taxi:{...t},km:{...t},pernottamento:{...t},pasti:{...t},cod9908:{...t},cod9909:{...t},cod9913:{...t},ritenute:{...t},signer_name:""}}const Ln=[{id:"aereo",label:"Volo",icon:mc,expenseKeys:["aereo"],engineMode:"flight",engineSub:"economy",factorKey:"flight_short_economy",autoKmFrom:"destination_round_trip",mainJourney:!0},{id:"ferrovia",label:"Treno",icon:so,expenseKeys:["ferrovia"],engineMode:"train",engineSub:"standard",factorKey:"train_average",autoKmFrom:"destination_round_trip",mainJourney:!0},{id:"fs",label:"Treno alta velocità (F.S.)",icon:so,expenseKeys:["fs"],engineMode:"train",engineSub:"highspeed",factorKey:"train_highspeed",autoKmFrom:"destination_round_trip",mainJourney:!0},{id:"km",label:"Auto (rimborso chilometrico)",icon:Ws,expenseKeys:["km"],engineMode:"car",engineSub:"petrol",factorKey:"car_petrol",autoKmFrom:"destination_round_trip",mainJourney:!0},{id:"taxi",label:"Taxi / nolo",icon:Ws,expenseKeys:["taxi"],engineMode:"car",engineSub:"petrol",factorKey:"car_petrol",autoKmDefault:40},{id:"extraurbano",label:"Bus extraurbano",icon:Vs,expenseKeys:["extraurbano"],engineMode:"bus",engineSub:"regular",factorKey:"bus_average",autoKmDefault:100},{id:"urbano",label:"Trasporto urbano (bus / metro)",icon:Vs,expenseKeys:["urbano"],engineMode:"bus",engineSub:"regular",factorKey:"bus_average",autoKmDefault:30}];function On(t){const a=parseFloat(String((t==null?void 0:t.richiesta)||"").replace(",",".")),i=parseFloat(String((t==null?void 0:t.dovuta)||"").replace(",","."));return Number.isFinite(a)&&a>0||Number.isFinite(i)&&i>0}function Pa(t){return Number.isFinite(t)?t===0?"0 kg":t<1?`${t.toFixed(2)} kg`:t<10?`${t.toFixed(1)} kg`:`${Math.round(t).toLocaleString("en-GB")} kg`:"â"}function Ya(){return{width:"100%",fontFamily:"inherit",fontSize:13,padding:"6px 10px",borderRadius:8,border:"1px solid var(--border)",background:"var(--bg-surface, #fff)",color:"var(--text-primary)",outline:"none",boxSizing:"border-box"}}function Fm({form:t,mission:a,onChange:i,defaultOpen:n=!0,tint:o}){const[s,l]=f.useState(!1);f.useEffect(()=>{let S=!0;return $d().then(W=>{S&&W&&l(!0)}),()=>{S=!1}},[]);const[r,d]=f.useState(En);f.useEffect(()=>{let S=null;try{S=Rd(W=>d(W))}catch(W){console.warn("[mission-carbon] subscribeFactorsConfig failed; using defaults",W)}return()=>{try{S&&S()}catch{}}},[]);const m=(t==null?void 0:t.carbon)||{},[c,g]=f.useState(m.from||io.name||io.city||"Bari"),[h,p]=f.useState(m.to||(a==null?void 0:a.place)||""),[x,b]=f.useState(m.round_trip!==!1),[u,w]=f.useState(m.nights??"");f.useEffect(()=>{!m.to&&(a!=null&&a.place)&&!h&&p(a.place)},[a==null?void 0:a.place]);const v=f.useMemo(()=>{if(!c||!h)return null;const S=Md(c,h);return!Number.isFinite(S)||S<=0?null:Math.round(S)},[c,h]),j=f.useMemo(()=>v==null?null:x?v*2:v,[v,x]),_=Array.isArray(m.legs)?m.legs:[],C=f.useMemo(()=>{const S={};return Ln.forEach(W=>{const M=_.find(V=>V.id===W.id),J=W.expenseKeys.some(V=>
426On(t==null?void 0:t[V]));S[W.id]={included:M?M.included!==!1:J,km:(M==null?void 0:M.km)??""}}),S},[t,_]),[y,z]=f.useState(C),T=f.useRef({});f.useEffect(()=>{z(S=>{const W={...S};return Ln.forEach(M=>{const J=M.expenseKeys.some(K=>On(t==null?void 0:t[K])),V=T.current[M.id];J&&!V&&!W[M.id]?W[M.id]={included:!0,km:""}:J&&!V&&W[M.id]&&W[M.id].included===void 0&&(W[M.id]={...W[M.id],included:!0}),T.current[M.id]=J}),W})},[t]);const I=f.useRef(!1),D=S=>(...W)=>(I.current=!0,S(...W));function $(S,W){I.current=!0,z(M=>({...M,[S]:{...M[S],km:W}}))}function q(S){I.current=!0,z(W=>{var M;return{...W,[S]:{...W[S],included:!((M=W[S])!=null&&M.included)}}})}const R=f.useMemo(()=>{const S=x?2:1,W=Ln.map(G=>{const ne=y[G.id]||{included:!1,km:""},ue=parseFloat(String(ne.km||"").replace(",",".")),ge=Number.isFinite(ue)&&ue>0;let we=ge?ue:0,Se=!1,ot=!1;ge||(G.autoKmFrom==="destination_round_trip"&&v!=null?(we=v,Se=!0,ot=!0):G.autoKmDefault!=null&&(we=G.autoKmDefault,Se=!0));const it=G.expenseKeys.some(mt=>On(t==null?void 0:t[mt]));return{def:G,st:ne,oneWay:we,auto:Se,hasUserKm:ge,reliesOnDestination:ot,detected:it}}),M=W.filter(G=>G.def.mainJourney&&G.st.included&&G.reliesOnDestination);let J=null;if(M.length>0){let G=M[0],ne=+Ci(G.def.factorKey,r)||0;for(const ue of M.slice(1)){const ge=+Ci(ue.def.factorKey,r)||0;ge>ne&&(G=ue,ne=ge)}J=G.def.id}const V=W.map(G=>G.reliesOnDestination&&G.def.id!==J?{...G,oneWay:0,dedupedOut:!0}:{...G,dedupedOut:!1}),K=V.map(G=>({mode:G.st.included?G.def.engineMode:null,sub:G.def.engineSub,km:G.st.included?G.oneWay:0})),Q=parseFloat(String(u||"").replace(",","."))||0,le=Fd(K,{passengers:1,round_trip:x,nights:Q},r);return{legResults:V.map((G,ne)=>{const ue=le.perLeg[ne]||{km:0,kg:0,key:null},ge=ue.key||G.def.factorKey,we=+Ci(ge,r)||0,Se=G.st.included?ue.km*S:G.oneWay*S,ot=G.st.included?ue.kg*S:0;return{def:G.def,st:G.st,km:Se,auto:G.auto,detected:G.detected,dedupedOut:G.dedupedOut,factorKey:ge,factor:we,kg:ot}}),transportKg:le.travelKg,lodgingKg:le.lodgingKg}},[y,v,x,u,t,r]),O=R.legResults,k=R.transportKg,N=R.lodgingKg,L=k+N,B=f.useRef("");f.useEffect(()=>{if(typeof i!="function")return;const S={co2_kg:L,breakdown:{transport:k,lodging:N},from:c||"",to:h||"",round_trip:x,one_way_km:v,nights:parseFloat(String(u||"").replace(",","."))||0,legs:O.map(J=>({id:J.def.id,label:J.def.label,km:Math.round(J.km*10)/10,auto:J.auto,included:J.st.included,detected:J.detected,factor_key:J.factorKey,kg_co2e:Math.round(J.kg*1e3)/1e3})),factor_version:r.factor_version||En.factor_version,calculated_at:new Date().toISOString()},W=JSON.stringify({...S,calculated_at:void 0});if(W===B.current)return;const M=!I.current;B.current=W,i(S,{auto:M})},[i,L,k,N,c,h,x,v,u,O,r]);const P=o||"var(--space-tint, #0e7068)",[E,Y]=f.useState(n);return e.jsxs("div",{style:{"--bg-surface":"#ffffff","--cb-citta-fondo":"#ffffff","--text-primary":"#1a2330","--text-secondary":"#5a6678","--text-tertiary":"#8a94a3","--border":"rgba(26,35,48,0.12)",color:"#1a2330",border:"1px solid rgba(26,35,48,0.12)",borderRadius:14,background:`color-mix(in srgb, ${P} 5%, #ffffff)`,padding:E?"14px 16px":"10px 14px",display:"flex",flexDirection:"column",gap:E?12:0,fontFamily:"inherit"},children:[e.jsxs("button",{type:"button",onClick:()=>Y(S=>!S),style:{all:"unset",cursor:"pointer",display:"flex",alignItems:"center",gap:10,fontFamily:"inherit",fontSize:13.5,fontWeight:600,color:"var(--text-primary)"},children:[e.jsx("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:26,height:26,borderRadius:8,background:P,color:"#fff",flexShrink:0},children:e.jsx(xr,{size:13})}),e.jsx("span",{style:{flex:1},children:"Impronta di carbonio della missione"}),e.jsxs("span",{style:{fontSize:12.5,fontWeight:600,color:P,padding:"4px 9px",borderRadius:999,background:`color-mix(in srgb, ${P} 10%, transparent)`,whiteSpace:"nowrap"},children:[Pa(L)," CO2e"]}),e.jsx("span",{style:{color:"var(--text-tertiary)",display:"inline-flex"},children:E?e.jsx(pc,{size:13}):e.jsx(ln,{size:13})})]}),E&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(170px, 1fr))",gap:10},children:[e.jsx(Za,{label:"Partenza (città )",children:e.jsx(no,{valore:c,onCambia:D(g),segnaposto:"es. Bari",stileInput:Ya(),ariaLabel:"Partenza (città )"})}),e.jsx(Za,{label:"Destinazione (città )",children:e.jsx(no,{valore:h,onCambia:D(p),segnaposto:(a==null?void 0:a.place)||"es. Hei
426delberg",stileInput:Ya(),ariaLabel:"Destinazione (città )"})}),e.jsx(Za,{label:`Distanza A/R, ${x?"andata + ritorno":"solo andata"}`,children:e.jsxs("div",{style:{...Ya(),background:"transparent",border:"none",padding:"6px 0",color:"var(--text-secondary)",fontSize:13.5,fontWeight:500,fontVariantNumeric:"tabular-nums"},children:[j!=null?`${j.toLocaleString("it-IT")} km`:"â",v!=null&&e.jsxs("span",{style:{fontSize:11,color:"var(--text-tertiary)",marginLeft:6},children:["(sola andata: ",v.toLocaleString("it-IT")," km)"]})]})}),e.jsx(Za,{label:"Tipo viaggio",children:e.jsx(xe,{tone:"inherit",size:"sm",ariaLabel:"Tipo viaggio",value:x?"rt":"ow",onChange:D(S=>b(S==="rt")),options:[{value:"rt",label:"Andata e ritorno"},{value:"ow",label:"Solo andata"}]})}),e.jsx(Za,{label:"Notti in albergo",children:e.jsx("input",{inputMode:"numeric",value:u,onChange:D(S=>w(S.target.value)),placeholder:"es. 3",style:Ya()})})]}),e.jsxs("div",{style:{border:"1px solid var(--border)",borderRadius:10,background:"var(--bg-surface, #fff)",overflow:"hidden"},children:[e.jsx("div",{style:{padding:"6px 12px",background:`color-mix(in srgb, ${P} 6%, transparent)`,fontSize:11,fontWeight:600,textTransform:"uppercase",letterSpacing:"0.06em",color:"var(--text-secondary)",borderBottom:"1px solid var(--border)"},children:"Tratte di viaggio (auto-rilevate dalle voci di spesa)"}),O.map(S=>{const W=S.def.icon;return e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"20px 1fr 110px 90px",alignItems:"center",gap:10,padding:"8px 12px",borderBottom:"1px solid var(--divider, var(--border))",opacity:S.st.included?1:.45},children:[e.jsx("input",{type:"checkbox",checked:!!S.st.included,onChange:()=>q(S.def.id),title:S.detected?"Rilevata dalla distinta â clicca per escludere":"Aggiungi tratta",style:{cursor:"pointer",accentColor:P}}),e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:7,minWidth:0},children:[e.jsx(W,{size:13,style:{color:P,flexShrink:0}}),e.jsxs("div",{style:{minWidth:0},children:[e.jsx("div",{style:{fontSize:12.5,fontWeight:500,color:"var(--text-primary)",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:S.def.label}),e.jsxs("div",{style:{fontSize:10.5,color:"var(--text-tertiary)"},children:[S.factorKey,", ",S.factor.toFixed(5)," kg/km"]}),S.dedupedOut&&S.st.included&&e.jsx("div",{style:{fontSize:10,color:"#b45309",fontStyle:"italic",marginTop:1},children:"Tragitto principale gia conteggiato su un'altra tratta â inserisci i km solo se distinti."})]})]}),e.jsx("div",{children:e.jsx("input",{inputMode:"decimal",value:S.st.km,placeholder:S.auto?`${Math.round(S.km)} (auto)`:"0",onChange:M=>$(S.def.id,M.target.value),style:{...Ya(),fontVariantNumeric:"tabular-nums",textAlign:"right",fontSize:12.5,padding:"5px 8px"},title:S.auto?`Distanza auto: ${Math.round(S.km)} km (modifica per sovrascrivere)`:"Km percorsi"})}),e.jsx("div",{style:{textAlign:"right",fontSize:12.5,fontWeight:600,color:S.st.included?"var(--text-primary)":"var(--text-tertiary)",fontVariantNumeric:"tabular-nums"},children:Pa(S.kg)})]},S.def.id)}),e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"20px 1fr 110px 90px",alignItems:"center",gap:10,padding:"8px 12px",opacity:Number(u)>0?1:.55},children:[e.jsx("div",{}),e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:7},children:[e.jsx(Ld,{size:13,style:{color:P}}),e.jsxs("div",{children:[e.jsx("div",{style:{fontSize:12.5,fontWeight:500,color:"var(--text-primary)"},children:"Hotel / alloggio"}),e.jsxs("div",{style:{fontSize:10.5,color:"var(--text-tertiary)"},children:["hotel_average, ",(+Ci("hotel_average",r)||0).toFixed(2)," kg/notte"]})]})]}),e.jsxs("div",{style:{textAlign:"right",fontSize:12.5,color:"var(--text-tertiary)",fontVariantNumeric:"tabular-nums"},children:[u||0," notti"]}),e.jsx("div",{style:{textAlign:"right",fontSize:12.5,fontWeight:600,color:"var(--text-primary)",fontVariantNumeric:"tabular-nums"},children:Pa(N)})]})]}),e.jsxs("div",{style:{display:"flex",alignItems:"baseline",flexWrap:"wrap",gap:10,paddingTop:6,borderTop:"1px dashed var(--divider, var(--border))"},children:[e.jsxs("div",{style:{fontSize:18,fontWeight:700,color:"var(--text-primary)",letterSpacing:"-0.01em"},children:[Pa(L)," CO2e"]}),e.jsxs("div",{style:{fontSize:12,color:"var(--text-tertiary)",flex:1,minWidth:220},children:["transport: ",Pa(k),", hotel: ",Pa(N),","," ",e.jsx("span",{style:{opacity:.85},children:r.factor_version||En.factor_version})]})]})]})]})}function Za({label:t,children:a}){return e.jsxs("label",{style:{display:"flex",flexDirection:"column",gap:4,fontFamily:"inherit"},children:[e.jsx("span",{style:{fontSize:10.5,fontWeight:600,textTransform:"uppercase",letterSpacing:"0.06em",color:"var(--text-tertiary)"},children:t}),a]})}function hs(t){const a=/^(\d{4})-(\d{2})-(\d{2})/.exec(String(t||""));return a?{year:a[1],month:a[2],day:a[3]}:{year:"",month:"",day:""}}function Do(t,a){const i=hs(a);if(!i.day)return"";const n=Number(i.day),o=Number(i.month),s=/(\d{1,2})[/.](\d{1,2})(?:[/.]\d{2,4})?\s*(?:ore\s*)?(\d{1,2})[:.](\d{2})/g;let l;for(;(l=s.exec(String(t||"")))!==null;)if(Number(l[1])===n&&Number(l[2])===o)return`${l[3].padStart(2,"0")}:${l[4]}`;return""}function To(t,a){return t?a?`${t}, ore ${a}`:t:a?`ore ${a}`:""}function Lm(t,a){var p,x;const i=((x=(p=t==null?void 0:t.prospetto_data)==null?void 0:p.carbon)==null?void 0:x.from)||"Bari",n=(t==null?void 0:t.place)||"",o=(a||[]).filter(b=>oa(b.category).travel),s=o.find(b=>b.direction==="andata")||null,l=o.find(b=>b.direction==="ritorno")||null,r=(s==null?void 0:s.date)&&String(s.date).slice(0,10)||(t==null?void 0:t.date)||"",d=(l==null?void 0:l.date)&&String(l.date).slice(0,10)||(t==null?void 0:t.date_end)||(t==null?void 0:t.date)||"",m=b=>`${(b==null?void 0:b.merchant)||""} ${(b==null?void 0:b.reading_notes)||""}`,c=(s==null?void 0:s.time)||o.map(b=>Do(m(b),r)).find(Boolean)||"",g=(l==null?void 0:l.time)||o.map(b=>Do(m(b),d)).find(Boolean)||"",h=[{...hs(r),departure:To(i,c),arrival:n}];return d&&h.push({...hs(d),departure:To(n,g),arrival:i}),h}
426function Om(t){return!(t||[]).some(a=>a&&(a.day||a.month||a.year||a.departure||a.arrival))}const qm=["EUR","USD","GBP","CHF","PLN","SEK","NOK","DKK","CZK","HUF","RON","BGN","JPY","CNY","HKD","SGD","KRW","INR","TRY","ILS","CAD","AUD","NZD","BRL","MXN","ZAR","THB","MYR","IDR","PHP","ISK"],qn={};async function Um(t,a){if(!t||t==="EUR")return 1;if(qn[t]!=null)return qn[t];const i=await fetch(`https://open.er-api.com/v6/latest/${encodeURIComponent(t)}`);if(!i.ok)throw new Error(`rate HTTP ${i.status}`);const n=await i.json(),o=Number(n&&n.rates&&n.rates.EUR);if(!o||!isFinite(o))throw new Error("no rate for "+t);return qn[t]=o,o}const Ni="mission_receipt_inbox",Ps="pending",Bm="filed",Gm="dismissed";async function fs({mission:t,member:a,file:i,source:n="drop",targetExpenseId:o=null}){if(!(t!=null&&t.id))throw new Error("mission missing");if(!t.team_uid)throw new Error("mission team_uid missing");return(await ca(Ie(te,Ni),{team_uid:t.team_uid,person:(a==null?void 0:a.name)||t.person||"",mission_id:t.id,mission_place:t.place||"",mission_date:t.date||"",file:{url:i.url,path:i.path,name:i.name||"",size:Number(i.size)||0,mime:i.mime||""},status:Ps,expense_id:null,source:n,...o?{target_expense_id:o}:{},created_at:ie(),filed_at:null})).id}function Wm(t,a){const i=ft(Ie(te,Ni),Bt("team_uid","==",t),Bt("status","==",Ps));return Ye(i,n=>{a(cl(n.docs.map(o=>({id:o.id,...o.data()}))))},n=>{console.error("[receipt-inbox] subscribe failed",n),a([])})}function ol(t,a){if(!(t!=null&&t.id)||!(t!=null&&t.team_uid))return a([]),()=>{};const i=ft(Ie(te,Ni),Bt("mission_id","==",t.id),Bt("team_uid","==",t.team_uid));return Ye(i,n=>{a(cl(n.docs.map(o=>({id:o.id,...o.data()}))))},n=>{console.error("[receipt-inbox] subscribe failed",n),a([])})}async function rl(t){const{getFunctions:a,httpsCallable:i}=await Ae(async()=>{const{getFunctions:l,httpsCallable:r}=await import("./vendor-firebase-AOn3Fvmd.js").then(d=>d.ah);return{getFunctions:l,httpsCallable:r}},[]),{app:n}=await Ae(async()=>{const{app:l}=await import("./firebase-config-Dn2Tu_JL.js").then(r=>r.c);return{app:l}},__vite__mapDeps([3,2])),s=await i(a(n,"europe-west1"),"leggiRicevuta",{timeout:31e4})({inboxId:t});return(s==null?void 0:s.data)||null}async function Io(t,a){const i=oe(te,Ni,t);return xd(te,async n=>{const o=await n.get(i);return!o.exists()||o.data().status!==Ps?!1:(n.update(i,{status:Bm,expense_id:a||null,filed_at:ie()}),!0)})}function ll(t){return la(oe(te,Ni,t),{status:Gm,filed_at:ie()})}function cl(t){return[...t].sort((a,i)=>Po(i.created_at)-Po(a.created_at))}function Po(t){return t?typeof t.toMillis=="function"?t.toMillis():typeof t.seconds=="number"?t.seconds*1e3:0:0}const Vm=330*1e3,Hm=90*1e3;function gs(t){if(!t)return 0;if(typeof t.toMillis=="function")return t.toMillis();if(typeof t.seconds=="number")return t.seconds*1e3;const a=Date.parse(t);return Number.isFinite(a)?a:0}function bn(t,a=Date.now()){const i=(t==null?void 0:t.lettura)||null;if((t==null?void 0:t.status)==="dismissed")return null;if((t==null?void 0:t.status)==="filed")return(i==null?void 0:i.fase)==="fatta"?"fatta":null;if((i==null?void 0:i.fase)==="errore")return"errore";const n=(i==null?void 0:i.fase)==="scansione"||(i==null?void 0:i.fase)==="lettura"?i.fase:"coda",o=gs(i==null?void 0:i.at)||gs(t==null?void 0:t.created_at);return o&&a-o>Vm?"ferma":n}function Km(t,a=Date.now()){return(t||[]).filter(i=>{var o;const n=bn(i,a);return n?n==="fatta"?a-gs(((o=i.lettura)==null?void 0:o.at)||i.filed_at)<Hm:!0:!1})}function dl(t){const[a,i]=f.useState(()=>Date.now());return f.useEffect(()=>{if(!t)return;const n=setInterval(()=>i(Date.now()),2e3);return()=>clearInterval(n)},[t]),a}const Jm=["coda","scansione","lettura"];function Ym({fase:t,t:a}){const i=Jm,n={coda:a("Arrivata","Arrived"),scansione:a("Raddrizzo","Straightening"),lettura:a("Gemini legge","Gemini reads")},o=i.indexOf(t);return e.jsx("span",{className:"rr-steps","aria-hidden":"true",children:i.map((s,l)=>e.jsxs("span",{className:`rr-step${l<o?" is-done":""}${l===o?" is-now":""}`,children:[l<o?e.jsx(ke,{size:11}):e.jsx("span",{className:"rr-step-dot"}),n[s]]},s))})}function Zm({d:t,now:a,onRileggi:i,onAMano:n,onScarta:o,onApri:s}){var w,v,j,_;const{t:l,lang:r}=X(),[d,m]=f.useState(!1),[c,g]=f.useState(null),h=d?"lettura":bn(t,a),p=h==="coda"||h==="scansione"||h==="lettura";async function x(){m(!0),g(null);try{await i(t)}catch(C){console.error("[receipts] leggiRicevuta",C),g(l("Non riesco a raggiungere il server. Riprova tra poco.","Could not reach the server. Try again shortly."))}finally{m(!1)}}const b=(w=t.lettura)==null?void 0:w.esito,u={coda:l("Arrivata, la lettura parte adesso","Arrived, reading starts now"),scansione:l("Raddrizzo la foto e la rendo leggibile","Straightening the photo and making it readable"),lettura:l("Gemini sta leggendo importo, data e tipo","Gemini is reading amount, date and type"),errore:l("La lettura automatica non è riuscita","Automatic reading failed"),ferma:l("La lettura si è fermata a metà ","Reading stopped halfway")}[h];return e.jsxs("li",{className:`rr-item rr-${h}`,children:[e.jsxs("div",{className:"rr-top",children:[e.jsxs("button",{type:"button",className:"rr-name",onClick:()=>s(t.file),children:[e.jsx(rn,{size:13})," ",((v=t.file)==null?void 0:v.name)||l("documento","document")
426]}),e.jsxs("span",{className:"rr-acts",children:[(h==="errore"||h==="ferma")&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{type:"button",className:"rr-go",onClick:x,children:[e.jsx(hc,{size:13})," ",l("Leggi di nuovo","Read again")]}),n&&e.jsxs("button",{type:"button",className:"rr-hand",onClick:()=>n(t),title:l("Crea la riga e compilala tu","Create the row and fill it in yourself"),children:[e.jsx(fc,{size:13})," ",t.target_expense_id?l("Lascia così","Leave as is"):l("A mano","By hand")]})]}),h!=="fatta"&&!p&&e.jsx("button",{type:"button",className:"rr-x",title:l("Scarta","Discard"),onClick:()=>o(t),children:e.jsx(Ce,{size:13})})]})]}),h==="fatta"?e.jsxs("p",{className:"rr-done",children:[e.jsx(ke,{size:14}),e.jsxs("span",{children:[e.jsx("strong",{children:Jr(b==null?void 0:b.category,r)})," ",ut(b==null?void 0:b.amount,b==null?void 0:b.currency),b!=null&&b.merchant?`, ${b.merchant}`:""]}),e.jsx("span",{className:"rr-done-tag",children:b!=null&&b.allegato?(j=b==null?void 0:b.riempiti)!=null&&j.length?l("allegata alla riga, completati i campi vuoti","attached to the row, empty fields completed"):l("allegata alla riga","attached to the row"):(_=b==null?void 0:b.incerti)!=null&&_.length?l("registrata, da ricontrollare","filed, please check"):l("registrata","filed")})]}):e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"rr-state",children:[p?e.jsx(br,{size:14,className:"rr-pulse"}):e.jsx(at,{size:14}),e.jsx("span",{children:c||u}),d&&e.jsx(me,{size:13,className:"rr-spin"})]}),p&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"rr-track",children:e.jsx("span",{className:"rr-bar"})}),e.jsx(Ym,{fase:h,t:l})]})]})]})}function ul({items:t,onRileggi:a,onAMano:i,onScarta:n,onApri:o,titolo:s}){const{t:l}=X(),r=dl((t||[]).length>0),d=Km(t,r);if(!d.length)return null;const m=d.filter(c=>["coda","scansione","lettura"].includes(bn(c,r))).length;return e.jsxs("div",{className:"rr-box",children:[e.jsxs("div",{className:"rr-head",children:[m>0?e.jsx(me,{size:15,className:"rr-spin"}):e.jsx(br,{size:15}),e.jsx("strong",{children:s||(m>0?m===1?l("Sto leggendo 1 ricevuta","Reading 1 receipt"):`${l("Sto leggendo","Reading")} ${m} ${l("ricevute","receipts")}`:l("Ricevute lette","Receipts read"))}),m>0&&e.jsx("span",{className:"rr-head-sub",children:l("Non serve fare niente: la riga di spesa si scrive da sola.","Nothing to do: the expense row writes itself.")})]}),e.jsx("ul",{className:"rr-list",children:d.map(c=>e.jsx(Zm,{d:c,now:r,onRileggi:a,onAMano:i,onScarta:n,onApri:o},c.id))})]})}const Xm=f.lazy(()=>Ae(()=>import("./VisoreFile-3lweNgSX.js").then(t=>t.V),__vite__mapDeps([6,1,2,3,4,7,8,9,10,11,12,13,14])));function Qm(t){return String(t||"").replace(/[^A-Za-z0-9]+/g,"_").replace(/^_+|_+$/g,"").slice(0,40)||"missione"}function Eo(t,a){const i=URL.createObjectURL(t),n=document.createElement("a");n.href=i,n.download=a,document.body.appendChild(n),n.click(),n.remove(),setTimeout(()=>URL.revokeObjectURL(i),3e4)}const ep=/^image\/(jpeg|jpg|png|gif|webp|avif|bmp|heic|heif|x-icon|vnd\.microsoft\.icon)$/i,tp=/\.(jpe?g|png|gif|webp|avif|bmp|heic|heif|ico)(\?|$)/i;function ap(t){const a=String((t==null?void 0:t.mime)||"").toLowerCase();return a?ep.test(a):tp.test(String((t==null?void 0:t.name)||""))}function ip({file:t,onClose:a}){const{t:i}=X(),n=t==null?void 0:t.url,o=(t==null?void 0:t.name)||"documento",s=/pdf/i.test((t==null?void 0:t.mime)||"")||/\.pdf(\?|$)/i.test(o),l=!s&&ap(t);return n?e.jsx(f.Suspense,{fallback:null,children:e.jsx(Xm,{tema:"piattaforma",file:{url:n,nome:o,mime:(t==null?void 0:t.mime)||"",tipo:s?"pdf":l?"immagine":void 0,nota:i("E' un file che il browser non sa aprire, di solito un RAW di fotocamera (.dng). Scaricalo per vederlo, oppure ricarica lo stesso scatto in JPEG.","A file the browser cannot open, usually a camera RAW (.dng). Download it to view it, or upload the same shot again as a JPEG.")},onChiudi:a})}):null}const np=75*1024*1024;function sp({mission:t,member:a,onUpdate:i,onFillProspetto:n,defaultOpen:o=!1}){const{t:s}=X(),l=Array.isArray(t.expense_items)?t.expense_items:[],[r,d]=f.useState(!!o),[m,c]=f.useState(null),[g,h]=f.useState(null),[p,x]=f.useState(null),[b,u]=f.useState(null),[w,v]=f.useState(!1),[j,_]=f.useState(()=>new Set),[C,y]=f.useState(null),[z,T]=f.useState(()=>new Set),[I,D]=f.useState({}),[$,q]=f.useState(()=>new Set),R=f.useRef(null),O=f.useRef(null),k=f.useRef(null),N=f.useRef(l);N.current=l;const L=A=>i("expense_items",A),{grand:B}=Li(l),P=l.length>0,[E,Y]=f.useState([]);f.useEffect(()=>{if(t!=null&&t.id)return ol(t,Y)},[t==null?void 0:t.id,t==null?void 0:t.team_uid]);const S=E.filter(A=>A.status==="pending"),W=dl(S.length>0),M=S.filter(A=>["coda","scansione","lettura"].includes(bn(A,W))).length,J=S.length-M;async function V(A){if(A.target_expense_id){await Io(A.id,A.target_expense_id).catch(()=>{});return}const H=$n(A.file);H.source="drop",await Io(A.id,H.id).catch(re=>(console.error("[receipts] claimForManualFiling",re),!1))&&(L([...N.current,H]),d(!0))}function K(A){var H;(H=A.file)!=null&&H.path&&!A.target_expense_id&&de(A.file.path).catch(()=>{}),ll(A.id).catch(Z=>console.error("[receipts] dismiss",Z))}async function Q(A){const H=Ts(),Z=(String(A.name).split(".").pop()||"jpg").toLowerCase().replace(/[^a-z0-9]/g,"").slice(0,5)||"jpg",re=`team-missions/${t.team_uid}/${t.id}/receipts/${H}.${Z}`,pe=await ze(re,A);return{url:pe.url,path:pe.path,name:A.name,size:A.size,mime:A.type}}async function le(A){const H=[...A||[]].filter(re=>re&&(String(re.type).startsWith("image/")||re.type==="application/pdf"));if(!H.length)return;if(!t.team_uid){x(s("team_uid mancante sulla missione â eliminala e ricreala.","mission team_uid missing â delete and recreate it."));return}x(null);const Z=[];c({total:H.length,done:0,label:""});for(let re=0;re<H.length;re++)try{if(H[re].size>
426=np){const Re=(H[re].size/1048576).toFixed(0);x(s(`«${H[re].name}» pesa ${Re} MB e il limite e' 75 MB. Scegli la stessa foto in JPEG, oppure spegni ProRAW nelle impostazioni Fotocamera.`,`"${H[re].name}" is ${Re} MB and the limit is 75 MB. Pick the same photo as a JPEG, or turn ProRAW off in Camera settings.`));continue}c({total:H.length,done:re,label:s("Caricamento ","Uploading ")+H[re].name});const pe=await Q(H[re]);try{await fs({mission:t,member:a,file:pe,source:"mission"})}catch(Re){console.error("[receipts] addPendingReceipt",Re),x(s("Il documento e' stato caricato, ma non e' partita la lettura automatica: lo trovi come riga da compilare a mano.","The document was uploaded, but automatic reading did not start: you will find it as a row to fill in by hand.")),Z.push($n(pe,null))}}catch(pe){console.error("[receipts] upload failed",pe),x(s("Caricamento non riuscito: ","Upload failed: ")+((pe==null?void 0:pe.message)||pe))}c(null),Z.length&&L([...l,...Z]),d(!0)}async function U(A,H){const Z=[...H||[]].filter(pe=>pe&&(String(pe.type).startsWith("image/")||pe.type==="application/pdf"));if(!Z.length||!t.team_uid)return;x(null),c({total:Z.length,done:0,label:s("Caricamentoâ¦","Uploadingâ¦")});const re=[];for(let pe=0;pe<Z.length;pe++)try{c({total:Z.length,done:pe,label:s("Caricamento ","Uploading ")+Z[pe].name}),re.push(await Q(Z[pe]))}
426catch(Re){console.error(Re),x(s("Caricamento non riuscito: ","Upload failed: ")+((Re==null?void 0:Re.message)||Re))}if(c(null),!!re.length){L(N.current.map(pe=>pe.id===A?{...pe,files:[...pe.files||[],...re]}:pe));for(const pe of re)await fs({mission:t,member:a,file:pe,source:"mission",targetExpenseId:A}).catch(Re=>console.error("[receipts] lettura del documento aggiunto non avviata",Re))}}function G(A,H){L(N.current.map(Z=>Z.id===A?{...Z,...H}:Z))}async function ne(A){const H=N.current.find(Z=>Z.id===A);if(!(!H||!H.currency||H.currency==="EUR")){T(Z=>{const re=new Set(Z);return re.add(A),re});try{const Z=await Um(H.currency,H.date);G(A,{rate:Z})}catch(Z){console.warn("[receipts] rate fetch failed",Z),x(s("Cambio non recuperato â inseriscilo a mano.","Rate not fetched â enter it by hand."))}finally{T(Z=>{const re=new Set(Z);return re.delete(A),re})}}}function ue(A,H){if(H==="EUR"){G(A,{currency:"EUR",rate:1});return}G(A,{currency:H}),setTimeout(()=>ne(A),0)}function ge(A){const H=l.find(Z=>Z.id===A);((H==null?void 0:H.files)||[]).forEach(Z=>{Z.path&&de(Z.path).catch(()=>{})}),L(l.filter(Z=>Z.id!==A)),_(Z=>{const re=new Set(Z);return re.delete(A),re})}function we(A,H){var pe;const Z=l.find(Re=>Re.id===A),re=(pe=Z==null?void 0:Z.files)==null?void 0:pe[H];re!=null&&re.path&&de(re.path).catch(()=>{}),G(A,{files:((Z==null?void 0:Z.files)||[]).filter((Re,ma)=>ma!==H)})}function Se(){L([...l,$n(null)]),d(!0)}function ot(A){_(H=>{const Z=new Set(H);return Z.has(A)?Z.delete(A):Z.add(A),Z})}function it(A){var Ee,xt,_t,Nt;const H=Oa(l).filter(De=>A.includes(De.id));if(H.length<2)return;const Z=H[0],re=H.flatMap(De=>
426De.files||[]),pe=((Ee=H.find(De=>Number(De.amount)>0))==null?void 0:Ee.amount)||Z.amount||0,Re=((xt=H.find(De=>De.category&&De.category!=="altro"))==null?void 0:xt.category)||Z.category,ma=((_t=H.find(De=>De.date))==null?void 0:_t.date)||Z.date,Sn=((Nt=H.find(De=>De.merchant))==null?void 0:Nt.merchant)||Z.merchant,F={...Z,files:re,amount:pe,category:Re,date:ma,merchant:Sn},ce=new Set(H.slice(1).map(De=>De.id));L(l.filter(De=>!ce.has(De.id)).map(De=>De.id===Z.id?F:De))}function mt(){it([...j]),_(new Set)}const Vt=(A,H)=>[A,H].sort().join("|"),Et=[];{const A=Oa(l);for(let H=0;H<A.length;H+=1){const Z=Zu(A[H],A.slice(H+1));for(const re of Z){const pe=Vt(A[H].id,re.expense_id);if($.has(pe))continue;const Re=A.find(ma=>ma.id===re.expense_id);Re&&Et.push({key:pe,a:A[H],b:Re,confidence:re.confidence,why:re.why})}}}function ae(){if(!n)return;const A=n(Li(l).byGroup,l)||{};u(A)}async function he(){h("pdf"),x(null);try{const A=await Is({mission:t,member:a,expenses:l});Eo(A,`Elenco_spese_${Qm((a==null?void 0:a.name)||(t==null?void 0:t.person))}.pdf`)}catch(A){x(s("Generazione PDF non riuscita: ","PDF generation failed: ")+((A==null?void 0:A.message)||A))}finally{h(null)}}async function be(){h("zip"),x(null);try{const A=await Zr({mission:t,member:a,expenses:l});Eo(A,Yr(t,a))}catch(A){x(s("Creazione ZIP non riuscita: ","ZIP creation failed: ")+((A==null?void 0:A.message)||A))}finally{h(null)}}return e.jsxs("div",{className:"mt-receipts",children:[e.jsxs("button",{type:"button",className:"mt-receipts-head",onClick:()=>d(A=>!A),children:[e.jsxs("span",{className:"mt-receipts-head-l",children:[e.jsx(Ba,{size:16}),e.jsx("span",{className:"mt-receipts-title",children:s("Ricevute & spese","Receipts & expenses")}),e.jsx("span",{className:"mt-receipts-badge",children:s("informale","informal")}),P&&e.jsxs("span",{className:"mt-receipts-count",children:[l.length," ",s("voci","items"),", ",ut(B)]}),M>0&&e.jsxs("span",{className:"mt-receipts-waiting",children:[e.jsx(me,{size:11,className:"spin"})," ",M," ",s("in lettura","being read")]}),J>0&&e.jsxs("span",{className:"mt-receipts-waiting is-stuck",children:[e.jsx(at,{size:11})," ",J," ",s("da rileggere","to read again")]})]}),e.jsx(ln,{size:16,className:`mt-receipts-chev${r?" is-open":""}`})]}),r&&e.jsxs("div",{className:"mt-receipts-body",children:[e.jsx("p",{className:"mt-receipts-hint",children:s('Carica ogni scontrino/ricevuta: ognuno diventa una riga. Indica tipo, data e costo. Se più documenti sono la stessa spesa (ricevuta + scontrino, Booking + hotel), selezionali e premi "Unisci". Clicca un documento per vederlo in anteprima. Poi scarichi il PDF elenco e lo ZIP delle ricevute. Non tocca il prospetto ufficiale.','Upload each receipt: each becomes a row. Set type, date and cost. If several documents are the same expense (receipt + fiscal slip, Booking + hotel), select them and press "Merge". Click a document to preview it. Then download the list PDF and the receipts ZIP. It never touches the official statement.')}),e.jsx("input",{ref:R,type:"file",multiple:!0,accept:"application/pdf,image/jpeg,image/png,image/webp,image/heic,image/heif",style:{display:"none"},onChange:A=>{le(A.target.files),A.target.value=""}}),e.jsx("input",{ref:O,type:"file",multiple:!0,accept:"application/pdf,image/jpeg,image/png,image/webp,image/heic,image/heif",style:{display:"none"},onChange:A=>{const H=k.current;H&&U(H,A.target.files),k.current=null,A.target.value=""}}),e.jsx("div",{className:`mt-receipts-drop${w?" is-drag":""}`,onClick:()=>{var A;return!m&&((A=R.current)==null?void 0:A.click())},onDragOver:A=>{A.preventDefault(),v(!0)},onDragLeave:()=>v(!1),onDrop:A=>{A.preventDefault(),v(!1),m||le(A.dataTransfer.files)},role:"button",tabIndex:0,children:m?e.jsxs("span",{className:"mt-receipts-drop-busy",children:[e.jsx(me,{size:16,className:"spin"}),m.label||s("Elaborazioneâ¦","Processingâ¦"),e.jsxs("span",{className:"mt-receipts-prog",children:[m.done,"/",m.total]})]}):e.jsxs("span",{className:"mt-receipts-drop-idle",children:[e.jsx(Od,{size:20}),e.jsx("strong",{children:s("Trascina qui le ricevute","Drop your receipts here")}),e.jsx("span",{children:s("o clicca per sceglierle, una riga per documento, JPG, PNG, PDF","or click to choose, one row per document, JPG, PNG, PDF")})]})}),e.jsx(ul,{items:E,onRileggi:A=>rl(A.id),onAMano:V,onScarta:K,onApri:y}),p&&e.jsxs("div",{className:"mt-receipts-alert",children:[e.jsx(at,{size:14})," ",p]}),Et.map(A=>e.jsxs("div",{className:"mt-receipts-dupbar",children:[e.jsxs("span",{className:"mt-receipts-dupbar-txt",children:[e.jsx(Tt,{size:14}),s(`"${A.a.merchant||s("(senza esercente)","(no merchant)")}" e "${A.b.merchant||s("(senza esercente)","(no merchant)")}" â stesso importo (${ut(A.a.amount,A.a.currency)}) e stessa data: potrebbero essere la stessa spesa.`,`"${A.a.merchant||"(no merchant)"}" and "${A.b.merchant||"(no merchant)"}" â same amount (${ut(A.a.amount,A.a.currency)}) and same date: this might be the same expense.`)]}),e.jsxs("span",{className:"mt-receipts-dupbar-r",children:[e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>q(H=>{const Z=new Set(H);return Z.add(A.key),Z}),children:s("Non è la stessa","Not the same")}
426),e.jsxs("button",{type:"button",className:"btn btn-primary btn-sm",onClick:()=>it([A.a.id,A.b.id]),children:[e.jsx(Tt,{size:13})," ",s("Unisci","Merge")]})]})]},A.key)),j.size>=2&&e.jsxs("div",{className:"mt-receipts-mergebar",children:[e.jsxs("span",{children:[j.size," ",s("righe selezionate","rows selected")]}),e.jsxs("span",{className:"mt-receipts-mergebar-r",children:[e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>_(new Set),children:s("Deseleziona","Clear")}),e.jsxs("button",{type:"button",className:"btn btn-primary btn-sm",onClick:mt,children:[e.jsx(Tt,{size:13})," ",s("Unisci in unâunica spesa","Merge into one expense")]})]})]}),P&&e.jsx("div",{className:"mt-receipts-list",children:Oa(l).map(A=>e.jsxs("div",{className:`mt-receipts-row${j.has(A.id)?" is-sel":""}`,children:[e.jsxs("div",{className:"mt-receipts-row-main",children:[e.jsx("input",{type:"checkbox",className:"mt-receipts-check",checked:j.has(A.id),onChange:()=>ot(A.id),title:s("Seleziona per unire","Select to merge")}),e.jsx(xe,{tone:"inherit",size:"sm",matchWidth:!1,className:"mt-receipts-cat",value:A.category,onChange:H=>G(A.id,{category:H}),title:s("Tipo di spesa","Expense type"),ariaLabel:s("Tipo di spesa","Expense type"),options:us.map(H=>({label:s(H.it,H.en),options:xn.filter(Z=>Z.group===H.key).map(Z=>({value:Z.key,label:s(Z.it,Z.en)}))}))}),e.jsx(Pe,{className:"input mt-receipts-date",value:A.date||"",onChange:H=>G(A.id,{date:H.target.value})}),Ku(A.category)&&e.jsx(xe,{tone:"inherit",size:"sm",matchWidth:!1,className:"mt-receipts-dir",value:A.direction||"",onChange:H=>G(A.id,{direction:H}),title:s("Direzione","Direction"),ariaLabel:s("Direzione","Direction"),options:[{value:"",label:s("â","â")},{value:"andata",label:s("Andata","Outbound")},{value:"ritorno",label:s("Ritorno","Return")}]}),e.jsx("input",{className:"input mt-receipts-merchant",value:A.merchant||"",placeholder:s("Descrizione / esercente","Description / merchant"),onChange:H=>G(A.id,{merchant:H.target.value})}),e.jsxs("div",{className:"mt-receipts-amt",children:[e.jsx("input",{className:"input",type:"number",step:"0.01",min:"0",placeholder:"0,00",value:I[A.id]!==void 0?I[A.id]:A.amount||"",onChange:H=>{const Z=H.target.value;D(re=>({...re,[A.id]:Z})),G(A.id,{amount:parseFloat(Z)||0})},onBlur:()=>D(H=>{if(!(A.id in H))return H;const Z={...H};return delete Z[A.id],Z})}),e.jsx(xe,{tone:"inherit",size:"xs",block:!1,matchWidth:!1,style:{flex:"0 0 auto",width:76},value:A.currency||"EUR",onChange:H=>ue(A.id,H),title:s("Valuta","Currency"),ariaLabel:s("Valuta","Currency"),options:qm})]}),e.jsx("button",{type:"button",className:"mt-receipts-del",title:s("Elimina riga","Delete row"),onClick:()=>ge(A.id),children:e.jsx($e,{size:14})})]}),A.currency&&A.currency!=="EUR"&&e.jsxs("div",{className:"mt-receipts-conv",children:[e.jsx("button",{type:"button",className:"mt-receipts-conv-refresh",onClick:()=>ne(A.id),title:s("Aggiorna il cambio attuale â modificalo a mano per la data esatta","Refresh the current rate â edit it by hand for the exact date"),children:z.has(A.id)?e.jsx(me,{size:12,className:"spin"}):e.jsx(on,{size:12})}),e.jsx("span",{className:"mt-receipts-conv-lbl",children:s("cambio","rate")}),e.jsx("input",{className:"input mt-receipts-conv-rate",type:"number",step:"0.0001",min:"0",placeholder:"0,0000",value:I[`${A.id}:rate`]!==void 0?I[`${A.id}:rate`]:A.rate||"",onChange:H=>{const Z=H.target.value;D(re=>({...re,[`${A.id}:rate`]:Z})),G(A.id,{rate:parseFloat(Z)||0})},onBlur:()=>D(H=>{const Z=`${A.id}:rate`;if(!(Z in H))return H;const re={...H};return delete re[Z],re}),title:`EUR / 1 ${A.currency}`}),e.jsxs("span",{className:"mt-receipts-conv-eq",children:["= ",e.jsx("strong",{children:ut(Zi(A),"EUR")})]})]}),e.jsxs("div",{className:"mt-receipts-row-files",children:[(A.files||[]).map((H,Z)=>e.jsxs("span",{className:"mt-receipts-file",children:[e.jsxs("button",{type:"button",className:"mt-receipts-file-open",onClick:()=>y(H),title:s("Anteprima","Preview"),children:[e.jsx(rn,{size:11})," ",H.name||s("documento","document")]}),e.jsx("button",{type:"button",className:"mt-receipts-file-x",onClick:()=>we(A.id,Z),title:s("Rimuovi documento","Remove document"),children:"Ã"})]},Z)),e.jsxs("button",{type:"button",className:"mt-receipts-addfile",onClick:()=>{var H;k.current=A.id,(H=O.current)==null||H.click()},title:s("Aggiungi un documento a questa spesa","Add a document to this expense"),children:[e.jsx(qd,{size:12}
426)," ",s("documento","document")]})]})]},A.id))}),P&&e.jsxs("div",{className:"mt-receipts-totals",children:[us.map(A=>{const{byGroup:H}=Li(l),Z=H[A.key];return Z?e.jsxs("div",{className:"mt-receipts-total-row",children:[e.jsx("span",{children:s(A.it,A.en)}),e.jsx("span",{children:ut(Z.total)})]},A.key):null}),e.jsxs("div",{className:"mt-receipts-total-row grand",children:[e.jsx("span",{children:s("Totale complessivo","Grand total")}),e.jsx("span",{children:ut(B)})]})]}),n&&P&&e.jsxs("div",{className:"mt-receipts-fill",children:[e.jsxs("button",{type:"button",className:"btn btn-primary btn-sm mt-receipts-fillbtn",onClick:ae,children:[e.jsx(gc,{size:14})," ",s("Conferma e compila il prospetto","Confirm & fill the statement")]}),b&&e.jsxs("p",{className:"mt-receipts-fill-note",children:[b.filled>0?s("Prospetto compilato con i totali per categoria, con lo stesso importo in Richiesta e Dovuta. Se hai ricevuto unâanticipazione, lascia le spese come sono e metti tutto lâimporto ricevuto nel Cod. 9913: si toglie dal totale una volta sola.","Statement filled with the per-category totals, the same amount in Requested and Due. If you received an advance, leave the expenses as they are and enter the whole amount received in Cod. 9913: it is subtracted from the total once."):s("Nessuna voce con un totale da riportare.","No line with a total to carry over."),b.tragitti>0?" "+s("Tragitti compilati: andata e ritorno, con le date e le ore dei biglietti. Controlla le località e aggiungi lâora di arrivo se serve.","Trips filled in: outbound and return, with the dates and times from the tickets. Check the places and add the arrival time if needed."):"",b.altro?" "+s('Le spese in "Altro" non hanno una voce nel prospetto: riclassificale o inseriscile a mano.','Expenses in "Other" have no official line: reclassify them or enter by hand.'):""]})]}),e.jsxs("div",{className:"mt-receipts-actions",children:[e.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Se,children:[e.jsx(Le,{size:13})," ",s("Aggiungi riga","Add row")]}),e.jsxs("div",{className:"mt-receipts-actions-r",children:[e.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:!P||g,onClick:he,children:[g==="pdf"?e.jsx(me,{size:13,className:"spin"}):e.jsx(qt,{size:13})," ",s("PDF elenco","List PDF")]}),e.jsxs("button",{type:"button",className:"btn btn-primary btn-sm",disabled:!P||g,onClick:be,children:[g==="zip"?e.jsx(me,{size:13,className:"spin"}):e.jsx(Ua,{size:13})," ",s("ZIP ricevute","Receipts ZIP")]})]})]})]}),C&&e.jsx(ip,{file:C,onClose:()=>y(null)})]})}const Un=7,op={iscrizione:"cod9907",aereo:"aereo",ferrovia:"ferrovia",piroscafi:"piroscafi",urbano:"urbano",extraurbano:"extraurbano",taxi_nolo:"taxi",km_pedaggio:"km",pernottamento:"pernottamento",pasti:"pasti"};function rp({mission:t,member:a,isAdmin:i,onPatch:n,children:o}){var R,O,k,N,L,B;const{t:s}=X(),l=f.useMemo(()=>({...Mm(),...t.prospetto_data||{}}),[t.id]),[r,d]=f.useState(l),[m,c]=f.useState(!1),[g,h]=f.useState(null);f.useEffect(()=>{d(l)},[l]);const p=Ga([Array.isArray(t.expense_items)&&t.expense_items.length>0,(r.travel_rows||[]).some(P=>P&&(P.day||P.departure)),!!((R=t.prospetto_signed_pdf)!=null&&R.url)]),x=f.useMemo(()=>cp(r),[r]),b=String(((O=t.advance_data)==null?void 0:O.advance_amount)||"").trim();function u(P){const E={...r,...P};d(E),T(E)}function w(P,E){const Y=r[P]||{richiesta:"",dovuta:""};u({[P]:{...Y,...E}})}function v(P,E){const Y={};let S=0,W=0;if(Om(r.travel_rows)){const M=Lm(t,E);M.length&&(Y.travel_rows=M,W=M.length)}for(const[M,J]of Object.entries(op)){const V=P&&P[M]&&P[M].total||0;if(V>0){const K=V.toLocaleString("de-DE",{minimumFractionDigits:2,maximumFractionDigits:2});Y[J]={...r[J]||{},richiesta:K,dovuta:K},S+=1}}if(S>0||W>0){const M={...r,...Y};d(M),T(M)}return{filled:S,tragitti:W,altro:!!(P&&P.altro&&P.altro.total>0)}}function j(){(r.travel_rows||[]).length>=Un||u({travel_rows:[...r.travel_rows||[],{day:"",month:"",year:"",departure:"",arr
426ival:""}]})}function _(P,E){const Y=(r.travel_rows||[]).map((S,W)=>W===P?{...S,...E}:S);u({travel_rows:Y})}function C(P){u({travel_rows:(r.travel_rows||[]).filter((E,Y)=>Y!==P)})}const y=f.useRef(n);y.current=n;const z=f.useRef(null);f.useEffect(()=>()=>{z.current&&clearTimeout(z.current)},[]);const T=f.useCallback(P=>{z.current&&clearTimeout(z.current),z.current=setTimeout(async()=>{z.current=null;try{await y.current({prospetto_data:P}),h(new Date)}catch(E){console.error("[prospetto] save",E)}},700)},[]),I=f.useRef(r);I.current=r;function D(P){const E={...I.current,carbon:P};I.current=E,d(E),z.current&&T(E)}async function $(){c(!0);try{await $m({mission:t,member:a,data:r});try{if(t!=null&&t.team_uid&&(t!=null&&t.id)){const P=await Rm({mission:t,member:a,data:r}),E=((a==null?void 0:a.name)||"membro").replace(/[^A-Za-z0-9]+/g,"_").slice(0,30),Y=((t==null?void 0:t.place)||"").replace(/[^A-Za-z0-9]+/g,"_").slice(0,30),S=`Prospetto_missione_${E}_${Y}.pdf`,W=new File([P],S,{type:"application/pdf"}),M=`team-missions/${t.team_uid}/${t.id}/prospetto.pdf`,J=await ze(M,W);await n({prospetto_pdf:{url:J.url,path:J.path,name:W.name,size:W.size}})}}catch(P){console.warn("[prospetto] auto-upload failed",P)}}catch(P){alert(s("Generazione PDF non riuscita: ","PDF generation failed: ")+(P.message||P))}finally{c(!1)}}async function q(P){var S,W;const E=(S=P.target.files)==null?void 0:S[0];if(!E)return;if(!(E.type==="application/pdf"||/\.pdf$/i.test(E.name||""))){alert(s("Qui va il PROSPETTO FIRMATO in PDF. Le ricevute e gli scontrini si caricano in «Ricevute & spese», in cima a questa scheda: eâ liâ che vengono letti e classificati.","This slot is for the SIGNED STATEMENT as a PDF. Receipts go in âReceipts & expensesâ at the top of this card: that is where they are read and classified.")),P.target.value="";return}c(!0);try{if((W=t.prospetto_signed_pdf)!=null&&W.path)try{await de(t.prospetto_signed_pdf.path)}catch{}const M=`team-missions/${t.team_uid}/${t.id}/prospetto_firmato.pdf`,J=await ze(M,E);await n({prospetto_signed_pdf:{url:J.url,path:J.path,name:E.name,size:E.size}})}catch(M){alert(s("Caricamento non riuscito: ","Upload failed: ")+(M.message||M))}finally{c(!1),P.target.value=""}}return e.jsxs("div",{className:"prospetto-builder",children:[e.jsx(va,{n:1,stato:p[0],titolo:s("Ricevute e spese","Receipts and expenses"),sotto:s("Carica le ricevute: vengono lette da sole e diventano righe di spesa. Controlla tipo, data e importo.","Upload the receipts: they are read automatically and become expense rows. Check type, date and amount.")}),e.jsx(sp,{mission:t,member:a,onUpdate:(P,E)=>n({[P]:E}),onFillProspetto:v,defaultOpen:!0}),e.jsx(va,{n:2,stato:p[1],titolo:s("Compila il prospetto","Fill in the statement"),sotto:s("Premi «Conferma e compila il prospetto» qui sopra: tragitti e importi si riempiono da soli. Poi controlla.","Press âConfirm & fill the statementâ above: trips and amounts fill themselves. Then check.")}),e.jsxs(Xa,{half:!0,title:"Tragitti",hint:`Una riga per spostamento (max ${Un}). Se la missione ha solo andata+ritorno, bastano 2 righe.`,children:[(r.travel_rows||[]).map((P,E)=>e.jsxs("div",{className:"prospetto-travelrow",children:[e.jsx("input",{className:"input mono",placeholder:"GG",value:P.day,onChange:Y=>_(E,{day:Y.target.value}),style:{width:50}}),e.jsx("input",{className:"input mono",placeholder:"MM",value:P.month,onChange:Y=>_(E,{month:Y.target.value}),style:{width:50}}),e.jsx("input",{className:"input mono",placeholder:"AAAA",value:P.year,onChange:Y=>_(E,{year:Y.target.value}),style:{width:70}}),e.jsx("input",{className:"input",placeholder:"Partenza (es. Bari, ore 06:00)",value:P.departure,onChange:Y=>_(E,{departure:Y.target.value}),style:{flex:1,minWidth:160}}),e.jsx("input",{className:"input",placeholder:"Rientro (es. Cambridge, ore 14:00)",value:P.arrival,onChange:Y=>_(E,{arrival:Y.target.value}),style:{flex:1,minWidth:160}}),e.jsx("button",{type:"button",className:"btn btn-ghost btn-sm mt-row-delete",onClick:()=>C(E),children:"Ã"})]},E)),(r.travel_rows||[]).length<Un&&e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:j,children:"+ Aggiungi riga"})]}),e.jsxs(Xa,{title:"Distinta analitica della spesa",hint:"Inserisci RICHIESTA = quanto chiedi; DOVUTA = importo riconosciuto (di solito uguale, salvo decurtazioni).",children:[e.jsx(Xe,{label:"Cod. 9907 â Quota iscrizione, versata direttamente dal comandato",pair:r.cod9907,onChange:P=>w("cod9907",P)}),e.jsxs("div",{className:"prospetto-row",children:[e.jsxs("span",{className:"prospetto-row-label",children:["Cod. ",e.jsx("input",{className:"input mono",style:{width:70},value:r.codOtherIscrCode,onChange:P=>u({codOtherIscrCode:P.target.value}),placeholder:"es. 0123"})," â Quota iscrizione, versata in nome/per conto Università "]}),e.jsx(ml,{pair:r.codOtherIscr,onChange:P=>w("codOtherIscr",P)})]}
426),e.jsx(Xe,{label:"Ferrovia (n° biglietti)",detail:r.ferroviaDetail,onDetailChange:P=>u({ferroviaDetail:P}),pair:r.ferrovia,onChange:P=>w("ferrovia",P),placeholder:"dettaglio (es. 2 biglietti)"}),e.jsx(Xe,{label:"F.S. (Posto letto / Singolo / Speciale / T2 / T3 / T4 / CC)",detail:r.fsDetail,onDetailChange:P=>u({fsDetail:P}),pair:r.fs,onChange:P=>w("fs",P),placeholder:"es. T2"}),e.jsx(Xe,{label:"Piroscafi",detail:r.piroscafiDetail,onDetailChange:P=>u({piroscafiDetail:P}),pair:r.piroscafi,onChange:P=>w("piroscafi",P),placeholder:""}),e.jsx(Xe,{label:"Aereo (tariffa intera/ridotta â convenzioni / last minute) + polizza vita",pair:r.aereo,onChange:P=>w("aereo",P)}),e.jsx(Xe,{label:"Mezzi trasporto urbano",detail:r.urbanoDetail,onDetailChange:P=>u({urbanoDetail:P}),pair:r.urbano,onChange:P=>w("urbano",P),placeholder:""}),e.jsx(Xe,{label:"Mezzi trasporto extraurbano",detail:r.extraurbanoDetail,onDetailChange:P=>u({extraurbanoDetail:P}),pair:r.extraurbano,onChange:P=>w("extraurbano",P),placeholder:""}),e.jsx(Xe,{label:"Mezzi a nolo (allegato contratto) / taxi (autorizzato)",pair:r.taxi,onChange:P=>w("taxi",P)}),e.jsx(Xe,{label:"Rimborso chilometrico (1/5 costo benzina super) + pedaggio autostrada",pair:r.km,onChange:P=>w("km",P)}),e.jsx(Xe,{label:"Fatture / r.fiscali pernottamento",pair:r.pernottamento,onChange:P=>w("pernottamento",P)}),e.jsx(Xe,{label:"Ricevute / scontrini fiscali pasti",pair:r.pasti,onChange:P=>w("pasti",P)}),e.jsxs("div",{className:"prospetto-totals",children:[e.jsx(Qa,{label:"SUB 1 (iscrizioni)",v:x.sub1}),e.jsx(Qa,{label:"SUB 2 (trasporti + vitto/alloggio)",v:x.sub2}),e.jsx(Qa,{label:"TOTALE (1+2)",v:x.tot12,accent:!0})]})]}),e.jsx(Xa,{title:"Impronta di carbonio della missione",hint:"Stima opzionale in kg CO2e (fattori DEFRA 2024). Le tratte attive vengono auto-rilevate dalla distinta spese sopra â puoi accendere/spegnere o correggere i km di ogni tratta. La distanza A/R è calcolata in linea d'aria fra le città indicate.",children:e.jsx(Fm,{form:r,mission:t,onChange:(P,{auto:E}={})=>E?D(P):u({carbon:P})})}),e.jsxs(Xa,{half:!0,title:"Riservato alla Ragioneria",hint:"Sezione normalmente compilata in DJSGE â lascia vuota se non sei tu a calcolarla.",children:[e.jsx(Xe,{label:"Cod. 9908 â Quota esente Estero",pair:r.cod9908,onCh
426ange:P=>w("cod9908",P)}),e.jsx(Xe,{label:"Cod. 9909 â Quota imponibile Estero",pair:r.cod9909,onChange:P=>w("cod9909",P)}),e.jsx(Xe,{label:"Cod. 9913 â Recupero Anticipazione",pair:r.cod9913,onChange:P=>w("cod9913",P)}),b&&!((k=r.cod9913)!=null&&k.dovuta)&&!((N=r.cod9913)!=null&&N.richiesta)&&e.jsxs("div",{className:"muted text-xs",style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap",marginBottom:8},children:[e.jsx("span",{children:s(`Anticipazione chiesta: ${b} â¬. Metti qui quella ricevuta.`,`Advance requested: ⬠${b}. Enter the amount received here.`)}),e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>w("cod9913",{richiesta:b,dovuta:b}),children:s("Usa questa cifra","Use this amount")})]}),e.jsx(Xe,{label:"Ritenute C/Amm.ne 24,20% su Cod. 9909",pair:r.ritenute,onChange:P=>w("ritenute",P)}),e.jsxs("div",{className:"prospetto-totals",children:[e.jsx(Qa,{label:"TOTALE COMPL.",v:x.totCompl}),e.jsx(Qa,{label:"TOTALE GENERALE",v:x.totGen,accent:!0})]})]}),e.jsx(Xa,{half:!0,title:"Firmatario",children:e.jsx("input",{className:"input",value:r.signer_name||"",onChange:P=>u({signer_name:P.target.value}),placeholder:(a==null?void 0:a.name)||"Nome che compare sotto «In fede»"})}),e.jsx(va,{n:3,stato:p[2],titolo:s("Genera il prospetto, firmalo e caricalo","Generate the statement, sign it and upload it"),sotto:s("Il PDF si scarica; quello firmato si carica con «Carica PDF firmato».","The PDF downloads; upload the signed one with âUpload signed PDFâ.")}),e.jsxs("div",{className:"ospite-formactions",children:[e.jsx("div",{className:"muted text-xs",children:g?`${s("Salvato","Saved")} ${g.toLocaleTimeString("it-IT")}`:""}),e.jsxs("div",{className:"ospite-pill-row",children:[e.jsxs("button",{type:"button",className:"mt-pill is-primary anim-shimmer",onClick:$,disabled:m,children:[e.jsx(ta,{size:14}),e.jsx("span",{children:m?"â¦":s("Genera PDF compilato","Generate filled PDF")})]}),e.jsxs("label",{className:"mt-pill anim-shimmer",style:{cursor:"pointer"},children:[e.jsx(qa,{size:14}),e.jsx("span",{children:m?"â¦":(L=t.prospetto_signed_pdf)!=null&&L.url?s("Sostituisci PDF firmato","Replace signed PDF"):s("Carica PDF firmato","Upload signed PDF")}),e.jsx("input",{type:"file",accept:"application/pdf",onChange:q,style:{display:"none"},disabled:m})]}),((B=t.prospetto_signed_pdf)==null?void 0:B.url)&&e.jsxs("a",{href:Je(t.prospetto_signed_pdf.url),target:"_blank",rel:"noreferrer",className:"mt-pill anim-shimmer mt-pill-accent-tint",children:[e.jsx(st,{size:14}),e.jsx("span",{children:s("Scarica PDF firmato","Download signed PDF")})]})]})]}),o,Array.isArray(t.receipts)&&t.receipts.length>0&&e.jsx(lp,{mission:t,member:a,onPatch:n}
426)]})}function lp({mission:t,member:a,onPatch:i}){const{t:n}=X(),[o,s]=f.useState(!1),[l,r]=f.useState(!1),d=Array.isArray(t.receipts)?t.receipts:[];async function m(){const h=Sr(t);if(h.length===0){alert(n("Non ci sono ancora documenti da scaricare per questa missione.","There are no documents to download for this mission yet."));return}r(!0);try{const{default:p}=await Sa(()=>Ae(()=>import("./jszip.min-DN5-FNYE.js").then(v=>v.j),__vite__mapDeps([5,4]))),x=new p;await kr(x,h);const b=await x.generateAsync({type:"blob"}),u=URL.createObjectURL(b),w=document.createElement("a");w.href=u,w.download=Dr(t,a==null?void 0:a.name),document.body.appendChild(w),w.click(),w.remove(),setTimeout(()=>URL.revokeObjectURL(u),3e4)}catch(p){alert(n("Creazione ZIP non riuscita: ","ZIP creation failed: ")+((p==null?void 0:p.message)||p))}finally{r(!1)}}async function c(h){const p=d.find(x=>x.id===h);if(p&&await Na(`${n("Eliminare","Delete")} "${p.name}"? ${n("L'operazione è definitiva.","This action is permanent.")}`)){s(!0);try{if(p.path)try{await de(p.path)}catch{}await i({receipts:d.filter(x=>x.id!==h)})}catch(x){alert(n("Eliminazione non riuscita: ","Deletion failed: ")+((x==null?void 0:x.message)||x))}finally{s(!1)}}}function g(h){return h?h<1024?`${h} B`:h<1024*1024?`${Math.round(h/1024)} KB`:`${(h/1024/1024).toFixed(1)} MB`:""}return e.jsxs("div",{className:"ospite-formsection",style:{marginTop:18},children:[e.jsxs("div",{className:"ospite-formsection-head",children:[e.jsx("h3",{className:"ospite-formsection-title",children:n("Archivio della missione","Mission archive")}),e.jsx("p",{className:"ospite-formsection-hint",children:n('Un solo file .zip con richiesta, lettera di incarico, anticipazione, prospetto, dichiarazione di fine missione e tutte le ricevute caricate in "Ricevute & spese" qui sopra.','A single .zip with the request, assignment letter, advance request, statement, end-of-mission declaration and every receipt uploaded in "Receipts & expenses" above.')})]}),e.jsx("div",{className:"ospite-pill-row",children:e.jsxs("button",{type:"button",className:"mt-pill anim-shimmer",onClick:m,disabled:l,title:n("Scarica un .zip con richiesta, lettera di incarico, anticipazione, prospetto e tutte le ricevute della missione","Download a .zip with request, assignment letter, advance request, statement and all the mission receipts"),children:[e.jsx(ta,{size:14}),e.jsx("span",{children:l?n("Preparazione ZIPâ¦","Preparing ZIPâ¦"):n("Scarica tutto (ZIP)","Download all (ZIP)")})]})}),d.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"ospite-formsection-hint",style:{marginTop:14},children:n('Allegati caricati con il vecchio raccoglitore. Entrano regolarmente nello ZIP; per aggiungerne di nuovi usa "Ricevute & spese" in cima alla scheda.','Attachments uploaded with the old collector. They are included in the ZIP as usual; to add new ones use "Receipts & expenses" at the top of this tab.')}),e.jsx("ul",{className:"mt-doc-list-receipts",children:d.map(h=>e.jsxs("li",{children:[e.jsx(hn,{size:14,className:"mt-doc-icon"}),e.jsx("a",{href:Je(h.url),target:"_blank",rel:"noreferrer",children:h.name}),e.jsx("span",{className:"muted text-xs mt-doc-size",children:g(h.size)}),e.jsx("button",{type:"button",className:"mt-pill mt-pill-sm is-danger",onClick:()=>c(h.id),disabled:o,title:n("Elimina ricevuta","Delete receipt"),children:"Ã"})]}
426,h.id))})]})]})}function Xa({title:t,hint:a,children:i,half:n=!1}){return e.jsxs("div",{className:"ospite-formsection"+(n?" is-half":""),children:[e.jsx("h3",{children:t}),a&&e.jsx("p",{className:"muted text-xs",style:{marginTop:-6,marginBottom:8},children:a}),i]})}function Xe({label:t,detail:a,onDetailChange:i,placeholder:n,pair:o,onChange:s}){return e.jsxs("div",{className:"prospetto-row",children:[e.jsxs("span",{className:"prospetto-row-label",children:[t,i!=null&&e.jsx("input",{className:"input prospetto-detail",value:a||"",onChange:l=>i(l.target.value),placeholder:n||"dettaglio"})]}),e.jsx(ml,{pair:o,onChange:s})]})}function ml({pair:t,onChange:a}){return e.jsxs("div",{className:"prospetto-pair",children:[e.jsx(Ao,{value:(t==null?void 0:t.richiesta)||"",onChange:i=>a({richiesta:i}),placeholder:"Richiesta â¬"}),e.jsx(Ao,{value:(t==null?void 0:t.dovuta)||"",onChange:i=>a({dovuta:i}),placeholder:"Dovuta â¬"})]})}function Ao({value:t,onChange:a,placeholder:i}){return e.jsx("input",{className:"input mono prospetto-eur",inputMode:"decimal",value:t,onChange:n=>a(n.target.value),placeholder:i})}function Qa({label:t,v:a,accent:i}){return e.jsxs("div",{className:"prospetto-total"+(i?" is-accent":""),children:[e.jsx("div",{className:"prospetto-total-label",children:t}),e.jsxs("div",{className:"prospetto-total-vals mono",children:[e.jsxs("span",{title:"Richiesta",children:["R: ⬠",$o(a==null?void 0:a.richiesta)]}),e.jsxs("span",{title:"Dovuta",children:["D: ⬠",$o(a==null?void 0:a.dovuta)]})]})]})}function $o(t){const a=Number(t);return isFinite(a)?a.toLocaleString("de-DE",{minimumFractionDigits:2,maximumFractionDigits:2}):"0,00"}function cp(t){const a=b=>parseFloat(String(b??"").replace(/\./g,"").replace(",","."))||0,i=b=>{var u;return a((u=t==null?void 0:t[b])==null?void 0:u.richiesta)},n=b=>{var u;return a((u=t==null?void 0:t[b])==null?void 0:u.dovuta)},o=i("cod9907")+i("codOtherIscr"),s=n("cod9907")+n("codOtherIscr"),l=["ferrovia","fs","piroscafi","aereo","urbano","extraurbano","taxi","km","pernottamento","pasti"],r=l.reduce((b,u)=>b+i(u),0),d=l.reduce((b,u)=>b+n(u),0),m=o+r,c=s+d,g=m+i("cod9908")+i("cod9909"),h=c+n("cod9908")+n("cod9909"),p=g-i("cod9913")-i("ritenute"),x=h-n("cod9913")-n("ritenute");return{sub1:{richiesta:o,dovuta:s},sub2:{richiesta:r,dovuta:d},tot12:{richiesta:m,dovuta:c},totCompl:{richiesta:g,dovuta:h},totGen:{richiesta:p,dovuta:x}}}const dp=["gennaio","febbraio","marzo","aprile","maggio","giugno","luglio","agosto","settembre","ottobre","novembre","dicembre"];function Ro(t){if(!t||typeof t!="string")return"";const a=t.match(/^(\d{4})-(\d{2})-(\d{2})$/);if(!a)return t;const[,i,n,o]=a,s=parseInt(n,10)-1,l=dp[s]||n;return`${parseInt(o,10)} ${l} ${i}`}function up(t,a){if(!t||!a)return null;try{const i=new Date(t+"T00:00:00"),n=new Date(a+"T00:00:00"),o=Math.round((n.getTime()-i.getTime())/(1e3*60*60*24));return o>0?o:null}catch{return null}}function Be(t){return t==null?0:typeof t=="number"?t:parseFloat(String(t).replace(/\./g,"").replace(",","."))||0}function Qe(t){return t==null||isNaN(t)?"0,00":Number(t).toLocaleString("it-IT",{minimumFractionDigits:2,maximumFractionDigits:2})}const Bn=["","uno","due","tre","quattro","cinque","sei","sette","otto","nove"],mp=["dieci","undici","dodici","tredici","quattordici","quindici","sedici","diciassette","diciotto","diciannove"],pp=["","","venti","trenta","quaranta","cinquanta","sessanta","settanta","ottanta","novanta"];function ri(t){if(t===0)return"";if(t<10)return Bn[t];if(t<20)return mp[t-10];if(t<100){const o=Math.floor(t/10),s=t%10;let l=pp[o];return s>0&&((s===1||s===8)&&(l=l.slice(0,-1)),l+=Bn[s]),l}const a=Math.floor(t/100),i=t%100,n=a===1?"cento":Bn[a]+"cento";return i===0?n:n+ri(i)}function pl(t){if(!isFinite(t)||t<0)return"";if(t=Math.floor(t),t===0)return"zero";if(t<1e3)return ri(t);if(t<1e6){const o=Math.floor(t/1e3),s=t%1e3,l=o===1?"mille":ri(o)+"mila";return s===0?l:l+ri(s)}
426const a=Math.floor(t/1e6),i=t-a*1e6,n=a===1?"unmilione":ri(a)+"milioni";return i===0?n:n+pl(i)}function hp(t){const a=Be(t),i=Math.floor(a),n=Math.round((a-i)*100),o=pl(i)||"zero",s=String(n).padStart(2,"0");return`${o}/${s}`}function hl(t){const a=String((t==null?void 0:t.reimbursement_method)||"").trim();return a==="italia_analitico"||a==="estero_forfait"?a:"estero_documentato"}function Es(t){const a=Be(t==null?void 0:t.forfait_daily),i=parseInt(t==null?void 0:t.forfait_days,10)||0,n=t!=null&&t.forfait_half?a/2:0;return a*i+n}function fl(t,a){const i=Be(a==null?void 0:a.travel_cost_estimate);if(t==="estero_forfait")return i+.9*Es(a);if(t==="italia_analitico"){const n=Be(a==null?void 0:a.meals_estimate),o=Be(a==null?void 0:a.hotel_total_cost);return .75*(i+n+o)}return Be(a==null?void 0:a.hotel_total_cost)}async function gl(t,a,i){const n=hl(t),o=await Pt(),s=new o({unit:"mm",format:"a4"}),l=await Gt();Wt(s,l);const r=da(s,l);s.setFont(fe,"normal"),s.setFontSize(Me),s.setTextColor("#1d1d1f"),s.text(`Taranto, ${Ge(new Date)}`,Ne,r.y),s.setFont(fe,"bold"),s.text(`Al Direttore del ${aa}`,Oe,r.y,{align:"right"}),r.advance(je),s.setFont(fe,"normal"),s.text("Università degli Studi di Bari Aldo Moro",Oe,r.y,{align:"right"}),r.advance(je+8),jt(s,r,"RICHIESTA DI ANTICIPAZIONE DELLE SPESE PER MISSIONE",{gap:.5}),s.setFont(fe,"italic"),s.setFontSize(Me-1),s.text("(da presentare almeno 10 giorni prima della partenza â art. 12, comma 2, Regolamento Missioni)",Zt/2,r.y,{align:"center"}),r.advance(je+6);const d=fp(t.date,t.date_end||i.date_end),m=(t.place||i.destination||"").trim(),c="Oggetto: Richiesta di anticipazione delle spese per missione"+(m?` â ${m}`:"")+(d?` (${d})`:"");ee(s,r,c,{gap:6,bold:!0});const g=((a==null?void 0:a.name)||t.person||"").trim()||"[Nome Cognome]",h=((t==null?void 0:t.qualifica)||(a==null?void 0:a.qualifica)||"").trim()||"[qualifica]";ee(s,r,`Il sottoscritto ${g}, in qualità di ${h} presso il Dipartimento Jonico dell'Università degli Studi di Bari Aldo Moro,`,{gap:4}),ee(s,r,"premesso che",{gap:3,italic:!0});const p=(t.description||i.purpose||"").trim(),x=i.destination_country?`${m} (${i.destination_country})`:m;ee(s,r,"â come da richiesta è stato autorizzato a compiere una missione"+(x?` presso ${x}`:"")+(d?` nel periodo ${d}`:"")+(p?`, per le seguenti finalità istituzionali: ${p}`:".")+(p?";":""),{gap:3});const b=[];i.travel_outbound&&b.push(i.travel_outbound.trim()),i.travel_return&&b.push(i.travel_return.trim());const u=b.length>0?b.join(" e "):`con ${gp(t.transport)}`,w=Be(i.travel_cost_estimate);ee(s,r,`â il viaggio sarà effettuato ${u}`+(w>0?`, per un costo stimato di circa ⬠${Qe(w)}`:"")+";",{gap:3});const v=(t.upb||i.upb||ji).trim();ee(s,r,`â la missione grava sull'UPB: ${v};`,{gap:3});const j=n==="estero_forfait"?"per la missione in oggetto si intende avvalersi del rimborso alternativo (forfettario) ai sensi dell'art. 5, comma 3, e dell'art. 15, comma 2, del Regolamento Missioni vigente":n==="italia_analitico"?"per la missione in oggetto si intende avvalersi del rimborso analitico ai sensi dell'art. 5, comma 2, del Regolamento Missioni vigente":"per la missione in oggetto si intende avvalersi del rimborso documentato e analitico ai sensi dell'art. 5, comma 3, e dell'art. 15, comma 1, del Regolamento Missioni vigente",_=(i.reimbursement_basis||"").trim()||j;if(ee(s,r,`â ${_};`,{gap:6}),ee(s,r,"visto",{gap:3,italic:!0}),ee(s,r,n==="estero_forfait"?`l'art. 12, comma 4, del Regolamento Missioni dell'Università degli Studi di Bari Aldo Moro (D.R. n. 3330 del 18 settembre 2024), il quale prevede che, nel caso di anticipi su missioni all'estero con rimborso alternativo a quello documentato, l'importo da anticipare sia pari alle spese di viaggio (esclusi mezzi urbani, extraurbani e taxi) e ad una somma contenuta nel limite del 90% del rimborso forfettario alternativo spettante secondo le allegate tabelle "B" e "C";`:n==="italia_analitico"?"l'art. 12, comma 3, del Regolamento Missioni dell'Università degli Studi di Bari Aldo Moro (D.R. n. 3330 del 18 settembre 2024), il quale prevede che, per le missioni in Italia, possa essere chiesta un'anticipazione pari al 75% delle spese stimate di viaggio, di vitto e di alloggio;":"l'art. 12, comma 4, del Regolamento Missioni dell'Università degli Studi di Bari Aldo Moro (D.R. n. 3330 del 18 settembre 2024), il quale prevede che, nel caso di anticipi su missioni all'estero con rimborso documentato, l'importo da accreditare non possa essere superiore alle spese alberghiere, ai sensi dell'art. 3 del D.M. 23 marzo 2011;",{gap:3}),ee(s,r,"l'art. 12, comma 2, del medesimo Regolamento, ai sensi del quale la richiesta di anticipazione deve pervenire all'ufficio liquidatore almeno 10 giorni prima della data prevista per l'inizio della missione;",{gap:6}),ee(s,r,"considerato che",{gap:3,italic:!0}),n==="estero_forfait"){const $=Be(i.travel_cost_estimate),q=Be(i.forfait_daily),R=parseInt(i.forfait_days,10)||0,O=Es(i);q>0&&R>0?(ee(s,r,`il trattamento alternativo di missione prevede una quota giornaliera di rimborso forfettario di ⬠${Qe(q)} per ciascuna delle n. ${R} giornate di missione`+(i.forfait_half?", oltre ad un'ulteriore mezza quota per la prosecuzione di almeno 12 ore continuative":"")+`, per un importo forfettario complessivo di ⬠${Qe(O)};`,{gap:3}),ee(s,r,"ai sensi dell'art. 12, comma 4, l'anticipo è costituito dalle spese di viaggio"+($>0?` (⬠${Qe($)})`:"")+", anticipabili per intero, e da una somma entro il 90% della quota forfettaria"+(O>0?` (⬠${Qe(.9*O)})`:"")+($>0||O>0?`, per un anticipo complessivo di ⬠${Qe($+.9*O)}`:"")+";",{gap:6})):ee(s,r,"[indicare la quota giornaliera forfettaria (Tabella C) e il numero di giornate];",{gap:6})}else if(n==="italia_analitico"){const $=Be(i.travel_cost_estimate),q=Be(i.meals_estimate),R=Be(i.hotel_total_cost),O=$+q+R;O>0?(ee(s,r,`le spese stimate per la missione ammontano a complessivi ⬠${Qe(O)} (viaggio ⬠${Qe($)}, vitto ⬠${Qe(q)}, alloggio ⬠${Qe(R)}), nei limiti dei massimali di cui alla Tabella A del Regolamento;`,{gap:3}),ee(s,r,`ai sensi dell'art. 12, comma 3, è anticipabile una somma pari al 75% delle spese stimate, pari a ⬠${Qe(.75*O)};`,{gap:6}
426)):ee(s,r,"[indicare le spese stimate di viaggio, vitto e alloggio];",{gap:6})}else{const $=(i.hotel_name||"").trim(),q=i.hotel_nights?parseInt(i.hotel_nights,10):up(t.date,t.date_end||i.date_end),R=Be(i.hotel_total_cost),O=q&&R?R/q:Be(i.hotel_cost_per_night),k=Be(i.hotel_max_per_night)||250;$||q||R?(ee(s,r,`la sistemazione prevista è ${$?`presso ${$}`:"[albergo da indicare]"} `+(q?`per n. ${q} notti`:"")+(d?` (${d})`:"")+(R>0?`, per un costo complessivo di ⬠${Qe(R)}`:"")+";",{gap:3}),O>0?ee(s,r,`il costo medio a notte è pari a ⬠${Qe(O)}, rientrante nel massimale di ⬠${Qe(k)} a notte previsto dal Regolamento;`,{gap:6}):r.advance(3)):ee(s,r,"[indicare sistemazione alberghiera, n. notti e costo complessivo];",{gap:6})}ee(s,r,"chiede",{gap:3,italic:!0});const y=n==="estero_documentato"?Be(i.advance_amount)||Be(i.hotel_total_cost):fl(n,i),z=y>0?hp(y):"";ee(s,r,`la corresponsione di ${n==="estero_forfait"?"un'anticipazione, ai sensi dell'art. 12, comma 4, del Regolamento Missioni, sulle spese di viaggio e sulla quota forfettaria del trattamento alternativo di missione, per un importo complessivo di ":n==="italia_analitico"?"un'anticipazione, ai sensi dell'art. 12, comma 3, del Regolamento Missioni, pari al 75% delle spese stimate di viaggio, vitto e alloggio, per un importo complessivo di ":"un'anticipazione, ai sensi dell'art. 12, comma 4, del Regolamento Missioni, sulle spese di alloggio per la missione in oggetto, per un importo complessivo di "}`+(y>0?`⬠${Qe(y)} (${z}).`:"⬠[importo]."),{gap:6}),ee(s,r,"Si impegna, ai sensi dell'art. 12, comma 5, del Regolamento, a far pervenire all'ufficio liquidatore la documentazione necessaria ai fini della liquidazione entro 30 giorni dalla fine della missione.",{gap:5});const I=n==="estero_forfait"?"eventuale preventivo o prenotazione del viaggio (a supporto del costo di viaggio anticipato).":n==="italia_analitico"?"eventuali preventivi a supporto delle spese stimate.":"conferma di prenotazione alberghiera (a supporto del costo di alloggio anticipato).";ee(s,r,"Si allega:",{gap:2,bold:!0}),ee(s,r," ⢠copia dell'incarico di missione autorizzato;",{gap:2}),ee(s,r,` ⢠${I}`,{gap:8});const D=(i.signer_name||g).trim()||"[Firma]";return ws(s,r,"In fede",D),s}function fp(t,a){const i=Ro(t),n=Ro(a);return i&&n?`dal ${i} al ${n}`:i?`dal ${i}`:n?`al ${n}`:""}function gp(t){switch(t){case"aereo":return"volo aereo";case"treno":return"treno";case"bus":return"autobus";case"proprio":return"mezzo proprio";default:return"mezzo di trasporto"}}const xl=(t,a)=>Ca("Richiesta di anticipazione delle spese per missione",(a==null?void 0:a.name)||(t==null?void 0:t.person));async function xp({mission:t,member:a,data:i}){const n=await gl(t||{},a||{},i||{});await ka(n,["Richiesta_anticipazione_missione",(t==null?void 0:t.place)||(i==null?void 0:i.destination)||"",((t==null?void 0:t.date)||"").slice(0,10)],xl(t,a))}async function bp({mission:t,member:a,data:i}){const n=await gl(t||{},a||{},i||{});return za(n,xl(t,a))}function vp(t){return{destination_country:"",travel_outbound:"",travel_return:"",travel_cost_estimate:"",hotel_name:"",hotel_nights:"",hotel_total_cost:"",hotel_cost_per_night:"",hotel_max_per_night:"250",advance_amount:"",reimbursement_basis:"",signer_name:"",meals_estimate:"",forfait_daily:"",forfait_days:"",forfait_half:!1,date_end:"",purpose:"",destination:"",upb:"",carbon:null}}function jp({mission:t,member:a,onPatch:i,children:n}){const{t:o}=X(),s=Ga([!!(t!=null&&t.advance_data),!!(t!=null&&t.advance_pdf),!!(t!=null&&t.advance_signed_pdf)]),l=f.useMemo(()=>({...vp(),...t.advance_data||{}}),[t.id]),[r,d]=f.useState(l),[m,c]=f.useState(!1),[g,h]=f.useState(null);f.useEffect(()=>{d(l)},[l]);const p=hl(t);function x(y){typeof i=="function"&&i({reimbursement_method:y})}const b=f.useMemo(()=>fl(p,r),[p,r]),u=y=>isFinite(y)&&y>0?y.toLocaleString("de-DE",{minimumFractionDigits:2,maximumFractionDigits:2}):null,w=y=>parseFloat(String(y||"").replace(/\./g,"").replace(",","."))||0,v=f.useMemo(()=>{const y=parseFloat(String(r.hotel_total_cost||"").replace(/\./g,"").replace(",",".")),z=parseInt(r.hotel_nights,10);return!isFinite(y)||!isFinite(z)||z<=0?null:y/z},[r.hotel_total_cost,r.hotel_nights]);function j(y){const z={...r,...y};d(z),_(z)}const _=f.useMemo(()=>{let y=null;return z=>{y&&clearTimeout(y),y=setTimeout(async()=>{try{await i({advance_data:z}),h(new Date)}catch(T){console.error("[advance] save",T)}},700)}},[i]);async function C(){c(!0);try{await xp({mission:t,member:a,data:r});try{if(t!=null&&t.team_uid&&(t!=null&&t.id)){const y=await bp({mission:t,member:a,data:r}),z=((a==null?void 0:a.name)||"membro").replace(/[^A-Za-z0-9]+/g,"_").slice(0,30),T=((t==null?void 0:t.place)||"").replace(/[^A-Za-z0-9]+/g,"_").slice(0,30),I=`Richiesta_anticipazione_${z}_${T}.pdf`,D=new File([y],I,{type:"application/pdf"}),$=`team-missions/${t.team_uid}/${t.id}/advance.pdf`,q=await ze($,D);await i({advance_pdf:{url:q.url,path:q.path,name:D.name,size:D.size}}
426)}}catch(y){console.warn("[advance] auto-upload failed",y)}}catch(y){alert(o("Generazione PDF non riuscita: ","PDF generation failed: ")+(y.message||y))}finally{c(!1)}}return e.jsxs("div",{className:"prospetto-builder",children:[e.jsx(va,{n:1,stato:s[0],facoltativo:!0,titolo:o("Compila la richiesta di anticipazione","Fill in the advance request"),sotto:o("Serve solo se chiedi un anticipo, almeno 10 giorni prima della partenza. I dati base vengono dalla missione.","Only if you ask for an advance, at least 10 days before departure. The basic data come from the mission.")}),e.jsx(wt,{half:!0,title:"Metodo di rimborso",hint:"Determina come si calcola l'anticipo (art. 12 Regolamento). Italia: solo analitico (anticipo 75% di viaggio+vitto+alloggio). Estero: documentato (anticipo ⤠spese alberghiere) oppure forfettario (viaggio + 90% della quota giornaliera Tabella C). Si sincronizza con la scheda missione.",children:e.jsx(qe,{label:"Metodo",children:e.jsx(xe,{tone:"inherit",value:p,onChange:y=>x(y),ariaLabel:"Metodo di rimborso",style:{maxWidth:380},options:[{value:"italia_analitico",label:"Italia â rimborso analitico"},{value:"estero_documentato",label:"Estero â rimborso documentato"},{value:"estero_forfait",label:"Estero â rimborso forfettario (alternativo)"}]})})}),e.jsx(wt,{half:!0,title:"Destinazione (campi aggiuntivi)",half:!0,hint:"Persona, città , periodo e finalità arrivano automaticamente dalla missione. Aggiungi qui SOLO informazioni che mancano nella scheda missione (es. paese).",children:e.jsxs("div",{className:"mt-mission-row",children:[e.jsx(qe,{label:`Città destinazione (default: ${t.place||"â"})`,wide:!0,children:e.jsx("input",{className:"input",value:r.destination,onChange:y=>j({destination:y.target.value}),placeholder:t.place||"es. Heidelberg"})}),e.jsx(qe,{label:"Paese destinazione",children:e.jsx("input",{className:"input",value:r.destination_country,onChange:y=>j({destination_country:y.target.value}),placeholder:"es. Germania"})})]})}),e.jsxs(wt,{half:!0,title:"Viaggio",half:!0,hint:"Descrizione testuale del viaggio andata/ritorno con date e orari, più costo stimato.",children:[e.jsx(qe,{label:"Viaggio di andata (descrizione)",children:e.jsx("input",{className:"input",value:r.travel_outbound,onChange:y=>j({travel_outbound:y.target.value}),placeholder:"es. volo aereo BariâFrancoforte in data 23 luglio 2026 (partenza ore 10:40)"})}),e.jsx(qe,{label:"Viaggio di ritorno (descrizione)",children:e.jsx("input",{className:"input",value:r.travel_return,onChange:y=>j({travel_return:y.target.value}),placeholder:"es. FrancoforteâBari in data 23 agosto 2026 (partenza ore 15:00, arrivo a Bari ore 17:00)"})}),e.jsx(qe,{label:"Costo stimato del viaggio (â¬)",children:e.jsx("input",{className:"input mono",inputMode:"decimal",value:r.travel_cost_estimate,onChange:y=>j({travel_cost_estimate:y.target.value}),placeholder:"es. 300,00",style:{maxWidth:200}})})]}),p==="estero_documentato"&&e.jsxs(wt,{half:!0,title:"Sistemazione alberghiera",half:!0,hint:"Nome dell'albergo, numero di notti e costo complessivo. Il costo medio a notte è calcolato in automatico e va confrontato col massimale di ⬠250,00 a notte previsto dal Regolamento. Con il metodo documentato l'anticipo non può superare le spese alberghiere.",children:[e.jsx(qe,{label:"Nome dell'albergo / struttura",wide:!0,children:e.jsx("input",{className:"input",value:r.hotel_name,onChange:y=>j({hotel_name:y.target.value}),placeholder:"es. Aparthotel Adagio Heidelberg"})}),e.jsxs("div",{className:"mt-mission-row",children:[e.jsx(qe,{label:"Numero di notti",children:e.jsx("input",{className:"input mono",inputMode:"numeric",value:r.hotel_nights,onChange:y=>j({hotel_nights:y.target.value}),placeholder:"es. 31",style:{maxWidth:120}})}),e.jsx(qe,{label:"Costo totale alloggio (â¬)",children:e.jsx("input",{className:"input mono",inputMode:"decimal",value:r.hotel_total_cost,onChange:y=>j({hotel_total_cost:y.target.value}),placeholder:"es. 2543,81",style:{maxWidth:200}})}),e.jsx(qe,{label:"Massimale a notte (â¬)",children:e.jsx("input",{className:"input mono",inputMode:"decimal",value:r.hotel_max_per_night,onChange:y=>j({hotel_max_per_night:y.target.value}),placeholder:"250,00",style:{maxWidth:140}})})]}),v!=null&&e.jsxs("p",{className:"muted text-sm",children:["Costo medio a notte:"," ",e.jsxs("strong",{children:["⬠",v.toLocaleStr
426ing("de-DE",{minimumFractionDigits:2,maximumFractionDigits:2})]})," ","â ",parseFloat(String(r.hotel_max_per_night||"250").replace(",","."))>=v?"sotto massimale, ok.":"SOPRA massimale, attenzione."]})]}),p==="estero_forfait"&&e.jsxs(wt,{half:!0,title:"Rimborso forfettario (trattamento alternativo)",half:!0,hint:"Quota giornaliera da Tabella C (AREA A/B/C ⬠120, D ⬠125, E ⬠130, F ⬠140 per ogni 24h), numero di giornate, ed eventuale mezza quota per prosecuzione ⥠12h. L'anticipo = spese di viaggio + 90% della quota forfettaria.",children:[e.jsxs("div",{className:"mt-mission-row",children:[e.jsx(qe,{label:"Quota giornaliera ⬠(Tabella C)",children:e.jsx("input",{className:"input mono",inputMode:"decimal",value:r.forfait_daily,onChange:y=>j({forfait_daily:y.target.value}),placeholder:"es. 120,00",style:{maxWidth:170}})}),e.jsx(qe,{label:"N. giornate (24h)",children:e.jsx("input",{className:"input mono",inputMode:"numeric",value:r.forfait_days,onChange:y=>j({forfait_days:y.target.value}),placeholder:"es. 3",style:{maxWidth:120}})})]}),e.jsxs("label",{style:{display:"flex",alignItems:"center",gap:8,marginTop:8,fontSize:13,cursor:"pointer"},children:[e.jsx("input",{type:"checkbox",checked:!!r.forfait_half,onChange:y=>j({forfait_half:y.target.checked})}),e.jsx("span",{children:"Prosecuzione di almeno 12 ore continuative (+ mezza quota)"})]})]}),p==="estero_forfait"&&e.jsx(wt,{half:!0,title:"Dati per la lettera di incarico (art. 9 c.6)",half:!0,hint:"Per le missioni all'estero col metodo forfettario il Regolamento (art. 9 c.6) richiede matricola e reddito annuo lordo del beneficiario. Si salvano sulla missione e vengono stampati nella lettera di incarico.",children:e.jsxs("div",{className:"mt-mission-row",children:[e.jsx(qe,{label:"Matricola",children:e.jsx("input",{className:"input mono",value:r.matricola||"",onChange:y=>j({matricola:y.target.value}),placeholder:"es. 012345",style:{maxWidth:170}})}),e.jsx(qe,{label:"Reddito annuo lordo (â¬)",children:e.jsx("input",{className:"input mono",inputMode:"decimal",value:r.reddito_lordo||"",onChange:y=>j({reddito_lordo:y.target.value}),placeholder:"es. 35.000,00",style:{maxWidth:200}})})]})}),p==="italia_analitico"&&e.jsx(wt,{half:!0,title:"Vitto e alloggio (stima)",hint:"Spese stimate di vitto e alloggio (massimali Tabella A: vitto ⬠40 tra 8-12h / ⬠80 oltre 12h; alloggio max ⬠250/notte). L'anticipo = 75% di viaggio + vitto + alloggio.",children:e.jsxs("div",{className:"mt-mission-row",children:[e.jsx(qe,{label:"Vitto stimato (â¬)",children:e.jsx("input",{className:"input mono",inputMode:"decimal",value:r.meals_estimate,onChange:y=>j({meals_estimate:y.target.value}),placeholder:"es. 80,00",style:{maxWidth:170}})}),e.jsx(qe,{label:"Alloggio stimato (â¬)",children:e.jsx("input",{className:"input mono",inputMode:"decimal",value:r.hotel_total_cost,onChange:y=>j({hotel_total_cost:y.target.value}),placeholder:"es. 200,00",style:{maxWidth:170}})})]})}),e.jsx(wt,{half:!0,title:"Importo dell'anticipazione richiesta",hint:p==="estero_forfait"?"Anticipabile: costo del viaggio PER INTERO + fino al 90% della quota forfettaria (art. 12 c. 4). Il costo del viaggio si inserisce nella sezione âViaggioâ qui sopra.":p==="italia_analitico"?"Anticipabile: 75% delle spese stimate di viaggio, vitto e alloggio (art. 12 c. 3).":"Anticipabile: solo le spese alberghiere (art. 12 c. 4). Tipicamente coincide col costo totale alloggio.",children:p==="estero_documentato"?e.jsxs(e.Fragment,{children:[e.jsx(qe,{label:"Importo (â¬)",children:e.jsx("input",{className:"input mono",inputMode:"decimal",value:r.advance_amount,onChange:y=>j({advance_amount:y.target.value}),placeholder:u(b)?`suggerito: ${u(b)}`:"es. 2543,81",style:{maxWidth:200}})}),u(b)&&e.jsxs("p",{className:"muted text-sm",style:{marginTop:6},children:["Importo suggerito: ",e.jsxs("strong",{children:["⬠",u(b)]})," ",e.jsx("button",{type:"button",className:"mt-pill",style:{marginLeft:6},onClick:()=>j({advance_amount:u(b)}),children:"Usa importo suggerito"})]})]}):e.jsxs("div",{style:{padding:"12px 14px",borderRadius:10,background:"rgba(0,0,0,0.035)"},children:[p==="estero_forfait"?e.jsxs("p",{className:"text-sm",style:{margin:0,lineHeight:1.8},children:["Viaggio (per intero): ",e.jsxs("strong",{children:["⬠",u(w(r.travel_cost_estimate))||"0,00"]}),e.jsx("br",{}),"90% della quota forfettaria: ",e.jsxs("strong",{children:["⬠",u(.9*Es(r))||"0,00"]}),e.jsx("br",{}
426),"Anticipo richiesto: ",e.jsxs("strong",{children:["⬠",u(b)||"0,00"]})]}):e.jsxs("p",{className:"text-sm",style:{margin:0,lineHeight:1.8},children:["75% di viaggio + vitto + alloggio",e.jsx("br",{}),"Anticipo richiesto: ",e.jsxs("strong",{children:["⬠",u(b)||"0,00"]})]}),e.jsx("p",{className:"muted text-xs",style:{margin:"6px 0 0"},children:"Calcolato automaticamente dai campi qui sopra â include sempre il viaggio."})]})}),e.jsx(wt,{title:"Frase descrittiva del regime di rimborso (opzionale)",hint:"Generata automaticamente in base al metodo scelto sopra (cita gli articoli corretti del Regolamento). Compila questo campo solo se vuoi sovrascrivere il testo.",children:e.jsx(qe,{label:"Frase descrittiva del regime di rimborso",wide:!0,children:e.jsx("textarea",{className:"textarea",rows:2,value:r.reimbursement_basis,onChange:y=>j({reimbursement_basis:y.target.value}),placeholder:"(lasciare vuoto per usare il default)"})})}),e.jsx(wt,{title:"Firmatario",half:!0,children:e.jsx("input",{className:"input",value:r.signer_name,onChange:y=>j({signer_name:y.target.value}),placeholder:(a==null?void 0:a.name)||t.person||"Nome che compare sotto «In fede»"})}),e.jsx(va,{n:2,stato:s[1],titolo:o("Genera il PDF","Generate the PDF"),sotto:o("Il PDF si scarica: va firmato e caricato al passo 3.","The PDF downloads: sign it and upload it at step 3.")}),e.jsxs("div",{className:"ospite-formactions",children:[e.jsx("div",{className:"muted text-xs",children:g?`${o("Salvato","Saved")} ${g.toLocaleTimeString("it-IT")}`:""}),e.jsx("div",{className:"ospite-pill-row",children:e.jsxs("button",{type:"button",className:"mt-pill is-primary anim-shimmer",onClick:C,disabled:m,children:[e.jsx(ta,{size:14}),e.jsx("span",{children:m?"â¦":o("Genera PDF richiesta anticipazione","Generate advance request PDF")})]})})]}),n]})}function wt({title:t,hint:a,children:i,half:n=!1}){return e.jsxs("div",{className:"ospite-formsection"+(n?" is-half":""),children:[e.jsx("h3",{children:t}),a&&e.jsx("p",{className:"muted text-xs",style:{marginTop:-6,marginBottom:8},children:a}),i]})}function qe({label:t,wide:a,children:i}){return e.jsxs("div",{className:"mt-field"+(a?" is-wide":""),children:[e.jsx("label",{className:"mt-field-label muted text-xs",children:t}),i]})}async function yp({budgetRef:t,missionId:a,storagePath:i,fileName:n,fileUrl:o,piUid:s=Vi}){var b;const l=(t==null?void 0:t.row_id)||a;if(!l)return;const r=oe(te,"users",s,"data","main"),d=await vi(r);if(!d.exists())return;const m=d.data();if(!m||!m.value)return;let c;try{c=JSON.parse(m.value)}catch{return}const g=(b=c==null?void 0:c.rows)==null?void 0:b.missioni;if(!Array.isArray(g))return;const h=g.findIndex(u=>u&&u.id===l);if(h===-1)return;const p=Array.isArray(g[h].documents)?g[h].documents:[];if(p.some(u=>typeof u=="string"?u===i:(u==null?void 0:u.path)===i))return;const x={path:i,name:n,url:o,added_at:new Date().toISOString(),source:"rt-import"};g[h]={...g[h],documents:[...p,x]},await _e(r,{value:JSON.stringify(c),ts:ie()},{merge:!0})}async function _p({budgetRef:t,missionId:a,storagePath:i,piUid:n=Vi}){var p;const o=(t==null?void 0:t.row_id)||a;if(!o)return;const s=oe(te,"users",n,"data","main"),l=await vi(s);if(!l.exists())return;const r=l.data();if(!r||!r.value)return;let d;try{d=JSON.parse(r.value)}catch{return}const m=(p=d==null?void 0:d.rows)==null?void 0:p.missioni;if(!Array.isArray(m))return;const c=m.findIndex(x=>x&&x.id===o);if(c===-1)return;const g=Array.isArray(m[c].documents)?m[c].documents:[],h=g.filter(x=>typeof x=="string"?x!==i:(x==null?void 0:x.path)!==i);h.length!==g.length&&(m[c]={...m[c],documents:h},await _e(s,{value:JSON.stringify(d),ts:ie()},{merge:!0}))}function bl(t,a,i){const n=i==="en"?"en-GB":"it-IT",o=m=>{const c=Date.parse(String(m).slice(0,10)+"T12:00:00");return Number.isFinite(c)?new Date(c):null},s=o(t),l=a&&a!==t?o(a):null;if(!s)return String(t||"");const r=m=>m.getDate(),d=m=>m.toLocaleDateString(n,{month:"short"}).replace(".","");return l?s.getFullYear()!==l.getFullYear()?`${r(s)} ${d(s)} ${s.getFullYear()} â ${r(l)} ${d(l)} ${l.getFullYear()}`:s.getMonth()!==l.getMonth()?`${r(s)} ${d(s)} â ${r(l)} ${d(l)} ${l.getFullYear()}`:`${r(s)}â${r(l)} ${d(l)} ${l.getFullYear()}`:`${r(s)} ${d(s)} ${s.getFullYear()}`}const Np=["pianificata","autorizzata","spesa"],wp={pianificata:"planned",autorizzata:"authorised",spesa:"spent"},zp={pianificata:"pianificata",autorizzata:"autorizzata",spesa:"spesa"};function vl(t,a){return(a==="it"?zp:wp)[t]||t}function Cp(t){return[{value:"budget",label:"Budget"},{value:"sg",label:t("Spese generali (SG)","General expenses (SG)")}]}function kp(){return Math.random().toString(36).slice(2,10)+Date.now().toString(36).slice(-4)}function tn(t){return!t&&t!==0?0:typeof t=="number"?t:parseFloat(String(t).replace(/\./g,"").replace(",","."))||0}
426function Sp(t){return t==null||isNaN(t)?"â":t.toLocaleString("de-DE",{minimumFractionDigits:2,maximumFractionDigits:2})}function jl(t){return t==null||isNaN(t)?"â":Math.round(t).toLocaleString("de-DE")}const Dp=["milano","roma","torino","napoli","firenze","bologna","perugia","siena","palermo","catania","trento","padova","venezia","genova","bari","cagliari","verona","trieste","pisa","parma","modena","reggio","lecce","sassari","ancona","aquila","l'aquila","udine","brescia","ferrara","bergamo","catanzaro","taranto","salerno","rimini","prato","matera","vicenza","viterbo","varese","agrigento","foggia","potenza","livorno","pescara","campobasso","crotone","asti","siracusa","caserta","grosseto","arezzo","novara"];function Tp(t){if(!t)return null;const a=t.toLowerCase();return Dp.some(i=>a.includes(i))?"MI":"ME"}function Ip(t){if(!t)return"";const i=t.replace(/\([^)]*\)/g,"").trim().split(/\s+/).filter(Boolean);return i.length?i[i.length-1].replace(/[^A-Za-zÃ-ÿ'-]/g,""):""}function Pp(t){if(!t)return null;const a=String(t).match(/^(\d{4})/);return a?parseInt(a[1],10):null}function Ep({allMissions:t,mission:a}){const i=Tp(a.place),n=Ip(a.person),o=Pp(a.date);if(!i||!n||!o)return null;const s=new RegExp("^(?:ME|MI)-"+n+"-"+o+"-(\\d+)$","i");let l=0;return t.forEach(r=>{if(r.id===a.id||typeof r.code!="string")return;const d=r.code.match(s);if(d){const m=parseInt(d[1],10);m>l&&(l=m)}}),i+"-"+n+"-"+o+"-"+String(l+1).padStart(2,"0")}function Mo({member:t,isAdmin:a,onBack:i,allTeam:n=!1,headExtra:o=null,guide:s=null}){const{t:l}=X(),[r,d]=f.useState([]),[m,c]=f.useState(!0),g=f.useRef({}),h=f.useRef({}),[p,x]=f.useState(null),[b,u]=f.useState(null);f.useEffect(()=>{function D($){const q=$.detail||{};u({id:Date.now(),tone:q.tone||"info",title:q.title||"",body:q.body||""});const R=Number(q.ttl)||5e3,O=setTimeout(()=>u(k=>k&&k.id===O?null:k),R);u(k=>k&&{...k,id:O})}return window.addEventListener("mt:toast",D),()=>window.removeEventListener("mt:toast",D)},[]),f.useEffect(()=>{const D=n?ft(Ie(te,"team_missions")):ft(Ie(te,"team_missions"),Bt("team_uid","==",t.uid)),$=Ye(D,q=>{const R=q.docs.map(k=>({id:k.id,...k.data()})),O=g.current;for(const k of R)O[k.id]&&Object.assign(k,O[k.id]);R.sort((k,N)=>{const L=k.date||"",B=N.date||"";return!L&&!B?0:L?B?B.localeCompare(L):-1:1}),d(R),c(!1)},q=>
426{console.error("[team-missions] subscribe error:",q),x(l("Caricamento delle missioni non riuscito: ","Failed to load missions: ")+q.message),c(!1)});return()=>$()},[t.uid,n]),f.useEffect(()=>()=>{Object.entries(h.current).forEach(([D,$])=>{var N;clearTimeout($);const q=D.indexOf(":"),R=D.slice(0,q),O=D.slice(q+1),k=(N=g.current[R])==null?void 0:N[O];k!==void 0&&_e(oe(te,"team_missions",R),{[O]:k,updated_at:ie()},{merge:!0}).catch(()=>{})})},[]);const[w,v]=f.useState(null);async function j({kind:D="standard"}={}){const $=kp();v($);const q=oe(te,"team_missions",$),R={id:$,team_uid:t.uid,person:t.name,date:"",place:"",year:"",code:"",amount:0,source:"budget",sforo_label:"",status:"pianificata",note:"",source_kind:D,request_pdf:null,assignment_pdf:null,assignment_signed_pdf:null,authorized_pdf:null,generic_documents:[],created_at:ie(),created_by:ye.currentUser.uid,updated_at:ie()};await _e(q,R)}function _(D,$,q){const R=g.current;R[D]={...R[D]||{},[$]:q},d(k=>k.map(N=>N.id===D?{...N,[$]:q}:N));const O=D+":"+$;h.current[O]&&clearTimeout(h.current[O]),h.current[O]=setTimeout(async()=>{delete h.current[O];try{const k=oe(te,"team_missions",D),N=!a&&($==="place"||$==="date")&&(await vi(k)).data()||null;if(await _e(k,{[$]:q,updated_at:ie()},{merge:!0}),N){const L={...N,[$]:q};Yc(N,L)&&(await _e(k,{details_notified_at:ie()},{merge:!0}),Zc({member:t,mission:L}))}}
426catch(k){console.error("[team-missions] updateField",k)}finally{const k=g.current[D];k&&(delete k[$],Object.keys(k).length||delete g.current[D])}},350)}async function C(D){var $,q,R,O,k,N,L,B,P;if(confirm(l("Eliminare la missione","Delete the mission")+(D.place?' "'+D.place+'"':"")+"?")){($=D.request_pdf)!=null&&$.path&&await de(D.request_pdf.path),(q=D.assignment_pdf)!=null&&q.path&&await de(D.assignment_pdf.path),(R=D.authorized_pdf)!=null&&R.path&&await de(D.authorized_pdf.path),(O=D.assignment_signed_pdf)!=null&&O.path&&await de(D.assignment_signed_pdf.path),(k=D.prospetto_pdf)!=null&&k.path&&await de(D.prospetto_pdf.path),(N=D.advance_pdf)!=null&&N.path&&await de(D.advance_pdf.path),(L=D.prospetto_signed_pdf)!=null&&L.path&&await de(D.prospetto_signed_pdf.path),(B=D.end_declaration_pdf)!=null&&B.path&&await de(D.end_declaration_pdf.path);for(const E of["request_signed_person_pdf","request_signed_pi_pdf","assignment_signed_person_pdf","assignment_signed_pi_pdf","end_declaration_signed_pdf","advance_signed_pdf"])if((P=D[E])!=null&&P.path)try{await de(D[E].path)}catch{}if(Array.isArray(D.direzione_docs)){for(const E of D.direzione_docs)if(E!=null&&E.path)try{await de(E.path)}catch{}}if(Array.isArray(D.receipts)){for(const E of D.receipts)if(E!=null&&E.path)try{await de(E.path)}catch{}}if(Array.isArray(D.generic_documents)){for(const E of D.generic_documents)if(E!=null&&E.path)try{await de(E.path)}catch{}}await gt(oe(te,"team_missions",D.id))}}const y=f.useMemo(()=>{const D={A1:0,A2:0,A3:0,A4:0,none:0,all:0};return r.forEach($=>{const q=tn($.amount);D.all+=q;const R=String($.year||"");R==="1"?D.A1+=q:R==="2"?D.A2+=q:R==="3"?D.A3+=q:R==="4"?D.A4+=q:D.none+=q}),D},[r]),[z,T]=f.useState("all"),I=f.useMemo(()=>z==="all"?r:z==="none"?r.filter(D=>!String(D.year||"").trim()):r.filter(D=>String(D.year||"")===z),[r,z]);return e.jsxs(e.Fragment,{children:[e.jsx("section",{className:"mt-band mt-band-dark",children:e.jsxs("div",{className:"mt-wrap",children:[i&&e.jsxs("button",{className:"btn btn-ghost btn-sm mt-back reveal",onClick:i,children:[e.jsx(Wa,{size:14})," ",l("Indietro","Back")]}),e.jsxs("div",{className:"mt-section-head reveal","data-d":"1",style:{alignItems:"flex-start"},children:[e.jsxs("div",{children:[e.jsx("p",{className:"mt-eyebrow",children:l("Research Team","Research Team")}),e.jsxs("h1",{className:"mt-section-title",children:[l("Missioni di","Missions of")," ",n?l("tutto il team","the whole team"):t.name]}),e.jsx("p",{className:"mt-section-sub",children:n?l("Tutte le missioni del team in un unico elenco (la colonna Persona indica di chi è ciascuna). Apri una voce per modificarla o caricare documenti, anche per altri ricercatori.","All team missions in a single list (the Person column shows whose each one is). Open any entry to edit it or upload documents, including for other researchers."):a?l("Tutte le missioni di questo ricercatore. Puoi crearle e modificarle, e caricare il PDF autorizzato.","All of this researcher's missions. You can create and edit them, and upload the authorised PDF."):l("Aggiungi qui le tue missioni e carica il PDF di richiesta. Una volta approvate dal PI, il PDF autorizzato comparirà di fianco â scaricabile ma non rimovibile.","Add your missions here and upload the request PDF. Once the PI approves them, the authorised PDF will appear alongside â downloadable but not removable.")})]}),e.jsxs("div",{style:{display:"flex",gap:8,flexWrap:"wrap",alignItems:"center"},children:[o,!n&&e.jsxs("button",{className:"btn btn-sm btn-primary anim-shimmer",onClick:()=>j({kind:"standard"}),title:l('Crea una nuova missione. Se richiesta e lettera di incarico sono già state gestite fuori dal sistema, spunta "Autorizzazione ottenuta esternamente" nella scheda della missione: potrai comunque generare fine missione, anticipazione, prospetto e ricevute.','Create a new mission. If the request and assignment letter were already handled outside the system, tick "Authorisation obtained externally" in the mission card: you can still generate end-of-mission, advance, statement and receipts.'),children:[e.jsx(Le,{size:14})," ",l("Nuova missione","New mission")]})]})]}),s]})}),e.jsx("section",{className:"mt-band mt-band-tight",children:e.jsxs("div",{className:"mt-wrap",children:[b&&e.jsxs("div",{role:"status",className:"anim-toast-in mt-toast",children:[e.jsx(Ot,{size:16,className:"mt-toast-icon"}),e.jsxs("div",{children:[e.jsx("strong",{children:b.title}),b.body&&e.jsxs("span",{children:[" â ",b.body]})]})]}),p&&e.jsxs("div",{className:"login-alert login-alert-error mt-error-banner",children:[e.jsx(at,{size:16})," ",e.jsx("span",{children:p})]}),e.jsx(Kr,{configKey:"missions_instructions",title:l("Istruzioni e scadenze per la registrazione delle missioni","Instru
426ctions and deadlines for recording missions"),isAdmin:a,defaultText:l(`Per ogni missione: inserisci data, luogo, anno di progetto (A1âA4), codice ME-/MI- e importo stimato. 427Carica il PDF di richiesta missione (modulo dellâUniversità , firmato) â il PI caricherà di fianco la versione autorizzata. 428Stati: pianificata â autorizzata â spesa. Tieni aggiornato lo stato. Le missioni in Italia non sono direttamente rendicontabili (rientrano nel forfait Spese Generali).`,`For each mission: enter date, place, project year (A1âA4), ME-/MI- code and estimated amount. 429Upload the mission request PDF (University template, signed) â the PI will upload the authorised version alongside. 430Statuses: planned â authorised â spent. Keep the status up to date. Missions within Italy are not directly reportable (they fall under the General Expenses flat rate).`)}),e.jsxs("div",{className:"mt-card mt-totals",children:[e.jsx(Ea,{label:`${l("Anno","Year")} 1`,val:y.A1}),e.jsx(Ea,{label:`${l("Anno","Year")} 2`,val:y.A2}),e.jsx(Ea,{label:`${l("Anno","Year")} 3`,val:y.A3}),e.jsx(Ea,{label:`${l("Anno","Year")} 4`,val:y.A4}),y.none>0&&e.jsx(Ea,{label:l("Senza anno","No year"),val:y.none,muted:!0}),e.jsx(Ea,{label:l("Totale","Total"),val:y.all,accent:!0}),e.jsxs("span",{className:"muted text-sm mt-ml-auto",children:[r.length," ",r.length===1?l("missione","mission"):l("missioni","missions")]})]}),r.length>0&&e.jsxs("div",{className:"mt-yfilter",children:[e.jsx("span",{className:"mt-yfilter-label",children:l("Filtra per anno","Filter by year")}),[{v:"all",label:l("Tutte","All"),count:r.length},{v:"1",label:"A1",count:r.filter(D=>String(D.year||"")==="1").length},{v:"2",label:"A2",count:r.filter(D=>String(D.year||"")==="2").length},{v:"3",label:"A3",count:r.filter(D=>String(D.year||"")==="3").length},{v:"4",label:"A4",count:r.filter(D=>String(D.year||"")==="4").length},{v:"none",label:l("Senza anno","No year"),count:r.filter(D=>!String(D.year||"").trim()).length}].filter(D=>D.v==="all"||D.count>0).map(D=>{const $=z===D.v;return e.jsxs("button",{type:"button",onClick:()=>T(D.v),className:"mt-yfilter-chip"+($?" is-active":""),children:[D.label,e.jsxs("span",{className:"mt-yfilter-chip-count",children:["· ",D.count]})]},D.v)})]}),m?e.jsx("div",{className:"mt-card mt-empty",children:l("Caricamentoâ¦","Loadingâ¦")}):r.length===0?e.jsxs("div",{className:"mt-card mt-empty",children:[l("Nessuna missione registrata. Clicca","No missions recorded. Click")," ",e.jsxs("strong",{children:["+ ",l("Nuova missione","New mission")]})," ",l("per iniziare.","to start.")]}):I.length===0?e.jsxs("div",{className:"mt-card mt-empty",children:[l("Nessuna missione corrisponde al filtro per anno selezionato.","No missions match the selected year filter.")," ",e.jsx("button",{type:"button",className:"btn btn-link",onClick:()=>T("all"),style:{display:"inline",padding:0},children:l("Mostra tutte","Show all")})]}):e.jsx("div",{className:"mt-mission-list",children:I.map(D=>e.jsx(Ap,{m:D,member:n?{uid:D.team_uid,name:D.person,super_admin:t.super_admin}:t,isAdmin:a,allMissions:r,appenaCreata:w,onUpdate:($,q)=>_(D.id,$,q),onRemove:()=>C(D)},D.id))})]})})]})}function Ea({label:t,val:a,accent:i,muted:n}){return e.jsxs("div",{className:"mt-stat"+(i?" is-accent":"")+(n?" is-muted":""),children:[e.jsx("div",{className:"mt-stat-label",children:t}),e.jsxs("div",{className:"mt-stat-val",children:["â¬",Sp(a)]})]})}function Ap({m:t,member:a,isAdmin:i,allMissions:n,appenaCreata:o,onUpdate:s,onRemove:l}){var W;const{t:r,lang:d}=X(),m=!!(t.place&&t.person&&t.date),[c,g]=f.useState(!1),[h,p]=f.useState(!1),[x,b]=f.useState(null),u=t.source_kind==="budget-import",w=t.external_auth!=null?!!t.external_auth:t.source_kind==="fuori-flusso",v=async()=>{const M=Ep({allMissions:n,mission:t});M?await s("code",M):alert(r("Per generare il codice devono essere compilati Persona, Data e Luogo.","Person, Date and Place must be filled in to generate the code."))},{openMask:j,update:_,close:C,masks:y}=Va(),z="mission-"+t.id,T=y.find(M=>M.id===z)||null,I=!!T,D=t.place||r("Missione senza luogo","Mission without a place"),$=[t.date,t.code,w&&r("aut. esterna","ext. auth")].filter(
430Boolean).join(", ")||r("Dettagli missione","Mission details"),q=e.jsx("div",{className:"slideover-panel",children:e.jsx($p,{m:t,member:a,isAdmin:i,isImported:u,externalAuth:w,canSuggestCode:m,handleGenerateCode:v,onUpdate:s,onRemove:l,endDeclOpen:c,setEndDeclOpen:g,assignmentOpen:h,setAssignmentOpen:p,mailPicker:x,setMailPicker:b})}),R=e.jsx(pi,{size:18}),O=r("Dettagli missione","Mission details"),k=$&&$!==O?`${D}, ${$}`:D,N=T==null?void 0:T.state,L=f.useRef({content:q,title:k,icon:R});L.current={content:q,title:k,icon:R};const B=JSON.stringify([t.id,t.place,t.date,t.date_end,t.code,t.person,t.amount,t.status,t.year,t.note,t.closed_at?1:0,w?1:0,u?1:0,((W=t.updated_at)==null?void 0:W.seconds)??t.updated_at??null,c?1:0,h?1:0,x?1:0,i?1:0,(a==null?void 0:a.uid)||""]);f.useEffect(()=>{if(!I)return;const{content:M,title:J,icon:V}=L.current;_(z,{title:J,icon:V,content:M})},[I,N,B]);const P=f.useRef(!1);f.useEffect(()=>{P.current||o&&t.id===o&&(P.current=!0,Y())},[o]);const E=(Array.isArray(n)?n:[]).filter(M=>M&&M.id).map(M=>({id:"mission-"+M.id,label:[M.place||r("Luogo non impostato","Place not set"),M.date,M.code].filter(Boolean).join(", ")})),Y=()=>j({id:z,title:k,icon:R,content:q,item:t.id,siblings:E});f.useEffect(()=>Bd(M=>String(M)===z,()=>Y()),[]);function S(){I?C(z):Y()}return e.jsxs("article",{className:"mt-listrow"+(I?" is-open":""),role:"button",tabIndex:0,"aria-expanded":I,onClick:M=>{M.target.closest("button, a, input, select, textarea")||S()},onKeyDown:M=>{(M.key==="Enter"||M.key===" ")&&(M.preventDefault(),S())},children:[e.jsxs("span",{className:"mt-listrow-cell mt-listrow-primary is-stacked",children:[e.jsx("strong",{className:"mt-listrow-title",children:t.place||e.jsx("span",{className:"mt-listrow-ph",children:r("Luogo non impostato","Place not set")})}),(t.code||w)&&e.jsxs("span",{className:"mt-listrow-meta",children:[t.code&&e.jsx("span",{className:"mono mt-listrow-code",children:t.code}),w&&e.jsx("span",{className:"mt-mhead-tag is-fuori",children:r("aut. esterna","ext. auth")})]})]}),e.jsx("span",{className:"mt-listrow-cell mt-listrow-person",children:t.person||"â"}),e.jsxs("span",{className:"mt-listrow-cell mt-listrow-date",children:[e.jsx("span",{children:t.date?bl(t.date,t.date_end,d):"â"}),t.year&&e.jsxs("span",{className:"mt-mhead-tag is-year mt-listrow-year",children:["A",t.year]})]}),e.jsxs("span",{className:"mono mt-listrow-cell mt-listrow-amount",children:["â¬",jl(tn(t.amount))]}),e.jsx("span",{className:"mt-listrow-cell mt-mhead-status is-"+(t.closed_at?"closed":t.status||"pianificata"),children:t.closed_at?r("Chiusa","Closed"):vl(t.status||"pianificata",d)}),e.jsxs("button",{type:"button",className:"mt-listrow-open",onClick:M=>{M.stopPropagation(),S()},"aria-label":I?r("Chiudi dettaglio missione","Close mission detail"):r("Apri dettaglio missione","Open mission detail"),children:[I?r("Aperto","Opened"):r("Apri","Open"),e.jsx(yt,{size:15})]})]})}function $p({m:t,member:a,isAdmin:i,isImported:n,externalAuth:o,canSuggestCode:s,handleGenerateCode:l,onUpdate:r,onRemove:d,endDeclOpen:m,setEndDeclOpen:c,assignmentOpen:g,setAssignmentOpen:h,mailPicker:p,setMailPicker:x,tabIniziale:b="data"}){var I,D,$,q,R,O,k;const{t:u,lang:w}=X(),v=Wu(t),j=Ga([Array.isArray(t.expense_items)&&t.expense_items.length>0,Array.isArray((I=t.prospetto_data)==null?void 0:I.travel_rows)&&t.prospetto_data.travel_rows.some(N=>N&&(N.day||N.departure)),!!((D=t.prospetto_signed_pdf)!=null&&D.url),!!(($=t.end_declaration_signed_pdf)!=null&&$.url),!!t.chiusura_inviata_at]),_=Ga([!!(t.place&&t.date),!!(t.request_pdf||t.assignment_pdf||t.request_signed_person_pdf||t.assignment_signed_person_pdf),cs(t)||Ji(t)||kt(t)&&v.pronto,ds(t)||kt(t)||Ji(t),!!(t.segreteria_inviata_at||t.authorized_pdf),!!(t.authorized_pdf&&t.assignment_signed_pdf)]),[C,y]=f.useState(b),z=[{key:"data",label:u("Dati missione","Mission data")},{key:"advance",label:u("Richiesta anticipazione","Advance request")},{key:"prospetto",label:u("Prospetto riepilogativo","Summary statement")},{key:"finali",label:u("Documenti finali","Final documents")}],T=N=>C===N?void 0:{display:"none"};return e.jsxs(e.Fragment,{children:[!n&&e.jsx("div",{className:"mt-mission-tabs",children:z.map(N=>e.jsx("button",{type:"button",className:"mt-mission-tab"+(C===N.key?" is-active":""),onClick:()=>y(N.key),children:N.label},N.key))}),e.jsxs("div",{className:"mt-mission-pane mt-mission-pane-data",style:T("data"),children:[e.jsxs("div",{className:"mt-mission-pane-col",children:[(()=>{var E;const N=(a==null?void 0:a.super_admin)===!0,L=!!t.closed_at,B=i||((E=ye.currentUser)==null?void 0:E.uid)===t.team_uid,P={display:"flex",alignItems:"center",gap:12,flexWrap:"wrap",margin:"0 0 14px",padding:"11px 14px",borderRadius:10,border:"1px solid var(--border)"};return L?e.jsxs("div",{style:{...P,background:"color-mix(in srgb, var(--color-success, #16a34a) 12%, transparent)"},children:[e.jsx("strong",{style:{fontSize:13.5},children:u("Missione chiusa","Mission closed")}),N?e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",style:{marginLeft:"auto"},onClick:()=>{r("closed_at",null),r("closed_by",null)},children:u("Riapri missione","Reopen mission")}):e.jsx("span",{className:"muted",style:{marginLeft:"auto",fontSize:12.5},children:u("Solo il PI può riaprirla.","Only the PI can reopen it.")})]}):B?e.jsxs("div",{style:P,children:[e.jsx("span",{className:"muted",style:{fontSize:12.5},children:u("Missione conclusa? Chiudila per fermare i promemoria.","Mission finished? Close it to stop the reminders.")}),e.jsx("button",{type:"button",className:"btn btn-primary btn-sm",style:{marginLeft:"auto"},title:u("Segna la missione come conclusa","Mark the mission as finished"),onClick:()=>{var Y;r("closed_at",ie()),r("closed_by",((Y=ye.currentUser)==null?void 0:Y.uid)||null)},children:u("Chiudi missione","Close mission")})]}):null})(),e.jsx(va,{n:1,stato:_[0],titolo:u("Dati della missione","Mission data"),sotto:u("Chi, dove, quando, quanto: servono per generare i documenti.","Who, where, when, how much: needed to generate the documents.")}),e.jsxs("div",{className:"mt-mission-row",children:[e.jsx(Te,{label:u("Persona","Person"),wide:!0,children:e.jsx(se,{className:"input",value:t.person||"",onChange:N=>r("person",N.target.value)})}),e.jsx(Te,{label:u("Qualifica (universitaria)","University role"),wide:!0,children:e.jsx(se,{className:"input",value:t.qualifica||"",onChange:N=>r("qualifica",N.target.value),placeholder:(a==null?void 0:a.qualifica)||u("es. Ricercatore a tempo determinato, Professore Associatoâ¦","e.g. Researcher, Associate Professorâ¦")})}),e.jsx(Te,{label:u("Data","Date"),children:e.jsx(Pe,{className:"input",value:t.date||"",onChange:N=>r("date",N.target.value)})}),e.jsx(Te,{label:u("Luogo","Place"),wide:!0,children:e.jsx(se,{className:"input",value:t.place||"",onChange:N=>r("place",N.target.value),placeholder:u("es. Bruxelles","e.g. Brussels")})}),e.jsx(Te,{label:u("Anno","Year"),children:e.jsx(xe,{tone:"inherit",value:t.year||"",onChange:N=>r("year",N),ariaLabel:u("Anno","Year"),options:[{value:"",label:"â"},{value:"1",label:"A1"},{value:"2",label:"A2"},{value:"3",label:"A3"},{value:"4",label:"A4"}]})}),e.jsx(Te,{label:u("Codice","Code"),children:e.jsxs("div",{className:"mt-code-inputrow",children:[e.jsx(se,{className:"input",value:t.code||"",onChange:N=>r("code",N.target.value),placeholder:"ME-Cognome-YYYY-NN",style:{flex:1,minWidth:0}}),e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:l,disabled:!s,title:s?u("Genera ME/MI-Cognome-Anno-NN dagli altri campi","Generate ME/MI-Surname-Year-NN from the other fields"):u("Compila prima Persona, Data e Luogo","Fill in Person, Date and Place first"),children:"â»"})]})})]}),e.jsxs("div",{className:"mt-mission-row",children:[e.jsxs(Te,{label:u("Importo (â¬)","Amount (â¬)"),children:[e.jsx(se,{className:"input mono",inputMode:"decimal",value:t.amount??0,onChange:N=>r("amount",tn(N.target.value))}),!t.closed_at&&t.prospetto_data&&e.jsx("span",{className:"muted text-xs",children:u("Segue il totale complessivo del prospetto, prima di togliere l'anticipazione.","Follows the statement's overall total, before the advance is deducted.")})]}),e.jsx(Te,{label:u("Fonte di finanziamento","Funding source"),children:e.jsx(xe,{tone:"inherit",value:t.source||"budget",onChange:N=>r("source",N),ariaLabel:u("Fonte di finanziamento","Funding source"),options:Cp(u)})}),t.source==="sg"&&e.jsx(Te,{label:u("Sforo SG (etichetta libera)","SG overrun (free-text label)"),wide:!0,children:e.jsx(se,{className:"input",value:t.sforo_label||"",onChange:N=>r("sforo_label",N.target.value),placeholder:u("es. sforo missioni PI / margine SG","e.g. PI missions overrun / SG margin")})}),e.jsx(Te,{label:u("Stato","Status"),children:e.jsx(xe,{tone:"inherit",value:t.status||"pianificata",onChange:N=>r("status",N),ariaLabel:u("Stato","Status"),options:Np.map(N=>({value:N,label:vl(N,w)}))})}),e.jsx(Te,{label:u("Subtotale","Subtotal"),align:"right",children:e.jsxs("div",{className:"mt-mission-subtotal mono",children:["â¬",jl(tn(t.amount))]})})]}),e.jsx("div",{className:"mt-mission-row",children:e.jsx(Te,{label:u("Note","Note"),wide:!0,children:e.jsx(se,{as:"textarea",className:"textarea",rows:2,value:t.note||"",onChange:N=>r("note",N.target.value)})})}),e.jsx(Te,{label:u("Descrizione della missione (per il PDF di richiesta, in italiano)","Mission description (for the request PDF, in Italian)"),wide:!0,children:e.jsx(se,{className:"input",value:t.description||"",onChange:N=>r("description",N.target.value),placeholder:"e.g. Soggiorno di ricerca a Barcellona â presso la Universitat de Barcelona, Facultat de Dret"})}),e.jsxs("div",{className:"mt-mission-row",children:[e.jsx(Te,{label:u("Data fine","End date"),children:e.jsx(Pe,{className:"input",value:t.date_end||"",onChange:N=>r("date_end",N.target.value)})}),e.jsx(Te,{label:u("Trasporto","Transport"),children:e.jsx(xe,{tone:"inherit",value:t.transport||"",onChange:N=>r("transport",N),ariaLabel:u("Trasporto","Transport"),options:[{value:"",label:"â"},{value:"bus",label:"Bus"},{value:"treno",label:u("Treno","Train")},{value:"aereo",label:u("Aereo","Plane")},{value:"proprio",label:u("Mezzo proprio","Own vehicle")},{value:"altro",label:u("Altro","Other")}]})}),e.jsx(Te,{label:u("Metodo di rimborso","Reimbursement method"),wide:!0,children:e.jsx(xe,{tone:"inherit",matchWidth:!1,value:t.reimbursement_method||"estero_documentato",onChange:N=>r("reimbursement_method",N),ariaLabel:u("Metodo di rimborso","Reimbursement method"),title:u("Determina il calcolo dellâanticipazione (art. 12 Regolamento). Ital
430ia: solo analitico. Estero: documentato o forfait.","Drives the advance computation (art. 12). Italy: itemised only. Abroad: documented or flat-rate."),options:[{value:"italia_analitico",label:u("Italia â analitico","Italy â itemised")},{value:"estero_documentato",label:u("Estero â documentato","Abroad â documented")},{value:"estero_forfait",label:u("Estero â forfait (alternativo)","Abroad â flat-rate (alternative)")}]})}),e.jsx(Te,{label:"UPB",wide:!0,children:e.jsx(se,{className:"input mono",value:t.upb||"",onChange:N=>r("upb",N.target.value),placeholder:"default: SIGIM.Prog.FIS3Climpact.Naglieri"})})]}),t.transport==="proprio"&&e.jsxs("div",{className:"mt-mat-block mt-subsection-dashed",children:[e.jsx("div",{className:"muted text-xs mt-subsection-dashed-title",children:u("Dettagli per lâautorizzazione al mezzo proprio","Details for the own-vehicle authorisation")}),e.jsx(Te,{label:u("Motivazione (perché è necessario il mezzo proprio, in italiano)","Justification (why the own vehicle is necessary, in Italian)"),children:e.jsx(se,{as:"textarea",className:"textarea",rows:3,value:t.own_vehicle_motivation||"",onChange:N=>r("own_vehicle_motivation",N.target.value),placeholder:u("es. il collegamento ferroviario richiede almeno due cambi e oltre 14 ore di percorrenza, incompatibile con la durata della missioneâ¦","e.g. the rail connection requires at least two changes and over 14 hours of travel, incompatible with the mission durationâ¦")})}),e.jsxs("div",{className:"mt-mission-row",children:[e.jsx(Te,{label:u("Veicolo (marca/modello)","Vehicle (make/model)"),wide:!0,children:e.jsx(se,{className:"input",value:t.own_vehicle_make_model||"",onChange:N=>r("own_vehicle_make_model",N.target.value),placeholder:u("es. Peugeot 2008","e.g. Peugeot 2008")})}),e.jsx(Te,{label:u("Targa","Number plate"),children:e.jsx(se,{className:"input mono",value:t.own_vehicle_plate||"",onChange:N=>r("own_vehicle_plate",N.target.value),placeholder:u("es. GS298HV","e.g. GS298HV")})})]}),e.jsxs("div",{className:"mt-mission-row",children:[e.jsx(Te,{label:u("N. patente","Driving licence no."),children:e.jsx(se,{className:"input mono",value:t.own_license_number||"",onChange:N=>r("own_license_number",N.target.value),placeholder:u("es. U157T1017K","e.g. U157T1017K")})}),e.jsx(Te,{label:u("Rilasciata da","Issued by"),wide:!0,children:e.jsx(se,{className:"input",value:t.own_license_issued_by||"",onChange:N=>r("own_license_issued_by",N.target.value),placeholder:u("es. Motorizzazione Civile di Roma","e.g. Motorizzazione Civile di Roma")})}),e.jsx(Te,{label:u("Il","On"),children:e.jsx(Pe,{className:"input",value:t.own_license_issued_date||"",onChange:N=>r("own_license_issued_date",N.target.value)})})]}),e.jsxs("div",{className:"mt-mission-row",children:[e.jsx(Te,{label:u("Compagnia assicurativa","Motor insurance company"),wide:!0,children:e.jsx(se,{className:"input",value:t.own_insurance_company||"",onChange:N=>r("own_insurance_company",N.target.value),placeholder:u("es. HDI","e.g. HDI")})}),e.jsx(Te,{label:u("N. polizza","Policy no."),children:e.jsx(se,{className:"input mono",value:t.own_insurance_policy_number||"",onChange:N=>r("own_insurance_policy_number",N.target.value),placeholder:u("es. 0493416845","e.g. 0493416845")})})]})]}),n&&e.jsxs("div",{className:"mt-banner-warn",children:[e.jsx(Gd,{size:14,className:"mt-banner-warn-icon"}),e.jsx("strong",{children:u("Missione importata dal budget","Budget-imported mission")}),e.jsx("span",{className:"mt-banner-warn-body",children:u('â carica qui le scansioni dei documenti; compaiono anche nella scheda "Documenti" del budget PI.','â upload the document scans here; they also appear in the "Documents" tab of the PI budget.')})]}),!n&&e.jsxs("label",{className:"mt-mission-extauth",children:[e.jsx("input",{type:"checkbox",checked:o,onChange:N=>r("external_auth",N.target.checked)}),e.jsxs("span",{children:[e.jsx("strong",{children:u("Autorizzazione ottenuta esternamente","Authorisation obtained externally")}),u(" â richiesta di autorizzazione e lettera di incarico gestite fuori dal sistema. Puoi comunque inserire i dati e generare anticipazione, fine missione, prospetto e ricevute. Le scansioni firmate caricale qui sotto."," â mission request and assignment letter handled outside the system. You can still enter the data and generate advance, end-of-mission, statement and receipts. Upload the signed scans below.")]})]}),(n||o&&Array.isArray(t.generic_documents)&&t.generic_documents.length>0)&&e.jsx(Fp,{mission:t,isAdmin:i,onUpdate:r,allowUpload:n})]}),!n&&e.jsxs("div",{className:"mt-mission-pane-col mt-mission-pane-col-docs",children:[!
430o&&e.jsxs(e.Fragment,{children:[e.jsx(dt,{n:2,stato:_[1],titolo:u("Genera richiesta e lettera di incarico","Generate the request and assignment letter"),sotto:u("I PDF si scaricano: vanno firmati e caricati al passo 3.","The PDFs download: sign them and upload them at step 3."),children:e.jsxs("div",{className:"mt-mission-actions-row",children:[e.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:async()=>{try{await um({mission:{title:t.description||(t.place?t.person?`Missione di ${t.person} a ${t.place}`:`Missione a ${t.place}`:""),destination:t.place,date_start:t.date,date_end:t.date_end,transport:t.transport,upb:t.upb,qualifica:t.qualifica||(a==null?void 0:a.qualifica)||""},member:{name:t.person||(a==null?void 0:a.name),uid:a==null?void 0:a.uid,role:a==null?void 0:a.role,qualifica:a==null?void 0:a.qualifica}})}catch(N){alert(u("Generazione PDF non riuscita: ","PDF generation failed: ")+(N.message||N))}},title:u("Genera la richiesta di autorizzazione missione (PDF) â da firmare e ricaricare","Generate the mission authorisation request (PDF) â to be signed and re-uploaded"),children:[e.jsx(st,{size:12})," ",u("Genera PDF richiesta","Generate request PDF")]}),e.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>h(!0),title:u("Genera (o modifica e rigenera) la lettera di incarico (PDF) â firmata dal PI e controfirmata dal Direttore","Generate (or edit and regenerate) the assignment letter (PDF) â signed by the PI and countersigned by the Director"),children:[e.jsx(st,{size:12})," ",t.assignment_letter_data?u("Modifica lettera di incarico","Edit assignment letter"):u("Genera PDF lettera di incarico","Generate assignment letter PDF")]}),t.transport==="proprio"&&e.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:async()=>{try{await pm({mission:{title:t.description||(t.place?`Missione a ${t.place}`:""),destination:t.place,description:t.description,own_vehicle_motivation:t.own_vehicle_motivation,own_vehicle_make_model:t.own_vehicle_make_model,own_vehicle_plate:t.own_vehicle_plate,own_license_number:t.own_license_number,own_license_issued_by:t.own_license_issued_by,own_license_issued_date:t.own_license_issued_date,own_insurance_company:t.own_insurance_company,own_insurance_policy_number:t.own_insurance_policy_number},member:{name:t.person||(a==null?void 0:a.name),role:a==null?void 0:a.role,qualifica:a==null?void 0:a.qualifica}})}catch(N){alert(u("Generazione PDF non riuscita: ","PDF generation failed: ")+(N.message||N))}},title:u("Genera la richiesta di autorizzazione allâuso del mezzo proprio (PDF) â da firmare e allegare alla richiesta di missione","Generate the own-vehicle use authorisation request (PDF) â to be signed and attached to the mission request"),children:[e.jsx(st,{size:12})," ",u("Genera autorizzazione mezzo proprio","Generate own-vehicle authorisation")]})]})}
430),e.jsx(dt,{n:3,stato:_[2],titolo:(kt(t),u("Firmale e caricale","Sign and upload them")),sotto:kt(t)?u("Una firma sola: la missione è del PI.","One signature only: this is the PIâs mission."):u("Appena ci sono tutte e due, il PI riceve la mail per controfirmare.","Once both are here, the PI gets the email to countersign."),children:e.jsx(Fo,{mission:t,member:a,isAdmin:i,onUpdate:r,chi:"persona"})}),!kt(t)&&e.jsx(dt,{n:4,stato:_[3],titolo:u("Controfirma del PI","PI countersignature"),sotto:u("Quando il PI ha caricato le due controfirme, arriva la mail per lâinvio.","Once the PI has uploaded both countersignatures, the email for sending arrives."),children:e.jsx(Fo,{mission:t,member:a,isAdmin:i,onUpdate:r,chi:"pi"})}),e.jsxs(dt,{n:kt(t)?4:5,stato:_[4],titolo:u("Invia alla Segreteria DJSGE","Send to the DJSGE Secretariat"),sotto:u("Si sblocca quando ci sono tutte le firme: prepara la mail con i PDF allegati.","It unlocks once every signature is in: it prepares the email with the PDFs attached."),children:[e.jsx(_i,{invio:t.invio_partenza}),e.jsxs("div",{className:"mt-mission-actions-row",children:[!t.authorized_pdf&&e.jsxs("button",{type:"button",className:"btn btn-primary btn-sm anim-shimmer",disabled:!v.pronto,onClick:async()=>{if(!v.pronto)return;r("segreteria_inviata_at",new Date().toISOString());const[N,L,B]=v.files;try{const P=S=>{if(!S)return"";try{return new Date(S).toLocaleDateString("it-IT",{day:"2-digit",month:"long",year:"numeric"})}catch{return S}},E=`Richiesta autorizzazione missione â ${t.place||""} â dal ${P(t.date)} al ${P(t.date_end)}`,Y=`Gentile Segreteria DJSGE, 431 432`+(B?`allego richiesta di autorizzazione missione, corrispondente bozza della lettera di incarico e richiesta di anticipazione come da oggetto. 433 434`:`allego richiesta di autorizzazione missione e corrispondente bozza della lettera di incarico come da oggetto. 435 436`)+`Cordiali saluti, 437${t.person||(a==null?void 0:a.name)||""}`;x({contesto:{tipo:"missione",id:t.id,titolo:`Missione a ${t.place||""}`},onEsito:S=>r("invio_partenza",S),to:"[email protected]",cc:"[email protected]",subject:E,body:Y,files:[{url:N.url,name:N.name||"Richiesta_missione.pdf"},{url:L.url,name:L.name||"Lettera_incarico.pdf"},...B?[{url:B.url,name:B.name||"Richiesta_anticipo.pdf"}]:[]]})}catch(P){alert(u("Preparazione dellâemail non riuscita: ","Preparation of the email failed: ")+(P.message||P))}},title:v.pronto?u(`Scarica i ${v.files.length} PDF firmati e apre lâemail pronta per la Segreteria DJSGE`,`Downloads the ${v.files.length} signed PDFs and opens the email ready for the DJSGE Secretariat`):Yi(v.mancano,w),children:[e.jsx(Ot,{size:12})," ",u("Invia alla Segreteria DJSGE","Send to DJSGE Secretariat")]}),!t.authorized_pdf&&!v.pronto&&e.jsx("span",{className:"mt-firme-manca",children:Yi(v.mancano,w)}),t.authorized_pdf&&e.jsx("span",{className:"mt-firme-manca",children:u("La missione è già autorizzata.","The mission is already authorised.")})]})]}),e.jsx(dt,{n:kt(t)?5:6,stato:_[5],titolo:u("Autorizzazione e lettera firmate dal Direttore","Authorisation and letter signed by the Director"),sotto:u("Le carica Vizzielli dal suo collegamento (scheda Documenti finali), oppure le carichi tu qui.","Vizzielli uploads them from his link (Final documents tab), or you upload them here."),children:e.jsxs("div",{className:"mt-mission-pdfs",children:[e.jsx(Dt,{title:u("Richiesta missione â firmata dal Direttore","Mission request â signed by the Director"),subtitle:u("versione finale restituita dalla Segreteria DJSGE","final version returned by the DJSGE Secretariat"),file:t.authorized_pdf,canUpload:!0,canRemove:i||((q=ye.currentUser)==null?void 0:q.uid)===t.created_by,onUpload:async N=>{var P;if(!t.team_uid)throw new Error("team_uid missing on the mission (id="+t.id+"). Delete it and create it again.");const L="team-missions/"+t.team_uid+"/"+t.id+"/authorized.pdf",B=await ze(L,N);if(await r("authorized_pdf",{url:B.url,path:B.path,name:N.name,size:N.size}),(P=t.request_pdf)!=null&&P.path){try{await de(t.request_pdf.path)}catch{}await r("request_pdf",null)}Xc({member:a,mission:t})},onRemove:async()=>{var N;(N=t.authorized_pdf)!=null&&N.path&&await de(t.authorized_pdf.path),await r("authorized_pdf",null)}}),e.jsx(Dt,{title:u("Lettera di incarico â firmata dal Direttore","Assignment letter â signed by the Director"),subtitle:u("versione finale restituita dalla Segreteria DJSGE","final version returned by the DJSGE Secretariat"),file:t.assignment_signed_pdf,canUpload:!0,canRemove:i||((R=ye.currentUser)==null?void 0:R.uid)===t.created_by,onUpload:async N=>{var P;if(!t.team_uid)throw new Error("team_uid missing on the mission (id="+t.id+"). Delete it and create it again.");const L="team-missions/"+t.team_uid+"/"+t.id+"/assignment-signed.pdf",B=await ze(L,N);if(await r("assignment_signed_pdf",{url:B.url,path:B.path,name:N.name,size:N.size}),(P=t.assignment_pdf)!=null&&P.path){try{await de(t.assignment_pdf.path)}catch{}await r("assignment_pdf",null)}},onRemove:async()=>{var N;(N=t.assignment_signed_pdf)!=null&&N.path&&await de(t.assignment_signed_pdf.path),await r("assignment_signed_pdf",null)}})]})})]}),o&&e.jsx(dt,{n:2,stato:t.authorized_pdf&&t.assignment_signed_pdf?"fatto":t.place&&t.date?"adesso":"dopo",titolo:u("Carica autorizzazione e lettera firmate","Upload the signed authorisation and letter"),sotto:u("Lâautorizzazione è stata ottenuta fuori dal sistema: qui vanno le scansioni firmate.","The authorisation was obtained outside the system: the signed scans go here."),children:e.jsxs("div",{className:"mt-mission-pdfs",children:[e.jsx(Dt,{title:u("Autorizzazione missione â firmata","Mission authorisation â signed"),subtitle:u("la scansione firmata ottenuta esternamente","the signed scan obtained externally"),file:t.authorized_pdf,canUpload:!0,canRemove:i||((O=ye.currentUser)==null?void 0:O.uid)===t.created_by,onUpload:async N=>{if(!t.team_uid)throw new Error("team_uid missing on the mission (id="+t.id+"). Delete it and create it again.");const L="team-missions/"+t.team_uid+"/"+t.id+"/authorized.pdf",B=await ze(L,N);await r("authorized_pdf",{url:B.url,path:B.path,name:N.name,size:N.size})},onRemove:async()=>{var N;(N=t.authorized_pdf)!=null&&N.path&&await de(t.authorized_pdf.path),await r("authorized_pdf",null)}}),e.jsx(Dt,{title:u("Lettera di incarico â firmata","Assignment letter â signed"),subtitle:u("la scansione firmata ottenuta esternamente","the signed scan obtained externally"),file:t.assignment_signed_pdf,canUpload:!0,canRemove:i||((k=ye.currentUser)==null?void 0:k.uid)===t.created_by,onUpload:async N=>{if(!t.team_uid)throw new Error("team_uid missing on the mission (id="+t.id+"). Delete it and create it again.");const L="team-missions/"+t.team_uid+"/"+t.id+"/assignment-signed.pdf",B=await ze(L,N);await r("assignment_signed_pdf",{url:B.url,path:B.path,name:N.name,size:N.size})},onRemove:async()=>{var N;(N=t.assignment_signed_pdf)!=null&&N.path&&await de(t.assignment_signed_pdf.path),await r("assignment_signed_pdf",null)}})]})})]})]}),!n&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mt-mission-pane",style:T("advance"),children:e.jsx(Rp,{mission:t,member:a,onUpdate:r})}),e.jsx("div",{className:"mt-mission-pane",style:T("prospetto"),children:e.jsxs(Mp,{mission:t,member:a,isAdmin:i,onUpdate:r,children:[e.jsxs(dt,{n:4,stato:j[3],titolo:u("Dichiarazione di fine missione","End-of-mission declaration"),sotto:u("Generala, firmala e caricala qui.","Generate it, sign it and upload it here."),children:[e.jsx("div",{className:"mt-mission-actions-row",children:e.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>c(!0),title:u("Genera (o modifica e rigenera) la dichiarazione di fine missione (PDF) â da firmare a missione conclusa","Generate (or edit and regenerate) the end-of-mission declaration (PDF) â to be signed once the mission is over"),children:[e.jsx(st,{size:12})," ",t.end_declaration_data?u("Modifica fine missione","Edit end-of-mission"):u("Genera PDF fine missione","Generate end-of-mission PDF")]})}),e.jsx(_o,{mission:t,member:a,isAdmin:i,onUpdate:r,parte:"dichiarazione"})]}),e.jsx(dt,{n:5,stato:j[4],titolo:u("Invio alla Segreteria DJSGE","Send to the DJSGE Secretariat"),sotto:u("Alla Segreteria si inviano tutti i documenti della missione: richiesta, prospetto, dichiarazione di fine missione, elenco delle spese e ricevute. Restano esclusi soltanto la lettera di incarico e lâanticipazione.","All the mission documents go to the Secretariat: request, statement, end-of-mission declaration, expense list and receipts. Only the assignment letter and the advance request are left out."),children:e.jsx(_o,{mission:t,member:a,isAdmin:i,onUpdate:r,parte:"invio"})})]})}),e.jsx("div",{className:"mt-mission-pane",style:T("finali"),children:e.jsx(om,{mission:t,member:a})})]}),e.jsx("div",{className:"mt-mission-foot",children:e.jsxs("button",{className:"btn btn-ghost btn-sm mt-row-delete",onClick:d,children:[e.jsx($e,{size:14})," ",u("Elimina missione","Delete mission")]})}),m&&e.jsx(ym,{mission:t,member:a,onClose:()=>c(!1),onPatch:N=>{for(const[L,B]of Object.entries(N))r(L,B)}}),g&&e.jsx(Dm,{mission:t,member:a,onClose:()=>h(!1),onPatch:N=>{for(const[L,B]of Object.entries(N))r(L,B)}}),p&&e.jsx(Da,{info:p,onClose:()=>x(null)})]})}function Rp({mission:t,member:a,onUpdate:i}){const{t:n}=X();return e.jsxs("div",{className:"mt-mission-collapsible is-open",children:[e.jsxs("div",{className:"mt-mission-slot-head",children:[e.jsx(st,{size:14}),e.jsx("span",{children:n("Richiesta anticipazione spese","Expense advance request")})]}),e.jsx(jp,{mission:t,member:a,onPatch:o=>{for(const[s,l]of Object.entries(o))i(s,l)},children:e.jsx(dt,{n:3,stato:Ga([!!t.advance_data,!!t.advance_pdf,!!t.advance_signed_pdf])[2],titolo:n("Firmala e caricala","Sign and upload it"),sotto:n("Parte nella stessa mail della richiesta di autorizzazione e della lettera dâincarico: finché non câè, lâinvio aspetta.","It goes in the same email as the authorisation request and the assignment letter: until it is here, sending waits."),children:e.jsx(Dt,{title:n("Richiesta di anticipazione â firmata","Advance request â signed"),subtitle:n("il PDF generato al passo 2, firmato","the PDF generated at step 2, signed"),file:t.advance_signed_pdf,canUpload:!0,canRemove:!0,emptyText:n("Non ancora caricata.","Not uploaded yet."),onUpload:async o=>{if(!t.team_uid)throw new Error("team_uid missing on the mission (id="+t.id+").");const s=await ze(`team-missions/${t.team_uid}/${t.id}/anticipazione_firmata.pdf`,o);await i("advance_signed_pdf",{url:s.url,path:s.path,name:o.name,size:o.size})},onRemove:async()=>{var o;(o=t.advance_signed_pdf)!=null&&o.path&&await de(t.advance_signed_pdf.path),await i("advance_signed_pdf",null)}})})})]})}
437function Mp({mission:t,member:a,isAdmin:i,onUpdate:n,children:o}){var l;const{t:s}=X();return e.jsxs("div",{className:"mt-mission-collapsible is-open",children:[e.jsxs("div",{className:"mt-mission-slot-head",children:[e.jsx(wr,{size:14}),e.jsx("span",{children:s("Prospetto riepilogativo spese","Expense summary statement")}),((l=t.prospetto_signed_pdf)==null?void 0:l.url)&&e.jsxs("span",{className:"muted text-xs",children:["· ",s("firmato","signed")]})]}),e.jsx(rp,{mission:t,member:a,isAdmin:i,onPatch:r=>{for(const[d,m]of Object.entries(r))return n(d,m)},children:o})]})}function Fp({mission:t,isAdmin:a,onUpdate:i,allowUpload:n=!0}){const{t:o}=X(),s=f.useRef(null),[l,r]=f.useState(!1),[d,m]=f.useState(!1),c=Array.isArray(t.generic_documents)?t.generic_documents:[];async function g(u){if(!(!u||!u.length)){r(!0);try{const w=[...c];for(const v of Array.from(u)){const j=v.name.replace(/[^A-Za-z0-9._-]+/g,"_").slice(0,80)||"documento",_=Date.now().toString(36)+"_"+j,C=`mission-imports/${t.id}/${_}`,y=await ze(C,v),z={url:y.url,path:y.path,name:v.name,size:v.size};w.push(z);try{await yp({missionId:t.id,budgetRef:t.budget_ref,storagePath:y.path,fileName:v.name,fileUrl:y.url})}catch(T){console.warn("[mission-mirror] doc mirror failed:",(T==null?void 0:T.message)||T)}}await i("generic_documents",w)}catch(w){alert(o("Caricamento non riuscito: ","Upload failed: ")+(w.message||w))}finally{r(!1)}}}async function h(u){if(confirm(o('Rimuovere il documento "','Remove the document "')+u.name+'"?')){r(!0);try{if(u.path){try{await de(u.path)}catch{}try{await _p({missionId:t.id,budgetRef:t.budget_ref,storagePath:u.path})}catch(v){console.warn("[mission-mirror] doc unmirror failed:",(v==null?void 0:v.message)||v)}}const w=c.filter(v=>u.path?v.path!==u.path:v.url!==u.url);await i("generic_documents",w)}finally{r(!1)}}}function p(u){!a||!n||l||(u.preventDefault(),u.stopPropagation(),m(!0))}function x(u){u.preventDefault(),u.stopPropagation(),m(!1)}async function b(u){var w;!a||!n||l||(u.preventDefault(),u.stopPropagation(),m(!1),await g((w=u.dataTransfer)==null?void 0:w.files))}return e.jsxs("div",{className:"mt-pdf-slot has-file",style:{marginTop:10},children:[e.jsx("div",{className:"mt-pdf-head",children:e.jsxs("div",{children:[e.jsx("strong",{children:n?o("Documenti generici","General documents"):o("Documenti generici (archiviati)","General documents (archived)")}),e.jsx("div",{className:"muted text-xs",children:n?o('Ricevute, contratti firmati, scansioni cartacee. Visibili anche nella scheda "Documenti" del budget.','Receipts, signed contracts, paper scans. Also visible in the "Documents" tab of the budget.'):o("Documenti caricati in precedenza â restano nellâarchivio e nel budget. Per le nuove missioni ad autorizzazione esterna usa gli slot dei documenti firmati qui sopra.","Previously uploaded documents â kept in the archive and the budget. For new external-auth missions use the signed-document slots above.")})]})}),c.length>0&&e.jsx("ul",{className:"mt-doc-list",children:c.map((u,w)=>e.jsxs("li",{className:"mt-doc-list-row",children:[e.jsxs("a",{href:Je(u.url),target:"_blank",rel:"noreferrer",children:[e.jsx(qt,{size:13})," ",u.name||o("allegato","attachment")]}),e.jsx("span",{className:"muted text-xs",children:u.size?Math.round(u.size/1024)+" KB":""}),a&&e.jsxs("button",{type:"button",className:"mt-pill mt-pill-sm is-danger",disabled:l,onClick:()=>h(u),children:[e.jsx($e,{size:12})," ",o("Rimuovi","Remove")]})]},u.path||u.url||w))}),a&&n?e.jsxs("div",{className:"mt-pdf-drop"+(d?" is-drag-over":""),onClick:()=>{var u;return!l&&((u=s.current)==null?void 0:u.click())},onDragOver:p,onDragEnter:p,onDragLeave:x,onDrop:b,role:"button",tabIndex:0,onKeyDown:u=>{var w;(u.key==="Enter"||u.key===" ")&&(u.preventDefault(),(w=s.current)==null||w.click())},"aria-disabled":l,"data-busy":l?"1":void 0,children:[e.jsx(qa,{size:18}),e.jsx("span",{className:"mt-pdf-drop-hl",children:l?o("Caricamentoâ¦","Uploadingâ¦"):o("Trascina qui i documenti o clicca per scegliere","Drag documents here or click to choose")}),e.jsx("span",{className:"mt-pdf-drop-hint",children:o("PDF, immagini, qualsiasi formato â max 25 MB per file","PDF, images, any format â max 25 MB per file")})]}):c.length===0&&e.jsx("div",{className:"mt-pdf-empty",children:o("Nessun documento ancora caricato dal PI.","No documents uploaded by the PI yet.")}
437),e.jsx("input",{ref:s,type:"file",multiple:!0,className:"mt-hidden-input",onChange:u=>{g(u.target.files),u.target.value=""}})]})}function Te({label:t,children:a,wide:i,align:n}){return e.jsxs("div",{className:"mt-field"+(i?" is-wide":"")+(n==="right"?" mt-field-right":""),children:[e.jsx("label",{className:"label",children:t}),a]})}function Fo({mission:t,member:a,isAdmin:i,onUpdate:n,chi:o=null}){var x;const{t:s}=X(),l=kt(t),r=(t.person||(a==null?void 0:a.name)||"").split(" ")[0]||s("la persona","the traveller"),d=((x=ye.currentUser)==null?void 0:x.uid)===t.team_uid;async function m(b,u){if(!t.team_uid)throw new Error("team_uid missing on the mission (id="+t.id+"). Delete it and create it again.");const w=await ze(`team-missions/${t.team_uid}/${t.id}/${b.replace(/_pdf$/,"")}.pdf`,u),v={url:w.url,path:w.path,name:u.name,size:u.size};await n(b,v);const j={...t,[b]:v};l||(b.endsWith("_signed_person_pdf")&&cs(j)&&!cs(t)&&Qc({member:a,mission:j,file:u}),b.endsWith("_signed_pi_pdf")&&ds(j)&&!ds(t)&&ed({member:a,mission:j}))}async function c(b){var u;(u=t[b])!=null&&u.path&&await de(t[b].path),await n(b,null)}const g=[{key:"request",it:"Richiesta missione",en:"Mission request"},{key:"assignment",it:"Lettera di incarico",en:"Assignment letter"}],h=o!=="pi",p=o!=="persona"&&!l;return e.jsx("div",{className:o?"mt-firme-riga":"mt-firme-tutte",children:g.map(b=>{const u=`${b.key}_signed_person_pdf`,w=`${b.key}_signed_pi_pdf`,v=t[`${b.key}_pdf`];return e.jsxs("div",{className:o?"mt-firme-doc":"mt-firme-coppia",children:[h&&(v==null?void 0:v.url)&&e.jsxs("a",{className:"mt-firme-bozza",href:Je(v.url),target:"_blank",rel:"noreferrer",children:[e.jsx(qt,{size:13})," ",Ji(t)?s(`${b.it}, caricata col flusso precedente: ${v.name||"PDF"}`,`${b.en}, uploaded with the previous flow: ${v.name||"PDF"}`):s(`${b.it} generata dal sistema, da firmare: ${v.name||"PDF"}`,`${b.en} generated by the system, to be signed: ${v.name||"PDF"}`)]}),h&&e.jsx(Dt,{title:l?s(`${b.it} â firmata`,`${b.en} â signed`):s(`${b.it} â firmata da ${r}`,`${b.en} â signed by ${r}`),subtitle:s("il PDF generato al passo 2, firmato","the PDF generated at step 2, signed"),file:t[u],canUpload:d||i,canRemove:d||i,emptyText:s(`Non ancora caricata da ${r}.`,`Not yet uploaded by ${r}.`),onUpload:j=>m(u,j),onRemove:()=>c(u)}),p&&e.jsx(Dt,{title:s(`${b.it} â controfirmata dal PI`,`${b.en} â countersigned by the PI`),subtitle:t[u]?s("il PI scarica quella firmata, controfirma e ricarica qui","the PI downloads the signed one, countersigns and uploads it here"):s("si firma dopo la firma della persona","signed after the traveller has signed"),file:t[w],c
437anUpload:i&&!!t[u],canRemove:i,locked:!i,emptyText:t[u]?s("In attesa della firma del PI.","Waiting for the PIâs signature."):s("Prima serve la firma della persona.","The traveller signs first."),onUpload:j=>m(w,j),onRemove:()=>c(w)})]},b.key)})})}const Lp="image/jpeg,image/png,image/webp,image/heic,image/heif,application/pdf";function di(t){const a=String(t||"").slice(0,10);return/^\d{4}-\d{2}-\d{2}$/.test(a)?Math.floor(Date.parse(a+"T00:00:00Z")/864e5):null}function yl(t,a){const i=di(t.date),n=di(t.date_end)??i;return i==null||n==null?!1:i<=a&&a<=n}function Op(t,a){const i=di(a)??Math.floor(Date.now()/864e5);return[...t||[]].sort((o,s)=>n(o)-n(s));function n(o){const s=di(o.date),l=di(o.date_end)??s;if(l==null)return 1e6;if(yl(o,i))return-1e5+(l-i);const r=i-l;return r>=0?r:1e5+((s??l)-i)}}function Lo(t,a){return t.place||a("Missione senza destinazione","Mission with no destination")}function Oo(t,a){const i=String(t.date||"").slice(0,10);return i?bl(i,String(t.date_end||"").slice(0,10),a):""}const qp=75*1024*1024;function Up({me:t,onExit:a}){const{t:i,lang:n}=X(),[o,s]=f.useState(null),[l,r]=f.useState([]),[d,m]=f.useState(null),[c,g]=f.useState(null),[h,p]=f.useState(0),[x,b]=f.useState(null),u=f.useRef(null),w=f.useRef(null),v=(t==null?void 0:t.uid)||null,j=f.useRef(i);j.current=i,f.useEffect(()=>{if(!v)return;const O=ft(Ie(te,"team_missions"),Bt("team_uid","==",v));return Ye(O,k=>{s(k.docs.map(N=>({id:N.id,...N.data()})))},k=>{console.error("[drop] missions",k),b(j.current("Elenco missioni non raggiungibile.","Could not load your missions.")),s([])})},[v]),f.useEffect(()=>{if(v)return Wm(v,r)},[v]);const[_,C]=f.useState([]),y=(o||[]).find(O=>O.id===d)||null,z=(y==null?void 0:y.team_uid)||null;f.useEffect(()=>{if(!d||!z){C([]);return}return ol({id:d,team_uid:z},C)},[d,z]);const T=new Date().toISOString().slice(0,10),I=Math.floor(Date.parse(T+"T00:00:00Z")/864e5),D=f.useMemo(()=>Op(o||[],T),[o,T]),$=D.find(O=>O.id===d)||null,q=l.length;async function R(O){const k=[...O||[]].filter(L=>L&&(String(L.type).startsWith("image/")||L.type==="application/pdf"));if(!k.length||!$)return;if(!$.team_uid){b(i("Missione senza proprietario â aprila nel portale e ricreala.","Mission has no owner â open it in the portal and recreate it."));return}b(null);let N=0;for(let L=0;L<k.length;L++){g({total:k.length,done:L});const B=k[L];if(B.size>=qp){const P=(B.size/1048576).toFixed(0);b(i(`«${B.name}» pesa ${P} MB e il limite e' 75 MB. Anche per un RAW e' molto: scegli la stessa foto in JPEG, oppure spegni ProRAW nelle impostazioni Fotocamera.`,`"${B.name}" is ${P} MB and the limit is 75 MB. That is large even for a RAW: pick the same photo as a JPEG, or turn ProRAW off in Camera settings.`));continue}try{const P=(String(B.name).split(".").pop()||"jpg").toLowerCase().replace(/[^a-z0-9]/g,"").slice(0,5)||"jpg",E=`team-missions/${$.team_uid}/${$.id}/receipts/${Ts()}.${P}`,Y=await ze(E,B);await fs({mission:$,member:t,file:{url:Y.url,path:Y.path,name:B.name,size:B.size,mime:B.type}}),N+=1}catch(P){console.error("[drop] upload failed",P),b(i("Caricamento non riuscito: ","Upload failed: ")+((P==null?void 0:P.message)||P))}}g(null),N&&p(L=>L+N)}return $?e.jsxs(e.Fragment,{children:[e.jsx("section",{className:"mt-band mt-band-dark",children:e.jsxs("div",{className:"mt-wrap",children:[e.jsxs("button",{type:"button",className:"btn btn-ghost btn-sm mt-back",onClick:()=>{m(null),p(0)},children:[e.jsx(dn,{size:14})," ",i("Cambia missione","Change mission")]}),e.jsx("div",{className:"mt-section-head",style:{alignItems:"flex-start"},children:e.jsxs("div",{children:[e.jsx("p",{className:"mt-eyebrow",children:i("Research Team","Research Team")}),e.jsx("h1",{className:"mt-section-title",children:Lo($,i)}),e.jsx("p",{className:"mt-section-sub",children:Oo($,n)})]})})]})}),e.jsx("section",{className:"mt-band mt-band-tight",children:e.jsx("div",{className:"mt-wrap",children:e.jsxs("div",{className:"rdrop-content",children:[x&&e.jsxs("p",{className:"rdrop-error",children:[e.jsx(at,{size:15})," ",x]}),e.jsxs("div",{className:"rdrop-actions",children:[e.jsx("button",{type:"button",className:"rdrop-shoot",disabled:!!c,onClick:()=>{var O;return(O=u.current)==null?void 0:O.click()},children:c?e.jsxs(e.Fragment,{children:[e.jsx(me,{size:22,className:"rdrop-spin"})," ",i("Caricoâ¦","Uploadingâ¦")]}):e.jsxs(e.Fragment,{children:[e.jsx(xc,{size:22})," ",i("Fotografa uno scontrino","Photograph a receipt")]})}),e.jsxs("button",{type:"button",className:"rdrop-secondary",disabled:!!c,onClick:()=>{var O;return(O=w.current)==null?void 0:O.click()},children:[e.jsx(bc,{size:16})," ",i("Scegli dalle foto o un PDF","Pick from photos or a PDF")]})]}),c&&e.jsxs("p",{className:"rdrop-progress",children:[i("Documento ","Document "),c.done+1," / ",c.total]}),h>0&&!c&&e.jsxs("p",{className:"rdrop-ok",children:[e.jsx(ke,{size:16}),h===1?i("1 ricevuta al sicuro.","1 receipt is safe."):`${h} ${i("ricevute al sicuro.","receipts are safe.")}`]}),e.jsx(ul,{items:_,onRileggi:O=>rl(O.id),onScarta:O=>{var k;(k=O.file)!=null&&k.path&&de(O.file.path).catch(()=>{}),ll(O.id).catch(N=>console.error("[drop] dismiss",N))},onApri:O=>{O!=null&&O.url&&Er(O.url,O.name||"Receipt",O.mime||(Dd(O)?"pdf":null))}}),e.jsxs("p",{className:"rdrop-hint",children:[e.jsx(on,{size:13}),i("Ogni foto viene raddrizzata e letta da sola: tipo, data e importo finiscono nella missione senza fare niente.","Each photo is straightened and read on its own: type, date and amount land in the mission with nothing to do.")]}),e.jsx("input",{ref:u,type:"file",accept:"image/*",capture:"environment",multiple:!0,hidden:!0,onChange:O=>{R(O.target.files),O.target.value=""}}),e.jsx("input",{ref:w,type:"file",accept:Lp,multiple:!0,hidden:!0,onChange:O=>{R(O.target.files),O.target.value=""}})]})})})]}):e.jsxs(e.Fragment,{children:[e.jsx("section",{className:"mt-band mt-band-dark",children:e.jsx("div",{className:"mt-wrap",children:e.jsx("div",{className:"mt-section-head",style:{alignItems:"flex-start"},children:e.jsxs("div",{children:[e.jsx("p",{className:"mt-eyebrow",children:i("Research Team","Research Team")}),e.jsx("h1",{className:"mt-section-title",children:i("Svuotarsi le tasche","Empty your pockets")}),e.jsx("p",{className:"mt-section-sub",children:i("Per quale missione?","Which mission?")})]})})})}),e.jsx("section",{className:"mt-band mt-band-tight",children:e.jsx("div",{className:"mt-wrap",children:e.jsxs("div",{className:"rdrop-content",children:[x&&e.jsxs("p",{className:"rdrop-error",children:[e.jsx(at,{size:15})," ",x]}),o===null&&e.jsxs("p",{className:"rdrop-loading",children:[e.jsx(me,{size:16,className:"rdrop-spin"})," ",i("Carico le tue missioniâ¦","Loading your missionsâ¦")]}),o!==null&&D.length===0&&e.jsxs("div",{className:"rdrop-empty",children:[e.jsx("p",{children:i("Non hai ancora missioni.","You have no missions yet.")}),e.jsx("p",{className:"rdrop-empty-sub",children:i("Creane una nel portale, poi torna qui.","Create one in the portal, then come back here.")}),a&&e.jsx("button",{type:"button",className:"rdrop-secondary",onClick:a,children:i("Vai alle missioni","Go to missions")})]}),D.length>0&&e.jsx("ul",{className:"rdrop-list",children:D.map((O,k)=>{const N=l.filter(L=>L.mission_id===O.id).length;return e.jsx("li",{children:e.jsxs("button",{type:"button",className:`rdrop-pick${k===0?" is-first":""}`,onClick:()=>m(O.id),children:[e.jsxs("span",{className:"rdrop-pick-main",children:[e.jsxs("span",{className:"rdrop-pick-place",children:[e.jsx(pi,{size:14})," ",Lo(O,i)]}),e.jsxs("span",{className:"rdrop-pick-meta",children:[Oo(O,n)||i("senza date","no dates"),N>0&&`, ${N} ${i("in attesa","waiting")}`]})]}),k===0&&e.jsx("span",{className:"rdrop-badge",children:yl(O,I)?i("in corso","ongoing"):i("lâultima","latest")})]})},O.id)})}),q>0&&e.jsx("p",{className:"rdrop-foot",children:q===1?i("1 ricevuta in attesa di essere registrata.","1 receipt waiting to be filed."):`${q} ${i("ricevute in attesa di essere registrate.","receipts waiting to be filed.")}`})]})})})]})}const Bp="/timesheet-template.xlsx",Gp=["GENNAIO","FEBBRAIO","MARZO","APRILE","MAGGIO","GIUGNO","LUGLIO","AGOSTO","SETTEMBRE","OTTOBRE","NOVEMBRE","DICEMBRE"];function Wp(t){let a="";for(;t>0;){const i=(t-1)%26;a=String.fromCharCode(65+i)+a,t=Math.floor((t-1)/26)}return a}const Vp=6,Gn=Array.from({length:31},(t,a)=>
437Wp(Vp+a)),qo=t=>String(t??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'");function zt(t,a,i){const n=new RegExp(`<c r="${a}"([^>]*?)(/>|>[\\s\\S]*?</c>)`,"g");let o=!1;const s=t.replace(n,(l,r)=>{o=!0;const d=r.replace(/\s+t="[^"]*"/g,"").replace(/\s+t='[^']*'/g,"");return i==null||i===""||typeof i=="number"&&isNaN(i)?`<c r="${a}"${d}/>`:typeof i=="number"?`<c r="${a}"${d}><v>${i}</v></c>`:`<c r="${a}"${d} t="inlineStr"><is><t xml:space="preserve">${qo(i)}</t></is></c>`});if(!o){const l=a.match(/^([A-Z]+)(\d+)$/);if(l){const r=l[2],d=i==null||i===""?`<c r="${a}"/>`:typeof i=="number"?`<c r="${a}"><v>${i}</v></c>`:`<c r="${a}" t="inlineStr"><is><t xml:space="preserve">${qo(i)}</t></is></c>`,m=new RegExp(`(<row r="${r}"[^>]*>)`);return t.replace(m,c=>c+d)}}return s}function $t(t){const a=parseFloat(String(t??"").replace(",","."));return Number.isFinite(a)?a:0}function _l(t){return Math.round((Number(t)+Number.EPSILON)*100)/100}function Ct(t,a,i){const n=_l(i),o=new RegExp(`(<c r="${a}"[^>]*>)([\\s\\S]*?)(</c>)`);return t.replace(o,(s,l,r)=>{const d=r.match(/<f\b[^>]*\/>|<f\b[^>]*>[\s\S]*?<\/f>/);return d?`${l}${d[0]}<v>${n}</v></c>`:s})}function As(t,a){return new Date(t,a,0).getDate()}function Hp(t){const a=[[1,1],[1,6],[4,25],[5,1],[6,2],[8,15],[11,1],[12,8],[12,25],[12,26]],i=Kp(t),n=new Date(i.getFullYear(),i.getMonth(),i.getDate()+1),o=new Set(a.map(([s,l])=>`${s}-${l}`));return o.add(`${n.getMonth()+1}-${n.getDate()}`),o}function Kp(t){const a=t%19,i=Math.floor(t/100),n=t%100,o=Math.floor(i/4),s=i%4,l=Math.floor((i+8)/25),r=Math.floor((i-l+1)/3),d=(19*a+i-o-r+15)%30,m=Math.floor(n/4),c=n%4,g=(32+2*s+2*m-d-c)%7,h=Math.floor((a+11*d+22*g)/451),p=Math.floor((d+g-7*h+114)/31),x=(d+g-7*h+114)%31+1;return new Date(t,p-1,x)}function Wn(t,a,i){return new Date(t,a-1,i).getDay()===0}function Vn(t,a,i,n){return n.has(`${a}-${i}`)}async function Uo(t){var R,O,k,N,L,B,P,E,Y,S,W;const a=(await Sa(()=>Ae(()=>import("./jszip.min-DN5-FNYE.js").then(M=>M.j),__vite__mapDeps([5,4])))).default,i=await fetch(Bp);if(!i.ok)throw new Error("Template timesheet non caricabile");const n=await i.arrayBuffer(),o=await a.loadAsync(n),s="xl/worksheets/sheet1.xml";let l=await o.file(s).async("string");try{const M="xl/workbook.xml";let J=await o.file(M).async("string");J=J.replace(/(<definedName name="_xlnm\.Print_Area"[^>]*>)[^<]*(<\/definedName>)/,(V,K,Q)=>`${K}Timesheet!$D$3:$AK$40${Q}`),o.file(M,J)}catch{}try{const M="xl/drawings/drawing1.xml",J=o.file(M);if(J){let V=await J.async("string");V=V.replace('<xdr:twoCellAnchor editAs="oneCell">',"<xdr:oneCellAnchor>"),V=V.replace(/<xdr:to>[\s\S]*?<\/xdr:to>/,'<xdr:ext cx="17934398" cy="1795481"/>'),V=V.replace("</xdr:twoCellAnchor>","</xdr:oneCellAnchor>"),V=V.replace('<a:ext cx="17934398" cy="1856902"/>','<a:ext cx="17934398" cy="1795481"/>'),o.file(M,V)}}catch{}l=zt(l,"L15",t.figuraProfessionale||""),l=zt(l,"L16",t.nome||""),l=zt(l,"AC16",t.cognome||""),l=zt(l,"L17",t.codiceFiscale||"");const r=Gp[(t.month||1)-1]||"";l=zt(l,"Z9",r),l=zt(l,"AK9",Number(t.year)||"");const d=t.otherCups||[];[["E26",26],["E27",27],["E28",28]].forEach(([M,J],V)=>{const K=(d[V]||"").trim();l=zt(l,M,K?`CUP: ${K}`:"")}),(R=t.otherProjectLabel)!=null&&R.trim()&&(l=zt(l,"D29",`Attività svolte su altri progetti (${t.otherProjectLabel.trim()})`));const c=As(Number(t.year),Number(t.month)),g=(M,J)=>{for(let V=0;V<c;V++){const K=$t(J==null?void 0:J[V]),Q=Gn[V]+M;l=zt(l,Q,K!==0?_l(K):"")}for(let V=c;V<31;V++){const K=Gn[V]+M;l=zt(l,K,"")}},h=((O=t.hours)==null?void 0:O.climpact)||[],p=((N=(k=t.hours)==null?void 0:k.mur)==null?void 0:N[0])||[],x=((B=(L=t.hours)==null?void 0:L.mur)==null?void 0:B[1])||[],b=((E=(P=t.hours)==null?void 0:P.mur)==null?void 0:E[2])||[],u=((Y=t.hours)==null?void 0:Y.other)||[],w=((S=t.hours)==null?void 0:S.ordinary)||[],v=((W=t.hours)==null?void 0:W.altro)||[];g(24,h),g(26,p),g(27,x),g(28,b),g(29,u),g(30,w),g(31,v);const j=M=>M.reduce((J,V)=>J+$t(V),0),_=j(h),C=j(p),y=j(x),z=j(b),T=j(u),I=j(w),D=j(v),$=_+C+y+z+T+I+D;l=Ct(l,"AK24",_),l=Ct(l,"AC17",_),l=Ct(l,"AK26",C),l=Ct(l,"AK27",y),l=Ct(l,"AK28",z),l=Ct(l,"AK29",T),l=Ct(l,"AK30",I),l=Ct(l,"AK31",D),l=Ct(l,"AK32",$);for(let M=0;M<c;M++){const J=$t(h[M])+$t(p[M])+$t(x[M])+$t(b[M])+$t(u[M])+$t(w[M])+$t(v[M]);l=Ct(l,Gn[M]+"32",J)}l=l.replace(/<pageSetup\b[^>]*\/>/,'<pageSetup paperSize="9" fitToWidth="1" fitToHeight="0" orientation="landscape" r:id="rId1"/>'),l=l.replace(/<pageMargins\b[^>]*\/>/,'<printOptions horizontalCentered="1"/><pageMargins left="0.39" right="0.39" top="0.5" bottom="0.5" header="0.2" footer="0.2"/>'),o.file(s,l);const q=await o.generateAsync({type:"uint8array"});return new Blob([q],{type:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"})}async function Jp(t,a="timesheet.xlsx"){var r,d;const i=(r=ye)==null?void 0:r.currentUser;if(!i)throw new Error("xlsx2pdf: utente non autenticato");const n=await i.getIdToken(),o=new FormData;o.append("file",t,a);const s=await fetch(`${Wd}/tools/xlsx2pdf`,{method:"POST",body:o,headers:{Authorization:`Bearer ${n}`}});if(!s.ok){let m="";try{m=((d=await s.json())==null?void 0:d.detail)||""}catch{}throw new Error(`Conversione PDF fallita (${s.status})${m?": "+m:""}`)}const l=await s.arrayBuffer();try{const{PDFDocument:m}=await Sa(()=>Ae(()=>import("./index-CeY7slSg.js"),__vite__mapDeps([15,4]))),c=await m.load(l);if(c.getPageCount()>1){const g=await m.create(),[h]=await g.copyPages(c,[0]);g.addPage(h);const p=await g.save();return new Blob([p],{type:"application/pdf"})}}catch(m){console.warn("[xlsx2pdf] keep-first-page failed; returning full PDF",(m==null?void 0:m.message)||m)}return new Blob([l],{type:"application/pdf"})}function Ta(t,a){return t+"__"+a}function Nl(t){var o,s,l;const a=r=>parseFloat(String(r??"").replace(",","."))||0,i=r=>(r||[]).reduce((d,m)=>d+a(m),0),n=(t==null?void 0:t.hours)||{};return i(n.climpact)+i((o=n.mur)==null?void 0:o[0])+i((s=n.mur)==null?void 0:s[1])+i((l=n.mur)==null?void 0:l[2])+i(n.other)+i(n.ordinary)+i(n.altro)}function wl(t){var i,n,o;if(!t)return t;const a=t.hours||{};return{...t,hours:{climpact:a.climpact||[],mur:{0:((i=a.mur)==null?void 0:i[0])||[],
4371:((n=a.mur)==null?void 0:n[1])||[],2:((o=a.mur)==null?void 0:o[2])||[]},other:a.other||[],ordinary:a.ordinary||[],altro:a.altro||[]}}}function Bo(t){if(!t)return t;const a=t.hours||{},i=a.mur||{};return{...t,hours:{climpact:a.climpact||[],mur:[i[0]||[],i[1]||[],i[2]||[]],other:a.other||[],ordinary:a.ordinary||[],altro:a.altro||[]}}}async function Yp({member:t,year_month:a,formData:i}){var s;const n=t==null?void 0:t.uid;if(!n||!a)throw new Error("uid + year_month richiesti");const o=Nl(i);return await _e(oe(te,"team_timesheets",Ta(n,a)),{team_uid:n,year_month:a,review:{state:"pending",data:wl(i),total_hours:o,submitted_at:ie(),submitted_by:((s=ye.currentUser)==null?void 0:s.uid)||null,reviewed_at:null,reviewed_by:null,pi_note:null}},{merge:!0}),td({member:t,year_month:a,total_hours:o}).catch(()=>{}),{total:o}}async function Go({member:t,year_month:a,formData:i}){const n=t==null?void 0:t.uid;if(!n||!a||!i)return null;const o=Nl(i);return await _e(oe(te,"team_timesheets",Ta(n,a)),{team_uid:n,year_month:a,review:{data:wl(i),total_hours:o,draft_saved_at:ie()}},{merge:!0}),{total:o}}async function Zp({entryId:t,member:a,year_month:i,fromName:n}){var s;const o=t||Ta(a==null?void 0:a.uid,i);await _e(oe(te,"team_timesheets",o),{review:{state:"approved",reviewed_at:ie(),reviewed_by:((s=ye.currentUser)==null?void 0:s.uid)||null,pi_note:null}},{merge:!0}),nd({member:a,year_month:i,fromName:n||"PI"}).catch(()=>{})}async function Xp({entryId:t,member:a,year_month:i,note:n,fromName:o}){var l;const s=t||Ta(a==null?void 0:a.uid,i);if(!n||!n.trim())throw new Error("Una nota è obbligatoria per richiedere modifiche.");await _e(oe(te,"team_timesheets",s),{review:{state:"changes_requested",reviewed_at:ie(),reviewed_by:((l=ye.currentUser)==null?void 0:l.uid)||null,pi_note:n.trim()}},{merge:!0}),id({member:a,year_month:i,note:n.trim(),fromName:o||"PI"}).catch(()=>{})}async function Qp({entryId:t,member:a,year_month:i,reason:n}){var s;const o=t||Ta(a==null?void 0:a.uid,i);await _e(oe(te,"team_timesheets",o),{review:{state:"unlock_requested",unlock_requested_at:ie(),unlock_requested_by:((s=ye.currentUser)==null?void 0:s.uid)||null,unlock_reason:(n||"").trim()||null,unlock_decided_at:null,unlock_decided_by:null,unlock_denied_note:null}},{merge:!0}),ad({member:a,year_month:i,reason:(n||"").trim()||null}).catch(()=>{})}async function eh({entryId:t,member:a,year_month:i,fromName:n}){var s;const o=t||Ta(a==null?void 0:a.uid,i);await _e(oe(te,"team_timesheets",o),{review:{state:null,unlock_decided_at:ie(),unlock_decided_by:((s=ye.currentUser)==null?void 0:s.uid)||null,unlock_denied_note:null}},{merge:!0}),od({member:a,year_month:i,fromName:n||"PI"}).catch(()=>{})}async function th({entryId:t,member:a,year_month:i,note:n,fromName:o}){var l;const s=t||Ta(a==null?void 0:a.uid,i);await _e(oe(te,"team_timesheets",s),{review:{state:"approved",unlock_decided_at:ie(),unlock_decided_by:((l=ye.currentUser)==null?void 0:l.uid)||null,unlock_denied_note:(n||"").trim()||null}},{merge:!0}),sd({member:a,year_month:i,note:(n||"").trim()||null,fromName:o||"PI"}).catch(()=>{})}function ah(){const[t,a]=f.useState(()=>typeof window<"u"&&window.innerWidth<=900);return f.useEffect(()=>{var o;const i=window.matchMedia("(max-width: 900px)"),n=()=>a(i.matches);return n(),(o=i.addEventListener)==null||o.call(i,"change",n),()=>{var s;return(s=i.removeEventListener)==null?void 0:s.call(i,"change",n)}},[]),t}const ih=["Gennaio","Febbraio","Marzo","Aprile","Maggio","Giugno","Luglio","Agosto","Settembre","Ottobre","Novembre","Dicembre"],nh=["January","February","March","April","May","June","July","August","September","October","November","December"];function sh(t){return[{key:"climpact",label:"Climpact",color:"var(--accent)",helper:t("Ore svolte sul progetto Climpact (rigo principale)","Hours on the Climpact project (main row)")},{key:"mur0",label:t("Altro MUR (CUP 1)","Other MUR (CUP 1)"),color:"#7c3aed"},{key:"mur1",label:t("Altro MUR (CUP 2)","Other MUR (CUP 2)"),color:"#7c3aed"},{key:"mur2",label:t("Altro MUR (CUP 3)","Other MUR (CUP 3)"),color:"#7c3aed"},{key:"other",label:t("Altri progetti","Other projects"),color:"#0891b2",helper:t("es. Erasmus, JM Module, contratti privati","e.g. Erasmus, JM Module, private contracts")},{key:"ordinary",label:t("Attività ordinaria","Ordinary activity"),color:"#64748b"},{key:"altro",label:t("Altro (malattia/ferie)","Other (sick leave/holidays)"),color:"#92400e"}]}const zl=new Date,oh=zl.getMonth()+1,rh=zl.getFullYear();function fa(t){return new Array(t).fill("")}function Ii(t,a){const i=ni(a),[n,o]=i?i.split("-").map(Number):[rh,oh],s=As(n,o);return{nome:((t==null?void 0:t.name)||"").split(" ").slice(0,-1).join(" "),cognome:((t==null?void 0:t.name)||"").split(" ").slice(-1).join(" "),codiceFiscale:(t==null?void 0:t.tax_code)||"",figuraProfessionale:(t==null?void 0:t.qualifica)||(t==null?void 0:t.role_label)||"",month:o,year:n,otherCups:["","",""],otherProjectLabel:"",hours:{climpact:fa(s),mur:[fa(s),fa(s),fa(s)],other:fa(s),ordinary:fa(s),altro:fa(s)}}}function lh({member:t,ym:a,onClose:i,review:n,inMask:o=!1}){const{t:s,lang:l}=X(),r=sh(s),d=l==="en"?nh:ih,m=ah(),[c,g]=f.useState(()=>{if(n!=null&&n.data){const S=Bo(n.data);return{...Ii(t,a),...S}}return Ii(t,a)});f.useEffect(()=>{if(n!=null&&n.data){const S=Bo(n.data);g({...Ii(t,a),...S})}else g(Ii(t,a))},[a,n==null?void 0:n.submitted_at,n==null?void 0:n.state]);const[h,p]=f.useState(!1),[x,b]=f.useState(!1),[u,w]=f.useState(!1),[v,j]=f.useState(!1),[_,C]=f.useState(!1),[y,z]=f.useState("");f.useEffect(()=>{if(!m)return;const S=document.body.style.overflow;return document.body.style.overflow="hidden",()=>{document.body.style.overflow=S}},[m]);const T=f.useMemo(()=>As(c.year,c.month),[c.year,c.month]),I=f.useMemo(()=>Hp(c.year),[c.year]),D=["pending","approved","unlock_requested"].includes(n==null?void 0:n.state),$=D?{readOnly:!0}:null,q=D?{disabled:!0}:null,R=a||`${c.year}-${String(c.month).padStart(2,"0")}`,O=f.useRef(null);f.useEffect(()=>{if(!D)return clearTimeout(O.current),O.current=setTimeout(()=>{Go({member:t,year_month:R,formData:c}
437).catch(()=>{})},1200),()=>clearTimeout(O.current)},[c,D,t,R]),f.useEffect(()=>{g(S=>{const W=M=>{const J=[...M||[]];for(;J.length<T;)J.push("");return J.slice(0,T)};return{...S,hours:{climpact:W(S.hours.climpact),mur:S.hours.mur.map(W),other:W(S.hours.other),ordinary:W(S.hours.ordinary),altro:W(S.hours.altro)}}})},[T]);function k(S,W,M,J){g(V=>{const K={...V,hours:{...V.hours}};return S==="mur"?K.hours.mur=V.hours.mur.map((Q,le)=>le===J?Q.map((U,G)=>G===W?M:U):Q):K.hours[S]=V.hours[S].map((Q,le)=>le===W?M:Q),K})}const N=f.useMemo(()=>{const S=K=>parseFloat(String(K??"").replace(",","."))||0,W=new Array(T).fill(0),M=K=>K.reduce((Q,le)=>Q+S(le),0),J={climpact:M(c.hours.climpact),mur:c.hours.mur.map(M),other:M(c.hours.other),ordinary:M(c.hours.ordinary),altro:M(c.hours.altro)};for(let K=0;K<T;K++)W[K]+=S(c.hours.climpact[K])+S(c.hours.mur[0][K])+S(c.hours.mur[1][K])+S(c.hours.mur[2][K])+S(c.hours.other[K])+S(c.hours.ordinary[K])+S(c.hours.altro[K]);const V=W.reduce((K,Q)=>K+Q,0);return{dayCol:W,rowTot:J,grand:V}},[c,T]);async function L(){p(!0);try{const S=await Uo({...c,hours:{...c.hours}}),M=`Timesheet_${(c.cognome||"timesheet").replace(/[^A-Za-z0-9]+/g,"_")}_${c.year}-${String(c.month).padStart(2,"0")}.xlsx`,J=URL.createObjectURL(S),V=document.createElement("a");V.href=J,V.download=M,document.body.appendChild(V),V.click(),V.remove(),setTimeout(()=>URL.revokeObjectURL(J),1500)}catch(S){alert(s("Generazione xlsx non riuscita: ","xlsx generation failed: ")+(S.message||S))}finally{p(!1)}}async function B(){b(!0),D||Go({member:t,year_month:R,formData:c}).catch(()=>{});try{const S=await Uo({...c,hours:{...c.hours}}),M=`Timesheet_${(c.cognome||"timesheet").replace(/[^A-Za-z0-9]+/g,"_")}_${c.year}-${String(c.month).padStart(2,"0")}`;let J=await Jp(S,M+".xlsx");{const Q=[c.nome,c.cognome].filter(Boolean).join(" ").trim();J=await Vd(J,{chiave:"rt.timesheet",tipo:"form",titolo:`Timesheet ${String(c.month).padStart(2,"0")}/${c.year}`,...Q?{intestatario:Q}:{}})}const V=URL.createObjectURL(J),K=document.createElement("a");K.href=V,K.download=M+".pdf",document.body.appendChild(K),K.click(),K.remove(),setTimeout(()=>URL.revokeObjectURL(V),1500)}catch(S){alert(s("Generazione PDF non riuscita: ","PDF generation failed: ")+(S.message||S)+s(` 438 439Puoi sempre usare "Genera xlsx" come ripiego.`,` 440 441You can always use "Generate xlsx" as a fallback.`))}finally{b(!1)}}async function P(){if(N.grand<=0){alert(s("Inserisci almeno un'ora prima di sottomettere.","Enter at least one hour before submitting."));return}w(!0);try{const S=`${c.year}-${String(c.month).padStart(2,"0")}`;await Yp({member:t,year_month:S,formData:c})}catch(S){alert(s("Sottomissione non riuscita: ","Submission failed: ")+(S.message||S))}finally{w(!1)}}async function E(){j(!0);try{const S=`${c.year}-${String(c.month).padStart(2,"0")}`;await Qp({member:t,year_month:S,reason:y}),z(""),C(!1)}catch(S){alert(s("Richiesta di sblocco non riuscita: ","Unlock request failed: ")+(S.message||S))}finally{j(!1)}}const Y=e.jsxs("div",{className:"ts-builder portal-site"+(m&&!o?" ts-builder-fullscreen":""),children:[i&&!o&&e.jsx("button",{type:"button",className:"ts-builder-close",onClick:i,"aria-label":s("Chiudi timesheet","Close timesheet"),title:s("Chiudi","Close"),children:e.jsx(Ce,{size:18})}),e.jsxs("div",{className:"ts-builder-head",children:[e.jsxs("div",{className:"ts-builder-head-id",children:[!o&&e.jsx("span",{className:"ts-builder-eyebrow",children:s("Timesheet mensile","Monthly timesheet")}),e.jsxs("h2",{className:"ts-builder-title",children:[d[c.month-1]," ",c.year]}),e.jsxs("p",{className:"ts-builder-sub",children:[[c.nome,c.cognome].filter(Boolean).join(" ")||s("Compila la griglia giorno per giorno","Fill in the grid day by day"),c.figuraProfessionale?`, ${c.figuraProfessionale}`:""]})]}),e.jsxs("div",{className:"ts-builder-total","data-empty":N.grand<=0?"true":"false",children:[e.jsx("span",{className:"ts-builder-total-label",children:s("Totale mensile","Monthly total")}),e.jsx("span",{className:"ts-builder-total-val mono",children:ei(N.grand)}),e.jsx("span",{className:"ts-builder-total-unit",children:s("ore","hours")})]})]}),(n==null?void 0:n.state)==="pending"&&e.jsxs("div",{className:"ts-banner ts-banner-pending",children:[e.jsx(me,{size:14}),e.jsxs("div",{children:[e.jsx("strong",{children:s("In revisione â campi bloccati.","Under review â fields locked.")})," ",s("Il PI ha ricevuto questa proposta. Riceverai una notifica quando approva o richiede modifiche.","The PI has received this submission. You will be notified when they approve or request changes.")]})]}),(n==null?void 0:n.state)==="approved"&&e.jsxs("div",{className:"ts-banner ts-banner-approved",children:[e.jsx(tt,{size:14}),e.jsxs("div",{children:[e.jsx("strong",{children:s("Approvato dal PI â campi bloccati.","Approved by the PI â fields locked.")})," ",s(`Ora puoi scaricare l'xlsx, salvarlo in PDF, firmarlo e caricarlo nello slot "Versione ricercatore" qui sopra.`,'You can now download the xlsx, save it as PDF, sign it and upload it to the "Researcher version" slot above.'),n.unlock_denied_note&&e.jsxs("div",{className:"ts-banner-note",children:[e.jsx("strong",{children:s("Il PI ha negato la tua ultima richiesta di sblocco:","The PI denied your last unlock request:")})," ","«",n.unlock_denied_note,"»"]}),e.jsx("div",{className:"muted text-xs",style:{marginTop:6},children:s("Per modificarlo dopo l'approvazione, devi richiedere autorizzazione al PI.","To edit it after approval, you must request authorisation from the PI.")}
441)]})]}),(n==null?void 0:n.state)==="unlock_requested"&&e.jsxs("div",{className:"ts-banner ts-banner-pending",children:[e.jsx(me,{size:14}),e.jsxs("div",{children:[e.jsx("strong",{children:s("Richiesta di sblocco inviata.","Unlock request sent.")})," ",s("Il PI ha ricevuto la tua richiesta di poter modificare il timesheet già approvato.","The PI has received your request to edit the already-approved timesheet."),n.unlock_reason&&e.jsxs("div",{className:"ts-banner-note",children:["«",n.unlock_reason,"»"]}),e.jsx("div",{className:"muted text-xs",style:{marginTop:4},children:s("Riceverai notifica quando il PI autorizza o nega.","You will be notified when the PI authorises or denies it.")})]})]}),(n==null?void 0:n.state)==="changes_requested"&&e.jsxs("div",{className:"ts-banner ts-banner-changes",children:[e.jsx(ba,{size:14}),e.jsxs("div",{children:[e.jsx("strong",{children:s("Modifiche richieste dal PI.","Changes requested by the PI.")}),n.pi_note&&e.jsxs("div",{className:"ts-banner-note",children:["«",n.pi_note,"»"]}),e.jsx("div",{className:"muted text-xs",style:{marginTop:4},children:s("Aggiorna i dati e ri-sottometti per una nuova revisione.","Update the data and resubmit for a new review.")})]})]}),e.jsxs(Hn,{title:s("Anagrafica","Personal details"),children:[e.jsxs("div",{className:"ts-row",children:[e.jsx(Yt,{label:s("Mese","Month"),children:e.jsx(xe,{tone:"inherit",value:c.month,...q,onChange:S=>g({...c,month:Number(S)}),ariaLabel:s("Mese","Month"),options:d.map((S,W)=>({value:String(W+1),label:S}))})}),e.jsx(Yt,{label:s("Anno","Year"),children:e.jsx("input",{className:"input mono",type:"number",min:"2024",max:"2030",value:c.year,...$,onChange:S=>g({...c,year:Number(S.target.value)}),style:{width:90}})}),e.jsx(Yt,{label:s("Figura professionale","Professional profile"),wide:!0,children:e.jsx("input",{className:"input",value:c.figuraProfessionale,...$,onChange:S=>g({...c,figuraProfessionale:S.target.value}),placeholder:s("es. Ricercatore, PhD candidate, Principal Investigatorâ¦","e.g. Researcher, PhD candidate, Principal Investigatorâ¦")})})]}),e.jsxs("div",{className:"ts-row",children:[e.jsx(Yt,{label:s("Nome","First name"),wide:!0,children:e.jsx("input",{className:"input",value:c.nome,...$,onChange:S=>g({...c,nome:S.target.value})})}),e.jsx(Yt,{label:s("Cognome","Last name"),wide:!0,children:e.jsx("input",{className:"input",value:c.cognome,...$,onChange:S=>g({...c,cognome:S.target.value})})}),e.jsx(Yt,{label:s("Codice fiscale","Tax code"),children:e.jsx("input",{className:"input mono",value:c.codiceFiscale,...$,onChange:S=>g({...c,codiceFiscale:S.target.value.toUpperCase()}),maxLength:16,style:{width:200}})})]})]}),e.jsx(Hn,{title:s("Altri progetti (opzionale)","Other projects (optional)"),hint:s("Compila solo se in questo mese hai lavorato anche su altri progetti MUR o iniziative parallele.","Fill in only if this month you also worked on other MUR projects or parallel initiatives."),children:e.jsxs("div",{className:"ts-row",children:[[0,1,2].map(S=>e.jsx(Yt,{label:`${s("CUP altro progetto MUR","CUP other MUR project")} #${S+1}`,children:e.jsx("input",{className:"input mono",value:c.otherCups[S],...$,onChange:W=>{const M=[...c.otherCups];M[S]=W.target.value,g({...c,otherCups:M})},placeholder:"â",style:{width:180}})},S)),e.jsx(Yt,{label:s("Etichetta «altri progetti»","Label for «other projects»"),wide:!0,children:e.jsx("input",{className:"input",value:c.otherProjectLabel,...$,onChange:S=>g({...c,otherProjectLabel:S.target.value}),placeholder:s('es. "JM Module CLIMOVE-U" â appare nel modulo come "Attività svolte su altri progetti (â¦)"','e.g. "JM Module CLIMOVE-U" â appears on the form as "Activities on other projects (â¦)"')})})]})}),e.jsxs(Hn,{title:`${s("Ore per giorno","Hours per day")}, ${d[c.month-1]} ${c.year}`,hint:s("Inserisci le ore svolte per categoria. Sabati/domeniche/festivi sono evidenziati. Totali per giorno e per riga si aggiornano live.","Enter the hours worked per category. Saturdays/Sundays/holidays are highlighted. Per-day and per-row totals update live."),children:[e.jsx("div",{className:"ts-grid-wrap",children:e.jsxs("table",{className:"ts-grid",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"ts-grid-cat",children:s("Categoria","Category")}),Array.from({length:T},(S,W)=>W+1).map(S=>{const W=new Date(c.year,c.month-1,S).getDay(),M=(l==="en"?["S","M","T","W","T","F","S"]:["D","L","M","M","G","V","S"])[W],J=Wn(c.year,c.month,S)||Vn(c.year,c.month,S,I);return e.jsxs("th",{className:"ts-grid-day"+(J?" is-nonworking":""),children:[e.jsx("div",{className:"ts-grid-day-num",children:S}),e.jsx("div",{className:"ts-grid-day-dow",children:M})]},S)}),e.jsx("th",{className:"ts-grid-tot",children:s("Tot.","Tot.")})]})}),e.jsxs("tbody",{children:[r.map(S=>{var le;const W=S.key.startsWith("mur"),M=W?Number(S.key.slice(3)):-1,J=W?c.hours.mur[M]:c.hours[S.key],V=W?N.rowTot.mur[M]:N.rowTot[S.key],K=W?String(((le=c.otherCups)==null?void 0:le[M])||"").trim():"",Q=W?K?`CUP: ${K}`:S.helper:S.key==="other"&&String(c.otherProjectLabel||"").trim()?String(c.otherProjectLabel).trim():S.helper;return e.jsxs("tr",{children:[e.jsxs("th",{className:"ts-grid-cat-label",children:[e.jsx("span",{className:"ts-cat-dot",style:{background:S.color}}),e.jsxs("span",{className:"ts-cat-text",children:[e.jsx("span",{className:"ts-cat-name",children:S.label}),Q&&e.jsx("span",{className:"ts-cat-help muted",children:Q})]})]}),J.map((U,G)=>{const ne=G+1,ue=Wn(c.year,c.month,ne)||Vn(c.year,c.month,ne,I);return e.jsx("td",{className:ue?"is-nonworking":"",children:e.jsx("input",{className:"input mono ts-cell",inputMode:"decimal",value:U,...$,onChange:ge=>W?k("mur",G,ge.target.value,M):k(S.key,G,ge.target.value)})},G)}),e.jsx("td",{className:"ts-grid-tot mono",children:ei(V)})]},S.key)}),e.jsxs("tr",{className:"ts-grid-totalrow",children:[e.jsx("th",{children:s("Totale ore","Total hours")}),N.dayCol.map((S,W)=>{const M=Wn(c.year,c.month,W+1)||Vn(c.year,c.month,W+1,I);return e.jsx("td",{className:"mono"+(M?" is-nonworking":""),children:S?ei(S):""},W)}),e.jsx("td",{className:"ts-grid-tot mono is-grand",children:ei(N.grand)})]})]})]})}),e.jsx("div",{className:"ts-grid-foot",children:e.jsxs("div",{className:"ts-legend",children:[e.jsxs("span",{className:"ts-legend-item",children:[e.jsx("span",{className:"ts-leg ts-leg-nonworking",children:"â "})," ",s("domenica / festivo italiano (Pasquetta inclusa)","Sunday / Italian public holiday (Easter Monday included)")]}),e.jsx("span",{className:"ts-legend-item ts-legend-hint",children:s("Scorri orizzontalmente per vedere tutti i giorni del mese.","Scroll horizontally to see all the days of the month.")})]})})]}),(n==null?void 0:n.state)==="approved"&&_&&e.jsxs("div",{className:"ts-unlock-form",children:[e.jsx("label",{className:"label ts-unlock-label",children:s("Motivo della richiesta di modifica (opzionale ma utile al PI):","Reason for the edit request (optional but useful to the PI):")}),e.jsx("textarea",{className:"textarea ts-unlock-textarea",rows:2,value:y,onChange:S=>z(S.target.value),placeholder:s("es. Ho dimenticato di registrare le 4 ore del 12 maggio dedicate al meeting Climpact.","e.g. I forgot to re
441cord the 4 hours of 12 May spent on the Climpact meeting.")}),e.jsxs("div",{className:"ospite-pill-row ts-unlock-actions",children:[e.jsxs("button",{type:"button",className:"btn btn-primary btn-sm",disabled:v,onClick:E,children:[e.jsx(vr,{size:14}),e.jsx("span",{children:v?"â¦":s("Invia richiesta sblocco","Send unlock request")})]}),e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{C(!1),z("")},children:e.jsx("span",{children:s("Annulla","Cancel")})})]})]}),e.jsxs("div",{className:"ospite-formactions ts-actions",children:[e.jsx("div",{className:"muted text-xs ts-actions-note",children:N.grand>0&&`${s("Totale mensile","Monthly total")}: ${ei(N.grand)} ${s("ore","hours")}`}),e.jsxs("div",{className:"ospite-pill-row",children:[(!(n!=null&&n.state)||(n==null?void 0:n.state)==="changes_requested")&&e.jsxs("button",{type:"button",className:"btn btn-primary",onClick:P,disabled:u,title:s("Invia in revisione al PI","Submit to the PI for review"),children:[e.jsx(Ot,{size:14}),e.jsx("span",{children:u?"â¦":(n==null?void 0:n.state)==="changes_requested"?s("Ri-sottometti al PI","Resubmit to the PI"):s("Sottometti al PI per revisione","Submit to the PI for review")})]}),(n==null?void 0:n.state)==="approved"&&!_&&e.jsxs("button",{type:"button",className:"btn btn-secondary",onClick:()=>C(!0),title:s("Per modificare un timesheet già approvato serve l'autorizzazione del PI","Editing an already-approved timesheet requires the PIâs authorisation"),children:[e.jsx(cn,{size:14}),e.jsx("span",{children:s("Richiedi modifica al PI","Request edit from the PI")})]}),e.jsxs("button",{type:"button",className:"btn btn-primary",onClick:B,disabled:x,title:s("Genera il PDF A4 orizzontale (identico all'Excel), pronto da firmare","Generate the A4 landscape PDF (identical to the Excel), ready to sign"),children:[e.jsx(Ue,{size:14}),e.jsx("span",{children:x?s("Genero il PDFâ¦","Generating the PDFâ¦"):s("Genera PDF","Generate PDF")})]}),e.jsxs("button",{type:"button",className:"btn btn-secondary",onClick:L,disabled:h,title:s("Scarica l'Excel modificabile (se preferisci convertirlo tu)","Download the editable Excel (if you prefer to convert it yourself)"),children:[e.jsx(Ui,{size:14}),e.jsx("span",{children:h?"â¦":s("Genera xlsx","Generate xlsx")})]}),i&&e.jsx("button",{type:"button",className:"btn btn-secondary",onClick:i,children:e.jsx("span",{children:s("Chiudi","Close")})})]})]})]});return m&&!o&&typeof document<"u"?ra.createPortal(Y,document.body):Y}function Hn({title:t,hint:a,children:i}){return e.jsxs("div",{className:"ospite-formsection",children:[e.jsx("h3",{children:t}),a&&e.jsx("p",{className:"muted text-xs",style:{marginTop:-6,marginBottom:8},children:a}),i]})}function Yt({label:t,children:a,wide:i}){return e.jsxs("div",{className:"mt-field"+(i?" is-wide":""),children:[e.jsx("label",{className:"label",children:t}),a]})}function ei(t){return t?Number(t).toLocaleString("de-DE",{minimumFractionDigits:0,maximumFractionDigits:2}):"0"}const Wo=".pdf,application/pdf";function ch(t){if(!t)return"";const a=t.replace(/\([^)]*\)/g,"").trim().split(/\s+/).filter(Boolean);return a.length?a[a.length-1].replace(/[^A-Za-zÃ-ÿ'-]/g,""):""}function Kn(t,a){const[i,n]=String(a).split("-"),o=an[parseInt(n,10)-1]||n;return"Timesheet "+(ch(t==null?void 0:t.name)||(t!=null&&t.uid?t.uid.slice(-6):"sconosciuto"))+" "+o+" "+i+".pdf"}const an=["Gennaio","Febbraio","Marzo","Aprile","Maggio","Giugno","Luglio","Agosto","Settembre","Ottobre","Novembre","Dicembre"],xs=["January","February","March","April","May","June","July","August","September","October","November","December"];
441function Ft(t,a){if(!t)return"";const[i,n]=t.split("-");return(a==="it"?an:xs)[parseInt(n,10)-1]+" "+i}function ti(){const t=new Date;return t.getFullYear()+"-"+String(t.getMonth()+1).padStart(2,"0")}function dh(t,a){if(!t)return[];const i=[],[n,o]=t.split("-").map(Number),[s,l]=a.split("-").map(Number);let r=n,d=o;for(let m=0;m<120&&(i.push(r+"-"+String(d).padStart(2,"0")),!(r===s&&d===l||(d++,d===13&&(d=1,r++),r>s)));m++);return i}function uh(t,a){if(!a||t.length===0)return t.length?[{yearNum:1,months:[...t]}]:[];const[i,n]=a.split("-").map(Number),o=i*12+(n-1),s=new Map;for(const l of t){const[r,d]=l.split("-").map(Number),c=r*12+(d-1)-o,g=Math.max(1,Math.floor(c/12)+1);s.has(g)||s.set(g,[]),s.get(g).push(l)}return[...s.entries()].sort((l,r)=>l[0]-r[0]).map(([l,r])=>({yearNum:l,months:r}))}function mh(t,a){if(!t.months.length)return"";const i=t.months[0],n=t.months[t.months.length-1];return`${Ft(i,a)} â ${Ft(n,a)}`}function ph({member:t,isAdmin:a,onBack:i}){const{t:n,lang:o}=X(),[s,l]=f.useState(ni(t.timesheet_start_month)),[r,d]=f.useState(!1),[m,c]=f.useState(ni(t.timesheet_start_month)||ti()),[g,h]=f.useState({});f.useEffect(()=>{const b=Ye(oe(te,"users",t.uid),u=>{if(u.exists()){const w=ni(u.data().timesheet_start_month);l(w),r||c(w||ti())}});return()=>b()},[t.uid]),f.useEffect(()=>{const b=ft(Ie(te,"team_timesheets"),Bt("team_uid","==",t.uid)),u=Ye(b,w=>{const v={};w.docs.forEach(j=>{const _=j.data();v[_.year_month]={id:j.id,..._}}),h(v)});return()=>u()},[t.uid]);const p=f.useMemo(()=>s?dh(s,ti()):[],[s]);async function x(){const b=ni(m);if(!b){alert(n("Formato mese non valido (es. 2026-05).","Invalid month format (e.g. 2026-05)."));return}await _e(oe(te,"users",t.uid),{timesheet_start_month:b},{merge:!0}),d(!1)}return e.jsxs(e.Fragment,{children:[e.jsx("section",{className:"mt-band mt-band-dark",children:e.jsxs("div",{className:"mt-wrap",children:[i&&e.jsxs("button",{className:"btn btn-ghost btn-sm mt-back reveal",onClick:i,children:[e.jsx(Wa,{size:14})," ",n("Indietro","Back")]}),e.jsx("p",{className:"mt-eyebrow reveal",children:n("Gruppo di ricerca","Research Team")}),e.jsxs("h1",{className:"mt-section-title reveal","data-d":"1",children:[n("Timesheet di","Timesheet of")," ",t.name]}),e.jsx("p",{className:"mt-section-sub reveal","data-d":"2",children:a?n("Imposta il mese di inizio, segui le sottomissioni in revisione e i caricamenti dei PDF firmati.","Set the start month, follow submissions under review and the uploads of signed PDFs."):n("Compila il timesheet mensile direttamente nella pagina (con il calendario, domeniche e festività in rosso). Inviarlo al PI per la revisione, scarica lâxlsx, salvalo come PDF, firmalo e ricaricalo.","Fill in the monthly timesheet directly on the page (calendar-aware, with Sundays and public holidays in red). Submit it to the PI for review, download the xlsx, save it as PDF, sign it and upload it back.")})]})}),e.jsx("section",{className:"mt-band mt-band-tight",children:e.jsxs("div",{className:"mt-wrap",children:[e.jsx(Kr,{configKey:"timesheet_instructions",title:n("Istruzioni e scadenze per il caricamento del timesheet","Instructions and deadlines for the timesheet upload"),isAdmin:a,defaultText:n(`Per ogni mese: apri il pannello "Compila timesheet (xlsx)" nella riga del mese, compila la griglia (con il calendario, domeniche e festività evidenziate) e â facoltativo ma consigliato â clicca "Invia al PI per la revisione" PRIMA di scaricare lâxlsx. 442Il PI viene avvisato, controlla i dati e risponde in app con "Approvato" o "Modifiche richieste" + una nota. In entrambi i casi ricevi una notifica. 443Una volta approvato, scarica lâxlsx, salvalo come PDF, firmalo digitalmente (CAdES/PAdES) â un timesheet senza firma digitale non è valido ai fini della rendicontazione â e caricalo nello slot "Versione del ricercatore". 444Scadenza: entro il 15 del mese successivo al mese rendicontato.`,`For each month: open the "Fill in timesheet (xlsx)" panel on the month row, fill in the grid (calendar-aware, with Sundays and public holidays highlighted) and â optional but recommended â click "Submit to the PI for review" BEFORE downloading the xlsx. 445The PI is notified, checks the data and replies in app with "Approved" or "Changes requested" + a note. You receive a notification either way. 446Once approved, download the xlsx, save it as PDF, sign it digitally (CAdES/PAdES) â a timesheet without a digital signature is not val
446id for reporting â and upload it to the "Researcher version" slot. 447Deadline: by the 15th of the month following the reporting month.`)}),e.jsxs("div",{className:"mt-card mt-startmonth",children:[e.jsx(hi,{size:16}),e.jsxs("div",{style:{flex:1},children:[e.jsx("strong",{children:n("Mese di inizio timesheet","Timesheet start month")}),e.jsx("div",{className:"muted text-xs",children:n("Le righe mensili compaiono da questo mese in poi, una per ogni mese fino a quello corrente.","Monthly rows appear from this month onwards, one for each month up to the current one.")})]}),r&&a?e.jsxs(e.Fragment,{children:[e.jsx(oc,{value:m,onChange:c,clearable:!1}),e.jsxs("button",{className:"btn btn-primary btn-sm",onClick:x,children:[e.jsx(ke,{size:12})," ",n("Salva","Save")]}),e.jsxs("button",{className:"btn btn-secondary btn-sm",onClick:()=>{d(!1),c(s||ti())},children:[e.jsx(Ce,{size:12})," ",n("Annulla","Cancel")]})]}):e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"mono",style:{fontSize:13},children:s?Ft(s,o):n("non impostato","not set")}),a&&e.jsxs("button",{className:"btn btn-ghost btn-sm",onClick:()=>d(!0),children:[e.jsx(wa,{size:12})," ",n("Modifica","Edit")]})]})]}),s?e.jsx("div",{className:"ts-year-list",children:uh(p,s).map(b=>e.jsx(hh,{group:b,entries:g,member:t,isAdmin:a,startMonth:s,currentYM:ti()},b.yearNum))}):e.jsx("div",{className:"mt-card mt-empty",children:a?n("Imposta qui sopra il mese di inizio per generare le righe mensili.","Set the start month above to generate the monthly rows."):n("Il PI non ha ancora impostato il mese di inizio per i tuoi timesheet.","The PI has not yet set the start month for your timesheets.")})]})})]})}function hh({group:t,entries:a,member:i,isAdmin:n,startMonth:o,currentYM:s}){var v,j;const{t:l,lang:r}=X(),d=`ts_year_open_${i.uid}_${t.yearNum}`,m=t.months.includes(s),[c,g]=f.useState(()=>{try{const _=localStorage.getItem(d);if(_==="1")return!0;if(_==="0")return!1}catch{}return m});function h(){g(_=>{const C=!_;try{localStorage.setItem(d,C?"1":"0")}catch{}return C})}const p=t.months.length;let x=0,b=0,u=0,w=0;for(const _ of t.months){const C=a[_];C&&((C.researcher_pdf||C.file)&&x++,C.signed_pdf&&b++,(((v=C.review)==null?void 0:v.state)==="pending"||((j=C.review)==null?void 0:j.state)==="unlock_requested")&&u++,typeof C.hours=="number"&&(w+=C.hours))}return e.jsxs("div",{className:"ts-year card"+(c?" is-open":" is-closed"),children:[e.jsxs("button",{type:"button",className:"ts-year-head",onClick:h,children:[e.jsx("span",{className:"ts-year-chevron",children:c?e.jsx(ln,{size:16}):e.jsx(yt,{size:16})}),e.jsxs("strong",{className:"ts-year-title",children:[l("Anno","Year")," ",t.yearNum]}),e.jsx("span",{className:"muted text-xs ts-year-range",children:mh(t,r)}),e.jsxs("span",{className:"ts-year-stats",children:[e.jsxs("span",{className:"chip",children:[p," ",p===1?l("mese","month"):l("mesi","months")]}),x>0&&e.jsxs("span",{className:"chip",children:[x," ",l("caricati","uploaded")]}),b>0&&e.jsxs("span",{className:"chip chip-success",children:[b," ",l("firmati","signed")]}),u>0&&e.jsxs("span",{className:"chip chip-accent",children:[u," ",l("in revisione","under review")]}),w>0&&e.jsxs("span",{className:"chip",children:[w,"h"]})]})]}),c&&e.jsx("div",{className:"mt-pill-list ts-year-body",children:t.months.map(_=>e.jsx(fh,{ym:_,entry:a[_],member:i,isAdmin:n,defaultOpen:_===s},_))})]})}function fh({ym:t,entry:a,member:i,isAdmin:n,defaultOpen:o}){var V,K,Q,le;const{t:s,lang:l}=X(),[r,d]=f.useState("idle"),[m,c]=f.useState(null),[g,h]=f.useState(""),[p,x]=f.useState(null),{openMask:b,update:u,close:w,masks:v}=Va(),j="timesheet-"+i.uid+"-"+t,_=v.some(U=>U.id===j),C="Timesheet "+(l==="it"?"di ":"for ")+((l==="it"?an:xs)[parseInt(String(t).split("-")[1],10)-1]||t)+" "+String(t).split("-")[0],y=f.useRef(null),z=f.useRef(null),T=(a==null?void 0:a.researcher_pdf)||(a==null?void 0:a.file)||null,I=(a==null?void 0:a.signed_pdf)||null;function D(U){return!U.type.includes("pdf")&&!/\.pdf$/i.test(U.name)?(alert(s("Il timesheet deve essere un PDF (firmato digitalmente).","The timesheet must be a PDF (digitally signed).")),!1):!0}function $(U){var ne;const G=(ne=U.target.files)==null?void 0:ne[0];if(G){if(!D(G)){U.target.value="";return}c(G),h(a!=null&&a.hours?String(a.hours):""),x(null),d("confirming-researcher"),U.target.value=""}}async function q(U){var ne;const G=(ne=U.target.files)==null?void 0:ne[0];if(G){if(!D(G)){U.target.value="";return}d("uploading-signed");try{const ge=Kn(i,t).replace(/\.pdf$/i,"")+" (firmato PI).pdf",we="team-timesheets/"+i.uid+"/signed/"+ge,Se=new File([G],ge,{type:G.type||"application/pdf"}),ot=await ze(we,Se,{contentType:G.type||"application/pdf",contentDisposition:'attachment; filename="'+ge+'"'});I!=null&&I.path&&I.path!==we&&await de(I.path);const it=i.uid+"__"+t;await _e(oe(te,"team_timesheets",it),{team_uid:i.uid,year_month:t,signed_pdf:{url:ot.url,path:ot.path,name:ge,size:G.size,uploaded_at:ie(),uploaded_by:ye.currentUser.uid},signed_at:ie()},{merge:!0}),ld({member:i,year_month:t,file:{name:ge,size:G.size}}),d("idle")}catch(ue){console.error(ue),alert(s("Caricamento non riuscito: ","Upload failed: ")+(ue.message||ue)),d("idle")}U.target.value=""}}async function R(){const U=parseFloat(String(g).replace(",","."));if(!g||isNaN(U)||U<=0){x(s("Inserisci un numero di ore valido.","Enter a valid number of hours."));return}d("uploading-researcher");try{const G=Kn(i,t),ne="team-timesheets/"+i.uid+"/researcher/"+G,ue=new File([m],G,{type:m.type||"application/pdf"}),ge=await ze(ne,ue,{contentType:m.type||"application/pdf",contentDisposition:'attachment; filename="'+G+'"'});T!=null&&T.path&&T.path!==ne&&await de(T.path);const we=i.uid+"__"+t,Se={team_uid:i.uid,year_month:t,hours:U,researcher_pdf:{url:ge.url,path:ge.path,name:G,size:m.size,uploaded_at:ie(),uploaded_by:ye.currentUser.uid},confirmed_at:ie(),created_by:ye.currentUser.uid};a!=null&&a.file&&!(a!=null&&a.researcher_pdf)&&(Se.file=null),await _e(oe(te,"team_timesheets",we),Se,{merge:!0}),rd({member:i,year_month:t,hours:U,file:{name:G,size:m.size}}),d("idle"),c(null),h("")}catch(G){console.error(G),x(s("Caricamento non riuscito: ","Upload failed: ")+(G.message||G)),d("confirming-researcher")}}function O(){d("idle"),c(null),h(""),x(null)}async function k(){if(confirm(s("Eliminare lâintera voce per ","Delete the whole entry for ")+Ft(t,l)+s(" (entrambi i PDF, ore, conferma)?"," (both PDFs, hours, confirmation)?")))try{T!=null&&T.path&&await de(T.path),I!=null&&I.path&&await de(I.path),await gt(oe(te,"team_timesheets",a.id))}catch(U){alert(s("Eliminazione non riuscita: ","Delete failed: ")+(U.message||U))}}async function N(){if(confirm(s("Rimuovere il PDF controfirmato dal PI? Il timesheet del ricercatore resta intatto.","Remove the PDF countersigned by the PI? The researcher timesheet stays intact.")))try{I!=null&&I.path&&await de(I.path),await _e(oe(te,"team_timesheets",a.id),{signed_pdf:null,signed_at:null},{merge:!0})}catch(U){alert(s("Errore: ","Error: ")+(U.message||U))}}async function L(){if(n&&confirm(s("Rimuovere il PDF caricato dal ricercatore? La voce resta (ore + eventuale firma del PI).","Remove the PDF uploaded by the researcher? The entry remains (hours + any PI signature).")))try{T!=null&&T.path&&await de(T.path),await _e(oe(te,"team_timesheets",a.id),{researcher_pdf:null,file:null,hours:null,confirmed_at:null},{merge:!0})}catch(U){alert(s("Errore: ","Error: ")+(U.message||U))}}const B=!!(T||I),P=a==null?void 0:a.review,E=P==null?void 0:P.state,Y=(()=>
447{switch(E){case"pending":return{label:s("in revisione","under review"),cls:"chip chip-accent"};case"approved":return{label:s("approvato","approved"),cls:"chip chip-success"};case"changes_requested":return{label:s("modifiche richieste","changes requested"),cls:"chip chip-warning"};case"unlock_requested":return{label:s("sblocco richiesto","unlock requested"),cls:"chip chip-accent"};default:return null}})(),[S,W]=String(t).split("-"),M=e.jsx("div",{className:"mt-shell-body portal-site",children:r==="confirming-researcher"&&m?e.jsxs("div",{className:"mt-pill mt-pill-confirm card",children:[e.jsx("div",{className:"mt-pill-row",children:e.jsxs("strong",{children:[s("Conferma caricamento â ","Confirm upload â "),Ft(t,l)]})}),e.jsxs("div",{className:"mt-pill-confirm-fields",children:[e.jsxs("div",{className:"field",children:[e.jsx("label",{className:"label",children:s("Mese","Month")}),e.jsx("input",{className:"input",readOnly:!0,value:(l==="it"?an:xs)[parseInt(W,10)-1]})]}),e.jsxs("div",{className:"field",children:[e.jsx("label",{className:"label",children:s("Anno","Year")}),e.jsx("input",{className:"input",readOnly:!0,value:S})]}),e.jsxs("div",{className:"field",children:[e.jsx("label",{className:"label",children:s("Ore dichiarate per il mese","Hours declared for the month")}
447),e.jsx("input",{className:"input mono",autoFocus:!0,value:g,onChange:U=>{h(U.target.value),x(null)},placeholder:s("es. 168","e.g. 168"),inputMode:"decimal"})]}),e.jsxs("div",{className:"field",children:[e.jsx("label",{className:"label",children:s("File selezionato","Selected file")}),e.jsxs("div",{className:"muted text-sm",style:{paddingTop:8},children:[m.name,", ",Math.round(m.size/1024)," KB"]}),e.jsxs("div",{className:"muted text-xs",style:{marginTop:4,fontStyle:"italic"},children:[s("Sarà salvato come: ","It will be saved as: "),e.jsx("strong",{style:{fontStyle:"normal"},children:Kn(i,t)})]})]})]}),p&&e.jsxs("div",{className:"login-alert login-alert-error",style:{marginTop:8},children:[e.jsx(at,{size:14})," ",e.jsx("span",{children:p})]}),e.jsxs("div",{className:"mt-pill-confirm-actions",children:[e.jsxs("button",{className:"btn btn-primary",onClick:R,children:[e.jsx(ke,{size:14})," ",s("Conferma e carica","Confirm and upload")]}),e.jsxs("button",{className:"btn btn-secondary",onClick:O,children:[e.jsx(Ce,{size:14})," ",s("Annulla","Cancel")]})]})]}):r==="uploading-researcher"||r==="uploading-signed"?e.jsxs("div",{className:"mt-pill card mt-pill-busy",children:[s("Caricamento del timesheet per ","Uploading the timesheet for "),Ft(t,l),"â¦"]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"mt-pill-slots",children:[e.jsx(Vo,{title:s("Versione del ricercatore","Researcher version"),subtitle:s("caricata e firmata digitalmente dal ricercatore","uploaded and digitally signed by the researcher"),file:T,canUpload:!0,canRemove:n,locked:!1,onPick:()=>{var U;return(U=y.current)==null?void 0:U.click()},onRemove:L}),e.jsx(Vo,{title:s("Controfirma del PI","PI countersignature"),subtitle:n?s("copia dâarchivio firmata dal PI","archive copy signed by the PI"):s("copia dâarchivio firmata dal PI, solo download","archive copy signed by the PI, download only"),file:I,canUpload:n,canRemove:n,locked:!n,onPick:()=>{var U;return(U=z.current)==null?void 0:U.click()},onRemove:N})]}),e.jsx("input",{ref:y,type:"file",accept:Wo,style:{display:"none"},onChange:$}),e.jsx("input",{ref:z,type:"file",accept:Wo,style:{display:"none"},onChange:q}),n&&((V=a==null?void 0:a.review)==null?void 0:V.state)==="pending"&&e.jsx(gh,{entry:a,ym:t,member:i}),n&&((K=a==null?void 0:a.review)==null?void 0:K.state)==="unlock_requested"&&e.jsx(xh,{entry:a,ym:t,member:i}),e.jsx("div",{style:{marginTop:10,paddingTop:10,borderTop:"1px dashed var(--divider)"},children:e.jsx(lh,{member:i,ym:t,review:a==null?void 0:a.review,inMask:!0})})]})});f.useEffect(()=>{_&&u(j,{title:C,icon:e.jsx(Ui,{size:18}),content:M})},[_,r,m,g,p,(Q=a==null?void 0:a.review)==null?void 0:Q.state,(le=a==null?void 0:a.review)==null?void 0:le.total_hours,T==null?void 0:T.url,I==null?void 0:I.url,a==null?void 0:a.hours]);function J(){_?w(j):b({id:j,title:C,icon:e.jsx(Ui,{size:18}),content:M})}return e.jsxs("article",{className:"mt-listrow mt-listrow-timesheet"+(_?" is-open":""),role:"button",tabIndex:0,"aria-expanded":_,onClick:U=>{U.target.closest("button, a, input, select, textarea")||J()},onKeyDown:U=>{(U.key==="Enter"||U.key===" ")&&(U.preventDefault(),J())},children:[e.jsxs("span",{className:"mt-listrow-cell mt-listrow-primary",children:[e.jsx(hi,{size:14,className:"muted"}),e.jsxs("strong",{className:"mt-listrow-title",children:["Timesheet ",Ft(t,l)]})]}),e.jsxs("span",{className:"mt-listrow-cell mt-listrow-chips",children:[T&&e.jsx("span",{className:"chip",children:s("PDF ricercatore","researcher PDF")}),I&&e.jsx("span",{className:"chip",children:s("firmato PI","PI-signed")})]}),e.jsx("span",{className:"mt-listrow-cell mt-listrow-num",children:(a==null?void 0:a.hours)!=null?`${a.hours} ${s("ore","hours")}`:"â"}),e.jsx("span",{className:"mt-listrow-cell mt-listrow-chips",children:Y&&e.jsx("span",{className:Y.cls,children:Y.label})}),n&&B?e.jsx("button",{type:"button",className:"btn btn-ghost btn-sm mt-row-delete",onClick:U=>{U.stopPropagation(),k()},"aria-label":s("Elimina voce timesheet","Delete timesheet entry"),title:s("Elimina lâintera voce per il mese","Delete the whole entry for the month"),children:e.jsx($e,{size:14})}):e.jsx("span",{className:"mt-listrow-cell","aria-hidden":"true"}),e.jsxs("button",{type:"button",className:"mt-listrow-open",onClick:U=>{U.stopPropagation(),J()},"aria-label":_?s("Chiudi timesheet del mese","Close month timesheet"):s("Apri timesheet del mese","Open month timesheet"),children:[_?s("Aperto","Opened"):s("Apri","Open"),e.jsx(yt,{size:15})]})]})}function gh({entry:t,ym:a,member:i}){const{t:n,lang:o}
447=X(),[s,l]=f.useState(!1),[r,d]=f.useState(!1),[m,c]=f.useState(""),h=(t.review||{}).total_hours;async function p(){l(!0);try{await Zp({entryId:t.id,member:i,year_month:a})}catch(b){alert(n("Errore: ","Error: ")+(b.message||b))}finally{l(!1)}}async function x(){if(!m.trim()){alert(n("Scrivi una nota per il ricercatore.","Write a note for the researcher."));return}l(!0);try{await Xp({entryId:t.id,member:i,year_month:a,note:m}),c(""),d(!1)}catch(b){alert(n("Errore: ","Error: ")+(b.message||b))}finally{l(!1)}}return e.jsxs("div",{className:"ts-review-pi",children:[e.jsxs("div",{className:"ts-review-pi-head",children:[e.jsx(Ot,{size:14})," ",n("Sottomissione in revisione","Submission under review")]}),e.jsxs("div",{className:"ts-review-pi-meta",children:[(i==null?void 0:i.name)||n("Ricercatore","Researcher")," ",n("ha sottomesso il timesheet di","submitted the timesheet for")," ",Ft(a,o)," ",h!=null&&e.jsxs("strong",{children:["· ",h," ",n("ore totali","total hours")]}),"."," ",n('Apri "Compila timesheet (xlsx)" qui sotto per vedere la griglia compilata.','Open "Fill in timesheet (xlsx)" below to see the filled grid.')]}),r?e.jsxs(e.Fragment,{children:[e.jsx("textarea",{className:"textarea",rows:3,placeholder:n("Spiega cosa va modificato (es. «Mancano le ore del 7-8-9 maggio»)","Explain what needs changing (e.g. «Hours for 7-8-9 May are missing»)"),value:m,onChange:b=>c(b.target.value),style:{fontSize:12.5}}),e.jsxs("div",{className:"ts-review-pi-actions",children:[e.jsxs("button",{className:"btn btn-primary btn-sm",disabled:s||!m.trim(),onClick:x,children:[e.jsx(as,{size:12})," ",n("Invia richiesta modifiche","Send change request")]}),e.jsxs("button",{className:"btn btn-ghost btn-sm",onClick:()=>{d(!1),c("")},children:[e.jsx(Ce,{size:12})," ",n("Annulla","Cancel")]})]})]}):e.jsxs("div",{className:"ts-review-pi-actions",children:[e.jsxs("button",{className:"btn btn-primary btn-sm",disabled:s,onClick:p,children:[e.jsx(ke,{size:12})," ",n("Approva","Approve")]}),e.jsxs("button",{className:"btn btn-secondary btn-sm",disabled:s,onClick:()=>d(!0),children:[e.jsx(as,{size:12})," ",n("Richiedi modifiche","Request changes")]})]})]})}function xh({entry:t,ym:a,member:i}){const{t:n,lang:o}=X(),[s,l]=f.useState(!1),[r,d]=f.useState(!1),[m,c]=f.useState(""),g=t.review||{};async function h(){if(confirm(n("Autorizzare lo sblocco? Il ricercatore potrà modificare il timesheet e dovrà ri-sottometterlo.","Authorise the unlock? The researcher will be able to edit the timesheet and will have to resubmit it."))){l(!0);try{await eh({entryId:t.id,member:i,year_month:a})}catch(x){alert(n("Errore: ","Error: ")+(x.message||x))}finally{l(!1)}}}async function p(){if(!m.trim()){alert(n("Scrivi il motivo del rifiuto.","Write the reason for the refusal."));return}l(!0);try{await th({entryId:t.id,member:i,year_month:a,note:m}),c(""),d(!1)}catch(x){alert(n("Errore: ","Error: ")+(x.message||x))}finally{l(!1)}}return e.jsxs("div",{className:"ts-review-pi",children:[e.jsxs("div",{className:"ts-review-pi-head",children:[e.jsx(Ot,{size:14})," ",n("Richiesta sblocco timesheet approvato","Unlock request for an approved timesheet")]}),e.jsxs("div",{className:"ts-review-pi-meta",children:[(i==null?void 0:i.name)||n("Ricercatore","Researcher")," ",n("chiede di poter modificare il timesheet di","is asking to edit the timesheet for")," ",Ft(a,o)," ",n("(già approvato).","(already approved)."),g.unlock_reason&&e.jsxs("div",{style:{marginTop:4,fontStyle:"italic",color:"var(--text-primary)"},children:[n("Motivazione: «","Reason: «"),g.unlock_reason,"»"]})]}),r?e.jsxs(e.Fragment,{children:[e.jsx("textarea",{className:"textarea",rows:3,placeholder:n("Motivo del rifiuto (es. «Il timesheet è già stato inviato in rendicontazione»)","Reason for refusal (e.g. «The timesheet has already been submitted for reporting»)"),value:m,onChange:x=>c(x.target.value),style:{fontSize:12.5}}),e.jsxs("div",{className:"ts-review-pi-actions",children:[e.jsxs("button",{className:"btn btn-primary btn-sm",disabled:s||!m.trim(),onClick:p,children:[e.jsx(Ce,{size:12})," ",n("Conferma rifiuto","Confirm refusal")]}),e.jsx("button",{className:"btn btn-ghost btn-sm",onClick:()=>{d(!1),c("")},children:n("Annulla","Cancel")})]})]}):e.jsxs("div",{className:"ts-review-pi-actions",children:[e.jsxs("button",{className:"btn btn-primary btn-sm",disabled:s,onClick:h,children:[e.jsx(ke,{size:12})," ",n("Autorizza modifica","Authorise edit")]}),e.jsxs("button",{className:"btn btn-secondary btn-sm",disabled:s,onClick:()=>d(!0),children:[e.jsx(Ce,{size:12})," ",n("Nega","Deny")]})]})]})}function Vo({title:t,subtitle:a,file:i,canUpload:n,canRemove:o,locked:s,onPick:l,onRemove:r}){const{t:d}=X();return e.jsxs("div",{className:"mt-pdf-slot"+(i?" has-file":"")+(s?" is-locked":""),children:[e.jsxs("div",{className:"mt-pdf-head",children:[e.jsxs("div",{children:[e.jsx("strong",{children:t}),e.jsx("div",{className:"muted text-xs",children:a})]}),s&&!n&&e.jsx(cn,{size:14,className:"muted"})]}),i?e.jsxs("div",{className:"mt-pdf-file",children:[e.jsxs("a",{href:Je(i.url),target:"_blank",rel:"noreferrer",className:"mt-pdf-file-link",children:[e.jsx(qt,{size:14})," ",i.name||"file.pdf"]}),e.jsx("span",{className:"muted text-xs",children:i.size?Math.round(i.size/1024)+" KB":""}),e.jsxs("div",{className:"mt-pdf-file-actions",children:[n&&e.jsxs("button",{className:"btn btn-secondary btn-sm",onClick:l,children:[e.jsx(qa,{size:12})," ",d("Sostituisci","Replace")]}),o&&e.jsxs("button",{className:"btn btn-ghost btn-sm mt-row-delete",onClick:r,children:[e.jsx($e,{size:12})," ",d("Rimuovi","Remove")]})]})]}
447):n?e.jsxs("button",{className:"mt-pdf-drop",onClick:l,children:[e.jsx(qa,{size:16})," ",d("Carica PDF","Upload PDF")]}):e.jsx("div",{className:"mt-pdf-empty",children:d("Non ancora caricato dal PI.","Not yet uploaded by the PI.")})]})}function bh({label:t,hint:a,storagePrefix:i,files:n=[],onChange:o,busy:s=!1,setBusy:l,emptyHint:r}){const{t:d}=X(),m=t??d("Materiali","Materials"),c=r??d("Nessun file caricato.","No files uploaded."),g=f.useRef(null),[h,p]=f.useState(!1),x=s||h,b=l||p;async function u(v){const j=Array.from(v.target.files||[]);if(j.length){b(!0);try{const _=[];for(const C of j){const y=C.name.replace(/[^A-Za-z0-9.\-_]/g,"_"),z=`${i}/${Date.now()}-${Math.random().toString(36).slice(2,6)}-${y}`,T=await ze(z,C,{contentType:C.type});_.push({id:pn(),url:T.url,path:T.path,name:C.name,size:C.size,uploaded_at:new Date().toISOString()})}o([...n||[],..._])}catch(_){alert(d("Caricamento non riuscito: ","Upload failed: ")+(_.message||_))}finally{b(!1),v.target.value=""}}}async function w(v){const j=(n||[]).find(_=>_.id===v);if(j){if(j.path)try{await de(j.path)}catch(_){console.warn("[materials] delete",_)}o((n||[]).filter(_=>_.id!==v))}}return e.jsxs("div",{className:"mt-mat-block",children:[e.jsxs("div",{className:"mt-mat-head",children:[e.jsx("span",{className:"label",children:m}),a&&e.jsx("span",{className:"muted text-xs",children:a})]}),(n||[]).length===0?e.jsx("div",{className:"mt-mat-empty muted text-xs",children:c}):e.jsx("div",{className:"mt-mat-list",children:n.map(v=>e.jsxs("div",{className:"sab-fileslot",children:[e.jsx(Ue,{size:14,className:"muted"}),e.jsx("a",{href:Je(v.url),target:"_blank",rel:"noreferrer",className:"sab-fileslot-name",title:v.name,children:v.name}),e.jsxs("span",{className:"muted text-xs sab-fileslot-meta",children:[Td(v.size),v.uploaded_at&&", "+new Date(v.uploaded_at).toLocaleDateString("en-GB",{day:"numeric",month:"short",year:"numeric"})]}),e.jsx("a",{href:Je(v.url),target:"_blank",rel:"noreferrer",className:"btn btn-ghost btn-sm mt-ml-auto",title:d("Apri in una nuova scheda","Open in a new tab"),children:e.jsx(fi,{size:12})}),e.jsx("button",{type:"button",className:"btn btn-ghost btn-sm mt-row-delete",onClick:()=>w(v.id||v.path),disabled:x,title:d("Rimuovi","Remove"),children:e.jsx($e,{size:12})})]},v.id||v.path))}),e.jsx("input",{ref:g,type:"file",multiple:!0,onChange:u,disabled:x,className:"mt-hidden-input"}),e.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm mt-mat-add",onClick:()=>{var v;return(v=g.current)==null?void 0:v.click()},disabled:x,children:[e.jsx(Le,{size:12})," ",d("Aggiungi file","Add files"),((n||[]).length,"")]})]})}const vh="/carta-intestata.png?v=ci4",jh=7087/709,vn=210,yh=297,Cl=+(vn/jh).toFixed(2),ea=22,Ho=Cl+12,_h=yh-14,vt=4.8,Fa=11,kl=2.6,Aa=vn-ea,Nh=vn-2*ea,ht="times",wh="Charting the Landscape of Climate Litigation Impacts: An Interdisciplinary Framework and Open Access Database",zh="finanziato dal Fondo Italiano per la Scienza â Bando FIS 3, Schema di finanziamento Starting Grant, Settore ERC SH2, D.D. n. 1802 del 21 novembre 2024 (CUP: H53C25000820001)",Ch="Il Principal Investigator",kh="Dott. Giuseppe Naglieri",Sh="Il Direttore del Dipartimento",Dh="Prof. Paolo Pardolesi",Th="Dichiaro di aver preso visione e compreso lâinformativa, allegata al presente incarico e disponibile allâindirizzo https://www.uniba.it/ateneo/privacy/aggiornamento-informative-regolamentoUE-2016-679 e di aver ricevuto il Codice di Comportamento UNIBA";async function Ih(){const t=await Sa(()=>Ae(()=>import("./jspdf.es.min-27wbmQzZ.js").then(a=>a.j),__vite__mapDeps([16,1,2,3,4,17])));return t.jsPDF||t.default}async function Ph(t){try{const a=await fetch(t,{cache:"force-cache"});if(!a.ok)return null;const i=await a.blob();return await new Promise((n,o)=>{const s=new FileReader;s.onload=()=>n(s.result),s.onerror=o,s.readAsDataURL(i)})}catch{return null}}let Pi;async function Eh(){return Pi!==void 0||(Pi=await Ph(vh)||null),Pi}function Sl(t,a){if(a)try{t.addImage(a,"PNG",0,0,vn,Cl,void 0,"FAST")}catch{}}function Ah(t,a){let i=Ho;return{get y(){return i},set y(n){i=n},advance(n){i+=n},needSpace(n){i+n>_h&&(t.addPage(),Sl(t,a),i=Ho)}}}const $h=["Domenica","Lunedì","Martedì","Mercoledì","Giovedì","Venerdì","Sabato"];function Rh(t){if(!(t!=null&&t.date_start))return"(in data da definire)";const a=new Date(t.date_start);if(isNaN(a.getTime()))return"(in data da definire)";const i=$h[a.getDay()],n=Ge(a),o=(t.event_time_start||"").trim();if(t.date_end&&t.date_end!==t.date_start){const s=new Date(t.date_end);if(!isNaN(s.getTime()))return`dal ${n} al ${Ge(s)}`}return`${i} ${n}${o?" a partire dalle "+o:""}`}function Mh(t){const a=(t||"").toLowerCase();return["prof.ssa","dott.ssa","sig.ra","avv.ssa","ing.ssa"].some(n=>a.includes(n))?"Chiar.ma":"Chiar.mo"}function Fh(t){return t==null||t===""?NaN:parseFloat(String(t).replace(",","."))}function Lh(t){const a=Oh(t),i=[],n=/\{\{i\}\}([\s\S]*?)\{\{\/i\}\}/g;let o=0,s;for(;(s=n.exec(a))!==null;)s.index>o&&i.push({text:a.slice(o,s.index)}),i.push({text:s[1],italic:!0}),o=s.index+s[0].length;return o<a.length&&i.push({text:a.slice(o)}),i.length?i:[{text:a}]}function Oh(t){return t.replace(/'/g,"â").replace(/"([^"]*)"/g,"â$1â")}function bs(t,a,i,n={}
447){const{size:o=Fa,gap:s=kl,maxWidth:l=Nh,leftX:r=ea}=n;t.setFontSize(o),t.setTextColor("#1d1d1f");const d=[];for(const h of i){const p=h.italic?"italic":h.bold?"bold":"normal";for(const x of h.text.split(/(\s+)/).filter(Boolean))d.push({text:x,font:p})}const m=[];let c=[],g=0;for(const h of d){t.setFont(ht,h.font);const p=t.getTextWidth(h.text),x=/^\s+$/.test(h.text);if(g+p>l&&c.length>0){for(;c.length&&/^\s+$/.test(c[c.length-1].text);){const b=c.pop();t.setFont(ht,b.font),g-=t.getTextWidth(b.text)}if(m.push(c),c=[],g=0,x)continue}c.push(h),g+=p}c.length&&m.push(c);for(const h of m){a.needSpace(vt);let p=r;for(const x of h)t.setFont(ht,x.font),t.text(x.text,p,a.y),p+=t.getTextWidth(x.text);a.advance(vt)}a.advance(s)}function $a(t,a,i,n={}){const{italic:o=!1,bold:s=!1}=n;bs(t,a,[{text:i,italic:o,bold:s}],n)}function Jn(t,a,i,n={}){const{x:o=ea,align:s="left",size:l=Fa,font:r="normal",advance:d=!0}=n;a.needSpace(vt),t.setFont(ht,r),t.setFontSize(l),t.setTextColor("#1d1d1f"),t.text(i,o,a.y,{align:s}),d&&a.advance(vt)}async function nn({event:t,participant:a}){const i=await Ih(),n=new i({unit:"mm",format:"a4"}),o=await Eh();Sl(n,o);const s=Ah(n,o),l=t||{},r=a||{},d=s.y;n.setFont(ht,"normal"),n.setFontSize(Fa),n.setTextColor("#1d1d1f"),n.text(`Taranto, ${Ge(new Date)}`,ea,d),n.setFont(ht,"normal"),n.text("Alla Cortese Attenzione",Aa,d,{align:"right"}),n.setFont(ht,"italic");const m=[r.title,r.first_name,r.last_name].filter(Boolean).join(" ").trim()||"[Nome Cognome]";n.text(m,Aa,d+vt,{align:"right"});const c=(r.email||"").trim();let g=0;c&&(n.setFont(ht,"italic"),n.setFontSize(Fa-1),n.text(c,Aa,d+vt*2,{align:"right"}),n.setFontSize(Fa),g=1),s.y=d+vt*(2+g)+8;const h=Mh(r.title),p=[r.title,r.last_name].filter(Boolean).join(" ").trim()||m;$a(n,s,`${h} ${p},`);const x=(l.title||"").trim()||"(titolo evento da definire)",b=/^[aeiouhAEIOUH]/.test(x)?"dellâ":"del ",u=Rh(l),w=l.location?`, presso ${l.location}`:"";bs(n,s,[{text:`ho il piacere di invitarLa a tenere un intervento in occasione ${b}${x} `},{text:`â ${wh}`,italic:!0},{text:`, che si svolgerà ${u}${w}.`}]);const v=(r.intervention_phrase||"").trim()||"terrà un intervento",j=[{text:`Lâevento è previsto nellâambito del progetto di ricerca CLIMPACT, ${zh}, nel corso del quale `},...Lh(v),{text:"."}];bs(n,s,j);const _=Fh(r.honorarium_eur);isFinite(_)&&_>0&&$a(n,s,`Per la Sua partecipazione è inoltre previsto un compenso pari a ⬠${ua(_)} lordi, da intendersi al lordo delle ritenute a carico del percipiente e di IVA (ove dovuta) e al netto degli oneri a carico dellâamministrazione.`),$a(n,s,"Per la Sua partecipazione sarà corrisposto il rimborso delle spese di viaggio, vitto e alloggio, come previsto dal Regolamento missioni di Ateneo dellâUniversità degli Studi di Bari Aldo Moro."),$a(n,s,"Qualora fosse impossibilitato a rispettare quanto detto, la S.V. è invitata a darne comunicazione con la massima tempestività ."),$a(n,s,"RingraziandoLa per la disponibilità , La saluto con viva cordialità .",{gap:kl+2}),s.needSpace(vt*2+14);const C=s.y,y=12;n.setFont(ht,"bold"),n.setFontSize(Fa),n.text(Ch,ea,C),n.setFont(ht,"normal"),n.text(kh,ea,C+y),n.setFont(ht,"normal");const z=(l.director_role||"").trim()||Sh,T=(l.director_name||"").trim()||Dh;n.text(z,Aa,C,{align:"right"}),n.text(T,Aa,C+y,{align:"right"}),s.y=C+y+vt+8,s.needSpace(vt*5+4),Jn(n,s,"Per accettazione:",{font:"italic"}),s.advance(2),Jn(n,s,"Data ___________"),s.advance(3),Jn(n,s,"Firma _________________________"),s.advance(4),$a(n,s,Th,{size:7.5,gap:2.5}),s.needSpace(vt),n.setFont(ht,"normal"),n.setFontSize(8.5),n.setTextColor("#1d1d1f");const I=s.y+1,D=ea+18;n.text("Data",D,I);const $=D+n.getTextWidth("Data")+2,q=$+32;n.setDrawColor("#1d1d1f"),n.line($,I+.4,q,I+.4);const R=Aa-18;n.text("Firma",R,I,{align:"right"});const O=R-n.getTextWidth(" Firma"),k=O-50;n.line(k,I+.4,O,I+.4);const N=(l.title||"evento").replace(/[^A-Za-z0-9]+/g,"_").slice(0,40),B=`Conferimento_incarico_${[r.last_name,r.first_name].filter(Boolean).join("_").replace(/[^A-Za-z0-9_]/g,"")||"partecipante"}_${N}
447.pdf`,P=[r.first_name,r.last_name].filter(Boolean).join(" ").trim(),{bytes:E,codice:Y}=await Hd(n,{chiave:"rt.lettere_convegni",tipo:"letter",titolo:"Lettera di conferimento incarico",intestatario:P});return Y?Kd(E,B):n.save(B),{blob:new Blob([E],{type:"application/pdf"}),filename:B}}const Dl="[email protected]",Tl="[email protected]";function $s(t){return[t==null?void 0:t.title,t==null?void 0:t.first_name,t==null?void 0:t.last_name].filter(Boolean).join(" ").trim()||"(senza nome)"}function Il(t){return String(t||"").replace(/\{\{i\}\}|\{\{\/i\}\}/g,"")}function qh(t,a){const i=((t==null?void 0:t.title)||"(evento senza titolo)").slice(0,80);return`[CLIMPACT] Conferimento incarico â ${$s(a)}, ${i}`}function Uh(t,a){var m;const i=((t==null?void 0:t.title)||"(evento senza titolo)").trim(),n=$s(a),o=((a==null?void 0:a.email)||"").trim(),s=Il((a==null?void 0:a.intervention_phrase)||"").trim(),l=(a==null?void 0:a.honorarium_eur)||"",r=((m=a==null?void 0:a.generated_letter)==null?void 0:m.name)||"la lettera generata in PDF",d=["Gentilissimi,","","in allegato la lettera di conferimento incarico predisposta nell'ambito del progetto di ricerca CLIMPACT (FIS 3 Starting Grant), che si chiede cortesemente di sottoporre alla firma del Direttore del Dipartimento e di inoltrare al destinatario.","","Dati per il routing:",` ⢠Destinatario: ${n}${o?" <"+o+">":""}`,` ⢠Evento: ${i}`];return s&&d.push(` ⢠Ruolo nell'evento: ${s}`),l&&d.push(` ⢠Compenso lordo: ⬠${l}`),d.push("",`(Allegato: ${r})`,"","RingraziandoVi per la collaborazione, porgo i miei più cordiali saluti.","","â","Dott. Giuseppe Naglieri","Principal Investigator del progetto CLIMPACT","Università degli Studi di Bari Aldo Moro"),d.join(` 448`)}function Bh(t,a){const i=((t==null?void 0:t.title)||"(evento senza titolo)").slice(0,70);return`[CLIMPACT] Conferimenti incarico â ${a.length} lettere, ${i}`}function Gh(t,a){const i=((t==null?void 0:t.title)||"(evento senza titolo)").trim(),n=["Gentilissimi,","",`in allegato le ${a.length} lettere di conferimento incarico per i partecipanti dell'evento «${i}», predisposte nell'ambito del progetto di ricerca CLIMPACT (FIS 3 Starting Grant). Si chiede cortesemente di sottoporle alla firma del Direttore del Dipartimento e di inoltrarle ai rispettivi destinatari.`,"","Destinatari:"];for(const o of a){const s=$s(o),l=(o.email||"").trim(),r=Il(o.intervention_phrase||"").trim(),d=r?` â ${r}`:"",m=l?` <${l}>`:"";n.push(` ⢠${s}${m}${d}`)}return n.push("",`(Allegati: ${a.length} PDF â uno per ciascun partecipante.)`,"","RingraziandoVi per la collaborazione, porgo i miei più cordiali saluti.","","â","Dott. Giuseppe Naglieri","Principal Investigator del progetto CLIMPACT","Università degli Studi di Bari Aldo Moro"),n.join(` 449`)}function Pl(t){const a=t==null?void 0:t.generated_letter;if(!(a!=null&&a.url))return null;const i=[t==null?void 0:t.last_name,t==null?void 0:t.first_name].filter(Boolean).join("_").replace(/[^A-Za-z0-9_]+/g,"_")||"partecipante";return{url:a.url,name:/\.pdf$/i.test(a.name||"")?a.name:`Lettera_incarico_${i}.pdf`}}function Wh({event:t,participant:a}){return{contesto:{tipo:"evento",id:(t==null?void 0:t.id)||"",titolo:(t==null?void 0:t.title)||""},to:Dl,cc:Tl,subject:qh(t,a),body:Uh(t,a),files:[Pl(a)].filter(Boolean)}}function Vh({event:t,participants:a}){return{contesto:{tipo:"evento",id:(t==null?void 0:t.id)||"",titolo:(t==null?void 0:t.title)||""},to:Dl,cc:Tl,subject:Bh(t,a),body:Gh(t,a),files:a.map(Pl).filter(Boolean)}}function Hh({onBack:t}){const{t:a}=X(),[i,n]=f.useState([]),[o,s]=f.useState(!0),[l,r]=f.useState(null);f.useEffect(()=>{const g=Ye(ft(Ie(te,Ke.events),mn("created_at","desc")),h=>{n(h.docs.map(p=>({id:p.id,...p.data()}))),s(!1)},h=>{console.error("[team-events] subscribe",h),s(!1)});return()=>g()},[]);async function d(){const g=pn();await _e(oe(te,Ke.events,g),{id:g,type:"conference",title:"",type_other_label:"",date_start:"",date_end:"",location:"",description:"",participants:[],materials:[],created_at:ie(),updated_at:ie()}),r(g)}async function m(g,h){await _e(oe(te,Ke.events,g),{...h,updated_at:ie()},{merge:!0})}async function c(g){if(await Na(`${a("Eliminare definitivamente","Permanently delete")} "${g.title||a("(senza titolo)","(untitled)")}" ${a("e tutti i suoi file?","and all its files?")}`))try{await gt(oe(te,Ke.events,g.id))}catch(h){alert(a("Eliminazione fallita: ","Deletion failed: ")+(h.message||h))}}return e.jsxs(e.Fragment,{children:[e.jsx("section",{className:"mt-band mt-band-dark",children:e.jsxs("div",{className:"mt-wrap",children:[e.jsxs("button",{className:"btn btn-ghost btn-sm mt-back reveal",onClick:t,children:[e.jsx(Wa,{size:14})," ",a("Indietro","Back")]}),e.jsxs("div",{className:"mt-section-head reveal","data-d":"1",style:{alignItems:"flex-start"},children:[e.jsxs("div",{children:[e.jsx("p",{className:"mt-eyebrow",children:a("Research Team","Research Team")}),e.jsx("h1",{className:"mt-section-title",children:a("Convegni & workshop","Conferences & workshops")}),e.jsx("p",{className:"mt-section-sub",children:a("Eventi, convegni, workshop e seminari del progetto. Per ogni evento puoi aggiungere partecipanti, allegare preventivi e documenti ufficiali, e generare automaticamente la lettera di conferimento incarico in PDF.","Project events, conferences, workshops and seminars. For each event you can add participants, attach quotes and official documents, and automatically generate the assignment letter in PDF.")})]}),e.jsxs("button",{className:"btn btn-primary",onClick:d,children:[e.jsx(Le,{size:14})," ",a("Nuovo evento","New event")]})]})]})}),e.jsx("section",{className:"mt-band mt-band-tight",children:e.jsx("div",{className:"mt-wrap",children:o?e.jsx("div",{className:"mt-card mt-empty reveal",children:a("Caricamentoâ¦","Loadingâ¦")}):i.length===0?e.jsxs("div",{className:"mt-card mt-empty reveal",children:[a("Ancora nessun evento. Clicca","No events yet. Click")," ",e.jsxs("strong",{children:["+ ",a("Nuovo evento","New event")]})," ",a("per crearne uno.","to create one.")]}):e.jsx("div",{className:"reveal mt-list-stack mt-list-stack-rows",children:i.map(g=>e.jsx(Kh,{ev:g,autoOpen:l===g.id,onPatch:h=>m(g.id,h),onRemove:()=>c(g)},g.id))})})})]})}function Kh({ev:t,autoOpen:a,onPatch:i,onRemove:n}){const{t:o,lang:s}=X(),l=Ar.find(_=>_.value===t.type),r=(l?s==="en"&&l.labelEn?l.labelEn:l.label:null)||t.type_other_label||o("Evento","Event"),d=Xh(t.date_start,t.date_end),{openMask:m,update:c,close:g,masks:h}=Va(),p="event-"+t.id,x=h.some(_=>_.id===p),b=e.jsx(hi,{size:18}),u=t.title||o("Evento senza titolo","Untitled event"),w=e.jsx("div",{className:"slideover-panel",children:e.jsx(Jh,{ev:t,onPatch:i,onRemove:n})});f.useEffect(()=>{x&&c(p,{title:u,icon:b,content:w})},[x,u,w]);const v=f.useRef(!1);f.useEffect(()=>{v.current||(v.current=!0,a&&m({id:p,title:u,icon:b,content:w}))},[]);function j(){x?g(p):m({id:p,title:u,icon:b,content:w})}return e.jsxs("article",{className:"mt-listrow mt-listrow-event"+(x?" is-open":""),role:"button",tabIndex:0,"aria-expanded":x,onClick:_=>{_.target.closest("button, a, input, select, textarea")||j()},onKeyDown:_=>{(_.key==="Enter"||_.key===" ")&&(_.preventDefault(),j())},children:[e.jsx("span",{className:"mt-listrow-cell mt-listrow-primary",children:e.jsx("strong",{className:"mt-listrow-title",children:t.title||e.jsx("span",{className:"mt-listrow-ph",children:o("senza titolo","untitled")})})}),e.jsx("span",{className:"mt-listrow-cell mt-listrow-date",children:d?e.jsxs(e.Fragment,{children:[e.jsx(hi,{size:11,className:"mt-icon-bl"})," ",d]}):"â"}),e.jsx("span",{className:"mt-listrow-cell mt-listrow-person",children:t.location?e.jsxs(e.Fragment,{children:[e.jsx(pi,{size:11,className:"mt-icon-bl"})," ",t.location]}):"â"}),e.jsxs("span",{className:"mt-listrow-cell mt-listrow-counts",children:[e.jsxs("span",{title:o("Partecipanti","Participants"),children:[e.jsx(ia,{size:11,className:"mt-icon-bl"})," ",(t.participants||[]).length]}),e.jsxs("span",{title:o("Documenti","Documents"),children:[e.jsx(Ue,{size:11,className:"mt-icon-bl"})," ",(t.materials||[]).length]})]}),e.jsx("span",{className:"mt-listrow-cell mt-listrow-chips",children:e.jsx("span",{className:"chip mt-chip-sm",children:r})}),e.jsxs("button",{type:"button",className:"mt-listrow-open",onClick:_=>{_.stopPropagation(),j()},"aria-label":x?o("Chiudi dettaglio evento","Close event detail"):o("Apri dettaglio evento","Open event detail"),children:[o(x?"Aperto":"Apri","Open"),e.jsx(yt,{size:15})]})]})}function Jh({ev:t,onPatch:a,onRemove:i}){const{t:n,lang:o}=X();function s(r,d){a({[r]:d})}const l=t.type==="other";return e.jsxs("div",{className:"mt-row-editor",children:[e.jsxs("div",{className:"mt-mission-row",children:[e.jsx(He,{label:n("Tipo","Type"),children:e.jsx(xe,{tone:"inherit",value:t.type||"conference",onChange:r=>s("type",r),ariaLabel:n("Tipo","Type"),options:Ar.map(r=>({value:r.value,label:o==="en"&&r.labelEn?r.labelEn:r.label}))})}),l&&e.jsx(He,{label:n("Specifica","Specify"),wide:!0,children:e.jsx(se,{className:"input",value:t.type_other_label||"",onChange:r=>s("type_other_label",r.target.value),placeholder:n("es. Tavola rotonda, lectio magistralis, â¦","e.g. Round table, lectio magistralis, â¦")})}),e.jsx(He,{label:n("Data inizio","Start date"),children:e.jsx(Pe,{className:"input",value:t.date_start||"",onChange:r=>s("date_start",r.target.value)})}),e.jsx(He,{label:n("Data fine (se più giorni)","End date (if multi-day)"),children:e.jsx(Pe,{className:"input",value:t.date_end||"",onChange:r=>s("date_end",r.target.value)})})]}),e.jsx(He,{label:n("Titolo dell'evento","Event title"),children:e.jsx(se,{className:"input",value:t.title||"",onChange:r=>s("title",r.target.value),placeholder:"es. Climate Litigation Summer School 2026"})}),e.jsxs("div",{className:"mt-mission-row",children:[e.jsx(He,{label:n("Orario di inizio (testo libero)","Start time (free text)"),children:e.jsx(se,{className:"input",value:t.event_time_start||"",onChange:r=>s("event_time_start",r.target.value),placeholder:n("es. ore 10.30","e.g. 10:30")})}),e.jsx(He,{label:n("Sede","Venue"),wide:!0,children:e.jsx(se,{className:"input",value:t.location||"",onChange:r=>s("location",r.target.value),placeholder:n("es. Sala Convegni della Biblioteca dell'Ateneo - Bari","e.g. University Library Conference Hall - Bari")})})]}),e.jsx(He,{label:n("Direttore del Dipartimento (firmatario della lettera)","Director of the Department (letter signatory)"),children:e.jsx(se,{className:"input",value:t.director_name||"",onChange:r=>s("director_name",r.target.value),placeholder:n("es. Prof. Paolo Pardolesi (lascia vuoto se firma manuale)","e.g. Prof. Paolo Pardolesi (leave empty for manual signature)")})}),e.jsx(He,{label:n("Descrizione (opzionale)","Description (optional)"),children:e.jsx(se,{as:"textarea",className:"textarea",rows:3,value:t.description||"",onChange:r=>s("description",r.target.value)})}),e.jsx(bh,{label:n("Documenti dell'evento","Event documents"),hint:n("preventivi, programma, locandina, accordi","quotes, programme, poster, agreements"),storagePrefix:`team-events/${t.id}/materials`,files:t.materials||[],onChange:r=>a({materials:r}),emptyHint:n("Nessun documento allegato all'evento.","No documents attached to the event.")}),e.jsx(Yh,{ev:t,onPatch:a}),e.jsx("div",{className:"mt-foot-divider",children:e.jsxs("button",{className:"btn btn-ghost btn-sm mt-row-delete",onClick:i,children:[e.jsx($e,{size:12})," ",n("Elimina evento","Delete event")]})})]})}function Yh({ev:t,onPatch:a}){const{t:i}=X(),n=t.participants||[],[o,s]=f.useState(!1),[l,r]=f.useState(null);function d(){a({participants:[...n,Id()]})}function m(p){a({participants:n.filter(x=>x.id!==p)})}function c(p,x){a({participants:n.map(b=>b.id===p?{...b,...x}:b)})}async function g(){if(!n.length)return;const p=n.filter(w=>{var v;return!((v=w.generated_letter)!=null&&v.url)});if(!p.length){alert(i("Tutti i partecipanti hanno già la lettera generata.","All participants already have a generated letter."));return}if(!await Na(`${i("Generare e salvare la lettera per","Generate and save the letter for")} ${p.length} ${i("partecipanti?","participants?")}`))return;s(!0);let x=0,b=0;const u=[];
449for(const w of p)try{const{blob:v,filename:j}=await nn({event:t,participant:w}),_=`team-events/${t.id}/participants/${w.id}/generated.pdf`,C=new File([v],"generated.pdf",{type:"application/pdf"}),y=await ze(_,C);await c(w.id,{generated_letter:{url:y.url,path:y.path,name:j,size:v.size}}),x++}catch(v){b++,u.push(`⢠${w.last_name||w.first_name||"?"}: ${v.message||v}`)}s(!1),alert(`${i("Generate","Generated")} ${x} ${i("lettere.","letters.")}`+(b?` 450${b} ${i("errori:","errors:")} 451${u.join(` 452`)}`:""))}async function h(){if(!n.length)return;const p=n.filter(v=>{var j;return!((j=v.generated_letter)!=null&&j.url)}),x=p.length?`${i("Genererò","I will generate")} ${p.length} ${i("lettere mancanti, poi aprirò UNA mail cumulativa per","missing letters, then open ONE cumulative email for")} ${n.length} ${i("partecipanti. Procedo?","participants. Proceed?")}`:`${i("Aprirò UNA mail cumulativa per","I will open ONE cumulative email for")} ${n.length} ${i("partecipanti. Procedo?","participants. Proceed?")}`;if(!await Na(x))return;s(!0);const b=[],u=new Map;for(const v of p)try{const{blob:j,filename:_}=await nn({event:t,participant:v}),C=`team-events/${t.id}/participants/${v.id}/generated.pdf`,y=new File([j],"generated.pdf",{type:"application/pdf"}),z=await ze(C,y),T={url:z.url,path:z.path,name:_,size:j.size};await c(v.id,{generated_letter:T}),u.set(v.id,T)}catch(j){b.push(`⢠${v.last_name||v.first_name||"?"}: ${j.message||j}`)}const w=new Date().toISOString();for(const v of n)try{await c(v.id,{email_sent_at:w})}catch{}s(!1),b.length&&alert(`${b.length} ${i("errori in generazione:","generation errors:")} 453${b.join(` 454`)} 455 456${i("Apro comunque la mail cumulativa.","Opening the cumulative email anyway.")}`),r({...Vh({event:t,participants:n.map(v=>u.has(v.id)?{...v,generated_letter:u.get(v.id)}:v)}),onEsito:async v=>{for(const j of n)try{await c(j.id,{invio_segreteria:v})}catch{}}})}return e.jsxs("div",{className:"mt-mat-block",children:[l&&e.jsx(Da,{info:l,onClose:()=>r(null)}),e.jsxs("div",{className:"mt-mat-head mt-mat-head-split mt-mat-head-wrap",children:[e.jsxs("div",{children:[e.jsx("span",{className:"label",children:i("Partecipanti","Participants")}),e.jsxs("span",{className:"muted text-xs mt-partecipanti-count",children:[n.length," ",n.length===1?i("partecipante","participant"):i("partecipanti","participants")]})]}),e.jsxs("div",{className:"mt-section-actions-row mt-section-actions-row-tight",children:[n.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"btn btn-ghost btn-sm",onClick:g,disabled:o,title:i("Genera e salva la lettera per ogni partecipante che non ce l'ha ancora","Generate and save the letter for every participant who does not have one yet"),children:[e.jsx(st,{size:12})," ",o?"â¦":i("Genera tutte","Generate all")]}),e.jsxs("button",{className:"btn btn-primary btn-sm",onClick:h,disabled:o,title:i("Genera/salva tutte le lettere mancanti, poi apre il client di posta con UNA email cumulativa che riepiloga tutti i partecipanti â allega manualmente i PDF appena scaricati","Generate/save all missing letters, then open the mail client with ONE cumulative email summarising all participants â attach the just-downloaded PDFs manually"),children:[e.jsx(We,{size:12})," ",o?"â¦":i("Invia tutte DJSGE","Send all DJSGE")]})]}),e.jsxs("button",{className:"btn btn-secondary btn-sm",onClick:d,children:[e.jsx(Le,{size:12})," ",i("Aggiungi partecipante","Add participant")]})]})]}),n.length===0?e.jsxs("div",{className:"mt-mat-empty muted text-xs",children:[i("Ancora nessun partecipante. Clicca","No participants yet. Click")," ",e.jsxs("strong",{children:["+ ",i("Aggiungi partecipante","Add participant")]})," ",i("per iniziare.","to get started.")]}):e.jsx("div",{className:"mt-participant-stack",children:n.map((p,x)=>e.jsx(Zh,{index:x,event:t,p,onUpdate:b=>c(p.id,b),onRemove:()=>m(p.id)},p.id))})]})}function Zh({index:t,event:a,p:i,onUpdate:n,onRemove:o}){const{t:s}=X(),[l,r]=f.useState(null);function d(u,w){n({[u]:w})}function m(){n({custom_fields:[...i.custom_fields||[],Ed()]})}function c(u){n({custom_fields:(i.custom_fields||[]).filter(w=>w.id!==u)})}
456function g(u,w){n({custom_fields:(i.custom_fields||[]).map(v=>v.id===u?{...v,...w}:v)})}async function h({saveCopy:u}={}){try{const{blob:w,filename:v}=await nn({event:a,participant:i});if(u){const j=`team-events/${a.id}/participants/${i.id}/generated.pdf`,_=new File([w],"generated.pdf",{type:"application/pdf"}),C=await ze(j,_);n({generated_letter:{url:C.url,path:C.path,name:v,size:w.size}})}}catch(w){alert(s("Generazione PDF non riuscita: ","PDF generation failed: ")+(w.message||w))}}async function p(u){const w=`team-events/${a.id}/participants/${i.id}/signed.pdf`,v=await ze(w,u);n({signed_letter:{url:v.url,path:v.path,name:u.name,size:u.size}})}async function x(){var u;(u=i.signed_letter)!=null&&u.path&&await de(i.signed_letter.path),n({signed_letter:null})}async function b(){var w;let u=i;if(!((w=u.generated_letter)!=null&&w.url))try{const{blob:v,filename:j}=await nn({event:a,participant:i}),_=`team-events/${a.id}/participants/${i.id}/generated.pdf`,C=new File([v],"generated.pdf",{type:"application/pdf"}),y=await ze(_,C),z={url:y.url,path:y.path,name:j,size:v.size};n({generated_letter:z}),u={...i,generated_letter:z}}catch(v){alert(s("Generazione lettera non riuscita: ","Letter generation failed: ")+(v.message||v));return}r({...Wh({event:a,participant:u}),onEsito:v=>n({invio_segreteria:v})}),n({email_sent_at:new Date().toISOString()})}return e.jsxs("div",{className:"mt-card mt-participant-card",children:[l&&e.jsx(Da,{info:l,onClose:()=>r(null)}),e.jsx(_i,{invio:i.invio_segreteria}),e.jsxs("div",{className:"mt-participant-head",children:[e.jsxs("span",{className:"muted text-xs",children:["#",t+1]}),e.jsxs("strong",{className:"mt-participant-title",children:[i.title," ",i.first_name," ",i.last_name," ",!i.first_name&&!i.last_name&&e.jsx("em",{className:"muted",children:s("â compila i dati","â fill in the data")})]}),i.email_sent_at&&e.jsxs("span",{className:"chip chip-success mt-chip-sm-inline",title:`${s("Email a DJSGE inviata il","Email to DJSGE sent on")} ${new Date(i.email_sent_at).toLocaleString("it-IT")}`,children:[e.jsx(We,{size:11})," ",s("inviata DJSGE","sent DJSGE")]}),e.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>h({saveCopy:!1}),title:s("Genera e scarica soltanto (senza salvare nella maschera né aprire l'email)","Generate and download only (without saving to the editor or opening the email)"),children:[e.jsx(st,{size:12})," ",s("Genera PDF","Generate PDF")]}),e.jsxs("button",{type:"button",className:"btn btn-primary btn-sm",onClick:b,title:s("Genera, scarica, salva la copia nella maschera e apre il client di posta","Generate, download, save the copy in the editor and open the mail client"),children:[e.jsx(We,{size:12})," ",s("Invia DJSGE","Send DJSGE")]}),e.jsx("button",{type:"button",className:"btn btn-ghost btn-sm mt-row-delete",onClick:o,children:e.jsx($e,{size:12})})]}),e.jsxs("div",{className:"mt-mission-row",children:[e.jsx(He,{label:s("Titolo","Title"),children:e.jsx(xe,{tone:"inherit",value:i.title||"",onChange:u=>d("title",u),ariaLabel:s("Titolo","Title"),options:[{value:"",label:"â"},...Pd]})}),e.jsx(He,{label:s("Nome","First name"),children:e.jsx(se,{className:"input",value:i.first_name||"",onChange:u=>d("first_name",u.target.value)})}),e.jsx(He,{label:s("Cognome","Last name"),children:e.jsx(se,{className:"input",value:i.last_name||"",onChange:u=>d("last_name",u.target.value)})})]}),e.jsxs("div",{className:"mt-mission-row",children:[e.jsx(He,{label:s("Università / Istituzione","University / Institution"),wide:!0,children:e.jsx(se,{className:"input",value:i.institution||"",onChange:u=>d("institution",u.target.value),placeholder:s("es. Università di Bari Aldo Moro","e.g. University of Bari Aldo Moro")})}),e.jsx(He,{label:"Email",children:e.jsx(se,{className:"input",type:"email",value:i.email||"",onChange:u=>d("email",u.target.value)})})]}),e.jsxs(He,{label:s('Cosa farà al convegno (frase completa, segue "nel corso del quale")','What they will do at the event (full sentence, follows "during which")'),children:[e.jsx(se,{as:"textarea",className:"textarea",rows:2,value:i.intervention_phrase||"",onChange:u=>d("intervention_phrase",u.target.value),placeholder:s("es. terrà una Keynote Lecture dal titolo {{i}}«Staying Within One's Fair Shareâ¦Â»{{/i}} · oppure: presiederà la sessione di apertura","e.g. will give a Keynote Lecture titled {{i}}«Staying Within One's Fair Shareâ¦Â»{{/i}} · or: will chair the opening session")}),e.jsxs("div",{className:"muted text-xs",style:{marginTop:4},children:[s("Usa","Use")," ",e.jsxs("code",{children:["{{i}}","â¦","{{/i}}"]})," ",s("per il corsivo (es. il titolo dellâintervento). Apostrofi e virgolette diritti vengono convert
456iti automaticamente.","for italics (e.g. the talk title). Straight apostrophes and quotes are converted automatically.")]})]}),e.jsx(He,{label:s("Compenso lordo (â¬, opzionale)","Gross honorarium (â¬, optional)"),children:e.jsx(se,{className:"input",inputMode:"decimal",value:i.honorarium_eur||"",onChange:u=>d("honorarium_eur",u.target.value),placeholder:s("vuoto = a titolo gratuito","empty = free of charge")})}),e.jsxs("div",{className:"mt-custom-fields",children:[e.jsxs("div",{className:"mt-mat-head mt-mat-head-split",children:[e.jsx("span",{className:"muted text-xs mt-custom-fields-label",children:s("Campi aggiuntivi","Additional fields")}),e.jsxs("button",{className:"btn btn-ghost btn-sm",onClick:m,children:[e.jsx(Le,{size:11})," ",s("Campo","Field")]})]}),(i.custom_fields||[]).length===0?e.jsx("div",{className:"muted text-xs mt-custom-fields-empty",children:s("Aggiungi un campo libero per dati extra (es. CF, partita IVA, IBAN, telefonoâ¦).","Add a free field for extra data (e.g. tax code, VAT number, IBAN, phoneâ¦).")}
456):e.jsx("div",{className:"mt-bullet-list",children:(i.custom_fields||[]).map(u=>e.jsxs("div",{className:"mt-custom-field-row",children:[e.jsx(se,{className:"input mt-custom-field-label",placeholder:s("Etichetta","Label"),value:u.label,onChange:w=>g(u.id,{label:w.target.value})}),e.jsx(se,{className:"input mt-custom-field-value",placeholder:s("Valore","Value"),value:u.value,onChange:w=>g(u.id,{value:w.target.value})}),e.jsx("button",{type:"button",className:"btn btn-ghost btn-sm mt-row-delete",onClick:()=>c(u.id),children:e.jsx(Ce,{size:12})})]},u.id))})]}),e.jsxs("div",{className:"mt-pdf-pair mt-pdf-pair-tight",children:[e.jsx(Ko,{title:s("Lettera generata (non firmata)","Generated letter (unsigned)"),subtitle:s("copia salvata della lettera auto-generata","saved copy of the auto-generated letter"),file:i.generated_letter,onRemove:async()=>{var u;if((u=i.generated_letter)!=null&&u.path)try{await de(i.generated_letter.path)}catch{}n({generated_letter:null})}}),e.jsx(Ko,{title:s("Lettera firmata","Signed letter"),subtitle:s("carica il PDF dopo le firme di PI e Direttore","upload the PDF after the PI and Director have signed"),file:i.signed_letter,canUpload:!0,onUpload:p,onRemove:x})]})]})}function Ko({title:t,subtitle:a,file:i,canUpload:n,onUpload:o,onRemove:s}){const{t:l}=X(),[r,d]=f.useState(!1);async function m(c){var h;const g=(h=c.target.files)==null?void 0:h[0];if(g){d(!0);try{await o(g)}catch(p){alert(l("Caricamento non riuscito: ","Upload failed: ")+(p.message||p))}finally{d(!1),c.target.value=""}}}return e.jsxs("div",{className:"mt-card mt-pdf-mini mt-pdf-mini-compact",children:[e.jsx("div",{className:"muted text-xs mt-pdf-mini-title",children:t}),e.jsx("div",{className:"muted text-xs mt-pdf-mini-sub",children:a}),i!=null&&i.url?e.jsxs("div",{className:"mt-pdf-mini-row",children:[e.jsxs("a",{href:Je(i.url),target:"_blank",rel:"noreferrer",className:"btn btn-ghost btn-sm mt-pdf-mini-link",children:[e.jsx(Ue,{size:12})," ",i.name||l("documento.pdf","document.pdf")]}),e.jsx("button",{type:"button",className:"btn btn-ghost btn-sm mt-pdf-mini-x",onClick:s,children:"Ã"})]}):n?e.jsxs("label",{className:"btn btn-secondary btn-sm mt-pdf-mini-upload",children:[r?l("Caricamentoâ¦","Loadingâ¦"):l("+ carica PDF firmato","+ upload signed PDF"),e.jsx("input",{type:"file",accept:"application/pdf",onChange:m,className:"mt-hidden-input",disabled:r})]}):e.jsx("div",{className:"muted text-xs",children:l("â nessun file â","â no file â")})]})}function He({label:t,children:a,wide:i}){return e.jsxs("div",{className:"mt-field"+(i?" is-wide":""),children:[e.jsx("label",{className:"label",children:t}),a]})}function Xh(t,a){return!t&&!a?"":t&&a&&t!==a?`${La(t)} â ${La(a)}`:La(t||a)}const Qh={chiave:"rt.acquisti",tipo:"form",titolo:"Richiesta di acquisto beni o servizi"};function ef(t){return t==null||t===""?NaN:parseFloat(String(t).replace(",","."))}async function tf(t){const a=await Pt(),i=new a({unit:"mm",format:"a4"}),n=await Gt();Wt(i,n);const o=da(i,n),s=(t.director_name||"").trim()||Ir,l=(t.requester_name||"").trim()||bi,r=(t.requester_qualifica||"").trim()||"Principal Investigator",d=(t.upb||"").trim()||ji,m=ef(t.amount),c=isFinite(m)&&m>0?`⬠${ua(m)}`:"⬠___________",g=(t.affidamento_ditta||"").trim(),h=(t.affidamento_motivazioni||"").trim();zs(i,o,["Alla c.a. del","Direttore del Dipartimento Jonico",s],{gap:12}),jt(i,o,"RICHIESTA DI ACQUISTO BENI O SERVIZI",{gap:10});const p={align:"justify"};ee(i,o,`Il sottoscritto ${l}, qualifica ${r}.`,p),ee(i,o,`Per la realizzazione del Progetto di Ricerca FIS 3 CLIMPACT â ${Hi}, CUP ${ks}`,p),jt(i,o,"CHIEDE",{size:Me+1,gap:4,font:"bold"});const x=(t.goods_service||"").trim()||"[descrizione bene/servizio da inserire]";ee(i,o,`che si provveda, secondo le procedure amministrative di cui alla normativa vigente, allâacquisto del bene/servizio: ${x}, specificato nellâallegata scheda.`,p),ee(i,o,`Lâimporto presunto del suddetto acquisto a carico del Dipartimento è di ${c} e graverà sui seguenti fondi:`,p),Ma(i,o,`UPB ${d}`,{font:"bold"}),o.advance(2),ee(i,o,"Il sottoscritto dichiara, sotto la personale responsabilità , consapevole delle conseguenze civili e pe
456nali cui incorre in caso di dichiarazioni false o mendaci, che il predetto acquisto ha stretta attinenza con il progetto sopra specificato.",p),g&&(ee(i,o,`Il sottoscritto chiede di procedere ad affidamento diretto della ditta ${g} per le seguenti motivazioni: ${h||"[motivazioni da inserire]"}.`,p),ee(i,o,`Dichiara lâinsussistenza di rapporti di parentela o affinità con il titolare, gli amministratori, i soci e i dipendenti della ditta ${g} e comunque lâinsussistenza di qualsiasi situazione di conflitto di interessi, anche potenziale (legge 190/2012).`,p)),o.advance(8),o.needSpace(je*3+14);const b=o.y;return i.setFont(fe,"normal"),i.setFontSize(Me),i.setTextColor("#1d1d1f"),i.text("Visto, si autorizza",Ne,b),i.text("Il Direttore",Ne,b+je),i.text(s,Ne,b+je*2+12),i.text("Il Richiedente",Oe,b,{align:"right"}),i.text(l,Oe,b+je*2+12,{align:"right"}),o.y=b+je*2+12+je+6,o.advance(6),i.setFont(fe,"normal"),i.setFontSize(Me-1),i.text("Il titolare dei fondi (se diverso dal richiedente)",Oe,o.y,{align:"right"}),o.advance(je+8),i.setDrawColor("#1d1d1f"),i.line(Oe-70,o.y,Oe,o.y),o.advance(8),i.setFont(fe,"normal"),i.setFontSize(Me),i.text(`Taranto, ${Ge(new Date)}`,Oe,o.y,{align:"right"}),i}async function af({item:t}){const a=await tf(t||{});return za(a,Qh)}const El="[email protected]",nf="[email protected]",Al=[nf,"[email protected]"].join(",");function $l(t){if(t==null||t==="")return"";const a=parseFloat(String(t).replace(",","."));return isFinite(a)?a.toLocaleString("de-DE",{minimumFractionDigits:2,maximumFractionDigits:2}):String(t)}function sf(t){return`[CLIMPACT] Richiesta di acquisto â ${(t.title||t.goods_service||"acquisto").slice(0,60)}`}function of(t){var m;const a=(t.requester_name||"Dott. Giuseppe Naglieri").trim(),i=(t.requester_qualifica||"Principal Investigator").trim(),n=(t.goods_service||"[descrizione bene/servizio]").trim(),o=$l(t.amount),s=(t.upb||"SIGIM.Prog.FIS3Climpact.Naglieri").trim(),l=(t.affidamento_ditta||"").trim(),r=((m=t.generated_pdf)==null?void 0:m.name)||"la richiesta in PDF",d=["Gentilissimi,","","in allegato la richiesta di acquisto beni/servizi predisposta nell'ambito del progetto di ricerca CLIMPACT (FIS 3 Starting Grant), che si chiede cortesemente di sottoporre alla firma del Direttore del Dipartimento.","","Dati di sintesi:",` ⢠Richiedente: ${a} (${i})`,` ⢠Bene/servizio: ${n}`];return o&&d.push(` ⢠Importo presunto: ⬠${o}`),d.push(` ⢠UPB: ${s}`),l&&d.push(` ⢠Affidamento diretto a: ${l}`),d.push("",`(Allegato: ${r})`,"","RingraziandoVi per la collaborazione, porgo i miei più cordiali saluti.","","â",a,i+" del progetto CLIMPACT","Università degli Studi di Bari Aldo Moro"),d.join(` 457`)}function rf({item:t}){return{to:El,cc:Al,subject:sf(t),body:of(t)}}function lf(t){var n;const a=(t.title||((n=t.figura_professionale)==null?void 0:n.slice(0,50))||"incarico").slice(0,60);return`[CLIMPACT] Attivazione procedura selettiva â ${t.n_contratti&&t.n_contratti>1?`n. ${t.n_contratti} contratti â `:""}${a}`}function cf(t){var g;const a=(t.figura_professionale||"[figura professionale]").trim(),i=a.length>200?a.slice(0,200)+"â¦":a,n=t.durata_mesi||"",o=t.ore_totali||"",s=$l(t.importo_eur),l=t.n_contratti||1,r=t.selection_mode==="solo_titoli"?"per titoli (max 100 punti)":"per titoli (50) e colloquio (50)",d=t.payment_mode==="unica"?"in unica soluzione":"in due tranche",m=((g=t.generated_pdf)==null?void 0:g.name)||"la richiesta in PDF",c=["Gentilissimi,","","in allegato la richiesta di attivazione di procedura selettiva per il conferimento di un incarico individuale con contratto di lavoro autonomo, predisposta nell'ambito del progetto di ricerca CLIMPACT (FIS 3 Starting Grant), che si chiede cortesemente di sottoporre alla firma del Direttore del Dipartimento.","","Dati di sintesi:",` ⢠N. contratti: ${l}`,` ⢠Figura professionale: ${i}`];return n&&c.push(` ⢠Durata: ${n} mesi${o?" ("+o+" ore)":""}`),s&&c.push(` ⢠Importo lordo onnicomprensivo: ⬠${s}`),c.push(` ⢠Modalità di selezione: ${r}`,` ⢠Modalità di pagamento: ${d}`,"",`(Allegato: ${m})`,"","RingraziandoVi per la collaborazione, porgo i miei più cordiali saluti.","","â","Dott. Giuseppe Naglieri","Principal Investigator del progetto CLIMPACT","Università degli Studi di Bari Aldo Moro"),c.join(` 458`)}function df({item:t}){return{to:El,cc:Al,subject:lf(t),body:cf(t)}}function Rl({it:t,onPatch:a,cartella:i,nomeDoc:n,nomePdf:o,generaBlob:s,infoMail:l,onApriMail:r}){var w,v,j,_,C;const{t:d}=X(),[m,c]=f.useState(!1),g=t.signed_requester_pdf,h=t.invio_segreteria||t.email_sent_at,p=Ga([!!((w=t.generated_pdf)!=null&&w.url),!!(g!=null&&g.url),!!h,!!((v=t.signed_pdf)!=null&&v.url)]);async function x(){c(!0);try{const y=await s(),z=await ze(`${i}/${t.id}/generated.pdf`,new File([y],o,{type:"application/pdf"}));await a({generated_pdf:{url:z.url,path:z.path,name:o,size:y.size}});const T=URL.createObjectURL(y),I=document.createElement("a");I.href=T,I.download=o,document.body.appendChild(I),I.click(),I.remove(),setTimeout(()=>URL.revokeObjectURL(T),3e4)}catch(y){alert(d("Generazione PDF non riuscita: ","PDF generation failed: ")+(y.message||y))}finally{c(!1)}}async function b(y,z,T){const I=await ze(`${i}/${t.id}/${z}`,T);await a({[y]:{url:I.url,path:I.path,name:T.name,size:T.size}})}async function u(y){var z;(z=t[y])!=null&&z.path&&await de(t[y].path),await a({[y]:null})}return e.jsxs("div",{className:"mt-passi-richiesta",children:[e.jsx(dt,{n:1,stato:p[0],titolo:d("Genera la richiesta","Generate the request"),sotto:d("Il PDF si scarica: va firmato e caricato al passo 2.","The PDF downloads: sign it and upload it at step 2."),children:e.jsx("div",{className:"mt-mission-actions-row",children:e.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:x,disabled:m,children:[m?e.jsx(me,{size:12,className:"spin"}):(j=t.generated_pdf)!=null&&j.url?e.jsx(on,{size:12}):e.jsx(st,{size:12})," ",(_=t.generated_pdf)!=null&&_.url?d("Rigenera PDF","Regenerate PDF"):d("Genera PDF","Generate PDF")]})})}),e.jsxs(dt,{n:2,stato:p[1],titolo:d("Firmala e caricala","Sign and upload it"),sotto:d("à la copia f
458irmata che parte alla Segreteria.","The signed copy is the one that goes to the Secretariat."),children:[((C=t.generated_pdf)==null?void 0:C.url)&&e.jsxs("a",{className:"mt-firme-bozza",href:Je(t.generated_pdf.url),target:"_blank",rel:"noreferrer",children:[e.jsx(qt,{size:13})," ",d(`${n.it} generata dal sistema, da firmare: ${t.generated_pdf.name||"PDF"}`,`${n.en} generated by the system, to be signed: ${t.generated_pdf.name||"PDF"}`)]}),e.jsx(Dt,{title:d(`${n.it} â firmata dal PI`,`${n.en} â signed by the PI`),subtitle:d("il PDF generato al passo 1, firmato","the PDF generated at step 1, signed"),file:g,canUpload:!0,canRemove:!0,emptyText:d("Non ancora caricata.","Not uploaded yet."),onUpload:y=>b("signed_requester_pdf","signed_requester.pdf",y),onRemove:()=>u("signed_requester_pdf")})]}),e.jsxs(dt,{n:3,stato:p[2],titolo:d("Invia alla Segreteria DJSGE","Send to the DJSGE Secretariat"),sotto:d("Si sblocca quando câè la copia firmata: prepara la mail con il PDF firmato allegato.","It unlocks once the signed copy is here: it prepares the email with the signed PDF attached."),children:[e.jsx(_i,{invio:t.invio_segreteria}),e.jsx("div",{className:"mt-mission-actions-row",children:e.jsxs("button",{type:"button",className:"btn btn-primary btn-sm anim-shimmer",disabled:!(g!=null&&g.url),onClick:()=>r({...l,onEsito:y=>a({invio_segreteria:y,email_sent_at:new Date().toISOString()}),files:[{url:g.url,name:g.name||o}]}),children:[e.jsx(We,{size:12})," ",d("Invia alla Segreteria DJSGE","Send to the DJSGE Secretariat")]})})]}),e.jsx(dt,{n:4,stato:p[3],titolo:d("Firmata dal Direttore","Signed by the Director"),sotto:d("La versione finale restituita dalla Segreteria DJSGE.","The final version returned by the DJSGE Secretariat."),children:e.jsx("div",{className:"mt-mission-pdfs",children:e.jsx(Dt,{title:d(`${n.it} â firmata dal Direttore`,`${n.en} â signed by the Director`),subtitle:d("versione finale restituita dalla Segreteria DJSGE","final version returned by the DJSGE Secretariat"),file:t.signed_pdf,canUpload:!0,canRemove:!0,onUpload:y=>b("signed_pdf","signed.pdf",y),onRemove:()=>u("signed_pdf")})})})]})}const uf="[email protected]",Jo={fattura:"Fattura",affidamento:"Documenti dellâaffidamento",altro:"Altro documento"};async function Yn(t,a=!1){const{getFunctions:i,httpsCallable:n}=await Ae(async()=>{const{getFunctions:l,httpsCallable:r}=await import("./vendor-firebase-AOn3Fvmd.js").then(d=>d.ah);return{getFunctions:l,httpsCallable:r}},[]),{app:o}=await Ae(async()=>{const{app:l}=await import("./firebase-config-Dn2Tu_JL.js").then(r=>r.c);return{app:l}},__vite__mapDeps([3,2]));return(await n(i(o,"europe-west1"),"ufficioLinkAcquisto")({purchaseId:t,registra:a})).data}function Yo(t){const a=Number(String(t||"").replace(",","."));return Number.isFinite(a)&&a>0?`⬠${a.toLocaleString("de-DE",{minimumFractionDigits:2,maximumFractionDigits:2})}`:""}function mf({it:t}){const{t:a}=X(),[i,n]=f.useState(null),[o,s]=f.useState(null),[l,r]=f.useState(null),d=Array.isArray(t.ufficio_docs)?t.ufficio_docs:[],c=(Array.isArray(t.ufficio_richieste)?t.ufficio_richieste:[]).map(x=>x.at).sort().pop();async function g(){n("mail"),s(null);try{const{url:x}=await Yn(t.id),b=t.title||t.goods_service||"richiesta di acquisto",u=[t.affidamento_ditta&&`affidamento a ${t.affidamento_ditta}`,Yo(t.amount)&&`importo ${Yo(t.amount)}`].filter(Boolean).join(", ");r({url:x,subject:`Acquisto «${b}»: fattura e documenti dellâaffidamento da caricare`,body:`Gentile Dott. Mazza, 459 460con riferimento alla richiesta di acquisto «${b}»${u?` (${u})`:""}, come da accordi Le chiedo cortesemente di voler caricare la fattura e i documenti dellâaffidamento tramite il collegamento riportato di seguito. 461 462La raccolta consente di conservare in un unico archivio digitale, in modo ordinato e completo, tutta la documentazione dellâacquisto ai fini della rendicontazione del progetto. 463 464Il collegamento è riservato a questo acquisto e non richiede credenziali di accesso. Resta attivo anche successivamente, per eventuali integrazioni della documentazione. 465 466Dalla stessa pagina è possibile consultare tutti gli acquisti del progetto e i documenti già caricati, inserendo il codice di accesso 04052026. 467 468La ringrazio per la collaborazione. 469 470Cordiali saluti, 471Giuseppe Naglieri 472Principal Investigator del progetto CLIMPACT (FIS 3) 473Università degli Studi di Bari Aldo Moro`})}catch(x){s({ok:!1,testo:a("Non riesco a preparare il collegamento: ","Could not prepare the link: ")+((x==null?void 0:x.message)||x)})}finally{n(null)}}async function h(){n("link"),s(null);try{const{url:x}=await Yn(t.id);await navigator.clipboard.writeText(x),s({ok:!0,testo:a("Collegamento copiato: si apre senza accesso.","Link copied: it opens without signing in.")})}catch(x){s({ok:!1,testo:a("Non riesco a preparare il collegamento: ","Could not prepare the link: ")+((x==null?void 0:x.message)||x)})}finally{n(null)}}async function p(){r(null);try{await Yn(t.id,!0)}catch(x){console.warn("[acquisto] registra",x)}s({ok:!0,testo:a("Mail partita. I file che lâufficio carica arr
473ivano qui.","Email sent. The files the office uploads arrive here.")})}return e.jsxs("div",{className:"mt-ufficio",children:[e.jsxs("div",{className:"mt-ufficio-head",children:[e.jsx("strong",{children:a("Fattura e documenti dellâaffidamento","Invoice and award documents")}),e.jsx("span",{className:"muted text-xs",children:a("Li carica lâufficio (Albino Mazza) da un collegamento, senza accesso. La richiesta parte quando la mandi tu.","The office (Albino Mazza) uploads them from a link, without signing in. The request goes out when you send it.")})]}),e.jsxs("div",{className:"mt-section-actions-row",children:[e.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:!!i,onClick:g,children:[i==="mail"?e.jsx(me,{size:12,className:"spin"}):e.jsx(We,{size:12})," ",a("Chiedi fattura e documenti a Mazza","Ask Mazza for the invoice and documents")]}),e.jsxs("button",{type:"button",className:"btn btn-ghost btn-sm",disabled:!!i,onClick:h,title:a("Copia lâindirizzo della pagina di caricamento, senza mandare nessuna mail.","Copies the address of the upload page, without sending any email."),children:[e.jsx(Tt,{size:12})," ",a("Copia il collegamento (senza mail)","Copy the link (no email)")]})]}),c&&e.jsxs("p",{className:"muted text-xs",children:[a("Richiesta inviata il ","Request sent on "),new Date(c).toLocaleDateString("it-IT",{day:"numeric",month:"long"}),"."]}),o&&e.jsxs("p",{className:"mt-ufficio-esito"+(o.ok?" is-ok":""),children:[o.ok&&e.jsx(ke,{size:13})," ",o.testo]}),e.jsx(Xr,{pratica:t,acquisto:!0}),d.length>0&&e.jsx("ul",{className:"mt-ufficio-docs",children:d.map(x=>e.jsx("li",{children:e.jsxs("a",{href:Je(x.url,{nome:x.name}),target:"_blank",rel:"noreferrer",children:[e.jsx(qt,{size:13})," ",e.jsx("strong",{children:Jo[x.kind]||Jo.altro})," ",x.name]})},x.id))}),l&&e.jsx(Ns,{open:!0,assetsPrivate:!0,onClose:()=>r(null),onSent:p,sendMail:Ra,loadRecipients:async()=>[],portalLabel:"Research Team",initialAudience:{mode:"custom",emails:uf},templates:[{id:"ufficio",label:a("Richiesta fattura e documenti allâufficio","Invoice and documents request to the office"),build:()=>l}],initialPrefill:{templateId:"ufficio"},wrapHtml:(x,b,u)=>Wi({heading:b,bodyHtml:x,headerGradient:u==null?void 0:u.headerGradient,ctaLabel:"Carica i documenti",ctaHref:l.url,manualLabel:"In alternativa, copiare questo indirizzo nel browser:",policyHref:"https://www.climpact.it/privacy"})})]})}const pf="TKuaPxLsEobzv43Bdj7jrzyaVjs2",hf=new Set(["missioni","personale"]);function ff(t){return`⬠${(Number(t)||0).toLocaleString("de-DE",{minimumFractionDigits:2,maximumFractionDigits:2})}`}function gf({it:t,onPatch:a}){var h;const{t:i}=X(),[n,o]=f.useState(null),[s,l]=f.useState(null);f.useEffect(()=>Ye(oe(te,"users",pf,"data","main"),p=>o(p.exists()?JSON.parse(p.data().value||"{}"):{}),p=>l((p==null?void 0:p.message)||String(p))),[]);const r=t.budget_link||null,d=((n==null?void 0:n.categories)||[]).filter(p=>!hf.has(p.id)),m=r!=null&&r.cat?((h=n==null?void 0:n.rows)==null?void 0:h[r.cat])||[]:[],c=m.filter(p=>p&&(!p.team_purchase_id||p.team_purchase_id===t.id)&&!p._rt_purchase_created),g=m.find(p=>p&&p.team_purchase_id===t.id);return e.jsxs("div",{className:"mt-ufficio mt-voce-budget"+(r!=null&&r.cat?"":" is-da-scegliere"),children:[e.jsxs("div",{className:"mt-ufficio-head",children:[e.jsx("strong",{children:r!=null&&r.cat?i("Voce di budget","Budget line"):i("A quale voce di budget va questo acquisto?","Which budget line does this purchase belong to?")}),e.jsx("span",{className:"muted text-xs",children:i("Scegli dove sta questa spesa nel budget del PI. Se câè già una riga scritta a mano, collegala invece di crearne unâaltra: da quel momento importo, stato e documenti la seguono da soli.","Choose where this cost sits in the PI budget. If a hand-written row already exists, link it instead of creating another: from then on amount, status and documents follow on their own.")})]}),s&&e.jsxs("p",{className:"mt-ufficio-esito",children:[i("Budget non raggiungibile: ","Budget not reachable: "),s]}),n&&e.jsxs("div",{className:"mt-mission-row",children:[e.jsx(xe,{tone:"inherit",value:(r==null?void 0:r.cat)||"",onChange:p=>
473a({budget_link:p?{cat:p,row_id:null}:null}),ariaLabel:i("Voce di budget","Budget line"),options:[{value:"",label:i("Non collegato al budget","Not linked to the budget")},...d.map(p=>({value:p.id,label:p.name||p.id}))]}),(r==null?void 0:r.cat)&&e.jsx(xe,{tone:"inherit",value:r.row_id||"",onChange:p=>a({budget_link:{cat:r.cat,row_id:p||null}}),ariaLabel:i("Riga","Row"),matchWidth:!1,options:[{value:"",label:i("Nuova riga","New row")},...c.map(p=>({value:p.id,label:`${p.desc||p.code||p.id} â ${ff(p.amount??p.cost)}`}))]})]}),g&&e.jsxs("p",{className:"muted text-xs",style:{display:"inline-flex",alignItems:"center",gap:6,margin:0},children:[e.jsx(Tt,{size:12})," ",i("Collegata alla riga «","Linked to row â"),g.desc||g.id,i("», stato ","â, status "),g.status||"â","."]})]})}async function xf(t){const a=await Pt(),i=new a({unit:"mm",format:"a4"}),n=await Gt();Wt(i,n);const o=da(i,n);o.advance(10),jt(i,o,"ATTESTAZIONE DI CONFORMITÃ",{gap:.5}),o.advance(je+6);const s={align:"justify"},l=String((t==null?void 0:t.department)||"").trim(),r=String((t==null?void 0:t.description)||"").trim()||"[descrizione bene/servizio da inserire]",d=String((t==null?void 0:t.supplier)||"").trim(),m=String((t==null?void 0:t.amount)||"").trim(),c=String((t==null?void 0:t.orderRef)||"").trim(),g=String((t==null?void 0:t.upb)||"").trim()||ji;let h=`Il sottoscritto ${bi}, in qualità di Principal Investigator del progetto di ricerca CLIMPACT (${Hi}), finanziato ${Fi} (CUP ${ks})`;l&&(h+=`, con riferimento all'acquisto di beni o servizi per il Dipartimento «${l}»`),ee(i,o,h,s),jt(i,o,"ATTESTA",{gap:.5,size:Me}),o.advance(je+2);let p=`di aver ricevuto il/i seguente/i bene/servizio: ${r}`;d&&(p+=`; fornitore: ${d}`),m&&(p+=`; importo: ${m}`),c&&(p+=`; rif. ordine/impegno: ${c}`),p+=";",ee(i,o,p,s),ee(i,o,`e DICHIARA che il/i medesimo/i è/sono conforme/i a quanto richiesto e ordinato, pienamente rispondente/i alle caratteristiche e alle quantità previste, e regolarmente funzionante/i, e che nulla osta alla liquidazione della relativa spesa a valere sui fondi del progetto (${g}).`,s),o.advance(2),ee(i,o,"In fede.",{gap:8});const x=t!=null&&t.date?Ge(t.date):Ge(new Date);return i.setFont(fe,"normal"),i.setFontSize(Me),i.setTextColor("#1d1d1f"),o.needSpace(je),i.text(`Taranto, ${x}`,Ne,o.y),o.advance(je+16),Cs(i,o,Cd,bi,{sigGap:14,gap:6}),i}const bf={chiave:"rt.conformita",tipo:"form",titolo:"Attestazione di conformità "};async function vf(t){return((t==null?void 0:t.description)||"conformita").replace(/[^A-Za-z0-9]+/g,"_").slice(0,40)}async function jf(t){const a=await xf(t||{});await ka(a,["Attestazione-conformita",await vf(t)],bf)}function yf(){const t=new Date,a=t.getFullYear(),i=String(t.getMonth()+1).padStart(2,"0"),n=String(t.getDate()).padStart(2,"0");return`${a}-${i}-${n}`}function _f({initial:t,onClose:a}){const{t:i}=X(),[n,o]=f.useState({department:(t==null?void 0:t.department)??Pr,description:(t==null?void 0:t.description)??"",supplier:(t==null?void 0:t.supplier)??"",amount:(t==null?void 0:t.amount)??"",orderRef:(t==null?void 0:t.orderRef)??"",date:(t==null?void 0:t.date)??yf()}),[s,l]=f.useState(!1),[r,d]=f.useState(null),m=g=>h=>o(p=>({...p,[g]:h.target.value}));async function c(){if(!String(n.description||"").trim()){d(i("La descrizione del bene/servizio è obbligatoria.","The goods/service description is required."));return}l(!0),d(null);try{await jf(n),a==null||a()}catch(g){d((g==null?void 0:g.message)||String(g))}finally{l(!1)}}return ra.createPortal(e.jsxs("div",{className:"modal-backdrop anim-scrim mt-dialog-host",role:"dialog","aria-modal":"true","aria-labelledby":"attc-title",onClick:g=>{g.target===g.currentTarget&&(a==null||a())},children:[e.jsxs("div",{className:"modal-panel anim-pop attc-panel portal-site",children:[e.jsxs("header",{className:"attc-head",children:[e.jsxs("div",{children:[e.jsx("div",{className:"attc-eyebrow",children:i("Research Team","Research Team")}),e.jsx("h2",{id:"attc-title",className:"attc-title",children:i("Attestazione di conformità ","Conformity attestation")}),e.jsx("p",{className:"attc-sub",children:i("Il Principal Investigator attesta di aver ricevuto un bene/servizio acquistato e che esso è conforme a quanto richiesto e ordinato. Lâheader MUR ufficiale è inserito automaticamente.","The Principal Investigator attests that a purchased good/service has been received and conforms to what was requested and ordered. The official MUR header is inserted automatically.")})]}),e.jsx("button",{type:"button",className:"attc-close",onClick:a,"aria-label":i("Chiudi","Close"),children:e.jsx(Ce,{size:16})})]}),e.jsxs("div",{className:"attc-body",children:[e.jsxs("div",{className:"attc-grid",children:[e.jsxs("label",{className:"attc-field attc-field-wide",children:[e.jsx("span",{children:i("Dipartimento","Department")}),e.jsx("input",{type:"text",value:n.department,onChange:m("department"),placeholder:i("es. Dipartimento Jonicoâ¦","e.g. Ionian Departmentâ¦")})]}),e.jsxs("label",{className:"attc-field attc-field-wide",children:[e.jsxs("span",{children:[i("Descrizione bene/servizio","Goods/service description")," *"]}),e.jsx("textarea",{rows:3,value:n.description,onChange:m("description"),placeholder:i('es. n. 1 notebook Apple MacBo
473ok Pro 14", come da ordine, in dotazione al progetto','e.g. 1 Apple MacBook Pro 14" notebook, as ordered, assigned to the project')}),e.jsx("em",{className:"attc-hint",children:i("Testo che entrerà nellâattestazione (obbligatorio).","Text that will appear in the attestation (required).")})]}),e.jsxs("label",{className:"attc-field",children:[e.jsx("span",{children:i("Fornitore (opzionale)","Supplier (optional)")}),e.jsx("input",{type:"text",value:n.supplier,onChange:m("supplier"),placeholder:i("es. Apple Italia S.r.l.","e.g. Apple Italia S.r.l.")})]}),e.jsxs("label",{className:"attc-field",children:[e.jsx("span",{children:i("Importo (opzionale)","Amount (optional)")}),e.jsx("input",{type:"text",value:n.amount,onChange:m("amount"),placeholder:i("es. ⬠1.999,00","e.g. ⬠1,999.00")})]}),e.jsxs("label",{className:"attc-field",children:[e.jsx("span",{children:i("Riferimento ordine/impegno (opzionale)","Order/commitment reference (optional)")}),e.jsx("input",{type:"text",value:n.orderRef,onChange:m("orderRef"),placeholder:i("es. ODA n. 123/2026","e.g. PO no. 123/2026")})]}),e.jsxs("label",{className:"attc-field",children:[e.jsx("span",{children:i("Data","Date")}),e.jsx(Pe,{value:n.date,onChange:m("date")})]})]}),r&&e.jsx("div",{className:"attc-error",role:"alert",children:r})]}),e.jsxs("footer",{className:"attc-foot",children:[e.jsx("button",{type:"button",className:"btn btn-secondary",onClick:a,disabled:s,children:i("Annulla","Cancel")}),e.jsxs("button",{type:"button",className:"btn btn-primary anim-shimmer",onClick:c,disabled:s,children:[s?e.jsx(me,{size:14,className:"spin"}):e.jsx(hn,{size:14}),s?i("Generazioneâ¦","Generatingâ¦"):i("Genera PDF","Generate PDF")]})]})]}),e.jsx("style",{children:` 474 /* CENTERED MODAL â mirrors the mission dialogs. Scoped with 475 :has(.attc-panel) so ONLY this dialog is affected, not other
476 .modal-backdrop modals. */ 477 .modal-backdrop:has(.attc-panel) { 478 position: fixed; 479 inset: 0; 480 z-index: 1000; 481 display: flex; 482 align-items: center; 483 justify-content: center; 484 padding: 24px; 485 } 486 /* Public-site LIGHT look over the forced-dark platform (renders over 487 <body>). WHITE card, hairline border, soft shadow; accent stays the 488 portal's --space-tint (indigo for Research Team). */ 489 .modal-panel.attc-panel { 490 background: #ffffff; 491 -webkit-backdrop-filter: none; 492 backdrop-filter: none; 493 border: 1px solid rgba(26, 35, 48, 0.12); 494 border-radius: 18px; 495 box-shadow: 0 24px 70px rgba(26, 35, 48, 0.28), 0 2px 8px rgba(26, 35, 48, 0.08); 496 color: #1a2330; 497 --bg-surface: #ffffff; 498 --bg-hover: rgba(26, 35, 48, 0.05); 499 --text-primary: #1a2330; 500 --text-secondary:#5a6678; 501 --text-tertiary: #8a94a3; 502 --border: rgba(26, 35, 48, 0.12); 503 --border-strong: rgba(26, 35, 48, 0.20); 504 } 505 .attc-panel { 506 width: min(640px, 96vw); 507 max-height: 90vh; 508 display: flex; 509 flex-direction: column; 510 font-family: inherit; 511 animation: attc-pop 200ms cubic-bezier(0.32, 0.72, 0, 1) both; 512 } 513 @keyframes attc-pop { 514 from { transform: translateY(10px) scale(0.985); opacity: 0; } 515 to { transform: none; opacity: 1; } 516 } 517 @media (prefers-reduced-motion: reduce) { 518 .attc-panel { animation: none; } 519 } 520 /* The RT portal has a base rule (ManagementTeam.css "KILL THE ROUND 521 MASKS") that reshapes EVERY .mt-dialog-host backdrop into a 522 right-anchored full-height SLIDE-OVER with high specificity + 523 !important. Re-centre THIS dialog by matching that selector shape 524 (+ :has(.attc-panel)) and !important so it decisively wins â scoped 525 to .attc-panel so no other RT dialog is touched. */ 526 body > .modal-backdrop.mt-dialog-host:has(.attc-panel), 527 .mt-shell-body .modal-backdrop:has(.attc-panel) { 528 align-items: center !important; 529 justify-content: center !important; 530 padding: 24px !important; 531 } 532 body > .modal-backdrop.mt-dialog-host > .modal-panel.attc-panel, 533 .mt-shell-body .modal-backdrop > .modal-panel.attc-panel { 534 width: min(640px, 96vw) !important; 535 max-width: 96vw !important; 536 height: auto !important; 537 max-height: 90vh !important; 538 margin: 0 !important; 539 border: 1px solid rgba(26, 35, 48, 0.12) !important; 540 border-radius: 18px !important; 541 box-shadow: 0 24px 70px rgba(26, 35, 48, 0.28), 0 2px 8px rgba(26, 35, 48, 0.08) !important; 542 animation: attc-pop 200ms cubic-bezier(0.32, 0.72, 0, 1) both !important; 543 } 544 .attc-head { 545 padding: 22px 26px 18px; 546 background: #ffffff; 547 border-bottom: 1px solid rgba(26, 35, 48, 0.12); 548 display: flex; 549 align-items: flex-start; 550 gap: 16px; 551 } 552 .attc-eyebrow { 553 font-family: var(--font-display); 554 font-size: 11px; 555 font-weight: 400; 556 letter-spacing: 0.16em; 557 text-transform: uppercase; 558 color: var(--space-tint, #2e84ff); 559 margin-bottom: 6px; 560 } 561 .attc-title { 562 margin: 0; 563 font-family: var(--font-display); 564 font-size: 22px; 565 font-weight: 400; 566 letter-spacing: -0.01em; 567 color: #1a2330; 568 } 569 .attc-sub { 570 margin: 8px 0 0; 571 font-size: 12.5px; 572 line-height: 1.55; 573 color: #5a6678; 574 max-width: 520px; 575 } 576 .attc-close { 577 margin-left: auto; 578 background: #ffffff; 579 border: 1px solid rgba(26, 35, 48, 0.12); 580 border-radius: 999px; 581 width: 32px; 582 height: 32px; 583 display: inline-flex; 584 align-items: center; 585 justify-content: center; 586 color: #5a6678; 587 cursor: pointer; 588 transition: color 0.18s ease, border-color 0.18s ease; 589 } 590 .attc-close:hover { color: #1a2330; border-color: rgba(26, 35, 48, 0.20); } 591 .attc-body { 592 padding: 18px 26px 22px; 593 overflow-y: auto; 594 flex: 1 1 auto; 595 background: #ffffff; 596 } 597 .attc-grid { 598 display: grid; 599 grid-template-columns: repeat(2, 1fr); 600 gap: 12px 14px; 601 } 602 .attc-field { 603 display: flex; 604 flex-direction: column; 605 gap: 5px; 606 font-family: inherit; 607 } 608 .attc-field-wide { grid-column: 1 / -1; } 609 .attc-field > span { 610 font-family: var(--font-display); 611 font-size: 10.5px; 612 font-weight: 400; 613 letter-spacing: 0.1em; 614 text-transform: uppercase; 615 color: #5a6678; 616 } 617 .attc-field input, 618 .attc-field textarea { 619 font-family: var(--site-body-font, inherit); 620 font-size: 13px; 621 padding: 10px 12px; 622 background: #ffffff; 623 color: #1a2330; 624 border: 1px solid rgba(26, 35, 48, 0.20); 625 border-radius: 12px; 626 outline: none; 627 transition: border-color 120ms ease, box-shadow 120ms ease; 628 width: 100%; 629 box-sizing: border-box; 630 } 631 .attc-field input::placeholder, 632 .attc-field textarea::placeholder { color: #5a6678; opacity: 0.7; } 633 .attc-field textarea { 634 resize: vertical; 635 min-height: 64px; 636 line-height: 1.5; 637 } 638 .attc-field input:focus, 639 .attc-field textarea:focus { 640 border-color: var(--space-tint, #2e84ff); 641 box-shadow: 0 0 0 3px color-mix(in srgb, var(--space-tint, #2e84ff) 20%, transparent); 642 } 643 .attc-hint { 644 font-style: normal; 645 font-size: 10.5px; 646 color: #8a94a3; 647 letter-spacing: 0; 648 text-transform: none; 649 } 650 .attc-error { 651 margin-top: 14px; 652 padding: 10px 13px; 653 background: color-mix(in srgb, #ef4444 8%, transparent); 654 border: 1px solid color-mix(in srgb, #ef4444 28%, transparent); 655 border-radius: 12px; 656 font-size: 12.5px; 657 color: #b91c1c; 658 } 659 /* Nessuna striscia in fondo: vedi la nota su .modal-foot in global.css. */ 660 .attc-foot { 661 padding: 16px 26px 20px; 662 background: transparent; 663 border-top: 0; 664 display: flex; 665 justify-content: flex-end; 666 gap: 10px; 667 } 668 @media (max-width: 640px) { 669 .attc-grid { grid-template-columns: 1fr; } 670 .attc-head, .attc-body, .attc-foot { padding-left: 18px; padding-right: 18px; }
671 .modal-backdrop:has(.attc-panel) { padding: 0; } 672 .attc-panel { width: 100vw; max-height: 100vh; } 673 .modal-panel.attc-panel { border: none; border-radius: 0; } 674 } 675 `})]}),document.body)}function Nf({onBack:t,me:a}){const{t:i}=X(),[n,o]=f.useState([]),[s,l]=f.useState(!0),[r,d]=f.useState(null),[m,c]=f.useState(null);f.useEffect(()=>{const x=Ye(ft(Ie(te,Ke.purchases),mn("created_at","desc")),b=>{o(b.docs.map(u=>({id:u.id,...u.data()}))),l(!1)},b=>{console.error("[purchases] subscribe",b),l(!1)});return()=>x()},[]);async function g(){const x=pn();await _e(oe(te,Ke.purchases,x),{id:x,title:"",requester_name:"Dott. Giuseppe Naglieri",requester_qualifica:"Principal Investigator",goods_service:"",amount:"",upb:"",affidamento_ditta:"",affidamento_motivazioni:"",director_name:"",created_at:ie(),updated_at:ie()}),d(x)}async function h(x,b){await _e(oe(te,Ke.purchases,x),{...b,updated_at:ie()},{merge:!0})}async function p(x){var b,u,w;if(await Na(`${i("Eliminare","Delete")} "${x.title||x.goods_service||i("(senza titolo)","(untitled)")}" ${i("e i suoi file?","and its files?")}`))try{(b=x.generated_pdf)!=null&&b.path&&await de(x.generated_pdf.path),(u=x.signed_pdf)!=null&&u.path&&await de(x.signed_pdf.path),(w=x.signed_requester_pdf)!=null&&w.path&&await de(x.signed_requester_pdf.path),await gt(oe(te,Ke.purchases,x.id))}catch(v){alert(i("Eliminazione fallita: ","Deletion failed: ")+(v.message||v))}}return e.jsxs(e.Fragment,{children:[e.jsx("section",{className:"mt-band mt-band-dark",children:e.jsxs("div",{className:"mt-wrap",children:[e.jsxs("button",{className:"btn btn-ghost btn-sm mt-back reveal",onClick:t,children:[e.jsx(Wa,{size:14})," ",i("Indietro","Back")]}),e.jsxs("div",{className:"mt-section-head reveal","data-d":"1",style:{alignItems:"flex-start"},children:[e.jsxs("div",{children:[e.jsx("p",{className:"mt-eyebrow",children:i("Research Team","Research Team")}),e.jsx("h1",{className:"mt-section-title",children:i("Acquisti","Procurement")}),e.jsxs("p",{className:"mt-section-sub",children:[i("Richieste di acquisto beni/servizi al Direttore del Dipartimento. Compila i campi â clicca","Goods/services purchase requests to the Director of the Department. Fill in the fields â click")," ",e.jsx("strong",{children:i("Genera PDF","Generate PDF")})," ",i("â firma â carica il PDF firmato qui sotto.","â sign â upload the signed PDF below.")]})]}),e.jsxs("div",{className:"mt-section-head-actions",children:[e.jsxs("button",{className:"btn btn-secondary",onClick:()=>c({}),title:i("Genera unâattestazione di conformità (il PI attesta di aver ricevuto un bene/servizio conforme a quanto ordinato)","Generate a conformity attestation (the PI attests a received good/service conforms to what was ordered)"),children:[e.jsx(hn,{size:14})," ",i("Attestazione di conformità ","Conformity attestation")]}),e.jsxs("button",{className:"btn btn-primary anim-shimmer",onClick:g,children:[e.jsx(Le,{size:14})," ",i("Nuova richiesta","New request")]})]})]})]})}),m&&e.jsx(_f,{initial:m,onClose:()=>c(null)}),e.jsx("section",{className:"mt-band mt-band-tight",children:e.jsx("div",{className:"mt-wrap",children:s?e.jsx("div",{className:"mt-card mt-empty reveal",children:i("Caricamentoâ¦","Loadingâ¦")}):n.length===0?e.jsxs("div",{className:"mt-card mt-empty reveal",children:[i("Ancora nessuna richiesta. Clicca","No requests yet. Click")," ",e.jsxs("strong",{children:["+ ",i("Nuova richiesta","New request")]})," ",i("per crearne una.","to create one.")]}):e.jsx("div",{className:"reveal mt-list-stack mt-list-stack-rows",children:n.map(x=>e.jsx(wf,{it:x,me:a,autoOpen:r===x.id,onPatch:b=>h(x.id,b),onRemove:()=>p(x),onAttestazione:b=>c(b)},x.id))})})})]})}function wf({it:t,me:a,autoOpen:i,onPatch:n,onRemove:o,onAttestazione:s}){var v,j,_,C;const{t:l}=X(),{openMask:r,update:d,close:m,masks:c}=Va(),g="purchase-"+t.id,h=c.some(y=>y.id===g),p=e.jsx(Ue,{size:18}),x=t.title||((v=t.goods_service)==null?void 0:v.slice(0,60))||l("Acquisto senza titolo","Untitled purchase"),b=e.jsx("div",{className:"slideover-panel",children:e.jsx(zf,{it:t,me:a,onPatch:n,onRemove:o,onAttestazione:s})});f.useEffect(()=>{h&&d(g,{title:x,icon:p,content:b})},[h,x,b]);const u=f.useRef(!1);f.useEffect(()=>
675{u.current||(u.current=!0,i&&r({id:g,title:x,icon:p,content:b}))},[]);function w(){h?m(g):r({id:g,title:x,icon:p,content:b})}return e.jsxs("article",{className:"mt-listrow mt-listrow-purchase"+(h?" is-open":""),role:"button",tabIndex:0,"aria-expanded":h,onClick:y=>{y.target.closest("button, a, input, select, textarea")||w()},onKeyDown:y=>{(y.key==="Enter"||y.key===" ")&&(y.preventDefault(),w())},children:[e.jsx("span",{className:"mt-listrow-cell mt-listrow-primary is-stacked",children:e.jsx("strong",{className:"mt-listrow-title",children:t.title||(t.goods_service?t.goods_service.split(/[.\n]/)[0]:null)||e.jsx("span",{className:"mt-listrow-ph",children:l("senza titolo","untitled")})})}),e.jsx("span",{className:"mt-listrow-cell mt-listrow-person",children:t.affidamento_ditta||(t.upb?e.jsx("span",{className:"mono",children:t.upb}):"â")}),e.jsx("span",{className:"mt-listrow-cell mt-listrow-amount",children:t.amount?`⬠${ua(t.amount)}`:"â"}),e.jsxs("span",{className:"mt-listrow-cell mt-listrow-chips",children:[t.email_sent_at&&!((j=t.signed_pdf)!=null&&j.url)&&e.jsxs("span",{className:"chip mt-chip-sm-inline",title:`${l("Inviata a DJSGE il","Sent to DJSGE on")} ${new Date(t.email_sent_at).toLocaleString("it-IT")}`,children:[e.jsx(We,{size:11})," ",l("inviata","sent")]}),((_=t.signed_pdf)==null?void 0:_.url)&&e.jsx("span",{className:"chip chip-success mt-chip-sm",children:l("firmato","signed")}),!((C=t.budget_link)!=null&&C.cat)&&e.jsx("span",{className:"chip mt-chip-sm-inline",title:l("Apri e scegli la voce di budget","Open and choose the budget line"),children:l("senza voce di budget","no budget line")})]}),e.jsxs("button",{type:"button",className:"mt-listrow-open",onClick:y=>{y.stopPropagation(),w()},"aria-label":h?l("Chiudi dettaglio acquisto","Close purchase detail"):l("Apri dettaglio acquisto","Open purchase detail"),children:[l(h?"Aperto":"Apri","Open"),e.jsx(yt,{size:15})]})]})}function zf({it:t,me:a,onPatch:i,onRemove:n,onAttestazione:o}){const{t:s}=X(),l=(c,g)=>i({[c]:g}),[r,d]=f.useState(null);function m(){o==null||o({description:(t.goods_service||"").trim(),supplier:(t.affidamento_ditta||"").trim(),amount:t.amount?`⬠${ua(t.amount)}`:""})}return e.jsxs("div",{className:"mt-row-editor mt-row-editor-gap-12",children:[e.jsx(gf,{it:t,onPatch:i}),e.jsx(Rt,{label:s("Titolo breve (uso interno)","Short title (internal use)"),children:e.jsx(se,{className:"input",value:t.title||"",onChange:c=>l("title",c.target.value),placeholder:s("es. Acquisto hardware ricerca","e.g. Research hardware purchase")})}),e.jsxs("div",{className:"mt-mission-row",children:[e.jsx(Rt,{label:s("Richiedente (nome che firma)","Requester (signing name)"),wide:!0,children:e.jsx(se,{className:"input",value:t.requester_name||"",onChange:c=>l("requester_name",c.target.value),placeholder:"default: Dott. Giuseppe Naglieri"})}),e.jsx(Rt,{label:s("Qualifica","Qualification"),wide:!0,children:e.jsx(se,{className:"input",value:t.requester_qualifica||"",onChange:c=>l("requester_qualifica",c.target.value),placeholder:"default: Principal Investigator"})})]}),e.jsx(Rt,{label:s("Descrizione bene/servizio (testo che entrerà nella lettera)","Goods/service description (text that will appear in the letter)"),children:e.jsx(se,{as:"textarea",className:"textarea",rows:3,value:t.goods_service||"",onChange:c=>l("goods_service",c.target.value),placeholder:s("es. Acquisto hardware per le esigenze organizzative, di ricerca e di outreach del progetto, specificato nell'allegata scheda","e.g. Purchase of hardware for the projectâs organisational, research and outreach needs, as detailed in the attached sheet")})}),e.jsxs("div",{className:"mt-mission-row",children:[e.jsx(Rt,{label:s("Importo presunto (â¬)","Estimated amount (â¬)"),children:e.jsx(se,{className:"input mono",inputMode:"decimal",value:t.amount||"",onChange:c=>l("amount",c.target.value),placeholder:s("es. 25000","e.g. 25000")})}),e.jsx(Rt,{label:"UPB",wide:!0,children:e.jsx(se,{className:"input mono",value:t.upb||"",onChange:c=>l("upb",c.target.value),placeholder:"default: SIGIM.Prog.FIS3Climpact.Naglieri"})})]}),e.jsxs("div",{className:"mt-mat-block mt-subsection-dashed",children:[e.jsx("div",{className:"muted text-xs mt-subsection-dashed-title",children:s("Affidamento diretto (opzionale)","Direct award (optional)")}),e.jsx(Rt,{label:s("Ditta a cui affidare (lascia vuoto per omettere queste clausole)","Company to award to (leave empty to omit these clauses)"),children:e.jsx(se,{className:"input",value:t.affidamento_ditta||"",onChange:c=>l("affidamento_ditta",c.target.value),placeholder:s("es. Apple Italia S.r.l.","e.g. Apple Italia S.r.l.")})}),e.jsx(Rt,{label:s("Motivazioni dell'affidamento diretto","Reasons for the direct award"),children:e.jsx(se,{as:"textarea",className:"textarea",rows:3,value:t.affidamento_motivazioni||"",onChange:c=>l("affidamento_motivazioni",c.target.value),placeholder:s("es. unico fornitore autorizzato per⦠· rapporto qualità /prezzo migliore di mercato â¦","e.g. sole authorised supplier for⦠· best value for money on the market â¦")})})]}),e.jsx(Rt,{label:s("Direttore del Dipartimento (firmatario, opzionale)","Director of the Department (signatory, optional)"),children:e.jsx(se,{className:"input",value:t.director_name||"",onChange:c=>l("director_name",c.target.value),placeholder:"default: Prof. Paolo Pardolesi"})}),e.jsx(Rl,{it:t,onPatch:i,cartella:"team-purchases",nomeDoc:{it:"Richiesta di acquisto",en:"Purchase request"},nomePdf:`Richiesta_acquisto_${(t.title||t.goods_service||"acquisto").replace(/[^A-Za-z0-9]+/g,"_").slice(0,40)}.pdf`,generaBlob:()=>af({item:t}),infoMail:rf({item:t}),onApriMail:d}),e.jsx("div",{className:"mt-section-actions-row",children:e.jsxs("button",{className:"btn btn-secondary btn-sm",onClick:m,title:s("Genera unâattestazione di conformità precompilata da questa richiesta (il PI attesta di aver ricevuto il bene/servizio conforme allâordine)","Generate a conformity attestation prefilled from this request (the PI attests the good/service was received and conforms to the order)"),children:[e.jsx(hn,{size:12})," ",s("Attestazione di conformità ","Conformity attestation")]})}),e.jsx(mf,{it:t}),e.jsx("div",{className:"mt-foot-divider",children:e.jsxs("button",{className:"btn btn-ghost btn-sm mt-row-delete",onClick:n,children:[e.jsx($e,{size:12})," ",s("Elimina richiesta","Delete request")]})}),r&&e.jsx(Da,{info:r,onClose:()=>d(null)})]})}function Rt({label:t,children:a,wide:i}){return e.jsxs("div",{className:"mt-field"+(i?" is-wide":""),children:[e.jsx("label",{className:"label",children:t}),a]})}const Cf=["zero","uno","due","tre","quattro","cinque","sei","sette","otto","nove","dieci","undici","dodici","tredici","quattordici","quindici","sedici","diciassette","diciotto","diciannove","venti"];function Ml(t){return Cf[t]||String(t)}function kf(t){const a=parseInt(t,10);return!isFinite(a)||a<=0?"X":`${a} (${Ml(a)})`}function Zo(t){const a=parseInt(t,10);return!isFinite(a)||a<=0?"1 (uno)":`${a} (${Ml(a)})`}function Sf(t){return t==null||t===""?NaN:parseFloat(String(t).replace(",","."))}const Fl=["supporto alla gestione della corrispondenza scientifica e istituzionale del progetto e al raccordo con le strutture amministrative dellâAteneo e con lâente finanziatore;","cura degli adempimenti organizzativi connessi agli eventi scientifici del progetto (workshop, seminari, convegni), inclusi gli aspetti logistici e comunicativi;","supporto alla cura redazionale e alla preparazione editoriale dei prodotti scientifici del progetto, inclusa la verifica della conformità ai requisiti redazionali delle sedi editoriali di riferimento;","ausilio nella predisposizione della documentazione necessaria alla rendicontazione peri
675odica delle attività e al monitoraggio delle scadenze progettuali;","supporto allâaggiornamento dei contenuti del sito web del progetto e alla cura delle attività di comunicazione e disseminazione dei risultati della ricerca."],Ll="Diploma di laurea magistrale o a ciclo unico in Giurisprudenza, Scienze politiche, Relazioni internazionali, Scienze dellâamministrazione, Lingue e letterature moderne, Comunicazione pubblica e dâimpresa, Economia, o titoli equipollenti, conseguiti ai sensi del D.M. 270/2004 o dei previgenti ordinamenti.",vs=[{label:"voto di laurea",max:5,detail:"101â103: punti 1; 104â106: punti 2; 107â109: punti 3; 110: punti 4; 110 e lode: punti 5."},{label:"ulteriori titoli accademici rispetto a quelli richiesti per la partecipazione",max:5,detail:""},{label:"comprovata e documentata esperienza nel settore di attività oggetto del contratto",max:20,detail:""},{label:"conoscenze linguistiche e informatiche documentate e pertinenti allâoggetto del contratto",max:10,detail:""},{label:"altri titoli inerenti alle attività oggetto del contratto",max:10,detail:""}],Ol=[{label:"voto di laurea",max:10,detail:"101â103: punti 2; 104â106: punti 4; 107â109: punti 6; 110: punti 8; 110 e lode: punti 10."},{label:"ulteriori titoli accademici rispetto a quelli richiesti per la partecipazione",max:10,detail:""},{label:"comprovata e documentata esperienza nel settore di attività oggetto del contratto",max:40,detail:""},{label:"conoscenze linguistiche e informatiche documentate e pertinenti allâoggetto del contratto",max:20,detail:""},{label:"altri titoli inerenti alle attività oggetto del contratto",max:20,detail:""}],Df=[{value:"tranche",label:"In due tranche (50% dopo sei mesi + 50% al termine)"},{value:"unica",label:"In unica soluzione al termine del contratto"}],Tf=[{value:"titoli_colloquio",label:"Per titoli (50 punti) e colloquio (50 punti)"},{value:"solo_titoli",label:"Solo per titoli (100 punti)"}],Xt={oggetto_prestazione:Fl,titolo_studio:Ll,punteggi_titoli:vs,punteggi_titoli_colloquio:vs,punteggi_solo_titoli:Ol,payment_mode:"tranche",selection_mode:"titoli_colloquio"},If={chiave:"rt.contratti",tipo:"form",titolo:"Richiesta di attivazione procedura selettiva"};async function Pf(t){const a=await Pt(),i=new a({unit:"mm",format:"a4"}),n=await Gt();Wt(i,n);const o=da(i,n),s=(t.director_name||"").trim()||Ir,l=parseInt(t.n_contratti,10)||1,r=(t.figura_professionale||"").trim()||"[figura professionale richiesta â da inserire]",d=Array.isArray(t.oggetto_prestazione)&&t.oggetto_prestazione.length?t.oggetto_prestazione:Fl,m=t.durata_mesi||"",c=t.ore_totali||"",g=Sf(t.importo_eur),h=(t.titolo_studio||"").trim()||Ll,x=(t.selection_mode||"titoli_colloquio")==="solo_titoli",b=Array.isArray(t.punteggi_titoli)&&t.punteggi_titoli.length?t.punteggi_titoli:x?Ol:vs,u=!x&&
675!!(t.colloquio_si??!0),w=(t.colloquio_dettaglio||"Il colloquio verterà sulle tematiche attinenti allâoggetto della prestazione e comprenderà la verifica della conoscenza della lingua inglese.").trim(),v=(t.sede_prestazione||"").trim()||`prevalentemente presso il ${Pr}, nonché da remoto, senza vincolo di subordinazione nei confronti del committente`,j=t.payment_mode||"tranche";i.setFont(fe,"normal"),i.setFontSize(Me),i.setTextColor("#1d1d1f"),i.text(`Taranto, ${Ge(new Date)}`,Oe,o.y,{align:"right"}),o.advance(je+4),zs(i,o,["Al Direttore del Dipartimento",s,"S E D E"],{gap:8});const _={align:"justify"};Ht(i,o,[{text:`Oggetto: ${x?"Attivazione procedura selettiva per titoli":"Attivazione procedura selettiva per titoli e colloquio"} per il conferimento di n. ${Zo(l)} contratto di lavoro autonomo di natura occasionale per le esigenze del progetto di ricerca âCLIMPACT â `,bold:!0},{text:Hi,bold:!0,italic:!0},{text:`â, ${Fi}.`,bold:!0}],{gap:4,align:"justify"}),ee(i,o,`Lo scrivente ${bi}, in qualità di Principal Investigator del progetto di ricerca âCLIMPACT â ${Hi}â, ${Fi}, richiede lâattivazione della procedura per il conferimento di n. ${Zo(l)} incarico individuale con contratto di lavoro autonomo di natura occasionale, ai sensi dellâart. 7, comma 6, del D.Lgs. 30 marzo 2001, n. 165, e del Regolamento per il conferimento di incarichi individuali con contratti di lavoro autonomo emanato con D.R. n. 1653 del 5.3.2010.`,_),Ht(i,o,[{text:"La prestazione richiesta ha "},{text:"natura temporanea e altamente qualificata",bold:!0},{text:", in quanto connessa alla realizzazione delle specifiche attività progettuali previste dal suddetto progetto di ricerca e richiede competenze specialistiche non rinvenibili nel personale in servizio presso lâAteneo."}],_),ee(i,o,"Si rappresenta che lâaffidamento dellâincarico a soggetto estraneo allâUniversità è motivato dallâimpossibilità oggettiva di utilizzare le risorse umane disponibili allâinterno dellâAteneo, come sarà previamente accertato mediante apposita indagine conoscitiva ai sensi dellâart. 7, comma 6, del D.Lgs. n. 165/2001.",_),ee(i,o,"Il sottoscritto dichiara che la figura professionale richiesta è:",_),Ht(i,o,kd("1) "+r),_),ee(i,o,"Lâoggetto della prestazione sarà :",_);for(const D of d)Ht(i,o,[{text:"â "+Mi(D)}],{leftX:Ne+4,gap:1.5,align:"justify"});o.advance(2);const y=m?`${kf(m)} mesi`:"___ ( __________ ) mesi",z=c?`, per un totale di ${c} ore`:"";ee(i,o,`Lâincarico avrà durata di ${y} dalla data di sottoscrizione del contratto${z}. La prestazione sarà svolta ${v}.`,_);const T=isFinite(g)&&g>0?`⬠${ua(g)}`:"⬠___________";Ht(i,o,[{text:"Lâimporto lordo onnicomprensivo del contratto sarà di euro "},{text:T,bold:!0},{text:`, a valere sui fondi del progetto CLIMPACT, ${Fi}.`}],_),ee(i,o,"Il compenso deve intendersi al lordo di tutte le ritenute fiscali, previdenziali ed assistenziali a carico del percipiente e del committente. Non spettano alla figura in esame rimborsi spese o altri oneri, a piè di lista o a forfait.",_),Ht(i,o,[{text:"Il sottoscritto attesta la "},{text:"congruità del compenso",bold:!0},{text:" proposto in relazione alla tipologia e alla durata della prestazione richiesta, nonché la sussistenza della relativa "},{text:"copertura finanziaria",bold:!0},{text:` a valere sul budget del progetto CLIMPACT (CUP ${ks}).`}],_),ee(i,o,"Il pagamento verrà effettuato secondo le seguenti modalità :",_),j==="unica"?Ht(i,o,[{text:"â in unica soluzione al termine del contratto, previa certificazione da parte del Responsabile Scientifico di regolare esecuzione della prestazione e verifica da parte del Direttore del Dipartimento, dietro rilascio di nota di lavoro/fattura emessa dal prestatore dâopera."}],{leftX:Ne+4,align:"justify"}):Ht(i,o,[{text:"â in due tranche: la prima verrà corrisposta dopo sei mesi e la seconda al termine del contratto, previa certificazione da parte del Responsabile Scientifico di regolare esecuzione della prestazione e verifica da parte del Direttore del Dipartimento, dietro rilascio di nota di lavoro/fattura emessa dal prestatore dâopera."}],{leftX:Ne+4,align:"justify"}),ee(i,o,x?"Allâuopo fa presente che sono richiesti i requisiti (A) e i titoli (B) sottoelencati, che si ritengono congrui alla prestazione suindicata:":"Allâuopo fa presente che sono richiesti i requisiti (A) e i titoli (B) sottoelencati, oltre al colloquio (C), che si ritengono congrui alla prestazione suindicata:",_),Ma(i,o,"REQUISITI DI AMMISSIONE:",{font:"bold"}),Ma(i,o,"A) Titolo di Studio",{font:"bold"}),ee(i,o,h,_);const I=b.reduce((D,$)=>D+(parseInt($.max,10)||0),0);return Ma(i,o,`B) TITOLI (punteggio massimo: ${I} punti):`,{font:"bold"}),b.forEach((D,$)=>{const q=D.detail?" "+D.detail:"";ee(i,o,`${$+1}. ${D.label}: fino a ${D.max} punti.${q}`,{gap:1.5,align:"justify"})}),o.advance(2),x||(Ma(i,o,`C) COLLOQUIO: ${u?"SI":"NO"} (punteggio massimo: 50 punti).`,{font:"bold"}
675),u&&ee(i,o,w,_)),o.advance(10),Cs(i,o,"Il Richiedente",bi),i}async function Ef({item:t}){const a=await Pf(t||{});return za(a,If)}function Af({onBack:t,me:a}){const{t:i}=X(),[n,o]=f.useState([]),[s,l]=f.useState(!0),[r,d]=f.useState(null);f.useEffect(()=>{const h=Ye(ft(Ie(te,Ke.contracts),mn("created_at","desc")),p=>{o(p.docs.map(x=>({id:x.id,...x.data()}))),l(!1)},p=>{console.error("[contracts] subscribe",p),l(!1)});return()=>h()},[]);async function m(){const h=pn();await _e(oe(te,Ke.contracts,h),{id:h,title:"",n_contratti:1,figura_professionale:"",oggetto_prestazione:[...Xt.oggetto_prestazione],durata_mesi:"",ore_totali:"",importo_eur:"",titolo_studio:Xt.titolo_studio,selection_mode:Xt.selection_mode,payment_mode:Xt.payment_mode,punteggi_titoli:Xt.punteggi_titoli_colloquio.map(p=>({...p})),colloquio_si:!0,colloquio_dettaglio:"",sede_prestazione:"",director_name:"",created_at:ie(),updated_at:ie()}),d(h)}async function c(h,p){await _e(oe(te,Ke.contracts,h),{...p,updated_at:ie()},{merge:!0})}async function g(h){var p,x,b,u;if(await Na(`${i("Eliminare","Delete")} "${h.title||((p=h.figura_professionale)==null?void 0:p.slice(0,40))||i("(senza titolo)","(untitled)")}" ${i("e i suoi file?","and its files?")}`))try{(x=h.generated_pdf)!=null&&x.path&&await de(h.generated_pdf.path),(b=h.signed_pdf)!=null&&b.path&&await de(h.signed_pdf.path),(u=h.signed_requester_pdf)!=null&&u.path&&await de(h.signed_requester_pdf.path),await gt(oe(te,Ke.contracts,h.id))}catch(w){alert(i("Eliminazione fallita: ","Deletion failed: ")+(w.message||w))}}return e.jsxs(e.Fragment,{children:[e.jsx("section",{className:"mt-band mt-band-dark",children:e.jsxs("div",{className:"mt-wrap",children:[e.jsxs("button",{className:"btn btn-ghost btn-sm mt-back reveal",onClick:t,children:[e.jsx(Wa,{size:14})," ",i("Indietro","Back")]}),e.jsxs("div",{className:"mt-section-head reveal","data-d":"1",style:{alignItems:"flex-start"},children:[e.jsxs("div",{children:[e.jsx("p",{className:"mt-eyebrow",children:i("Research Team","Research Team")}),e.jsx("h1",{className:"mt-section-title",children:i("Consulenze & contratti","Consultancies & contracts")}),e.jsx("p",{className:"mt-section-sub",children:i("Richieste di attivazione procedura selettiva per contratti di lavoro autonomo / consulenza. La maschera produce automaticamente la lettera ufficiale (PDF) â firmala e ricarica la copia firmata.","Requests to activate the selection procedure for self-employment / consultancy contracts. The editor automatically produces the official letter (PDF) â sign it and re-upload the signed copy.")})]}),e.jsxs("button",{className:"btn btn-primary anim-shimmer",onClick:m,children:[e.jsx(Le,{size:14})," ",i("Nuova richiesta","New request")]})]})]})}),e.jsx("section",{className:"mt-band mt-band-tight",children:e.jsx("div",{className:"mt-wrap",children:s?e.jsx("div",{className:"mt-card mt-empty reveal",children:i("Caricamentoâ¦","Loadingâ¦")}):n.length===0?e.jsxs("div",{className:"mt-card mt-empty reveal",children:[i("Ancora nessuna richiesta. Clicca","No requests yet. Click")," ",e.jsxs("strong",{children:["+ ",i("Nuova richiesta","New request")]}),"."]}):e.jsx("div",{className:"reveal mt-list-stack mt-list-stack-rows",children:n.map(h=>e.jsx($f,{it:h,me:a,autoOpen:r===h.id,onPatch:p=>c(h.id,p),onRemove:()=>g(h)},h.id))})})})]})}function $f({it:t,me:a,autoOpen:i,onPatch:n,onRemove:o}){var w,v,j,_;const{t:s}=X(),{openMask:l,update:r,close:d,masks:m}=Va(),c="contract-"+t.id,g=m.some(C=>C.id===c),h=e.jsx(st,{size:18}),p=t.title||((w=t.figura_professionale)==null?void 0:w.slice(0,60))||s("Contratto senza titolo","Untitled contract"),x=e.jsx("div",{className:"slideover-panel",children:e.jsx(Rf,{it:t,me:a,onPatch:n,onRemove:o})});f.useEffect(()=>{g&&r(c,{title:p,icon:h,content:x})},[g,p,x]);const b=f.useRef(!1);f.useEffect(()=>{b.current||(b.current=!0,i&&l({id:c,title:p,icon:h,content:x}))},[]);function u(){g?d(c):l({id:c,title:p,icon:h,content:x})}return e.jsxs("article",{className:"mt-listrow mt-listrow-contract"+(g?" is-open":""),role:"button",tabIndex:0,"aria-expanded":g,onClick:C=>{C.target.closest("button, a, input, select, textarea")||u()},onKeyDown:C=>{(C.key==="Enter"||C.key===" ")&&(C.preventDefault(),u())},children:[e.jsxs("span",{className:"mt-listrow-cell mt-listrow-primary",children:[e.jsx("strong",{className:"mt-listrow-title",children:t.title||((v=t.figura_professionale)==null?void 0:v.slice(0,60))||e.jsx("span",{className:"mt-listrow-ph",children:s("senza titolo","untitled")})}),t.title&&t.figura_professionale&&e.jsx("span",{className:"mt-listrow-code",children:t.figura_professionale.slice(0,48)})]}),e.jsx("span",{className:"mt-listrow-cell mt-listrow-num",children:t.n_contratti?`n. ${t.n_contratti}`:"â"}),e.jsx("span",{className:"mt-listrow-cell mt-listrow-date",children:t.durata_mesi?`${t.durata_mesi} ${s("mesi","months")}`:"â"}),e.jsx("span",{className:"mt-listrow-cell mt-listrow-amount",children:t.importo_eur?`⬠${ua(t.importo_eur)}`:"â"}),e.jsxs("span",{className:"mt-listrow-cell mt-listrow-chips",children:[t.email_sent_at&&!((j=t.signed_pdf)!=null&&j.url)&&e.jsxs("span",{className:"chip mt-chip-sm-inline",title:`${s("Inviata a DJSGE il","Sent to DJSGE on")}
675 ${new Date(t.email_sent_at).toLocaleString("it-IT")}`,children:[e.jsx(We,{size:11})," ",s("inviata","sent")]}),((_=t.signed_pdf)==null?void 0:_.url)&&e.jsx("span",{className:"chip chip-success mt-chip-sm",children:s("firmato","signed")})]}),e.jsxs("button",{type:"button",className:"mt-listrow-open",onClick:C=>{C.stopPropagation(),u()},"aria-label":g?s("Chiudi dettaglio contratto","Close contract detail"):s("Apri dettaglio contratto","Open contract detail"),children:[s(g?"Aperto":"Apri","Open"),e.jsx(yt,{size:15})]})]})}function Rf({it:t,me:a,onPatch:i,onRemove:n}){const{t:o}=X(),s=(u,w)=>i({[u]:w}),[l,r]=f.useState(null),d=(t.selection_mode||"titoli_colloquio")==="solo_titoli",m=t.punteggi_titoli||Xt.punteggi_titoli;function c(u,w,v){const j=m.map((_,C)=>C===u?{..._,[w]:v}:_);s("punteggi_titoli",j)}function g(u){const w=u==="solo_titoli"?Xt.punteggi_solo_titoli:Xt.punteggi_titoli_colloquio;i({selection_mode:u,punteggi_titoli:w.map(v=>({...v})),colloquio_si:u!=="solo_titoli"})}const h=t.oggetto_prestazione||[];function p(u,w){s("oggetto_prestazione",h.map((v,j)=>j===u?w:v))}function x(){s("oggetto_prestazione",[...h,""])}function b(u){s("oggetto_prestazione",h.filter((w,v)=>v!==u))}return e.jsxs("div",{className:"mt-row-editor mt-row-editor-gap-12",children:[e.jsx(ct,{label:o("Titolo breve (uso interno)","Short title (internal use)"),children:e.jsx(se,{className:"input",value:t.title||"",onChange:u=>s("title",u.target.value),placeholder:o("es. Incarico supporto organizzativo CLIMPACT","e.g. CLIMPACT organisational support assignment")})}),e.jsxs("div",{className:"mt-mission-row",children:[e.jsx(ct,{label:o("N. contratti","No. of contracts"),children:e.jsx(se,{className:"input mono",type:"number",min:"1",value:t.n_contratti||1,onChange:u=>s("n_contratti",parseInt(u.target.value,10)||1)})}),e.jsx(ct,{label:o("Durata (mesi) *","Duration (months) *"),children:e.jsx(se,{className:"input mono",type:"number",min:"1",value:t.durata_mesi||"",onChange:u=>s("durata_mesi",u.target.value),placeholder:o("es. 12 (obbligatorio)","e.g. 12 (required)")})}),e.jsx(ct,{label:o("Ore totali","Total hours"),children:e.jsx(se,{className:"input mono",type:"number",min:"1",value:t.ore_totali||"",onChange:u=>s("ore_totali",u.target.value),placeholder:o("es. 400","e.g. 400")})}),e.jsx(ct,{label:o("Importo lordo (â¬)","Gross amount (â¬)"),children:e.jsx(se,{className:"input mono",inputMode:"decimal",value:t.importo_eur||"",onChange:u=>s("importo_eur",u.target.value),placeholder:o("es. 7000","e.g. 7000")})})]}),e.jsxs("div",{className:"mt-mission-row",children:[e.jsx(ct,{label:o("Modalità di selezione","Selection method"),wide:!0,children:e.jsx(xe,{tone:"inherit",matchWidth:!1,value:t.selection_mode||"titoli_colloquio",onChange:u=>g(u),ariaLabel:o("Modalità di selezione","Selection method"),options:Tf})}),e.jsx(ct,{label:o("Modalità di pagamento","Payment method"),wide:!0,children:e.jsx(xe,{tone:"inherit",matchWidth:!1,value:t.payment_mode||"tranche",onChange:u=>s("payment_mode",u),ariaLabel:o("Modalità di pagamento","Payment method"),options:Df})})]}),e.jsx(ct,{label:o("Figura professionale richiesta (testo lungo, entra nel PDF)","Required professional profile (long text, appears in the PDF)"),children:e.jsx(se,{as:"textarea",className:"textarea",rows:4,value:t.figura_professionale||"",onChange:u=>s("figura_professionale",u.target.value),placeholder:o("es. Laureato/a con competenze nell'organizzazione e nella gestione di attività connesse a progetti di ricerca, â¦","e.g. Graduate with skills in organising and managing activities related to research projects, â¦")})}),e.jsx(ct,{label:o("Sede della prestazione (default: presso il Dip. Jonico, nonché da remoto)","Place of performance (default: at the Ionian Dept., and remotely)"),children:e.jsx(se,{className:"input",value:t.sede_prestazione||"",onChange:u=>s("sede_prestazione",u.target.value),placeholder:o("lasciare vuoto per usare il default","leave empty to use the default")})}),e.jsxs("div",{children:[e.jsxs("div",{className:"mt-mat-head mt-mat-head-split",children:[e.jsx("span",{className:"label",children:o("Oggetto della prestazione (elenco puntato)","Subject of the service (bullet list)")}),e.jsxs("button",{className:"btn btn-ghost btn-sm",onClick:x,children:[e.jsx(Le,{size:11})," ",o("Punto","Bullet")]})]}),e.jsx("div",{className:"mt-bullet-list",children:h.map((u,w)=>e.jsxs("div",{className:"mt-bullet-row",children:[e.jsx("span",{className:"muted mt-bullet-dash",children:"â"}),e.jsx(se,{as:"textarea",className:"textarea mt-bullet-text",rows:2,value:u,onChange:v=>p(w,v.target.value)}),e.jsx("button",{type:"button",className:"btn btn-ghost btn-sm mt-bullet-x",onClick:()=>b(w),title:o("Rimuovi punto","Remove bullet"),children:e.jsx(Ce,{size:12})})]},w))})]}),e.jsx(ct,{label:o("A) Titolo di studio richiesto (testo lungo)","A) Required academic qualification (long text)"),children:e.jsx(se,{as:"textarea",className:"textarea",rows:4,value:t.titolo_studio||"",onChange:u=>s("titolo_studio",u.target.value),placeholder:o("es. Diploma di laurea magistrale o a ciclo unico in Giurisprudenza, â¦","e.g. Masterâs or single-cycle degree in Law, â¦")})}),e.jsxs("div",{children:[e.jsx("div",{className:"mt-mat-head mt-mat-head-tight",children:e.jsxs("span",{className:"label",children:[o("B) Punteggi per i titoli (max totali:","B) Scores for qualifications (max total:")," ",(m||[]).reduce((u,w)=>u+(parseInt(w.max,10)||0),0)," ",o("punti)","points)")]})}),e.jsx("div",{className:"mt-bullet-list",children:(m||[]).map((u,w)=>e.jsxs("div",{className:"mt-tri-grid",children:[e.jsx(se,{className:"input",placeholder:o("Etichetta","Label"),value:u.label||"",onChange:v=>c(w,"label",v.target.value)}),e.jsx(se,{className:"input mono",type:"number",min:"0",value:u.max||0,onChange:v=>c(w,"max",parseInt(v.target.value,10)||0),placeholder:o("max punti","max points")}),e.jsx(se,{className:"input",placeholder:o("Dettaglio (opzionale, es. ripartizione voto laurea)","Detail (optional, e.g. degree-mark breakdown)"),value:u.detail||"",onChange:v=>c(w,"detail",v.target.value)})]},w))})]}),!d&&e.jsxs("div",{className:"mt-mission-row",children:[e.jsx(ct,{label:o("C) Colloquio","C) Interview"),children:e.jsx(xe,{tone:"inherit",value:t.colloquio_si?"si":"no",onChange:u=>s("colloquio_si",u==="si"),ariaLabel:o("C) Colloquio","C) Interview"),options:[{value:"si",label:o("SÃ","YES")},{value:"no",label:o("NO","NO")}]})}),e.jsx(ct,{label:o("Dettaglio colloquio (se SÃ)","Interview detail (if YES)"),wide:!0,children:e.jsx(se,{className:"input",value:t.colloquio_dettaglio||"",onChange:u=>s("colloquio_dettaglio",u.target.value),placeholder:o("default: verterà sulle tematiche ⦠e verifica della lingua inglese","default: will cover the topics ⦠and English-language assessment")})})]}),e.jsx(ct,{label:o("Direttore del Dipartimento (firmatario, opzionale)","Director of the Department (signatory, optional)"),children:e.jsx(se,{className:"input",value:t.director_name||"",onChange:u=>s("director_name",u.target.value),placeholder:"default: Prof. Paolo Pardolesi"})}),e.jsx(Rl,{it:t,onPatch:i,cartella:"team-contracts",nomeDoc:{it:"Richiesta di attivazione",en:"Activation request"},nomePdf:`Richiesta_attivazione_contratto_${(t.title||t.figura_professionale||"incarico").replace(/[^A-Za-z0-9]+/g,"_").slice(0,40)}.pdf`,generaBlob:()=>Ef({item:t}),infoMail:df({item:t}),onApriMail:r}),e.jsx("div",{className:"mt-foot-divider",children:e.jsxs("button",{className:"btn btn-ghost btn-sm mt-row-delete",onClick:n,children:[e.jsx($e,{size:12})," ",o("Elimina richiesta","Delete request")]})}),l&&e.jsx(Da,{info:l,onClose:()=>r(null)})]})}function ct({label:t,children:a,wide:i}){return e.jsxs("div",{className:"mt-field"+(i?" is-wide":""),children:[e.jsx("label",{className:"label",children:t}),a]})}const ai=t=>String(t||"").replace(/[^A-Za-z0-9._-]+/g,"_").replace(/^_+|_+$/g,"").slice(0,80);async function Zn(t){const a=await fetch(t);if(!a.ok)throw new Error(`HTTP ${a.status} ${t}`);return await a.blob()}function Mf(t){var a;return((a=$r.find(i=>i.value===t))==null?void 0:a.label)||t||"altro"}async function Ff(t,{onProgress:a}={}){var b,u,w,v,j;if(!t)return;const i=(await Sa(()=>Ae(()=>import("./jszip.min-DN5-FNYE.js").then(_=>_.j),__vite__mapDeps([5,4])))).default,n=new i,o=n.folder(ai(t.name)||((b=t.id)==null?void 0:b.slice(0,8))||"ospite");let s=0,l=0;const r=_=>{l++,a==null||a(l,s,_)};s=(t.expenses||[]).flatMap(_=>{var C;return(Array.isArray(_.receipts)?_.receipts:(C=_.receipt)!=null&&C.url?[_.receipt]:[]).map(y=>({exp:_,r:y,kind:"receipt"})).concat((Array.isArray(_.payment_proofs)?_.payment_proofs:[]).map(y=>({exp:_,r:y,kind:"proof"})))}).length+((u=t.rimborso_form_generated)!=null&&u.url?1:0)+((w=t.rimborso_form)!=null&&w.url?1:0)+((v=t.incarico_letter)!=null&&v.url?1:0)+2;try{const _=await to({guest:t,lang:"it"});o.file("riepilogo_spese_IT.pdf",_),r("riepilogo IT")}catch(_){console.warn("[zip] summary IT failed",_),r("riepilogo IT")}try{const _=await to({guest:t,lang:"en"});o.file("riepilogo_spese_EN.pdf",_),r("riepilogo EN")}catch(_){console.warn("[zip] summary EN failed",_),r("riepilogo EN")}for(const[_,C]of[["rimborso_form_generated","rimborso_compilato.pdf"],["rimborso_form","rimborso_firmato.pdf"],["incarico_letter","incarico.pdf"]]){const y=t[_];if(y!=null&&y.url){try{const z=await Zn(y.url);o.file(C,z)}catch(z){console.warn(`[zip] ${C} failed`,z)}r(C)}}const m=o.folder("spese"),c=t.expenses||[];for(let _=0;_<c.length;_++){const C=c[_],y=String(_+1).padStart(2,"0"),z=ai(`${y}_${Mf(C.kind)}_${C.date||"no-date"}_${C.vendor||""}`),T=m.folder(z),I=Array.isArray(C.receipts)?C.receipts:(j=C.receipt)!=null&&j.url?[C.receipt]:[],D=Array.isArray(C.payment_proofs)?C.payment_proofs:[];for(let $=0;$<I.length;$++){const q=I[$];try{const R=await Zn(q.url);T.file(`ricevuta-${$+1}_${ai(q.name)||"file"}`,R)}catch(R){console.warn("[zip] receipt fail",q,R)}r(`ricevuta ${y}.${$+1}`)}for(let $=0;$<D.length;$++){const q=D[$];try{const R=await Zn(q.url);T.file(`pagamento-${$+1}_${ai(q.name)||"file"}`,R)}catch(R){console.warn("[zip] proof fail",q,R)}r(`pagamento ${y}.${$+1}`)}}const g=await n.generateAsync({type:"blob",compression:"DEFLATE",compressionOptions:{level:6}}),h=`${ai(t.name)||"ospite"}_rimborso_completo.zip`,p=URL.createObjectURL(g),x=document.createElement("a");return x.href=p,x.download=h,document.body.appendChild(x),x.click(),x.remove(),setTimeout(()=>URL.revokeObjectURL(p),1500),{fileName:h,size:g.size}}function Lf(){const t=new Uint8Array(16);return crypto.getRandomValues(t),Array.from(t,a=>a.toString(16).padStart(2,"0")).join("")}function Of(t){const a=window.location.origin;return t!=null&&t.dossier_token&&(t!=null&&t.event_slug)?`${a}/event/${t.event_slug}/trip/${t.dossier_token}`:`${a}/ospite/${typeof t=="string"?t:t==null?void 0:t.id}`}function Xo(t,a){return`${String(t||"").trim().toLowerCase()}::${a||""}`}function Qo(...t){const a=t.filter(Boolean).join(" ").normalize("NFD").replace(/[\u0300-\u036f]/g,"").toLowerCase().replace(/[^a-z0-9\s]/g," ").split(/\s+/).filter(
675Boolean).sort().join(" ");return a.length>=5?a:""}function qf(t,a){const i=Rr.find(n=>n.value===t);return i?a==="en"&&i.labelEn?i.labelEn:i.label:t}function Uf(t){switch(t){case"completato":return"chip-success";case"rimborsato":return"chip-success";case"in_compilazione":return"chip-accent";default:return""}}function Bf({onBack:t,me:a}){const{t:i}=X(),[n,o]=f.useState([]),[s,l]=f.useState(!0),[r,d]=f.useState(null),[m,c]=f.useState([]),[g,h]=f.useState(!1);f.useEffect(()=>{const v=Ye(ft(Ie(te,Ke.guests),mn("created_at","desc")),j=>{o(j.docs.map(_=>({id:_.id,..._.data()}))),l(!1)},j=>{console.error("[guests] subscribe",j),l(!1)});return()=>v()},[]),f.useEffect(()=>{const v=Ye(ft(Ie(te,"speaker_registrations"),Bt("billing_mode","==","rimborso")),j=>c(j.docs.map(_=>({id:_.id,..._.data()}))),j=>console.error("[guests] speaker_registrations subscribe",j));return()=>v()},[]);const{diEvento:p,altre:x}=f.useMemo(()=>{const v=new Map(m.map(T=>[T.id,T])),j=new Map(m.map(T=>[Xo(T.email,T.event_id),T])),_=new Map(m.map(T=>[String(T.email||"").trim().toLowerCase(),T])),C=new Map(m.map(T=>[Qo(T.first_name,T.last_name),T]).filter(([T])=>T)),y=[],z=[];for(const T of n){const I=String(T.email||"").trim().toLowerCase(),D=Qo(T.name),$=T.reg_id&&v.get(T.reg_id)||j.get(Xo(T.email,T.event_id))||I&&_.get(I)||D&&C.get(D);if($){y.push({...T,reg:$});continue}z.push(T)}return{diEvento:y,altre:z}},[n,m]);async function b(){const v=Lf();await _e(oe(te,Ke.guests,v),{...Ad(),created_at:ie(),updated_at:ie()}),d(v)}async function u(v,j){await _e(oe(te,Ke.guests,v),{...j,updated_at:ie()},{merge:!0})}async function w(v){var j,_;if(await Na(`${i("Eliminare l'ospite","Delete the guest")} "${v.name||v.email||i("(senza nome)","(no name)")}" ${i("e tutti i suoi file?","and all their files?")}`))try{const C=[...(v.expenses||[]).map(y=>{var z;return(z=y.receipt)==null?void 0:z.path}).filter(Boolean),(j=v.rimborso_form)==null?void 0:j.path,(_=v.incarico_letter)==null?void 0:_.path].filter(Boolean);for(const y of C)try{await de(y)}catch{}await gt(oe(te,Ke.guests,v.id))}catch(C){alert(i("Eliminazione fallita: ","Deletion failed: ")+(C.message||C))}}return e.jsxs(e.Fragment,{children:[e.jsx("section",{className:"mt-band mt-band-dark",children:e.jsxs("div",{className:"mt-wrap",children:[e.jsxs("button",{className:"btn btn-ghost btn-sm mt-back reveal",onClick:t,children:[e.jsx(Wa,{size:14})," ",i("Indietro","Back")]}),e.jsxs("div",{className:"mt-section-head reveal","data-d":"1",style:{alignItems:"flex-start"},children:[e.jsxs("div",{children:[e.jsx("p",{className:"mt-eyebrow",children:i("Research Team","Research Team")}),e.jsx("h1",{className:"mt-section-title",children:i("Ospiti â rimborsi","Guests â reimbursements")}),e.jsxs("p",{className:"mt-section-sub",children:[i("Crea un ospite, condividi il link al portale pubblico via email (clic su","Create a guest and share the public portal link by email (click")," ",e.jsx(We,{size:11,style:{verticalAlign:"-1px"}})," ",i("Invia link). L'ospite carica autonomamente le proprie spese e ricevute; tu vedi tutto in tempo reale e ricevi notifica al completamento.","Send link). The guest uploads their own expenses and receipts; you see everything in real time and are notified on completion.")]})]}),e.jsxs("button",{className:"btn btn-primary anim-shimmer",onClick:b,children:[e.jsx(Le,{size:14})," ",i("Nuovo ospite","New guest")]})]})]})}),e.jsx("section",{className:"mt-band mt-band-tight",children:e.jsxs("div",{className:"mt-wrap",children:[s?e.jsx("div",{className:"mt-card mt-empty reveal",children:i("Caricamentoâ¦","Loadingâ¦")}):p.length===0?e.jsx("div",{className:"mt-card mt-empty reveal",children:i("Nessun relatore in modalitaâ a rimborso, per ora.","No speaker on the reimbursement model yet.")}):e.jsx("div",{className:"reveal mt-list-stack mt-list-stack-rows",children:p.map(v=>e.jsx(er,{it:v,autoOpen:r===v.id,onPatch:j=>u(v.id,j),onRemove:()=>w(v)},v.id))}),!s&&x.length>0&&e.jsxs("div",{className:"reveal",style:{marginTop:18},children:[e.jsx("button",{type:"button",className:"btn btn-ghost btn-sm","aria-expanded":g,onClick:()=>h(v=>!v),children:g?i("Nascondi le altre schede","Hide the other records"):`${i("Altre schede","Other records")} (${x.length})`}),g&&e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"mt-section-sub",style:{marginTop:10},children:i("Ospiti esterni non legati a un evento, e relatori che non sono in modalitaâ a rimborso (agenzia, self funded): per loro il rimborso non passa da qui.","External guests not tied to an event, and speakers who are not on the reimbursement model (agency, self funded): their reimbursement does not go through this list.")}),e.jsx("div",{className:"mt-list-stack mt-list-stack-rows",style:{marginTop:10},children:x.map(v=>e.jsx(er,{it:v,autoOpen:r===v.id,onPatch:j=>u(v.id,j),onRemove:()=>w(v)},v.id))})]})]})]})})]})}
675function er({it:t,autoOpen:a,onPatch:i,onRemove:n}){const{t:o,lang:s}=X(),l=(t.expenses||[]).reduce((j,_)=>{const C=parseFloat(String(_.amount||"").replace(",","."));return j+(isFinite(C)?C:0)},0),r=(t.expenses||[]).length,{openMask:d,update:m,close:c,masks:g}=Va(),h="guest-"+t.id,p=g.some(j=>j.id===h),x=e.jsx(Ba,{size:18}),b=t.name||o("Ospite senza nome","Unnamed guest"),u=e.jsx("div",{className:"slideover-panel",children:e.jsx(Gf,{it:t,onPatch:i,onRemove:n})});f.useEffect(()=>{p&&m(h,{title:b,icon:x,content:u})},[p,b,u]);const w=f.useRef(!1);f.useEffect(()=>{w.current||(w.current=!0,a&&d({id:h,title:b,icon:x,content:u}))},[]);function v(){p?c(h):d({id:h,title:b,icon:x,content:u})}return e.jsxs("article",{className:"mt-listrow mt-listrow-guest"+(p?" is-open":""),role:"button",tabIndex:0,"aria-expanded":p,onClick:j=>{j.target.closest("button, a, input, select, textarea")||v()},onKeyDown:j=>{(j.key==="Enter"||j.key===" ")&&(j.preventDefault(),v())},children:[e.jsxs("span",{className:"mt-listrow-cell mt-listrow-primary",children:[e.jsx("strong",{className:"mt-listrow-title",children:t.name||e.jsx("span",{className:"mt-listrow-ph",children:o("senza nome","no name")})}),t.event_title&&e.jsx("span",{className:"mt-listrow-sub",children:t.event_title})]}),e.jsx("span",{className:"mt-listrow-cell mt-listrow-person",children:t.email||"â"}),e.jsxs("span",{className:"mt-listrow-cell mt-listrow-date",children:[r," ",r===1?o("spesa","expense"):o("spese","expenses"),l>0&&e.jsxs("span",{className:"mt-listrow-code",children:[", ⬠",ua(l)]})]}),e.jsx("span",{className:"mt-listrow-cell mt-listrow-chips",children:e.jsx("span",{className:"chip mt-chip-sm "+Uf(t.status),children:qf(t.status,s)})}),e.jsxs("button",{type:"button",className:"mt-listrow-open",onClick:j=>{j.stopPropagation(),v()},"aria-label":p?o("Chiudi dettaglio ospite","Close guest detail"):o("Apri dettaglio ospite","Open guest detail"),children:[o(p?"Aperto":"Apri","Open"),e.jsx(yt,{size:15})]})]})}function Gf({it:t,onPatch:a,onRemove:i}){const{t:n,lang:o}=X(),s=(j,_)=>a({[j]:_}),[l,r]=f.useState(!1),d=Of(t);function m(){navigator.clipboard.writeText(d).then(()=>{r(!0),setTimeout(()=>r(!1),1800)},()=>alert(n("Copia non riuscita â copialo manualmente: ","Copy failed â copy it manually: ")+d))}const[c,g]=f.useState(null);function h(){const j=(t.instructions||ao).trim();g({contesto:{tipo:"ospite",id:t.id||"",titolo:[t.first_name,t.last_name].filter(Boolean).join(" ")||t.email||""},to:t.email||"",cc:"",subject:"CLIMPACT â Guest reimbursement portal",body:`${j} 676 677â â â 678Your personal portal link (please do not share): 679${d} 680`,files:[],onEsito:_=>a({invio_invito:_})})}async function p(j){try{await Sd({guest:t,lang:j})}catch(_){alert(n("Generazione PDF non riuscita: ","PDF generation failed: ")+(_.message||_))}}const[x,b]=f.useState(!1),[u,w]=f.useState(null);async function v(){b(!0);try{await Ff(t,{onProgress:(j,_,C)=>w(`${j}/${_}, ${C}`)})}catch(j){alert(n("Bundle ZIP non riuscito: ","ZIP bundle failed: ")+(j.message||j))}finally{b(!1),w(null)}}return e.jsxs("div",{className:"mt-row-editor mt-row-editor-gap-12",children:[c&&e.jsx(Da,{info:c,onClose:()=>g(null)}),e.jsx(_i,{invio:t.invio_invito}),e.jsxs("div",{className:"mt-mission-row",children:[e.jsx(Ei,{label:n("Nome dell'ospite","Guest name"),wide:!0,children:e.jsx(se,{className:"input",value:t.name||"",onChange:j=>s("name",j.target.value),placeholder:n("es. Prof. Lukas Mayer","e.g. Prof. Lukas Mayer")})}),e.jsx(Ei,{label:n("Email dell'ospite","Guest email"),wide:!0,children:e.jsx(se,{className:"input",type:"email",value:t.email||"",onChange:j=>s("email",j.target.value),placeholder:"es. [email protected]"})}),e.jsx(Ei,{label:n("Stato","Status"),children:e.jsx(xe,{tone:"inherit",value:t.status||"invitato",onChange:j=>s("status",j),ariaLabel:n("Stato","Status"),options:Rr.map(j=>({value:j.value,label:o==="en"&&j.labelEn?j.labelEn:j.label}))})})]}),e.jsxs("label",{className:"mt-check-row",children:[e.jsx("input",{type:"checkbox",checked:!!t.incarico_requires_signature,onChange:j=>s("incarico_requires_signature",j.target.checked)}),e.jsxs("span",{children:[n("Lettera di incarico â l'ospite la deve","Assignment letter â the guest must")," ",e.jsx("strong",{children:n("firmare e ricaricare","sign and re-upload")})," ",n("dal portale (se OFF: download in sola lettura)","from the portal (if OFF: read-only download)")]})]}),e.jsxs("div",{className:"mt-card mt-pdf-mini",children:[e.jsx("div",{className:"muted text-xs mt-link-card-meta",children:n("Link al portale ospite (protetto da token)","Guest portal link (token-protected)")}),e.jsxs("div",{className:"mt-link-card-row",children:[e.jsx("code",{className:"text-xs mono mt-link-code",children:d}),e.jsxs("button",{type:"button",className:"btn btn-ghost btn-sm",onClick:m,children:[l?e.jsx(ke,{size:12}):e.jsx(gi,{size:12})," ",l?n("Copiato","Copied"):n("Copia","Copy")]}),e.jsxs("a",{href:d,target:"_blank",rel:"noreferrer",className:"btn btn-ghost btn-sm",children:[e.jsx(fi,{size:12})," ",n("Apri","Open")]}),e.jsxs("button",{type:"button",className:"btn btn-primary btn-sm anim-shimmer",onClick:h,children:[e.jsx(We,{size:12})," ",n("Invia link via email","Send link by email")]})]})]}),e.jsxs(Ei,{label:n("Istruzioni â visibili sul portale dell'ospite e usate come corpo dell'email di invito","Instru
680ctions â shown on the guest portal and used as the invitation email body"),children:[e.jsx(se,{as:"textarea",className:"textarea",rows:8,value:t.instructions||"",onChange:j=>s("instructions",j.target.value),placeholder:n("(se vuoto si usa il default in inglese)","(the English default is used if empty)")}),e.jsxs("div",{className:"muted text-xs mt-instructions-foot",children:[e.jsxs("button",{type:"button",className:"btn btn-ghost btn-sm",onClick:()=>s("instructions",ao),children:[e.jsx(as,{size:14})," ",n("Ripristina il default","Reset to default")]}),e.jsx("span",{className:"mt-instructions-foot-note",children:n("Modifichi qui una sola volta: lo stesso testo va sia sul portale (in cima) sia nel corpo dell'email di invito (con il link aggiunto in fondo).","Edit here once: the same text appears both on the portal (at the top) and in the invitation email body (with the link appended at the end).")})]})]}),e.jsxs("div",{className:"mt-mat-block",children:[e.jsxs("div",{className:"muted text-xs mt-subsection-dashed-title mt-no-dash",children:[n("Spese caricate dall'ospite","Expenses uploaded by the guest")," (",(t.expenses||[]).length,")"]}),(t.expenses||[]).length===0?e.jsx("div",{className:"muted text-xs",children:n("Nessuna spesa caricata ancora.","No expenses uploaded yet.")}):e.jsxs("table",{className:"text-xs mt-data-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:n("Tipo","Type")}),e.jsx("th",{children:n("Data","Date")}),e.jsx("th",{children:n("Fornitore","Vendor")}),e.jsx("th",{className:"is-right",children:n("Importo","Amount")}),e.jsx("th",{className:"is-center",children:n("Cartaceo","Paper")}),e.jsx("th",{children:n("Ricevuta","Receipt")})]})}),e.jsx("tbody",{children:(t.expenses||[]).map(j=>{var y;const _=Array.isArray(j.receipts)?j.receipts:(y=j.receipt)!=null&&y.url?[j.receipt]:[],C=Array.isArray(j.payment_proofs)?j.payment_proofs:[];return e.jsxs("tr",{children:[e.jsx("td",{children:(()=>{const z=$r.find(T=>T.value===j.kind);return z?o==="en"&&z.labelEn?z.labelEn:z.label:j.kind})()}),e.jsx("td",{children:(()=>{if(j.kind==="alloggio"&&(j.date_from||j.date_to)){const z=j.date_from||j.date,T=j.date_to,I=z&&T?Math.max(0,Math.round((new Date(T+"T00:00:00")-new Date(z+"T00:00:00"))/864e5)):null;return e.jsxs(e.Fragment,{children:[z?La(z):"â"," â ",T?La(T):"â",I!=null&&e.jsxs("span",{className:"muted",children:[", ",I," ",o==="en"?I===1?"night":"nights":`nott${I===1?"e":"i"}`]})]})}return j.date?La(j.date):"â"})()}),e.jsx("td",{children:j.vendor||"â"}),e.jsx("td",{className:"is-right mono",children:j.amount?`⬠${ua(j.amount)}`:"â"}),e.jsx("td",{className:"is-center",children:j.paper_kept?e.jsx(ke,{size:11}):""}),e.jsx("td",{children:e.jsxs("div",{className:"mt-data-table-rec-stack",children:[_.length>0?_.map((z,T)=>e.jsxs("a",{href:Je(z.url),target:"_blank",rel:"noreferrer",className:"text-xs inline-flex items-center gap-1",title:z.description||"",children:[e.jsx(rn,{size:11})," ",z.name||n("ricevuta","receipt"),z.description?` â ${z.description}`:""]},z.id||T)):e.jsx("span",{className:"muted text-xs",children:n("â nessuna ricevuta â","â no receipt â")}),C.map((z,T)=>e.jsxs("a",{href:Je(z.url),target:"_blank",rel:"noreferrer",className:"text-xs inline-flex items-center gap-1 mt-data-table-warn",title:z.description||n("Documento contabile (tracciabilità pagamento)","Accounting document (payment traceability)"),children:[e.jsx(Ba,{size:11})," ",z.name||n("pagamento","payment"),z.description?` â ${z.description}`:""]},z.id||`p${T}`)),j.payment_proof_in_receipts&&e.jsxs("span",{className:"muted text-xs inline-flex items-center gap-1",title:n("L'ospite ha dichiarato che il documento contabile è già nelle ricevute","The guest declared that the accounting document is already in the receipts"),children:[e.jsx(ke,{size:11})," ",n("pagamento incluso nelle ricevute","payment included in the receipts")]})]})})]},j.id)})})]})]}),e.jsxs("div",{className:"mt-row-foot-split",children:[e.jsxs("div",{className:"mt-section-actions-row",children:[e.jsxs("span",{className:"mt-lang-seg",role:"group","aria-label":n("Lingua del riepilogo PDF","PDF summary language"),children:[e.jsx("span",{className:"mt-lang-seg-label",children:n("Riepilogo PDF","PDF summary")}
680),e.jsx("button",{className:"btn btn-secondary btn-sm mt-lang-seg-btn",onClick:()=>p("it"),title:n("Riepilogo spese in italiano (header carta intestata, suddivisione per tipologia, dettaglio, totale)","Expense summary in Italian (letterhead header, breakdown by type, detail, total)"),children:"IT"}),e.jsx("button",{className:"btn btn-secondary btn-sm mt-lang-seg-btn",onClick:()=>p("en"),title:n("Riepilogo spese in inglese","Expense summary in English"),children:"EN"})]}),e.jsxs("button",{className:"btn btn-primary btn-sm anim-shimmer",onClick:v,disabled:x,title:n("Scarica un singolo ZIP con: riepilogo IT/EN, modulo rimborso compilato e firmato, lettera di incarico, e tutte le ricevute/pagamenti raggruppati per voce di spesa.","Download a single ZIP with: IT/EN summary, completed and signed reimbursement form, assignment letter, and all receipts/payments grouped by expense item."),children:[e.jsx(Bi,{size:12}),x?u||n("Creazione bundleâ¦","Bundlingâ¦"):n(" Scarica tutto (ZIP)"," Download all (ZIP)")]})]}),e.jsxs("button",{className:"btn btn-ghost btn-sm mt-row-delete",onClick:i,children:[e.jsx($e,{size:12})," ",n("Elimina ospite","Delete guest")]})]})]})}function Ei({label:t,children:a,wide:i}){return e.jsxs("div",{className:"mt-field"+(i?" is-wide":""),children:[e.jsx("label",{className:"label",children:t}),a]})}function ii(t){return String(t).padStart(2,"0")}function ql(t,a){const i=n=>n instanceof Date&&!Number.isNaN(n.getTime());if(!i(t)||!i(a))throw new Error("start and end Dates are required")}function ui(t){return t.getUTCFullYear()+ii(t.getUTCMonth()+1)+ii(t.getUTCDate())+"T"+ii(t.getUTCHours())+ii(t.getUTCMinutes())+ii(t.getUTCSeconds())+"Z"}function Ai(t){return String(t??"").replace(/\\/g,"\\\\").replace(/;/g,"\\;").replace(/,/g,"\\,").replace(/\r\n|\r|\n/g,"\\n")}function Wf(){const t=typeof globalThis<"u"&&globalThis.crypto?globalThis.crypto:null;if(t&&typeof t.randomUUID=="function")return t.randomUUID();const a=Math.random().toString(36).slice(2),i=Math.random().toString(36).slice(2);return Date.now().toString(36)+"-"+a+i}function Ul({title:t,description:a="",location:i="",start:n,end:o,url:s=""}){ql(n,o);let l=a||"";s&&(l=l?l+` 681`+s:s);const r=["BEGIN:VCALENDAR","VERSION:2.0","PRODID:-//Climpact//Meetings//EN","CALSCALE:GREGORIAN","METHOD:PUBLISH","BEGIN:VEVENT","UID:"+Wf()+"@climpact.it","DTSTAMP:"+ui(new Date),"DTSTART:"+ui(n),"DTEND:"+ui(o),"SUMMARY:"+Ai(t),"DESCRIPTION:"+Ai(l)];return s&&r.push("URL:"+Ai(s)),r.push("LOCATION:"+Ai(i)),r.push("END:VEVENT"),r.push("END:VCALENDAR"),r.join(`\r 682`)+`\r 683`}function Bl(t,a){if(typeof document>"u")return;const i=new Blob([a],{type:"text/calendar;charset=utf-8"}),n=URL.createObjectURL(i),o=document.createElement("a");o.href=n,o.download=t||"invite.ics",document.body.appendChild(o),o.click(),document.body.removeChild(o),URL.revokeObjectURL(n)}function Gl({title:t,details:a="",location:i="",start:n,end:o}){ql(n,o);const s=new URLSearchParams;return s.set("action","TEMPLATE"),s.set("text",t||""),s.set("dates",ui(n)+"/"+ui(o)),s.set("details",a||""),s.set("location",i||""),"https://calendar.google.com/calendar/render?"+s.toString()}const Xn=/^[^\s@]+@[^\s@]+\.[^\s@]+$/,Mt=t=>String(t||"").trim().toLowerCase(),Vf="#3d5afe";function Hf({meeting:t,recipients:a=[],me:i,busy:n=!1,error:o=null,onSave:s,onClose:l,buildPreview:r}){const[d,m]=f.useState(()=>(t==null?void 0:t.identity_color)||""),[c,g]=f.useState(()=>new Set),[h,p]=f.useState([]),[x,b]=f.useState(""),[u,w]=f.useState(""),[v,j]=f.useState(()=>new Set),[_,C]=f.useState(!1),y=f.useRef(null),z=f.useMemo(()=>{const U=Array.isArray(t==null?void 0:t.invited_emails)?t.invited_emails:[];return[...new Set(U.map(Mt).filter(G=>G.includes("@")))]},[t==null?void 0:t.invited_emails]),T=f.useMemo(()=>new Set(z),[z]),I=f.useMemo(()=>z.filter(U=>!v.has(U)),[z,v]),D=f.useMemo(()=>a.filter(U=>(U==null?void 0:U.email)&&U.uid!==(i==null?void 0:i.uid)),[a,i==null?void 0:i.uid]),$=f.useMemo(()=>D.filter(U=>!T.has(Mt(U.email))||v.has(Mt(U.email))),[D,T,v]),q=f.useMemo(()=>{const U=new Map;
683for(const G of a)G!=null&&G.email&&U.set(Mt(G.email),G.name||"");return U},[a]),R=f.useRef({});function O(){const U=R.current;if(!U.busy){if(U.hasChanges){C(!0);return}l==null||l()}}f.useEffect(()=>{var G,ne;const U=ue=>{var ge,we;if(ue.key==="Escape"){ue.preventDefault(),O();return}(ue.metaKey||ue.ctrlKey)&&(ue.key==="s"||ue.key==="S")&&(ue.preventDefault(),(we=(ge=R.current).save)==null||we.call(ge))};return window.addEventListener("keydown",U),(ne=(G=y.current)==null?void 0:G.focus)==null||ne.call(G),()=>window.removeEventListener("keydown",U)},[]);const k=$.length>0&&$.every(U=>c.has(U.email));function N(){g(k?new Set:new Set($.map(U=>U.email)))}function L(U){g(G=>{const ne=new Set(G);return ne.has(U)?ne.delete(U):ne.add(U),ne})}function B(U){j(G=>{const ne=new Set(G);return ne.has(U)?ne.delete(U):ne.add(U),ne})}function P(){const U=x.split(/[,\s;]+/).map(G=>G.trim()).filter(Boolean);U.length&&(p(G=>{const ne=new Set(G.map(Mt)),ue=new Set(D.map(we=>Mt(we.email))),ge=[];for(const we of U){const Se=Mt(we);Xn.test(we)&&!ne.has(Se)&&!ue.has(Se)&&!(T.has(Se)&&!v.has(Se))&&(ne.add(Se),ge.push(we))}return ge.length?[...G,...ge]:G}),b(""))}function E(U){U.key==="Enter"||U.key===","||U.key===";"?(U.preventDefault(),P()):U.key==="Backspace"&&!x&&h.length&&p(G=>G.slice(0,-1))}function Y(U){p(G=>G.filter(ne=>ne!==U))}const S=f.useMemo(()=>{const U=new Set([...c,...h].map(Mt)),G=x.trim();Xn.test(G)&&U.add(Mt(G));for(const ne of[...U])T.has(ne)&&!v.has(ne)&&U.delete(ne);return[...U]},[c,h,x,T,v]),W=f.useMemo(()=>[...v].filter(U=>!S.includes(U)),[v,S]),M=(d||"")!==((t==null?void 0:t.identity_color)||""),J=S.length>0||W.length>0||M,V=!n&&J,K=Number.isFinite(t==null?void 0:t.scheduled_at)?t.scheduled_at:null,Q=(t==null?void 0:t.recurring)===!0;function le(){R.current.canSave&&(s==null||s(S,u.trim(),W,d))}return R.current={busy:n,hasChanges:J,canSave:V,save:le},ra.createPortal(e.jsx("div",{className:"mid-overlay",style:fn(d||(t==null?void 0:t.identity_color)),role:"dialog","aria-modal":"true","aria-label":"Meeting participants",onMouseDown:U=>
683{U.target===U.currentTarget&&O()},children:e.jsxs("div",{className:"mid-card mk-scope",style:Ss(d||(t==null?void 0:t.identity_color)),children:[e.jsxs("header",{className:"mid-head",children:[e.jsxs("div",{className:"mid-head-text",children:[e.jsxs("p",{className:"mid-eyebrow",children:[e.jsx(We,{size:13,"aria-hidden":"true"})," Participants"]}),e.jsx("h2",{className:"mid-title",children:(t==null?void 0:t.title)||"Meeting"}),K?e.jsxs("p",{className:"mid-when",children:[e.jsx(Ut,{size:13,"aria-hidden":"true"})," ",Kf(K),Q?", every week":""]}):null]}),e.jsx("button",{type:"button",className:"mid-x",onClick:O,disabled:n,"aria-label":"Close",children:e.jsx(Ce,{size:18})})]}),e.jsxs("div",{className:`mid-body${typeof r=="function"?"":" mid-body-solo"}`,children:[_?e.jsxs("div",{className:"mk-bar mid-bar",children:[e.jsxs("span",{className:"mid-count is-dirty",children:[e.jsx(ba,{size:14,"aria-hidden":"true"})," ",tr(S.length,W.length)," not saved. Close anyway?"]}),e.jsx("span",{className:"mk-bar-spacer"}),e.jsx("button",{type:"button",className:"mk-pill is-quiet",onClick:()=>C(!1),children:"Keep editing"}),e.jsxs("button",{type:"button",className:"mk-pill is-danger",onClick:()=>{C(!1),l==null||l()},children:[e.jsx($e,{size:15}),e.jsx("span",{children:"Close and discard"})]})]}):e.jsxs("div",{className:"mk-bar mid-bar",children:[e.jsx("button",{type:"button",className:"mk-pill is-quiet",onClick:O,disabled:n,children:"Cancel"}),e.jsx("span",{className:"mid-count"+(n?"":J?" is-dirty":" is-done"),children:n?"Savingâ¦":tr(S.length,W.length)}),e.jsx("span",{className:"mid-kbd",title:"Save from the keyboard",children:"âS"}),e.jsx("span",{className:"mk-bar-spacer"}),e.jsxs("button",{type:"button",className:"mk-pill is-primary mid-send",onClick:le,disabled:!V,children:[n?e.jsx(me,{size:15,className:"mid-spin"}):e.jsx(Ot,{size:15}),e.jsx("span",{children:n?"Savingâ¦":S.length>0?"Save and invite":"Save changes"})]})]}),e.jsxs("div",{className:"mid-col-left",children:[z.length>0&&e.jsxs("div",{className:"mid-section",children:[e.jsxs("span",{className:"mid-section-label",children:[e.jsx(jr,{size:14,"aria-hidden":"true"})," On this meeting (",I.length,")"]}),e.jsx("div",{className:"mid-chips",children:z.map(U=>{const G=v.has(U),ne=q.get(U);return e.jsxs("span",{className:`mid-chip mid-chip-saved${G?" is-off":""}`,children:[ne?`${ne}, ${U}`:U,e.jsx("button",{type:"button",className:"mid-chip-x",onClick:()=>B(U),"aria-label":G?`Keep ${U}`:`Remove ${U}`,title:G?"Undo â keep them on the meeting":"Remove from this meeting",children:G?e.jsx(Le,{size:12}):e.jsx(Ce,{size:12})})]},U)})}),e.jsx("p",{className:"mid-hint",children:"They get the reminders â one hour and ten minutes before. This list decides who is invited and reminded, not who may enter: anyone you send the link to can still join."})]}),e.jsxs("div",{className:"mid-section",children:[e.jsxs("div",{className:"mid-section-head",children:[e.jsxs("span",{className:"mid-section-label",children:[e.jsx(ia,{size:14,"aria-hidden":"true"})," Team members"]}),$.length>0&&e.jsx("button",{type:"button",className:"mid-selectall",onClick:N,children:k?"Clear all":"Select all"})]}),$.length===0?e.jsx("p",{className:"mid-empty",children:D.length===0?"No other team members to invite.":"Everyone on the team is already on this meeting."}):e.jsx("ul",{className:"mid-people",ref:y,tabIndex:-1,children:$.map(U=>{const G=c.has(U.email);return e.jsx("li",{children:e.jsxs("button",{type:"button",className:`mid-person${G?" is-on":""}`,onClick:()=>L(U.email),children:[e.jsx("span",{className:`mid-check${G?" is-on":""}`,"aria-hidden":"true",children:G?e.jsx(ke,{size:13}):null}),e.jsxs("span",{className:"mid-person-text",children:[e.jsx("span",{className:"mid-person-name",children:U.name||U.email}),e.jsx("span",{className:"mid-person-mail",children:U.email})]})]})},U.uid||U.email)})})]}),e.jsxs("div",{className:"mid-section",children:[e.jsxs("span",{className:"mid-section-label",children:[e.jsx(Tt,{size:14,"aria-hidden":"true"})," External guests (optional)"]}),e.jsxs("div",{className:"mid-chips",children:[h.map(U=>e.jsxs("span",{className:"mid-chip",children:[U,e.jsx("button",{type:"button",className:"mid-chip-x",onClick:()=>Y(U),"aria-label":`Remove ${U}`,children:e.jsx(Ce,{size:12})})]},U)),e.jsx("input",{className:"mid-chip-input",type:"email",inputMode:"email",placeholder:h.length?"Add anotherâ¦":"[email protected]",value:x,onChange:U=>
683b(U.target.value),onKeyDown:E,onBlur:P,disabled:n}),x.trim()&&Xn.test(x.trim())&&e.jsx("button",{type:"button",className:"mid-chip-add",onClick:P,"aria-label":"Add guest",children:e.jsx(Le,{size:14})})]}),e.jsx("p",{className:"mid-hint",children:"Anyone outside the team: they get the invitation now and the same reminders as everyone else. They join as guests via the link â no account needed (unless the room is locked); the in-platform bell only reaches people who have a Climpact profile."})]}),e.jsxs("div",{className:"mid-section",children:[e.jsx("span",{className:"mid-section-label",children:"Colour of this meeting"}),e.jsx(Or,{color:d,onColor:m,onReset:()=>m(""),swatchColor:Vf,showMatch:!1,showTone:!1,hint:"Sets the invitationâs header, keyline and button. Leave empty for the standard Climpact Meet blue."})]}),e.jsxs("div",{className:"mid-section",children:[e.jsx("span",{className:"mid-section-label",children:"Message (optional)"}),e.jsx(Lr,{className:"rtf-evt",value:u,onChange:w,minHeight:80,placeholder:"Add a short note to the invitationâ¦",ariaLabel:"Invitation note"})]}),o&&e.jsx("p",{className:"mid-err",children:o})]}),typeof r=="function"&&e.jsxs("div",{className:"mid-section mid-section-preview",children:[e.jsx("span",{className:"mid-section-label",children:"Preview â exactly what the new invitees receive"}),e.jsx("iframe",{className:"mid-preview",title:"Invitation preview",srcDoc:r(u.trim(),d)})]})]})]})}),document.body)}function tr(t,a){const i=[];return t&&i.push(`${t} new invitation${t===1?"":"s"}`),a&&i.push(`${a} removed`),i.length?i.join(", "):"No changes yet"}function Kf(t){const a=new Date(t);return isNaN(a.getTime())?"":a.toLocaleString("en-GB",{weekday:"short",day:"numeric",month:"short",hour:"2-digit",minute:"2-digit"})}const ja=7*24*3600*1e3,Wl=2*3600*1e3;function Rs(t){return(Array.isArray(t==null?void 0:t.moved_occurrences)?t.moved_occurrences:[]).map(i=>({from:Number(i==null?void 0:i.from),to:Number(i==null?void 0:i.to)})).filter(i=>Number.isFinite(i.from)&&Number.isFinite(i.to))}function Vl(t,a){return a.some(i=>Math.abs(i.from-t)<Wl)}function Ms(t,a=Date.now()){const i=Number(t==null?void 0:t.scheduled_at);if(!Number.isFinite(i))return null;if(!t.recurring)return i>=a?{at:i,from:null,moved:!1}:null;const n=Rs(t);let o=i>=a?i:i+Math.ceil((a-i)/ja)*ja;for(let l=0;l<60&&Vl(o,n);l+=1)o+=ja;let s={at:o,from:o,moved:!1};for(const l of n)l.to>=a&&l.to<s.at&&(s={at:l.to,from:l.from,moved:!0});return s}function Jf(t,a=Date.now()){const i=Ms(t,a);return i?i.at:null}function kb(t,a=Date.now()){const i=Number(t==null?void 0:t.scheduled_at);if(!Number.isFinite(i))return null;if(!t.recurring)return i<=a?i:null;const n=Rs(t);let o=null;if(i<=a){let s=i+Math.floor((a-i)/ja)*ja;for(let l=0;l<60&&s>=i&&Vl(s,n);l+=1)s-=ja;s>=i&&(o=s)}for(const s of n)s.to<=a&&(o==null||s.to>o)&&(o=s.to);return o}function Yf(t,a,i,n=Date.now()){const o=Rs(t).filter(s=>Math.abs(s.from-a)>=Wl&&Math.max(s.from,s.to)>n-ja);return Number.isFinite(i)&&Math.abs(i-a)>=6e4&&o.push({from:a,to:i}),o.sort((s,l)=>s.from-l.from)}const Zf="#3d5afe";function Xf(t){if(!Number.isFinite(Number(t)))return"";const a=new Date(Number(t)),i=n=>String(n).padStart(2,"0");return`${a.getFullYear()}-${i(a.getMonth()+1)}-${i(a.getDate())}T${i(a.getHours())}:${i(a.getMinutes())}`}function Qn(t){if(!Number.isFinite(Number(t)))return"";try{return new Intl.DateTimeFormat("en-GB",{weekday:"long",day:"numeric",month:"long",hour:"2-digit",minute:"2-digit"}).format(new Date(Number(t)))}catch{return""}}function Qf(t,a){const i=Number.isFinite(Number(t))?Math.floor(Number(t)/6e4):null,n=Number.isFinite(Number(a))?Math.floor(Number(a)/6e4):null;return i===n}function eg({meeting:t,busy:a=!1,error:i=null,onSave:n,onClose:o,buildReschedulePreview:s}){const[l]=f.useState(()=>t!=null&&t.recurring&&!(t!=null&&t.personal)?Ms(t,Date.now()):null),[r,d]=f.useState(()=>(t==null?void 0:t.title)||""),[m,c]=f.useState(()=>Xf(l?l.at:t==null?void 0:t.scheduled_at)),[g,h]=f.useState("one"),[p,x]=f.useState(()=>String((t==null?void 0:t.duration_min)||60)),[b,u]=f.useState(()=>!!(t!=null&&t.recurring)),[w,v]=f.useState(()=>(t==null?void 0:t.team_calendar)===!0),[j,_]=f.useState(()=>(t==null?void 0:t.identity_color)||""),[C,y]=f.useState(()=>(t==null?void 0:t.details)||""),[z,T]=f.useState(!0),[I,D]=f.useState(!1),$=l?l.at:Number.isFinite(Number(t==null?void 0:t.scheduled_at))?Number(t.scheduled_at):null,q=m?new Date(m).getTime():null,R=!Qf($,Number.isFinite(q)?q:null),O=Array.isArray(t==null?void 0:t.invited_emails)?t.invited_emails.length:0,k=R&&O>0&&Number.isFinite(q),N=!!l&&b&&R&&Number.isFinite(q),L=N?g:"all",B=R&&Number.isFinite(q)&&q<Date.now(),P=R?l?L==="one"?{moved_occurrences:Yf(t,l.from,q)}:Number.isFinite(q)?{scheduled_at:Number(t.scheduled_at)+(q-l.from),moved_occurrences:[]}:{scheduled_at:null,moved_occurrences:[]}:{scheduled_at:Number.isFinite(q)?q:null}:{},E=f.useMemo(()=>t!=null&&t.personal?{title:r,identity_color:j||null,details:C}:{title:r,...P,duration_min:Number(p)||60,recurring:b,team_calendar:w,identity_color:j||null,details:C},[t==null?void 0:t.personal,r,q,R,L,p,b,w,j,C]),Y=!!(t!=null&&t.personal),S=r!==((t==null?void 0:t.t
683itle)||"")||R||String(p)!==String((t==null?void 0:t.duration_min)||60)||b!==!!(t!=null&&t.recurring)||w!==((t==null?void 0:t.team_calendar)===!0)||(j||"")!==((t==null?void 0:t.identity_color)||"")||C!==((t==null?void 0:t.details)||""),W=f.useRef({});W.current={dirty:S,busy:a,patch:E,canNotify:k,notify:z,effScope:L,oldWhen:$,newWhen:q};function M(){if(!W.current.busy){if(W.current.dirty){D(!0);return}o==null||o()}}function J(){const Q=W.current;!Q.dirty||Q.busy||n==null||n(Q.patch,{notify:Q.canNotify&&Q.notify,scope:Q.effScope,oldWhen:Q.oldWhen,newWhen:Q.newWhen})}f.useEffect(()=>{const Q=le=>{if(le.key==="Escape"){le.preventDefault(),M();return}(le.metaKey||le.ctrlKey)&&(le.key==="s"||le.key==="S")&&(le.preventDefault(),J())};return window.addEventListener("keydown",Q),()=>window.removeEventListener("keydown",Q)},[]);const V=k&&z&&typeof s=="function",K=I?e.jsxs("div",{className:"mk-bar mid-bar",children:[e.jsxs("span",{className:"mid-count is-dirty",children:[e.jsx(ba,{size:14,"aria-hidden":"true"})," Unsaved changes. Close anyway?"]}),e.jsx("span",{className:"mk-bar-spacer"}),e.jsx("button",{type:"button",className:"mk-pill is-quiet",onClick:()=>D(!1),children:"Keep editing"}),e.jsxs("button",{type:"button",className:"mk-pill is-danger",onClick:()=>{D(!1),o==null||o()},children:[e.jsx($e,{size:15}),e.jsx("span",{children:"Close and discard"})]})]}):e.jsxs("div",{className:"mk-bar mid-bar",children:[e.jsx("button",{type:"button",className:"mk-pill is-quiet",onClick:M,disabled:a,children:"Cancel"}),e.jsx("span",{className:"mid-count"+(a?"":S?" is-dirty":" is-done"),children:a?"Savingâ¦":S?k&&z?`Not saved yet â saving also warns ${O} ${O===1?"invitee":"invitees"}`:"Not saved yet":"Everything saved"}),e.jsx("span",{className:"mid-kbd",title:"Save from the keyboard",children:"âS"}),e.jsx("span",{className:"mk-bar-spacer"}),e.jsxs("button",{type:"button",className:"mk-pill is-primary mid-send",disabled:!S||a,onClick:J,children:[a?e.jsx(me,{size:15,className:"mid-spin"}):e.jsx(vc,{size:15}),e.jsx("span",{children:a?"Savingâ¦":"Save"})]})]});return ra.createPortal(e.jsx("div",{className:"mid-overlay",style:fn(j||(t==null?void 0:t.identity_color)),role:"dialog","aria-modal":"true","aria-label":"Edit meeting",onMouseDown:Q=>{Q.target===Q.currentTarget&&M()},children:e.jsxs("div",{className:"mid-card mk-scope",style:Ss(j||(t==null?void 0:t.identity_color)),children:[e.jsxs("header",{className:"mid-head",children:[e.jsxs("div",{className:"mid-head-text",children:[e.jsxs("p",{className:"mid-eyebrow",children:[e.jsx(Ut,{size:13,"aria-hidden":"true"})," Edit meeting"]}),e.jsx("h2",{className:"mid-title",children:(t==null?void 0:t.title)||"Meeting"}),e.jsx("p",{className:"mid-when",children:"The link does not change: whoever has it keeps using the same one."})]}),e.jsx("button",{type:"button",className:"mid-x",onClick:M,disabled:a,"aria-label":"Close",children:e.jsx(Ce,{size:18})})]}),e.jsxs("div",{className:`mid-body${V?"":" mid-body-solo"}`,children:[K,e.jsxs("div",{className:"mid-col-left",children:[e.jsxs("div",{className:"mid-section",children:[e.jsx("span",{className:"mid-section-label",children:"Title"}),e.jsx("input",{className:"mt-meet-input",type:"text",value:r,maxLength:80,onChange:Q=>d(Q.target.value),disabled:a})]}),!Y&&e.jsxs("div",{className:"mid-section",children:[e.jsx("span",{className:"mid-section-label",children:"When"}),e.jsx(Pe,{className:"mt-meet-input",type:"datetime-local",value:m,onChange:Q=>c(Q.target.value),disabled:a}),l&&!R&&e.jsx("p",{className:"mid-hint",children:l.moved?"Next meeting, already moved from its usual time.":"Next meeting of the series."}),R&&$&&e.jsxs("p",{className:"mid-warn",children:[e.jsx(ba,{size:14,"aria-hidden":"true"}),e.jsxs("span",{children:["From ",Qn($)," to"," ",Number.isFinite(q)?Qn(q):"no date","."]})]}),B&&e.jsxs("p",{className:"mid-warn",children:[e.jsx(ba,{size:14,"aria-hidden":"true"}),e.jsx("span",{children:"This date is in the past."})]}),N&&e.jsxs("div",{className:"mid-scope",role:"radiogroup","aria-label":"Which meetings move",children:[e.jsx("button",{type:"button",role:"radio","aria-checked":g==="one",disabled:a,className:"mk-pill"+(g==="one"?" is-primary":" is-quiet"),onClick:()=>h("one"),children:e.jsx("span",{children:"Only this one"})}),e.jsx("button",{type:"button",role:"radio","aria-checked":g==="all",disabled:a,className:"mk-pill"+(g==="all"?" is-primary":" is-quiet"),onClick:()=>h("all"),children:e.jsx("span",{children:"All meetings in the series"})}),e.jsx("p",{className:"mid-hint",children:g==="one"?`Only the meeting of ${Qn($)} moves. The following ones stay as they are.`:"Every meeting from now on moves to the new day and time."})]})]}),!Y&&e.jsxs("div",{className:"mid-section",children:[e.jsx("span",{className:"mid-section-label",children:"Duration (minutes)"}),e.jsx("input",{className:"mt-meet-input",type:"number",min:15,step:15,value:p,onChange:Q=>x(Q.target.value),disabled:a})]}),!Y&&e.jsx("div",{className:"mid-section",children:e.jsxs("label",{className:"mt-meet-recurring",children:[e.jsx("input",{type:"checkbox",checked:b,disabled:a,onChange:Q=>u(Q.target.checked)}),e.jsx("span",{children:"Recurring â every week, same room"})]})}),!Y&&e.jsx("div",{className:"mid-section",children:e.jsxs("label",{className:"mt-meet-recurring",children:[e.jsx("input",{type:"checkbox",checked:w,disabled:a,onChange:Q=>v(Q.target.checked)}),e.jsx("span",{children:"Team meeting â also on the Climpact Google Calendar, with the link"})]})}),e.jsxs("div",{className:"mid-section",children:[e.jsx("span",{className:"mid-section-label",children:"Meeting colour"}),e.jsx(Or,{color:j,onColor:_,onReset:()=>
683_(""),swatchColor:Zf,showMatch:!1,showTone:!1,hint:"Dresses the invitation, the row in the portal, the waiting room and the room itself."})]}),e.jsxs("div",{className:"mid-section",children:[e.jsx("span",{className:"mid-section-label",children:"Details (optional)"}),e.jsx(Lr,{className:"rtf-evt",value:C,onChange:y,minHeight:80,placeholder:"Agenda, materials, notesâ¦",ariaLabel:"Meeting details"})]}),k&&e.jsx("div",{className:"mid-section",children:e.jsxs("label",{className:"mt-meet-recurring",children:[e.jsx("input",{type:"checkbox",checked:z,disabled:a,onChange:Q=>T(Q.target.checked)}),e.jsxs("span",{children:["Tell the ",O," ",O===1?"invitee":"invitees"," it has moved"]})]})}),i&&e.jsx("p",{className:"mid-err",children:i})]}),V&&e.jsxs("div",{className:"mid-section mid-section-preview",children:[e.jsx("span",{className:"mid-section-label",children:"Preview â exactly what the invitees receive"}),e.jsx("iframe",{className:"mid-preview",title:"Rescheduling preview",srcDoc:s({...t,...E},$,{scope:L,newWhen:q})})]})]})]})}),document.body)}function tg(t){if(!Number.isFinite(Number(t)))return null;try{return new Intl.DateTimeFormat("en-GB",{weekday:"long",day:"numeric",month:"long",hour:"2-digit",minute:"2-digit"}).format(new Date(Number(t)))}catch{return null}}function ar(t){if(!(t!=null&&t.toDate))return"â";try{return new Intl.DateTimeFormat("en-GB",{day:"2-digit",month:"2-digit",hour:"2-digit",minute:"2-digit"}).format(t.toDate())}catch{return"â"}}function ag({meeting:t,onClose:a,onEdit:i,onInvite:n,onArchive:o,isAdmin:s=!1}){const[l,r]=f.useState(null),[d,m]=f.useState(null),[c,g]=f.useState(!1),[h,p]=f.useState([]),x=Ha((t==null?void 0:t.code)||(t==null?void 0:t.slug)),b=t!=null&&t.recurring?Jf(t):null,u=tg(b||(t==null?void 0:t.scheduled_at)),w=Number(b||(t==null?void 0:t.scheduled_at))>0?Number(b||t.scheduled_at):null,v=w?w+(Number(t==null?void 0:t.duration_min)||60)*6e4:null,j=Array.isArray(t==null?void 0:t.invited_emails)?t.invited_emails:[];f.useEffect(()=>{let k=!1;return(async()=>{const[N,L]=await Promise.all([qr(t.slug).catch(()=>[]),oo(t.slug).catch(()=>[])]);k||(r(N||[]),m(L||[]))})(),()=>{k=!0}},[t==null?void 0:t.slug]),f.useEffect(()=>Jd(t==null?void 0:t.slug,p),[t==null?void 0:t.slug]);const[_,C]=f.useState({});f.useEffect(()=>{let k=!1;return(async()=>{const N=await Promise.all(h.map(async L=>{const B=await oo(L.slug).catch(()=>[]),P=new Map;return(B||[]).forEach(E=>{var V,K,Q,le;const Y=((K=(V=E.joined_at)==null?void 0:V.toMillis)==null?void 0:K.call(V))||0,S=((le=(Q=E.left_at)==null?void 0:Q.toMillis)==null?void 0:le.call(Q))||0,W=Y&&S?Math.max(1,Math.round((S-Y)/6e4)):0,M=E.uid||E.id,J=P.get(M)||{name:E.name||"Participant",min:0};P.set(M,{name:J.name,min:J.min+W})}),[L.slug,[...P.values()]]}));k||C(Object.fromEntries(N))})(),()=>{k=!0}},[h.map(k=>k.slug).join("|")]);const y=k=>{var B,P,E,Y;const N=((P=(B=k.joined_at)==null?void 0:B.toMillis)==null?void 0:P.call(B))||0,L=((Y=(E=k.left_at)==null?void 0:E.toMillis)==null?void 0:Y.call(E))||0;return N&&L?Math.max(1,Math.round((L-N)/6e4)):null};function z(){if(!(d!=null&&d.length))return;const k=E=>E!=null&&E.toDate?E.toDate().toISOString().replace("T"," ").slice(0,19):"",L=[["Meeting","Person","Joined","Left","Minutes"]].concat(d.map(E=>[t.title||t.slug,E.name||"",k(E.joined_at),k(E.left_at),String(y(E)??"")])).map(E=>E.map(Y=>`"${String(Y).replace(/"/g,'""')}"`).join(",")).join(` 684`),B=URL.createObjectURL(new Blob([L],{type:"text/csv;charset=utf-8"})),P=document.createElement("a");P.href=B,P.download=`attendance-${t.code||t.slug}.csv`,document.body.appendChild(P),P.click(),P.remove(),setTimeout(()=>URL.revokeObjectURL(B),3e4)}function T(){w&&Bl(`${t.code||t.slug}.ics`,Ul({title:t.title||"Climpact meeting",start:new Date(w),end:new Date(v),url:x,description:`Join link: ${x}`}))}const[I,D]=f.useState(!1);function $(){if(j.length)try{navigator.clipboard.writeText(j.join(", ")),D(!0),setTimeout(()=>D(!1),1600)}catch{}}async function q(k){if(!(k!=null&&k.path)||!confirm("Delete this recording? This cannot be undone."))return;await Br(k.path)&&r(L=>
684(L||[]).filter(B=>B.path!==k.path))}const R=(d||[]).reduce((k,N)=>k+(y(N)||0),0);async function O(){try{await navigator.clipboard.writeText(x),g(!0),setTimeout(()=>g(!1),1600)}catch{}}return f.useEffect(()=>{const k=N=>{N.key==="Escape"&&(N.preventDefault(),a==null||a())};return window.addEventListener("keydown",k),()=>window.removeEventListener("keydown",k)},[a]),ra.createPortal(e.jsx("div",{className:"mid-overlay",style:fn(t==null?void 0:t.identity_color),role:"dialog","aria-modal":"true","aria-label":"Meeting details",onMouseDown:k=>{k.target===k.currentTarget&&(a==null||a())},children:e.jsxs("div",{className:"mid-card mk-scope",style:Ss(t==null?void 0:t.identity_color),children:[e.jsxs("header",{className:"mid-head",children:[e.jsxs("div",{className:"mid-head-text",children:[e.jsxs("p",{className:"mid-eyebrow",children:[e.jsx(Ut,{size:13,"aria-hidden":"true"})," Meeting"]}),e.jsx("h2",{className:"mid-title",children:(t==null?void 0:t.title)||(t==null?void 0:t.slug)}),e.jsxs("p",{className:"mid-when",children:[u||"No date â the room is always open",t!=null&&t.recurring?", every week":""]})]}),e.jsx("button",{type:"button",className:"mid-x",onClick:a,"aria-label":"Close",children:e.jsx(Ce,{size:18})})]}),e.jsxs("div",{className:"mid-body",children:[e.jsxs("div",{className:"mk-bar mid-bar",children:[e.jsx("span",{className:"mid-count",children:t!=null&&t.recurring?e.jsxs(e.Fragment,{children:[e.jsx(is,{size:13,"aria-hidden":"true"})," Recurring meeting"]}):"One-off meeting"}),e.jsx("span",{className:"mk-bar-spacer"}),n&&e.jsxs("button",{type:"button",className:"mk-pill",onClick:()=>{a==null||a(),n(t)},children:[e.jsx(We,{size:15}),e.jsx("span",{children:"Participants"})]}),o&&!(t!=null&&t.personal)&&e.jsxs("button",{type:"button",className:"mk-pill",onClick:()=>{a==null||a(),o(t)},children:[e.jsx(Bi,{size:15}),e.jsx("span",{children:t!=null&&t.archived?"Restore":"Archive"})]}),i&&e.jsxs("button",{type:"button",className:"mk-pill is-primary",onClick:()=>{a==null||a(),i(t)},children:[e.jsx(wa,{size:15}),e.jsx("span",{children:"Edit"})]})]}),e.jsxs("div",{className:"mid-col-left",children:[e.jsxs("div",{className:"mid-section",children:[e.jsxs("span",{className:"mid-section-label",children:[e.jsx(Tt,{size:14,"aria-hidden":"true"})," Join link"]}),e.jsxs("div",{className:"mdd-link",children:[e.jsx("code",{className:"mdd-code",children:x}),e.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:O,children:[c?e.jsx(ke,{size:15}):e.jsx(gi,{size:15}),e.jsx("span",{children:c?"Copied":"Copy"})]}),e.jsxs("a",{className:"btn btn-primary btn-sm",href:`/meet/${encodeURIComponent(t.slug)}`,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(fi,{size:15}),e.jsx("span",{children:"Join"})]})]}),w&&e.jsxs("div",{className:"mdd-cal",children:[e.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:T,children:[e.jsx(li,{size:15}),e.jsx("span",{children:"Download .ics"})]}),e.jsxs("a",{className:"btn btn-secondary btn-sm",href:Gl({title:t.title||"Climpact meeting",details:`Join link: ${x}`,start:new Date(w),end:new Date(v)}),target:"_blank",rel:"noopener noreferrer",children:[e.jsx(li,{size:15}),e.jsx("span",{children:"Google Calendar"})]})]})]}),e.jsxs("div",{className:"mid-section",children:[e.jsxs("span",{className:"mid-section-label",children:[e.jsx(ia,{size:14,"aria-hidden":"true"})," Invited (",j.length,")",j.length>0&&e.jsxs("button",{type:"button",className:"mdd-mini",onClick:$,title:"Copy every address",children:[I?e.jsx(ke,{size:12}):e.jsx(gi,{size:12})," ",I?"copied":"copy list"]})]}),j.length===0?e.jsx("p",{className:"mdd-empty",children:"Nobody invited: the meeting is reached with the link only."}):e.jsx("ul",{className:"mdd-people",children:j.map(k=>e.jsx("li",{children:k},k))})]}),h.length>0&&e.jsxs("div",{className:"mid-section",children:[e.jsxs("span",{className:"mid-section-label",children:[e.jsx(jc,{size:14,"aria-hidden":"true"})," Breakout rooms (",h.length,")"]}),e.jsx("ul",{className:"mdd-subrooms",children:h.map(k=>{var N;return e.jsxs("li",{children:[e.jsxs("span",{className:"mdd-sub-name",children:[k.breakout_name||k.title||k.slug,((N=_[k.slug])==null?void 0:N.length)>0&&e.jsxs("span",{className:"mdd-sub-stat",children:[_[k.slug].length," ",_[k.slug].length===1?"person":"people",", ",_[k.slug].reduce((L,B)=>L+B.min,0)," min"," â ",_[k.slug].map(L=>
684L.name).join(", ")]})]}),e.jsx("code",{className:"mdd-sub-code",children:k.code||k.slug}),e.jsx("a",{className:"mdd-sub-go",href:`/meet/${encodeURIComponent(k.slug)}`,target:"_blank",rel:"noopener noreferrer",title:"Open the room",children:e.jsx(fi,{size:15})})]},k.slug)})})]}),(t==null?void 0:t.details)&&e.jsxs("div",{className:"mid-section",children:[e.jsx("span",{className:"mid-section-label",children:"Details"}),e.jsx("div",{className:"mdd-details",dangerouslySetInnerHTML:{__html:t.details}})]})]}),e.jsxs("div",{className:"mid-section mid-section-preview mdd-right",children:[e.jsxs("span",{className:"mid-section-label",children:[e.jsx(Gi,{size:14,"aria-hidden":"true"})," Recordings"]}),l===null&&e.jsx("p",{className:"mdd-empty",children:"One momentâ¦"}),(l==null?void 0:l.length)===0&&e.jsx("p",{className:"mdd-empty",children:"No recordings. Recording starts inside the room, from the control bar."}),(l==null?void 0:l.length)>0&&e.jsx("ul",{className:"mdd-recs",children:l.map(k=>e.jsxs("li",{children:[e.jsx("span",{className:"mdd-rec-name",children:k.name||"Recording"}),e.jsx("span",{className:"mdd-rec-meta",children:k.size?Ur(k.size):""}),e.jsx("a",{className:"mdd-rec-dl",href:Je(k.url),target:"_blank",rel:"noopener noreferrer",title:"Download",children:e.jsx(ta,{size:15})}),s&&e.jsx("button",{type:"button",className:"mdd-rec-del",onClick:()=>q(k),title:"Delete the recording",children:e.jsx($e,{size:15})})]},k.path||k.url))}),e.jsxs("span",{className:"mid-section-label mdd-sep",children:[e.jsx(ia,{size:14,"aria-hidden":"true"})," Attendance",(d==null?void 0:d.length)>0&&e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"mdd-tot",children:[e.jsx(ns,{size:12})," ",R," min in total"]}),e.jsxs("button",{type:"button",className:"mdd-mini",onClick:z,title:"Download for reporting",children:[e.jsx(Ui,{size:12})," CSV"]})]})]}),d===null&&e.jsx("p",{className:"mdd-empty",children:"One momentâ¦"}),(d==null?void 0:d.length)===0&&e.jsx("p",{className:"mdd-empty",children:"Nobody joined this meeting yet."}),(d==null?void 0:d.length)>0&&e.jsxs("table",{className:"mdd-att",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Person"}),e.jsx("th",{children:"Joined"}),e.jsx("th",{children:"Left"}),e.jsx("th",{children:"Minutes"})]})}),e.jsx("tbody",{children:d.map(k=>e.jsxs("tr",{children:[e.jsx("td",{children:k.name||"â"}),e.jsx("td",{children:ar(k.joined_at)}),e.jsx("td",{children:k.left_at?ar(k.left_at):"still in"}),e.jsx("td",{children:y(k)??"â"})]},k.id))})]})]})]})]})}),document.body)}function ig({slug:t,title:a,color:i=null,canDelete:n=!1,onClose:o}){const[s,l]=f.useState(null),[r,d]=f.useState(null),[m,c]=f.useState(null),[g,h]=f.useState(null),[p,x]=f.useState(!1),[b,u]=f.useState({}),[w,v]=f.useState({state:"idle",body:""}),[j,_]=f.useState(null),[C,y]=f.useState(""),z=f.useRef(null),T=f.useCallback(async()=>{l(null),l(await qr(t))},[t]);f.useEffect(()=>{T()},[T]),f.useEffect(()=>{const k=N=>{N.key==="Escape"&&(o==null||o())};return window.addEventListener("keydown",k),()=>window.removeEventListener("keydown",k)},[o]);const I=f.useCallback(async(k,N)=>{try{await navigator.clipboard.writeText(k),d(N),setTimeout(()=>d(L=>L===N?null:L),1800)}catch{}},[]),D=f.useCallback(async k=>{if(!m&&confirm("Delete this recording permanently? This cannot be undone.")){c(k.path);try{await Br(k.path),l(N=>N&&N.filter(L=>L.path!==k.path)),h(N=>N===k.path?null:N),x(N=>g===k.path?!1:N)}catch(N){console.error("[meet] delete recording failed",N),alert("Couldnât delete the recording. Try again.")}finally{c(null)}}},[m,g]),$=f.useCallback(k=>{h(k.path),x(!0)},[]),q=(s||[]).find(k=>k.path===g)||null,R=(q==null?void 0:q.transcript)||null;f.useEffect(()=>{let k=!0,N=null;if(y(""),!R){v({state:"idle",body:""}),_(null);return}return v({state:R.txt?"loading":"idle",body:""}),_(null),R.txt&&ru(R.txt).then(L=>{k&&v(L?{state:"ready",body:L}:{state:"error",body:""})}),lu(R).then(L=>{if(L){if(!k){URL.revokeObjectURL(L);return}N=L,_(L)}}),()=>{k=!1,N&&URL.revokeObjectURL(N)}},[R]),f.useEffect(()=>{var L;if(!j)return;const k=z.current,N=(L=k==null?void 0:k.textTracks)==null?void 0:L[0];
684N&&(N.mode="showing")},[j]);const O=f.useMemo(()=>{const k=C.trim();if(!k||w.state!=="ready")return null;const N=k.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),L=w.body.split(new RegExp("("+N+")","ig")),B=Math.floor(L.length/2);return{parts:L,hits:B,q:k}},[C,w]);return e.jsx("div",{className:"mrec-overlay",style:fn(i),role:"dialog","aria-modal":"true","aria-label":"Meeting recordings",onMouseDown:k=>{k.target===k.currentTarget&&(o==null||o())},children:e.jsxs("div",{className:"mrec-card",style:ou(i),children:[e.jsxs("header",{className:"mrec-head",children:[e.jsxs("div",{className:"mrec-head-text",children:[e.jsxs("p",{className:"mrec-eyebrow",children:[e.jsx(yc,{size:13,"aria-hidden":"true"})," Recordings"]}),e.jsx("h2",{className:"mrec-title",children:a||t})]}),e.jsx("button",{type:"button",className:"mrec-x",onClick:o,"aria-label":"Close",children:e.jsx(Ce,{size:18})})]}),e.jsxs("div",{className:`mrec-body${p?" is-phone-preview":""}`,children:[e.jsx("div",{className:"mrec-col-list",children:s===null?e.jsxs("div",{className:"mrec-empty",children:[e.jsx(me,{size:18,className:"mrec-spin"})," ",e.jsx("span",{children:"Loading recordingsâ¦"})]}):s.length===0?e.jsxs("div",{className:"mrec-empty",children:[e.jsx(Gi,{size:22,"aria-hidden":"true"}),e.jsx("p",{children:"No recordings yet. Recordings appear here a short while after a host stops recording (encoding takes a minute or two)."})]}):e.jsx("ul",{className:"mrec-list",children:s.map(k=>{const N=k.durationSec||b[k.path]||null,L=[k.size?Ur(k.size):"",N?cu(N):""].filter(Boolean).join(", ");return e.jsxs("li",{className:`mrec-item${g===k.path?" is-sel":""}`,children:[e.jsxs("button",{type:"button",className:"mrec-item-main",onClick:()=>$(k),"aria-pressed":g===k.path,children:[e.jsx("span",{className:"mrec-item-icon","aria-hidden":"true",children:e.jsx(Gi,{size:17})}),e.jsxs("span",{className:"mrec-item-text",children:[e.jsx("span",{className:"mrec-item-name",children:ir(k)}),e.jsxs("span",{className:"mrec-item-meta",children:[L||"Video file",k.transcript?e.jsxs("span",{className:"mrec-item-tr",children:[e.jsx(Ue,{size:11,"aria-hidden":"true"})," Transcript"]}):null]})]})]}),e.jsxs("div",{className:"mrec-item-actions",children:[e.jsx("a",{className:"mrec-icon-btn",href:Je(k.url),target:"_blank",rel:"noopener noreferrer",download:!0,title:"Download","aria-label":"Download this recording",children:e.jsx(ta,{size:15})}),n&&e.jsx("button",{type:"button",className:"mrec-icon-btn mrec-del",onClick:()=>D(k),disabled:m===k.path,title:"Delete recording","aria-label":"Delete this recording",children:m===k.path?e.jsx(me,{size:15,className:"mrec-spin"}):e.jsx($e,{size:15})})]})]},k.path)})})}),e.jsx("div",{className:"mrec-col-view",children:q?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"mrec-view-head",children:[e.jsxs("button",{type:"button",className:"mrec-back",onClick:()=>x(!1),children:[e.jsx(dn,{size:15,"aria-hidden":"true"})," ",e.jsx("span",{children:"All recordings"})]}),e.jsx("p",{className:"mrec-view-title",children:ir(q)})]}),e.jsx("video",{ref:z,className:"mrec-video",src:q.url,controls:!0,playsInline:!0,preload:"metadata",onLoadedMetadata:k=>{var L;const N=(L=k.currentTarget)==null?void 0:L.duration;Number.isFinite(N)&&N>0&&u(B=>B[q.path]===N?B:{...B,[q.path]:N})},children:j?e.jsx("track",{kind:"captions",label:"Transcript",srcLang:"en",src:j,default:!0}):null},q.path),e.jsxs("div",{className:"mrec-view-actions",children:[e.jsxs("a",{className:"btn btn-primary btn-sm mrec-act",href:Je(q.url),target:"_blank",rel:"noopener noreferrer",download:!0,children:[e.jsx(ta,{size:15})," ",e.jsx("span",{children:"Download"})]}),e.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm mrec-act",onClick:()=>I(q.url,q.path),children:[r===q.path?e.jsx(ke,{size:15}):e.jsx(gi,{size:15}),e.jsx("span",{children:r===q.path?"Copied":"Copy link"})]}),n&&e.jsxs("button",{type:"button",className:"btn btn-ghost btn-sm mrec-act mrec-del",onClick:()=>D(q),disabled:m===q.path,children:[m===q.path?e.jsx(me,{size:15,className:"mrec-spin"}):e.jsx($e,{size:15}),e.jsx("span",{children:"Delete"})]})]}),e.jsxs("section",{className:"mrec-tr",children:[e.jsxs("header",{className:"mrec-tr-head",children:[e.jsxs("p",{className:"mrec-tr-title",children:[e.jsx(Ue,{size:14,"aria-hidden":"true"})," ",e.jsx("span",{children:"Transcript"})]}),R?e.jsxs("div",{className:"mrec-tr-links",children:[R.txt?e.jsxs("a",{className:"mrec-tr-link",href:R.txt,target:"_blank",rel:"noopener noreferrer",download:!0,children:[e.jsx(ta,{size:13,"aria-hidden":"true"})," ",e.jsx("span",{children:"Text"})]}):null,R.srt?e.jsxs("a",{className:"mrec-tr-link",href:R.srt,target:"_blank",rel:"noopener noreferrer",download:!0,children:[e.jsx(_c,{size:13,"aria-hidden":"true"})," ",e.jsx("span",{children:"Subtitles"})]}):null]}):null]}),R?w.state==="loading"?e.jsx("p",{className:"mrec-tr-note",children:e.jsx(xa.List,{rows:3,avatar:!1,label:"Loading the transcript"})}):w.state==="ready"?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"mrec-tr-find",children:[e.jsx(Nc,{size:14,"aria-hidden":"true",style:{flex:"0 0 auto",opacity:.6}}),e.jsx("input",{className:"mrec-tr-input",type:"search",value:C,onChange:k=>y(k.target.value),placeholder:"Find a word or a phrase in this transcriptâ¦","aria-label":"Find in transcript"}),C.trim()&&e.jsxs("span",{className:"mrec-tr-hits",children:[(O==null?void 0:O.hits)||0," ",(O==null?void 0:O.hits)===1?"match":"matches"]})]}),e.jsx("div",{className:"mrec-tr-body",tabIndex:0,children:O?O.parts.map((k,N)=>N%2?e.jsx("mark",{children:k},N):e.jsx("span",{children:k},N)):w.body})]}):w.state==="idle"?e.jsx("p",{className:"mrec-tr-note",children:"Subtitles are attached to the player for this recording. The full text version is not available."}):e.jsx("p",{className:"mrec-tr-note",children:"The transcript file is there but could not be read here. Use Text above to download it."}):e.jsx("p",{className:"mrec-tr-note",children:"No transcript yet. Recordings are transcribed on the server after the call ends, so the text usually appears within a few minutes of the meeting."})]})]}):e.jsxs("div",{className:"mrec-view-empty",children:[e.jsx(du,{size:26,"aria-hidden":"true"}),e.jsx("p",{children:"Pick a recording from the list to play it here. Nothing is downloaded until you choose Download."})]})})]})]})})}function ir(t){return t.createdAt?ng(t.createdAt):t.name||"Recording"}
684function ng(t){return t.toLocaleString("en-GB",{weekday:"short",day:"numeric",month:"short",year:"numeric",hour:"2-digit",minute:"2-digit"})}const nr=new Set;function sg({soloInglese:t=!1,me:a,isAdmin:i,recipientLoader:n,sendMail:o,wrapEmail:s,overview:l=null,showHead:r=!0,archive:d,onArchiveChange:m,onArchivedCount:c,showCreate:g=!0}){const{t:h}=X(),p=t?(F,ce)=>ce:h,[x,b]=f.useState(null),[u,w]=f.useState(""),[v,j]=f.useState(""),[_,C]=f.useState(!1),[y,z]=f.useState(!1),[T,I]=f.useState(""),[D,$]=f.useState(!1),[q,R]=f.useState(null),[O,k]=f.useState(null),[N,L]=f.useState(null),[B,P]=f.useState(!1),[E,Y]=f.useState(null),[S,W]=f.useState([]),[M,J]=f.useState(null),[V,K]=f.useState(null),[Q,le]=f.useState(null),[U,G]=f.useState(!1),ne=typeof d=="boolean",ue=ne?d:U,ge=F=>{const ce=typeof F=="function"?F(ue):F;m?m(ce):G(ce)},[we,Se]=f.useState(!1),[ot,it]=f.useState(null),[mt,Vt]=f.useState({});f.useEffect(()=>Yd(b),[]),f.useEffect(()=>{if(!Array.isArray(x))return;const F=x.filter(ce=>!ce.code&&!ce.personal);F.length!==0&&F.forEach(ce=>{Zd(ce)})},[x]),f.useEffect(()=>{Array.isArray(x)&&x.forEach(F=>{if(!F.slug||F.is_breakout)return;const ce=`${F.slug}:${F.identity_color||""}`;nr.has(ce)||(nr.add(ce),ro(F.code||F.slug,F.slug,F.code||F.slug,F.identity_color||null,F.title||null),F.code&&F.code!==F.slug&&ro(F.slug,F.slug,F.code,F.identity_color||null,F.title||null))})},[x]),f.useEffect(()=>{const F=document.title;return document.title="Climpact Meet",()=>{document.title=F}},[]);const Et=f.useCallback((F,ce)=>{Vt(Ee=>({...Ee,[F]:ce})),ce&&ce.endsWith("-ok")&&setTimeout(()=>Vt(Ee=>Ee[F]===ce?{...Ee,[F]:null}:Ee),2200)},[]),ae=f.useCallback(F=>{window.open(`/meet/${encodeURIComponent(F)}`,"_blank","noopener")},[]),he=Xd(x,a,i),be=he.filter(F=>!F.is_breakout).filter(F=>ue?!!F.archived:!F.archived),A=he.filter(F=>F.archived&&!F.is_breakout).length;f.useEffect(()=>{c&&c(A)},[A,c]);const H=f.useCallback(async()=>{const F=u.trim();if(D)return;$(!0),k(null);const ce=v?new Date(v):null;try{const Ee=await Qd({title:F||"Meeting",me:a,scheduledAt:ce&&!isNaN(ce.getTime())?ce:null,recurring:_,color:T||null,extra:ce&&y?{team_calendar:!0}:null});w(""),j(""),C(!1),z(!1),I(""),ce||ae(Ee)}catch(Ee){console.error("[meetings] create failed",Ee),k(p("Creazione della riunione non riuscita. Riprova.","Couldnât create the meeting. Try again."))}finally{$(!1)}},[u,v,_,y,T,D,a,ae]),Z=f.useCallback(async F=>{if(L(F),Y(null),S.length===0&&typeof n=="function")try{W(await n())}catch(ce){console.error("[meetings] recipient load",ce)}},[S.length,n]),re=f.useCallback(async(F,ce,Ee,xt)=>{if(!N)return;const _t=Array.isArray(F)?F:[],Nt=Array.isArray(Ee)?Ee:[],De=(xt||"")!==(N.identity_color||"");if(!(_t.length===0&&Nt.length===0&&!De)){if(_t.length>0&&(typeof o!="function"||typeof s!="function")){Y(p("Lâemail non è disponibile al momento.","Email is not available right now."));return}P(!0),Y(null);try{if(De&&await eu(N.slug,{color:xt,code:N.code}),_t.length>0){const{subject:Ka,html:Dn,text:Tn}=sr({meeting:N,me:a,note:ce,wrapEmail:s,color:xt});await o({to:_t,subject:Ka,html:Dn,text:Tn,replyTo:a==null?void 0:a.email,rethrow:!0}),await tu(N.slug,_t)}Nt.length>0&&await au(N.slug,Nt),L(null),Et(N.slug,"invite-ok")}catch(Ka){console.error("[meetings] invite save failed",Ka),Y(p("Salvataggio dei partecipanti non riuscito. Riprova.","Couldnât save the participants. Try again."))}finally{P(!1)}}},[N,a,o,s,Et]),pe=f.useCallback(async(F,{notify:ce,scope:Ee="all",oldWhen:xt,newWhen:_t}={})=>{if(V){Se(!0),it(null);try{const Nt=Number.isFinite(Number(xt))?Number(xt):Number.isFinite(Number(V.scheduled_at))?Number(V.scheduled_at):null;if(await iu(V.slug,F,{code:V.code}),ce){const De=Array.isArray(V.invited_emails)?V.invited_emails:[];if(De.length>0&&typeof o=="function"&&typeof s=="function"){const{subject:Ka,html:Dn,text:Tn}=or({meeting:{...V,...F},oldWhen:Nt,newWhen:_t,scope:Ee,me:a,wrapEmail:s});await o({to:De,subject:Ka,html:Dn,text:Tn,replyTo:a==null?void 0:a.email,rethrow:!0})}}K(null),Et(V.slug,"invite-ok")}catch(Nt){console.error("[meetings] edit failed",Nt),it(p("Salvataggio non riuscito. Riprova.","Couldnât save. Try again."))}finally{Se(!1)}}},[V,a,o,s,Et]),Re=f.useCallback(async()=>
684{if(mt.__personal!=="personal"){Vt(F=>({...F,__personal:"personal"}));try{const F=await nu(a);ae(F)}catch(F){console.error("[meetings] personal room failed",F),alert(p("Apertura della tua stanza personale non riuscita. Riprova.","Couldnât open your personal room. Try again."))}finally{Vt(F=>({...F,__personal:null}))}}},[mt.__personal,a,ae]),ma=f.useCallback(async F=>{const ce=typeof F=="string"?F:(F==null?void 0:F.code)||(F==null?void 0:F.slug);try{await navigator.clipboard.writeText(Ha(ce)),R(ce),setTimeout(()=>R(Ee=>Ee===ce?null:Ee),1800)}catch{}},[]),Sn=f.useCallback(async F=>{if(confirm(p("Rimuovere questa riunione dallâelenco? Il link non comparirà più qui (le chiamate in corso non vengono interrotte).","Remove this meeting from the list? The link will stop appearing here (calls in progress are not interrupted).")))try{await su(F)}catch(ce){console.error("[meetings] delete failed",ce),alert(p("Eliminazione non riuscita.","Delete failed."))}},[]);return e.jsxs(e.Fragment,{children:[r&&e.jsx("section",{className:"mt-band mt-band-dark",children:e.jsxs("div",{className:"mt-wrap",children:[e.jsx("p",{className:"mt-eyebrow reveal",children:p("Videoriunioni","Video meetings")}),e.jsx("h1",{className:"mt-section-title reveal","data-d":"1",children:"Climpact Meet"}),e.jsx("p",{className:"mt-section-sub reveal","data-d":"2",children:p("Stanze video del team con link unici. Crea una riunione, condividi il link e apri la chiamata a tutto schermo â lâaccesso è riservato ai membri del team e agli ospiti che inviti.","Team video rooms with unique links. Create a meeting, share the link, and open the call full-screen â access is reserved to team members and the guests you invite.")})]})}),e.jsx("section",{className:"mt-band mt-band-tight",children:e.jsxs("div",{className:"mt-wrap reveal",children:[l,g&&!ue&&e.jsxs("div",{className:"mt-card mt-meet-create meet-toned",style:co(uo(T)),children:[e.jsxs("div",{className:"mt-meet-create-field",children:[e.jsx("label",{className:"mt-meet-label",htmlFor:"mt-meet-title",children:p("Nuova riunione","New meeting")}),e.jsx("input",{id:"mt-meet-title",className:"mt-meet-input",type:"text",placeholder:p("Titolo (es. Riunione di coordinamento)","Title (e.g. Coordination meeting)"),value:u,maxLength:80,onChange:F=>w(F.target.value),onKeyDown:F=>{F.key==="Enter"&&H()},disabled:D})]}),e.jsxs("div",{className:"mt-meet-create-field mt-meet-create-when",children:[e.jsx("label",{className:"mt-meet-label",htmlFor:"mt-meet-when",children:p("Pianifica per dopo (opzionale)","Schedule for later (optional)")}),e.jsx(Pe,{id:"mt-meet-when",className:"mt-meet-input",type:"datetime-local",value:v,onChange:F=>j(F.target.value),disabled:D})]}),e.jsxs("label",{className:"mt-meet-colour",title:p("Colore della riunione","Meeting colour"),children:[e.jsx("span",{className:"mt-meet-label",children:p("Colore","Colour")}),e.jsxs("span",{className:"mt-meet-colour-row",children:[e.jsx("input",{type:"color",className:"mt-meet-colour-dot",value:T||"#3d5afe",onChange:F=>I(F.target.value),disabled:D,"aria-label":p("Colore della riunione","Meeting colour")}),T&&e.jsx("button",{type:"button",className:"mt-meet-colour-clear",onClick:()=>I(""),disabled:D,children:p("Togli","Clear")})]})]}),e.jsxs("label",{className:"mt-meet-recurring",title:p("Riusa la stessa stanza ogni volta (senza suffisso casuale)","Reuse the same room each time (no random suffix)"),children:[e.jsx("input",{type:"checkbox",checked:_,onChange:F=>C(F.target.checked),disabled:D}),e.jsx(is,{size:14,"aria-hidden":"true"}),e.jsx("span",{children:p("Ricorrente","Recurring")})]}),v&&e.jsxs("label",{className:"mt-meet-recurring",title:p("La mette anche nel Google Calendar Climpact, con il collegamento","Also puts it on the Climpact Google Calendar, with the link"),children:[e.jsx("input",{type:"checkbox",checked:y,onChange:F=>z(F.target.checked),disabled:D}),e.jsx(li,{size:14,"aria-hidden":"true"}),e.jsx("span",{children:p("Riunione di team","Team meeting")})]}),e.jsxs("button",{type:"button",className:"btn btn-primary mt-meet-create-btn",onClick:H,disabled:D,children:[D?e.jsx(me,{size:16,className:"mt-meet-spin"}):v?e.jsx(Ut,{size:16}):e.jsx(Le,{size:16}),e.jsx("span",{children:v?p("Pianifica","Schedule"):p("Crea ed entra","Create & join")})]})]}),O&&e.jsx("p",{className:"mt-meet-err",children:O}),!l&&e.jsxs("div",{className:"mt-meet-quick",children:[e.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm mt-meet-act",onClick:Re,disabled:mt.__personal==="personal",children:[mt.__personal==="personal"?e.jsx(me,{size:15,className:"mt-meet-spin"}):e.jsx(na,{size:15}),e.jsx("span",{children:p("La mia stanza personale","My personal room")})]}),e.jsx("span",{className:"mt-meet-quick-hint",children:p("Una stanza permanente con link stabile â comoda per gli 1:1 veloci.","A permanent room with a stable link â handy for quick 1:1s.")})]}),x!==null&&(A>0||ue)&&e.jsxs("div",{className:"mt-meet-listhead",children:[e.jsx("span",{className:"mt-meet-listhead-title",children:ue?p("Archivio","Archive"):p("Riunioni","Meetings")}),!ne&&e.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm mt-meet-act",onClick:()=>ge(F=>!F),children:[ue?e.jsx(Hs,{size:15}):e.jsx(Bi,{size:15}),e.jsx("span",{children:ue?p("Torna alle riunioni","Back to meetings"):`${p("Archivio","Archive")} (${A})`})]})]}),x===null?e.jsx("div",{className:"mt-card mt-meet-empty",children:p("Caricamento riunioniâ¦","Loading meetingsâ¦")}):be.length===0?e.jsxs("div",{className:"mt-card mt-meet-empty",children:[e.jsx(Zs,{size:22,"aria-hidden":"true"}),e.jsx("p",{children:ue?p("Lâarchivio è vuoto.","The archive is empty."):p("Ancora nessuna riunione. Creane una qui s
684opra per ottenere un link condivisibile.","No meetings yet. Create one above to get a shareable link.")})]}):e.jsx("ul",{className:"mt-meet-list",children:be.map(F=>e.jsxs("li",{className:"mt-card mt-meet-item meet-toned",style:co(uo(F.identity_color)),children:[e.jsxs("div",{className:"mt-meet-item-main",children:[e.jsx("div",{className:"mt-meet-item-icon","aria-hidden":"true",children:e.jsx(Zs,{size:18})}),e.jsxs("div",{className:"mt-meet-item-text",children:[e.jsxs("h3",{className:"mt-meet-item-title",children:[e.jsx("button",{type:"button",className:"mt-meet-item-title-btn",onClick:()=>le(F),title:p("Apri la riunione: collegamento, invitati, presenze, registrazioni","Open the meeting: link, invitees, attendance, recordings"),children:F.title||F.slug}),F.recurring?e.jsxs("span",{className:"mt-meet-badge",children:[e.jsx(is,{size:11,"aria-hidden":"true"})," ",p("Ricorrente","Recurring")]}):null,F.team_calendar?e.jsxs("span",{className:"mt-meet-badge",children:[e.jsx(li,{size:11,"aria-hidden":"true"})," ",p("Calendario Climpact","Climpact calendar")]}):null,F.personal?e.jsxs("span",{className:"mt-meet-badge mt-meet-badge-personal",children:[e.jsx(na,{size:11,"aria-hidden":"true"})," ",p("Personale","Personal")]}):null]}),F.scheduled_at?e.jsxs("p",{className:"mt-meet-item-sched",children:[e.jsx(Ut,{size:13,"aria-hidden":"true"})," ",nt(F.scheduled_at,F.recurring,p),(()=>{const ce=F.recurring?Ms(F):null;return ce!=null&&ce.moved?e.jsxs("span",{children:[p(", la prossima spostata a ",", next one moved to "),nt(ce.at,!1,p)]}):null})()]}):null,e.jsxs("p",{className:"mt-meet-item-meta",children:[F.created_by_name?e.jsxs("span",{children:[p("Creata da","Created by")," ",F.created_by_name]}):null,F.created_by_name&&es(F,p)?e.jsx("span",{className:"mt-meet-dot",children:","}):null,es(F,p)?e.jsx("span",{children:es(F,p)}):null,Array.isArray(F.invited_emails)&&F.invited_emails.length>0?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"mt-meet-dot",children:","}),e.jsxs("span",{children:[F.invited_emails.length," ",p(F.invited_emails.length===1?"invitato":"invitati",(F.invited_emails.length===1,"invited"))]})]}):null]})]})]}),e.jsxs("div",{className:"mt-meet-item-actions",children:[e.jsxs("button",{type:"button",className:"btn btn-primary btn-sm mt-meet-act mt-meet-join",onClick:()=>ae(F.slug),children:[e.jsx(fi,{size:15}),e.jsx("span",{children:p("Entra","Join")})]}),e.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm mt-meet-act",onClick:()=>ma(F),children:[q===(F.code||F.slug)?e.jsx(ke,{size:15}):e.jsx(gi,{size:15}),e.jsx("span",{children:q===(F.code||F.slug)?p("Copiato","Copied"):p("Copia link","Copy link")})]}),e.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm mt-meet-act",onClick:()=>Z(F),title:p("Chi partecipa: aggiungi o togli persone. I nuovi ricevono lâinvito e, da quel momento, i promemoria","Who is on this meeting: add or remove people. New ones get the invitation and, from then on, the reminders"),children:[mt[F.slug]==="invite-ok"?e.jsx(ke,{size:15}):e.jsx(We,{size:15}),e.jsx("span",{children:mt[F.slug]==="invite-ok"?p("Salvato","Saved"):p("Partecipanti","Participants")})]}),F.recording||F.recording_started_at||F.recording_stopped_at||F.recording_path?e.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm mt-meet-act",onClick:()=>J(F),title:p("Vedi le registrazioni di questa riunione","View this meeting's recordings"),children:[e.jsx(Gi,{size:15}),e.jsx("span",{children:p("Registrazioni","Recordings")})]}):null,F.scheduled_at?e.jsxs(e.Fragment,{children:[e.jsxs("a",{className:"btn btn-secondary btn-sm mt-meet-act",href:Fs(F),target:"_blank",rel:"noopener noreferrer",title:p("Aggiungi a Google Calendar","Add to Google Calendar"),children:[e.jsx(li,{size:15}),e.jsx("span",{children:"Google"})]}),e.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm mt-meet-act",onClick:()=>og(F),title:p("Scarica invito .ics","Download .ics invite"),children:[e.jsx(ta,{size:15}),e.jsx("span",{children:".ics"})]})]}):null,e.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm mt-meet-act",onClick:()=>{K(F),it(null)},title:p("Modifica titolo, data, orario, durata, colore e dettagli","Edit title, date, time, duration, colour and details"),children:[e.jsx(wa,{size:15}),e.jsx("span",{children:p("Modifica","Edit")})]}),!F.personal&&e.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm mt-meet-act",onClick:()=>lo(F.slug,!F.archived),title:F.archived?p("Riporta la riunione nellâelenco","Bring the meeting back to the list"):p("Togli dallâelenco senza cancellare nulla","Remove from the list without deleting anything"),children:[F.archived?e.jsx(Hs,{size:15}):e.jsx(Bi,{size:15}
684),e.jsx("span",{children:F.archived?p("Ripristina","Restore"):p("Archivia","Archive")})]}),i&&e.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm mt-meet-act mt-meet-del",title:p("Elimina la riunione: non si torna indietro","Delete the meeting: this cannot be undone"),onClick:()=>Sn(F.slug),children:[e.jsx($e,{size:15}),e.jsx("span",{children:p("Elimina","Delete")})]})]})]},F.slug))})]})}),Q&&e.jsx(ag,{meeting:(x||[]).find(F=>F.slug===Q.slug)||Q,onClose:()=>le(null),isAdmin:i,onEdit:F=>{K(F),it(null)},onInvite:F=>Z(F),onArchive:F=>lo(F.slug,!F.archived)}),V&&e.jsx(eg,{meeting:(x||[]).find(F=>F.slug===V.slug)||V,busy:we,error:ot,onClose:()=>{we||K(null)},onSave:pe,buildReschedulePreview:(F,ce,{scope:Ee,newWhen:xt}={})=>or({meeting:F,oldWhen:ce,newWhen:xt,scope:Ee,me:a,wrapEmail:s}).html}),N&&e.jsx(Hf,{meeting:(x||[]).find(F=>F.slug===N.slug)||N,recipients:S,me:a,busy:B,error:E,buildPreview:(F,ce)=>sr({meeting:N,me:a,note:F,wrapEmail:s,color:ce}).html,onSave:re,onClose:()=>{B||(L(null),Y(null))}}),M&&e.jsx(ig,{slug:M.slug,title:M.title||M.slug,color:M.identity_color||null,canDelete:i,onClose:()=>J(null)})]})}function sr({meeting:t,me:a,note:i,wrapEmail:n,color:o}){const s=[o,t.identity_color].find(x=>/^#[0-9a-fA-F]{6}$/.test(String(x||"")))||"#3d5afe",l=t.title||"Meeting",r=Ha(t.code||t.slug),d=(a==null?void 0:a.name)||(a==null?void 0:a.email)||"A teammate",m=Number.isFinite(t.scheduled_at)?t.scheduled_at:null,c=m?`Climpact meeting invitation â ${l} (${nt(m)})`:`Climpact meeting invitation â ${l}`;let g="";i&&(g+=/<[a-z][\s\S]*>/i.test(i)?Gr(i):`<p>${Ve(i)}</p>`),g+=`<p><strong>${Ve(d)}</strong> invites you to a Climpact video meeting.</p>`,m&&(g+=`<p style="margin:10px 0"><strong>${Ve(nt(m))}</strong></p>`,g+=`<p style="margin:10px 0"><a href="${Ve(Fs(t))}" style="color:${s}">Add to Google Calendar</a></p>`),g+=`<p style="margin:10px 0;color:#6b7280;font-size:13px">Or open this link in your browser: <a href="${Ve(r)}" style="color:${s}">${Ve(r)}</a></p>`;const h=n({heading:m?`You're invited: ${l}`:`Join the meeting: ${l}`,bodyHtml:g,ctaLabel:"Join the meeting",ctaHref:r,portalName:"Climpact Meet",policyHref:`${Cr}/privacy`,subBrand:l,tint:s}),p=`${d} invites you to a Climpact video meeting: ${l} 685`+(m?`${nt(m)} 686`:"")+(i?` 687${i} 688`:"")+` 689Join: ${r}`;return{subject:c,html:h,text:p}}function or({meeting:t,oldWhen:a,newWhen:i,scope:n="all",me:o,wrapEmail:s}){const l=t.title||"Meeting",r=Ha(t.code||t.slug),d=(o==null?void 0:o.name)||(o==null?void 0:o.email)||"The organiser",m=/^#[0-9a-fA-F]{6}$/.test(String(t.identity_color||""))?t.identity_color:"#3d5afe",c=!!t.recurring,g=c&&n==="one",h=Number.isFinite(Number(i))?Number(i):Number.isFinite(Number(t.scheduled_at))?Number(t.scheduled_at):null,p=c&&!g&&a?nt(a,!0):null,x=c&&!g&&h?nt(h,!0):null;let b=g?`<p><strong>${Ve(d)}</strong> has moved one meeting of this series.</p>`:c?`<p><strong>${Ve(d)}</strong> has moved every meeting of this series.</p>`:`<p><strong>${Ve(d)}</strong> has rescheduled this meeting.</p>`;a&&(b+=`<p style="margin:10px 0;color:#8a93a3;text-decoration:line-through">${Ve(p||nt(a))}</p>`),h?(b+=`<p style="margin:2px 0 14px;font-size:18px;font-weight:700">${Ve(x||nt(h))}</p>`,g&&t.scheduled_at?b+=`<p style="margin:10px 0">The following meetings stay as usual: ${Ve(nt(t.scheduled_at,!0))}.</p>`:x&&(b+=`<p style="margin:10px 0">Next meeting: ${Ve(nt(h))}.</p>`),b+=`<p style="margin:10px 0"><a href="${Ve(Fs({...t,scheduled_at:h}))}" style="color:${m}">Update your calendar</a></p>`):b+='<p style="margin:10px 0">The meeting no longer has a set date. The room stays open â the link below keeps working.</p>',t.details&&(b+=Gr(String(t.details))),b+=`<p style="margin:10px 0;color:#6b7280;font-size:13px">The link has not changed: <a href="${Ve(r)}" style="color:${m}">${Ve(r)}</a></p>`;const u=s({heading:`Rescheduled: ${l}`,bodyHtml:b,ctaLabel:"Join the meeting",ctaHref:r,portalName:"Climpact Meet",policyHref:`${Cr}/privacy`,subBrand:l,tint:m}),w=(g?`${d} has moved one meeting of "${l}". 690`:`${d} has rescheduled "${l}". 691`)+(a?`Was: ${p||nt(a)} 692`:"")+(h?`Now: ${x||nt(h)} 693`:`The meeting no longer has a set date. 694`)+(g&&t.scheduled_at?`The following meetings stay as usual: ${nt(t.scheduled_at,!0)}. 695`:"")+` 696Join: ${r}`;return{subject:`Meeting rescheduled â ${l}`,html:u,text:w}}function Ve(t){return String(t||"").replace(/[&<>"']/g,a=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[a])}function nt(t,a,i=(n,o)=>o){const n=new Date(t);if(isNaN(n.getTime()))return"";if(a){const o=i("it","en")==="it"?"it-IT":"en-GB",s=n.toLocaleDateString(o,{weekday:"long"}),l=n.toLocaleTimeString(o,{hour:"2-digit",minute:"2-digit"});return i(`Ogni ${s} alle ${l}`,`Every ${s} at ${l}`)}
696return n.toLocaleString("en-GB",{weekday:"short",day:"numeric",month:"short",hour:"2-digit",minute:"2-digit"})}function Fs(t){const a=new Date(t.scheduled_at),i=new Date(t.scheduled_at+(t.duration_min||60)*6e4);return Gl({title:t.title||"Meeting",details:`Join the Climpact meeting: ${Ha(t.code||t.slug)}`,start:a,end:i})}function og(t){const a=new Date(t.scheduled_at),i=new Date(t.scheduled_at+(t.duration_min||60)*6e4),n=Ul({title:t.title||"Meeting",description:"Climpact video meeting",start:a,end:i,url:Ha(t.code||t.slug)});Bl(`${t.slug||"meeting"}.ics`,n)}function es(t,a){const i=a||(m=>m),n=t.last_used_at||t.created_at,o=rg(n);if(!o)return"";const s=Date.now()-o.getTime(),l=Math.floor(s/6e4);if(l<1)return i("proprio ora","just now");if(l<60)return`${l} ${i("min fa","min ago")}`;const r=Math.floor(l/60);if(r<24)return`${r} ${i("h fa","h ago")}`;const d=Math.floor(r/24);return d<7?`${d} ${i("g fa","d ago")}`:o.toLocaleDateString("en-GB",{day:"numeric",month:"short"})}function rg(t){if(!t)return null;if(typeof t.toDate=="function")return t.toDate();if(t.seconds!=null)return new Date(t.seconds*1e3);const a=new Date(t);return isNaN(a.getTime())?null:a}const jn="team_workpackages",yn="team_deliverables",_n="team_milestones",wi="team_tasks",js=[{id:"not_started",label:"Da avviare",labelEn:"Not started",color:"#94a3b8"},{id:"in_progress",label:"In corso",labelEn:"In progress",color:"#6366f1"},{id:"submitted",label:"Sottomesso",labelEn:"Submitted",color:"#d97706"},{id:"delivered",label:"Consegnato",labelEn:"Delivered",color:"#16a34a"},{id:"delayed",label:"In ritardo",labelEn:"Delayed",color:"#dc2626"}],Hl=[{id:"report",label:"Report",labelEn:"Report"},{id:"dataset",label:"Dataset",labelEn:"Dataset"},{id:"publication",label:"Pubblicazione",labelEn:"Publication"},{id:"event",label:"Evento",labelEn:"Event"},{id:"software",label:"Software",labelEn:"Software"},{id:"other",label:"Altro",labelEn:"Other"}],St=[{id:"todo",label:"Da fare",labelEn:"To do",color:"#94a3b8"},{id:"doing",label:"In corso",labelEn:"In progress",color:"#6366f1"},{id:"blocked",label:"Bloccato",labelEn:"Blocked",color:"#dc2626"},{id:"done",label:"Completato",labelEn:"Done",color:"#16a34a"}],ys=[{id:"low",label:"Bassa",labelEn:"Low",color:"#94a3b8"},{id:"normal",label:"Normale",labelEn:"Normal",color:"#6366f1"},{id:"high",label:"Alta",labelEn:"High",color:"#dc2626"}],qi=new Set(["delivered"]);function Ls(t,a){return t&&(a==="en"&&t.labelEn?{...t,label:t.labelEn}:t)}function lg(t,a){return Ls(js.find(i=>i.id===t)||js[0],a)}function cg(t,a){return Ls(St.find(i=>i.id===t)||St[0],a)}function dg(t,a){return Ls(ys.find(i=>i.id===t)||ys[1],a)}function ug(t,a){const i=Hl.find(n=>n.id===t);return i?a==="en"&&i.labelEn?i.labelEn:i.label:a==="en"?"Other":"Altro"}function ga(t){if(!t)return null;const[a,i,n]=String(t).split("-").map(Number);if(!a||!i||!n)return null;const o=new Date(2e3,i-1,n,12,0,0,0);return o.setFullYear(a),o.getTime()}function Qt(t){if(!t&&t!==0)return"";const a=new Date(t);if(Number.isNaN(a.getTime()))return"";const i=n=>String(n).padStart(2,"0");return`${a.getFullYear()}-${i(a.getMonth()+1)}-${i(a.getDate())}`}const mg=["gen","feb","mar","apr","mag","giu","lug","ago","set","ott","nov","dic"];function It(t){if(!t&&t!==0)return"â";const a=new Date(t);return Number.isNaN(a.getTime())?"â":`${a.getDate()} ${mg[a.getMonth()]} ${a.getFullYear()}`}function Kl(t){if(!t&&t!==0)return null;const a=new Date;a.setHours(0,0,0,0);const i=new Date(t);return i.setHours(0,0,0,0),Math.round((i.getTime()-a.getTime())/864e5)}function Lt(t,a){if(a)return!1;const i=Kl(t);return i!==null&&i<0}function Nn(t,a,i){return Ye(Ie(te,t),n=>{const o=n.docs.map(s=>({id:s.id,...s.data()||{}}));a&&o.sort(a),i(o)},n=>{console.error(`[activity] subscribe ${t}`,n),i([])})}const Jl=(t,a)=>String(t.code||"").localeCompare(String(a.code||""),"it",{numeric:!0}),Yl=(t,a)=>(t.due??1/0)-(a.due??1/0),pg=(t,a)=>(t.order??0)-(a.order??0)||Jl(t,a);function hg(t){return Nn(jn,pg,t)}async function fg(t,a){return(await ca(Ie(te,jn),{code:(t.code||"").trim(),title:(t.title||"").trim(),description:t.description||"",lead_uid:t.lead_uid||null,lead_name:t.lead_name||null,start:t.start??null,end:t.end??null,order:Number(t.order)||0,archived:!1,created_by:(a==null?void 0:a.uid)||null,created_at:ie(),updated_at:ie()})).id}async function gg(t,a){await la(oe(te,jn,t),{...a,updated_at:ie()})}async function xg(t){await gt(oe(te,jn,t))}function Zl(t){return Nn(yn,Jl,t)}async function bg(t,a){return(await ca(Ie(te,yn),{code:(t.code||"").trim(),title:(t.title||"").trim(),description:t.description||"",wp_id:t.wp_id||null,type:t.type||"report",status:t.status||"not_started",owner_uid:t.owner_uid||null,owner_name:t.owner_name||null,due:t.due??null,progress:Math.max(0,Math.min(100,Number(t.progress)||0)),notes:t.notes||"",archived:!1,created_by:(a==null?void 0:a.uid)||null,created_at:ie(),updated_at:ie()})).id}async function vg(t,a){await la(oe(te,yn,t),{...a,updated_at:ie()})}async function jg(t){await gt(oe(te,yn,t))}function Xl(t){return Nn(_n,Yl,t)}async function yg(t,a){return(await ca(Ie(te,_n),{code:(t.code||"").trim(),title:(t.title||"").trim(),wp_id:t.wp_id||null,due:t.due??null,achieved:!!t.achieved,achieved_at:t.achieved?ie():null,notes:t.notes||"",archived:!1,created_by:(a==null?void 0:a.uid)||null,created_at:ie(),updated_at:ie()})).id}async function Ql(t,a){const i={...a,updated_at:ie()};Object.prototype.hasOwnProperty.call(a,"achieved")&&(i.achieved_at=a.achieved?ie():null),await la(oe(te,_n,t),i)}async function _g(t){await gt(oe(te,_n,t))}function ec(t){return Nn(wi,Yl,t)}async function Ng(t,a){return(await ca(Ie(te,wi),{title:(t.title||"").trim(),description:t.description||"",wp_id:t.wp_id||null,deliverable_id:t.deliverable_id||null,assignee_uid:t.assignee_uid||null,assignee_name:t.assignee_name||null,due:t.due??null,status:t.status||"todo",priority:t.priority||"normal",created_by:(a==null?void 0:a.uid)||null,created_at:ie(),updated_at:ie(),done_at:null})).id}async function wg(t,a){await la(oe(te,wi,t),{...a,updated_at:ie()})}async function zg(t){await gt(oe(te,wi,t))}async function Cg(t,a){await la(oe(te,wi,t),{status:a,updated_at:ie(),done_at:a==="done"?ie():null})}const ya={"--bg-surface-solid":"#0f121c","--bg-surface-elevated":"rgba(255, 255, 255, 0.05)","--text-primary":"#eef1f8","--text-secondary":"rgba(238, 241, 248, 0.62)","--border":"rgba(255, 255, 255, 0.16)"};function kg(t){return[{id:"deliverables",label:t("Deliverable","Deliverables"),Icon:_a},{id:"workpackages",label:t("Work package","Work packages"),Icon:Ua},{id:"milestones",label:t("Milestone","Milestones"),Icon:un},{id:"tasks",label:t("Task","Tasks"),Icon:_s}]}function Sg({me:t,isAdmin:a,recipientLoader:i}){const{t:n}=X(),o=kg(n),[s,l]=f.useState(null),[r,d]=f.useState(null),[m,c]=f.useState(null),[g,h]=f.useState(null),[p,x]=f.useState([]),[b,u]=f.useState("deliverables"),[w,v]=f.useState(null);f.useEffect(()=>{const z=[hg(l),Zl(d),Xl(c),ec(h)];return()=>z.forEach(T=>{try{T==null||T()}catch{}})},[]),f.useEffect(()=>{let z=!0;return(async()=>
696{if(typeof i=="function")try{const T=await i();z&&Array.isArray(T)&&x(T)}catch(T){console.error("[activity] recipient load",T)}})(),()=>{z=!1}},[i]);const j=f.useMemo(()=>{const z=new Map;return(s||[]).forEach(T=>z.set(T.id,T)),z},[s]),_=f.useCallback(z=>v({kind:z,doc:null}),[]),C=f.useCallback((z,T)=>v({kind:z,doc:T}),[]),y=f.useCallback(()=>v(null),[]);return e.jsxs(e.Fragment,{children:[e.jsx("section",{className:"mt-band mt-band-dark",children:e.jsxs("div",{className:"mt-wrap",children:[e.jsx("p",{className:"mt-eyebrow reveal",children:n("Gruppo di ricerca","Research Team")}),e.jsx("h1",{className:"mt-section-title reveal","data-d":"1",children:n("Attività & deliverable","Activities & deliverables")}),e.jsx("p",{className:"mt-section-sub reveal","data-d":"2",children:n("Work package, deliverable, milestone e task del progetto in un unico piano operativo. Ogni membro del team consulta lo stato di avanzamento; la pianificazione è curata dal coordinamento.","Work packages, deliverables, milestones and tasks of the project in a single operational plan. Every team member can check progress; planning is handled by the coordination.")})]})}),e.jsx("section",{className:"mt-band mt-band-tight",children:e.jsxs("div",{className:"mt-wrap reveal",children:[e.jsx("div",{className:"mt-act-tabs",role:"tablist","aria-label":n("Sezioni attività ","Activity sections"),children:o.map(({id:z,label:T,Icon:I})=>e.jsxs("button",{type:"button",role:"tab","aria-selected":b===z,className:`mt-act-tab${b===z?" is-active":""}`,onClick:()=>u(z),children:[e.jsx(I,{size:16,"aria-hidden":"true"}),e.jsx("span",{children:T})]},z))}),b==="deliverables"&&e.jsx(Tg,{dels:r,wps:s,wpById:j,isAdmin:a,onCreate:()=>_("del"),onEdit:z=>C("del",z)}),b==="workpackages"&&e.jsx(Ig,{wps:s,dels:r,isAdmin:a,onCreate:()=>_("wp"),onEdit:z=>C("wp",z)}),b==="milestones"&&e.jsx(Pg,{miles:m,isAdmin:a,onCreate:()=>_("ms"),onEdit:z=>C("ms",z)}),b==="tasks"&&e.jsx(Eg,{tasks:g,me:t,isAdmin:a,onCreate:()=>_("task"),onEdit:z=>C("task",z)})]})}),w&&e.jsx($g,{kind:w.kind,doc:w.doc,me:t,members:p,wps:s||[],dels:r||[],onClose:y})]})}function Dg(t,a){return t&&(a==="en"&&t.labelEn?{...t,label:t.labelEn}:t)}function wn({label:t}){return e.jsxs("div",{className:"mt-card mt-act-loading",children:[e.jsx(me,{size:18,className:"mt-act-spin","aria-hidden":"true"}),e.jsx("span",{children:t})]})}function Os({Icon:t,children:a}){return e.jsxs("div",{className:"mt-card mt-act-empty",children:[t?e.jsx(t,{size:22,"aria-hidden":"true"}):null,e.jsx("p",{children:a})]})}function zn({eyebrow:t,title:a,sub:i,action:n}){return e.jsxs("div",{className:"mt-act-head",children:[e.jsxs("div",{className:"mt-act-head-text",children:[t?e.jsx("p",{className:"mt-act-head-eyebrow",children:t}):null,e.jsx("h2",{className:"mt-act-head-title",children:a}),i?e.jsx("p",{className:"mt-act-head-sub",children:i}):null]}),n]})}function tc({meta:t}){return e.jsx("span",{className:"mt-act-chip",style:{color:t.color,background:`color-mix(in srgb, ${t.color} 16%, transparent)`,borderColor:`color-mix(in srgb, ${t.color} 38%, transparent)`},children:t.label})}function qs({onEdit:t,onDelete:a}){const{t:i}=X();return e.jsxs("div",{className:"mt-act-rowactions",children:[e.jsx("button",{type:"button",className:"mt-act-iconbtn",onClick:t,"aria-label":i("Modifica","Edit"),title:i("Modifica","Edit"),children:e.jsx(wa,{size:15})}),e.jsx("button",{type:"button",className:"mt-act-iconbtn mt-act-iconbtn-danger",onClick:a,"aria-label":i("Elimina","Delete"),title:i("Elimina","Delete"),children:e.jsx($e,{size:15})})]})}function Tg({dels:t,wps:a,wpById:i,isAdmin:n,onCreate:o,onEdit:s}){const{t:l,lang:r}=X(),d=f.useCallback(async c=>{if(confirm(`${l("Eliminare il deliverable","Delete the deliverable")} â${c.code||c.title||l("senza titolo","untitled")}â?`))try{await jg(c.id)}catch(g){console.error("[activity] delete deliverable",g),alert(l("Eliminazione non riuscita.","Deletion failed."))}},[l]),m=f.useMemo(()=>{if(!t)return null;const c=new Map;for(const h of t){const p=h.wp_id||"__none";c.has(p)||c.set(p,[]),c.get(p).push(h)}const g=[];for(const h of a||[])c.has(h.id)&&(g.push({key:h.id,wp:h,items:c.get(h.id)}),c.delete(h.id));for(const[h,p]of c.entries())h!=="__none"&&g.push({key:h,wp:i.get(h)||null,items:p});return c.has("__none")&&g.push({key:"__none",wp:null,items:c.get("__none")}),g},[t,a,i]);return e.jsxs("div",{className:"mt-act-pane",children:[e.jsx(zn,{eyebrow:l("Piano di lavoro","Work plan"),title:l("Deliverable","Deliverables"),sub:l("I prodotti del progetto raggruppati per work package, con stato e avanzamento.","The project outputs grouped by work package, with status and progress."),action:n?e.jsxs("button",{type:"button",className:"btn btn-primary btn-sm mt-act-add",onClick:o,children:[e.jsx(Le,{size:16}),e.jsx("span",{children:l("Nuovo deliverable","New deliverable")})]}):null}),t===null?e.jsx(wn,{label:l("Caricamento deliverableâ¦","Loading deliverablesâ¦")}):t.length===0?e.jsxs(Os,{Icon:_a,children:[l("Nessun deliverable.","No deliverables.")," ",n?l("Creane uno con il pulsante qui sopra.","Create one with the button above."):l("Il piano non è ancora stato compilato.","The plan has not been filled in yet.")]}):e.jsx("div",{className:"mt-act-groups",children:m.map(c=>e.jsxs("div",{className:"mt-act-group",children:[e.jsxs("h3",{className:"mt-act-group-title",children:[c.wp?e.jsxs(e.Fragment,{children:[c.wp.code?e.jsx("span",{className:"mt-act-group-code",children:c.wp.code}):null,e.jsx("span",{children:c.wp.title||l("Work package","Work package")})]}):e.jsx("span",{className:"mt-act-group-none",children:l("Senza WP","No WP")}),e.jsx("span",{className:"mt-act-group-count",children:c.items.length})]}),e.jsx("ul",{className:"mt-act-list",children:c.items.map(g=>{const h=lg(g.status,r),p=Lt(g.due,qi.has(g.status)),x=Math.max(0,Math.min(100,Number(g.progress)||0));return e.jsxs("li",{className:"mt-card mt-act-del",children:[e.jsxs("div",{className:"mt-act-del-main",children:[e.jsxs("div",{className:"mt-act-del-titleline",children:[g.code?e.jsx("span",{className:"mt-act-code",children:g.code}):null,e.jsx("span",{className:"mt-act-del-title",children:g.title||l("Senza titolo","Untitled")})]}),e.jsxs("div",{className:"mt-act-del-meta",children:[e.jsx("span",{className:"mt-act-tag",children:ug(g.type,r)}),g.owner_name?e.jsxs("span",{className:"mt-act-meta-item",children:[e.jsx(na,{size:13,"aria-hidden":"true"}),g.owner_name]}):null,g.due||g.due===0?e.jsxs("span",{className:`mt-act-meta-item${p?" is-overdue":""}`,children:[e.jsx(Ut,{size:13,"aria-hidden":"true"}),It(g.due)]}):null]}),e.jsx("div",{className:"mt-act-progress",role:"progressbar","aria-valuenow":x,"aria-valuemin":0,"aria-valuemax":100,children:e.jsx("span",{className:"mt-act-progress-fill",style:{width:`${x}%`,background:h.color}})})]}),e.jsxs("div",{className:"mt-act-del-side",children:[e.jsx(tc,{meta:h}),n&&e.jsx(qs,{onEdit:()=>s(g),onDelete:()=>d(g)})]})]},g.id)})})]},c.key))})]})}function Ig({wps:t,dels:a,isAdmin:i,onCreate:n,onEdit:o}){const{t:s}=X(),l=f.useCallback(async d=>{if(confirm(`${s("Eliminare il work package","Delete the work package")} â${d.code||d.title||s("senza titolo","untitled")}â?`))try{await xg(d.id)}catch(m){console.error("[activity] delete wp",m),alert(s("Eliminazione non riuscita.","Deletion failed."))}},[s]),r=f.useMemo(()=>{const d=new Map;
696return(a||[]).forEach(m=>{m.wp_id&&d.set(m.wp_id,(d.get(m.wp_id)||0)+1)}),d},[a]);return e.jsxs("div",{className:"mt-act-pane",children:[e.jsx(zn,{eyebrow:s("Struttura del progetto","Project structure"),title:s("Work package","Work packages"),sub:s("Le linee di lavoro in cui è articolato il progetto.","The work streams the project is organised into."),action:i?e.jsxs("button",{type:"button",className:"btn btn-primary btn-sm mt-act-add",onClick:n,children:[e.jsx(Le,{size:16}),e.jsx("span",{children:s("Nuovo work package","New work package")})]}):null}),t===null?e.jsx(wn,{label:s("Caricamento work packageâ¦","Loading work packagesâ¦")}):t.length===0?e.jsxs(Os,{Icon:Ua,children:[s("Nessun work package.","No work packages.")," ",i?s("Creane uno con il pulsante qui sopra.","Create one with the button above."):s("La struttura non è ancora stata definita.","The structure has not been defined yet.")]}):e.jsx("div",{className:"mt-act-wpgrid",children:t.map(d=>{const m=d.start||d.start===0||d.end||d.end===0;return e.jsxs("div",{className:"mt-card mt-act-wp",children:[e.jsxs("div",{className:"mt-act-wp-head",children:[e.jsx("div",{className:"mt-act-wp-icon","aria-hidden":"true",children:e.jsx(Ua,{size:18})}),e.jsxs("div",{className:"mt-act-wp-id",children:[d.code?e.jsx("span",{className:"mt-act-code",children:d.code}):null,e.jsx("h3",{className:"mt-act-wp-title",children:d.title||s("Senza titolo","Untitled")})]}),i&&e.jsx(qs,{onEdit:()=>o(d),onDelete:()=>l(d)})]}),d.description?e.jsx("p",{className:"mt-act-wp-desc",children:d.description}):null,e.jsxs("div",{className:"mt-act-wp-meta",children:[d.lead_name?e.jsxs("span",{className:"mt-act-meta-item",children:[e.jsx(na,{size:13,"aria-hidden":"true"}),d.lead_name]}):null,m?e.jsxs("span",{className:"mt-act-meta-item",children:[e.jsx(Ut,{size:13,"aria-hidden":"true"}),It(d.start)," â ",It(d.end)]}):null,e.jsxs("span",{className:"mt-act-meta-item mt-act-wp-count",children:[e.jsx(_a,{size:13,"aria-hidden":"true"}),r.get(d.id)||0," ",s("deliverable","deliverables")]})]})]},d.id)})})]})}function Pg({miles:t,isAdmin:a,onCreate:i,onEdit:n}){const{t:o}=X(),s=f.useCallback(async r=>{if(confirm(`${o("Eliminare la milestone","Delete the milestone")} â${r.code||r.title||o("senza titolo","untitled")}â?`))try{await _g(r.id)}catch(d){console.error("[activity] delete milestone",d),alert(o("Eliminazione non riuscita.","Deletion failed."))}},[o]),l=f.useCallback(async r=>{try{await Ql(r.id,{achieved:!r.achieved})}catch(d){console.error("[activity] toggle milestone",d),alert(o("Aggiornamento non riuscito.","Update failed."))}},[o]);return e.jsxs("div",{className:"mt-act-pane",children:[e.jsx(zn,{eyebrow:o("Tappe del progetto","Project milestones"),title:o("Milestone","Milestones"),sub:o("I traguardi del progetto in ordine cronologico.","The project milestones in chronological order."),action:a?e.jsxs("button",{type:"button",className:"btn btn-primary btn-sm mt-act-add",onClick:i,children:[e.jsx(Le,{size:16}),e.jsx("span",{children:o("Nuova milestone","New milestone")})]}):null}),t===null?e.jsx(wn,{label:o("Caricamento milestoneâ¦","Loading milestonesâ¦")}):t.length===0?e.jsxs(Os,{Icon:un,children:[o("Nessuna milestone.","No milestones.")," ",a?o("Creane una con il pulsante qui sopra.","Create one with the button above."):o("Non sono ancora state definite tappe.","No milestones have been defined yet.")]}):e.jsx("ol",{className:"mt-act-timeline",children:t.map(r=>{const d=!r.achieved&&Lt(r.due,!1);return e.jsxs("li",{className:`mt-act-tl-item${r.achieved?" is-done":""}`,children:[e.jsx("span",{className:"mt-act-tl-dot","aria-hidden":"true",children:r.achieved?e.jsx(ke,{size:12}):null}),e.jsxs("div",{className:"mt-card mt-act-tl-card",children:[e.jsxs("div",{className:"mt-act-tl-main",children:[e.jsxs("div",{className:"mt-act-del-titleline",children:[r.code?e.jsx("span",{className:"mt-act-code",children:r.code}):null,e.jsx("span",{className:"mt-act-del-title",children:r.title||o("Senza titolo","Untitled")})]}),e.jsxs("div",{className:"mt-act-del-meta",children:[r.due||r.due===0?e.jsxs("span",{className:`mt-act-meta-item${d?" is-overdue":""}`,children:[e.jsx(Ut,{size:13,"aria-hidden":"true"}),It(r.due)]}):null,r.notes?e.jsx("span",{className:"mt-act-meta-item mt-act-tl-notes",children:r.notes}):null]})]}),e.jsxs("div",{className:"mt-act-tl-side",children:[a?e.jsxs("button",{type:"button",className:`mt-act-achieve${r.achieved?" is-on":""}`,onClick:()=>l(r),"aria-pressed":!!r.achieved,children:[e.jsx("span",{className:"mt-act-achieve-box","aria-hidden":"true",children:r.achieved?e.jsx(ke,{size:13}):null}
696),e.jsx("span",{children:r.achieved?o("Raggiunta","Achieved"):o("Da raggiungere","Outstanding")})]}):e.jsx("span",{className:`mt-act-state${r.achieved?" is-on":""}`,children:r.achieved?e.jsxs(e.Fragment,{children:[e.jsx(ke,{size:14,"aria-hidden":"true"}),o("Raggiunta","Achieved")]}):o("In attesa","Pending")}),a&&e.jsx(qs,{onEdit:()=>n(r),onDelete:()=>s(r)})]})]})]},r.id)})})]})}function Eg({tasks:t,me:a,isAdmin:i,onCreate:n,onEdit:o}){const{t:s,lang:l}=X(),r=f.useCallback(async c=>{if(confirm(`${s("Eliminare il task","Delete the task")} â${c.title||s("senza titolo","untitled")}â?`))try{await zg(c.id)}catch(g){console.error("[activity] delete task",g),alert(s("Eliminazione non riuscita.","Deletion failed."))}},[s]),d=f.useCallback(async(c,g)=>{if(g!==c.status)try{await Cg(c.id,g)}catch(h){console.error("[activity] move task",h),alert(s("Spostamento non riuscito.","Move failed."))}},[s]),m=f.useMemo(()=>{const c=new Map(St.map(g=>[g.id,[]]));return(t||[]).forEach(g=>{(c.get(g.status)||c.get("todo")).push(g)}),St.map(g=>({meta:Dg(g,l),items:c.get(g.id)||[]}))},[t,l]);return e.jsxs("div",{className:"mt-act-pane",children:[e.jsx(zn,{eyebrow:s("Lavagna operativa","Operational board"),title:s("Task","Tasks"),sub:s("Le attività assegnate al team. Cambia lo stato per aggiornare l'avanzamento.","The tasks assigned to the team. Change the status to update progress."),action:i?e.jsxs("button",{type:"button",className:"btn btn-primary btn-sm mt-act-add",onClick:n,children:[e.jsx(Le,{size:16}),e.jsx("span",{children:s("Nuovo task","New task")})]}):null}),t===null?e.jsx(wn,{label:s("Caricamento taskâ¦","Loading tasksâ¦")}):e.jsx("div",{className:"mt-act-kanban",children:m.map(c=>e.jsxs("section",{className:"mt-act-col",children:[e.jsxs("header",{className:"mt-act-col-head",style:{borderTopColor:c.meta.color},children:[e.jsx("span",{className:"mt-act-col-dot",style:{background:c.meta.color},"aria-hidden":"true"}),e.jsx("span",{className:"mt-act-col-title",children:c.meta.label}),e.jsx("span",{className:"mt-act-col-count",children:c.items.length})]}),e.jsx("div",{className:"mt-act-col-body",children:c.items.length===0?e.jsx("p",{className:"mt-act-col-empty",children:s("Nessun task","No tasks")}):c.items.map(g=>{const h=i||(a==null?void 0:a.uid)&&a.uid===g.assignee_uid,p=dg(g.priority,l),x=(g.due||g.due===0)&&g.status!=="done"&&Lt(g.due,!1);return e.jsxs("article",{className:"mt-act-task",children:[e.jsxs("div",{className:"mt-act-task-top",children:[e.jsx("span",{className:"mt-act-task-prio",style:{background:p.color},title:`${s("Priorità ","Priority")}: ${p.label}`,"aria-label":`${s("Priorità ","Priority")}: ${p.label}`}),e.jsx("h4",{className:"mt-act-task-title",children:g.title||s("Senza titolo","Untitled")}),i&&e.jsx("button",{type:"button",className:"mt-act-iconbtn mt-act-iconbtn-danger mt-act-task-del",onClick:()=>r(g),"aria-label":s("Elimina","Delete"),title:s("Elimina","Delete"),children:e.jsx($e,{size:14})})]}),e.jsxs("div",{className:"mt-act-task-meta",children:[g.assignee_name?e.jsxs("span",{className:"mt-act-meta-item",children:[e.jsx(na,{size:12,"aria-hidden":"true"}),g.assignee_name]}):e.jsx("span",{className:"mt-act-meta-item mt-act-task-unassigned",children:s("Non assegnato","Unassigned")}),g.due||g.due===0?e.jsxs("span",{className:`mt-act-meta-item${x?" is-overdue":""}`,children:[e.jsx(Ut,{size:12,"aria-hidden":"true"}),It(g.due)]}):null]}),e.jsxs("div",{className:"mt-act-task-foot",children:[h?e.jsx(Ag,{task:g,onMove:d}):e.jsx(tc,{meta:cg(g.status,l)}),i&&e.jsx("button",{type:"button",className:"mt-act-iconbtn mt-act-task-edit",onClick:()=>o(g),"aria-label":s("Modifica","Edit"),title:s("Modifica","Edit"),children:e.jsx(wa,{size:14})})]})]},g.id)})})]},c.meta.id))})]})}function Ag({task:t,onMove:a}){const{t:i,lang:n}=X(),o=d=>d?n==="en"&&d.labelEn?d.labelEn:d.label:"",s=St.findIndex(d=>d.id===t.status),l=s>0?St[s-1]:null,r=s>=0&&s<St.length-1?St[s+1]:null;return e.jsxs("div",{className:"mt-act-move",children:[e.jsx("button",{type:"button",className:"mt-act-move-step",disabled:!l,onClick:()=>
696l&&a(t,l.id),"aria-label":l?`${i("Sposta in","Move to")} ${o(l)}`:i("Stato iniziale","First status"),title:l?`${i("Sposta in","Move to")} ${o(l)}`:void 0,children:e.jsx(dn,{size:15})}),e.jsx(xe,{tone:"inherit",size:"xs",block:!1,matchWidth:!1,style:{flex:"1 1 auto",minWidth:0},value:t.status,onChange:d=>a(t,d),ariaLabel:i("Stato del task","Task status"),options:St.map(d=>({value:d.id,label:o(d)}))}),e.jsx("button",{type:"button",className:"mt-act-move-step",disabled:!r,onClick:()=>r&&a(t,r.id),"aria-label":r?`${i("Sposta in","Move to")} ${o(r)}`:i("Stato finale","Last status"),title:r?`${i("Sposta in","Move to")} ${o(r)}`:void 0,children:e.jsx(yt,{size:15})})]})}const rr={del:{eyebrow:"Deliverable",eyebrowEn:"Deliverable",Icon:_a},wp:{eyebrow:"Work package",eyebrowEn:"Work package",Icon:Ua},ms:{eyebrow:"Milestone",eyebrowEn:"Milestone",Icon:un},task:{eyebrow:"Task",eyebrowEn:"Task",Icon:_s}};function $g({kind:t,doc:a,me:i,members:n,wps:o,dels:s,onClose:l}){const{t:r}=X(),d=!!a,m=rr[t]||rr.del,[c,g]=f.useState(()=>Og(t,a)),[h,p]=f.useState(!1),[x,b]=f.useState(null);f.useEffect(()=>{const _=C=>{C.key==="Escape"&&!h&&(l==null||l())};return window.addEventListener("keydown",_),()=>window.removeEventListener("keydown",_)},[h,l]);const u=f.useCallback((_,C)=>g(y=>({...y,[_]:C})),[]),w=f.useCallback(_=>{const C=n.find(y=>y.uid===_);return C&&(C.name||C.email)||null},[n]),v=f.useCallback(async _=>{var C;if((C=_==null?void 0:_.preventDefault)==null||C.call(_),!h){if(!String(c.title||"").trim()){b(r("Il titolo è obbligatorio.","The title is required."));return}p(!0),b(null);try{const y=qg(t,c,w);t==="del"?d?await vg(a.id,y):await bg(y,i):t==="wp"?d?await gg(a.id,y):await fg(y,i):t==="ms"?d?await Ql(a.id,y):await yg(y,i):t==="task"&&(d?await wg(a.id,y):await Ng(y,i)),l==null||l()}catch(y){console.error("[activity] save failed",y),b(r("Salvataggio non riuscito. Riprova.","Save failed. Try again."))}finally{p(!1)}}},[h,c,t,d,a,i,w,l]),j=m.Icon;return e.jsx("div",{className:"mt-act-overlay portal-site",role:"dialog","aria-modal":"true","aria-label":`${d?r("Modifica","Edit"):r("Nuovo","New")} ${m.eyebrow.toLowerCase()}`,onMouseDown:_=>{_.target===_.currentTarget&&!h&&(l==null||l())},children:e.jsxs("form",{className:"mt-act-modal",onSubmit:v,children:[e.jsxs("header",{className:"mt-act-modal-head",children:[e.jsxs("div",{className:"mt-act-modal-headtext",children:[e.jsxs("p",{className:"mt-act-modal-eyebrow",children:[e.jsx(j,{size:13,"aria-hidden":"true"})," ",m.eyebrow]}),e.jsx("h2",{className:"mt-act-modal-title",children:d?r("Modifica","Edit"):`${r("Nuovo","New")} ${m.eyebrow.toLowerCase()}`})]}),e.jsx("button",{type:"button",className:"mt-act-modal-x",onClick:l,disabled:h,"aria-label":r("Chiudi","Close"),children:e.jsx(Ce,{size:18})})]}),e.jsxs("div",{className:"mt-act-modal-body",children:[t==="del"&&e.jsx(Rg,{form:c,set:u,wps:o,members:n}),t==="wp"&&e.jsx(Mg,{form:c,set:u,members:n}),t==="ms"&&e.jsx(Fg,{form:c,set:u,wps:o}),t==="task"&&e.jsx(Lg,{form:c,set:u,wps:o,dels:s,members:n}),x&&e.jsxs("p",{className:"mt-act-modal-err",children:[e.jsx(at,{size:15,"aria-hidden":"true"})," ",x]})]}),e.jsxs("footer",{className:"mt-act-modal-foot",children:[e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:l,disabled:h,children:r("Annulla","Cancel")}),e.jsxs("button",{type:"submit",className:"btn btn-primary btn-sm mt-act-modal-save",disabled:h,children:[h?e.jsx(me,{size:15,className:"mt-act-spin"}):e.jsx(ke,{size:15}),e.jsx("span",{children:h?r("Salvataggioâ¦","Savingâ¦"):d?r("Salva","Save"):r("Crea","Create")})]})]})]})})}function ve({label:t,children:a,wide:i}){return e.jsxs("label",{className:`mt-act-field${i?" is-wide":""}`,children:[e.jsx("span",{className:"mt-act-field-label",children:t}),a]})}function Us({value:t,onChange:a,members:i,placeholder:n,ariaLabel:o}){const{t:s}=X(),l=n||s("â nessuno â","â none â");return e.jsx(xe,{tone:"inherit",style:ya,matchWidth:!1,value:t||"",onChange:r=>a(r),ariaLabel:o,options:[{value:"",label:l},...i.map(r=>({value:r.uid,label:r.name||r.email||r.uid}))]})}function Bs({value:t,onChange:a,wps:i,ariaLabel:n}){const{t:o}=X();return e.jsx(xe,{tone:"inherit",style:ya,matchWidth:!1,value:t||"",onChange:s=>a(s),ariaLabel:n,options:[{value:"",label:o("â nessuno â","â none â")},...i.map(s=>({value:s.id,label:`${s.code?`${s.code}, `:""}${s.title||o("Senza titolo","Untitled")}`}))]})}function Rg({form:t,set:a,wps:i,members:n}){const{t:o,lang:s}=X();return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"mt-act-grid",children:[e.jsx(ve,{label:o("Codice","Code"),children:e.jsx("input",{className:"mt-act-input",type:"text",value:t.code,maxLength:24,placeholder:"D1.1",onChange:l=>a("code",l.target.value)})}),e.jsx(ve,{label:o("Titolo","Title"),wide:!0,children:e.jsx("input",{className:"mt-act-input",type:"text",value:t.title,maxLength:160,placeholder:o("Titolo del deliverable","Deliverable title"),onChange:l=>a("title",l.target.value)})})]}),e.jsx(ve,{label:o("Descrizione","Description"),wide:!0,children:e.jsx("textarea",{className:"mt-act-input mt-act-textarea",rows:3,value:t.description,onChange:l=>a("description",l.target.value)})}),e.jsxs("div",{className:"mt-act-grid",children:[e.jsx(ve,{label:o("Work package","Work package"),children:e.jsx(Bs,{value:t.wp_id,onChange:l=>a("wp_id",l),wps:i,ariaLabel:o("Work package","Work package")})}),e.jsx(ve,{label:o("Tipo","Type"),children:e.jsx(xe,{tone:"inherit",style:ya,value:t.type,onCh
696ange:l=>a("type",l),ariaLabel:o("Tipo","Type"),options:Hl.map(l=>({value:l.id,label:s==="en"&&l.labelEn?l.labelEn:l.label}))})})]}),e.jsxs("div",{className:"mt-act-grid",children:[e.jsx(ve,{label:o("Stato","Status"),children:e.jsx(xe,{tone:"inherit",style:ya,value:t.status,onChange:l=>a("status",l),ariaLabel:o("Stato","Status"),options:js.map(l=>({value:l.id,label:s==="en"&&l.labelEn?l.labelEn:l.label}))})}),e.jsx(ve,{label:o("Responsabile","Owner"),children:e.jsx(Us,{value:t.owner_uid,onChange:l=>a("owner_uid",l),members:n,ariaLabel:o("Responsabile","Owner")})})]}),e.jsxs("div",{className:"mt-act-grid",children:[e.jsx(ve,{label:o("Scadenza","Due date"),children:e.jsx(Pe,{className:"mt-act-input",value:t.due,onChange:l=>a("due",l.target.value)})}),e.jsx(ve,{label:`${o("Avanzamento","Progress")} (${Math.max(0,Math.min(100,Number(t.progress)||0))}%)`,children:e.jsx("input",{className:"mt-act-range",type:"range",min:0,max:100,step:5,value:Number(t.progress)||0,onChange:l=>a("progress",l.target.value)})})]}),e.jsx(ve,{label:o("Note","Notes"),wide:!0,children:e.jsx("textarea",{className:"mt-act-input mt-act-textarea",rows:2,value:t.notes,onChange:l=>a("notes",l.target.value)})})]})}function Mg({form:t,set:a,members:i}){const{t:n}=X();return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"mt-act-grid",children:[e.jsx(ve,{label:n("Codice","Code"),children:e.jsx("input",{className:"mt-act-input",type:"text",value:t.code,maxLength:24,placeholder:"WP1",onChange:o=>a("code",o.target.value)})}),e.jsx(ve,{label:n("Titolo","Title"),wide:!0,children:e.jsx("input",{className:"mt-act-input",type:"text",value:t.title,maxLength:160,placeholder:n("Titolo del work package","Work package title"),onChange:o=>a("title",o.target.value)})})]}),e.jsx(ve,{label:n("Descrizione","Description"),wide:!0,children:e.jsx("textarea",{className:"mt-act-input mt-act-textarea",rows:3,value:t.description,onChange:o=>a("description",o.target.value)})}),e.jsxs("div",{className:"mt-act-grid",children:[e.jsx(ve,{label:n("Responsabile (lead)","Lead"),children:e.jsx(Us,{value:t.lead_uid,onChange:o=>a("lead_uid",o),members:i,ariaLabel:n("Responsabile (lead)","Lead")})}),e.jsx(ve,{label:n("Ordine","Order"),children:e.jsx("input",{className:"mt-act-input",type:"number",value:t.order,onChange:o=>a("order",o.target.value)})})]}),e.jsxs("div",{className:"mt-act-grid",children:[e.jsx(ve,{label:n("Inizio","Start"),children:e.jsx(Pe,{className:"mt-act-input",value:t.start,onChange:o=>a("start",o.target.value)})}),e.jsx(ve,{label:n("Fine","End"),children:e.jsx(Pe,{className:"mt-act-input",value:t.end,onChange:o=>a("end",o.target.value)})})]})]})}function Fg({form:t,set:a,wps:i}){const{t:n}=X();return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"mt-act-grid",children:[e.jsx(ve,{label:n("Codice","Code"),children:e.jsx("input",{className:"mt-act-input",type:"text",value:t.code,maxLength:24,placeholder:"M1",onChange:o=>a("code",o.target.value)})}),e.jsx(ve,{label:n("Titolo","Title"),wide:!0,children:e.jsx("input",{className:"mt-act-input",type:"text",value:t.title,maxLength:160,placeholder:n("Titolo della milestone","Milestone title"),onChange:o=>a("title",o.target.value)})})]}),e.jsxs("div",{className:"mt-act-grid",children:[e.jsx(ve,{label:n("Work package","Work package"),children:e.jsx(Bs,{value:t.wp_id,onChange:o=>a("wp_id",o),wps:i,ariaLabel:n("Work package","Work package")})}),e.jsx(ve,{label:n("Scadenza","Due date"),children:e.jsx(Pe,{className:"mt-act-input",value:t.due,onChange:o=>a("due",o.target.value)})})]}),e.jsxs("label",{className:"mt-act-check",children:[e.jsx("input",{type:"checkbox",checked:!!t.achieved,onChange:o=>a("achieved",o.target.checked)}),e.jsx("span",{children:n("Milestone raggiunta","Milestone achieved")})]}),e.jsx(ve,{label:n("Note","Notes"),wide:!0,children:e.jsx("textarea",{className:"mt-act-input mt-act-textarea",rows:2,value:t.notes,onChange:o=>a("notes",o.target.value)})})]})}function Lg({form:t,set:a,wps:i,dels:n,members:o}){const{t:s,lang:l}=X();return e.jsxs(e.Fragment,{children:[e.jsx(ve,{label:s("Titolo","Title"),wide:!0,children:e.jsx("input",{className:"mt-act-input",type:"text",value:t.title,maxLength:160,placeholder:s("Cosa va fatto","What needs to be done"),onChange:r=>a("title",r.target.value)})}),e.jsx(ve,{label:s("Descrizione","Description"),wide:!0,children:e.jsx("textarea",{className:"mt-act-input mt-act-textarea",rows:3,value:t.description,onChange:r=>a("description",r.target.value)})}),e.jsxs("div",{className:"mt-act-grid",children:[e.jsx(ve,{label:s("Work package","Work package"),children:e.jsx(Bs,{value:t.wp_id,onChange:r=>a("wp_id",r),wps:i,ariaLabel:s("Work package","Work package")})}),e.jsx(ve,{label:s("Deliverable","Deliverable"),children:e.jsx(xe,{tone:"inherit",style:ya,matchWidth:!1,value:t.deliverable_id||"",onChange:r=>a("deliverable_id",r),ariaLabel:s("Deliverable","Deliverable"),options:[{value:"",label:s("â nessuno â","â none â")},...n.map(r=>
696({value:r.id,label:`${r.code?`${r.code}, `:""}${r.title||s("Senza titolo","Untitled")}`}))]})})]}),e.jsxs("div",{className:"mt-act-grid",children:[e.jsx(ve,{label:s("Assegnatario","Assignee"),children:e.jsx(Us,{value:t.assignee_uid,onChange:r=>a("assignee_uid",r),members:o,ariaLabel:s("Assegnatario","Assignee")})}),e.jsx(ve,{label:s("Scadenza","Due date"),children:e.jsx(Pe,{className:"mt-act-input",value:t.due,onChange:r=>a("due",r.target.value)})})]}),e.jsxs("div",{className:"mt-act-grid",children:[e.jsx(ve,{label:s("Stato","Status"),children:e.jsx(xe,{tone:"inherit",style:ya,value:t.status,onChange:r=>a("status",r),ariaLabel:s("Stato","Status"),options:St.map(r=>({value:r.id,label:l==="en"&&r.labelEn?r.labelEn:r.label}))})}),e.jsx(ve,{label:s("Priorità ","Priority"),children:e.jsx(xe,{tone:"inherit",style:ya,value:t.priority,onChange:r=>a("priority",r),ariaLabel:s("Priorità ","Priority"),options:ys.map(r=>({value:r.id,label:l==="en"&&r.labelEn?r.labelEn:r.label}))})})]})]})}function Og(t,a){const i=a||{};return t==="del"?{code:i.code||"",title:i.title||"",description:i.description||"",wp_id:i.wp_id||"",type:i.type||"report",status:i.status||"not_started",owner_uid:i.owner_uid||"",due:Qt(i.due),progress:Number(i.progress)||0,notes:i.notes||""}:t==="wp"?{code:i.code||"",title:i.title||"",description:i.description||"",lead_uid:i.lead_uid||"",start:Qt(i.start),end:Qt(i.end),order:i.order??0}:t==="ms"?{code:i.code||"",title:i.title||"",wp_id:i.wp_id||"",due:Qt(i.due),achieved:!!i.achieved,notes:i.notes||""}:{title:i.title||"",description:i.description||"",wp_id:i.wp_id||"",deliverable_id:i.deliverable_id||"",assignee_uid:i.assignee_uid||"",due:Qt(i.due),status:i.status||"todo",priority:i.priority||"normal"}}function qg(t,a,i){return t==="del"?{code:a.code,title:a.title,description:a.description,wp_id:a.wp_id||null,type:a.type,status:a.status,owner_uid:a.owner_uid||null,owner_name:a.owner_uid?i(a.owner_uid):null,due:ga(a.due),progress:Number(a.progress)||0,notes:a.notes}:t==="wp"?{code:a.code,title:a.title,description:a.description,lead_uid:a.lead_uid||null,lead_name:a.lead_uid?i(a.lead_uid):null,start:ga(a.start),end:ga(a.end),order:Number(a.order)||0}:t==="ms"?{code:a.code,title:a.title,wp_id:a.wp_id||null,due:ga(a.due),achieved:!!a.achieved,notes:a.notes}:{title:a.title,description:a.description,wp_id:a.wp_id||null,deliverable_id:a.deliverable_id||null,assignee_uid:a.assignee_uid||null,assignee_name:a.assignee_uid?i(a.assignee_uid):null,due:ga(a.due),status:a.status,priority:a.priority}}const Cn="team_minutes",kn="team_action_items",lr=[{id:"open",label:"Aperta",labelEn:"Open",color:"#d97706"},{id:"done",label:"Completata",labelEn:"Done",color:"#16a34a"}];function ac(t,a){const i=lr.find(n=>n.id===t)||lr[0];return a==="en"&&i.labelEn?{...i,label:i.labelEn}:i}function Ug(t){return Ye(Ie(te,Cn),a=>{const i=a.docs.map(n=>({id:n.id,...n.data()||{}}));i.sort((n,o)=>(o.date??0)-(n.date??0)),t(i)},a=>{console.error("[minutes] subscribe",a),t([])})}async function Bg(t,a){return(await ca(Ie(te,Cn),{title:(t.title||"").trim()||"Verbale",date:t.date??Date.now(),meeting_slug:t.meeting_slug||null,attendee_uids:Array.isArray(t.attendee_uids)?t.attendee_uids:[],attendee_names:Array.isArray(t.attendee_names)?t.attendee_names:[],agenda:Array.isArray(t.agenda)?t.agenda:[],notes:t.notes||"",decisions:Array.isArray(t.decisions)?t.decisions:[],created_by:(a==null?void 0:a.uid)||null,created_by_name:(a==null?void 0:a.name)||(a==null?void 0:a.email)||null,created_at:ie(),updated_at:ie()})).id}async function Gg(t,a){await la(oe(te,Cn,t),{...a,updated_at:ie()})}async function Wg(t){await gt(oe(te,Cn,t))}function ic(t){return Ye(Ie(te,kn),a=>{const i=a.docs.map(n=>({id:n.id,...n.data()||{}}));i.sort((n,o)=>(n.due??1/0)-(o.due??1/0)),t(i)},a=>{console.error("[action-items] subscribe",a),t([])})}async function Vg(t,a){return(await ca(Ie(te,kn),{minute_id:t.minute_id||null,minute_title:t.minute_title||null,text:(t.text||"").trim(),assignee_uid:t.assignee_uid||null,assignee_name:t.assignee_name||null,due:t.due??null,status:"open",created_by:(a==null?void 0:a.uid)||null,created_at:ie(),updated_at:ie(),done_at:null})).id}async function nc(t){await gt(oe(te,kn,t))}async function Hg(t,a){await la(oe(te,kn,t),{status:a,updated_at:ie(),done_at:a==="done"?ie():null})}async function Kg({assigneeUid:t,text:a,minuteTitle:i,due:n,fromN
696ame:o}){if(!t)return;const l={kind:"action_item",title:"Nuova azione assegnata",body:`Nuova azione da "${i}": ${a}`,from_uid:null,from_name:o||"CLIMPACT",target:{kind:"action_item",member_uid:t},payload:{due:n??null}},r=uu();try{await ca(Ie(te,"mt_notifications",t,"inbox"),{...l,origin_id:r,read:!1,read_at:null,created_at:ie()})}catch(d){console.warn("[action-items] bell failed",(d==null?void 0:d.message)||d);return}await mu({uid:t,portal:"rt",payload:l,originId:r,legacyRoot:"mt_notifications"})}const Jg={"--bg-surface-solid":"#0f121c","--bg-surface-elevated":"rgba(255, 255, 255, 0.05)","--text-primary":"#eef1f8","--text-secondary":"rgba(238, 241, 248, 0.62)","--border":"rgba(255, 255, 255, 0.16)"};function Yg(t){return[{id:"verbali",label:t("Verbali","Minutes"),icon:sa},{id:"azioni",label:t("Azioni","Actions"),icon:xi}]}function Zg({me:t,isAdmin:a,recipientLoader:i}){const{t:n}=X(),o=Yg(n),[s,l]=f.useState(null),[r,d]=f.useState(null),[m,c]=f.useState([]),[g,h]=f.useState("verbali"),[p,x]=f.useState(null),[b,u]=f.useState(null);f.useEffect(()=>{const C=Ug(l),y=ic(d);return()=>{C==null||C(),y==null||y()}},[]),f.useEffect(()=>{let C=!0;return(async()=>{if(typeof i=="function")try{const y=await i();C&&c(Array.isArray(y)?y:[])}catch(y){console.error("[minutes] recipient load",y)}})(),()=>{C=!1}},[i]);const w=f.useMemo(()=>(s||[]).find(C=>C.id===p)||null,[s,p]),v=f.useCallback(C=>(r||[]).filter(y=>y.minute_id===C&&y.status==="open").length,[r]),j=f.useCallback(async C=>{const y={title:C.title,date:C.date,meeting_slug:C.meeting_slug,attendee_uids:C.attendee_uids,attendee_names:C.attendee_names,agenda:C.agenda,notes:C.notes,decisions:C.decisions};C.id?await Gg(C.id,y):await Bg(y,t)},[t]),_=f.useCallback(async C=>{if(confirm(n("Eliminare definitivamente questo verbale? Le azioni collegate non vengono rimosse.","Permanently delete this minute? Linked actions are not removed.")))try{await Wg(C),p===C&&x(null)}catch(y){console.error("[minutes] delete",y),alert(n("Eliminazione non riuscita.","Deletion failed."))}},[p,n]);return e.jsxs(e.Fragment,{children:[e.jsx("section",{className:"mt-band mt-band-dark",children:e.jsxs("div",{className:"mt-wrap",children:[e.jsx("p",{className:"mt-eyebrow reveal",children:n("Gruppo di ricerca","Research Team")}),e.jsx("h1",{className:"mt-section-title reveal","data-d":"1",children:n("Verbali & action item","Minutes & action items")}),e.jsx("p",{className:"mt-section-sub reveal","data-d":"2",children:n("Il registro delle riunioni del gruppo: ordine del giorno, decisioni e note di ogni verbale, con le azioni di follow-up assegnate ai membri e il loro stato di avanzamento.","The register of the teamâs meetings: agenda, decisions and notes of each minute, with the follow-up actions assigned to members and their progress.")})]})}),e.jsx("section",{className:"mt-band mt-band-tight",children:e.jsxs("div",{className:"mt-wrap reveal",children:[e.jsx("div",{className:"mt-min-tabs",role:"tablist","aria-label":n("Sezioni verbali","Minutes sections"),children:o.map(C=>{const y=C.icon,z=g===C.id;return e.jsxs("button",{type:"button",role:"tab","aria-selected":z,className:`mt-min-tab${z?" is-on":""}`,onClick:()=>h(C.id),children:[e.jsx(y,{size:15,"aria-hidden":"true"}),e.jsx("span",{children:C.label})]},C.id)})}),g==="verbali"?e.jsx(Xg,{minutes:s,isAdmin:a,openCountFor:v,onOpen:x,onNew:()=>u(ax())}):e.jsx(ex,{actions:r,isAdmin:a,me:t,minutes:s,onOpenMinute:C=>{h("verbali"),x(C)}})]})}),w&&e.jsx(Qg,{minute:w,actions:(r||[]).filter(C=>C.minute_id===w.id),members:m,isAdmin:a,me:t,onClose:()=>x(null),onEdit:()=>u(ix(w)),onDelete:()=>_(w.id)}),b&&e.jsx(tx,{draft:b,members:m,onClose:()=>u(null),onSave:j})]})}function Xg({minutes:t,isAdmin:a,openCountFor:i,onOpen:n,onNew:o}){const{t:s}=X();return e.jsxs(e.Fragment,{children:[a&&e.jsx("div",{className:"mt-min-bar",children:e.jsxs("button",{type:"button",className:"btn btn-primary mt-min-newbtn",onClick:o,children:[e.jsx(Le,{size:16,"aria-hidden":"true"}),e.jsx("span",{children:s("Nuovo verbale","New minute")})]})}),t===null?e.jsxs("div",{className:"mt-card mt-min-loading",children:[e.jsx(me,{size:18,className:"mt-min-spin","aria-hidden":"true"}),e.jsx("span",{children:s("Caricamento verbaliâ¦","Loading minutesâ¦")})]}):t.length===0?e.jsxs("div",{className:"mt-card mt-min-empty",children:[e.jsx(sa,{size:22,"aria-hidden":"true"}),e.jsxs("p",{children:[s("Nessun verbale registrato.","No minutes recorded."),a?s(' Crea il primo con "Nuovo verbale".',' Create the first one with "New minute".'):""]})]}):e.jsx("ul",{className:"mt-min-list",children:t.map(l=>{const r=i(l.id),d=Array.isArray(l.attendee_uids)?l.attendee_uids.length:0;return e.jsx("li",{children:e.jsxs("button",{type:"button",className:"mt-card mt-min-card",onClick:()=>n(l.id),children:[e.jsx("div",{className:"mt-min-card-icon","aria-hidden":"true",children:e.jsx(sa,{size:18})}),e.jsxs("div",{className:"mt-min-card-main",children:[e.jsx("h3",{className:"mt-min-card-title",children:l.title||s("Verbale","Minute")}),e.jsxs("p",{className:"mt-min-card-meta",children:[e.jsxs("span",{className:"mt-min-meta-item",children:[e.jsx(mi,{size:13,"aria-hidden":"true"})," ",It(l.date)]}),e.jsx("span",{className:"mt-min-dot",children:","}),e.jsxs("span",{className:"mt-min-meta-item",children:[e.jsx(ia,{size:13,"aria-hidden":"true"})," ",d," ",d===1?s("partecipante","participant"):s("partecipanti","participants")]}),r>0&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"mt-min-dot",children:","}),e.jsxs("span",{className:"mt-min-badge",children:[e.jsx(pu,{size:12,"aria-hidden":"true"})," ",r," ",r===1?s("azione aperta","open action"):s("azioni aperte","open actions")]})]})]})]}),e.jsx(yt,{size:18,className:"mt-min-card-chev","aria-hidden":"true"})]})},l.id)})})]})}function Qg({minute:t,actions:a,members:i,isAdmin:n,me:o,onClose:s,onEdit:l,onDelete:r}){const{t:d,lang:m}=X(),[c,g]=f.useState(""),[h,p]=f.useState(""),[x,b]=f.useState(""),[u,w]=f.useState(!1),[v,j]=f.useState(null);f.useEffect(()=>{const I=D=>{D.key==="Escape"&&!u&&(s==null||s())};return window.addEventListener("keydown",I),()=>window.removeEventListener("keydown",I)},[u,s]);
696const _=Array.isArray(t.agenda)?t.agenda.filter(Boolean):[],C=Array.isArray(t.decisions)?t.decisions.filter(Boolean):[],y=Array.isArray(t.attendee_names)?t.attendee_names.filter(Boolean):[],z=f.useCallback(async()=>{const I=c.trim();if(!I||u)return;w(!0),j(null);const D=i.find(R=>R.uid===h)||null,$=D?D.name||D.email:null,q=ga(x);try{await Vg({minute_id:t.id,minute_title:t.title||"Verbale",text:I,assignee_uid:h||null,assignee_name:$,due:q},o),h&&await Kg({assigneeUid:h,text:I,minuteTitle:t.title||"Verbale",due:q,fromName:(o==null?void 0:o.name)||(o==null?void 0:o.email)}),g(""),p(""),b("")}catch(R){console.error("[minutes] add action",R),j(d("Impossibile aggiungere lâazione. Riprova.","Couldnât add the action. Try again."))}finally{w(!1)}},[c,h,x,u,i,t,o,d]),T=f.useCallback(async I=>{if(confirm(d("Eliminare questa azione?","Delete this action?")))try{await nc(I)}catch(D){console.error("[minutes] delete action",D),alert(d("Eliminazione non riuscita.","Deletion failed."))}},[d]);return e.jsx("div",{className:"mt-min-overlay",role:"dialog","aria-modal":"true","aria-label":`${d("Verbale","Minute")}: ${t.title||""}`,onMouseDown:I=>{I.target===I.currentTarget&&!u&&(s==null||s())},children:e.jsxs("div",{className:"mt-min-modal",children:[e.jsxs("header",{className:"mt-min-modal-head",children:[e.jsxs("div",{className:"mt-min-modal-head-text",children:[e.jsxs("p",{className:"mt-min-eyebrow",children:[e.jsx(sa,{size:13,"aria-hidden":"true"})," ",d("Verbale","Minute")]}),e.jsx("h2",{className:"mt-min-modal-title",children:t.title||d("Verbale","Minute")}),e.jsxs("p",{className:"mt-min-modal-sub",children:[e.jsx(mi,{size:13,"aria-hidden":"true"})," ",It(t.date),t.created_by_name?e.jsxs("span",{className:"mt-min-modal-sub-by",children:[", ",d("redatto da","drafted by")," ",t.created_by_name]}):null]})]}),e.jsxs("div",{className:"mt-min-modal-head-actions",children:[n&&e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button",className:"mt-min-iconbtn",onClick:l,"aria-label":d("Modifica verbale","Edit minute"),title:d("Modifica verbale","Edit minute"),children:e.jsx(wa,{size:16})}),e.jsx("button",{type:"button",className:"mt-min-iconbtn mt-min-iconbtn-danger",onClick:r,"aria-label":d("Elimina verbale","Delete minute"),title:d("Elimina verbale","Delete minute"),children:e.jsx($e,{size:16})})]}),e.jsx("button",{type:"button",className:"mt-min-iconbtn",onClick:s,"aria-label":d("Chiudi","Close"),title:d("Chiudi","Close"),children:e.jsx(Ce,{size:18})})]})]}),e.jsxs("div",{className:"mt-min-modal-body",children:[e.jsxs("section",{className:"mt-min-block",children:[e.jsxs("h3",{className:"mt-min-block-h",children:[e.jsx(ia,{size:14,"aria-hidden":"true"})," ",d("Partecipanti","Participants")]}),y.length===0?e.jsx("p",{className:"mt-min-muted",children:d("Nessun partecipante indicato.","No participants indicated.")}):e.jsx("div",{className:"mt-min-chips",children:y.map((I,D)=>e.jsxs("span",{className:"mt-min-attchip",children:[e.jsx(na,{size:12,"aria-hidden":"true"})," ",I]},`${I}-${D}`))})]}),e.jsxs("section",{className:"mt-min-block",children:[e.jsxs("h3",{className:"mt-min-block-h",children:[e.jsx(yr,{size:14,"aria-hidden":"true"})," ",d("Ordine del giorno","Agenda")]}),_.length===0?e.jsx("p",{className:"mt-min-muted",children:d("Nessun punto allâordine del giorno.","No agenda items.")}):e.jsx("ol",{className:"mt-min-agenda",children:_.map((I,D)=>e.jsx("li",{children:I},D))})]}),e.jsxs("section",{className:"mt-min-block",children:[e.jsxs("h3",{className:"mt-min-block-h",children:[e.jsx(Ue,{size:14,"aria-hidden":"true"})," ",d("Note","Notes")]}),t.notes?e.jsx("p",{className:"mt-min-notes",children:t.notes}):e.jsx("p",{className:"mt-min-muted",children:d("Nessuna nota.","No notes.")})]}),e.jsxs("section",{className:"mt-min-block",children:[e.jsxs("h3",{className:"mt-min-block-h",children:[e.jsx(tt,{size:14,"aria-hidden":"true"})," ",d("Decisioni","Decisions")]}),C.length===0?e.jsx("p",{className:"mt-min-muted",children:d("Nessuna decisione registrata.","No decisions recorded.")}):e.jsx("ul",{className:"mt-min-decisions",children:C.map((I,D)=>e.jsxs("li",{children:[e.jsx(tt,{size:14,"aria-hidden":"true"})," ",e.jsx("span",{children:I})]},D))})]}),e.jsxs("section",{className:"mt-min-block",children:[e.jsxs("h3",{className:"mt-min-block-h",children:[e.jsx(xi,{size:14,"aria-hidden":"true"})," ",d("Azioni collegate","Linked actions")]}),a.length===0?e.jsx("p",{className:"mt-min-muted",children:d("Nessuna azione collegata a questo verbale.","No actions linked to this minute.")}):e.jsx("ul",{className:"mt-min-actlist",children:a.map(I=>{const D=ac(I.status,m),$=Lt(I.due,I.status==="done");return e.jsxs("li",{className:"mt-min-act",children:[e.jsx("span",{className:"mt-min-act-dot",style:{background:D.color},"aria-hidden":"true"}),e.jsxs("div",{className:"mt-min-act-main",children:[e.jsx("p",{className:"mt-min-act-text",children:I.text}),e.jsxs("p",{className:"mt-min-act-meta",children:[I.assignee_name?e.jsxs("span",{children:[e.jsx(na,{size:12,"aria-hidden":"true"})," ",I.assignee_name]}):e.jsx("span",{className:"mt-min-muted",children:d("Non assegnata","Unassigned")}),I.due||I.due===0?e.jsxs("span",{className:$?"mt-min-act-due is-overdue":"mt-min-act-due",children:[e.jsx(mi,{size:12,"aria-hidden":"true"})," ",It(I.due)]}):null,e.jsx("span",{className:"mt-min-act-status",style:{color:D.color},children:D.label})]})]}),n&&e.jsx("button",{type:"button",className:"mt-min-iconbtn mt-min-iconbtn-danger mt-min-iconbtn-sm",onClick:()=>T(I.id),"aria-label":d("Elimina azione","Delete action"),title:d("Elimina azione","Delete action"),children:e.jsx($e,{size:14})})]},I.id)})}),n&&e.jsxs("div",{className:"mt-min-addact",children:[e.jsx("input",{className:"mt-min-input",type:"text",placeholder:d("Nuova azione di follow-upâ¦","New follow-up actionâ¦"),value:c,maxLength:240,onChange:I=>g(I.target.value),disabled:u}),e.jsxs("div",{className:"mt-min-addact-row",children:[e.jsx(xe,{tone:"inherit",style:{...Jg,minWidth:0},value:h,onChange:I=>p(I),disabled:u,ariaLabel:d("Assegnatario","Assignee"),options:[{value:"",label:d("Assegna aâ¦","Assign toâ¦")},...i.map(I=>({value:I.uid,label:I.name||I.email}))]}),e.jsx(Pe,{className:"mt-min-input mt-min-date",value:x,onChange:I=>b(I.target.value),disabled:u,"aria-label":d("Scadenza","Due date")}),e.jsxs("button",{type:"button",className:"btn btn-primary btn-sm mt-min-addact-btn",onClick:z,disabled:u||!c.trim(),children:[u?e.jsx(me,{size:15,className:"mt-min-spin"}):e.jsx(Le,{size:15}),e.jsx("span",{children:d("Aggiungi","Add")})]})]}),v&&e.jsx("p",{className:"mt-min-err",children:v})]})]})]})]})})}function ex({actions:t,isAdmin:a,me:i,minutes:n,onOpenMinute:o}){const{t:s}=X(),[l,r]=f.useState(null),d=f.useCallback(h=>{var p;return h.minute_title||((p=(n||[]).find(x=>x.id===h.minute_id))==null?void 0:p.title)||null},[n]),m=f.useCallback(async h=>{r(h.id);try{await Hg(h.id,h.status==="done"?"open":"done")}catch(p){console.error("[minutes] toggle status",p),alert(s("Aggiornamento non riuscito.","Update failed."))}finally{r(null)}},[s]);if(t===null)return e.jsxs("div",{className:"mt-card mt-min-loading",children:[e.jsx(me,{size:18,className:"mt-min-spin","aria-hidden":"true"}),e.jsx("span",{children:s("Caricamento azioniâ¦","Loading actionsâ¦")})]});if(!a){const h=t.filter(x=>x.assignee_uid===(i==null?void 0:i.uid)),p=t.filter(x=>x.assignee_uid!==(i==null?void 0:i.uid)&&x.status==="open");return e.jsxs(e.Fragment,{children:[e.jsx("h2",{className:"mt-min-grouph",children:s("Le mie azioni","My actions")}),h.length===0?e.jsxs("div",{className:"mt-card mt-min-empty",children:[e.jsx(xi,{size:22,"aria-hidden":"true"}),e.jsx("p",{children:s("Nessuna azione assegnata a te.","No actions assigned to you.")})]}):e.jsx("ul",{className:"mt-min-rows",children:h.map(x=>e.jsx($i,{a:x,title:d(x),onOpenMinute:o,canToggle:!0,busy:l===x.id,onToggle:()=>m(x)},x.id))}),p.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("h2",{className:"mt-min-grouph mt-min-grouph-sub",children:s("Altre azioni aperte","Other open actions")}),e.jsx("ul",{className:"mt-min-rows",children:p.map(x=>e.jsx($i,{a:x,title:d(x),onOpenMinute:o,readOnly:!0},x.id))})]})]})}const c=t.filter(h=>h.status!=="done"),g=t.filter(h=>h.status==="done");return t.length===0?e.jsxs("div",{className:"mt-card mt-min-empty",children:[e.jsx(xi,{size:22,"aria-hidden":"true"}),e.jsx("p",{children:s("Nessuna azione registrata. Aggiungile dal dettaglio di un verbale.","No actions recorded. Add them from a minuteâs detail.")})]}):e.jsxs(e.Fragment,{children:[e.jsxs("h2",{className:"mt-min-grouph",children:[s("Aperte","Open")," ",e.jsx("span",{className:"mt-min-count",children:c.length})]}),c.length===0?e.jsx("div",{className:"mt-card mt-min-empty mt-min-empty-sm",children:e.jsx("p",{children:s("Nessuna azione aperta.","No open actions.")})}):e.jsx("ul",{className:"mt-min-rows",children:c.map(h=>e.jsx($i,{a:h,title:d(h),onOpenMinute:o,isAdmin:!0,canToggle:!0,busy:l===h.id,onToggle:()=>m(h)},h.id))}),e.jsxs("h2",{className:"mt-min-grouph mt-min-grouph-sub",children:[s("Completate","Completed")," ",e.jsx("span",{className:"mt-min-count",children:g.length})]}),g.length===0?e.jsx("div",{className:"mt-card mt-min-empty mt-min-empty-sm",children:e.jsx("p",{children:s("Nessuna azione completata.","No completed actions.")})}):e.jsx("ul",{className:"mt-min-rows",children:g.map(h=>e.jsx($i,{a:h,title:d(h),onOpenMinute:o,isAdmin:!0,canToggle:!0,busy:l===h.id,onToggle:()=>m(h)},h.id))})]})}function $i({a:t,title:a,onOpenMinute:i,isAdmin:n=!1,readOnly:o=!1,canToggle:s=!1,busy:l=!1,onToggle:r}){const{t:d,lang:m}=X(),c=ac(t.status,m),g=t.status==="done",h=Lt(t.due,g),p=f.useCallback(async()=>
696{if(confirm(d("Eliminare questa azione?","Delete this action?")))try{await nc(t.id)}catch(x){console.error("[minutes] delete action",x),alert(d("Eliminazione non riuscita.","Deletion failed."))}},[t.id,d]);return e.jsxs("li",{className:`mt-card mt-min-row${g?" is-done":""}`,children:[s&&!o?e.jsx("button",{type:"button",className:"mt-min-toggle",onClick:r,disabled:l,"aria-label":g?d("Riapri azione","Reopen action"):d("Segna come completata","Mark as completed"),title:g?d("Riapri azione","Reopen action"):d("Segna come completata","Mark as completed"),children:l?e.jsx(me,{size:18,className:"mt-min-spin"}):g?e.jsx(tt,{size:18,style:{color:c.color}}):e.jsx(ts,{size:18})}):e.jsx("span",{className:"mt-min-toggle is-static","aria-hidden":"true",children:g?e.jsx(tt,{size:18,style:{color:c.color}}):e.jsx(ts,{size:18})}),e.jsxs("div",{className:"mt-min-row-main",children:[e.jsx("p",{className:"mt-min-row-text",children:t.text}),e.jsxs("p",{className:"mt-min-row-meta",children:[t.assignee_name?e.jsxs("span",{className:"mt-min-row-who",children:[e.jsx(na,{size:12,"aria-hidden":"true"})," ",t.assignee_name]}):e.jsx("span",{className:"mt-min-muted",children:d("Non assegnata","Unassigned")}),a?e.jsxs("button",{type:"button",className:"mt-min-row-src",onClick:()=>i==null?void 0:i(t.minute_id),title:d("Apri il verbale di origine","Open the source minute"),children:[e.jsx(sa,{size:12,"aria-hidden":"true"})," ",a]}):null,t.due||t.due===0?e.jsxs("span",{className:h?"mt-min-row-due is-overdue":"mt-min-row-due",children:[e.jsx(mi,{size:12,"aria-hidden":"true"})," ",It(t.due)]}):null]})]}),e.jsx("span",{className:"mt-min-pill",style:{color:c.color,borderColor:c.color,background:`${c.color}1f`},children:c.label}),n&&e.jsx("button",{type:"button",className:"mt-min-iconbtn mt-min-iconbtn-danger mt-min-iconbtn-sm",onClick:p,"aria-label":d("Elimina azione","Delete action"),title:d("Elimina azione","Delete action"),children:e.jsx($e,{size:14})})]})}function tx({draft:t,members:a,onClose:i,onSave:n}){const{t:o}=X(),[s,l]=f.useState(t.title||""),[r,d]=f.useState(t.dateInput||Qt(D
696ate.now())),[m,c]=f.useState(t.meeting_slug||""),[g,h]=f.useState(()=>new Set(t.attendee_uids||[])),[p,x]=f.useState(()=>{var R;return(R=t.agenda)!=null&&R.length?[...t.agenda]:[""]}),[b,u]=f.useState(t.notes||""),[w,v]=f.useState(()=>{var R;return(R=t.decisions)!=null&&R.length?[...t.decisions]:[""]}),[j,_]=f.useState(!1),[C,y]=f.useState(null),z=!!t.id;f.useEffect(()=>{const R=O=>{O.key==="Escape"&&!j&&(i==null||i())};return window.addEventListener("keydown",R),()=>window.removeEventListener("keydown",R)},[j,i]);const T=R=>{h(O=>{const k=new Set(O);return k.has(R)?k.delete(R):k.add(R),k})},I=(R,O)=>(k,N)=>O(R.map((L,B)=>B===k?N:L)),D=(R,O)=>()=>O([...R,""]),$=(R,O)=>k=>O(R.length>1?R.filter((N,L)=>L!==k):[""]),q=f.useCallback(async()=>{if(j)return;_(!0),y(null);const R=[...g],O=R.map(k=>{const N=a.find(L=>L.uid===k);return N?N.name||N.email:k});try{await n({id:t.id||null,title:s.trim()||"Verbale",date:ga(r)??Date.now(),meeting_slug:m.trim()||null,attendee_uids:R,attendee_names:O,agenda:p.map(k=>k.trim()).filter(Boolean),notes:b.trim(),decisions:w.map(k=>k.trim()).filter(Boolean)}),i==null||i()}catch(k){console.error("[minutes] save",k),y(o("Salvataggio non riuscito. Riprova.","Save failed. Try again."))}finally{_(!1)}},[j,g,a,t.id,s,r,m,p,b,w,n,i,o]);return e.jsx("div",{className:"mt-min-overlay",role:"dialog","aria-modal":"true","aria-label":z?o("Modifica verbale","Edit minute"):o("Nuovo verbale","New minute"),onMouseDown:R=>{R.target===R.currentTarget&&!j&&(i==null||i())},children:e.jsxs("div",{className:"mt-min-modal",children:[e.jsxs("header",{className:"mt-min-modal-head",children:[e.jsxs("div",{className:"mt-min-modal-head-text",children:[e.jsxs("p",{className:"mt-min-eyebrow",children:[e.jsx(sa,{size:13,"aria-hidden":"true"})," ",z?o("Modifica verbale","Edit minute"):o("Nuovo verbale","New minute")]}),e.jsx("h2",{className:"mt-min-modal-title",children:z?s||o("Verbale","Minute"):o("Nuovo verbale","New minute")})]}),e.jsx("button",{type:"button",className:"mt-min-iconbtn",onClick:i,disabled:j,"aria-label":o("Chiudi","Close"),title:o("Chiudi","Close"),children:e.jsx(Ce,{size:18})})]}),e.jsxs("div",{className:"mt-min-modal-body",children:[e.jsxs("div",{className:"mt-min-frow",children:[e.jsxs("label",{className:"mt-min-field mt-min-field-grow",children:[e.jsx("span",{className:"mt-min-label",children:o("Titolo","Title")}),e.jsx("input",{className:"mt-min-input",type:"text",value:s,maxLength:120,placeholder:o("Es. Riunione di coordinamento","E.g. Coordination meeting"),onChange:R=>l(R.target.value),disabled:j})]}),e.jsxs("label",{className:"mt-min-field",children:[e.jsx("span",{className:"mt-min-label",children:o("Data","Date")}),e.jsx(Pe,{className:"mt-min-input mt-min-date",value:r,onChange:R=>d(R.target.value),disabled:j})]})]}),e.jsxs("label",{className:"mt-min-field",children:[e.jsx("span",{className:"mt-min-label",children:o("Slug riunione (opzionale)","Meeting slug (optional)")}),e.jsx("input",{className:"mt-min-input",type:"text",value:m,maxLength:80,placeholder:"es. coordinamento-2026",onChange:R=>c(R.target.value),disabled:j})]}),e.jsxs("div",{className:"mt-min-field",children:[e.jsxs("span",{className:"mt-min-label",children:[e.jsx(ia,{size:13,"aria-hidden":"true"})," ",o("Partecipanti","Participants")]}),a.length===0?e.jsx("p",{className:"mt-min-muted",children:o("Nessun membro disponibile.","No members available.")}):e.jsx("ul",{className:"mt-min-checks",children:a.map(R=>{const O=g.has(R.uid);return e.jsx("li",{children:e.jsxs("button",{type:"button",className:`mt-min-check${O?" is-on":""}`,onClick:()=>T(R.uid),disabled:j,children:[e.jsx("span",{className:`mt-min-checkbox${O?" is-on":""}`,"aria-hidden":"true",children:O?e.jsx(tt,{size:13}):null}),e.jsxs("span",{className:"mt-min-check-text",children:[e.jsx("span",{className:"mt-min-check-name",children:R.name||R.email}),R.email&&R.name?e.jsx("span",{className:"mt-min-check-mail",children:R.email}):null]})]})},R.uid)})})]}),e.jsx(cr,{label:o("Ordine del giorno","Agenda"),icon:yr,ordered:!0,lines:p,disabled:j,onSet:I(p,x),onAdd:D(p,x),onRemove:$(p,x),placeholder:o("Punto allâordine del giornoâ¦","Agenda itemâ¦")}),e.jsxs("label",{className:"mt-min-field",children:[e.jsxs("span",{className:"mt-min-label",children:[e.jsx(Ue,{size:13,"aria-hidden":"true"})," ",o("Note","Notes")]}),e.jsx("textarea",{className:"mt-min-textarea",rows:5,value:b,placeholder:o("Discussione, sintesi, osservazioniâ¦","Discussion, summary, observationsâ¦"),onChange:R=>u(R.target.value),disabled:j})]}),e.jsx(cr,{label:o("Decisioni","Decisions"),icon:tt,lines:w,disabled:j,onSet:I(w,v),onAdd:D(w,v),onRemove:$(w,v),placeholder:o("Decisione assuntaâ¦","Decision takenâ¦")}),C&&e.jsx("p",{className:"mt-min-err",children:C})]}),e.jsxs("footer",{className:"mt-min-modal-foot",children:[e.jsx("button",{type:"button",className:"btn btn-secondary",onClick:i,disabled:j,children:o("Annulla","Cancel")}),e.jsxs("button",{type:"button",className:"btn btn-primary mt-min-save",onClick:q,disabled:j,children:[j?e.jsx(me,{size:16,className:"mt-min-spin"}):e.jsx(tt,{size:16}),e.jsx("span",{children:j?o("Salvataggioâ¦","Savingâ¦"):z?o("Salva modifiche","Save changes"):o("Crea verbale","Create minute")})]})]})]})})}function cr({label:t,icon:a,ordered:i=!1,lines:n,disabled:o,onSet:s,onAdd:l,onRemove:r,placeholder:d}){const{t:m}=X();return e.jsxs("div",{className:"mt-min-field",children:[e.jsxs("span",{className:"mt-min-label",children:[a?e.jsx(a,{size:13,"aria-hidden":"true"}):null," ",t]}),e.jsx("ul",{className:"mt-min-lines",children:n.map((c,g)=>e.jsxs("li",{className:"mt-min-lineitem",children:[e.jsx("span",{className:"mt-min-linemark","aria-hidden":"true",children:i?`${g+1}.`:"·"}),e.jsx("input",{className:"mt-min-input",type:"text",value:c,maxLength:240,placeholder:d,onChange:h=>s(g,h.target.value),disabled:o}),e.jsx("button",{type:"button",className:"mt-min-linex",onClick:()=>r(g),disabled:o,"aria-label":m("Rimuovi riga","Remove line"),title:m("Rimuovi riga","Remove line"),children:e.jsx(Ce,{size:14})})]},g))}),e.jsxs("button",{type:"button",className:"mt-min-addline",onClick:l,disabled:o,children:[e.jsx(Le,{size:13,"aria-hidden":"true"})," ",e.jsx("span",{children:m("Aggiungi riga","Add line")})]})]})}function ax(){return{id:null,title:"",dateInput:Qt(Date.now()),meeting_slug:"",attendee_uids:[],attendee_names:[],agenda:[""],notes:"",decisions:[""]}}function ix(t){return{id:t.id,title:t.title||"",dateInput:Qt(t.date),meeting_slug:t.meeting_slug||"",attendee_uids:Array.isArray(t.attendee_uids)?[...t.attendee_uids]:[],attendee_names:Array.isArray(t.attendee_names)?[...t.attendee_names]:[],agenda:Array.isArray(t.agenda)&&t.agenda.length?[...t.agenda]:[""],notes:t.notes||"",decisions:Array.isArray(t.decisions)&&t.decisions.length?[...t.decisions]:[""]}}const nx="TKuaPxLsEobzv43Bdj7jrzyaVjs2",dr="/tools/management-pi",sx=["January","February","March","April","May","June","July","August","September","October","November","December"],ox=["Gennaio","Febbraio","Marzo","Aprile","Maggio","Giugno","Luglio","Agosto","Settembre","Ottobre","Novembre","Dicembre"];function rx(){const t=new Date,a=new Date(t.getFullYear(),t.getMonth()-1,1),i=a.getFullYear(),n=a.getMonth()+1;return{ym:`${i}
696-${String(n).padStart(2,"0")}`,mIdx:n-1,year:i}}function lx({me:t,recipientLoader:a,onOpen:i}){const{t:n,lang:o}=X(),[s,l]=f.useState(null),[r,d]=f.useState(null),[m,c]=f.useState(null),[g,h]=f.useState(null),[p,x]=f.useState(null),b=f.useMemo(rx,[]),u=`${(o==="en"?sx:ox)[b.mIdx]} ${b.year}`,w=(t==null?void 0:t.uid)===nx||(t==null?void 0:t.super_admin)===!0;f.useEffect(()=>{const y=[Zl(l),Xl(d),ec(c),ic(h)];return()=>y.forEach(z=>{try{z&&z()}catch{}})},[]),f.useEffect(()=>{let y=!1;return(async()=>{try{const z=await(a==null?void 0:a())||[],T=await ss(ft(Ie(te,"team_timesheets"),Bt("year_month","==",b.ym))),I=new Set;T.forEach($=>{var O;const q=$.data()||{},R=q.team_uid||String($.id).split("__")[0];R&&(q.researcher_pdf||q.file||(O=q.review)!=null&&O.state)&&I.add(R)});const D=z.filter($=>!I.has($.uid));y||x({done:z.length-D.length,total:z.length,pendingNames:D.map($=>$.name||$.email).slice(0,12)})}catch(z){console.error("[cruscotto] timesheet status",z),y||x({done:0,total:0,pendingNames:[]})}})(),()=>{y=!0}},[b.ym,a]);const v=s===null||r===null||m===null||g===null,j=f.useMemo(()=>
696{const y=s||[],z=r||[],T=m||[],I=g||[],D=y.filter(B=>!qi.has(B.status)),$=y.filter(B=>Lt(B.due,qi.has(B.status))),q=z.filter(B=>!B.achieved),R=z.filter(B=>!B.achieved&&Lt(B.due,!1)),O=T.filter(B=>B.status!=="done"),k=T.filter(B=>B.status!=="done"&&Lt(B.due,!1)),N=I.filter(B=>B.status!=="done"),L=I.filter(B=>B.status!=="done"&&Lt(B.due,!1));return{delOpen:D.length,delOverdue:$.length,delTotal:y.length,msOpen:q.length,msOverdue:R.length,msTotal:z.length,tkOpen:O.length,tkOverdue:k.length,tkTotal:T.length,aiOpen:N.length,aiOverdue:L.length,aiTotal:I.length}},[s,r,m,g]),_=f.useMemo(()=>{const y=[];return(s||[]).forEach(z=>{z.due&&!qi.has(z.status)&&y.push({key:`d-${z.id}`,kind:n("Deliverable","Deliverable"),view:"activity",title:`${z.code?z.code+", ":""}${z.title||""}`,due:z.due})}),(r||[]).forEach(z=>{z.due&&!z.achieved&&y.push({key:`m-${z.id}`,kind:n("Milestone","Milestone"),view:"activity",title:`${z.code?z.code+", ":""}${z.title||""}`,due:z.due})}),(m||[]).forEach(z=>{z.due&&z.status!=="done"&&y.push({key:`t-${z.id}`,kind:n("Attività ","Task"),view:"activity",title:z.title||"",due:z.due})}),(g||[]).forEach(z=>{z.due&&z.status!=="done"&&y.push({key:`a-${z.id}`,kind:n("Azione","Action"),view:"minutes",title:z.text||"",due:z.due})}),y.sort((z,T)=>(z.due??1/0)-(T.due??1/0)),y.slice(0,10)},[s,r,m,g,n]),C=[{id:"deliverables",label:n("Deliverable","Deliverables"),Icon:_a,view:"activity",main:j.delOpen,mainLabel:n("aperti","open"),total:j.delTotal,overdue:j.delOverdue},{id:"milestones",label:n("Milestone","Milestones"),Icon:un,view:"activity",main:j.msOpen,mainLabel:n("da raggiungere","outstanding"),total:j.msTotal,overdue:j.msOverdue},{id:"tasks",label:n("Attività ","Tasks"),Icon:_s,view:"activity",main:j.tkOpen,mainLabel:n("aperte","open"),total:j.tkTotal,overdue:j.tkOverdue},{id:"actions",label:n("Action item","Action items"),Icon:xi,view:"minutes",main:j.aiOpen,mainLabel:n("aperti","open"),total:j.aiTotal,overdue:j.aiOverdue}];return e.jsxs(e.Fragment,{children:[e.jsx("section",{className:"mt-band mt-band-dark",children:e.jsxs("div",{className:"mt-wrap",children:[e.jsx("p",{className:"mt-eyebrow reveal",children:n("Gruppo di ricerca","Research Team")}),e.jsx("h1",{className:"mt-section-title reveal","data-d":"1",children:n("Cruscotto di progetto","Project overview")}),e.jsx("p",{className:"mt-hero-lead reveal","data-d":"2",children:n("Avanzamento del gruppo di ricerca CLIMPACT: deliverable, milestone, attività e action item aperti, stato dei timesheet e prossime scadenze, aggiornati in tempo reale.","Progress across the CLIMPACT research group: open deliverables, milestones, tasks and action items, timesheet status, and upcoming deadlines, updated in real time.")})]})}),e.jsx("section",{className:"mt-band mt-band-tight",children:e.jsx("div",{className:"mt-wrap reveal",children:v?e.jsxs("div",{className:"mt-card",children:[e.jsx(xa.Cards,{count:4,height:92,min:180,label:n("Caricamento del cruscottoâ¦","Loading the overviewâ¦")}),e.jsx("div",{style:{marginTop:18},children:e.jsx(xa.List,{rows:4})})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"cru-kpis",children:C.map(y=>e.jsxs("button",{type:"button",className:"cru-kpi",onClick:()=>i==null?void 0:i(y.view),children:[e.jsxs("div",{className:"cru-kpi-head",children:[e.jsx("span",{className:"cru-kpi-icon",children:e.jsx(y.Icon,{size:18})}),e.jsx("span",{className:"cru-kpi-label",children:y.label}),e.jsx(Ri,{size:15,className:"cru-kpi-go"})]}),e.jsxs("div",{className:"cru-kpi-main",children:[e.jsx("span",{className:"cru-kpi-num",children:y.main}),e.jsx("span",{className:"cru-kpi-unit",children:y.mainLabel})]}),e.jsxs("div",{className:"cru-kpi-foot",children:[e.jsxs("span",{className:"cru-kpi-total",children:[y.total," ",n("totali","total")]}),y.overdue>0&&e.jsxs("span",{className:"cru-kpi-overdue",children:[e.jsx(ba,{size:13})," ",y.overdue," ",n("in ritardo","overdue")]})]})]},y.id))}),e.jsxs("div",{className:"cru-grid",children:[e.jsxs("div",{className:"mt-card cru-panel",children:[e.jsx("div",{className:"cru-panel-head",children:e.jsxs("h2",{className:"cru-panel-title",children:[e.jsx(ns,{size:16})," ",n("Prossime scadenze","Upcoming deadlines")]})}),_.length===0?e.jsx("p",{className:"cru-muted",children:n("Nessuna scadenza aperta.","No open deadlines.")}):e.jsx("ul",{className:"cru-feed",children:_.map(y=>{const z=Kl(y.due),T=z!==null&&z<0,I=z!==null&&z>=0&&z<=7;return e.jsxs("li",{className:"cru-feed-row",onClick:()=>i==null?void 0:i(y.view),children:[e.jsx("span",{className:"cru-feed-kind",children:y.kind}),e.jsx("span",{className:"cru-feed-title",children:y.title||"â"}),e.jsx("span",{className:"cru-feed-due",children:It(y.due)}),e.jsx("span",{className:`cru-feed-days${T?" is-late":I?" is-soon":""}`,children:T?`${Math.abs(z)}${n("g fa","d ago")}`:z===0?n("oggi","today"):`${n("tra ","in ")}${z}${n("g","d")}`})]},y.key)})})]}),e.jsxs("div",{className:"mt-card cru-panel",children:[e.jsx("div",{className:"cru-panel-head",children:e.jsxs("h2",{className:"cru-panel-title",children:[e.jsx(ns,{size:16})," ",n("Timesheet di","Timesheet for")," ",u]})}),p===null?e.jsxs("p",{className:"cru-muted",children:[e.jsx(me,{size:14,className:"cru-spin"})," ",n("Caricamentoâ¦","Loadingâ¦")]}):p.total===0?e.jsx("p",{className:"cru-muted",children:n("Nessun membro del team da monitorare.","No team members to monitor.")}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"cru-ts-bar",children:e.jsx("div",{className:"cru-ts-fill",style:{width:`${Math.round(p.done/p.total*100)}%`}})}),e.jsxs("p",{className:"cru-ts-num",children:[e.jsx("strong",{children:p.done})," / ",p.total," ",n("inviati","submitted")]}),p.pendingNames.length>0&&e.jsxs("div",{className:"cru-ts-pending",children:[e.jsx("span",{className:"cru-muted",children:n("In sospeso:","Pending:")}
696),e.jsx("div",{className:"cru-chips",children:p.pendingNames.map((y,z)=>e.jsx("span",{className:"cru-chip",children:y},z))})]})]})]})]}),w&&e.jsxs("div",{className:"cru-links",children:[e.jsxs(Gs,{to:dr,className:"cru-link-card",children:[e.jsx("span",{className:"cru-link-icon",children:e.jsx(wc,{size:18})}),e.jsxs("span",{className:"cru-link-body",children:[e.jsx("span",{className:"cru-link-title",children:n("Avanzamento budget","Budget progress")}),e.jsx("span",{className:"cru-link-sub",children:n("Rendiconto finanziario nel portale PI","Financial statement in the PI portal")})]}),e.jsx(Ri,{size:16,className:"cru-link-go"})]}),e.jsxs(Gs,{to:dr,className:"cru-link-card",children:[e.jsx("span",{className:"cru-link-icon",children:e.jsx(xr,{size:18})}),e.jsxs("span",{className:"cru-link-body",children:[e.jsx("span",{className:"cru-link-title",children:n("Impronta di carbonio","Carbon footprint")}),e.jsx("span",{className:"cru-link-sub",children:n("Carbon Tracker nel portale PI","Carbon Tracker in the PI portal")})]}),e.jsx(Ri,{size:16,className:"cru-link-go"})]})]})]})})})]})}const sn=t=>!!(t&&(t.url||t.path));function ur(t,a){return a?!!(t.email_sent_at||sn(t.signed_pdf)||Array.isArray(t.ufficio_docs)&&t.ufficio_docs.length):!!(t.segreteria_inviata_at||sn(t.authorized_pdf)||t.closed_at||Array.isArray(t.direzione_docs)&&t.direzione_docs.length)}function mr(t,a){const i=a?t.ufficio_docs:t.direzione_docs,n=new Set((Array.isArray(i)?i:[]).map(o=>o.kind));return a?[n.has("fattura"),n.has("affidamento")]:[sn(t.authorized_pdf)||n.has("autorizzazione"),sn(t.assignment_signed_pdf)||n.has("lettera"),n.has("mandato")]}function pr({fatti:t,totale:a,size:i=30}){const n=(i-5)/2,o=2*Math.PI*n,s=a>0&&t>=a;return e.jsxs("span",{className:`mt-uff-anello${s?" is-completa":""}`,style:{width:i,height:i},children:[e.jsxs("svg",{width:i,height:i,viewBox:`0 0 ${i} ${i}`,"aria-hidden":"true",children:[e.jsx("circle",{cx:i/2,cy:i/2,r:n,className:"mt-uff-anello-fondo"}),e.jsx("circle",{cx:i/2,cy:i/2,r:n,className:"mt-uff-anello-pieno",strokeDasharray:o,strokeDashoffset:o*(1-(a?t/a:0)),transform:`rotate(-90 ${i/2} ${i/2})`})]}),e.jsx("span",{className:"mt-uff-anello-txt",children:s?e.jsx(ke,{size:i>40?18:12}):`${t}/${a}`})]})}function hr({titolo:t,Icona:a,righe:i,onApri:n}){const{t:o}=X();if(!i)return e.jsx("div",{className:"mt-uff-pannello is-carica"});const s=i.filter(m=>m.fatti>=m.totale).length,l=i.reduce((m,c)=>m+c.totale,0),r=i.reduce((m,c)=>m+c.fatti,0),d=i.filter(m=>m.fatti<m.totale);return e.jsxs("div",{className:"mt-uff-pannello",children:[e.jsxs("div",{className:"mt-uff-testa",children:[e.jsx(pr,{fatti:r,totale:l,size:64}),e.jsxs("div",{children:[e.jsxs("div",{className:"mt-uff-titolo",children:[e.jsx(a,{size:15})," ",t]}),e.jsxs("div",{className:"mt-uff-numeri",children:[e.jsxs("span",{children:[e.jsx("strong",{children:i.length})," ",o("pratiche","files")]}),e.jsxs("span",{className:"is-ok",children:[e.jsx("strong",{children:s})," ",o("complete","complete")]}),e.jsxs("span",{className:"is-da",children:[e.jsx("strong",{children:d.length})," ",o("da completare","to complete")]})]})]})]}),d.length>0&&e.jsx("ul",{className:"mt-uff-elenco",children:d.map((m,c)=>e.jsx("li",{style:{animationDelay:`${Math.min(c,10)*30}ms`},children:e.jsxs("button",{type:"button",className:"mt-uff-voce",onClick:()=>n==null?void 0:n(m),children:[e.jsx(pr,{fatti:m.fatti,totale:m.totale}),e.jsxs("span",{className:"mt-uff-voce-txt",children:[e.jsx("strong",{children:m.titolo}),e.jsx("span",{children:m.sotto})]})]})},m.id))})]})}function cx({onApriMissioni:t,onApriAcquisti:a}){const{t:i,lang:n}=X(),[o,s]=f.useState(null),[l,r]=f.useState(null);return f.useEffect(()=>{let d=!0;const m=c=>{if(!c)return"";try{return new Date(String(c).slice(0,10)).toLocaleDateString(n==="en"?"en-GB":"it-IT",{day:"numeric",month:"short",year:"numeric"})}catch{return c}};return ss(Ie(te,"team_missions")).then(c=>{if(!d)return;const g=[];c.forEach(h=>{const p=h.data()||{};if(!ur(p,!1))return;const x=mr(p,!1);g.push({id:h.id,titolo:`${p.person||""} a ${p.place||""}
696`.trim(),sotto:[m(p.date),p.code].filter(Boolean).join(", "),fatti:x.filter(Boolean).length,totale:x.length,data:p.date||""})}),g.sort((h,p)=>String(p.data).localeCompare(String(h.data))),s(g)}).catch(()=>{d&&s([])}),ss(Ie(te,"team_purchases")).then(c=>{if(!d)return;const g=[];c.forEach(h=>{const p=h.data()||{};if(!ur(p,!0))return;const x=mr(p,!0);g.push({id:h.id,titolo:p.title||p.goods_service||i("Richiesta di acquisto","Purchase request"),sotto:p.affidamento_ditta||"",fatti:x.filter(Boolean).length,totale:x.length})}),r(g)}).catch(()=>{d&&r([])}),()=>{d=!1}},[n,i]),e.jsx("section",{className:"mt-band mt-band-tight",children:e.jsxs("div",{className:"mt-wrap",children:[e.jsx("div",{className:"mt-section-head reveal",children:e.jsxs("div",{children:[e.jsx("p",{className:"mt-eyebrow",children:i("Documenti degli uffici","Office documents")}),e.jsx("h2",{className:"mt-section-title",children:i("Direzione e ufficio acquisti","Direction and purchasing office")}),e.jsx("p",{className:"mt-section-sub",children:i("Autorizzazioni, lettere di incarico e mandati caricati dalla Direzione; fatture e documenti dellâaffidamento caricati dallâufficio acquisti.","Authorisations, assignment letters and payment orders uploaded by the Direction; invoices and procurement documents uploaded by the purchasing office.")})]})}),e.jsxs("div",{className:"mt-uff-griglia",children:[e.jsx(hr,{titolo:i("Missioni, Direzione","Missions, Direction"),Icona:zc,righe:o,onApri:()=>t==null?void 0:t()}),e.jsx(hr,{titolo:i("Acquisti, ufficio","Purchases, office"),Icona:wr,righe:l,onApri:()=>a==null?void 0:a()})]})]})})}function dx({me:t,isAdmin:a}){const{t:i,lang:n}=X();async function o(s){t!=null&&t.uid&&await _e(oe(te,"users",t.uid),{photo_url:s||null,updated_at:ie()},{merge:!0})}return e.jsxs(e.Fragment,{children:[e.jsx("section",{className:"mt-band mt-band-dark",children:e.jsxs("div",{className:"mt-wrap",children:[e.jsx("p",{className:"mt-eyebrow reveal",children:i("Gruppo di ricerca","Research Team")}),e.jsx("h1",{className:"mt-section-title reveal","data-d":"1",children:i("Impostazioni","Settings")}),e.jsx("p",{className:"mt-section-sub reveal","data-d":"2",children:i("Impostazioni dellâaccount: foto profilo, dati personali, password.","Account settings: profile photo, personal details, password.")})]})}),e.jsx("section",{className:"mt-band mt-band-tight",children:e.jsx("div",{className:"mt-wrap",children:e.jsxs("div",{className:"reveal mt-form-stack",children:[e.jsx(gu,{cardClassName:"mt-card mt-settings-card",uid:t==null?void 0:t.uid,name:t==null?void 0:t.name,email:t==null?void 0:t.email,photoUrl:t==null?void 0:t.photo_url,uploadFile:ze,savePhotoUrl:o,lang:n}),e.jsxs("section",{className:"mt-card mt-settings-card",children:[e.jsxs("div",{className:"mt-card-icon-head",children:[e.jsx(Cc,{size:16,className:"muted"}),e.jsx("h3",{children:i("Profilo","Profile")})]}),e.jsxs("div",{className:"mt-card-meta-grid",children:[e.jsx("span",{className:"muted",children:i("Nome","Name")}),e.jsx("span",{children:(t==null?void 0:t.name)||e.jsx("em",{className:"muted",children:i("non impostato","not set")})}),e.jsx("span",{className:"muted",children:"Email"}),e.jsx("span",{className:"mono",children:t==null?void 0:t.email}),e.jsx("span",{className:"muted",children:i("Ruolo","Role")}),e.jsx("span",{children:a?e.jsx("span",{className:"chip chip-accent mt-chip-sm",children:"Admin"}):e.jsx("span",{className:"chip mt-chip-sm",children:i("Ricercatore","Researcher")})})]}),e.jsx("div",{className:"muted text-xs mt-card-foot-note",children:i("Per modificare nome o email, contatta il PI: questi dati sono gestiti a livello di amministrazione del team.","To change your name or email, contact the PI: these details are managed at team administration level.")})]}),e.jsx(gn,{dove:"impostazioni"}),a&&e.jsx(ux,{}),e.jsx(mx,{})]})})})]})}function ux(){const{t}=X(),[a,i]=f.useState(null),[n,o]=f.useState(!1);f.useEffect(()=>{hu().then(l=>i(!!l["rt.timesheet"]))},[]);const s=async()=>{if(!(a==null||n)){o(!0);try{await fu("rt.timesheet",!a),i(!a)}catch(l){alert(t("Salvataggio non riuscito: ","Save failed: ")+(l.message||l))}finally{o(!1)}}};return e.jsxs("section",{className:"mt-card mt-settings-card",children:[e.jsxs("div",{className:"mt-card-icon-head",children:[e.jsx(_r,{size:16,className:"muted"}),e.jsx("h3",{children:t("Codice di originalità sui timesheet","Originality code on timesheets")})]}),e.jsx("p",{className:"muted text-sm",style:{margin:"0 0 12px"},children:t("Se è acceso, il PDF del timesheet esce con il codice e il QR di verifica. Sugli altri documenti del Research Team (missioni, acquisti, contratti, ospiti) il codice non câè.","When on, the timesheet PDF comes out with the verification code and QR. The other Research Team documents (missions, procurement, contracts, guests) carry no code.")}),e.jsx("button",{type:"button",role:"switch","aria-checked":!!a,className:"btn btn-sm "+(a?"btn-primary":"btn-secondary"),onClick:s,disabled:a==null||n,children:a==null?t("Caricoâ¦","Loadingâ¦"):a?t("Acceso","On"):t("Spento","Off")})]})}function mx(){const{t}=X(),[a,i]=f.useState(""),[n,o]=f.useState(""),[s,l]=f.useState(""),[r,d]=f.useState(!1),[m,c]=f.useState(null),[g,h]=f.useState(!1);async function p(x){var b;if(x.preventDefault(),c(null),h(!1),!((b=ye.currentUser)!=null&&b.email)){c(t("Sessione non valida â disconnettiti e accedi di nuovo.","Invalid session â sign out and back in."));return}if(!a){c(t("Inserisci la password attuale.","Enter your current password."));return}if(n.length<6){c(t("La nuova password deve contenere almeno 6 caratteri.","The new password must be at least 6 characters long."));return}if(n!==s){c(t("La nuova password e la sua conferma non coincidono.","The new password and its confirmation do n
696ot match."));return}if(n===a){c(t("La nuova password deve essere diversa da quella attuale.","The new password must differ from the current one."));return}d(!0);try{const u=bd.credential(ye.currentUser.email,a);await vd(ye.currentUser,u),await jd(ye.currentUser,n),h(!0),i(""),o(""),l("")}catch(u){c(px(u,t))}finally{d(!1)}}return e.jsxs("section",{className:"mt-card mt-settings-card",children:[e.jsxs("div",{className:"mt-card-icon-head mt-card-icon-head-tight",children:[e.jsx(cn,{size:16,className:"muted"}),e.jsx("h3",{children:t("Cambia password","Change password")})]}),e.jsx("p",{className:"muted text-sm mt-pw-intro",children:t("Inserisci la password attuale e quella nuova (almeno 6 caratteri). Resterai connesso dopo la modifica.","Enter your current password and the new one (at least 6 characters). You will remain signed in after the change.")}),e.jsxs("form",{onSubmit:p,className:"mt-pw-form",children:[e.jsx(ci,{id:"pw-current",label:t("Password attuale","Current password"),autoComplete:"current-password",value:a,onChange:x=>i(x.target.value)}),e.jsx(ci,{id:"pw-next",label:t("Nuova password (almeno 6 caratteri)","New password (at least 6 characters)"),autoComplete:"new-password",value:n,onChange:x=>o(x.target.value),minLength:6}),e.jsx(ci,{id:"pw-confirm",label:t("Conferma nuova password","Confirm new password"),autoComplete:"new-password",value:s,onChange:x=>l(x.target.value),minLength:6}),m&&e.jsxs("div",{className:"login-alert login-alert-error mt-pw-alert",children:[e.jsx(at,{size:16})," ",e.jsx("span",{children:m})]}),g&&e.jsxs("div",{className:"login-alert login-alert-success mt-pw-alert mt-pw-alert-success",children:[e.jsx(tt,{size:16})," ",e.jsx("span",{children:t("Password aggiornata.","Password updated.")})]}),e.jsx("div",{children:e.jsxs("button",{type:"submit",className:"btn btn-primary anim-shimmer"+(g?" anim-pulse-success":""),disabled:r,children:[e.jsx(vr,{size:14})," ",r?t("Aggiornamentoâ¦","Updatingâ¦"):t("Aggiorna password","Update password")]})})]}),e.jsxs("div",{className:"muted text-xs mt-pw-info",children:[e.jsx(_r,{size:13,className:"mt-pw-info-icon"}),e.jsxs("span",{children:[t("Se non ricordi la password attuale, disconnettiti e usa","If you do not remember your current password, sign out and use"),e.jsx("strong",{children:t(' "Password dimenticata?"',' "Forgot password?"')}),t(" nella pagina di accesso per ricevere un link di reimpostazione via email."," on the login page to receive a reset link by email.")]})]})]})}function px(t,a){const i=(t==null?void 0:t.code)||"";return i==="auth/wrong-password"||i==="auth/invalid-credential"?a("La password attuale non è corretta.","The current password is incorrect."):i==="auth/weak-password"?a("La nuova password è troppo debole (almeno 6 caratteri).","The new password is too weak (at least 6 characters)."):i==="auth/too-many-requests"?a("Troppi tentativi falliti â riprova tra qualche minuto.","Too many failed attempts â try again in a few minutes."):i==="auth/requires-recent-login"?a("La sessione è scaduta â disconnettiti e accedi di nuovo prima di cambiare la password.","The session has expired â sign out and back in before changing the password."):(t==null?void 0:t.message)||a("Errore sconosciuto.","Unknown error.")}function hx(t){return[{id:"mission_req_reminder",label:t("Richiesta di missione â sollecito","Mission request â reminder"),build:cd},{id:"mission_authorized",label:t("Missione autorizzata","Mission authorised"),build:dd},{id:"timesheet_reminder",label:t("Timesheet â sollecito mensile","Timesheet â monthly reminder"),build:ud},{id:"general",label:t("Comunicazione al gruppo","Team announcement"),build:md}]}function fr({children:t,withVideo:a=!0}){return e.jsxs("div",{className:"mpi-root mt-root",style:{color:"var(--text-primary)",minHeight:"100vh",position:"relative",overflow:"hidden"},children:[a&&e.jsxs(e.Fragment,{children:[e.jsx(Gc,{className:"mpi-backdrop"}),e.jsx("div",{className:"mpi-backdrop-overlay"})]}),e.jsx("div",{id:"main-content",style:{position:"relative",zIndex:2},children:t})]})}function fx(){const t=bu("management_team");Oc();const{t:a,lang:i}=X(),{theme:n,toggle:o}=Mc(),[s,l]=f.useState("auth-checking"),[r,d]=f.useState(null),[m,c]=f.useState({name:"home"}),g=qc([s,m.name,m.tool,m.uid]);Uc(`${m.name}|${m.tool||""}|${m.uid||""}`);const[h,p]=f.useState(!1),[x,b]=f.useState(()=>{try{return localStorage.getItem("climpact-mt-sidebar-collapsed")==="1"}catch{return!1}});f.useEffect(()=>{try{localStorage.setItem("climpact-mt-sidebar-collapsed",x?"1":"0")}catch{}},[x]);const[u,w]=f.useState(!1),[v,j]=f.useState(!1);async function _(){try{const{getFunctions:E,httpsCallable:Y}=await Ae(async()=>{const{getFunctions:Q,httpsCallable:le}=await import("./vendor-firebase-AOn3Fvmd.js").then(U=>
696U.ah);return{getFunctions:Q,httpsCallable:le}},[]),{app:S}=await Ae(async()=>{const{app:Q}=await import("./firebase-config-Dn2Tu_JL.js").then(le=>le.c);return{app:Q}},__vite__mapDeps([3,2])),W=E(S,"europe-west1"),J=await Y(W,"getTeamDirectory")({}),V=J==null?void 0:J.data;return(Array.isArray(V)?V:(V==null?void 0:V.directory)||(V==null?void 0:V.users)||[]).filter(Q=>{var le,U;return!Q.archived&&Q.email&&((U=(le=Q.portals)==null?void 0:le.management_team)==null?void 0:U.role)}).map(Q=>({uid:Q.uid,email:Q.email,name:Q.name||Q.email,role:Q.portals.management_team.role}))}catch(E){return console.warn("[mt-composer] directory load",E),[]}}f.useEffect(()=>{let E=!1,Y=null;return(async()=>(await fd(),!E&&(Y=yd(ye,async S=>{var W,M;if(!S){await gd()&&!E&&(d(null),l("logged-out"));return}try{const J=oe(te,"users",S.uid),V=await vi(J);let K=V.exists()?V.data()||{}:null,Q=((M=(W=K==null?void 0:K.portals)==null?void 0:W.management_team)==null?void 0:M.role)||null;const le=S.uid===Vi||(K==null?void 0:K.super_admin)===!0;if(!Q){Q=le?"admin":"researcher";try{await _e(J,{uid:S.uid,email:S.email||(K==null?void 0:K.email)||"",name:(K==null?void 0:K.name)||S.displayName||S.email||"",super_admin:le,portals:{management_team:{role:Q,joined_at:ie()}},created_at:(K==null?void 0:K.created_at)||ie(),updated_at:ie(),auto_bootstrap:!K},{merge:!0})}catch{}K||(K={uid:S.uid,email:S.email||""})}le&&(Q="admin");const U={uid:S.uid,email:S.email||(K==null?void 0:K.email)||"",name:(K==null?void 0:K.name)||S.displayName||S.email||"",photo_url:(K==null?void 0:K.photo_url)||null,...K||{},role:Q};E||(d(U),l("ready"),c(U.role==="admin"?{name:"admin"}:{name:"missions",uid:S.uid}))}catch(J){console.error("[team] bootstrap error:",J),E||(d(null),l("logged-out"))}}))))(),()=>{E=!0,Y&&Y()}},[]);async function C(){if(confirm(a("Disconnettersi?","Sign out?")))try{await _d(ye)}catch(E){console.error(E)}}const y=f.useRef(!1);f.useEffect(()=>{y.current||!r||!(new URLSearchParams(window.location.search).get("mask")||"").startsWith("mission-")||(y.current=!0,c(r.role==="admin"?{name:"missions",scope:"team"}:{name:"missions",uid:r.uid}))},[r]);const z=f.useRef(!1);if(f.useEffect(()=>{if(z.current||!r)return;const E=new URLSearchParams(window.location.search).get("view")||"";E!=="missions"&&E!=="timesheet"&&E!=="drop"||(z.current=!0,c(E==="drop"?{name:"drop"}:E==="timesheet"?{name:"timesheet",uid:r.uid,member:r}:r.role==="admin"?{name:"missions",scope:"team"}:{name:"missions",uid:r.uid,member:r}))},[r]),s==="auth-checking")return e.jsx(zr,{portal:a("Management â Gruppo di ricerca","Management â Research Team")});if(s==="logged-out")return e.jsx(ku,{});const T=Su();if(T)return e.jsx(Du,{request:T});const I=r.role==="admin";if(r.archived&&r.uid!==Vi)return e.jsx(fr,{children:e.jsx("div",{className:"mt-content mt-archived-stage",children:e.jsxs("div",{className:"mt-card mt-archived-card",children:[e.jsx("h2",{className:"mt-archived-title",children:a("Account archiviato","Account archived")}),e.jsx("p",{className:"muted mt-archived-body",children:a("Questo account è stato sospeso dal Principal Investigator. Contatta direttamente il PI per riattivarlo.","This account has been suspended by the Principal Investigator. Contact the PI directly to have it reinstated.")}),e.jsx("button",{className:"btn btn-secondary",onClick:C,children:a("Disconnettiti","Sign out")})]})})});function D(E){return I?e.jsxs("div",{role:"group","aria-label":a("Ambito","Scope"),style:{display:"flex",gap:6,flexWrap:"wrap"},children:[e.jsx("button",{type:"button",className:"btn btn-sm "+(E==="team"?"btn-primary":"btn-secondary"),"aria-pressed":E==="team",onClick:()=>c({name:"missions",scope:"team"}),children:a("Tutto il team","Whole team")}),e.jsx("button",{type:"button",className:"btn btn-sm "+(E==="mine"?"btn-primary":"btn-secondary"),"aria-pressed":E==="mine",onClick:()=>c({name:"missions",uid:r.uid,member:r}),children:a("Le mie","Mine")})]}):null}let $=null;if(m.name==="admin"&&I)$=e.jsxs(e.Fragment,{children:[e.jsx("section",{className:"mt-band",children:e.jsxs("div",{className:"mt-wrap",children:[e.jsx("p",{className:"mt-eyebrow reveal",children:a("Gruppo di ricerca","Research Team")}),e.jsxs("h1",{className:"mt-hero-title reveal","data-d":"1",children:[a("Operatività ","Team "),e.jsx("em",{children:a("e adempimenti","operations")}),e.jsx("span",{className:"mt-hero-accent",children:a("del gruppo","and compliance")})]}),e.jsx("p",{className:"mt-hero-lead reveal","data-d":"2",children:a("Iscritti e accessi, missioni, eventi, acquisti e contratti, e i timesheet del gruppo di ricerca CLIMPACT.","Membership and access, missions, events, procurement and contracts, and the timesheets of the CLIMPACT research group.")}),e.jsx(Js,{guide:Ys.management_team,uid:r==null?void 0:r.uid,lang:i})]})}),e.jsx(Ou,{}),e.jsx(cx,{onApriMissioni:()=>c({name:"missions",scope:"team"}),onApriAcquisti:()=>c({name:"admin-tool",tool:"purchases"})}),e.jsx("section",{className:"mt-band mt-band-tight mt-band-alt",children:e.jsxs("div",{className:"mt-wrap",children:[e.jsx("div",{className:"mt-section-head reveal",children:e.jsxs("div",{children:[e.jsx("p",{className:"mt-eyebrow",children:a("Strumenti","Tools")}),e.jsx("h2",{className:"mt-section-title",children:a("Sezioni amministrative","Administrative sections")}),e.jsx("p",{className:"mt-section-sub",children:a("Le procedure ufficiali del progetto, c
696on documenti PDF generati automaticamente.","The project's official procedures, with automatically generated PDF documents.")})]})}),e.jsx("div",{className:"reveal","data-d":"1",children:e.jsx(_u,{onOpenTool:E=>c({name:"admin-tool",tool:E})})})]})}),e.jsx("section",{className:"mt-band mt-band-tight",children:e.jsx("div",{className:"mt-wrap reveal",children:e.jsx(rc,{portalKey:"management_team",me:r,sendMail:Ra,recipientLoader:_,createMember:Qs})})})]});else if(m.name==="admin-tool"&&I){const E=()=>c({name:"admin"});m.tool==="events"?$=e.jsx(Hh,{onBack:E}):m.tool==="purchases"?$=e.jsx(Nf,{onBack:E,me:r}):m.tool==="contracts"?$=e.jsx(Af,{onBack:E,me:r}):m.tool==="guests"?$=e.jsx(Bf,{onBack:E,me:r}):$=e.jsx("section",{className:"mt-band mt-band-tight",children:e.jsx("div",{className:"mt-wrap",children:e.jsx("div",{className:"mt-card mt-empty",children:a("Strumento non riconosciuto.","Unrecognised tool.")})})})}else if(m.name==="missions")if(I&&m.scope==="team")$=e.jsx(Mo,{onBack:()=>c({name:"admin"}),member:r,isAdmin:I,allTeam:!0,headExtra:D("team")});else{const Y=m.uid||r.uid,S=Y===r.uid;$=e.jsx(gr,{Component:Mo,uid:Y,prefetched:m.member||(S?r:null),isAdmin:I,onBack:I?()=>c({name:"admin"}):null,extraProps:{headExtra:S?D("mine"):null,guide:S?e.jsxs(e.Fragment,{children:[!I&&e.jsx(Js,{guide:Ys.management_team,uid:r.uid,lang:i}),e.jsx(gn,{dove:"home"})]}):null}})}else if(m.name==="drop")$=e.jsx(Up,{me:r,onExit:()=>c({name:"missions",uid:r.uid,member:r})});else if(m.name==="timesheet"){const E=m.uid||r.uid,Y=E===r.uid;$=e.jsx(gr,{Component:ph,uid:E,prefetched:m.member||(Y?r:null),isAdmin:I,onBack:I?()=>c({name:"admin"}):null})}else m.name==="meetings"?$=e.jsx(sc,{to:"/tools/meet",replace:!0}):m.name==="__meetings_legacy__"?$=e.jsx(sg,{me:r,isAdmin:I,recipientLoader:_,sendMail:Ra,wrapEmail:Wi,showCreate:!1}):m.name==="activity"?$=e.jsx(Sg,{me:r,isAdmin:I,recipientLoader:_}):m.name==="minutes"?$=e.jsx(Zg,{me:r,isAdmin:I,recipientLoader:_}):m.name==="dashboard"&&I?$=e.jsx(lx,{me:r,recipientLoader:_,onOpen:E=>c({name:E})}):m.name==="settings"?$=e.jsx(dx,{me:r,isAdmin:I}):m.name==="mail-rules"&&I?$=e.jsx("section",{className:"mt-band mt-band-tight",children:e.jsx("div",{className:"mt-wrap",children:e.jsx(wd,{platform:"rt",db:te,tint:Hc("management_team"),portalLabel:"Research Team",currentUserUid:r==null?void 0:r.uid})})}):m.name==="privacy"||m.name==="cookie"?$=e.jsx(xu,{docId:m.name==="cookie"?Xs.COOKIE:Xs.PRIVACY,onBack:()=>c(I?{name:"admin"}:{name:"missions",uid:r.uid,member:r}),backLabel:a("Torna al portale","Back to the portal"),heroClass:"mt-band mt-band-dark portal-legal-fullbleed",bodyClass:"mt-band mt-band-tight portal-legal-body-white portal-legal-fullbleed",wrapClass:"mt-wrap",eyebrowClass:"mt-eyebrow",titleClass:"mt-hero-title"}):$=e.jsx("section",{className:"mt-band mt-band-tight",children:e.jsx("div",{className:"mt-wrap",children:e.jsx("div",{className:"mt-card mt-empty",children:a("Vista non riconosciuta.","Unrecognised view.")})})});const q=m.name==="admin",R=m.name==="missions",O=m.name==="timesheet",k=m.name==="settings",N=I?[{id:"team",icon:e.jsx(ia,{size:16}),label:a("Team","Team"),onClick:()=>c({name:"admin"}),active:q},{divider:!0},{id:"activity",icon:e.jsx(_a,{size:16}),label:a("Attività ","Activities"),onClick:()=>c({name:"activity"}),active:m.name==="activity"},{id:"minutes",icon:e.jsx(sa,{size:16}),label:a("Verbali","Minutes"),onClick:()=>c({name:"minutes"}),active:m.name==="minutes"},{id:"dashboard",icon:e.jsx(kc,{size:16}),label:a("Cruscotto","Overview"),onClick:()=>c({name:"dashboard"}),active:m.name==="dashboard"},{divider:!0},{id:"missions",icon:e.jsx(pi,{size:16}),label:a("Missioni","Missions"),onClick:()=>c({name:"missions",scope:"team"}),active:R},{id:"timesheet",icon:e.jsx(Ue,{size:16}),label:a("Timesheet","Timesheet"),onClick:()=>c({name:"timesheet",uid:r.uid,member:r}),active:O},{id:"drop",icon:e.jsx(Ba,{size:16}),label:a("Ricevute","Receipts"),onClick:()=>c({name:"drop"}),active:m.name==="drop"},{divider:!0},{id:"events",icon:e.jsx(hi,{size:16}),label:a("Eventi del team","Team events"),onClick:()=>c({name:"admin-tool",tool:"events"}),active:m.name==="admin-tool"&&m.tool==="events"},{id:"purchases",icon:e.jsx(Nr,{size:16}),label:a("Acquisti","Procurement"),onClick:()=>c({name:"admin-tool",tool:"purchases"}),active:m.name==="admin-tool"&&m.tool==="purchases"},{id:"contracts",icon:e.jsx(st,{size:16}),label:a("Contratti","Contracts"),onClick:()=>c({name:"admin-tool",tool:"contracts"}),active:m.name==="admin-tool"&&m.tool==="contracts"},{id:"guests",icon:e.jsx(jr,{size:16}),label:a("Ospiti","Guests"),onClick:()=>c({name:"admin-tool",tool:"guests"}),active:m.name==="admin-tool"&&m.tool==="guests"},{divider:!0},{id:"mail-rules",icon:e.jsx(Sc,{size:16}),label:a("Regole mail","Mail rules"),onClick:()=>c({name:"mail-rules"}),active:m.name==="mail-rules"},{id:"settings",icon:e.jsx(Ks,{size:16}),label:a("Impostazioni","Settings"),onClick:()=>c({name:"settings"}),active:k},{id:"mcp",icon:e.jsx(ju,{size:16}),label:a("Usa da Claude","Use it from Claude"),onClick:()=>j(!0),active:!1},t.item]:[{id:"missions",icon:e.jsx(pi,{size:16}),label:a("Missioni","Missions"),onClick:()=>c({name:"missions",uid:r.uid,member:r}),active:R},{id:"timesheet",icon:e.jsx(Ue,{size:16}),label:a("Timesheet","Timesheet"),onClick:()=>c({name:"timesheet",uid:r.uid,member:r}),active:O},{id:"drop",icon:e.jsx(Ba,{size:16}),label:a("Ricevute","Receipts"),onClick:()=>c({name:"drop"}),active:m.name==="drop"},{divider:!0},{id:"activity",icon:e.jsx(_a,{size:16}),label:a("Attività ","Activities"),onClick:()=>c({name:"activity"}),active:m.name==="activity"},{id:"minutes",icon:e.jsx(sa,{size:16}),label:a("Verbali","Minutes"),onClick:()=>c({name:"minutes"}),active:m.name==="minutes"},{divider:!0},{id:"settings",icon:e.jsx(Ks,{size:16}),label:a("Impostazioni","Settings"),onClick:()=>c({name:"settings"}),active:k},t.item],L=e.jsx("img",{src:"/climpact-wordmark-white.svg?v=glass",alt:"climpact",className:"tt-wordmark"}),B=e.jsx(hd,{uid:r.uid,onJump:E=>{E!=null&&E.target&&(E.target.kind==="mission"?c({name:"missions",uid:E.target.member_uid||r.uid}):E.target.kind==="timesheet"?c({name:"timesheet",uid:E.target.member_uid||r.uid}):E.target.kind==="action_item"?c({name:"minutes"}):["deliverable","task","milestone","activity"].includes(E.target.kind)&&c({name:"activity"}))}}),P=e.jsx(Bc,{portalKey:"management_team",me:r,createMember:Qs,extraFields:[{key:"portals",label:"Climpact Platform portals",type:"portals-multi-select"}],collapsed:!0,sendTestMail:Ra});return e.jsx(fr,{children:e.jsxs(Ud,{children:[t.open&&e.jsx(vu,{open:!0,onClose:t.close,portalKey:t.portalKey,me:r}),e.jsx(Cu,{brand:L,items:N,me:r,isAdmin:I,onCompose:()=>w(!0),notifications:B,addMember:P,onLogout:C,mobileOpen:h,onMobileOpen:()=>p(!0),onMobileClose:()=>p(!1)}),v&&e.jsx(Ec,{strumenti:[Ac,$c],tinta:"#1a6b6a",titolo:"Missions from Claude",onClose:()=>j(!1)}),e.jsx(Ns,{assetsPrivate:!0,open:u,onClose:()=>w(!1),sendMail:Ra,loadRecipients:_,portalLabel:"Research Team",templates:hx(a),wrapHtml:(E,Y,S)=>Wi({heading:Y,bodyHtml:E,headerGradient:S==null?void 0:S.headerGradient})}),e.jsx("div",{className:"mt-shell-body portal-site",ref:g,children:e.jsx("div",{className:"mt-content",children:$})}),e.jsx(xx,{onPrivacy:()=>c({name:"privacy"}),onCookie:()=>c({name:"cookie"})})]})})}const gx="https://www.climpact.it";function xx({onPrivacy:t,onCookie:a}){const{t:i}=X();return e.jsx("footer",{className:"mt-site-foot","aria-label":"Climpact",children:e.jsxs("div",{className:"mt-site-foot-inner",children:[e.jsxs("div",{className:"mt-site-foot-top",children:[e.jsxs("div",{className:"mt-site-foot-about",children:[e.jsx("img",{src:"/climpact-wordmark-white.svg?v=glass",alt:"Climpact",className:"mt-site-foot-wordmark"}),e.jsxs("p",{className:"mt-site-foot-grant",children:[e.jsx("span",{className:"mt-site-foot-grant-lead",children:"Climpact"})," | Charting the Landscape of Climate Litigation Impacts: An Interdisciplinary Framework and Open Access Database is a Starting Grant funded under the FIS 3 (Fondo Italiano per la Scienza) Call",e.jsx("br",{}),"D.D. 1802/2024 â CUP H53C25000820001"]}),e.jsx("p",{className:"mt-site-foot-copy",children:i("© 2026 Team Climpact","© 2026 Climpact team")})]}),e.jsxs("div",{className:"mt-site-foot-nav",children:[e.jsxs("div",{className:"mt-site-foot-group",children:[e.jsx("h3",{className:"mt-site-foot-h",children:i("Esplora","Explore")}),e.jsxs("a",{className:"mt-site-foot-a",href:gx,target:"_blank",rel:"noopener noreferrer",children:["climpact.it ",e.jsx(Ri,{size:12,"aria-hidden":"true"})]}),e.jsx("a",{href:Ja("/site/research"),target:"_blank",rel:"noopener noreferrer",className:"mt-site-foot-a",children:i("Ricerca","Research")}),e.jsx("a",{href:Ja("/site/initiatives"),target:"_blank",rel:"noopener noreferrer",className:"mt-site-foot-a",children:i("Iniziative","Initiatives")}),e.jsx("a",{href:Ja("/site/governance"),target:"_blank",rel:"noopener noreferrer",className:"mt-site-foot-a",children:i("Governance","Governance")}),e.jsx("a",{href:Ja("/people"),target:"_blank",rel:"noopener noreferrer",className:"mt-site-foot-a",children:i("Persone","People")})]}),e.jsxs("div",{className:"mt-site-foot-group",children:[e.jsx("h3",{className:"mt-site-foot-h",children:i("Risorse","Resources")}),e.jsx("a",{href:Ja("/radar"),target:"_blank",rel:"noopener noreferrer",className:"mt-site-foot-a",children:"Climpact Radar"}),e.jsx(Wc,{onPrivacy:t,onCookie:a,etichette:{privacy:i("Informativa privacy","Privacy Policy"),cookie
696:i("Informativa cookie","Cookie Policy"),impostazioni:i("Impostazioni cookie","Cookie settings")}})]}),e.jsxs("div",{className:"mt-site-foot-group",children:[e.jsx("h3",{className:"mt-site-foot-h",children:i("Seguici","Follow")}),e.jsxs("div",{className:"mt-site-foot-social",children:[e.jsx("a",{href:In.linkedin,className:"mt-site-foot-social-btn","aria-label":i("Climpact su LinkedIn","Climpact on LinkedIn"),target:"_blank",rel:"noopener noreferrer",children:e.jsx(Dc,{size:18,"aria-hidden":"true"})}),e.jsx("a",{href:In.instagram,className:"mt-site-foot-social-btn","aria-label":i("Climpact su Instagram","Climpact on Instagram"),target:"_blank",rel:"noopener noreferrer",children:e.jsx(Tc,{size:18,"aria-hidden":"true"})}),e.jsx("a",{href:In.youtube,className:"mt-site-foot-social-btn","aria-label":i("Climpact su Instagram","Climpact on YouTube"),target:"_blank",rel:"noopener noreferrer",children:e.jsx(Ic,{size:18,"aria-hidden":"true"})})]})]})]})]}),e.jsx("div",{className:"mt-site-foot-base",children:e.jsx(Vc,{className:"mt-site-foot-logos"})})]})})}function gr({Component:t,uid:a,prefetched:i,isAdmin:n,onBack:o,extraProps:s}){const{t:l}=X(),[r,d]=f.useState(i||null);return f.useEffect(()=>{r||(async()=>{var m,c;try{const g=await vi(oe(te,"users",a));if(g.exists()){const h=g.data()||{};d({uid:a,...h,role:((c=(m=h.portals)==null?void 0:m.management_team)==null?void 0:c.role)||null})}}catch(g){console.error("[team] subpage member fetch",g)}})()},[a]),r?e.jsx(t,{member:r,isAdmin:n,onBack:o,...s||{}}):e.jsxs(e.Fragment,{children:[e.jsx("section",{className:"mt-band mt-band-dark",children:e.jsxs("div",{className:"mt-wrap",children:[e.jsx(xa.Line,{width:140}),e.jsx("div",{style:{height:14}}),e.jsx(xa.Title,{width:"46%",height:38}),e.jsx("div",{style:{height:18}}
696),e.jsx(xa.Text,{lines:2,label:l("Caricamento","Loading")})]})}),e.jsx("section",{className:"mt-band mt-band-tight",children:e.jsx("div",{className:"mt-wrap",children:e.jsx(xa.List,{rows:3,avatar:!1,label:l("Caricamento","Loading")})})})]})}const Sb=Object.freeze(Object.defineProperty({__proto__:null,default:fx},Symbol.toStringTag,{value:"Module"}));export{sg as M,Cu as T,xx as a,Sb as b,Jf as n,kb as p};
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.