1import{r as l,u as ma,j as e}from"./react-vendor-BorBU4Bs.js";import{a as Je,s as j,b as ua,aD as U,K as te,M as oe,B as _,A as Pe,bB as xa,bn as pa,b5 as ie,an as ha,ao as fa,X as va,I as ga,S as Re,d as De,f as Oe,g as Ee,h as de,aZ as ja,a_ as _a,n as C,bt as P,bC as qe,bD as Ie,bE as Te,N as Ue,O as $e,Q as $,U as N,V as Le,W as g,D as ba,i as Na,j as Aa,k as wa,F as Ca,L as D,G as Sa,J as ya}from"./index-DkhxOMdR.js";import{C as ka}from"./checkbox-Dl2yzLyD.js";import{S as Pa}from"./switch-FKqIeruD.js";import{l as L,p as Ra,E as Ve}from"./estadoLiberacao-C57GOuYf.js";import{S as Da}from"./shield-off-hP0m-pBq.js";import{L as Oa}from"./lock-BwzBHx05.js";import"./radix-vendor-CazrR58L.js";import"./charts-vendor-BxJanGhU.js";import"./query-vendor-dlntIC_S.js";import"./supabase-vendor-BxTHC7hl.js";import"./xlsx-vendor-DOnNs5_d.js";import"./qr-vendor-Ca1-Dxvv.js";const ze=["visualizar","classificar","validar_versao","reativar"];function Ea(){const{user:i}=Je(),[o,n]=l.useState(!0),[c,A]=l.useState({visualizar:!1,classificar:!1,validar_versao:!1,reativar:!1});return l.useEffect(()=>{let b=!1;return(async()=>{if(!(i!=null&&i.id)){b||n(!1);return}n(!0);const u=await Promise.all(ze.map(q=>j.rpc("has_qualidade_cap",{_user_id:i.id,_action:q})));if(b)return;const w={...c};ze.forEach((q,V)=>{w[q]=u[V].data===!0}),A(w),n(!1)})(),()=>{b=!0}},[i==null?void 0:i.id]),{caps:c,loading:o}}function Be(i){var n;const o=String((i==null?void 0:i.ultra_cod_produto)||((n=i==null?void 0:i.racoes)==null?void 0:n.codigo)||"").trim();return o?o.split("/")[0].trim().toUpperCase():"â"}function Fe(i){const o=i==null?void 0:i.ultra_des_versao;return o==null||String(o).trim()===""?"â":String(o).trim()}function qa(i){const o=new Map;for(const n of i){const c=`${Be(n)}|${Fe(n)}`,A=o.get(c);A?A.push(n):o.set(c,[n])}return Array.from(o.entries()).map(([n,c])=>{const A=Array.from(new Set(c.map(u=>String(u.estado_liberacao??"â")))),b=c.map(u=>typeof u.quantidade=="number"?u.quantidade:null).filter(u=>u!==null),R=Array.from(new Set(c.map(u=>u.ultra_ordem_uuid).filter(u=>!!u)));return{key:n,codigoBase:Be(c[0]),versao:Fe(c[0]),pendencias:c,representante:c[0],estados:A,ambiguo:A.length>1,quantidadeTotal:b.length?b.reduce((u,w)=>u+w,0):null,uuids:R,semUuid:c.some(u=>!u.ultra_ordem_uuid)}})}function y(i){return String(i??"").split("/")[0].trim()}function Me(i){return(i||[]).reduce((o,n)=>o+(Number(n==null?void 0:n.val_peso_ingrediente)||0),0)}const O={AGUARDANDO_CLASSIFICACAO_QUALIDADE:"classificar",AGUARDANDO_VALIDACAO_NOVA_VERSAO:"validar",AGUARDANDO_REATIVACAO_FORMULA:"reativar"},Ge={classificar:"classificar",validar:"validar_versao",reativar:"reativar"},Qe={AGUARDANDO_CLASSIFICACAO_QUALIDADE:"bg-amber-500/15 text-amber-600 border-amber-500/40",AGUARDANDO_VALIDACAO_NOVA_VERSAO:"bg-sky-500/15 text-sky-600 border-sky-500/40",AGUARDANDO_REATIVACAO_FORMULA:"bg-rose-500/15 text-rose-600 border-rose-500/40"};function He(i){if(!i)return"â";const[o]=String(i).split("T"),n=o.split("-");return n.length===3?`${n[2]}/${n[1]}/${n[0]}`:o}function E(i,o=3){return i==null?"â":Number(i).toLocaleString("pt-BR",{minimumFractionDigits:o,maximumFractionDigits:o})}const ne=(i,o)=>{const n=[];for(let c=0;c<i.length;c+=o)n.push(i.slice(c,c+o));return n};function Xa(){var Se,ye;const i=ma(),{toast:o}=ua(),{isMaster:n}=Je(),{caps:c,loading:A}=Ea(),b=n||c.visualizar,[R,u]=l.useState(!0),[w,q]=l.useState([]),[V,Xe]=l.useState({}),[Q,Ke]=l.useState({}),[le,We]=l.useState([]),[ce,Ze]=l.useState([]),[H,Ye]=l.useState(""),[z,ea]=l.useState("todos"),[aa,sa]=l.useState({}),[me,ue]=l.useState(new Set),[x,B]=l.useState(null),[F,J]=l.useState(""),[I,X]=l.useState([]),[K,W]=l.useState(!1),[Z,xe]=l.useState(""),[ra,pe]=l.useState(!1),[Y,ee]=l.useState(!1),[he,fe]=l.useState(!1),[ve,ge]=l.useState(null),je=async a=>{const s=new Set;if(!a.length)return s;(await Promise.all(ne(a,100).map(r=>j.from("produtos_qualidade").select("codigo_materia_prima").in("codigo_materia_prima",r)))).forEach(r=>(r.data||[]).forEach(p=>{const h=y(p.codigo_materia_prima);h&&s.add(h)}));const d=a.filter(r=>!s.has(r));return d.length&&(await Promise.all(ne(d,100).map(p=>
1j.from("racoes").select("codigo").in("codigo",p)))).forEach(p=>(p.data||[]).forEach(h=>{const S=y(h.codigo);S&&s.add(S)})),s},ta=async()=>{fe(!0);try{const a=Array.from(new Set(Object.values(Q).flat().map(t=>y(t.cod_ingrediente)).filter(t=>!!t))),s=await je(a);ue(s),o({title:"Catálogo reavaliado",description:`${s.size} código(s) encontrado(s) no cadastro.`})}catch(a){o({variant:"destructive",title:"Erro ao reavaliar catálogo",description:a.message})}finally{fe(!1)}},oa=async a=>{const s=a.representante.id;ge(a.key);try{const{data:t,error:d}=await j.rpc("qualidade_reavaliar_pendencia",{p_pedido_id:s});if(d)throw d;const r=t||{};o({title:r.alterado?"Pendência reavaliada":"Pendência sem alteração",description:r.estado===Ve?`Liberado ao PCP. ${r.pedidos_atualizados??0} pedido(s) atualizado(s).`:`${L({estado_liberacao:r.estado})||r.estado}${r.motivo?`: ${r.motivo}`:""}`}),await M()}catch(t){o({variant:"destructive",title:"Não foi possÃvel reavaliar",description:t.message})}finally{ge(null)}},M=async()=>{u(!0);try{const[a,s,t]=await Promise.all([j.from("pedidos").select("id, numero, ordem_producao, estado_liberacao, bloqueio_motivo, cliente_id, racao_id, ultra_cod_produto, ultra_nom_produto, ultra_des_versao, ultra_ordem_uuid, peso_solicitado, data_producao, created_at, racoes(codigo, nome), clientes(codigo, nome)").eq("cancelado",!1).neq("estado_liberacao",Ve).not("estado_liberacao","is",null).order("created_at",{ascending:!1}).order("id",{ascending:!0}).limit(500),j.from("clientes").select("id, codigo, nome").eq("ativo",!0).order("nome"),j.from("racoes_grupos").select("id, codigo, nome, medicado").eq("ativo",!0).order("nome")]);if(a.error)throw a.error;if(s.error)throw s.error;if(t.error)throw t.error;const d=(a.data||[]).map(f=>({...f,quantidade:f.peso_solicitado??null}));q(d),We(s.data||[]),Ze(t.data||[]);const r=Array.from(new Set(d.map(f=>f.ultra_ordem_uuid).filter(Boolean))),p={},h={};if(r.length){const f=ne(r,100),m=await Promise.all(f.map(k=>j.from("ordem_producao_ultra").select("uuid_externo, cod_ordem_producao, cod_produto, nom_produto, des_versao, dat_versao, val_peso_padrao, val_peso_programado, is_pesadinha").in("uuid_externo",k))),re=await Promise.all(f.map(k=>j.from("ordem_producao_ultra_ingredientes").select("ordem_uuid, cod_ingrediente, nom_ingrediente, des_posicao, val_peso_ingrediente").in("ordem_uuid",k)));m.forEach(k=>(k.data||[]).forEach(T=>p[T.uuid_externo]=T)),re.forEach(k=>(k.data||[]).forEach(T=>{var ke;(h[ke=T.ordem_uuid]||(h[ke]=[])).push(T)}))}Xe(p),Ke(h);const S=Array.from(new Set(Object.values(h).flat().map(f=>y(f.cod_ingrediente)).filter(f=>!!f)));ue(await je(S))}catch(a){o({variant:"destructive",title:"Erro ao carregar pendências",description:a.message})}finally{u(!1)}};l.useEffect(()=>{b?M():u(!1)},[b]);const _e=l.useMemo(()=>{const a=H.trim().toLowerCase();return w.filter(s=>{var d,r,p;return z!=="todos"&&s.estado_liberacao!==z?!1:a?[s.numero,s.ordem_producao,s.ultra_cod_produto,s.ultra_nom_produto,s.ultra_des_versao,(d=s.racoes)==null?void 0:d.codigo,(r=s.racoes)==null?void 0:r.nome,(p=s.clientes)==null?void 0:p.nome].filter(Boolean).join(" ").toLowerCase().includes(a):!0})},[w,H,z]),be=l.useMemo(()=>qa(_e),[_e]),ia=l.useMemo(()=>{const a={};return w.forEach(s=>{const t=String(s.estado_liberacao);a[t]=(a[t]||0)+1}),a},[w]),Ne=a=>{for(const s of a.uuids)if(V[s])return V[s];return null},ae=a=>{var s;for(const t of a.uuids)if((s=Q[t])!=null&&s.length)return Q[t];return[]},se=a=>{const s=ae(a),t=new Set;return s.forEach(d=>{const r=y(d.cod_ingrediente);r?me.has(r)||t.add(`${r} â ${d.nom_ingrediente||"?"}`):t.add(`${d.nom_ingrediente||"(sem nome)"} â sem código`)}),Array.from(t)},G=a=>a?n||c[Ge[a]]:!1,Ae=a=>{const s=a.representante;B(a),J(s.cliente_id||""),xe(""),pe(!1),ee(!1);const t=O[String(s.estado_liberacao)];(t==="validar"||t==="reativar")&&s.racao_id?(pe(!0),j.from("racao_grupos").select("grupo_id").eq("racao_id",s.racao_id).then(({data:d})=>X((d||[]).map(r=>r.grupo_id))),j.from("racoes").select("is_medicada, cliente_id").eq("id",s.racao_id).maybeSingle().then(({data:d})=>{d&&(W(!!d.is_medicada),J(r=>r||d.cliente_id||""))})):(X([]),W(!1))},da=a=>{X(s=>s.includes(a)?s.filter(t=>t!==a):[...s,a])},v=x?O[String(x.representante.estado_liberacao)]:null,na=(x&&v!=="reativar"?se(x):[]).length>0,la=async()=>
1{if(!x||!v)return;if(x.ambiguo){o({variant:"destructive",title:"Grupo inconsistente",description:"Resolva os pedidos individualmente."});return}if(!G(v)){o({variant:"destructive",title:"Sem permissão para esta ação"});return}const a=x.representante.id;if(v!=="reativar"){const s=se(x);if(s.length>0){o({variant:"destructive",title:"MP não cadastrada no catálogo",description:s.slice(0,5).join(" | ")});return}if(!F){o({variant:"destructive",title:"Selecione o cliente da ração"});return}if(I.length===0){o({variant:"destructive",title:"Selecione ao menos um grupo de contaminação"});return}}else if(!Z.trim()){o({variant:"destructive",title:"Informe o motivo da reativação"});return}ee(!0);try{const s=v==="classificar"?"qualidade_classificar_racao_ultra":v==="validar"?"qualidade_validar_versao_ultra":"qualidade_reativar_formula",t=v==="reativar"?{p_pedido_id:a,p_motivo:Z.trim()}:{p_pedido_id:a,p_cliente_id:F,p_grupo_ids:I,p_is_medicada:K},{data:d,error:r}=await j.rpc(s,t);if(r)throw r;const p=d||{};o({title:"Pendência resolvida",description:v==="reativar"?`Fórmula reativada. ${p.pedidos_liberados??0} pedido(s) liberado(s) ao PCP.`:`Versão ${p.versao??""} criada com ${p.ingredientes??0} ingrediente(s). ${p.pedidos_liberados??0} pedido(s) liberado(s) ao PCP.`}),B(null),await M()}catch(s){o({variant:"destructive",title:"Não foi possÃvel concluir",description:s.message})}finally{ee(!1)}},ca=((Se=le.find(a=>a.id===F))==null?void 0:Se.nome)||((ye=x==null?void 0:x.representante.clientes)==null?void 0:ye.nome)||"A definir";if(A)return e.jsxs("div",{className:"py-16 flex items-center justify-center text-muted-foreground",children:[e.jsx(U,{className:"h-5 w-5 animate-spin mr-2"})," Verificando permissõesâ¦"]});if(!b)return e.jsx(te,{className:"border-border max-w-lg mx-auto mt-10",children:e.jsxs(oe,{className:"p-8 text-center space-y-4",children:[e.jsx("div",{className:"mx-auto flex h-12 w-12 items-center justify-center rounded-full bg-destructive/10 text-destructive",children:e.jsx(Da,{className:"h-6 w-6"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-lg font-semibold text-foreground",children:"Acesso restrito"}),e.jsxs("p",{className:"text-sm text-muted-foreground mt-1",children:["à necessária a permissão ",e.jsx("span",{className:"font-mono",children:"qualidade.visualizar"})," para acessar a fila de pendências de fórmulas."]})]}),e.jsxs(_,{variant:"outline",onClick:()=>i("/qualidade"),children:[e.jsx(Pe,{className:"h-4 w-4 mr-2"})," Voltar para Qualidade"]})]})});const we=a=>{const s=ae(a),t=s.length?Me(s):null,d=se(a);return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(D,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Ingredientes do Ultra (somente leitura)"}),e.jsxs("div",{className:"flex items-center gap-2",children:[d.length>0&&e.jsxs(C,{variant:"outline",className:"bg-destructive/10 text-destructive border-destructive/40 text-[10px]",children:[e.jsx(P,{className:"h-3 w-3 mr-1"}),d.length," MP não cadastrada no catálogo"]}),e.jsxs(_,{type:"button",variant:"outline",size:"sm",onClick:ta,disabled:he,children:[he?e.jsx(U,{className:"h-3.5 w-3.5 mr-1 animate-spin"}):e.jsx(ie,{className:"h-3.5 w-3.5 mr-1"}),"Reavaliar catálogo"]})]})]}),d.length>0&&e.jsxs("div",{className:"flex gap-2 rounded-md border border-destructive/40 bg-destructive/10 p-3 text-xs text-destructive",children:[e.jsx(P,{className:"h-4 w-4 shrink-0"}),e.jsxs("span",{children:["MP não cadastrada no catálogo (Produtos/Qualidade): ",d.slice(0,10).join(" | "),d.length>10?` ⦠(+${d.length-10})`:"",". Cadastre as matérias-primas antes de liberar â a validação final é feita no servidor."]})]}),s.length===0?e.jsx("div",{className:"rounded-md border border-dashed border-border p-3 text-xs text-muted-foreground",children:"Nenhum ingrediente sincronizado para esta ordem do Ultra."}):e.jsx("div",{className:"max-h-64 overflow-y-auto rounded-md border border-border",children:e.jsxs(Ue,{children:[e.jsx($e,{children:e.jsxs($,{children:[e.jsx(N,{className:"text-xs",children:"Código"}),e.jsx(N,{className:"text-xs",children:"Ingrediente"}),e.jsx(N,{className:"text-xs",children:"Posição"}),e.jsx(N,{className:"text-xs text-right",children:"Peso (kg)"})]})}),e.jsxs(Le,{children:[s.map((r,p)=>e.jsxs($,{children:[e.jsxs(g,{className:"text-xs font-mono",children:[y(r.cod_ingrediente)||"â",!y(r.cod_ingrediente)||me.has(y(r.cod_ingrediente))?null:e.jsx(C,{variant:"outline",className:"ml-1.5 bg-destructive/10 text-destructive border-destructive/40 text-[10px]",children:"não cadastrada"})]}),e.jsx(g,{className:"text-xs",children:r.nom_ingrediente||"â"}),e.jsx(g,{className:"text-xs",children:r.des_posicao||"â"}),e.jsx(g,{className:"text-xs text-right",children:E(r.val_peso_ingrediente)})]},`${r.cod_ingrediente}-${p}`)),e.jsxs($,{children:[e.jsx(g,{colSpan:3,className:"text-xs font-semibold",children:"Peso da fórmula"}),e.jsx(g,{className:"text-xs text-right font-semibold",children:E(t)})]})]})]})})]})},Ce=a=>{const s=Ne(a),t=Me(ae(a));return s?e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-3 text-sm",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase text-muted-foreground",children:"OP Ultra"}),e.jsx("div",{className:"font-medium",children:s.cod_ordem_producao||"â"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase text-muted-foreground",children:"Produto Ultra"}),e.jsx("div",{className:"font-medium",children:s.cod_produto||"â"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:s.nom_produto||"â"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase text-muted-foreground",children:"Versão / Data"}),e.jsxs("div",{className:"font-medium",children:[s.des_versao||"â"," · ",He(s.dat_versao)]})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase text-muted-foreground",children:"Peso da fórmula"}),e.jsxs("div",{className:"font-medium",children:[E(t)," kg"]}),e.jsx("div",{className:"text-[10px] text-muted-foreground",children:"soma dos ingredientes"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase text-muted-foreground",children:"Peso programado"}),e.jsxs("div",{className:"font-medium",children:[E(s.val_peso_programado)," kg"]}),e.jsx("div",{className:"text-[10px] text-muted-foreground",children:"quantidade da OP (não escala a fórmula)"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase text-muted-foreground",children:"Tipo"}),e.jsx(C,{variant:"outline",className:"text-[10px]",children:s.is_pesadinha?"Pesadinha":"Ração"})]})]}):e.jsxs("div",{className:"flex gap-2 rounded-md border border-amber-500/40 bg-amber-500/10 p-3 text-xs text-amber-700",children:[e.jsx(P,{className:"h-4 w-4 shrink-0"}),e.jsxs("span",{children:["Dado incompleto: a ordem do Ultra não foi encontrada para esta pendência",a.semUuid?" (pedido sem vÃnculo de ordem)":"",". Os ingredientes continuam sendo lidos no servidor pela RPC."]})]})};
1return e.jsx(xa,{children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsxs(_,{variant:"outline",size:"sm",onClick:()=>i("/qualidade"),children:[e.jsx(Pe,{className:"h-4 w-4 mr-2"})," Voltar"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"flex h-9 w-9 items-center justify-center rounded-lg bg-primary/15 text-primary",children:e.jsx(pa,{className:"h-5 w-5"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-xl font-bold text-foreground",children:"Pendências de Fórmulas"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Agrupadas por ração (código base) + versão do Ultra"})]})]}),e.jsxs(_,{variant:"outline",size:"sm",className:"ml-auto",onClick:M,disabled:R,children:[e.jsx(ie,{className:`h-4 w-4 mr-2 ${R?"animate-spin":""}`})," Atualizar"]})]}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-3",children:Object.keys(O).map(a=>e.jsx(te,{className:"border-border",children:e.jsxs(oe,{className:"p-4 flex items-center justify-between",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:L({estado_liberacao:a})}),e.jsx("span",{className:"text-2xl font-bold text-foreground",children:ia[a]||0})]})},a))}),e.jsxs(te,{className:"border-border",children:[e.jsxs(ha,{className:"pb-3",children:[e.jsx(fa,{className:"text-base",children:"Fila da Qualidade"}),e.jsxs("div",{className:"flex flex-wrap gap-2 pt-2",children:[e.jsxs("div",{className:"relative flex-1 min-w-[220px]",children:[e.jsx(va,{className:"absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground"}),e.jsx(ga,{className:"pl-8",placeholder:"Buscar por pedido, OP, código ou produtoâ¦",value:H,onChange:a=>Ye(a.target.value)})]}),e.jsxs(Re,{value:z,onValueChange:ea,children:[e.jsx(De,{className:"w-[240px]",children:e.jsx(Oe,{})}),e.jsxs(Ee,{children:[e.jsx(de,{value:"todos",children:"Todos os tipos"}),Object.keys(O).map(a=>e.jsx(de,{value:a,children:L({estado_liberacao:a})},a))]})]})]})]}),e.jsx(oe,{children:R?e.jsxs("div",{className:"py-10 flex items-center justify-center text-muted-foreground",children:[e.jsx(U,{className:"h-5 w-5 animate-spin mr-2"})," Carregandoâ¦"]}):be.length===0?e.jsx("div",{className:"py-10 text-center text-sm text-muted-foreground",children:"Nenhuma pendência de fórmula. O PCP está liberado."}):e.jsx("div",{className:"space-y-3",children:be.map(a=>{var f;const s=a.representante,t=Ra(s),d=String(s.estado_liberacao),r=O[d],p=G(r),h=!!aa[a.key],S=Ne(a);return e.jsxs("div",{className:"rounded-lg border border-border",children:[e.jsxs("div",{className:"flex flex-wrap items-start gap-3 p-3",children:[e.jsx(_,{variant:"ghost",size:"icon",className:"h-7 w-7 shrink-0",onClick:()=>sa(m=>({...m,[a.key]:!m[a.key]})),"aria-label":h?"Recolher detalhes":"Expandir detalhes",children:h?e.jsx(ja,{className:"h-4 w-4"}):e.jsx(_a,{className:"h-4 w-4"})}),e.jsxs("div",{className:"min-w-[220px] flex-1",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"font-semibold text-foreground",children:a.codigoBase}),e.jsxs(C,{variant:"outline",className:"text-[10px]",children:["versão Ultra ",a.versao]}),a.ambiguo?e.jsxs(C,{variant:"outline",className:"bg-destructive/10 text-destructive border-destructive/40 text-[10px]",children:[e.jsx(P,{className:"h-3 w-3 mr-1"})," Estados divergentes"]}):e.jsx(C,{variant:"outline",className:Qe[d]||"",children:L(s)||d})]}),e.jsxs("div",{className:"text-sm text-muted-foreground mt-0.5",children:["Ultra: ",s.ultra_cod_produto||"â"," · ",s.ultra_nom_produto||"â"]}),s.racao_id&&e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Interno: ",t.codigo," · ",t.nome]}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Cliente: ",((f=s.clientes)==null?void 0:f.nome)||e.jsx("span",{className:"italic",children:"A definir"})]}),!a.ambiguo&&s.bloqueio_motivo&&e.jsx("div",{className:"text-[11px] text-muted-foreground mt-1 max-w-[420px]",children:s.bloqueio_motivo})]}),e.jsxs("div",{className:"text-xs text-muted-foreground min-w-[190px]",children:[e.jsxs("div",{children:[e.jsx("span",{className:"font-medium text-foreground",children:a.pendencias.length})," pedido(s):"," ",a.pendencias.map(m=>
1m.numero||m.ordem_producao||m.id.slice(0,6)).join(", ")]}),e.jsxs("div",{children:["Qtd. programada:"," ",a.quantidadeTotal!==null?`${E(a.quantidadeTotal,0)} kg`:"â"]}),S&&e.jsxs("div",{children:["OP Ultra: ",S.cod_ordem_producao||"â"]}),(a.semUuid||!S)&&e.jsxs("div",{className:"text-amber-600 flex items-center gap-1 mt-1",children:[e.jsx(P,{className:"h-3 w-3"})," dado do Ultra incompleto"]})]}),e.jsxs("div",{className:"ml-auto flex items-center gap-2",children:[e.jsxs(qe,{children:[e.jsx(Ie,{asChild:!0,children:e.jsx("span",{children:e.jsxs(_,{size:"sm",variant:"outline",onClick:()=>oa(a),disabled:ve===a.key,children:[ve===a.key?e.jsx(U,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}):e.jsx(ie,{className:"h-3.5 w-3.5 mr-1.5"}),"Reavaliar"]})})}),e.jsx(Te,{children:"Recalcula a pendência com o cadastro atual de ração, cliente e versão."})]}),a.ambiguo?e.jsx("span",{className:"text-xs text-muted-foreground",children:"Resolva individualmente (expanda)"}):p?e.jsx(_,{size:"sm",onClick:()=>Ae(a),children:"Resolver"}):e.jsxs(qe,{children:[e.jsx(Ie,{asChild:!0,children:e.jsx("span",{children:e.jsxs(_,{size:"sm",disabled:!0,children:[e.jsx(Oa,{className:"h-3.5 w-3.5 mr-1.5"})," Resolver"]})})}),e.jsxs(Te,{children:["Requer a permissão qualidade.",r?Ge[r]:"â"]})]})]})]}),h&&e.jsxs("div",{className:"border-t border-border p-3 space-y-4 bg-muted/30",children:[a.ambiguo&&e.jsxs("div",{className:"flex gap-2 rounded-md border border-destructive/40 bg-destructive/10 p-3 text-xs text-destructive",children:[e.jsx(P,{className:"h-4 w-4 shrink-0"}),e.jsxs("span",{children:["Inconsistência: pedidos com o mesmo código base e versão estão em estados diferentes (",a.estados.join(", "),"). A resolução em massa está bloqueada."]})]}),Ce(a),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(Ue,{children:[e.jsx($e,{children:e.jsxs($,{children:[e.jsx(N,{className:"text-xs",children:"Pedido"}),e.jsx(N,{className:"text-xs",children:"OP"}),e.jsx(N,{className:"text-xs",children:"Produção"}),e.jsx(N,{className:"text-xs text-right",children:"Qtd. (kg)"}),e.jsx(N,{className:"text-xs",children:"Estado"}),e.jsx(N,{className:"text-xs text-right",children:"Ação"})]})}),e.jsx(Le,{children:a.pendencias.map(m=>{const re=O[String(m.estado_liberacao)];return e.jsxs($,{children:[e.jsx(g,{className:"text-xs font-medium",children:m.numero||"â"}),e.jsx(g,{className:"text-xs",children:m.ordem_producao||"â"}),e.jsx(g,{className:"text-xs",children:He(m.data_producao)}),e.jsx(g,{className:"text-xs text-right",children:E(m.quantidade,0)}),e.jsx(g,{className:"text-xs",children:e.jsx(C,{variant:"outline",className:Qe[String(m.estado_liberacao)]||"",children:L(m)||String(m.estado_liberacao)})}),e.jsx(g,{className:"text-right",children:a.ambiguo&&G(re)?e.jsx(_,{size:"sm",variant:"outline",onClick:()=>Ae({...a,pendencias:[m],representante:m,estados:[String(m.estado_liberacao)],ambiguo:!1}),children:"Resolver"}):e.jsx("span",{className:"text-[11px] text-muted-foreground",children:"â"})})]},m.id)})})]})}),we(a)]})]},a.key)})})})]}),e.jsx(ba,{open:!!x,onOpenChange:a=>!a&&B(null),children:e.jsxs(Na,{className:"max-w-3xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(Aa,{children:[e.jsx(wa,{children:v==="classificar"?"Classificar ração nova":v==="validar"?"Validar nova versão":"Reativar fórmula"}),e.jsx(Ca,{children:x&&e.jsxs(e.Fragment,{children:[x.codigoBase," · versão Ultra ",x.versao," · ",x.pendencias.length," pedido(s)"]})})]}),x&&e.jsxs("div",{className:"space-y-5",children:[e.jsx("div",{className:"rounded-md border border-border p-3",children:Ce(x)}),e.jsxs("div",{className:"rounded-md border border-sky-500/40 bg-sky-500/10 p-3 text-xs text-sky-700",children:["Ao concluir, a RPC libera os pedidos deste código base + versão:"," ",e.jsx("span",{className:"font-medium",children:x.pendencias.map(a=>a.numero||a.ordem_producao||a.id.slice(0,6)).join(", ")})]}),we(x),v==="reativar"?e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex gap-2 rounded-md border border-amber-500/40 bg-amber-500/10 p-3 text-xs text-amber-700",children:[e.jsx(P,{className:"h-4 w-4 shrink-0"}),e.jsx("span",{children:"A ração e/ou versão foi baixada. A reativação restabelece apenas esta fórmula/versão e libera os pedidos correspondentes ao PCP â a classificação atual não é alterada."})]}),e.jsxs("div",{className:"rounded-md border border-border p-3 space-y-2",children:[e.jsx(D,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Classificação atual (somente leitura)"}),e.jsxs("div",{className:"text-sm",children:["Cliente: ",e.jsx("span",{className:"font-medium",children:ca})]}),e.jsxs("div",{className:"text-sm",children:["Medicada: ",e.jsx("span",{className:"font-medium",children:K?"Sim":"Não"})]}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:I.length===0?e.jsx("span",{className:"text-xs text-muted-foreground",children:"Sem grupos de contaminação registrados"}):I.map(a=>{const s=ce.find(t=>
1t.id===a);return e.jsx(C,{variant:"outline",className:"text-[10px]",children:s?s.codigo?`${s.codigo} â ${s.nome}`:s.nome:a.slice(0,8)},a)})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(D,{children:"Motivo da reativação *"}),e.jsx(Sa,{value:Z,onChange:a=>xe(a.target.value),placeholder:"Justifique a reativação (será registrado na auditoria)",rows:3})]})]}):e.jsxs("div",{className:"space-y-4",children:[ra&&e.jsx("div",{className:"rounded-md border border-sky-500/40 bg-sky-500/10 p-3 text-xs text-sky-700",children:"Valores herdados do cadastro atual da ração â confirme ou ajuste antes de validar a nova versão."}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(D,{children:"Cliente da ração *"}),e.jsxs(Re,{value:F,onValueChange:J,children:[e.jsx(De,{children:e.jsx(Oe,{placeholder:"Selecione o cliente"})}),e.jsx(Ee,{children:le.map(a=>e.jsx(de,{value:a.id,children:a.codigo?`${a.codigo} â ${a.nome}`:a.nome},a.id))})]})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-md border border-border p-3",children:[e.jsxs("div",{children:[e.jsx(D,{className:"text-sm",children:"Ração medicada"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Exige controle de receituário e contaminação"})]}),e.jsx(Pa,{checked:K,onCheckedChange:W})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(D,{children:"Grupos de contaminação *"}),e.jsx("div",{className:"max-h-48 overflow-y-auto rounded-md border border-border p-2 space-y-1",children:ce.map(a=>e.jsxs("label",{className:"flex items-center gap-2 rounded px-2 py-1.5 text-sm hover:bg-muted cursor-pointer",children:[e.jsx(ka,{checked:I.includes(a.id),onCheckedChange:()=>da(a.id)}),e.jsx("span",{className:"flex-1",children:a.codigo?`${a.codigo} â ${a.nome}`:a.nome}),a.medicado&&e.jsx(C,{variant:"outline",className:"text-[10px]",children:"medicado"})]},a.id))})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"A composição de ingredientes é copiada automaticamente da ordem do Ultra no servidor. Versões anteriores permanecem ativas."})]})]}),e.jsxs(ya,{children:[e.jsx(_,{variant:"outline",onClick:()=>B(null),disabled:Y,children:"Cancelar"}),e.jsxs(_,{onClick:la,disabled:Y||!G(v)||na,children:[Y&&e.jsx(U,{className:"h-4 w-4 mr-2 animate-spin"}),v==="reativar"?"Reativar e liberar":"Confirmar e liberar"]})]})]})})]})})}export{Xa 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.