1import{r as i,j as e,a9 as Z,u as _}from"./vendor-BlB_7aU1.js";import{Q as J,a8 as k,ah as T,ai as L,ak as F,a9 as A,C as W,E as X,F as ee,G as se,H as te,B as N,af as g,ag as D,O as re}from"./index-CBfKlGil.js";import{n as V}from"./nutritionClient-CUjCp0WO.js";import{r as ae}from"./readNutritionLinkedPatients-CcW07E-Z.js";const ne=200,oe=5e3;async function ie(t,x,d){const a=[],h=new Set;let n=null;for(;n===null||a.length<n;){const u=a.length,c=await V.from("nutrition_assessment_entries").select("*",{count:"exact"}).eq("patient_id",t).eq("professional_id",x).order("created_at",{ascending:!1}).order("id",{ascending:!1}).range(u,u+ne-1).abortSignal(d);if(c.error)throw c.error;if(c.count===null||c.data===null)throw new Error("nutrition_assessment_incomplete");if(n!==null&&c.count!==n)throw new Error("nutrition_assessment_changed");if(n=c.count,c.data.length===0&&a.length<n)throw new Error("nutrition_assessment_incomplete");for(const m of c.data){if(h.has(m.id))throw new Error("nutrition_assessment_changed");h.add(m.id),a.push(m)}if(a.length>n)throw new Error("nutrition_assessment_changed")}return a}
1async function ce(t,x){const d=new AbortController;let a;try{return await Promise.race([ie(t,x,d.signal),new Promise((h,n)=>{a=setTimeout(()=>{d.abort(),n(new Error("nutrition_assessment_timeout"))},oe)})])}finally{clearTimeout(a)}}const K={patient_report:"Relato do paciente",caregiver_report:"Relato do responsável",professional_observation:"Observação da nutricionista",document:"Documento informado",other:"Outra origem"};function le(t){return`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}-${String(t.getDate()).padStart(2,"0")}`}function w(){return{category:"",label:"",valueText:"",observedOn:le(new Date),sourceKind:"",sourceDetail:"",supersedesId:null}}function U(t){const[x,d,a]=t.split("-");return`${a}/${d}/${x}`}function he(){const{user:t}=J(),[x,d]=i.useState([]),[a,h]=i.useState(""),n=i.useRef(""),u=i.useRef(0),[c,m]=i.useState([]),[r,l]=i.useState(w),[f,C]=i.useState(!0),[E,O]=i.useState(!1),[v,S]=i.useState(!1),[p,j]=i.useState(!1),[R,q]=i.useState(!1),[$,B]=i.useState(0);i.useEffect(()=>{const s=()=>{++u.current,m([]),C(!0),B(o=>o+1)};return window.addEventListener("focus",s),()=>window.removeEventListener("focus",s)},[]),i.useEffect(()=>{function s(){++u.current,n.current="",h(""),m([]),l(w()),S(!1),j(!1)}if(!(t!=null&&t.id)){d([]),O(!1),s(),C(!1);return}let o=!0;return(async()=>{C(!0),O(!1);try{const b=await ae(t.id);if(!o)return;d(b),n.current&&!b.some(I=>I.id===n.current)&&s()}catch{if(!o)return;d([]),s(),O(!0)}finally{o&&C(!1)}})(),()=>{o=!1}},[t==null?void 0:t.id,$]);const y=i.useCallback(async()=>{if(!(t!=null&&t.id)||!a)return;const s=++u.current;S(!0),j(!1),m([]);try{const o=await ce(a,t.id);if(n.current!==a||u.current!==s)return;m(o),j(!1)}catch{if(n.current!==a||u.current!==s)return;m([]),j(!0)}finally{n.current===a&&u.current===s&&S(!1)}},[a,t==null?void 0:t.id]);i.useEffect(()=>{y()},[y,$]);const z=new Set(c.map(s=>s.supersedes_id).filter(Boolean)),M=c.filter(s=>!z.has(s.id)),P=c.filter(s=>z.has(s.id));function G(s){++u.current,n.current=s,h(s),m([]),S(!0),l(w()),j(!1)}function Q(s){var o;l({category:s.category,label:s.label,valueText:s.value_text,observedOn:s.observed_on,sourceKind:s.source_kind,sourceDetail:s.source_detail||"",supersedesId:s.id}),(o=document.getElementById("nutrition-assessment-category"))==null||o.focus()}async function Y(){if(!(t!=null&&t.id)||!a||n.current!==a||f||E||v||p)return;const s=r.category.trim(),o=r.label.trim(),b=r.valueText.trim(),I=r.sourceDetail.trim();if(!s||!o||!b||!r.observedOn){_.error("Preencha categoria, informação, valor e data observada.");return}if(!r.sourceKind){_.error("Selecione a origem da informação.");return}if((r.sourceKind==="document"||r.sourceKind==="other")&&!I){_.error("Descreva a origem do documento ou da informação.");return}q(!0);try{const H=await V.from("nutrition_assessment_entries").insert({patient_id:a,professional_id:t.id,category:s,label:o,value_text:b,observed_on:r.observedOn,source_kind:r.sourceKind,source_detail:I||null,supersedes_id:r.supersedesId});if(H.error)throw H.error;if(n.current!==a)return;l(w()),_.success(r.supersedesId?"Correção registrada sem apagar o histórico.":"Informação registrada."),await y()}catch{n.current===a&&_.error("Não foi possÃvel salvar. Confira o vÃnculo e os campos preenchidos.")}finally{q(!1)}}return e.jsxs("div",{className:"mx-auto max-w-5xl space-y-6 p-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"rounded-full bg-green-100 p-2 text-green-700",children:e.jsx(Z,{className:"h-5 w-5","aria-hidden":!0})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-semibold",children:"Avaliação nutricional"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Registre o contexto que fizer sentido para cada paciente."})]})]}),e.jsxs(k,{children:[e.jsxs(T,{children:[e.jsx(L,{children:"Paciente"}),e.jsx(F,{children:"Somente vÃnculos profissionais ativos e válidos."})]}),e.jsxs(A,{children:[e.jsxs(W,{value:a,disabled:R||f||E,onValueChange:G,children:[e.jsx(X,{"aria-label":"Selecionar paciente",children:e.jsx(ee,{placeholder:f?"Carregandoâ¦":"Selecionar paciente"})}),e.jsx(se,{children:x.map(s=>e.jsx(te,{value:s.id,children:s.name},s.id))})]}),E&&e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsx("p",{role:"alert",className:"text-sm text-destructive",children:"Não foi possÃvel carregar os pacientes vinculados."}),e.jsx(N,{type:"button",size:"sm",variant:"outline",onClick:()=>B(s=>s+1),children:"Tentar novamente"})]}),!f&&!E&&x.length===0&&e.jsx("p",{className:"mt-3 text-sm text-muted-foreground",children:"Nenhum paciente com vÃnculo ativo."})]})]}),a&&e.jsxs(e.Fragment,{children:[e.jsxs(k,{children:[e.jsxs(T,{children:[e.jsx(L,{children:r.supersedesId?"Corrigir informação":"Nova informação"}),e.jsx(F,{children:"Use categorias livres. Informe o que foi observado, quando e de onde veio; o sistema não define diagnóstico nem conduta."})]}),e.jsx(A,{children:e.jsxs("fieldset",{disabled:R||f||v||p,className:"min-w-0 space-y-4 border-0 p-0",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(g,{htmlFor:"nutrition-assessment-category",children:"Categoria"}),e.jsx(D,{id:"nutrition-assessment-category",list:"nutrition-assessment-categories",maxLength:80,value:r.category,onChange:s=>l({...r,category:s.target.value}),placeholder:"Preferências, recordatório, medidasâ¦"}),e.jsxs("datalist",{id:"nutrition-assessment-categories",children:[e.jsx("option",{value:"Preferências"}),e.jsx("option",{value:"Restrições"}),e.jsx("option",{value:"Recordatório"}),e.jsx("option",{value:"Objetivos"}),e.jsx("option",{value:"Medidas"}),e.jsx("option",{value:"Contexto clÃnico"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(g,{htmlFor:"nutrition-assessment-label",children:"Informação observada"}),e.jsx(D,{id:"nutrition-assessment-label",maxLength:160,value:r.label,onChange:s=>l({...r,label:s.target.value}),placeholder:"Ex.: rotina matinal"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(g,{htmlFor:"nutrition-assessment-value",children:"Valor ou descrição"}),e.jsx(re,{id:"nutrition-assessment-value",maxLength:2e3,value:r.valueText,onChange:s=>l({...r,valueText:s.target.value}),rows:3})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(g,{htmlFor:"nutrition-assessment-date",children:"Data observada"}),e.jsx(D,{id:"nutrition-assessment-date",type:"date",value:r.observedOn,onChange:s=>l({...r,observedOn:s.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(g,{htmlFor:"nutrition-assessment-source",children:"Origem"}),e.jsxs("select",{id:"nutrition-assessment-source",value:r.sourceKind,required:!0,className:"flex h-10 w-full rounded-md border border-input bg-background px-3 text-sm",onChange:s=>l({...r,sourceKind:s.target.value}),children:[e.jsx("option",{value:"",disabled:!0,children:"Selecione a origem"}),Object.entries(K).map(([s,o])=>e.jsx("option",{value:s,children:o},s))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(g,{htmlFor:"nutrition-assessment-source-detail",children:["Detalhe da origem",r.sourceKind==="document"||r.sourceKind==="other"?" (obr
1igatório)":" (opcional)"]}),e.jsx(D,{id:"nutrition-assessment-source-detail",maxLength:500,value:r.sourceDetail,onChange:s=>l({...r,sourceDetail:s.target.value}),placeholder:"Ex.: documento apresentado na consulta"})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(N,{type:"button",onClick:()=>void Y(),children:"Registrar informação"}),r.supersedesId&&e.jsx(N,{type:"button",variant:"outline",onClick:()=>l(w()),children:"Cancelar correção"})]})]})})]}),e.jsxs(k,{children:[e.jsxs(T,{children:[e.jsx(L,{children:"Perfil registrado"}),e.jsx(F,{children:"Registros da nutricionista atual. Correções preservam o texto anterior no histórico. Estas informações não são publicadas automaticamente ao paciente nem usadas em cálculos."})]}),e.jsxs(A,{className:"space-y-4",children:[v&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"Carregando avaliaçãoâ¦"}),p&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{role:"alert",className:"text-sm text-destructive",children:"Não foi possÃvel carregar a avaliação."}),e.jsx(N,{type:"button",size:"sm",variant:"outline",onClick:()=>void y(),children:"Tentar novamente"})]}),!v&&!p&&M.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"Ainda não há informações registradas."}),!p&&M.map(s=>e.jsxs("div",{className:"space-y-2 rounded-md border p-4",children:[e.jsxs("p",{className:"text-xs text-muted-foreground",children:[s.category," · Observado em ",U(s.observed_on)]}),e.jsx("h3",{className:"font-medium",children:s.label}),e.jsx("p",{className:"whitespace-pre-wrap text-sm",children:s.value_text}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Origem: ",K[s.source_kind]||s.source_kind,s.source_detail&&` · ${s.source_detail}`]}),e.jsx(N,{type:"button",variant:"outline",size:"sm",disabled:R||f||v||p,onClick:()=>Q(s),children:"Corrigir registro"})]},s.id)),P.length>0&&e.jsxs("details",{children:[e.jsxs("summary",{className:"cursor-pointer text-sm font-medium",children:["Histórico de correções (",P.length,")"]}),e.jsx("div",{className:"mt-3 space-y-2",children:P.map(s=>e.jsxs("div",{className:"rounded-md border p-3 text-sm",children:[e.jsxs("p",{className:"text-muted-foreground",children:[s.category," · ",s.label," · ",U(s.observed_on)]}),e.jsx("p",{className:"whitespace-pre-wrap",children:s.value_text}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Origem: ",K[s.source_kind]||s.source_kind,s.source_detail&&` · ${s.source_detail}`]})]},s.id))})]})]})]})]})]})}export{he 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.