1import{r as c,j as e}from"./vendor-ui-7a2g4EPQ.js";import{b as me,g as le,n as X}from"./index-BRqlr9pz.js";import{A as Ye,G as js}from"./AppLayout-gxgHxLD7.js";import{C as K,b as De,c as Pe,a as G}from"./card-dydI4wdZ.js";import{B as Y}from"./badge-flWvuATz.js";import{B as L}from"./button-IWipDNMr.js";import{I as R}from"./input-DDXvkULH.js";import{T as Ne,a as we,b as V,c as I}from"./tabs-MsazapdW.js";import{T as fe,a as je,b as U,c as E,d as ge,e as k}from"./table-z0ci0TOl.js";import{D as We,a as Qe,b as Je,c as Xe,e as gs}from"./dialog-CaoKy1hf.js";import{S as Z,a as ee,b as se,c as te,d as $}from"./select-DFzfCdPR.js";import{L as Ae}from"./label-CCYmj4WJ.js";import{a as ys}from"./useRoles-D6p9m1wA.js";import{u as _s,a as vs,b as Ns,c as ws,d as bs,e as Ss,f as ks,D as Le,h as Ie}from"./useWorkSchedules-Bd_KB1At.js";import{b as Cs,c as Ms,O as qs,u as Es}from"./OvertimeRequestDialog-D4j3ndi1.js";import{S as ye}from"./switch-CkGxWtyu.js";import{f as Ts}from"./usePontoHorarioSemanal-C9erAhgf.js";import{L as be}from"./loader-circle-iRnjTJNH.js";import{C as Ds}from"./calendar-range-DxWyrRNl.js";import{C as Ke}from"./calendar-DZ5UmznR.js";import{S as Ps}from"./save-CenMvpW6.js";import{P as ns}from"./plus-LvPZ1H8E.js";import{T as As}from"./trash-2-DdhoFaF7.js";import{C as Ze}from"./copy-Cxy46ndl.js";import{f as H,s as Oe,e as Fs,t as Fe,p as W,j as Ls,k as $s,u as _e,m as is}from"./vendor-date-BjUT7hhi.js";import{p as Se}from"./pt-pv7w5cIY.js";import{C as ls}from"./clock-C_pnHwX8.js";import{u as z,b as Os}from"./vendor-query-C7Sh1Wuq.js";import{S as ue}from"./search-CTiyquGI.js";import{M as $e}from"./map-pin-BarqtCFL.js";import{U as Ge}from"./users-DCOeoGK_.js";import{L as Be}from"./vendor-react-wPwDAbZm.js";import{g as ve}from"./VacationCalendar-D_63LJHB.js";import{C as os}from"./chevron-left-C7k5JJlX.js";import{C as cs}from"./chevron-right-YDxwak9y.js";import{T as Rs,P as Hs}from"./table-properties-JET3idwb.js";import{L as ds}from"./layout-grid-Gu9EbwY_.js";import{E as zs}from"./external-link-CXUgXr8R.js";import{L as Bs}from"./list-Do8P1ymN.js";import{C as es}from"./circle-check-BVuaRlc8.js";import{C as ss}from"./circle-x-QC8kEXGK.js";import"./vendor-supabase-CmEeeXwu.js";import"./vendor-pdf-C7_rzZkG.js";import"./vendor-charts-BA2datHr.js";import"./download-DhVe0c4Z.js";import"./wifi-off-DQHND7A_.js";import"./sheet-yE9VdCms.js";import"./popover-BV-bzWh8.js";import"./scroll-area-C82cbuBi.js";import"./chevron-down-B2ONYjXh.js";import"./check-Sze_G5rf.js";import"./building-2-DYhs9epK.js";import"./mail-DuqP7ufE.js";import"./sparkles-CC4s_vgX.js";import"./briefcase-B3Q3DxP-.js";import"./clipboard-list-DKfIBgTx.js";import"./stethoscope-IUcUMgxB.js";import"./shield-BUy3YEGg.js";import"./book-open-uB6Hzx6-.js";import"./user-BJd_oNUv.js";import"./triangle-alert-CGZj8GUT.js";import"./file-text-BU7RK35p.js";import"./circle-check-big-SYctJUov.js";import"./chevron-up-3e2jIu6C.js";import"./textarea-Chi2Y5XV.js";import"./ptHolidays-B_r775b4.js";import"./calendar-1UpBQPUQ.js";const ke={start_time:"09:00",end_time:"18:00",lunch_start:"13:00",lunch_end:"14:00"};function de(o){const[l,m]=o.split(":").map(Number);return l*60+(m||0)}function ms(o,l,m,p){const h=Math.max(de(o),de(m)),u=Math.min(de(l),de(p));return Math.max(0,u-h)}function Re(o){return o.reduce((l,m)=>
1m.is_active?l+Math.max(0,de(m.end_time)-de(m.start_time)-m.lunch_duration_minutes):l,0)}function He(o,l){const m=[];for(let p=0;p<7;p++){const h=o.find(F=>F.weekday===p&&(F.week_parity||"all")===l),u=h?.start_time?.slice(0,5)||ke.start_time,j=h?.end_time?.slice(0,5)||ke.end_time,g=h?.lunch_start?.slice(0,5)||ke.lunch_start,w=h?.lunch_end?.slice(0,5)||ke.lunch_end;m.push({weekday:p,week_parity:l,start_time:u,end_time:j,lunch_start:g,lunch_end:w,lunch_duration_minutes:ms(u,j,g,w),is_active:h?h.is_active:p>=1&&p<=5})}return m}function Us({userId:o,userName:l}){const{data:m=[],isLoading:p}=_s(o),{data:h}=vs(o),u=Ns(),j=ws(),g=h?.schedule_type==="biweekly",[w,F]=c.useState("week_a"),[q,O]=c.useState([]),[v,C]=c.useState([]),[A,a]=c.useState([]),[i,b]=c.useState(h?.biweekly_reference_date||""),f=H(new Date,"yyyy-MM"),[n,s]=c.useState(f),{data:t=[],isLoading:d}=bs(o,n),y=Ss(),S=ks(),[_,D]=c.useState(""),[P,Q]=c.useState({start_time:"09:00",end_time:"18:00",lunch_start:"13:00",lunch_end:"14:00",is_day_off:!1,reason:""});c.useEffect(()=>{a(He(m,"all")),O(He(m,"week_a")),C(He(m,"week_b"))},[m]),c.useEffect(()=>{h?.biweekly_reference_date&&b(h.biweekly_reference_date)},[h?.biweekly_reference_date]);const r=g?w==="week_a"?q:v:A,B=g?(Re(q)+Re(v))/2:Re(A),ae=x=>{g?w==="week_a"?O(x):C(x):a(x)},J=(x,N,T)=>{ae(M=>M.map((oe,fs)=>{if(fs!==x)return oe;const ne={...oe,[N]:T};return(N==="lunch_start"||N==="lunch_end"||N==="start_time"||N==="end_time")&&ne.lunch_start&&ne.lunch_end&&(ne.lunch_duration_minutes=ms(ne.start_time,ne.end_time,ne.lunch_start,ne.lunch_end)),ne}))},re=x=>{ae(N=>{const T=N[x];return N.map((M,oe)=>oe===x?M:M.weekday>=1&&M.weekday<=5?{...M,start_time:T.start_time,end_time:T.end_time,lunch_start:T.lunch_start,lunch_end:T.lunch_end,lunch_duration_minutes:T.lunch_duration_minutes,is_active:T.is_active}:M)}),me.info("Horário replicado para todos os dias úteis")},xe=x=>{ae(N=>{const T=N[x];return N.map((M,oe)=>oe===x?M:{...M,start_time:T.start_time,end_time:T.end_time,lunch_start:T.lunch_start,lunch_end:T.lunch_end,lunch_duration_minutes:T.lunch_duration_minutes,is_active:T.is_active})}),me.info("Horário replicado para todos os dias")},us=async()=>{const x=[];(g?[q,v]:[A]).forEach(T=>{T.forEach(M=>{x.push({user_id:o,weekday:M.weekday,week_parity:M.week_parity,start_time:M.start_time,end_time:M.end_time,lunch_start:M.lunch_start||null,lunch_end:M.lunch_end||null,lunch_duration_minutes:M.lunch_duration_minutes,is_active:M.is_active})})}),j.mutate(x)},xs=x=>{u.mutate({userId:o,schedule_type:x,biweekly_reference_date:x==="biweekly"?i||H(new Date,"yyyy-MM-dd"):null})},hs=()=>{_&&(y.mutate({user_id:o,override_date:_,start_time:P.is_day_off?null:P.start_time,end_time:P.is_day_off?null:P.end_time,lunch_start:P.is_day_off?null:P.lunch_start,lunch_end:P.is_day_off?null:P.lunch_end,is_day_off:P.is_day_off,reason:P.reason||null}),D(""))};if(p)return e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(be,{className:"w-5 h-5 animate-spin text-muted-foreground"})});const ps=x=>e.jsx("div",{className:"space-y-2",children:x.map((N,T)=>e.jsxs("div",{className:"flex items-center gap-3 flex-wrap rounded-lg border border-border p-3 bg-background",children:[e.jsxs("div",{className:"flex items-center gap-2 w-28",children:[e.jsx(ye,{checked:N.is_active,onCheckedChange:M=>J(T,"is_active",M)}),e.jsx("span",{className:`text-sm font-medium ${N.is_active?"text-foreground":"text-muted-foreground"}`,children:Le[N.weekday]})]}),N.is_active&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(R,{type:"time",value:N.start_time,onChange:M=>J(T,"start_time",M.target.value),className:"w-24 h-8 text-xs"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"â"}),e.jsx(R,{type:"time",value:N.end_time,onChange:M=>J(T,"end_time",M.target.value),className:"w-24 h-8 text-xs"})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Intervalo:"}),e.jsx(R,{type:"time",value:N.lunch_start,onChange:M=>J(T,"lunch_start",M.target.value),className:"w-24 h-8 text-xs",title:"Hora de inÃcio do intervalo â define aqui um intervalo grande (ex: 12:00â16:00) para uma jornada descontÃnua"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"â"}),e.jsx(R,{type:"time",value:N.lunch_end,onChange:M=>J(T,"lunch_end",M.target.value),className:"w-24 h-8 text-xs",title:"Hora de fim do intervalo"}),e.jsxs("span",{className:"text-xs text-muted-foreground ml-1 whitespace-nowrap",title:"Duração do intervalo, calculada automaticamente a partir das horas ao lado",children:["= ",N.lunch_duration_minutes," min"]}),!N.lunch_duration_minutes&&e.jsx("span",{className:"text-[11px] text-muted-foreground italic",children:"turno único, sem intervalo"})]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsxs(L,{variant:"ghost",size:"sm",className:"h-7 text-xs px-2",onClick:()=>re(T),title:"Replicar para dias úteis",children:[e.jsx(Ze,{className:"w-3 h-3 mr-1"})," Ãteis"]}),e.jsxs(L,{variant:"ghost",size:"sm",className:"h-7 text-xs px-2",onClick:()=>xe(T),title:"Replicar para todos",children:[e.jsx(Ze,{className:"w-3 h-3 mr-1"})," Todos"]})]})]})]},`${N.weekday}-${N.week_parity}`))});return e.jsxs("div",{className:"space-y-4",children:[l&&e.jsxs("h4",{className:"font-medium text-foreground",children:["Horário de ",l]}),e.jsxs("div",{className:"rounded-lg border border-border bg-muted/30 p-3 flex flex-wrap items-end gap-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(Ae,{className:"text-xs",children:"Tipo de horário"}),e.jsxs(Z,{value:h?.schedule_type||"weekly",onValueChange:x=>xs(x),children:[e.jsx(ee,{className:"h-8 w-44 text-xs",children:e.jsx(se,{})}),e.jsxs(te,{children:[e.jsx($,{value:"weekly",children:"Semanal (igual todas as semanas)"}
1),e.jsx($,{value:"biweekly",children:"Quinzenal (Semana A / Semana B)"})]})]})]}),g&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(Ae,{className:"text-xs",children:"Data de referência (Semana A começa)"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(R,{type:"date",value:i,onChange:x=>b(x.target.value),className:"w-44 h-8 text-xs"}),e.jsx(L,{size:"sm",variant:"outline",className:"h-8",onClick:()=>u.mutate({userId:o,schedule_type:"biweekly",biweekly_reference_date:i}),children:"Guardar"})]})]})]}),e.jsxs(Ne,{defaultValue:"weekly",children:[e.jsxs(we,{children:[e.jsx(V,{value:"weekly",children:g?e.jsxs(e.Fragment,{children:[e.jsx(Ds,{className:"w-3.5 h-3.5 mr-1"}),"Quinzenal"]}):"Semanal"}),e.jsxs(V,{value:"overrides",children:[e.jsx(Ke,{className:"w-3.5 h-3.5 mr-1"}),"Exceções"]})]}),e.jsxs(I,{value:"weekly",className:"space-y-3 mt-3",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3 flex-wrap",children:[e.jsx("p",{className:"text-xs text-muted-foreground flex-1 min-w-[220px]",children:g?"Define dois horários alternados. A semana A começa na data de referência e alterna a cada 7 dias.":"Horário recorrente semanal. Define as horas exatas do intervalo (a duração em minutos segue automaticamente), ou só a duração se o colaborador puder almoçar a qualquer hora. Para jornada descontÃnua (dois perÃodos de trabalho no mesmo dia), usa um intervalo grande â ex: inÃcio 08:00, intervalo 12:00â16:00, fim 20:00."}),e.jsxs("div",{className:"text-sm font-medium text-foreground whitespace-nowrap",children:[g?"Média semanal":"Total semanal",": ",Ts(B)]})]}),g&&e.jsx(Ne,{value:w,onValueChange:x=>F(x),children:e.jsxs(we,{className:"w-full grid grid-cols-2",children:[e.jsx(V,{value:"week_a",children:"Semana A"}),e.jsx(V,{value:"week_b",children:"Semana B"})]})}),ps(r),e.jsxs(L,{onClick:us,disabled:j.isPending,children:[j.isPending?e.jsx(be,{className:"w-4 h-4 animate-spin mr-2"}):e.jsx(Ps,{className:"w-4 h-4 mr-2"}),"Guardar Horário"]})]}),e.jsxs(I,{value:"overrides",className:"space-y-3 mt-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Exceções para dias especÃficos. Sobrepõem o horário semanal."}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Mês:"}),e.jsx(R,{type:"month",value:n,onChange:x=>s(x.target.value),className:"w-40 h-8 text-xs"})]}),e.jsx("div",{className:"rounded-lg border border-dashed border-border p-3 space-y-2",children:e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx(R,{type:"date",value:_,onChange:x=>D(x.target.value),className:"w-40 h-8 text-xs"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(ye,{checked:P.is_day_off,onCheckedChange:x=>Q(N=>({...N,is_day_off:x}))}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"Folga"})]}),!P.is_day_off&&e.jsxs(e.Fragment,{children:[e.jsx(R,{type:"time",value:P.start_time,onChange:x=>Q(N=>({...N,start_time:x.target.value})),className:"w-24 h-8 text-xs"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"â"}),e.jsx(R,{type:"time",value:P.end_time,onChange:x=>Q(N=>({...N,end_time:x.target.value})),className:"w-24 h-8 text-xs"})]}),e.jsx(R,{placeholder:"Motivo (opcional)",value:P.reason,onChange:x=>Q(N=>({...N,reason:x.target.value})),className:"w-36 h-8 text-xs"}),e.jsxs(L,{size:"sm",className:"h-8",onClick:hs,disabled:!_||y.isPending,children:[e.jsx(ns,{className:"w-3.5 h-3.5 mr-1"})," Adicionar"]})]})}),d?e.jsx("div",{className:"text-center text-sm text-muted-foreground py-4",children:"A carregarâ¦"}):t.length===0?e.jsx("div",{className:"text-center text-sm text-muted-foreground py-4",children:"Sem exceções neste mês."}):e.jsx("div",{className:"space-y-1.5",children:t.map(x=>e.jsxs("div",{className:"flex items-center justify-between gap-2 rounded-lg border border-border p-2.5 bg-background",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx("span",{className:"font-medium text-foreground",children:H(new Date(x.override_date+"T12:00:00"),"EEEE, d MMM",{locale:Se})}),x.is_day_off?e.jsx("span",{className:"text-xs text-muted-foreground bg-muted px-2 py-0.5 rounded",children:"Folga"}):e.jsxs("span",{className:"text-xs text-muted-foreground",children:[x.start_time?.slice(0,5)," â ",x.end_time?.slice(0,5)]}),x.reason&&e.jsxs("span",{className:"text-xs text-muted-foreground italic",children:["(",x.reason,")"]})]}),e.jsx(L,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-destructive",onClick:()=>S.mutate(x.id),children:e.jsx(As,{className:"w-3.5 h-3.5"})})]},x.id))})]})]})]})}const Ce=le();function Vs(){const[o,l]=c.useState(30),[m,p]=c.useState(!0),[h,u]=c.useState(!1);c.useEffect(()=>{(async()=>{const{data:g}=await Ce.from("time_tracking_settings").select("schedule_tolerance_minutes").maybeSingle();g?.schedule_tolerance_minutes!=null&&l(Number(g.schedule_tolerance_minutes)),p(!1)})()},[]);const j=async()=>{u(!0);try{const{data:g}=await Ce.from("time_tracking_settings").select("id").maybeSingle();if(g?.id){const{error:w}=await Ce.from("time_tracking_settings").update({schedule_tolerance_minutes:o}).eq("id",g.id);if(w)throw w}else{const{error:w}=await Ce.from("time_tracking_settings").insert([{schedule_tolerance_minutes:o}]);if(w)throw w}me.success("Tolerância guardada.")}catch(g){me.error(`Erro a guardar: ${g?.message||"desconhecido"}`)}finally{u(!1)}};return e.jsxs(K,{children:[e.jsx(De,{children:e.jsxs(Pe,{className:"text-base flex items-center gap-2",children:[e.jsx(ls,{className:"w-4 h-4"})," Configuração de Picagem"]})}),e.jsx(G,{className:"space-y-3",children:e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3 sm:items-end",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx(Ae,{htmlFor:"tolerance",className:"text-sm",children:"Tolerância fora do horário (minutos)"}),e.jsx(R,{id:"tolerance",type:"number",min:0,max:240,value:o,disabled:m,onChange:g=>l(Math.max(0,Number(g.target.value)||0))}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Margem antes/depois do horário previsto. Picagens fora desta janela ficam pendentes e requerem comentário."})]}),e.jsxs(L,{onClick:j,disabled:h||m,children:[h&&e.jsx(be,{className:"w-4 h-4 mr-2 animate-spin"}),"Guardar"]})]})})]})}const Me=le(),ze=[1,2,3,4,5];function Is({userIds:o}){const[l,m]=c.useState(""),[p,h]=c.useState("all"),[u,j]=c.useState("current"),{data:g=[]}=z({queryKey:["profiles-grid"],queryFn:async()=>{const a=["super_user","administrativo","tecnico","comercial","medico","enfermeiro","externo"],[{data:i,error:b},{data:f,error:n}]=await Promise.all([Me.from("profiles").select("id, nome, email").eq("is_archived",!1).order("nome"),Me.from("user_roles").select("user_id").in("role",a)]);if(b)throw b;if(n)throw n;const s=new Set((f||[]).map(t=>t.user_id));return(i||[]).filter(t=>s.has(t.id))}}),{data:w=[]}=z({queryKey:["clinics-active"],queryFn:async()=>{const{data:a,error:i}=await Me.from("clinics").select("id, name").eq("is_active",!0).order("name");if(i)throw i;return a||[]}}),{data:F=[]}=z({queryKey:["user-clinic-memberships"],queryFn:async()=>{const{data:a,error:i}=await Me.from("user_clinic_memberships").select("user_id, clinic_id");if(i)throw i;return a||[]}}),{data:q=[]}=Ie(),O=c.useMemo(()=>{const a=new Map;return F.forEach(i=>
1{a.has(i.clinic_id)||a.set(i.clinic_id,new Set),a.get(i.clinic_id).add(i.user_id)}),a},[F]),v=c.useMemo(()=>{let a=g;if(o&&o.length>0){const i=new Set(o);a=a.filter(b=>i.has(b.id))}if(p!=="all"){const i=O.get(p)??new Set;a=a.filter(b=>i.has(b.id))}return l&&(a=a.filter(i=>X(i.nome,l)||X(i.email,l))),a},[g,o,p,O,l]),C=(a,i)=>{const b=q.filter(f=>f.user_id===a&&f.weekday===i&&f.is_active);return u==="current"?b:b.filter(f=>f.week_parity==="all"||f.week_parity===u)},A=a=>a?a.slice(0,5):"";return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsxs("div",{className:"relative flex-1 min-w-[200px] max-w-sm",children:[e.jsx(ue,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(R,{value:l,onChange:a=>m(a.target.value),placeholder:"Pesquisar pessoaâ¦",className:"pl-9"})]}),e.jsxs(Z,{value:p,onValueChange:h,children:[e.jsxs(ee,{className:"w-[200px]",children:[e.jsx($e,{className:"h-4 w-4 mr-2 inline"}),e.jsx(se,{placeholder:"Local"})]}),e.jsxs(te,{children:[e.jsx($,{value:"all",children:"Todos os locais"}),w.map(a=>e.jsx($,{value:a.id,children:a.name},a.id))]})]}),e.jsxs(Z,{value:u,onValueChange:a=>j(a),children:[e.jsx(ee,{className:"w-[160px]",children:e.jsx(se,{})}),e.jsxs(te,{children:[e.jsx($,{value:"current",children:"Todas as semanas"}),e.jsx($,{value:"week_a",children:"Semana A"}),e.jsx($,{value:"week_b",children:"Semana B"})]})]}),e.jsxs("div",{className:"text-sm text-muted-foreground ml-auto flex items-center gap-1",children:[e.jsx(Ge,{className:"h-4 w-4"})," ",v.length," pessoa(s)"]})]}),e.jsx(K,{children:e.jsx(G,{className:"p-0 overflow-x-auto",children:e.jsxs("table",{className:"w-full border-collapse",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b bg-muted/30",children:[e.jsx("th",{className:"sticky left-0 bg-muted/30 text-left px-3 py-2 text-xs font-semibold text-muted-foreground min-w-[180px] border-r",children:"Colaborador"}),ze.map(a=>e.jsx("th",{className:"px-3 py-2 text-xs font-semibold text-muted-foreground text-center min-w-[140px] border-r last:border-r-0",children:Le[a]},a))]})}),e.jsxs("tbody",{children:[v.map(a=>e.jsxs("tr",{className:"border-b hover:bg-muted/20",children:[e.jsxs("td",{className:"sticky left-0 bg-background hover:bg-muted/20 px-3 py-2 border-r",children:[e.jsx("div",{className:"font-medium text-sm text-foreground",children:a.nome}),e.jsx("div",{className:"text-xs text-muted-foreground truncate max-w-[160px]",children:a.email})]}),ze.map(i=>{const b=C(a.id,i);return e.jsx("td",{className:"px-2 py-2 align-top border-r last:border-r-0",children:b.length===0?e.jsx("div",{className:"text-xs text-muted-foreground/40 text-center py-2",children:"â"}):e.jsx("div",{className:"space-y-1",children:b.map(f=>e.jsxs("div",{className:"rounded-md bg-primary/10 border border-primary/20 px-2 py-1 text-xs",title:f.week_parity!=="all"?`Semana ${f.week_parity==="week_a"?"A":"B"}`:void 0,children:[e.jsxs("div",{className:"font-medium text-primary",children:[A(f.start_time),"â",A(f.end_time)]}),f.lunch_start&&f.lunch_end&&e.jsxs("div",{className:"text-[10px] text-muted-foreground",children:["almoço ",A(f.lunch_start),"â",A(f.lunch_end)]}),f.week_parity!=="all"&&e.jsx(Y,{variant:"outline",className:"h-4 px-1 text-[9px] mt-0.5",children:f.week_parity==="week_a"?"Sem A":"Sem B"})]},f.id))})},i)})]},a.id)),v.length===0&&e.jsx("tr",{children:e.jsx("td",{colSpan:ze.length+1,className:"text-center text-sm text-muted-foreground py-8",children:"Sem colaboradores com os filtros atuais."})})]})]})})})]})}const qe=le(),Ee=[1,2,3,4,5],ie=15,Te="border-r-2 border-r-foreground/40";function ce(o){if(!o)return null;const[l,m]=o.split(":").map(Number);return l*60+(m||0)}function ts(o){const l=Math.floor(o/60),m=o%60;return`${String(l).padStart(2,"0")}:${String(m).padStart(2,"0")}`}function Ks({userIds:o}){const[l,m]=c.useState(""),[p,h]=c.useState("all"),[u,j]=c.useState("all"),{data:g=[]}=z({queryKey:["profiles-slot-grid"],queryFn:async()=>{const s=["super_user","administrativo","tecnico","comercial","medico","enfermeiro","externo"],[{data:t,error:d},{data:y,error:S}]=await Promise.all([qe.from("profiles").select("id, nome").eq("is_archived",!1).order("nome"),qe.from("user_roles").select("user_id").in("role",s)]);if(d)throw d;if(S)throw S;const _=new Set((y||[]).map(D=>
1D.user_id));return(t||[]).filter(D=>_.has(D.id))}}),{data:w=[]}=z({queryKey:["clinics-active-slot"],queryFn:async()=>{const{data:s,error:t}=await qe.from("clinics").select("id, name").eq("is_active",!0).order("name");if(t)throw t;return s||[]}}),{data:F=[]}=z({queryKey:["user-clinic-memberships-slot"],queryFn:async()=>{const{data:s,error:t}=await qe.from("user_clinic_memberships").select("user_id, clinic_id");if(t)throw t;return s||[]}}),{data:q=[]}=Ie(),O=c.useMemo(()=>{const s=new Map;return F.forEach(t=>{s.has(t.clinic_id)||s.set(t.clinic_id,new Set),s.get(t.clinic_id).add(t.user_id)}),s},[F]),v=c.useMemo(()=>{let s=g;if(o&&o.length>0){const t=new Set(o);s=s.filter(d=>t.has(d.id))}if(p!=="all"){const t=O.get(p)??new Set;s=s.filter(d=>t.has(d.id))}return l&&(s=s.filter(t=>X(t.nome,l))),s},[g,o,p,O,l]),C=s=>u==="all"?!0:s.week_parity==="all"||s.week_parity===u,{startMin:A,endMin:a}=c.useMemo(()=>{let s=1440,t=0;return q.forEach(d=>{if(!d.is_active||!C(d))return;const y=ce(d.start_time),S=ce(d.end_time);y!==null&&y<s&&(s=y),S!==null&&S>t&&(t=S)}),s>=t&&(s=8*60,t=20*60),s=Math.floor(s/ie)*ie,t=Math.ceil(t/ie)*ie,{startMin:s,endMin:t}},[q,u]),i=c.useMemo(()=>{const s=[];for(let t=A;t<a;t+=ie)s.push({start:t,end:t+ie});return s},[A,a]),b=(s,t,d,y)=>{const S=q.filter(_=>_.user_id===s&&_.weekday===t&&_.is_active&&C(_));for(const _ of S){const D=ce(_.start_time),P=ce(_.end_time);if(D===null||P===null||d<D||y>P)continue;const Q=ce(_.lunch_start),r=ce(_.lunch_end);if(!(Q!==null&&r!==null&&d>=Q&&y<=r))return!0}return!1},f=(s,t)=>{let d=0;return i.forEach(y=>{b(s,t,y.start,y.end)&&d++}),d*ie/60},n=s=>s===0?"â":s%1===0?`${s}`:s.toFixed(1);return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsxs("div",{className:"relative flex-1 min-w-[200px] max-w-sm",children:[e.jsx(ue,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(R,{value:l,onChange:s=>m(s.target.value),placeholder:"Pesquisar pessoaâ¦",className:"pl-9"})]}),e.jsxs(Z,{value:p,onValueChange:h,children:[e.jsxs(ee,{className:"w-[200px]",children:[e.jsx($e,{className:"h-4 w-4 mr-2 inline"}),e.jsx(se,{placeholder:"Local"})]}),e.jsxs(te,{children:[e.jsx($,{value:"all",children:"Todos os locais"}),w.map(s=>e.jsx($,{value:s.id,children:s.name},s.id))]})]}),e.jsxs(Z,{value:u,onValueChange:s=>j(s),children:[e.jsx(ee,{className:"w-[160px]",children:e.jsx(se,{})}),e.jsxs(te,{children:[e.jsx($,{value:"all",children:"Todas as semanas"}),e.jsx($,{value:"week_a",children:"Semana A"}),e.jsx($,{value:"week_b",children:"Semana B"})]})]}),e.jsxs("div",{className:"text-sm text-muted-foreground ml-auto flex items-center gap-1",children:[e.jsx(Ge,{className:"h-4 w-4"})," ",v.length," pessoa(s)"]})]}),e.jsx(K,{children:e.jsxs(G,{className:"p-0 overflow-x-auto",children:[e.jsxs("table",{className:"w-full border-collapse text-xs",children:[e.jsxs("thead",{children:[e.jsxs("tr",{className:"border-b bg-muted/40",children:[e.jsx("th",{className:"sticky left-0 bg-muted/40 px-2 py-2 border-r min-w-[60px] font-semibold text-muted-foreground",children:"InÃcio"}),e.jsx("th",{className:"px-2 py-2 border-r min-w-[60px] font-semibold text-muted-foreground",children:"Fim"}),Ee.map(s=>e.jsx("th",{colSpan:Math.max(1,v.length),className:`px-2 py-2 text-center font-semibold text-muted-foreground last:border-r-0 ${Te}`,children:Le[s]},s))]}),e.jsxs("tr",{className:"border-b bg-muted/20",children:[e.jsx("th",{className:"sticky left-0 bg-muted/20 px-2 py-1 border-r"}),e.jsx("th",{className:"px-2 py-1 border-r"}),Ee.map(s=>v.length===0?e.jsx("th",{className:"px-2 py-1 text-center text-muted-foreground border-r last:border-r-0",children:"â"},s):v.map((t,d)=>e.jsx("th",{className:`px-2 py-1 text-center text-[10px] font-medium text-muted-foreground ${d===v.length-1?Te:"border-r"}`,title:t.nome,children:t.nome.split(" ")[0]},`${s}-${t.id}`)))]})]}),e.jsxs("tbody",{children:[i.map(s=>e.jsxs("tr",{className:"border-b hover:bg-muted/10",children:[e.jsx("td",{className:"sticky left-0 bg-background px-2 py-1 border-r font-mono text-[11px] text-muted-foreground",children:ts(s.start)}),e.jsx("td",{className:"px-2 py-1 border-r font-mono text-[11px] text-muted-foreground",children:ts(s.end)}),Ee.map(t=>v.length===0?e.jsx("td",{className:"px-2 py-1 border-r last:border-r-0"},t):v.map((d,y)=>{const S=b(d.id,t,s.start,s.end);return e.jsx("td",{className:`px-2 py-1 text-center ${y===v.length-1?Te:"border-r"} ${S?"bg-primary/15 text-primary font-semibold":""}`},`${t}-${d.id}-${s.start}`)}))]},s.start)),e.jsxs("tr",{className:"border-t-2 bg-muted/30 font-semibold",children:[e.jsx("td",{className:"sticky left-0 bg-muted/30 px-2 py-2 border-r text-right",colSpan:2,children:"Total (h)"}),Ee.map(s=>v.length===0?e.jsx("td",{className:"px-2 py-2 text-center border-r last:border-r-0",children:"â"},s):v.map((t,d)=>e.jsx("td",{className:`px-2 py-2 text-center ${d===v.length-1?Te:"border-r"}`,children:n(f(t.id,s))},`tot-${s}-${t.id}`)))]})]})]}),v.length===0&&e.jsx("div",{className:"text-center text-sm text-muted-foreground py-8",children:"Sem colaboradores com os filtros atuais."})]})})]})}const he=le(),Gs={approved:"bg-emerald-500",pending:"bg-amber-400",change_requested:"bg-orange-400",rejected:"bg-muted-foreground
1/30"};function Ys(){const[o,l]=c.useState(()=>Oe(new Date)),[m,p]=c.useState(""),[h,u]=c.useState("all"),[j,g]=c.useState("approved_pending"),w=c.useMemo(()=>Oe(o),[o]),F=c.useMemo(()=>Fs(o),[o]),q=c.useMemo(()=>Fe({start:w,end:F}),[w,F]),O=c.useMemo(()=>ve(o.getFullYear()),[o]),v=s=>O.some(t=>is(t,s)),{data:C=[]}=z({queryKey:["profiles-vac-grid"],queryFn:async()=>{const s=["super_user","administrativo","tecnico","comercial","medico","enfermeiro","externo"],[{data:t,error:d},{data:y,error:S}]=await Promise.all([he.from("profiles").select("id, nome").eq("is_archived",!1).order("nome"),he.from("user_roles").select("user_id").in("role",s)]);if(d)throw d;if(S)throw S;const _=new Set((y||[]).map(D=>D.user_id));return(t||[]).filter(D=>_.has(D.id))}}),{data:A=[]}=z({queryKey:["clinics-active"],queryFn:async()=>{const{data:s,error:t}=await he.from("clinics").select("id, name").eq("is_active",!0).order("name");if(t)throw t;return s||[]}}),{data:a=[]}=z({queryKey:["user-clinic-memberships"],queryFn:async()=>{const{data:s,error:t}=await he.from("user_clinic_memberships").select("user_id, clinic_id");if(t)throw t;return s||[]}}),{data:i=[]}=z({queryKey:["vacations-month",H(w,"yyyy-MM")],queryFn:async()=>{const s=H(w,"yyyy-MM-dd"),t=H(F,"yyyy-MM-dd"),{data:d,error:y}=await he.from("vacation_requests").select("id, user_id, start_date, end_date, status").lte("start_date",t).gte("end_date",s);if(y)throw y;return d||[]}}),b=c.useMemo(()=>{const s=new Map;return a.forEach(t=>{s.has(t.clinic_id)||s.set(t.clinic_id,new Set),s.get(t.clinic_id).add(t.user_id)}),s},[a]),f=c.useMemo(()=>{let s=C;if(h!=="all"){const t=b.get(h)??new Set;s=s.filter(d=>t.has(d.id))}return m&&(s=s.filter(t=>X(t.nome,m))),s},[C,h,b,m]),n=c.useMemo(()=>{const s=new Map,t=new Set(j==="all"?["approved","pending","change_requested","rejected"]:j==="approved"?["approved"]:["approved","pending","change_requested"]);return i.forEach(d=>{if(!t.has(d.status))return;const y=Fe({start:W(d.start_date),end:W(d.end_date)});let S=s.get(d.user_id);S||(S=new Map,s.set(d.user_id,S)),y.forEach(_=>{const D=H(_,"yyyy-MM-dd");(!S.get(D)||d.status==="approved")&&S.set(D,d.status)})}),s},[i,j]);return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsxs("div",{className:"flex items-center gap-1 border rounded-md",children:[e.jsx(L,{variant:"ghost",size:"sm",onClick:()=>l(s=>Ls(s)),children:e.jsx(os,{className:"h-4 w-4"})}),e.jsx("div",{className:"px-3 text-sm font-medium min-w-[150px] text-center capitalize",children:H(o,"MMMM 'de' yyyy",{locale:Se})}),e.jsx(L,{variant:"ghost",size:"sm",onClick:()=>l(s=>$s(s,1)),children:e.jsx(cs,{className:"h-4 w-4"})}),e.jsx(L,{variant:"ghost",size:"sm",onClick:()=>l(Oe(new Date)),children:"Hoje"})]}),e.jsxs("div",{className:"relative flex-1 min-w-[180px] max-w-xs",children:[e.jsx(ue,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(R,{value:m,onChange:s=>p(s.target.value),placeholder:"Pesquisar pessoaâ¦",className:"pl-9"})]}),e.jsxs(Z,{value:h,onValueChange:u,children:[e.jsxs(ee,{className:"w-[180px]",children:[e.jsx($e,{className:"h-4 w-4 mr-2 inline"}),e.jsx(se,{})]}),e.jsxs(te,{children:[e.jsx($,{value:"all",children:"Todos os locais"}),A.map(s=>e.jsx($,{value:s.id,children:s.name},s.id))]})]}),e.jsxs(Z,{value:j,onValueChange:g,children:[e.jsx(ee,{className:"w-[180px]",children:e.jsx(se,{})}),e.jsxs(te,{children:[e.jsx($,{value:"approved_pending",children:"Aprovados + pendentes"}),e.jsx($,{value:"approved",children:"Só aprovados"}),e.jsx($,{value:"all",children:"Todos"})]})]}),e.jsxs("div",{className:"text-sm text-muted-foreground ml-auto flex items-center gap-3",children:[e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"w-3 h-3 rounded bg-emerald-500"})," Aprovado"]}),e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"w-3 h-3 rounded bg-amber-400"})," Pendente"]}),e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Ge,{className:"h-4 w-4"})," ",f.length]})]})]}),e.jsx(K,{children:e.jsx(G,{className:"p-0 overflow-x-auto",children:e.jsxs("table",{className:"border-collapse text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b bg-muted/30",children:[e.jsx("th",{className:"sticky left-0 z-10 bg-muted/30 text-left px-3 py-2 font-semibold text-muted-foreground min-w-[160px] border-r",children:"Colaborador"}),q.map(s=>{const t=_e(s),d=v(s);return e.jsxs("th",{className:`text-center font-medium border-r last:border-r-0 px-1 py-1 min-w-[28px] ${t||d?"bg-muted/50 text-muted-foreground":"text-foreground"}`,title:d?"Feriado":t?"Fim-de-semana":"",children:[e.jsx("div",{className:"text-[10px] uppercase",children:H(s,"EEEEE",{locale:Se})}),e.jsx("div",{children:H(s,"d")})]},s.toISOString())})]})}),e.jsxs("tbody",{children:[f.map(s=>{const t=n.get(s.id),d=t?Array.from(t.entries()).filter(([y,S])=>{const _=W(y);return S==="approved"&&!_e(_)&&!v(_)}).length:0;return e.jsxs("tr",{className:"border-b hover:bg-muted/10",children:[e.jsx("td",{className:"sticky left-0 z-10 bg-background hover:bg-muted/10 px-3 py-1.5 border-r",children:e.jsxs(Be,{to:`/ponto/colaboradores/${s.id}/ferias`,className:"block",children:[e.jsx("div",{className:"font-medium text-sm text-foreground hover:text-primary truncate max-w-[150px]",children:s.nome}),d>0&&e.jsxs(Y,{variant:"secondary",className:"h-4 px-1 text-[9px] mt-0.5",children:[d,"d"]})]})}),q.map(y=>{const S=H(y,"yyyy-MM-dd"),_=t?.get(S),D=_e(y),P=v(y);return e.jsx("td",{className:`border-r last:border-r-0 p-0.5 text-center ${D||P?"bg-muted/40":""}`,children:_?e.jsx("div",{className:`w-full h-5 rounded ${Gs[_]||"bg-muted"}`,title:`${H(y,"dd/MM/yyyy")} â ${_==="approved"?"Aprovado":_==="pending"?"Pendente":_==="change_requested"?"Alteração pedida":"Rejeitado"}`}):e.jsx("div",{className:"w-full h-5"})},S)})]},s.id)}),f.length===0&&e.jsx("tr",{children:e.jsx("td",{colSpan:q.length+1,className:"text-center text-sm text-muted-foreground py-8",children:"Sem colaboradores com os filtros atuais."})})]})]})})})]})}const pe=le(),Ws=["Janeiro","Fevereiro","Março","Abril","Maio","Junho","Julho","Agosto","Setembro","Outubro","Novembro","Dezembro"],as=22;function Qs({userIds:o}){const[l,m]=c.useState(""),[p,h]=c.useState("all"),[u,j]=c.useState(new Date().getFullYear()),{data:g=[]}=z({queryKey:["profiles-vac-summary"],queryFn:async()=>{const n=["super_user","administrativo","tecnico","comercial","medico","enfermeiro","externo"],[{data:s,error:t},{data:d,error:y}]=await Promise.all([pe.from("profiles").select("id, nome").eq("is_archived",!1).order("nome"),pe.from("user_roles").select("user_id").in("role",n)]);if(t)throw t;if(y)throw y;const S=new Set((d||[]).map(_=>_.user_id));return(s||[]).filter(_=>S.has(_.id))}}),{data:w=[]}=z({queryKey:["clinics-active-vac-summary"],queryFn:async()=>{const{data:n,error:s}=await pe.from("clinics").select("id, name").eq("is_active",!0).order("name");if(s)throw s;return n||[]}}),{data:F=[]}=z({queryKey:["user-clinic-memberships-vac-summary"],queryFn:async()=>{const{data:n,error:s}=await pe.from("user_clinic_memberships").select("user_id, clinic_id");if(s)throw s;return n||[]}}),{data:q=[]}=z({queryKey:["vacation-year",u],queryFn:async()=>{const{data:n,error:s}=await pe.from("vacation_requests").select("id, user_id, start_date, end_date, status").gte("start_date",`${u-1}-12-15`).lte("end_date",`${u+1}-01-15`);if(s)throw s;return n||[]}}),O=c.useMemo(()=>new Set(ve(u).map(n=>n.toISOString().slice(0,10))),[u]),v=c.useMemo(()=>{const n=new Map;return F.forEach(s=>
1{n.has(s.clinic_id)||n.set(s.clinic_id,new Set),n.get(s.clinic_id).add(s.user_id)}),n},[F]),C=c.useMemo(()=>{let n=g;if(o&&o.length>0){const s=new Set(o);n=n.filter(t=>s.has(t.id))}if(p!=="all"){const s=v.get(p)??new Set;n=n.filter(t=>s.has(t.id))}return l&&(n=n.filter(s=>X(s.nome,l))),n},[g,o,p,v,l]),A=c.useMemo(()=>{const n=new Map;return C.forEach(s=>n.set(s.id,Array(12).fill(0))),q.filter(s=>s.status==="approved").forEach(s=>{const t=n.get(s.user_id);if(!t)return;Fe({start:W(s.start_date),end:W(s.end_date)}).forEach(y=>{y.getFullYear()===u&&(_e(y)||O.has(y.toISOString().slice(0,10))||t[y.getMonth()]++)})}),n},[C,q,u,O]),a=n=>C.reduce((s,t)=>s+(A.get(t.id)?.[n]??0),0),i=n=>(A.get(n)??[]).reduce((s,t)=>s+t,0),b=C.reduce((n,s)=>n+i(s.id),0),f=n=>n===0?"text-muted-foreground/50":n>=10?"bg-primary/30 font-bold text-primary":n>=5?"bg-primary/20 font-semibold text-primary":"bg-primary/10 text-primary font-medium";return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(L,{variant:"outline",size:"icon",onClick:()=>j(n=>n-1),"aria-label":"Anterior",children:e.jsx(os,{className:"h-4 w-4"})}),e.jsx("div",{className:"px-3 font-semibold text-lg w-20 text-center",children:u}),e.jsx(L,{variant:"outline",size:"icon",onClick:()=>j(n=>n+1),"aria-label":"Seguinte",children:e.jsx(cs,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"relative flex-1 min-w-[200px] max-w-sm",children:[e.jsx(ue,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(R,{value:l,onChange:n=>m(n.target.value),placeholder:"Pesquisar pessoaâ¦",className:"pl-9"})]}),e.jsxs(Z,{value:p,onValueChange:h,children:[e.jsxs(ee,{className:"w-[200px]",children:[e.jsx($e,{className:"h-4 w-4 mr-2 inline"}),e.jsx(se,{placeholder:"Local"})]}),e.jsxs(te,{children:[e.jsx($,{value:"all",children:"Todos os locais"}),w.map(n=>e.jsx($,{value:n.id,children:n.name},n.id))]})]})]}),e.jsx(K,{children:e.jsxs(G,{className:"p-0 overflow-x-auto",children:[e.jsxs("table",{className:"w-full border-collapse text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b bg-muted/40",children:[e.jsx("th",{className:"sticky left-0 bg-muted/40 px-3 py-2 text-left font-semibold text-muted-foreground border-r min-w-[120px]",children:"Mês"}),C.map(n=>e.jsx("th",{className:"px-3 py-2 text-center font-semibold text-muted-foreground border-r last:border-r-0 min-w-[80px]",children:n.nome.split(" ")[0]},n.id)),e.jsx("th",{className:"px-3 py-2 text-center font-semibold text-muted-foreground bg-primary/10 min-w-[100px]",children:"TOTAL MÃS"})]})}),e.jsxs("tbody",{children:[Ws.map((n,s)=>e.jsxs("tr",{className:"border-b hover:bg-muted/10",children:[e.jsx("td",{className:"sticky left-0 bg-background px-3 py-2 border-r font-medium",children:n}),C.map(t=>{const d=A.get(t.id)?.[s]??0;return e.jsx("td",{className:`px-3 py-2 text-center border-r last:border-r-0 ${f(d)}`,children:d||"â"},t.id)}),e.jsx("td",{className:"px-3 py-2 text-center bg-primary/5 font-semibold",children:a(s)||"â"})]},n)),e.jsxs("tr",{className:"border-t-2 bg-muted/40 font-bold",children:[e.jsx("td",{className:"sticky left-0 bg-muted/40 px-3 py-2 border-r",children:"TOTAL ANUAL"}),C.map(n=>e.jsx("td",{className:"px-3 py-2 text-center border-r last:border-r-0",children:i(n.id)||"â"},n.id)),e.jsx("td",{className:"px-3 py-2 text-center bg-primary/20 text-primary",children:b||"â"})]}),e.jsxs("tr",{className:"bg-muted/20 text-xs text-muted-foreground",children:[e.jsxs("td",{className:"sticky left-0 bg-muted/20 px-3 py-1 border-r",children:["Saldo anual (",as,"d)"]}),C.map(n=>{const s=i(n.id),t=as-s;return e.jsx("td",{className:`px-3 py-1 text-center border-r last:border-r-0 ${t<0?"text-destructive font-semibold":""}`,children:t>=0?`${t}`:t},n.id)}),e.jsx("td",{className:"px-3 py-1 text-center bg-muted/30",children:"â"})]})]})]}),C.length===0&&e.jsx("div",{className:"text-center text-sm text-muted-foreground py-8",children:"Sem colaboradores com os filtros atuais."})]})})]})}const Ue=le();function Js(o){return z({queryKey:["team-vacations",o],queryFn:async()=>{const l=`${o}-01-01`,m=`${o}-12-31`,{data:p,error:h}=await Ue.from("vacation_requests").select("id, user_id, start_date, end_date, status, reason").gte("start_date",l).lte("start_date",m).order("start_date",{ascending:!1});if(h)throw h;return p||[]}})}function Xs(){return z({queryKey:["team-profiles-vacations"],queryFn:async()=>{const o=["super_user","administrativo","tecnico","comercial","medico","enfermeiro","externo"],[{data:l,error:m},{data:p,error:h}]=await Promise.all([Ue.from("profiles").select("id, nome, email").eq("is_archived",!1).order("nome"),Ue.from("user_roles").select("user_id").in("role",o)]);if(m)throw m;if(h)throw h;const u=new Set((p||[]).map(j=>
1j.user_id));return(l||[]).filter(j=>u.has(j.id))}})}function Zs(){const o=new Date().getFullYear(),[l,m]=c.useState(o),[p,h]=c.useState(""),{data:u=[],isLoading:j}=Js(l),{data:g=[]}=Xs(),w=c.useMemo(()=>[...ve(l-1),...ve(l),...ve(l+1)],[l]),F=a=>w.some(i=>is(i,a)),q=(a,i)=>Fe({start:a,end:i}).filter(f=>!_e(f)&&!F(f)).length,O=c.useMemo(()=>{const a=new Map;return g.forEach(i=>a.set(i.id,{approved:0,pending:0,rows:[]})),u.forEach(i=>{const b=a.get(i.user_id)||{approved:0,pending:0,rows:[]};b.rows.push(i);const f=q(W(i.start_date),W(i.end_date));i.status==="approved"?b.approved+=f:(i.status==="pending"||i.status==="change_requested")&&(b.pending+=f),a.set(i.user_id,b)}),a},[g,u,w]),v=g.filter(a=>!p||X(a.nome,p)||X(a.email,p)),C=u.filter(a=>a.status==="pending"||a.status==="change_requested"),A=a=>g.find(i=>i.id===a)?.nome||"â";return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[e.jsxs("div",{className:"relative w-full md:w-72",children:[e.jsx(ue,{className:"pointer-events-none absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(R,{value:p,onChange:a=>h(a.target.value),placeholder:"Pesquisar colaboradorâ¦",className:"pl-9"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Ano:"}),e.jsx(R,{type:"number",value:l,onChange:a=>m(parseInt(a.target.value)||o),className:"w-24 h-9"})]})]}),e.jsxs(Ne,{defaultValue:"year",children:[e.jsxs(we,{children:[e.jsxs(V,{value:"year",children:[e.jsx(Rs,{className:"w-4 h-4 mr-1"})," Resumo anual"]}),e.jsxs(V,{value:"month",children:[e.jsx(ds,{className:"w-4 h-4 mr-1"})," Vista mensal"]}),e.jsxs(V,{value:"overview",children:[e.jsx(Ke,{className:"w-4 h-4 mr-1"})," Visão geral"]}),e.jsxs(V,{value:"pending",children:["Pendentes",C.length>0&&e.jsx(Y,{variant:"destructive",className:"ml-1 text-xs",children:C.length})]})]}),e.jsx(I,{value:"year",className:"mt-4",children:e.jsx(Qs,{})}),e.jsx(I,{value:"month",className:"mt-4",children:e.jsx(Ys,{})}),e.jsx(I,{value:"overview",className:"mt-4",children:e.jsx(K,{children:e.jsx(G,{className:"p-0",children:j?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(be,{className:"w-5 h-5 animate-spin text-muted-foreground"})}):e.jsxs(fe,{children:[e.jsx(je,{children:e.jsxs(U,{children:[e.jsx(E,{children:"Colaborador"}),e.jsx(E,{className:"text-center",children:"Aprovados (dias úteis)"}),e.jsx(E,{className:"text-center",children:"Pendentes"}),e.jsx(E,{className:"text-center",children:"Pedidos"}),e.jsx(E,{className:"text-right",children:"Ações"})]})}),e.jsxs(ge,{children:[v.map(a=>{const i=O.get(a.id)||{approved:0,pending:0,rows:[]};return e.jsxs(U,{children:[e.jsxs(k,{children:[e.jsx("div",{className:"font-medium text-foreground",children:a.nome}),e.jsx("div",{className:"text-xs text-muted-foreground",children:a.email})]}),e.jsx(k,{className:"text-center",children:e.jsxs(Y,{variant:i.approved>0?"default":"secondary",className:"text-xs",children:[i.approved,"d"]})}),e.jsx(k,{className:"text-center",children:i.pending>0?e.jsxs(Y,{variant:"destructive",className:"text-xs",children:[i.pending,"d"]}):e.jsx("span",{className:"text-xs text-muted-foreground",children:"â"})}),e.jsx(k,{className:"text-center text-sm text-muted-foreground",children:i.rows.length}),e.jsx(k,{className:"text-right",children:e.jsx(L,{asChild:!0,variant:"outline",size:"sm",children:e.jsxs(Be,{to:`/ponto/colaboradores/${a.id}/ferias`,children:["Detalhes ",e.jsx(zs,{className:"w-3 h-3 ml-1"})]})})})]},a.id)}),v.length===0&&e.jsx(U,{children:e.jsx(k,{colSpan:5,className:"text-center text-muted-foreground py-6",children:"Sem colaboradores."})})]})]})})})}),e.jsx(I,{value:"pending",className:"mt-4",children:e.jsx(K,{children:e.jsx(G,{className:"p-0",children:e.jsxs(fe,{children:[e.jsx(je,{children:e.jsxs(U,{children:[e.jsx(E,{children:"Colaborador"}),e.jsx(E,{children:"PerÃodo"}),e.jsx(E,{children:"Dias úteis"}),e.jsx(E,{children:"Motivo"}),e.jsx(E,{children:"Estado"}),e.jsx(E,{className:"text-right",children:"Ações"})]})}),e.jsxs(ge,{children:[C.map(a=>{const i=q(W(a.start_date),W(a.end_date));return e.jsxs(U,{children:[e.jsx(k,{className:"font-medium",children:A(a.user_id
1)}),e.jsxs(k,{className:"text-sm",children:[H(W(a.start_date),"dd MMM",{locale:Se})," â ",H(W(a.end_date),"dd MMM yyyy",{locale:Se})]}),e.jsx(k,{children:e.jsxs(Y,{variant:"secondary",className:"text-xs",children:[i,"d"]})}),e.jsx(k,{className:"text-xs text-muted-foreground max-w-xs truncate",children:a.reason||"â"}),e.jsx(k,{children:e.jsx(Y,{variant:a.status==="change_requested"?"outline":"destructive",className:"text-xs",children:a.status==="change_requested"?"Alteração pedida":"Pendente"})}),e.jsx(k,{className:"text-right",children:e.jsx(L,{asChild:!0,variant:"outline",size:"sm",children:e.jsx(Be,{to:`/ponto/colaboradores/${a.user_id}/ferias`,children:"Decidir"})})})]},a.id)}),C.length===0&&e.jsx(U,{children:e.jsx(k,{colSpan:6,className:"text-center text-muted-foreground py-6",children:"Sem pedidos pendentes ð"})})]})]})})})})]})]})}const Ve=le();function et(){return z({queryKey:["profiles-schedules"],queryFn:async()=>{const o=["super_user","administrativo","tecnico","comercial","medico","enfermeiro","externo"],[{data:l,error:m},{data:p,error:h}]=await Promise.all([Ve.from("profiles").select("id, nome, email, employment_type, allow_outside_ip, allow_outside_radius").eq("is_archived",!1).order("nome"),Ve.from("user_roles").select("user_id, role").in("role",o)]);if(m)throw m;if(h)throw h;const u=new Map;return(p||[]).forEach(j=>{u.has(j.user_id)||u.set(j.user_id,new Set),u.get(j.user_id).add(j.role)}),(l||[]).filter(j=>u.has(j.id)).map(j=>({...j,is_super:u.get(j.id).has("super_user")}))}})}function rs({userId:o}){const{data:l=0}=Es(o);return e.jsxs(Y,{variant:l>0?"default":l<0?"destructive":"secondary",className:"text-xs",children:[l>0?"+":"",l,"h"]})}function ha(){const{isSuperUser:o}=ys(),{data:l=[]}=et(),m=Os(),{data:p=[]}=Ie(),{data:h=[]}=Cs(),u=Ms(),[j,g]=c.useState(""),[w,F]=c.useState(null),[q,O]=c.useState(null),[v,C]=c.useState(""),[A,a]=c.useState("all"),[i,b]=c.useState(null),[f,n]=c.useState(!0),s=c.useMemo(()=>f?l.filter(r=>!r.is_super):l,[l,f]),t=c.useMemo(()=>f?s.map(r=>r.id):void 0,[f,s]),d=async(r,B,ae)=>{m.setQueryData(["profiles-schedules"],re=>(re||[]).map(xe=>xe.id===r?{...xe,[B]:ae}:xe));const{error:J}=await Ve.from("profiles").update({[B]:ae}).eq("id",r);J?(me.error("Erro ao guardar exceção"),m.invalidateQueries({queryKey:["profiles-schedules"]})):me.success("Exceção atualizada")};if(!o())return e.jsx(Ye,{children:e.jsx("div",{className:"p-8",children:e.jsx(K,{children:e.jsx(G,{className:"p-6 text-muted-foreground",children:"Sem permissão."})})})});const y=s.filter(r=>!j||X(r.nome,j)||X(r.email,j)),S=r=>{const B=p.filter(re=>re.user_id===r&&re.is_active);if(!B.length)return"â";const ae=B.map(re=>Le[re.weekday].slice(0,3)).join(", "),J=B[0];return`${J.start_time?.slice(0,5)}â${J.end_time?.slice(0,5)} (${ae})`},_=h.filter(r=>r.status==="pending"),D=r=>l.find(B=>B.id===r)?.nome||r,P=A==="all"?h:h.filter(r=>r.user_id===A),Q=async r=>{q&&(await u.mutateAsync({id:q.id,status:r,decision_reason:v||void 0}),O(null),C(""))};return e.jsx(Ye,{children:e.jsxs("div",{className:"p-8 space-y-6",children:[e.jsxs("header",{children:[e.jsx("h1",{className:"text-3xl font-bold text-foreground",children:"Equipa â Horários, Férias & Saldos"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Gestão centralizada de horários, férias, horas extra e saldos da equipa."})]}),e.jsxs(Ne,{defaultValue:"schedules",children:[e.jsxs(we,{children:[e.jsxs(V,{value:"schedules",children:[e.jsx(ls,{className:"w-4 h-4 mr-1"})," Horários"]}),e.jsxs(V,{value:"vacations",children:[e.jsx(Hs,{className:"w-4 h-4 mr-1"})," Férias da equipa"]}),e.jsxs(V,{value:"overtime",children:[e.jsx(Ke,{className:"w-4 h-4 mr-1"})," Horas Extra",_.length>0&&e.jsx(Y,{variant:"destructive",className:"ml-1 text-xs",children:_.length})]})]}),e.jsx(I,{value:"vacations",className:"mt-4",children:e.jsx(Zs,{})}),e.jsxs(I,{value:"schedules",className:"space-y-4 mt-4",children:[e.jsx(Vs,{}),e.jsxs("div",{className:"flex items-center gap-2 justify-end",children:[e.jsx(ye,{id:"hide-super-users",checked:f,onCheckedChange:n}),e.jsx(Ae,{htmlFor:"hide-super-users",className:"text-sm text-muted-foreground cursor-pointer",children:"Ignorar super users (gestão, sem horário)"})]}),e.jsxs(Ne,{defaultValue:"slots",children:[e.jsxs(we,{children:[e.jsxs(V,{value:"slots",children:[e.jsx(js,{className:"w-4 h-4 mr-1"})," Grelha por slots"]}),e.jsxs(V,{value:"grid",children:[e.jsx(ds,{className:"w-4 h-4 mr-1"})," Grelha semanal"]}),e.jsxs(V,{value:"list",children:[e.jsx(Bs,{className:"w-4 h-4 mr-1"})," Lista"]})]}),e.jsx(I,{value:"slots",className:"mt-4",children:e.jsx(Ks,{userIds:t})}),e.jsx(I,{value:"grid",className:"mt-4",children:e.jsx(Is,{userIds:t})}),e.jsxs(I,{value:"list",className:"mt-4 space-y-4",children:[e.jsxs("div",{className:"relative w-full md:w-72",children:[e.jsx(ue,{className:"pointer-events-none absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(R,{value:j,onChange:r=>g(r.target.value),placeholder:"Pesquisarâ¦",className:"pl-9"})]}),e.jsx(K,{children:e.jsx(G,{className:"p-0",children:e.jsxs(fe,{children:[e.jsx(je,{children:e.jsxs(U,{children:[e.jsx(E,{children:"Colaborador"}),e.jsx(E,{children:"Tipo"}),e.jsx(E,{children:"Horário"}),e.jsx(E,{children:"Saldo"}),e.jsx(E,{className:"text-center",title:"Permitir picar fora do IP autorizado",children:"Fora IP"}),e.jsx(E,{className:"text-center",title:"Permitir picar fora do raio de 50m",children:"Fora raio"}),e.jsx(E,{className:"text-right",children:"Ações"})]})}),e.jsx(ge,{children:y.map(r=>e.jsxs(U,{children:[e.jsxs(k,{children:[e.jsx("div",{className:"font-medium text-foreground",children:r.nome}),e.jsx("div",{className:"text-xs text-muted-foreground",children:r.email})]}),e.jsx(k,{children:e.jsx(Y,{variant:r.employment_type==="full_time"?"default":"secondary",className:"text-xs",children:r.employment_type==="full_time"?"Full-time":"Part-time"})}),e.jsx(k,{className:"text-sm text-muted-foreground",children:S(r.id)}),e.jsx(k,{children:e.jsx(rs,{userId:r.id})}),e.jsx(k,{className:"text-center",children:e.jsx(ye,{checked:!!r.allow_outside_ip,onCheckedChange:B=>d(r.id,"allow_outside_ip",B)})}),e.jsx(k,{className:"text-center",children:e.jsx(ye,{checked:!!r.allow_outside_radius,onCheckedChange:B=>d(r.id,"allow_outside_radius",B)})}),e.jsx(k,{className:"text-right",children:e.jsx(L,{variant:"outline",size:"sm",onClick:()=>F(r.id),children:"Editar Horário"})})]},r.id))})]})})})]})]}),e.jsx(We,{open:!!w,onOpenChange:r=>!r&&F(null),children:e.jsxs(Qe,{className:"max-w-2xl max-h-[80vh] overflow-y-auto",children:[e.jsx(Je,{children:e.jsxs(Xe,{children:["Editar Horário â ",w?D(w):""]})}),w&&e.jsx(Us,{userId:w})]})})]}
1),e.jsxs(I,{value:"overtime",className:"space-y-4 mt-4",children:[e.jsxs(K,{children:[e.jsx(De,{children:e.jsx(Pe,{className:"text-base",children:"Panorama de Saldos"})}),e.jsx(G,{className:"p-0",children:e.jsxs(fe,{children:[e.jsx(je,{children:e.jsxs(U,{children:[e.jsx(E,{children:"Colaborador"}),e.jsx(E,{children:"Saldo atual"}),e.jsx(E,{className:"text-right",children:"Ações"})]})}),e.jsxs(ge,{children:[l.map(r=>e.jsxs(U,{children:[e.jsx(k,{children:e.jsx("div",{className:"font-medium text-foreground text-sm",children:r.nome})}),e.jsx(k,{children:e.jsx(rs,{userId:r.id})}),e.jsxs(k,{className:"text-right space-x-2",children:[e.jsxs(L,{variant:"outline",size:"sm",onClick:()=>b(r.id),children:[e.jsx(ns,{className:"w-3.5 h-3.5 mr-1"}),"Novo lançamento"]}),e.jsx(L,{variant:"outline",size:"sm",onClick:()=>a(r.id),children:"Ver histórico"})]})]},r.id)),l.length===0&&e.jsx(U,{children:e.jsx(k,{colSpan:3,className:"text-center text-muted-foreground",children:"Sem colaboradores."})})]})]})})]}),_.length>0&&e.jsxs(K,{children:[e.jsx(De,{children:e.jsx(Pe,{className:"text-base",children:"Pedidos Pendentes"})}),e.jsx(G,{className:"space-y-3",children:_.map(r=>e.jsxs("div",{className:"flex items-center justify-between gap-3 p-3 rounded-lg border border-border",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-sm text-foreground",children:D(r.user_id)}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[r.request_type==="overtime"?"Horas Extra":"Gozar Horas",": ",r.hours_amount,"h â ",H(new Date(r.date_from),"dd/MM/yyyy")," a ",H(new Date(r.date_to),"dd/MM/yyyy")]}),r.reason&&e.jsx("div",{className:"text-xs text-muted-foreground mt-1",children:r.reason})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(L,{size:"sm",variant:"outline",className:"text-emerald-600",onClick:()=>O(r),children:e.jsx(es,{className:"w-4 h-4"})}),e.jsx(L,{size:"sm",variant:"outline",className:"text-destructive",onClick:()=>{O(r)},children:e.jsx(ss,{className:"w-4 h-4"})})]})]},r.id))})]}),e.jsxs(K,{children:[e.jsxs(De,{className:"flex flex-row items-center justify-between gap-3 space-y-0",children:[e.jsx(Pe,{className:"text-base",children:"Histórico"}),e.jsxs(Z,{value:A,onValueChange:a,children:[e.jsx(ee,{className:"w-[220px]",children:e.jsx(se,{placeholder:"Todos os colaboradores"})}),e.jsxs(te,{children:[e.jsx($,{value:"all",children:"Todos os colaboradores"}),l.map(r=>e.jsx($,{value:r.id,children:r.nome},r.id))]})]})]}),e.jsx(G,{children:e.jsxs(fe,{children:[e.jsx(je,{children:e.jsxs(U,{children:[e.jsx(E,{children:"Colaborador"}),e.jsx(E,{children:"Tipo"}),e.jsx(E,{children:"Horas"}),e.jsx(E,{children:"PerÃodo"}),e.jsx(E,{children:"Estado"})]})}),e.jsxs(ge,{children:[P.map(r=>e.jsxs(U,{children:[e.jsxs(k,{className:"text-sm",children:[D(r.user_id),r.created_by&&e.jsxs("div",{className:"text-[10px] text-muted-foreground",children:["registado por ",D(r.created_by)]})]}),e.jsx(k,{children:e.jsx(Y,{variant:"outline",className:"text-xs",children:r.request_type==="overtime"?"Extra":"Gozar"})}),e.jsxs(k,{className:"text-sm",children:[r.hours_amount,"h"]}),e.jsxs(k,{className:"text-xs text-muted-foreground",children:[H(new Date(r.date_from),"dd/MM"),"â",H(new Date(r.date_to),"dd/MM/yyyy")]}),e.jsx(k,{children:e.jsx(Y,{variant:r.status==="approved"?"default":r.status==="rejected"?"destructive":"secondary",className:"text-xs",children:r.status==="approved"?"Aprovado":r.status==="rejected"?"Rejeitado":"Pendente"})})]},r.id)),P.length===0&&e.jsx(U,{children:e.jsx(k,{colSpan:5,className:"text-center text-muted-foreground",children:"Sem pedidos."})})]})]})})]}),e.jsx(We,{open:!!q,onOpenChange:r=>{r||(O(null),C(""))},children:e.jsxs(Qe,{children:[e.jsx(Je,{children:e.jsx(Xe,{children:"Decidir Pedido"})}),q&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("p",{className:"text-sm",children:[e.jsx("strong",{children:D(q.user_id)})," â ",q.request_type==="overtime"?"Horas Extra":"Gozar Horas",": ",q.hours_amount,"h"]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Motivo (opcional)"}
1),e.jsx(R,{value:v,onChange:r=>C(r.target.value)})]})]}),e.jsxs(gs,{className:"gap-2",children:[e.jsxs(L,{variant:"outline",onClick:()=>Q("rejected"),disabled:u.isPending,children:[e.jsx(ss,{className:"w-4 h-4 mr-1"})," Rejeitar"]}),e.jsxs(L,{onClick:()=>Q("approved"),disabled:u.isPending,children:[u.isPending&&e.jsx(be,{className:"w-4 h-4 animate-spin mr-1"}),e.jsx(es,{className:"w-4 h-4 mr-1"})," Aprovar"]})]})]})}),e.jsx(qs,{open:!!i,onOpenChange:r=>!r&&b(null),onBehalfOfUserId:i||void 0})]})]})]})})}export{ha as default};
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.