1import{r as d,j as e,f as bi,u as yi,e as Ni,l as wi}from"./react-vendor-BorBU4Bs.js";import{aA as gr,s as f,bR as Pi,m as I,bU as Si,aX as Ci,D as st,i as ot,j as Nt,k as wt,am as yt,F as Rs,L as Le,G as Fs,bs as Fa,bt as ga,bu as Ia,J as Is,B as O,bV as Jt,H as fr,S as Oa,d as Ba,f as Ka,g as Qa,h as ca,o as nt,aU as Mi,n as J,b as Xt,aP as _r,bW as Ai,b2 as qi,aD as Os,ax as ki,bX as $i,bY as To,I as Ca,aY as jr,K as Ha,aZ as Gt,a_ as Wt,M as Ua,N as ja,O as Ma,Q as ge,U as $,V as va,W as c,bZ as Di,b_ as Ei,a5 as na,a6 as da,af as rt,Y as fa,a7 as la,aV as _a,X as zi,u as Ti,bI as Li,b$ as Lo,a as Ri,c0 as Fi,c1 as Ro,c2 as Fo,a$ as As,c3 as Ii,a8 as Oi,a9 as Bi,aa as Ki,ab as Qi,ac as Hi,ad as Ui,ae as Vi,C as Io,bF as Oo,b8 as Bo,ay as Ko,b6 as Qo,c4 as Bt,c5 as Ho,A as Uo,az as Vo,c6 as Go,Z as at,_ as tt,$ as Je,P as _t,a0 as ia,c7 as Kt,r as Wo,t as Jo,v as Xo,w as Yo,x as Zo,y as er,z as ar,E as tr,c8 as Gi,c9 as sr,R as qs,bS as Wi,bn as Qt,T as ks,bv as or,ca as $s,a4 as Ji,b5 as Xi,cb as Yi}from"./index-DkhxOMdR.js";import{a as ve,u as Zi,b as Sa}from"./query-vendor-dlntIC_S.js";import{T as Ht}from"./TablePagination-RTuZAaRn.js";import{S as rr}from"./switch-FKqIeruD.js";import{i as za,l as Ts,p as ir,m as Ut}from"./estadoLiberacao-C57GOuYf.js";import{p as vr,m as nr}from"./programacaoBloqueio-KTFwD8Pn.js";import{a as dr}from"./abbreviateClientName-BXRhyGQG.js";import{J as Vt}from"./JustificativaAlteracaoDialog-DcYa75qI.js";import{u as en,M as an,a as tn}from"./useContaminacaoCheck-CDWN2BQf.js";import{utils as it,writeFile as br}from"./xlsx-vendor-DOnNs5_d.js";import{u as sn,T as Ke}from"./TableColumnFilter-BcDRj-SX.js";import{u as on,S as Qe}from"./SortableTableHead-BQcfj6gO.js";import{C as rn}from"./chevrons-up-down-CVH0PY0Y.js";import{F as nn}from"./file-warning-BkVse5Fs.js";import{R as dn,B as ln,X as cn,Y as mn,T as un,d as pn,e as xn}from"./charts-vendor-BxJanGhU.js";import{P as jt}from"./pencil-Cf5Ul2CU.js";import{B as Ds}from"./ban-DRwQmojn.js";import"./radix-vendor-CazrR58L.js";import"./supabase-vendor-BxTHC7hl.js";import"./qr-vendor-Ca1-Dxvv.js";import"./chevrons-right-BYe06OP4.js";import"./list-checks-B8gohjx4.js";import"./arrow-up-wTT2lxSL.js";/** 2 * @license lucide-react v0.462.0 - ISC 3 * 4 * This source code is licensed under the ISC license. 5 * See the LICENSE file in the root directory of this source tree. 6 */const hn=gr("GitCompare",[["circle",{cx:"18",cy:"18",r:"3",key:"1xkwt0"}],["circle",{cx:"6",cy:"6",r:"3",key:"1lh9wr"}],["path",{d:"M13 6h3a2 2 0 0 1 2 2v7",key:"1yeb86"}],["path",{d:"M11 18H8a2 2 0 0 1-2-2V9",key:"19pyzm"}]]);/** 7 * @license lucide-react v0.462.0 - ISC 8 * 9 * This source code is licensed under the ISC license. 10 * See the LICENSE file in the root directory of this source tree. 11 */const lr=gr("PackageOpen",[["path",{d:"M12 22v-9",key:"x3hkom"}],["path",{d:"M15.17 2.21a1.67 1.67 0 0 1 1.63 0L21 4.57a1.93 1.93 0 0 1 0 3.36L8.82 14.79a1.655 1.655 0 0 1-1.64 0L3 12.43a1.93 1.93 0 0 1 0-3.36z",key:"2ntwy6"}],["path",{d:"M20 13v3.87a2.06 2.06 0 0 1-1.11 1.83l-6 3.08a1.93 1.93 0 0 1-1.78 0l-6-3.08A2.06 2.06 0 0 1 4 16.87V13",key:"1pmm1c"}],["path",{d:"M21 12.43a1.93 1.93 0 0 0 0-3.36L8.83 2.2a1.64 1.64 0 0 0-1.63 0L3 4.57a1.93 1.93 0 0 0 0 3.36l12.18 6.86a1.636 1.636 0 0 0 1.63 0z",key:"12ttoo"}]]);function vt(i){return Math.trunc((Number(i)||0)*1e3)/1e3}async function gn(i,x){const{data:j,error:u}=await f.from("vw_estoque_cliente_lotes_disponiveis").select("*").eq("cliente_id",i).eq("codigo_produto",x);if(u)throw u;return fn(j??[])}function fn(i){return[...i].sort((x,j)=>{const u=x.data_validade||"9999-12-31",L=j.data_validade||"9999-12-31";return u!==L?u<L?-1:1:(x.lote||"").localeCompare(j.lote||"")})}async function _n(i,x,j){const u=vt(j);if(u<=0)return[];const L=await gn(i,x);if(L.length===0)throw new Error(`Produto ${x} não tem lote com saldo em estoque. Informe a entrada do lote antes de dar baixa.`);const y=[];let k=u;for(const M of L){if(k<=0)break;const Q=vt(Number(M.saldo_kg)||0);if(Q<=0)continue;const P=vt(Math.min(Q,k));y.push({lote:M.lote,nf:M.nf,data_fabricacao:M.data_fabricacao,data_validade:M.data_validade,quantidade:P}),k=vt(k-P)}if(k>.001){const M=vt(L.reduce((Q,P)=>Q+(Number(P.saldo_kg)||0),0));throw new Error(`Saldo insuficiente por lote no produto ${x}: pedido ${u} kg, disponÃvel ${M} kg.`)}return y}function jn(i,x,j){return j>1?`${i}/L${x+1}`:i}function vn(i,x=28){if(!i||i.length<=x)return i;let j=i.replace(/\bTERMINA[ÃC][AÃ]O\b/gi,"TERM.").replace(/\bINICIAL\b/gi,"INIC.").replace(/\bCRESCIMENTO\b/gi,"CRESC.").replace(/\bENGORDA\b/gi,"ENG.").replace(/\bALOJAMENTO\b/gi,"ALOJ.").replace(/\bMANUTEN[ÃC][AÃ]O\b/gi,"MANUT.").replace(/\bREPRODU[ÃC][AÃ]O\b/gi,"REPR.").replace(/\bLACTA[ÃC][AÃ]O\b/gi,"LACT.").replace(/\bGESTA[ÃC][AÃ]O\b/gi,"GEST.").replace(/\bFRANGOS?\b/gi,"FRG.").replace(/\bPOEDEIRAS?\b/gi,"POED.").replace(/\bSU[IÃ]NOS?\b/gi,"SUI.").replace(/\bBOVINOS?\b/gi,"BOV.").replace(/\bLEIT[OÃ]ES\b/gi,"LEIT.").replace(/\bPREMIUM\b/gi,"PREM.").replace(/\bESPECIAL\b/gi,"ESP.").replace(/\bF[ÃO]RMULA\b/gi,"FORM.").replace(/\bRA[ÃC][AÃ]O\b/gi,"R.").replace(/\bFASES?\b/gi,"F.").replace(/\bCOM\b/gi,"C/").replace(/\bPARA\b/gi,"P/").replace(/\bSEM\b/gi,"S/").replace(/\bLIMITADA\b/gi,"LTDA").replace(/\s{2,}/g," ").trim();return j.length<=x?j:j.substring(0,x-3)+"..."}function Es(i,x=10){if(!i||i.length<=x)return i;const j=i.trim().split(/\s+/);if(j.length>=2){const u=j[0],L=j[j.length-1][0],y=`${u} ${L}.`;if(y.length<=x)return y}return i.substring(0,x-1)+"."}function bn({pedidos:i,dataProducao:x,dataProducaoStr:j=null,logoUrl:u,numeroAlteracao:L=0,pedidoIds
11Filter:y=null,gradeNumero:k=null,paradasInicio:M=null,paradasFim:Q=null,rqData:P,assinaturaPcpUrl:z,assinaturaPcpInfo:H,assinaturaQualidadeUrl:ne,assinaturaQualidadeInfo:Y,justificativasAlteracao:ie=[],operadorNome:E=null}){const{config:xe}=Pi("programacao"),De=d.useMemo(()=>{const q=new Set;for(const S of i){const h=S.operador_producao_assinatura_url;h&&!/^(https?:|data:|blob:)/i.test(h)&&q.add(h)}return Array.from(q)},[i]),{data:oe={}}=ve({queryKey:["operador-assinatura-signed",De],enabled:De.length>0,staleTime:5*6e4,queryFn:async()=>{const q={};return await Promise.all(De.map(async S=>{const{data:h}=await f.storage.from("assinaturas-usuarios").createSignedUrl(S,3600);h!=null&&h.signedUrl&&(q[S]=h.signedUrl)})),q}}),Z=q=>q?/^(https?:|data:|blob:)/i.test(q)?q:oe[q]||null:null,A=d.useMemo(()=>{const q=new Set;for(const S of ie)S.user_id&&q.add(S.user_id);return Array.from(q)},[ie]),{data:R={}}=ve({queryKey:["alteracao-profiles",A],enabled:A.length>0,staleTime:5*6e4,queryFn:async()=>{const{data:q}=await f.from("profiles").select("user_id, assinatura_url, funcao").in("user_id",A),S={};for(const h of q||[])S[h.user_id]={assinatura_url:h.assinatura_url??null,funcao:h.funcao??null};return S}}),ee=d.useMemo(()=>{var S;const q=new Set;for(const h of Object.keys(R)){const te=(S=R[h])==null?void 0:S.assinatura_url;te&&!/^(https?:|data:|blob:)/i.test(te)&&q.add(te)}return Array.from(q)},[R]),{data:n={}}=ve({queryKey:["alteracao-assinatura-signed",ee],enabled:ee.length>0,staleTime:5*6e4,queryFn:async()=>{const q={};return await Promise.all(ee.map(async S=>{const{data:h}=await f.storage.from("assinaturas-usuarios").createSignedUrl(S,3600);h!=null&&h.signedUrl&&(q[S]=h.signedUrl)})),q}}),g=q=>{var h;if(!q)return null;const S=(h=R[q])==null?void 0:h.assinatura_url;return S?/^(https?:|data:|blob:)/i.test(S)?S:n[S]||null:null},{data:w=[]}=ve({queryKey:["paradas-codigos-print"],queryFn:async()=>{const{data:q,error:S}=await f.from("paradas_codigos").select("codigo, descricao").eq("ativo",!0).order("ordem",{ascending:!0});return S?[]:q||[]},staleTime:5*6e4}),v=(()=>{if(j&&/^\d{4}-\d{2}-\d{2}$/.test(j))return j;const q=x.getFullYear(),S=String(x.getMonth()+1).padStart(2,"0"),h=String(x.getDate()).padStart(2,"0");return`${q}-${S}-${h}`})(),{data:V=[]}=ve({queryKey:["paradas-dia-print",v,M,Q],queryFn:async()=>{const q=`${v}T00:00:00`,S=`${v}T23:59:59`,h=M&&M>q?M:q,te=Q&&Q<S?Q:S,{data:Ce,error:X}=await f.from("fabrica_paradas_log").select("inicio, fim, duracao_min, motivo, classificacao, codigo_parada_id, motivo_assinatura_url, motivo_registrado_por_nome, paradas_codigos(codigo, descricao)").gte("inicio",h).lte("inicio",te).neq("classificacao","fim_producao").order("inicio",{ascending:!0});return X?[]:Ce||[]},staleTime:6e4}),F=d.useMemo(()=>V.map(q=>{var ya,ea;const S=q.inicio?new Date(q.inicio):null,h=q.fim?new Date(q.fim):null,te=q.duracao_min,Ce=S?I(S,"HH:mm"):"",X=h?I(h,"HH:mm"):"â";let Ve="";if(te!=null){const Na=Math.floor(te/60),wa=te%60;Ve=Na>0?`${Na}h ${wa}m`:`${wa}m`}const ba=((ya=q.paradas_codigos)==null?void 0:ya.codigo)||"",Aa=q.motivo||((ea=q.paradas_codigos)==null?void 0:ea.descricao)||"";return{codigo:ba,horaIni:Ce,horaFim:X,tempo:Ve,descricao:Aa,assinaturaUrl:q.motivo_assinatura_url||null,assinanteNome:q.motivo_registrado_por_nome||null}}),[V]),ae=d.useMemo(()=>{const q=v,S=y&&y.length>0?new Set(y):null;return i.filter(h=>h.data_producao===q).filter(h=>S?S.has(h.id):!0).filter(h=>{var te,Ce;return!(((te=h.racoes)==null?void 0:te.tag)==="Pesadinha"||(((Ce=h.racoes)==null?void 0:Ce.nome)||"").toUpperCase().startsWith("PESADINHA"))}).sort((h,te)=>h.cancelado&&!te.cancelado?1:!h.cancelado&&te.cancelado?-1:(h.prioridade||999)-(te.prioridade||999))},[i,v,y]),ye=d.useMemo(()=>ae.reduce((q,S)=>q+(S.cancelado?0:Number(S.peso_solicitado||0)),0),[ae]),me=I(x,"EEEE, dd 'de' MMMM 'de' yyyy",{locale:Ci}),Se="#1a1a2e",sa="#ffffff",B="#1a1a2e",G="#f8f9fa",re={A4:297,A5:210,Letter:279.4},ze={A4:210,A5:148,Letter:215.9},_e=xe.size||"A4",Ne=xe.orientation==="landscape"?ze[_e]||210:re[_e]||297,ce=Math.max(120,Ne-xe.marginTop-xe.marginBottom),ue=3.78,he=17,Xe=Math.max(8,Math.min(24,Math.floor((ce*ue-470)/he))),ma=d.useMemo(()=>{const q=[];for(let S=0;S<ae.length;S+=Xe)q.push(ae.slice(S,S+Xe));return q.length>0?q:[[]]},[ae,Xe]),Ye=ma.length+1,Re=()=>e.jsxs(e.Fragment,{children:[e.jsx("table",{style:{width:"100%",borderCollapse:"collapse",marginBottom:"0"},children:e.jsx("tbody",{children:e.jsxs("tr",{children:[e.jsx("td",{style:{width:"20%",verticalAlign:"middle",padding:"8px 10px"},children:u&&e.jsx("img",{src:u,alt:"Logo",style:{maxHeight:"55px",maxWidth:"140px",objectFit:"contain"}})}),e.jsx("td",{style:{width:"50%",textAlign:"center",verticalAlign:"middle",padding:"8px"},children:e.jsxs("div",{style:{fontSize:"16pt",fontWeight:700,color:B,letterSpacing:"0.5px"},children:["Programação de Produção",k?` â ${k}ª Grade`:""]})}),e.jsx("td",{style:{width:"30%",verticalAlign:"middle",textAlign:"right",padding:"8px 10px"},children:e.jsx("table",{style:{marginLeft:"auto",borderCollapse:"collapse",fontSize:"7pt",color:"#555"},children:e.jsxs("tbody",{children:[e.jsxs("tr",{children:[e.jsx("td",{style:{padding:"1px 0",textAlign:"right"},children:"Código:"}),e.jsx("td",{style:{padding:"1px 0 1px 6px",fontWeight:600},children:(P==null?void 0:P.codigo)||"â"})]}),e.jsxs("tr",{children:[e.jsx("td",{style:{padding:"1px 0",textAlign:"right"},children:"Criado em:"}),e.jsx("td",{style:{padding:"1px 0 1px 6px"},children:P!=null&&P.criado_em?I(new Date(P.criado_em+"T00:00:00"),"dd/MM/yyyy"):"â"})]}),e.jsxs("tr",{children:[e.jsx("td",{style:{padding:"1px 0",textAlign:"right"},children:"Revisado em:"}),e.jsx("td",{style:{padding:"1px 0 1px 6px"},children:P!=null&&P.revisado_em?I(new Date(P.revisado_em+"T00:00:00"),"dd/MM/yyyy"):"â"})]}),e.jsxs("tr",{children:[e.jsx("td",{style:{padding:"1px 0",textAlign:"right"},children:"Nº Revisão:"}),e.jsx("td",{style:{padding:"1px 0 1px 6px",fontWeight:600},children:P?String(P.numero_revisao).padStart(2,"0"):"â"})]})]})})})]})})}),e.jsx("div",{style:{height:"3px",background:`linear-gradient(90deg, ${B}, #3a3a5e, ${B})`,marginBottom:"8px"}})]}),Ue=()=>e.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"8px",padding:"0 2px"},children:[e.jsxs("div",{style:{fontSize:"9pt"},children:[e.jsx("span",{style:{fontWeight:700,color:B},children:"Data de Fabricação:"})," ",e.jsx("span",{style:{fontWeight:500},children:me})]}),e.jsxs("div",{style:{fontSize:"9pt"},children:[e.jsx("span",{style:{fontWeight:700,color:B},children:"Nº da alteração do dia:"})," ",e.jsx("span",{style:{display:"inline-block",minWidth:"22px",textAlign:"center",fontWeight:700,fontSize:"10pt",border:`1.5px solid ${B}`,borderRadius:"3px",padding:"0 4px"},children:L})]})]}),Yt=()=>e.jsxs("div",{style:{display:"flex",justifyContent:"space-between",marginTop:"6px",fontSize:"8pt",padding:"0 2px",gap:"16px"},children:[e.jsxs("div",{style:{flex:1},children:[e.jsx("div",{style:{marginBottom:"2px",textAlign:"center"},children:"Assinatura do PCP:"}),z?e.jsxs("div",{children:[e.jsx("div",{style:{borderBottom:"1px solid #333",minHeight:"40px",display:"flex",alignItems:"flex-end",justifyContent:"center"},children:e.jsx("img",{src:z,alt:"Assinatura PCP",style:{maxHeight:"38px",maxWidth:"220px",objectFit:"contain"}})}),H&&e.jsxs("div",{style:{fontSize:"7pt",color:"#333",marginTop:"2px",textAlign:"center"},children:[H.nome,H.codigo?` (${H.codigo})`:"",H.em?` ⢠${I(new Date(H.em),"dd/MM/yyyy HH:mm")}`:""]})]}):e.jsx("div",{style:{borderBottom:"1px solid #333",minHeight:"40px"},children:" "})]}),e.jsxs("div",{style:{flex:1},children:[e.jsx("div",{style:{marginBottom:"2px",textAlign:"center"}
11,children:"Verificação Controle de Qualidade:"}),ne?e.jsxs("div",{children:[e.jsx("div",{style:{borderBottom:"1px solid #333",minHeight:"40px",display:"flex",alignItems:"flex-end",justifyContent:"center"},children:e.jsx("img",{src:ne,alt:"Assinatura Qualidade",style:{maxHeight:"38px",maxWidth:"220px",objectFit:"contain"}})}),Y&&e.jsxs("div",{style:{fontSize:"7pt",color:"#333",marginTop:"2px",textAlign:"center"},children:[Y.nome,Y.codigo?` (${Y.codigo})`:"",Y.em?` ⢠${I(new Date(Y.em),"dd/MM/yyyy HH:mm")}`:""]})]}):e.jsx("div",{style:{borderBottom:"1px solid #333",minHeight:"40px"},children:" "})]})]}),Ze=(q,S=!1)=>e.jsxs("div",{className:"pp-page-bottom",children:[e.jsxs("div",{className:"pp-signatures-footer",style:S?{paddingTop:"8px",borderTop:`1px dashed ${B}`}:void 0,children:[S&&e.jsx("div",{style:{fontSize:"8pt",fontWeight:700,color:B,marginBottom:"6px",textAlign:"center"},children:"Visto de Ciência"}),Yt()]}),e.jsxs("div",{className:"pp-page-num",children:["Página ",q,"/",Ye]})]}),be=q=>e.jsx("span",{className:"pp-cell-text",children:q||e.jsx(e.Fragment,{children:" "})}),Pt=(q,S)=>e.jsx("div",{className:"pp-production-table",children:e.jsxs("table",{children:[e.jsx("colgroup",{children:[4,7,5,6,5,20,12,15,8,6,5,7].map((h,te)=>e.jsx("col",{style:{width:`${h}%`}},te))}),e.jsx("thead",{children:e.jsx("tr",{children:["Prioridade",`Grade de 12Produção`,"Nº Produção",`Cód. 13Produção`,`Cód. 14Ração`,"Produto","Produtor","Cliente","Qtd. (kg)","Silo",`Pronta 15S/N?`,`Ass. 16Operador`].map((h,te)=>e.jsx("th",{style:{...cr,backgroundColor:Se,color:sa},children:h.split(` 17`).map((Ce,X)=>e.jsxs("span",{children:[X>0&&e.jsx("br",{}),Ce]},X))},te))})}),e.jsxs("tbody",{children:[q.map((h,te)=>{var Ve,ba,Aa,ya,ea,Na,wa;const Ce=S*Xe+te,X=h.cancelado?{textDecoration:"line-through",color:"#dc2626"}:{};return e.jsxs("tr",{style:{backgroundColor:Ce%2===1?G:"white"},children:[e.jsx("td",{style:{...Pe,textAlign:"center",fontWeight:700,color:h.cancelado?"#dc2626":void 0},children:be(h.cancelado?"CANCELADO":h.prioridade||Ce+1)}),e.jsx("td",{style:{...Pe,textAlign:"center",...X},children:be(h.numero_grade)}),e.jsx("td",{style:{...Pe,textAlign:"center",...X},children:be(h.lote_producao)}),e.jsx("td",{style:{...Pe,...X},children:be(h.ordem_producao)}),e.jsx("td",{style:{...Pe,...X},children:be((Ve=h.racoes)==null?void 0:Ve.codigo)}),e.jsx("td",{style:{...Pe,...X},children:be(e.jsxs(e.Fragment,{children:[vn(((ba=h.racoes)==null?void 0:ba.nome)||"",28),((Aa=h.racoes)==null?void 0:Aa.is_medicada)&&e.jsx("span",{style:{color:"#dc2626",fontWeight:700},children:" (Med.)"})]}))}),e.jsx("td",{style:{...Pe,...X},children:be(dr(((ya=h.produtores)==null?void 0:ya.nome)||"",18))}),e.jsx("td",{style:{...Pe,...X},children:be(dr(((ea=h.clientes)==null?void 0:ea.nome)||"",22))}),e.jsx("td",{style:{...Pe,textAlign:"right",fontWeight:500,...X},children:be(Number(h.peso_solicitado).toLocaleString("pt-BR"))}),e.jsx("td",{style:{...Pe,...X},children:be(((Na=h.silos_expedicao)==null?void 0:Na.nome)||((wa=(h.ordens_carregamento||[]).find(oa=>(oa.silo_expedicao||"").trim()))==null?void 0:wa.silo_expedicao)||null)}),e.jsx("td",{style:{...Pe,textAlign:"center",fontWeight:700},children:be(h.cancelado?null:h.status_producao==="finalizado"||h.silo_expedicao_id||(h.ordens_carregamento||[]).some(oa=>oa.status==="finalizado")?"S":"N")}),e.jsx("td",{style:{...Pe,textAlign:"center",padding:"1px"},children:h.cancelado?be(null):(()=>{const oa=Z(h.operador_producao_assinatura_url);return oa?e.jsx("img",{src:oa,alt:Es(h.operador_producao_nome||"Operador"),style:{maxHeight:"22px",maxWidth:"100%",objectFit:"contain",display:"inline-block"},onError:lt=>{const ct=lt.currentTarget,qa=document.createElement("span");qa.style.fontStyle="italic",qa.style.fontSize="7pt",qa.textContent=Es(h.operador_producao_nome||"Operador"),ct.replaceWith(qa)}}):h.operador_producao_nome?e.jsx("span",{style:{fontStyle:"italic",fontSize:"7pt"},children:Es(h.operador_producao_nome)}):be(null)})()})]},h.id)}),Array.from({length:Math.max(0,Xe-q.length)}).map((h,te)=>{const Ce=S*Xe+q.length+te;return e.jsx("tr",{style:{backgroundColor:Ce%2===1?G:"white"},children:Array.from({length:12}).map((X,Ve)=>e.jsx("td",{style:Pe,children:be(null)},Ve))},`empty-${S}-${te}`)})]}),e.jsx("tfoot",{children:e.jsxs("tr",{children:[e.jsx("td",{colSpan:8,style:{...Pe,textAlign:"right",fontWeight:700,backgroundColor:"#eef",fontSize:"8pt"},children:"Total:"}),e.jsx("td",{style:{...Pe,textAlign:"right",fontWeight:700,backgroundColor:"#eef",fontSize:"8pt"}
17,children:ye.toLocaleString("pt-BR")}),e.jsx("td",{colSpan:3,style:{...Pe,backgroundColor:"#eef"}})]})})]})}),dt=(q,S)=>e.jsxs("div",{className:"pp-page",children:[Re(),Ue(),Pt(q,S),e.jsxs("div",{style:{marginBottom:"8px"},children:[e.jsx("div",{style:{fontSize:"8.5pt",fontWeight:700,color:B,marginBottom:"2px",borderBottom:`2px solid ${B}`,paddingBottom:"1px",display:"inline-block"},children:"Observação"}),e.jsx("div",{style:{border:"1px solid #999",borderRadius:"2px",padding:"0 4px",marginTop:"2px"},children:Array.from({length:5}).map((h,te)=>e.jsx("div",{style:{borderBottom:te<4?"1px solid #ddd":"none",height:"17px"}},`obs-line-${S}-${te}`))})]}),Ze(S+1)]},`production-page-${S}`),St=q=>e.jsxs("div",{className:"pp-page pp-page--with-visto",children:[Re(),Ue(),e.jsx("div",{style:{fontSize:"9pt",fontWeight:700,color:B,marginBottom:"3px",borderBottom:`2px solid ${B}`,paddingBottom:"1px",display:"inline-block"},children:"Paradas do Processo"}),e.jsxs("table",{style:{width:"100%",borderCollapse:"collapse",marginBottom:"4px",marginTop:"2px"},children:[e.jsx("thead",{children:e.jsx("tr",{children:["Código da parada","Hora Inicial","Hora Final","Tempo total","Descrição","Assinatura"].map((S,h)=>e.jsx("th",{style:{...cr,backgroundColor:Se,color:sa,minWidth:h===4?"80px":void 0},children:S},h))})}),e.jsx("tbody",{children:(()=>{const h=Math.max(F.length,5);return Array.from({length:h}).map((te,Ce)=>{const X=F[Ce];return e.jsxs("tr",{style:{backgroundColor:Ce%2===1?G:"white",height:"26px"},children:[e.jsx("td",{style:{...Pe,height:"26px"},children:(X==null?void 0:X.codigo)||e.jsx(e.Fragment,{children:" "})}),e.jsx("td",{style:{...Pe,height:"26px"},children:(X==null?void 0:X.horaIni)||e.jsx(e.Fragment,{children:" "})}),e.jsx("td",{style:{...Pe,height:"26px"},children:(X==null?void 0:X.horaFim)||e.jsx(e.Fragment,{children:" "})}),e.jsx("td",{style:{...Pe,height:"26px"},children:(X==null?void 0:X.tempo)||e.jsx(e.Fragment,{children:" "})}),e.jsx("td",{style:{...Pe,height:"26px",textAlign:"left",paddingLeft:"4px"},children:(X==null?void 0:X.descricao)||e.jsx(e.Fragment,{children:" "})}),e.jsx("td",{style:{...Pe,height:"26px",padding:"1px",verticalAlign:"middle"},children:X!=null&&X.assinaturaUrl?e.jsx("img",{src:X.assinaturaUrl,alt:X.assinanteNome||"Assinatura",style:{height:"24px",maxWidth:"100%",objectFit:"contain",display:"block",margin:"0 auto"}}):X!=null&&X.assinanteNome?e.jsx("span",{style:{fontStyle:"italic",fontSize:"7pt"},children:X.assinanteNome}):e.jsx(e.Fragment,{children:" "})})]},`parada-${Ce}`)})})()})]}),e.jsxs("div",{style:{fontSize:"7pt",marginBottom:"8px",color:"#555",padding:"3px 4px",backgroundColor:"#f5f5f5",borderRadius:"2px"},children:[e.jsx("strong",{style:{color:B},children:"Códigos da parada:"})," ",w.length===0?"Nenhum código cadastrado":w.map((S,h)=>e.jsxs("span",{children:[S.codigo," - ",S.descricao,h<w.length-1?e.jsx(e.Fragment,{children:" â¢Â "}):null]},S.codigo))]}),e.jsxs("div",{style:{fontSize:"9pt",fontWeight:700,color:B,marginBottom:"2px",borderBottom:`2px solid ${B}`,paddingBottom:"1px",display:"inline-block"},children:["Justificativas de Alteração",ie.length>0?` (${ie.length})`:""]}),ie.length===0?e.jsxs(e.Fragment,{children:[e.jsx("div",{style:{border:"1px solid #999",borderRadius:"2px",padding:"0 4px",marginTop:"2px",marginBottom:"6px"},children:Array.from({length:5}).map((S,h)=>e.jsx("div",{style:{borderBottom:h<4?"1px solid #ddd":"none",height:"17px"}},`just-line-${h}`))}),e.jsxs("div",{style:{display:"flex",justifyContent:"space-between",fontSize:"8pt",padding:"0 2px"},children:[e.jsx("div",{children:"Responsável: ____________________________________"}),e.jsx("div",{children:"Data: ____/____/________"})]})]}):e.jsx("div",{style:{border:"1px solid #999",borderRadius:"2px",padding:"4px 8px",marginTop:"2px",marginBottom:"6px",fontSize:"8pt"},children:ie.map((S,h)=>{const te=g(S.user_id),Ce=S.created_at?I(new Date(S.created_at),"dd/MM/yyyy HH:mm"):"â";return e.jsxs("div",{style:{display:"flex",alignItems:"flex-end",gap:"8px",lineHeight:1.3,borderBottom:h<ie.length-1?"1px dotted #ddd":"none",paddingBottom:"4px",marginBottom:"4px"},children:[e.jsx("div",{style:{flex:1,minWidth:0},children:e.jsxs("div",{style:{whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:[e.jsxs("span",{style:{fontWeight:700},children:["Alteração N° ",h+1,":"]})," ",e.jsx("span",{style:{fontWeight:600},children:S.justificativa})]})}),e.jsxs("div",{style:{display:"flex",alignItems:"flex-end",gap:"6px",flexShrink:0},children:[e.jsxs("div",{style:{textAlign:"center",minWidth:"120px"},children:[e.jsx("div",{style:{height:"26px",display:"flex",alignItems:"flex-end",justifyContent:"center",borderBottom:"1px solid #333"},children:te?e.jsx("img",{src:te,alt:S.user_nome||"Assinatura",style:{maxHeight:"26px",maxWidth:"120px",objectFit:"contain"}}):null}),e.jsxs("div",{style:{fontSize:"6.5pt",color:"#333",marginTop:"1px"},children:["Responsável: ",S.user_nome||"â",S.user_codigo?` (${S.user_codigo})`:""]})]}),e.jsxs("div",{style:{textAlign:"center",minWidth:"80px"},children:[e.jsx("div",{style:{height:"26px",display:"flex",alignItems:"flex-end",justifyContent:"center",borderBottom:"1px solid #333",fontSize:"7.5pt"},children:Ce}),e.jsx("div",{style:{fontSize:"6.5pt",color:"#333",marginTop:"1px"},children:"Data"})]})]})]},`just-${h}`)})}),Ze(q,!0)]},"process-page");return e.jsxs("div",{className:"hidden print:block print-programacao",style:{backgroundColor:"white",color:"#1a1a2e",padding:"0",fontFamily:"'Inter', 'Segoe UI', Arial, Helvetica, sans-serif",fontSize:"8pt",lineHeight:1.4,width:"100%"},children:[e.jsx("style",{children:`@media print { ${Si(xe)} } 18 .pp-page { 19 position: relative; 20 display: flex; 21 flex-direction: column; 22 min-height: ${ce}mm; 23 max-height: ${ce}mm; 24 height: ${ce}mm; 25 box-sizing: border-box; 26 overflow: hidden; 27 } 28 @media print { 29 .pp-page { 30 min-height: auto; 31 max-height: none; 32 height: auto; 33 } 34 } 35 .pp-page-bottom { margin-top: auto; padding-top: 6px; } 36 .pp-page--with-visto .pp-page-bottom { padding-top: 8px; } 37 @media print { 38 .pp-page { break-inside: avoid; page-break-inside: avoid; } 39 .pp-page + .pp-page { break-before: page; page-break-before: always; } 40 .pp-page:last-child { break-after: avoid; page-break-after: avoid; } 41 } 42 .pp-production-table { flex: 0 0 auto; margin-bottom: 6px; } 43 .pp-production-table table { width: 100%; border-collapse: collapse; table-layout: fixed; } 44 .pp-production-table tbody tr { height: ${he}px !important; max-height: ${he}px !important; min-height: ${he}px !important; } 45 .pp-production-table tbody td { 46 height: ${he}px !important; 47 max-height: ${he}px !important; 48 min-height: ${he}px !important; 49 padding: 0 3px !important; 50 line-height: 1.05 !important; 51 vertical-align: middle !important; 52 box-sizing: border-box !important; 53 overflow: hidden; 54 white-space: nowrap; 55 text-overflow: ellipsis; 56 } 57 .pp-production-table .pp-cell-text { 58 display: block; 59 width: 100%; 60 max-height: ${he-2}px; 61 line-height: ${he-2}px; 62 overflow: hidden; 63 white-space: nowrap; 64 text-overflow: ellipsis; 65 } 66 .pp-production-table thead tr { height: ${he}px !important; max-height: ${he}px !important; min-height: ${he}px !important; } 67 .pp-production-table thead th { height: ${he}px !important; max-height: ${he}px !important; min-height: ${he}px !important; line-height: 1.0 !important; padding: 0 3px !important; box-sizing: border-box !important; vertical-align: middle !important; } 68 .pp-production-table tfoot td { height: ${he}px !important; padding: 0 3px !important; line-height: 1.05 !important; } 69 .pp-signatures-footer { font-size: 8pt; padding: 0 2px; } 70 .pp-page-num { text-align: center; font-size: 7.5pt; color: #555; padding-top: 4px; } 71 `}
71),ma.map((q,S)=>dt(q,S)),St(Ye)]})}const cr={border:"1px solid #333",padding:"3px 4px",fontSize:"7pt",fontWeight:600,textAlign:"center",letterSpacing:"0.2px"},Pe={border:"1px solid #ccc",borderLeft:"1px solid #ddd",borderRight:"1px solid #ddd",padding:"2px 4px",fontSize:"7.5pt",lineHeight:1.05};function yn({open:i,onOpenChange:x,documentoLabel:j,onConfirm:u}){const[L,y]=d.useState(""),[k,M]=d.useState(null);d.useEffect(()=>{i&&(y(""),M(null))},[i]);const Q=()=>{if(L.trim().length<5){M("Descreva o motivo da devolução (mÃnimo 5 caracteres).");return}u(L.trim())};return e.jsx(st,{open:i,onOpenChange:x,children:e.jsxs(ot,{className:"sm:max-w-md",children:[e.jsxs(Nt,{children:[e.jsxs(wt,{className:"flex items-center gap-2",children:[e.jsx(yt,{className:"h-5 w-5 text-destructive"}),"Devolver Programação à PCP"]}),e.jsx(Rs,{children:"Informe o motivo da devolução. A assinatura do PCP será removida e a programação retornará para ajustes."})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"rounded-md border bg-muted/40 p-3 text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Documento: "}),e.jsx("span",{className:"font-medium",children:j})]}),e.jsxs("div",{children:[e.jsx(Le,{htmlFor:"motivo-devolucao",children:"Motivo da devolução *"}),e.jsx(Fs,{id:"motivo-devolucao",value:L,onChange:P=>y(P.target.value),placeholder:"Ex.: Inconsistência na quantidade do pedido X / Falta de matéria-primaâ¦",rows:4,autoFocus:!0})]}),k&&e.jsxs(Fa,{variant:"destructive",children:[e.jsx(ga,{className:"h-4 w-4"}),e.jsx(Ia,{children:k})]})]}),e.jsxs(Is,{children:[e.jsx(O,{variant:"ghost",onClick:()=>x(!1),children:"Cancelar"}),e.jsxs(O,{variant:"destructive",onClick:Q,children:[e.jsx(yt,{className:"h-4 w-4 mr-1"}),"Devolver"]})]})]})})}async function mr(i,x){if(x.length===0)return[];const j=[];for(let L=0;L<x.length;L+=100)j.push(x.slice(L,L+100));const u=[];for(const L of j){const{data:y}=await f.from("audit_log").select("*").eq("table_name",i).in("record_id",L).order("changed_at",{ascending:!0});y==null||y.forEach(k=>u.push(k))}return u}function zs(i,x){let j=null,u=!1;for(const L of i){if(new Date(L.changed_at).getTime()>x)break;L.action==="INSERT"?(j={...L.new_data||{}},u=!1):L.action==="UPDATE"?(j={...j||{},...L.new_data||{}},u=!1):L.action==="DELETE"&&(u=!0)}return u?null:j}async function Nn(i){const{data:x}=await f.from("audit_log").select("old_data,new_data").eq("table_name","programacao_diaria_itens").or(`new_data->>programacao_id.eq.${i},old_data->>programacao_id.eq.${i}`),j=new Set;x==null||x.forEach(L=>{var M,Q;const y=(M=L.new_data)==null?void 0:M.pedido_id,k=(Q=L.old_data)==null?void 0:Q.pedido_id;y&&j.add(String(y)),k&&j.add(String(k))});const{data:u}=await f.from("programacao_diaria_itens").select("pedido_id").eq("programacao_id",i);return u==null||u.forEach(L=>L.pedido_id&&j.add(String(L.pedido_id))),Array.from(j)}async function ur(i){const x=Array.from(new Set(i.map(z=>z.racao_id).filter(Boolean))),j=Array.from(new Set(i.map(z=>z.cliente_id).filter(Boolean))),u=Array.from(new Set(i.map(z=>z.silo_expedicao_id).filter(Boolean))),[L,y,k]=await Promise.all([x.length?f.from("racoes").select("id,nome,codigo").in("id",x):Promise.resolve({data:[]}),j.length?f.from("clientes").select("id,nome").in("id",j):Promise.resolve({data:[]}),u.length?f.from("silos_expedicao").select("id,nome").in("id",u):Promise.resolve({data:[]})]),M=new Map((L.data||[]).map(z=>[z.id,z])),Q=new Map((y.data||[]).map(z=>[z.id,z])),P=new Map((k.data||[]).map(z=>[z.id,z]));for(const z of i)z.racao_id&&M.has(z.racao_id)&&(z.racao_nome=M.get(z.racao_id).nome),z.cliente_id&&Q.has(z.cliente_id)&&(z.cliente_nome=Q.get(z.cliente_id).nome),z.silo_expedicao_id&&P.has(z.silo_expedicao_id)&&(z.silo_nome=P.get(z.silo_expedicao_id).nome)}async function wn(i){const[{data:x},{data:j}]=await Promise.all([f.from("programacoes_diarias").select("*").eq("id",i).maybeSingle(),f.from("programacao_diaria_itens").select("*").eq("programacao_id",i)]),u=await Nn(i),[L,y,k]=await Promise.all([mr("programacoes_diarias",[i]),(async()=>{const{data:P}=await f.from("audit_log").select("*").eq("table_name","programacao_diaria_itens").or(`new_data->>programacao_id.eq.${i},old_data->>programacao_id.eq.${i}`).order("changed_at",{ascending:!0});return P||[]})(),mr("pedidos",u)]),M=new Map;for(const P of k){const z=M.get(P.record_id)||[];z.push(P),M.set(P.record_id,z)}const Q=new Map;if(u.length){const P=[];for(let z=0;z<u.length;z+=100)P.push(u.slice(z,z+100));for(const z of P){const{data:H}=await f.from("pedidos").select("*").in("id",z);H==null||H.forEach(ne=>Q.set(ne.id,ne))}}return{progLogs:L,itensLogs:y,pedidoLogs:M,pedidoIds:u,progAtual:x,itensAtuais:j||[],pedidosAtuais:Q}}function Pn(i){const x=[],j=(y,k)=>
71{x.push({ts:y,label:new Date(y).toLocaleString("pt-BR"),resumo:k})};for(const y of i.progLogs)j(y.changed_at,y.action==="INSERT"?"Programação criada":y.action==="DELETE"?"Programação excluÃda":"Cabeçalho alterado");for(const y of i.itensLogs){const k=y.action==="INSERT"?"Pedido adicionado":y.action==="DELETE"?"Pedido removido":"VÃnculo alterado";j(y.changed_at,k)}for(const[,y]of i.pedidoLogs)for(const k of y)k.action==="UPDATE"?j(k.changed_at,"Pedido alterado"):k.action==="DELETE"&&j(k.changed_at,"Pedido excluÃdo");const u=new Map;for(const y of x)u.has(y.ts)||u.set(y.ts,y);return Array.from(u.values()).sort((y,k)=>k.ts.localeCompare(y.ts))}async function Sn(i,x){if(x===null){const M=new Set(i.itensAtuais.map(P=>P.pedido_id)),Q=Array.from(M).map(P=>i.pedidosAtuais.get(P)).filter(Boolean).map(P=>({...P}));return await ur(Q),{programacao:i.progAtual,pedidos:Q.sort((P,z)=>(P.prioridade||999)-(z.prioridade||999)),versao:{label:"Versão Atual",ts:null}}}const j=new Date(x).getTime(),u=zs(i.progLogs,j)||i.progAtual,L=new Set;for(const M of i.itensLogs)L.add(M.record_id);const y=new Set;for(const M of L){const Q=i.itensLogs.filter(z=>z.record_id===M),P=zs(Q,j);P&&P.pedido_id&&y.add(String(P.pedido_id))}const k=[];for(const M of y){const Q=i.pedidoLogs.get(M)||[],P=zs(Q,j);P?k.push({...P}):i.pedidosAtuais.has(M)&&k.push({...i.pedidosAtuais.get(M),_absent:!0})}return await ur(k),{programacao:u,pedidos:k.sort((M,Q)=>(M.prioridade||999)-(Q.prioridade||999)),versao:{label:new Date(x).toLocaleString("pt-BR"),ts:x}}}const $e=i=>String(i??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">"),pr=i=>{const x=Number(i);return isFinite(x)?x.toLocaleString("pt-BR",{minimumFractionDigits:0,maximumFractionDigits:0}):"â"},Cn=i=>{if(!i)return"â";const x=String(i).slice(0,10),[j,u,L]=x.split("-");return j&&u&&L?`${L}/${u}/${j}`:x};function Mn(i){const x=i.reduce((u,L)=>u+(Number(L.peso_solicitado)||0),0);return i.length?` 72 <table style="width:100%;border-collapse:collapse;"> 73 <thead> 74 <tr style="background:#f3f4f6;"> 75 <th style="padding:4px 5px;border:1px solid #e5e7eb;font-size:9px;">Prio</th> 76 <th style="padding:4px 5px;border:1px solid #e5e7eb;text-align:left;font-size:9px;">Nº Grade</th> 77 <th style="padding:4px 5px;border:1px solid #e5e7eb;text-align:left;font-size:9px;">Cliente</th> 78 <th style="padding:4px 5px;border:1px solid #e5e7eb;text-align:left;font-size:9px;">Ração</th> 79 <th style="padding:4px 5px;border:1px solid #e5e7eb;text-align:right;font-size:9px;">Peso (kg)</th> 80 <th style="padding:4px 5px;border:1px solid #e5e7eb;font-size:9px;">Silo</th> 81 <th style="padding:4px 5px;border:1px solid #e5e7eb;font-size:9px;">Status</th> 82 </tr> 83 </thead> 84 <tbody> 85 ${i.map(u=>` 86 <tr${za(u)&&!u.cancelado?' style="background:#fef2f2;"':""}> 87 <td style="padding:3px 5px;border:1px solid #e5e7eb;text-align:center;font-size:9px;">${$e(u.prioridade??"â")}</td> 88 <td style="padding:3px 5px;border:1px solid #e5e7eb;font-family:monospace;font-size:9px;">${$e(u.numero_grade||"â")}</td> 89 <td style="padding:3px 5px;border:1px solid #e5e7eb;font-size:9px;">${$e(u.cliente_nome||u.cliente_id||"â")}</td> 90 <td style="padding:3px 5px;border:1px solid #e5e7eb;font-size:9px;">${$e(u.racao_nome||u.racao_id||"â")}</td> 91 <td style="padding:3px 5px;border:1px solid #e5e7eb;text-align:right;font-size:9px;font-weight:600;">${$e(pr(u.peso_solicitado))}</td> 92 <td style="padding:3px 5px;border:1px solid #e5e7eb;text-align:center;font-size:9px;">${$e(u.silo_nome||"â")}</td> 93 <td style="padding:3px 5px;border:1px solid #e5e7eb;text-align:center;font-size:9px;">${u.cancelado?"Cancelado":za(u)?`<span style="color:#b91c1c;font-weight:700;">BLOQUEADO PELA QUALIDADE</span><br/><span style="color:#b91c1c;">${$e(Ts(u)||"")}${u.bloqueio_motivo?`: ${$e(u.bloqueio_motivo)}`:""}</span>`:$e(u.status_producao||"pendente")}</td> 94 </tr>`).join("")} 95 <tr style="background:#f9fafb;font-weight:700;"> 96 <td colspan="4" style="padding:4px 5px;border:1px solid #e5e7eb;text-align:right;font-size:9px;">TOTAL</td> 97 <td style="padding:4px 5px;border:1px solid #e5e7eb;text-align:right;font-size:9px;">${$e(pr(x))}</td> 98 <td colspan="2" style="padding:4px 5px;border:1px solid #e5e7eb;font-size:9px;"></td> 99 </tr> 100 </tbody> 101 </table>`:'<p style="font-size:10px;color:#6b7280;font-style:italic;">Nenhum pedido nesta versão.</p>'}function Ls(i,x){const j=i.programacao||{},u=vr(i.pedidos),L=u.length?`<div style="border:1.5px solid #b91c1c;background:#fef2f2;border-radius:6px;padding:6px 8px;margin-bottom:8px;font-size:10px;color:#b91c1c;"> 102 <strong>Programação NÃO liberada para produção:</strong> ${u.length} pedido(s) bloqueado(s) pela Qualidade â 103 ${$e(u.map(k=>`${k.identificacao} (${k.label}${k.motivo?`: ${k.motivo}`:""})`).join("; "))} 104 </div>`:"",y=` 105 <div style="display:grid;grid-template-columns:repeat(3,1fr);gap:5px;margin-bottom:10px;"> 106 <div style="border:1px solid #e5e7eb;border-radius:6px;padding:5px 7px;"> 107 <div style="font-size:8px;text-transform:uppercase;color:#6b7280;font-weight:600;">Nº Programação</div> 108 <div style="font-size:10px;font-weight:600;">${$e(j.numero||"â")}${j.grade_numero?` (${j.grade_numero}ª Grade)`:""}</div> 109 </div> 110 <div style="border:1px solid #e5e7eb;border-radius:6px;padding:5px 7px;"> 111 <div style="font-size:8px;text-transform:uppercase;color:#6b7280;font-weight:600;">Data Produção</div> 112 <div style="font-size:10px;font-weight:600;">${$e(Cn(j.data_producao))}</div> 113 </div> 114 <div style="border:1px solid #e5e7eb;border-radius:6px;padding:5px 7px;"> 115 <div style="font-size:8px;text-transform:uppercase;color:#6b7280;font-weight:600;">Status</div> 116 <div style="font-size:10px;font-weight:600;">${$e(j.status_liberacao||"â")}${u.length?' <span style="color:#b91c1c;">
116(liberação inválida â pendência de Qualidade)</span>':""}</div> 117 </div> 118 </div>`;return` 119 <h2 style="font-size:13px;margin:14px 0 6px 0;color:#1a1a2e;border-bottom:1.5px solid #e5e7eb;padding-bottom:4px;">${$e(x)}</h2> 120 ${L} 121 ${y} 122 ${Mn(i.pedidos)} 123 `}const yr="/logo-3bs.png";function xr(i){const x=i.programacao||{};Jt({title:`Programação Nº ${x.numero||""} â ${i.versao.label}`,subtitle:i.versao.ts?`Estado em ${i.versao.label}`:"Estado atual",orientation:"portrait",content:Ls(i,i.versao.label),customLogoUrl:yr})}function An(i,x){const j=new Map(i.map(M=>[M.id,M])),u=new Map(x.map(M=>[M.id,M])),L=new Set([...j.keys(),...u.keys()]),y=[],k=[{k:"prioridade",label:"Prioridade"},{k:"peso_solicitado",label:"Peso (kg)"},{k:"racao_nome",label:"Ração"},{k:"cliente_nome",label:"Cliente"},{k:"silo_nome",label:"Silo"},{k:"numero_grade",label:"Nº Grade"},{k:"cancelado",label:"Cancelado"},{k:"status_producao",label:"Status"}];for(const M of L){const Q=j.get(M),P=u.get(M),z=P||Q,H=`${$e(z.numero_grade||"â")} ⢠${$e(z.cliente_nome||"â")} ⢠${$e(z.racao_nome||"â")}`;if(!Q&&P)y.push(`<li><strong style="color:#15803d;">Adicionado:</strong> ${H}</li>`);else if(Q&&!P)y.push(`<li><strong style="color:#b91c1c;">Removido:</strong> ${H}</li>`);else if(Q&&P){const ne=[];for(const Y of k){const ie=Q[Y.k],E=P[Y.k];JSON.stringify(ie??null)!==JSON.stringify(E??null)&&ne.push(`${$e(Y.label)}: <span style="text-decoration:line-through;color:#b91c1c;">${$e(ie??"â")}</span> â <span style="color:#15803d;">${$e(E??"â")}</span>`)}ne.length&&y.push(`<li><strong>Alterado:</strong> ${H}<ul style="margin-left:16px;list-style:circle;">${ne.map(Y=>`<li>${Y}</li>`).join("")}</ul></li>`)}}return y.length?`<ul style="font-size:10px;margin-left:18px;">${y.join("")}</ul>`:'<p style="font-size:10px;color:#6b7280;font-style:italic;">Sem diferenças nos pedidos entre as duas versões.</p>'}function qn(i,x){const j=x.programacao||i.programacao||{},u=` 124 ${Ls(i,`Antes â ${i.versao.label}`)} 125 ${Ls(x,`Depois â ${x.versao.label}`)} 126 <h2 style="font-size:13px;margin:14px 0 6px 0;color:#1a1a2e;border-bottom:1.5px solid #e5e7eb;padding-bottom:4px;">Diferenças</h2> 127 ${An(i.pedidos,x.pedidos)} 128 `;Jt({title:`Programação Nº ${j.numero||""} â Comparativo`,subtitle:`${i.versao.label} â ${x.versao.label}`,orientation:"portrait",content:u,customLogoUrl:yr})}const bt="__atual__";function kn({progId:i,onClose:x}
128){const j=!!i,[u,L]=d.useState(bt),[y,k]=d.useState(bt),{data:M,isLoading:Q}=ve({queryKey:["prog-snapshot-data",i],queryFn:()=>wn(i),enabled:j}),P=d.useMemo(()=>M?Pn(M):[],[M]),z=d.useMemo(()=>{var xe,De;if(!M)return[];const E=[];for(const oe of M.progLogs)E.push({ts:oe.changed_at,tipo:oe.action==="INSERT"?"Criação":oe.action==="DELETE"?"Exclusão":"Cabeçalho",descricao:oe.action==="INSERT"?"Programação criada":oe.action==="DELETE"?"Programação excluÃda":"Cabeçalho da programação alterado"});for(const oe of M.itensLogs){const Z=(((xe=oe.new_data)==null?void 0:xe.pedido_id)||((De=oe.old_data)==null?void 0:De.pedido_id)||"â").slice(0,8);E.push({ts:oe.changed_at,tipo:oe.action==="INSERT"?"Pedido +":oe.action==="DELETE"?"Pedido â":"VÃnculo",descricao:oe.action==="INSERT"?`Pedido ${Z} adicionado`:oe.action==="DELETE"?`Pedido ${Z} removido`:`VÃnculo alterado (${Z})`})}for(const[,oe]of M.pedidoLogs)for(const Z of oe){if(Z.action!=="UPDATE")continue;const A=Z.old_data||{},R=Z.new_data||{},n=["peso_solicitado","prioridade","racao_id","cliente_id","silo_expedicao_id","numero_grade","cancelado","status_producao"].filter(g=>JSON.stringify(A[g])!==JSON.stringify(R[g]));n.length!==0&&E.push({ts:Z.changed_at,tipo:"Pedido",descricao:`Pedido ${R.numero||(Z.record_id||"").slice(0,8)} â alterado: ${n.join(", ")}`})}return E.sort((oe,Z)=>Z.ts.localeCompare(oe.ts))},[M]);async function H(E){return M?Sn(M,E===bt?null:E):null}async function ne(){const E=await H(u);E&&xr(E)}async function Y(){const E=await H(y);E&&xr(E)}async function ie(){const[E,xe]=await Promise.all([H(u),H(y)]);E&&xe&&qn(E,xe)}return e.jsx(st,{open:j,onOpenChange:E=>{E||x()},children:e.jsxs(ot,{className:"max-w-3xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Nt,{children:e.jsxs(wt,{className:"flex items-center gap-2",children:[e.jsx(fr,{className:"h-5 w-5"})," Histórico da Programação"]})}),Q?e.jsx("p",{className:"text-sm text-muted-foreground py-6 text-center",children:"Carregando históricoâ¦"}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"rounded-md border bg-muted/30 p-3 space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-muted-foreground",children:"Versão A (antes)"}),e.jsxs(Oa,{value:u,onValueChange:L,children:[e.jsx(Ba,{children:e.jsx(Ka,{})}),e.jsxs(Qa,{children:[e.jsx(ca,{value:bt,children:"Versão Atual"}),P.map(E=>e.jsxs(ca,{value:E.ts,children:[E.label," â ",E.resumo]},`a-${E.ts}`))]})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-muted-foreground",children:"Versão B (depois)"}),e.jsxs(Oa,{value:y,onValueChange:k,children:[e.jsx(Ba,{children:e.jsx(Ka,{})}),e.jsxs(Qa,{children:[e.jsx(ca,{value:bt,children:"Versão Atual"}),P.map(E=>e.jsxs(ca,{value:E.ts,children:[E.label," â ",E.resumo]},`b-${E.ts}`))]})]})]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(O,{size:"sm",variant:"outline",onClick:ne,children:[e.jsx(nt,{className:"h-4 w-4 mr-1"})," Imprimir A"]}),e.jsxs(O,{size:"sm",variant:"outline",onClick:Y,children:[e.jsx(nt,{className:"h-4 w-4 mr-1"})," Imprimir B"]}),e.jsxs(O,{size:"sm",onClick:ie,children:[e.jsx(hn,{className:"h-4 w-4 mr-1"})," Imprimir Comparativo A â B"]})]})]}),e.jsxs("div",{children:[e.jsxs("h4",{className:"text-sm font-semibold mb-2",children:["Linha do tempo (",z.length,")"]}),z.length===0?e.jsx("p",{className:"text-xs text-muted-foreground italic",children:"Nenhum evento registrado. O histórico passa a ser registrado a partir da ativação da auditoria â alterações anteriores não são recuperáveis."}):e.jsx(Mi,{className:"max-h-[40vh] pr-3",children:e.jsx("div",{className:"space-y-2",children:z.map((E,xe)=>e.jsxs("div",{className:"flex items-start gap-2 border rounded-md p-2 text-sm",children:[e.jsx(J,{variant:"secondary",className:"shrink-0",children:E.tipo}),e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"text-xs text-muted-foreground font-mono",children:new Date(E.ts).toLocaleStr
128ing("pt-BR")}),e.jsx("div",{children:E.descricao})]})]},xe))})})]})]})]})})}function $n({value:i,onChange:x,scope:j,disabled:u,label:L="Receituário"}){const{toast:y}=Xt(),[k,M]=d.useState(!1),[Q,P]=d.useState(!1),z=d.useRef(null),H=async ie=>{var De;const E=(De=ie.target.files)==null?void 0:De[0];if(!E)return;if(!["application/pdf","image/jpeg","image/png","image/jpg"].includes(E.type)){y({title:"Arquivo inválido",description:"Envie PDF, JPG ou PNG.",variant:"destructive"});return}if(E.size>5*1024*1024){y({title:"Arquivo muito grande",description:"Máximo 5MB.",variant:"destructive"});return}M(!0);try{const oe=E.name.replace(/[^a-zA-Z0-9._-]/g,"_"),A=`pedidos/${j||"geral"}/${Date.now()}_${oe}`,{error:R}=await f.storage.from("receituarios").upload(A,E,{upsert:!1});if(R)throw R;x({path:A,nome:E.name}),y({title:"Receituário anexado!"})}catch(oe){y({title:"Erro ao anexar",description:oe.message,variant:"destructive"})}finally{M(!1),z.current&&(z.current.value="")}},ne=async()=>{i.path&&P(!0)},Y=()=>{x({path:null,nome:null})};return e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(Le,{className:"text-xs",children:L}),i.path?e.jsxs("div",{className:"flex items-center gap-2 rounded-md border bg-muted/30 p-2",children:[e.jsx(_r,{className:"h-4 w-4 text-primary shrink-0"}),e.jsxs("button",{type:"button",onClick:ne,className:"text-xs text-primary underline truncate flex-1 text-left",children:[i.nome||"Ver arquivo",e.
128jsx(Ai,{className:"h-3 w-3 inline ml-1"})]}),!u&&e.jsx(O,{type:"button",variant:"ghost",size:"sm",onClick:Y,className:"h-6 w-6 p-0 text-destructive hover:text-destructive",children:e.jsx(qi,{className:"h-3.5 w-3.5"})})]}):e.jsxs("div",{children:[e.jsx("input",{ref:z,type:"file",accept:"application/pdf,image/jpeg,image/png",onChange:H,className:"hidden"}),e.jsx(O,{type:"button",variant:"outline",size:"sm",className:"h-8 text-xs gap-1.5 w-full",disabled:u||k,onClick:()=>{var ie;return(ie=z.current)==null?void 0:ie.click()},children:k?e.jsxs(e.Fragment,{children:[e.jsx(Os,{className:"h-3 w-3 animate-spin"})," Enviandoâ¦"]}):e.jsxs(e.Fragment,{children:[e.jsx(ki,{className:"h-3 w-3"})," Anexar Receituário (PDF/JPG/PNG)"]})})]}),e.jsx($i,{path:i.path,nome:i.nome,open:Q,onOpenChange:P,title:L})]})}function Dn({open:i,onOpenChange:x,onConfirmed:j,racaoNome:u}){const{toast:L}=Xt(),[y,k]=d.useState(""),[M,Q]=d.useState(""),[P,z]=d.useState(""),[H,ne]=d.useState(null),[Y,ie]=d.useState(!1),[E,xe]=d.useState([]);d.useEffect(()=>{i&&(k(""),Q(""),z(""),ne(null),(async()=>{const{data:Z}=await f.from("profiles").select("id, full_name, codigo, access_profile_id").eq("is_approved",!0).order("full_name"),{data:A}=await f.from("user_roles").select("user_id, role"),{data:R}=await f.from("access_profile_permissions").select("profile_id, page_key, can_access").eq("page_key","qualidade").eq("can_access",!0),ee=new Set((A||[]).filter(w=>w.role==="master").map(w=>w.user_id)),n=new Set((R||[]).map(w=>w.profile_id)),g=(Z||[]).filter(w=>ee.has(w.id)||w.access_profile_id&&n.has(w.access_profile_id));xe(g)})())},[i]);const De=d.useMemo(()=>E.find(Z=>Z.id===M),[E,M]),oe=async()=>{if(!y.trim()){ne("Informe o motivo da liberação sem receituário.");return}if(!M){ne("Selecione o liberador da Qualidade.");return}if(!P.trim()){ne("Digite a senha de assinatura do liberador.");return}ie(!0),ne(null);try{const{data:Z,error:A}=await f.rpc("verificar_senha_liberador_qualidade",{_liberador_id:M,_senha:P});if(A)throw A;const R=Z;if(!(R!=null&&R.ok)){ne((R==null?void 0:R.mensagem)||"Falha na verificação");return}j({motivo:y.trim(),liberador_id:R.liberador_id,liberador_nome:R.liberador_nome,liberador_codigo:R.liberador_codigo??null}),x(!1),L({title:"Liberação registrada",description:`Liberado por ${R.liberador_nome}.`})}catch(Z){ne(Z.message||"Erro ao verificar senha")}finally{ie(!1)}};return e.jsx(st,{open:i,onOpenChange:x,children:e.jsxs(ot,{className:"sm:max-w-md",children:[e.jsxs(Nt,{children:[e.jsxs(wt,{className:"flex items-center gap-2",children:[e.jsx(To,{className:"h-5 w-5 text-destructive"})," Liberação sem Receituário"]}),e.jsxs(Rs,{children:["Esta ração",u?` (${u})`:""," é ",e.jsx("strong",{children:"medicada"}),". Para criar o pedido sem o receituário, é necessária a liberação assinada por um usuário da Qualidade."]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(Le,{children:"Motivo da liberação"}),e.jsx(Fs,{value:y,onChange:Z=>k(Z.target.value),rows:3,placeholder:"Ex.: Receituário será entregue até a produção."})]}),e.jsxs("div",{children:[e.jsx(Le,{children:"Liberador (Qualidade / Master)"}),e.jsxs(Oa,{value:M,onValueChange:Q,children:[e.jsx(Ba,{children:e.jsx(Ka,{placeholder:"Selecioneâ¦"})}),e.jsxs(Qa,{children:[E.length===0&&e.jsx("div",{className:"p-2 text-xs text-muted-foreground",children:"Nenhum usuário Qualidade encontrado."}),E.map(Z=>e.jsxs(ca,{value:Z.id,children:[Z.full_name||"(sem nome)",Z.codigo?` â ${Z.co
128digo}`:""]},Z.id))]})]})]}),De&&e.jsxs("div",{children:[e.jsx(Le,{children:"Senha de assinatura do liberador"}),e.jsx(Ca,{type:"password",value:P,onChange:Z=>z(Z.target.value),onKeyDown:Z=>{Z.key==="Enter"&&oe()},autoComplete:"off",placeholder:"â¢â¢â¢â¢â¢â¢"})]}),H&&e.jsxs(Fa,{variant:"destructive",children:[e.jsx(ga,{className:"h-4 w-4"}),e.jsx(Ia,{children:H})]})]}),e.jsxs(Is,{children:[e.jsx(O,{variant:"ghost",onClick:()=>x(!1),disabled:Y,children:"Cancelar"}),e.jsx(O,{onClick:oe,disabled:Y,children:Y?e.jsxs(e.Fragment,{children:[e.jsx(Os,{className:"h-4 w-4 mr-1 animate-spin"})," Verificandoâ¦"]}):e.jsxs(e.Fragment,{children:[e.jsx(To,{className:"h-4 w-4 mr-1"})," Confirmar Liberação"]})})]})]})})}function En(){const[i,x]=d.useState(new Set),{data:j=[],isLoading:u}=ve({queryKey:["consumo-cliente-pedidos-vigentes"],queryFn:async()=>{const{data:A,error:R}=await f.from("pedidos").select("id, numero_pedido, peso_solicitado, racao_id, data_producao, cliente_id").eq("cancelado",!1).in("status_producao",["pendente","em_producao"]).not("racao_id","is",null).order("data_producao");if(R)throw R;return A}}),L=d.useMemo(()=>[...new Set(j.map(A=>A.cliente_id))],[j]),y=d.useMemo(()=>[...new Set(j.map(A=>A.racao_id))],[j]),{data:k=[]}=ve({queryKey:["consumo-cliente-clientes",L],queryFn:async()=>{if(L.length===0)return[];const{data:A,error:R}=await f.from("clientes").select("id, nome").in("id",L);if(R)throw R;return A},enabled:L.length>0}),{data:M=[]}=ve({queryKey:["consumo-cliente-racoes",y],queryFn:async()=>{if(y.length===0)return[];const{data:A,error:R}=await f.from("racoes").select("id, nome, peso_padrao").in("id",y);if(R)throw R;return A},enabled:y.length>0}),{data:Q=[]}=ve({queryKey:["consumo-cliente-versoes",y],queryFn:async()=>{if(y.length===0)return[];const{data:A,error:R}=await f.from("racao_formula_versoes").select("id, racao_id, peso_padrao_snapshot").in("racao_id",y).eq("is_active",!0);if(R)throw R;return A},enabled:y.length>0}),P=d.useMemo(()=>Q.map(A=>A.id),[Q]),{data:z=[]}=ve({queryKey:["consumo-cliente-mps",P],queryFn:async()=>{if(P.length===0)return[];const A=1e3;let R=[],ee=0;for(;;){const{data:n,error:g}=await f.from("racao_materias_primas").select("racao_id, versao_id, codigo_mp, nome_mp, quantidade").in("versao_id",P).range(ee,ee+A-1);if(g)throw g;if(!n||n.length===0||(R=R.concat(n),n.length<A))break;ee+=A}return R},enabled:P.length>0}),{data:H}=ve({queryKey:["config-peso-padrao"],queryFn:async()=>{const{data:A}=await f.from("configuracoes").select("valor").eq("chave","peso_padrao_global").maybeSingle();return A!=null&&A.valor?Number(A.valor):2e3}}),{consumoPorPedido:ne,clienteGroups:Y}=d.useMemo(()=>{const A=[];for(const n of j){const g=Number(n.peso_solicitado)||0,w=k.find(ye=>ye.id===n.cliente_id),v=M.find(ye=>ye.id===n.racao_id),V=Q.find(ye=>ye.racao_id===n.racao_id),F=(V==null?void 0:V.peso_padrao_snapshot)||(v==null?void 0:v.peso_padrao)||H||2e3,ae=[];if(V&&F>0){const ye=z.filter(Se=>Se.versao_id===V.id),me=g/Number(F);for(const Se of ye)ae.push({codigo_mp:Se.codigo_mp||"â",nome_mp:Se.nome_mp||"Sem nome",qtd:(Number(Se.quantidade)||0)*me})}A.push({pedidoId:n.id,numeroPedido:n.numero_pedido,clienteNome:(w==null?void 0:w.nome)||"â",clienteId:n.cliente_id,racaoNome:(v==null?void 0:v.nome)||"â",pesoSolicitado:g,dataProducao:n.data_producao,materias:ae.sort((ye,me)=>ye.nome_mp.localeCompare(me.nome_mp))})}const R=new Map;for(const n of A){const g=R.get(n.clienteId);g?(g.pedidos.push(n),g.totalPeso+=n.pesoSolicitado):R.set(n.clienteId,{clienteNome:n.clienteNome,pedidos:[n],totalPeso:n.pesoSolicitado,materiasSomadas:[]})}for(const[,n]of R){const g=new Map;for(const w of n.pedidos)for(const v of w.materias){const V=v.nome_mp.toLowerCase(),F=g.get(V);F?F.qtd+=v.qtd:g.set(V,{codigo_mp:v.codigo_mp,nome_mp:v.nome_mp,qtd:v.qtd})}n.materiasSomadas=[...g.values()].sort((w,v)=>w.nome_mp.localeCompare(v.nome_mp))}const ee=[...R.entries()].sort((n,g)=>n[1].clienteNome.localeCompare(g[1].clienteNome));return{consumoPorPedido:A,clienteGroups:ee}},[j,k,M,Q,z,H]),ie=A=>{x(R=>{const ee=new Set(R);return ee.has(A)?ee.delete(A):ee.add(A),ee})},E=()=>{x(new Set(Y.map(([A])=>A)))},xe=()=>x(new Set),De=u,oe=()=>{const A=[["Consumo por Pedido de Cliente â Pedidos Vigentes"],[]];for(const[,n]of Y){A.push([`Cliente: ${n.clienteNome}
128`,"","",`Total: ${n.totalPeso.toLocaleString("pt-BR")} kg`]),A.push(["Pedido","Ração","Data","Peso (kg)","Cód MP","Matéria Prima","Qtd (kg)"]);for(const g of n.pedidos)if(g.materias.length===0)A.push([g.numeroPedido,g.racaoNome,I(new Date(g.dataProducao+"T00:00:00"),"dd/MM/yyyy"),g.pesoSolicitado,"","",""]);else for(let w=0;w<g.materias.length;w++){const v=g.materias[w];A.push([w===0?g.numeroPedido:"",w===0?g.racaoNome:"",w===0?I(new Date(g.dataProducao+"T00:00:00"),"dd/MM/yyyy"):"",w===0?g.pesoSolicitado:"",v.codigo_mp,v.nome_mp,Number(v.qtd.toFixed(2))])}A.push([])}const R=it.book_new(),ee=it.aoa_to_sheet(A);it.book_append_sheet(R,ee,"Consumo por Cliente"),br(R,"consumo-pedidos-vigentes.xlsx")},Z=()=>{let A="";for(const[,ee]of Y){A+=`<h2>${ee.clienteNome} <span style="font-weight:normal;color:#6b7280">â ${ee.totalPeso.toLocaleString("pt-BR")} kg</span></h2>`,A+=`<table> 129 <thead><tr> 130 <th>Pedido</th> 131 <th>Ração</th> 132 <th>Data</th> 133 <th class="text-right">Peso (kg)</th> 134 <th>Cód MP</th> 135 <th>Matéria Prima</th> 136 <th class="text-right">Qtd (kg)</th> 137 </tr></thead><tbody>`;for(const n of ee.pedidos)if(n.materias.length===0)A+=`<tr> 138 <td>${n.numeroPedido}</td> 139 <td>${n.racaoNome}</td> 140 <td>${I(new Date(n.dataProducao+"T00:00:00"),"dd/MM/yyyy")}</td> 141 <td class="text-right">${n.pesoSolicitado.toLocaleString("pt-BR")}</td> 142 <td colspan="3">â</td> 143 </tr>`;else for(let g=0;g<n.materias.length;g++){const w=n.materias[g];A+=`<tr${g===0?' class="border-top"':""}> 144 <td>${g===0?n.numeroPedido:""}</td> 145 <td>${g===0?n.racaoNome:""}</td> 146 <td>${g===0?I(new Date(n.dataProducao+"T00:00:00"),"dd/MM/yyyy"):""}</td> 147 <td class="text-right">${g===0?n.pesoSolicitado.toLocaleString("pt-BR"):""}</td> 148 <td>${w.codigo_mp}</td> 149 <td>${w.nome_mp}</td> 150 <td class="text-right">${w.qtd.toLocaleString("pt-BR",{minimumFractionDigits:2,maximumFractionDigits:2})}</td> 151 </tr>`}A+="</tbody></table>"}const R=`Total Clientes: ${Y.length} | Total Pedidos: ${ne.length}`;Jt({title:"Consumo de MP por Pedido de Cliente â Pedidos Vigentes",subtitle:R,content:A,orientation:"landscape"})};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-4",children:[e.jsx(J,{variant:"outline",className:"text-sm px-3 py-1",children:"Pedidos Vigentes (Pendentes / Em Produção)"}),e.jsxs("div",{className:"flex gap-2 ml-auto",children:[e.jsx(O,{variant:"outline",size:"sm",onClick:E,children:"Expandir Todos"}),e.jsx(O,{variant:"outline",size:"sm",onClick:xe,children:"Recolher"}),e.jsxs(O,{variant:"outline",size:"sm",onClick:oe,children:[e.jsx(jr,{className:"h-4 w-4 mr-1"}),"Excel"]}),e.jsxs(O,{variant:"outline",size:"sm",onClick:Z,children:[e.jsx(nt,{className:"h-4 w-4 mr-1"}),"Imprimir"]})]})]}),e.jsxs("div",{className:"flex gap-3 flex-wrap",children:[e.jsxs(J,{variant:"secondary",className:"text-sm px-3 py-1",children:["Clientes: ",Y.length]}),e.jsxs(J,{variant:"secondary",className:"text-sm px-3 py-1",children:["Pedidos: ",ne.length]}),e.jsxs(J,{variant:"secondary",className:"text-sm px-3 py-1",children:["Peso Total: ",ne.reduce((A,R)=>A+R.pesoSolicitado,0).toLocaleString("pt-BR")," kg"]})]}),De?e.jsx("p",{className:"text-center text-muted-foreground py-8",children:"Carregando..."}):Y.length===0?e.jsx("p",{className:"text-center text-muted-foreground py-8",children:"Nenhum pedido vigente encontrado."}):e.jsx("div",{className:"space-y-3",children:Y.map(([A,R])=>{const ee=i.has(A);return e.jsxs(Ha,{className:"border-border",children:[e.jsxs("button",{className:"w-full flex items-center justify-between px-4 py-3 text-left hover:bg-muted/50 transition-colors rounded-t-lg",onClick:()=>ie(A),children:[e.jsxs("div",{className:"flex items-center gap-3",children:[ee?e.jsx(Gt,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(Wt,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"font-semibold text-foreground",children:R.clienteNome}),e.jsxs(J,{variant:"outline",className:"text-xs",children:[R.pedidos.length," pedido",R.pedidos.length!==1?"s":""]})]}),e.jsxs("span",{className:"text-sm text-muted-foreground",children:[R.totalPeso.toLocaleStr
151ing("pt-BR")," kg"]})]}),ee&&e.jsxs(Ua,{className:"px-4 pb-4 pt-0",children:[e.jsxs(ja,{children:[e.jsx(Ma,{children:e.jsxs(ge,{className:"text-xs",children:[e.jsx($,{className:"w-[120px]",children:"Pedido"}),e.jsx($,{children:"Ração"}),e.jsx($,{className:"w-[100px]",children:"Data"}),e.jsx($,{className:"w-[100px] text-right",children:"Peso (kg)"}),e.jsx($,{className:"w-[80px]",children:"Cód MP"}),e.jsx($,{children:"Matéria Prima"}),e.jsx($,{className:"w-[100px] text-right",children:"Qtd (kg)"})]})}),e.jsx(va,{children:R.pedidos.map(n=>n.materias.length===0?e.jsxs(ge,{children:[e.jsx(c,{className:"font-medium text-xs",children:n.numeroPedido}),e.jsx(c,{className:"text-xs",children:n.racaoNome}),e.jsx(c,{className:"text-xs",children:I(new Date(n.dataProducao+"T00:00:00"),"dd/MM/yyyy")}),e.jsx(c,{className:"text-xs text-right",children:n.pesoSolicitado.toLocaleString("pt-BR")}),e.jsx(c,{colSpan:3,className:"text-xs text-muted-foreground",children:"Sem fórmula ativa"})]},n.pedidoId):n.materias.map((g,w)=>e.jsxs(ge,{className:w===0?"border-t-2 border-border":"",children:[e.jsx(c,{className:"font-medium text-xs",children:w===0?n.numeroPedido:""}),e.jsx(c,{className:"text-xs",children:w===0?n.racaoNome:""}),e.jsx(c,{className:"text-xs",children:w===0?I(new Date(n.dataProducao+"T00:00:00"),"dd/MM/yyyy"):""}),e.jsx(c,{className:"text-xs text-right",children:w===0?n.pesoSolicitado.toLocaleString("pt-BR"):""}),e.jsx(c,{className:"text-xs text-muted-foreground",children:g.codigo_mp}),e.jsx(c,{className:"text-xs",children:g.nome_mp}),e.jsx(c,{className:"text-xs text-right",children:g.qtd.toLocaleString("pt-BR",{minimumFractionDigits:2,maximumFractionDigits:2})})]},`${n.pedidoId}-${w}`)))})]}),R.materiasSomadas.length>0&&e.jsxs("div",{className:"mt-4 pt-3 border-t border-border",children:[e.jsxs("h4",{className:"text-xs font-semibold text-foreground mb-2",children:["Somatório de Matérias Primas â ",R.clienteNome]}),e.jsxs(ja,{children:[e.jsx(Ma,{children:e.jsxs(ge,{className:"text-xs bg-muted/50",children:[e.jsx($,{className:"w-[80px]",children:"Cód MP"}),e.jsx($,{children:"Matéria Prima"}),e.jsx($,{className:"w-[120px] text-right",children:"Total (kg)"})]})}),e.jsx(va,{children:R.materiasSomadas.map((n,g)=>e.jsxs(ge,{children:[e.jsx(c,{className:"text-xs text-muted-foreground",children:n.codigo_mp}),e.jsx(c,{className:"text-xs font-medium",children:n.nome_mp}),e.jsx(c,{className:"text-xs text-right font-semibold",children:n.qtd.toLocaleString("pt-BR",{minimumFractionDigits:2,maximumFractionDigits:2})})]},g))})]})]})]})]},A)})})]})}function zn(){const i=new Date,[x,j]=d.useState(Di(i)),[u,L]=d.use
151State(Ei(i)),[y,k]=d.useState(!1),[M,Q]=d.useState(!1),[P,z]=d.useState(""),[H,ne]=d.useState(""),[Y,ie]=d.useState(!1),[E,xe]=d.useState([]),[De,oe]=d.useState([]),[Z,A]=d.useState(new Set),[R,ee]=d.useState(new Set),{toast:n}=Xt(),[g,w]=d.useState(new Map),v=B=>B.normalize("NFD").replace(/[\u0300-\u036f]/g,"").toLowerCase().trim(),V=async()=>{ie(!0);try{const{data:B}=await f.from("produtos_qualidade").select("nome_materia_prima, codigo_materia_prima"),G=new Map;if(B)for(const ce of B)ce.codigo_materia_prima&&G.set(v(ce.nome_materia_prima),ce.codigo_materia_prima);w(G);let re=f.from("producoes_externas").select("*").order("data_producao",{ascending:!0});if(x&&(re=re.gte("data_producao",I(x,"yyyy-MM-dd")+"T00:00:00")),u&&(re=re.lte("data_producao",I(u,"yyyy-MM-dd")+"T23:59:59")),P.trim()&&(re=re.ilike("nom_produto",`%${P.trim()}%`)),H.trim()){const ce=parseInt(H.trim());isNaN(ce)||(re=re.eq("num_producao",ce))}const{data:ze,error:_e}=await re;if(_e)throw _e;const Ne=ze||[];if(xe(Ne),Ne.length>0){const ce=Ne.map(He=>He.id),ue=[],he=100;for(let He=0;He<ce.length;He+=he){const Xe=ce.slice(He,He+he);let ma=0;const Ye=1e3;for(;;){const{data:Re,error:Ue}=await f.from("producoes_rastreabilidade").select("id,producao_externa_id,nom_produto,peso_requisitado,peso_realizado,num_batelada,num_ordem,lote_materia_prima,num_nota_fiscal,ordem_recebimento,nom_origem,nom_balanca,nom_rota,aditivo").in("producao_externa_id",Xe).range(ma,ma+Ye-1);if(Ue)throw Ue;if(Re&&ue.push(...Re),!Re||Re.length<Ye)break;ma+=Ye}}oe(ue)}else oe([]);A(new Set),ee(new Set)}catch(B){n({title:"Erro ao buscar produções",description:B.message,variant:"destructive"})}finally{ie(!1)}},F=d.useMemo(()=>{const B=new Map;for(const G of De){const re=B.get(G.producao_externa_id)||[];re.push(G),B.set(G.producao_externa_id,re)}return E.map(G=>{const re=B.get(G.id)||[],ze=new Map;for(const Ne of re){const ce=Ne.num_batelada??0,ue=ze.get(ce)||[];ue.push(Ne),ze.set(ce,ue)}const _e=Array.from(ze.entries()).sort(([Ne],[ce])=>Ne-ce).map(([Ne,ce])=>{var Ye;const ue=ce.reduce((Re,Ue)=>Re+(Ue.peso_realizado??0),0),he=ce.reduce((Re,Ue)=>Re+(Ue.peso_requisitado??0),0),He=ue-he,Xe=he>0?He/he*100:0,ma=((Ye=ce[0])==null?void 0:Ye.nom_rota)||"â";return{num_batelada:Ne,nom_rota:ma,peso_realizado:ue,peso_requisitado:he,diferenca_kg:He,diferenca_percentual:Xe,detalhes:ce.sort((Re,Ue)=>(Re.num_ordem??0)-(Ue.num_ordem??0))}});return{producao:G,bateladas:_e}})},[E,De]),ae=B=>{A(G=>{const re=new Set(G);return re.has(B)?re.delete(B):re.add(B),re})},ye=B=>{ee(G=>{const re=new Set(G);return re.has(B)?re.delete(B):re.add(B),re})},me=B=>{if(B==null)return"â";const G=typeof B=="string"?parseFloat(B):B;return isNaN(G)?"â":G.toLocaleString("pt-BR",{minimumFractionDigits:0,maximumFractionDigits:2})},Se=B=>{if(B==null)return"â";const G=typeof B=="string"?parseFloat(B):B;return isNaN(G)?"â":(G*1e3).toLocaleString("pt-BR",{minimumFractionDigits:0,maximumFractionDigits:2})},sa=B=>{if(!B)return"â";try{return I(new Date(B),"dd/MM/yyyy HH:mm")}catch{return B}};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap items-end gap-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground mb-1 block",children:"Data Inicial"}),e.jsxs(na,{open:y,onOpenChange:k,children:[e.jsx(da,{asChild:!0,children:e.jsxs(O,{variant:"outline",size:"sm",className:rt("w-[140px] justify-start text-left font-normal text-xs",!x&&"text-muted-foreground"),children:[e.jsx(fa,{className:"mr-1 h-3.5 w-3.5"}),x?I(x,"dd/MM/yyyy"):"Selecionar"]})}),e.jsx(la,{className:"w-auto p-0",align:"start",children:e.jsx(_a,{mode:"single",selected:x,onSelect:B=>{j(B),k(!1)},initialFocus:!0,className:"p-3 pointer-events-auto"})})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground mb-1 block",children:"Data Final"}),e.jsxs(na,{open:M,onOpenChange:Q,children:[e.jsx(da,{asChild:!0,children:e.jsxs(O,{variant:"outline",size:"sm",className:rt("w-[140px] justify-start text-left font-normal text-xs",!u&&"text-muted-foreground"),children:[e.jsx(fa,{className:"mr-1 h-3.5 w-3.5"}),u?I(u,"dd/MM/yyyy"):"Selecionar"]})}),e.jsx(la,{className:"w-auto p-0",align:"start",children:e.jsx(_a,{mode:"single",selected:u,onSelect:B=>{L(B),Q(!1)},initialFocus:!0,className:"p-3 pointer-events-auto"})})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground mb-1 block",children:"Produto"}),e.jsx(Ca,{placeholder:"Buscar produto...",value:P,onChange:B=>z(B.target.value),className:"w-[180px] h-9 text-xs"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground mb-1 block",children:"Nº Produção"}),e.jsx(Ca,{placeholder:"Nº...",value:H,onChange:B=>ne(B.target.value),className:"w-[100px] h-9 text-xs"})]}),e.jsxs(O,{size:"sm",onClick:()=>V(),disabled:Y,children:[Y?e.jsx(Os,{className:"h-4 w-4 animate-spin mr-1"}):e.jsx(zi,{className:"h-4 w-4 mr-1"}),"Buscar"]})]}),F.length===0&&!Y&&e.jsx("p",{className:"text-center text-muted-foreground text-sm py-8",children:'Utilize os filtros acima e clique em "Buscar" para consultar as produções.'}),F.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"text-xs text-muted-foreground",children:[F.length," produções encontradas"]}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(ja,{children:[e.jsx(Ma,{children:e.jsxs(ge,{className:"table-header",children:[e.jsx($,{className:"w-8"}),e.jsx($,{children:"Nº Produção"}),e.jsx($,{children:"Produto"}),e.jsx($,{children:"Linha"}),e.jsx($,{className:"text-right",children:"Realizado"}),e.jsx($,{className:"text-right",children:"Requisitado"}),e.jsx($,{className:"text-right",children:"Diferença"}),e.jsx($,{className:"text-right",children:"Dif.%"}),e.jsx($,{className:"text-center",children:"Bateladas"}),e.jsx($,{children:"Data"}),e.jsx($,{className:"text-center",children:"Status"}),e.jsx($,{className:"text-center",children:"Estoque"})]})}),e.jsx(va,{children:F.map(B=>{const G=B.producao,re=Z.has(G.producao_id),ze=G.diferenca_percentual??0;return e.jsxs(e.Fragment,{children:[e.jsxs(ge,{className:"cursor-pointer hover:bg-muted/50",onClick:()=>ae(G.producao_id),children:[e.jsx(c,{children:re?e.jsx(Gt,{className:"h-4 w-4"}):e.jsx(Wt,{className:"h-4 w-4"})}),e.jsx(c,{className:"font-medium",children:G.num_producao}),e.jsx(c,{children:G.nom_produto}),e.jsx(c,{children:G.nom_linha_producao}),e.jsx(c,{className:"text-right",children:Se(G.total_realizado)}),e.jsx(c,{className:"text-right",children:Se(G.total_requisitado)}),e.jsx(c,{className:"text-right",children:Se(G.diferenca)}),e.jsx(c,{className:"text-right",children:e.jsxs("span",{className:rt(ze>1?"text-destructive":ze<-1?"text-orange-500":""),children:[me(ze),"%"]})}),e.jsx(c,{className:"text-center",children:G.bateladas_realizadas}),e.jsx(c,{className:"text-xs",children:sa(G.data_producao)}),e.jsx(c,{className:"text-center",children:(()=>{const _e=G.percentual_variacao??0,Ne=G.status_sync;return Ne==="perda"?e.jsx(J,{className:"text-[10px] bg-destructive text-destructive-foreground",children:"Perda"}):Ne==="atencao"?_e>5?e.jsxs(J,{className:"text-[10px] bg-destructive text-destructive-foreground animate-pulse",children:["â CrÃtico ",me(_e),"%"]}):_e>
1513?e.jsxs(J,{className:"text-[10px] bg-orange-500 text-white",children:["â Alto ",me(_e),"%"]}):e.jsxs(J,{className:"text-[10px] bg-yellow-500 text-black",children:["Atenção ",me(_e),"%"]}):Ne==="completa"?e.jsx(J,{variant:"secondary",className:"text-[10px] bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200",children:"Completo"}):e.jsx(J,{variant:"outline",className:"text-[10px]",children:"Incompleta"})})()}),e.jsx(c,{className:"text-center",children:G.estoque_baixado&&e.jsx(J,{variant:"secondary",className:"text-[10px] bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200",children:"Estoque â"})})]},G.producao_id),re&&B.bateladas.map(_e=>{const Ne=`${G.producao_id}-${_e.num_batelada}`,ce=R.has(Ne);return e.jsxs(e.Fragment,{children:[e.jsxs(ge,{className:"bg-muted/30 cursor-pointer",onClick:ue=>{ue.stopPropagation(),ye(Ne)},children:[e.jsx(c,{}),e.jsx(c,{colSpan:2,className:"text-xs font-medium",children:e.jsxs("span",{className:"flex items-center gap-1",children:[ce?e.jsx(Gt,{className:"h-3 w-3"}):e.jsx(Wt,{className:"h-3 w-3"}),"Batelada ",_e.num_batelada," â ",_e.nom_rota]})}),e.jsx(c,{className:"text-xs text-right",children:me(_e.peso_realizado)}),e.jsx(c,{className:"text-xs text-right",children:me(_e.peso_requisitado)}),e.jsx(c,{className:"text-xs text-right",children:me(_e.diferenca_kg)}),e.jsxs(c,{className:"text-xs text-right",children:[me(_e.diferenca_percentual),"%"]}),e.jsxs(c,{colSpan:3,className:"text-xs text-muted-foreground",children:[_e.detalhes.length," materiais"]})]},Ne),ce&&e.jsxs(e.Fragment,{children:[e.jsxs(ge,{className:"bg-muted/20 text-[10px] font-semibold text-muted-foreground uppercase tracking-wide",children:[e.jsx(c,{}),e.jsx(c,{className:"pl-8",children:"Ordem"}),e.jsx(c,{children:"Cód."}),e.jsx(c,{children:"Matéria-Prima"}),e.jsx(c,{children:"Lote"}),e.jsx(c,{className:"text-right",children:"Realizado"}),e.jsx(c,{className:"text-right",children:"Requisitado"}),e.jsx(c,{children:"NF"}),e.jsx(c,{children:"Origem"}),e.jsx(c,{children:"Balança"}),e.jsx(c,{children:"Info"})]}),_e.detalhes.map(ue=>{const he=ue.nom_produto&&g.get(v(ue.nom_produto))||"â";return e.jsxs(ge,{className:"bg-muted/10 text-xs",children:[e.jsx(c,{}),e.jsx(c,{className:"pl-8",children:ue.num_ordem}),e.jsx(c,{className:"font-medium",children:he}),e.jsx(c,{children:ue.nom_produto}),e.jsx(c,{className:"text-muted-foreground",children:ue.lote_materia_prima||"â"}),e.jsx(c,{className:"text-right",children:me(ue.peso_realizado)}),e.jsx(c,{className:"text-right",children:me(ue.peso_requisitado)}),e.jsx(c,{className:"text-muted-foreground",children:ue.num_nota_fiscal||"â"}),e.jsx(c,{className:"text-muted-foreground",children:ue.nom_origem||"â"}),e.jsx(c,{className:"text-muted-foreground",children:ue.nom_balanca||"â"}),e.jsx(c,{children:ue.aditivo&&e.jsx(J,{variant:"outline",className:"text-[10px]",children:"Aditivo"})})]},ue.id)})]})]})})]})})})]})})]})]})}const Te=i=>i.toLocaleString("pt-BR",{minimumFractionDigits:2,maximumFractionDigits:2});function Tn({enabled:i}){const[x,j]=d.useState(new Set),{data:u=[],isLoading:L}=ve({queryKey:["pesadinhas-analise-pedidos"],queryFn:async()=>{const{data:n,error:g}=await f.from("pedidos").select("id, numero_pedido, peso_solicitado, racao_id, data_producao, cliente_id, lote_producao, racoes(id, nome, tag, peso_padrao)").eq("cancelado",!1).is("lote_producao",null).not("racao_id","is",null).order("data_producao");if(g)throw g;return(n||[]).filter(w=>{var F,ae;const v=((F=w.racoes)==null?void 0:F.tag)||"",V=(((ae=w.racoes)==null?void 0:ae.nome)||"").toUpperCase();return v==="Pesadinha"||V.includes("PESADINHA")})},enabled:i}),y=d.useMemo(()=>[...new Set(u.map(n=>n.cliente_id))],[u]),k=d.useMemo(()=>[...new Set(u.map(n=>n.racao_id))],[u]),{data:M=[]}=ve({queryKey:["pesadinhas-analise-clientes",y],queryFn:async()=>{if(y.length===0)return[];const{data:n,error:g}=await f.from("clientes").select("id, nome").in("id",y);if(g)throw g;return n},enabled:i&&y.length>0}),{data:Q=[]}=ve({queryKey:["pesadinhas-analise-versoes",k],queryFn:async()=>{if(k.length===0)return[];const{data:n,error:g}
151=await f.from("racao_formula_versoes").select("id, racao_id, peso_padrao_snapshot").in("racao_id",k).eq("is_active",!0);if(g)throw g;return n},enabled:i&&k.length>0}),P=d.useMemo(()=>Q.map(n=>n.id),[Q]),{data:z=[]}=ve({queryKey:["pesadinhas-analise-mps",P],queryFn:async()=>{if(P.length===0)return[];const n=1e3;let g=[],w=0;for(;;){const{data:v,error:V}=await f.from("racao_materias_primas").select("racao_id, versao_id, codigo_mp, nome_mp, quantidade").in("versao_id",P).range(w,w+n-1);if(V)throw V;if(!v||v.length===0||(g=g.concat(v),v.length<n))break;w+=n}return g},enabled:i&&P.length>0}),{data:H}=ve({queryKey:["config-peso-padrao"],queryFn:async()=>{const{data:n}=await f.from("configuracoes").select("valor").eq("chave","peso_padrao_global").maybeSingle();return n!=null&&n.valor?Number(n.valor):2e3},enabled:i}),{data:ne=[]}=ve({queryKey:["pesadinhas-analise-estoque-view"],queryFn:async()=>{const{data:n,error:g}=await f.from("vw_estoque_interno_item_saldo").select("codigo, nome, saldo_kg, ativo").eq("ativo",!0);if(g)throw g;return n||[]},enabled:i}),{lista:Y,clienteGroups:ie,somatorioGlobal:E}=d.useMemo(()=>{const n=[];for(const F of u){const ae=Number(F.peso_solicitado)||0,ye=M.find(G=>G.id===F.cliente_id),me=F.racoes,Se=Q.find(G=>G.racao_id===F.racao_id),sa=(Se==null?void 0:Se.peso_padrao_snapshot)||(me==null?void 0:me.peso_padrao)||H||2e3,B=[];if(Se&&sa>0){const G=z.filter(ze=>ze.versao_id===Se.id),re=ae/Number(sa);for(const ze of G)B.push({codigo_mp:ze.codigo_mp||"â",nome_mp:ze.nome_mp||"Sem nome",qtd:(Number(ze.quantidade)||0)*re})}n.push({pedidoId:F.id,numeroPedido:F.numero_pedido,clienteNome:(ye==null?void 0:ye.nome)||"â",clienteId:F.cliente_id,racaoNome:(me==null?void 0:me.nome)||"â",pesoSolicitado:ae,dataProducao:F.data_producao,materias:B.sort((G,re)=>G.nome_mp.localeCompare(re.nome_mp))})}const g=new Map;for(const F of n){const ae=g.get(F.clienteId);ae?(ae.pedidos.push(F),ae.totalPeso+=F.pesoSolicitado):g.set(F.clienteId,{clienteNome:F.clienteNome,pedidos:[F],totalPeso:F.pesoSolicitado})}const w=[...g.entries()].sort((F,ae)=>F[1].clienteNome.localeCompare(ae[1].clienteNome)),v=new Map;for(const F of n)for(const ae of F.materias){const ye=ae.nome_mp.toLowerCase(),me=v.get(ye);me?me.qtd+=ae.qtd:v.set(ye,{codigo_mp:ae.codigo_mp,nome_mp:ae.nome_mp,qtd:ae.qtd})}const V=[...v.values()].sort((F,ae)=>F.nome_mp.localeCompare(ae.nome_mp));return{lista:n,clienteGroups:w,somatorioGlobal:V}},[u,M,Q,z,H]),xe=(n,g)=>{const w=(n||"").toLowerCase(),v=(g||"").toLowerCase(),V=ne.find(F=>n&&F.codigo&&F.codigo.toLowerCase()===w||F.nome&&F.nome.toLowerCase()===v);return V?Number(V.saldo_kg)||0:null},De=n=>{j(g=>{const w=new Set(g);return w.has(n)?w.delete(n):w.add(n),w})},oe=()=>j(new Set(ie.map(([n])=>n))),Z=()=>j(new Set),A=Y.reduce((n,g)=>n+g.pesoSolicitado,0),R=()=>{const n=[["Análise de MP â Pedidos Pesadinha Ativos"],[]];for(const[,v]of ie){n.push([`Cliente: ${v.clienteNome}`,"","",`Total: ${Te(v.totalPeso)} kg`]),n.push(["Pedido","Pesadinha","Data","Peso (kg)","Cód MP","Matéria Prima","Qtd (kg)"]);for(const V of v.pedidos)if(V.materias.length===0)n.push([V.numeroPedido,V.racaoNome,I(new Date(V.dataProducao+"T00:00:00"),"dd/MM/yyyy"),V.pesoSolicitado,"","",""]);else for(let F=0;F<V.materias.length;F++){const ae=V.materias[F];n.push([F===0?V.numeroPedido:"",F===0?V.racaoNome:"",F===0?I(new Date(V.dataProducao+"T00:00:00"),"dd/MM/yyyy"):"",F===0?V.pesoSolicitado:"",ae.codigo_mp,ae.nome_mp,Number(ae.qtd.toFixed(2))])}n.push([])}n.push([],["SOMATÃRIO CONSOLIDADO"]),n.push(["Cód MP","Matéria Prima","Total (kg)","Saldo Estoque (kg)","Status"]);for(const v of E){const V=xe(v.codigo_mp,v.nome_mp),F=V===null?"Sem cadastro":V>=v.qtd?"OK":`Faltam ${Te(v.qtd-V)}`;n.push([v.codigo_mp,v.nome_mp,Number(v.qtd.toFixed(2)),V??"",F])}const g=it.book_new(),w=it.aoa_to_sheet(n);it.book_append_sheet(g,w,"Análise Pesadinhas"),br(g,"analise-pesadinhas.xlsx")},ee=()=>{let n="";for(const[,w]of ie){n+=`<h2>${w.clienteNome} <span style="font-weight:normal;color:#6b7280">â ${Te(w.totalPeso)} kg</span></h2>`,n+=`<table> 152 <thead><tr> 153 <th>Pedido</th><th>Pesadinha</th><th>Data</th> 154 <th class="text-right">Peso (kg)</th> 155 <th>Cód MP</th><th>
155Matéria Prima</th> 156 <th class="text-right">Qtd (kg)</th> 157 </tr></thead><tbody>`;for(const v of w.pedidos)if(v.materias.length===0)n+=`<tr> 158 <td>${v.numeroPedido}</td> 159 <td>${v.racaoNome}</td> 160 <td>${I(new Date(v.dataProducao+"T00:00:00"),"dd/MM/yyyy")}</td> 161 <td class="text-right">${Te(v.pesoSolicitado)}</td> 162 <td colspan="3">â</td> 163 </tr>`;else for(let V=0;V<v.materias.length;V++){const F=v.materias[V];n+=`<tr${V===0?' class="border-top"':""}> 164 <td>${V===0?v.numeroPedido:""}</td> 165 <td>${V===0?v.racaoNome:""}</td> 166 <td>${V===0?I(new Date(v.dataProducao+"T00:00:00"),"dd/MM/yyyy"):""}</td> 167 <td class="text-right">${V===0?Te(v.pesoSolicitado):""}</td> 168 <td>${F.codigo_mp}</td> 169 <td>${F.nome_mp}</td> 170 <td class="text-right">${Te(F.qtd)}</td> 171 </tr>`}n+="</tbody></table>"}n+='<h2 style="margin-top:24px">Somatório Consolidado</h2>',n+=`<table> 172 <thead><tr> 173 <th>Cód MP</th><th>
173Matéria Prima</th> 174 <th class="text-right">Total (kg)</th> 175 <th class="text-right">Saldo (kg)</th> 176 <th>Status</th> 177 </tr></thead><tbody>`;for(const w of E){const v=xe(w.codigo_mp,w.nome_mp),V=v===null?"â":v>=w.qtd?"OK":`Faltam ${Te(w.qtd-v)}`;n+=`<tr> 178 <td>${w.codigo_mp}</td> 179 <td>${w.nome_mp}</td> 180 <td class="text-right">${Te(w.qtd)}</td> 181 <td class="text-right">${v===null?"â":Te(v)}</td> 182 <td>${V}</td> 183 </tr>`}n+="</tbody></table>";const g=`Pesadinhas: ${Y.length} | Peso Total: ${Te(A)} kg | MPs: ${E.length}`;Jt({title:"Análise de MP â Pedidos Pesadinha Ativos",subtitle:g,content:n,orientation:"landscape"})};return i?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(J,{variant:"outline",className:"text-sm px-3 py-1",children:"Pesadinhas Ativas (não finalizadas)"}),e.jsxs("div",{className:"flex gap-2 ml-auto",children:[e.jsx(O,{variant:"outline",size:"sm",onClick:oe,children:"Expandir Todos"}),e.jsx(O,{variant:"outline",size:"sm",onClick:Z,children:"Recolher"}),e.jsxs(O,{variant:"outline",size:"sm",onClick:R,children:[e.jsx(jr,{className:"h-4 w-4 mr-1"}),"Excel"]}),e.jsxs(O,{variant:"outline",size:"sm",onClick:ee,children:[e.jsx(nt,{className:"h-4 w-4 mr-1"}),"Imprimir"]})]})]}),e.jsxs("div",{className:"flex gap-3 flex-wrap",children:[e.jsxs(J,{variant:"secondary",className:"text-sm px-3 py-1",children:["Pesadinhas: ",Y.length]}),e.jsxs(J,{variant:"secondary",className:"text-sm px-3 py-1",children:["Peso Total: ",Te(A)," kg"]}),e.jsxs(J,{variant:"secondary",className:"text-sm px-3 py-1",children:["Tipos de MP: ",E.length]}),e.jsxs(J,{variant:"secondary",className:"text-sm px-3 py-1",children:["Clientes: ",ie.length]})]}),L?e.jsx("p",{className:"text-center text-muted-foreground py-8",children:"Carregando..."}):ie.length===0?e.jsx("p",{className:"text-center text-muted-foreground py-8",children:"Nenhuma pesadinha ativa encontrada."}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"space-y-3",children:ie.map(([n,g])=>{const w=x.has(n);return e.jsxs(Ha,{className:"border-border",children:[e.jsxs("button",{className:"w-full flex items-center justify-between px-4 py-3 text-left hover:bg-muted/50 transition-colors rounded-t-lg",onClick:()=>De(n),children:[e.jsxs("div",{className:"flex items-center gap-3",children:[w?e.jsx(Gt,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(Wt,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"font-semibold text-foreground",children:g.clienteNome}),e.jsxs(J,{variant:"outline",className:"text-xs",children:[g.pedidos.length," pedido",g.pedidos.length!==1?"s":""]})]}),e.jsxs("span",{className:"text-sm text-muted-foreground",children:[Te(g.totalPeso)," kg"]})]}),w&&e.jsx(Ua,{className:"px-4 pb-4 pt-0",children:e.jsxs(ja,{children:[e.jsx(Ma,{children:e.jsxs(ge,{className:"text-xs",children:[e.jsx($,{className:"w-[120px]",children:"Pedido"}),e.jsx($,{children:"Pesadinha"}),e.jsx($,{className:"w-[100px]",children:"Data"}),e.jsx($,{className:"w-[100px] text-right",children:"Peso (kg)"}),e.jsx($,{className:"w-[80px]",children:"Cód MP"}),e.jsx($,{children:"Matéria Prima"}),e.jsx($,{className:"w-[100px] text-right",children:"Qtd (kg)"})]})}
183),e.jsx(va,{children:g.pedidos.map(v=>v.materias.length===0?e.jsxs(ge,{children:[e.jsx(c,{className:"font-medium text-xs",children:v.numeroPedido}),e.jsx(c,{className:"text-xs",children:v.racaoNome}),e.jsx(c,{className:"text-xs",children:I(new Date(v.dataProducao+"T00:00:00"),"dd/MM/yyyy")}),e.jsx(c,{className:"text-xs text-right",children:Te(v.pesoSolicitado)}),e.jsx(c,{colSpan:3,className:"text-xs text-muted-foreground",children:"Sem fórmula ativa"})]},v.pedidoId):v.materias.map((V,F)=>e.jsxs(ge,{className:F===0?"border-t-2 border-border":"",children:[e.jsx(c,{className:"font-medium text-xs",children:F===0?v.numeroPedido:""}),e.jsx(c,{className:"text-xs",children:F===0?v.racaoNome:""}),e.jsx(c,{className:"text-xs",children:F===0?I(new Date(v.dataProducao+"T00:00:00"),"dd/MM/yyyy"):""}),e.jsx(c,{className:"text-xs text-right",children:F===0?Te(v.pesoSolicitado):""}),e.jsx(c,{className:"text-xs text-muted-foreground",children:V.codigo_mp}),e.jsx(c,{className:"text-xs",children:V.nome_mp}),e.jsx(c,{className:"text-xs text-right",children:Te(V.qtd)})]},`${v.pedidoId}-${F}`)))})]})})]},n)})}),E.length>0&&e.jsx(Ha,{className:"border-border",children:e.jsxs(Ua,{className:"p-4",children:[e.jsx("h3",{className:"text-sm font-semibold text-foreground mb-3",children:"Somatório Consolidado de Matérias-Primas"}),e.jsxs(ja,{children:[e.jsx(Ma,{children:e.jsxs(ge,{className:"text-xs bg-muted/50",children:[e.jsx($,{className:"w-[100px]",children:"Cód MP"}),e.jsx($,{children:"Matéria Prima"}),e.jsx($,{className:"w-[120px] text-right",children:"Necessário (kg)"}),e.jsx($,{className:"w-[120px] text-right",children:"Saldo (kg)"}),e.jsx($,{className:"w-[140px]",children:"Status"})]})}),e.jsx(va,{children:E.map((n,g)=>{const w=xe(n.codigo_mp,n.nome_mp),v=w!==null&&w>=n.qtd;return e.jsxs(ge,{children:[e.jsx(c,{className:"text-xs text-muted-foreground",children:n.codigo_mp}),e.jsx(c,{className:"text-xs font-medium",children:n.nome_mp}),e.jsx(c,{className:"text-xs text-right font-semibold",children:Te(n.qtd)}),e.jsx(c,{className:"text-xs text-right",children:w===null?"â":Te(w)}),e.jsx(c,{className:"text-xs",children:w===null?e.jsx(J,{variant:"outline",className:"text-xs",children:"Sem cadastro"}):v?e.jsx(J,{className:"text-xs bg-emerald-600 hover:bg-emerald-600",children:"OK"}):e.jsxs(J,{variant:"destructive",className:"text-xs",children:["Faltam ",Te(n.qtd-w)]})})]},g)})})]})]})})]})]}):null}const hr=["menu","pedidos","pesadinhas","aguardando","entregue","cancelados","todos","programacoes","consumo","materia-prima","mp-pendente","consumo-cliente","consumo-nexxus"];function dd(){var Eo;const[i,x]=bi(),j=yi(),u=Ni(),y=wi().id||null,k=!!y,{podeSequenciar:M,analisarSequencia:Q,isLoading:P}=en(),z=k?"programacoes":hr.includes(i.get("view"))?i.get("view"):"menu",[H,ne]=d.useState(z),Y=d.useCallback(a=>{ne(a),a==="menu"?i.delete("view"):i.set("view",a),x(i,{replace:!0})},[i,x]);d.useEffect(()=>{if(k)return;const a=i.get("view");a&&hr.includes(a)&&a!==H?ne(a):!a&&H!=="menu"&&ne("menu")},[i]);const{isAutoRefreshEnabled:ie}=Ti(),[E,xe]=d.useState(new Date),[De,oe]=d.useState(!1),[Z,A]=d.useState(null),ee=Li(new Date,{weekStartsOn:1}),n=Lo(ee,4),[g,w]=d.useState(ee),[v,V]=d.useState(n),[F,ae]=d.useState(!1),[ye,me]=d.useState(!1),Se=Lo(ee,6),[sa,B]=d.useState(ee),[G,re]=d.useState(Se),[ze,_e]=d.useState(!1),[Ne,ce]=d.useState(!1),[ue,he]=d.useState(ee),[He,Xe]=d.useState(Se),[ma,Ye]=d.useState(!1),[Re,Ue]=d.useState(!1),[Yt,Ze]=d.useState(!1),[be,Pt]=d.useState(null),[dt,St]=d.useState("pendente"),[q,S]=d.useState(""),[h,te]=d.useState(),[Ce,X]=d.useState(!1),[Ve,ba]=d.useState(""),[Aa,ya]=d.useState(""),[ea,Na]=d.useState(""),[wa,oa]=d.useState(""),[lt,ct]=d.useState(""),[qa,Zt]=d.useState(!1),[Ct,es]=d.useState(""),[as,ts]=d.useState(""),[Ln,ss]=d.useState(0),[aa,Bs]=d.useState(!1),[mt,os]=d.useState(""),[Nr,rs]=d.useState(!1),[ut,Mt]=d.useState({path:null,nome:null}),[Ee,Va]=d.useState(null),[wr,Ks]=d.useState(!1),[Qs,Hs]=d.useState(!1),[At,ua]=d.useState(k?y:null),[is,ns]=d.useState(null);d.useEffect(()=>{ua(k?y:null)},[k,y]);const[Pr,Us]=d.useState(null),[pa,Vs]=d.useState(null),[Sr,Gs]=d.use
183State(!1),[ds,Ws]=d.useState(null),[Cr,Js]=d.useState(!1),[qt,ls]=d.useState(null),[cs,ms]=d.useState(""),[Mr,Xs]=d.useState(!1),[Ar,kt]=d.useState(null),[qr,$t]=d.useState(null),[kr,Ys]=d.useState(null),[$r,Zs]=d.useState(null),[Pa,us]=d.useState(null),[Dr,ps]=d.useState(null),[Er,eo]=d.useState(!1),[zr,ao]=d.useState(""),[to,so]=d.useState(null),[oo,ro]=d.useState(null),[ka,Ta]=d.useState(null),[Tr,xs]=d.useState(!1),[hs,Dt]=d.useState(null),[Lr,gs]=d.useState(!1),[io,no]=d.useState(!1),[Rr,pt]=d.useState(""),{toast:W}=Xt(),{isMaster:Ga,isQualidade:Fr,user:pe}=Ri(),Et=Ga||Fr,se=Zi(),{data:_}=ve({queryKey:["meu_profile_pcp_assinatura",pe==null?void 0:pe.id],enabled:!!(pe!=null&&pe.id),queryFn:async()=>{const{data:a,error:s}=await f.from("profiles").select("full_name, funcao, codigo, assinatura_url").eq("id",pe.id).maybeSingle();if(s)throw s;return a}}),[Ir,zt]=d.useState(!1),[Or,Tt]=d.useState([]),[lo,Lt]=d.useState(null),[co,mo]=d.useState(!1),Br=`${window.location.origin}/logo-3bs.png`,{data:xt}=ve({queryKey:["rq-programacao-producao"],queryFn:async()=>{const{data:a,error:s}=await f.from("registros_qualidade").select("codigo, criado_em, revisado_em, numero_revisao").ilike("nome","Programação de Produção").maybeSingle();if(s)throw s;return a}}),$a=()=>{Pt(null),St("pendente"),S(""),te(void 0),ba(""),ya(""),Na(""),oa(""),ct(""),Zt(!1),es(""),ts(""),ss(0),Bs(!1),os(""),rs(!1),Vs(null),Mt({path:null,nome:null}),Va(null)},{data:Kr=[]}=ve({queryKey:["clientes"],queryFn:async()=>{const{data:a,error:s}=await f.from("clientes").select("*").order("nome");if(s)throw s;return a}}),{data:Wa=[]}=ve({queryKey:["racoes"],queryFn:async()=>{const{data:a,error:s}=await f.from("racoes").select("*").eq("ativo",!0).order("nome");if(s)throw s;return a}}),{data:uo=[]}=ve({queryKey:["produtores"],queryFn:async()=>{const{data:a,error:s}=await f.from("produtores").select("*").order("nome");if(s)throw s;return a}}),{data:Me=[],isLoading:Qr}=ve({queryKey:["pedidos"],queryFn:async()=>{let s=0;const t=[];for(;;){const{data:o,error:m}=await f.from("pedidos").select("*, clientes(nome, codigo), racoes(nome, codigo, tag, is_medicada), produtores(nome), silos_expedicao:silos_expedicao(nome), ordens_carregamento(status, silo_expedicao)").order("prioridade",{ascending:!0}).order("numero",{ascending:!1}).order("id",{ascending:!0}).range(s,s+1e3-1);if(m)throw m;if(t.push(...o||[]),!o||o.length<1e3)break;s+=1e3}return t},refetchOnWindowFocus:ie("pedidos")}),de=d.useMemo(()=>!aa||!mt?null:Me.find(a=>String(a.numero)===mt.trim())||null,[aa,mt,Me]),Hr=uo.filter(a=>!q||a.cliente_id===q),po=Fi(),xo=a=>a.id!==Ve&&a.id!==(de==null?void 0:de.racao_id)&&Gi(a.codigo,po.data),Ur=Wa.filter(a=>{if(!q||a.cliente_id!==q||xo(a))return!1;const s=(a.tag||"").toString(),t=(a.nome||"").toString().toUpperCase();return!(s==="Pesadinha"||t.includes("PESADINHA"))}),Vr=Wa.filter(a=>{if(!q||a.cliente_id!==q||xo(a))return!1;const s=(a.tag||"").toString(),t=(a.nome||"").toString().toUpperCase();return!!(s==="Pesadinha"||t.includes("PESADINHA"))}),[Gr,ho]=d.useState(!1),go=d.useMemo(()=>({numero:a=>String(a.numero),dataPedido:a=>a.created_at?I(new Date(a.created_at),"dd/MM/yyyy"):"",codCliente:a=>{var s;return((s=a.clientes)==null?void 0:s.codigo)||""},dataProducao:a=>a.data_producao?I(new Date(a.data_producao+"T00:00:00"),"dd/MM/yyyy"):"",codRacao:a=>{var s;return((s=a.racoes)==null?void 0:s.codigo)||""},produto:a=>{var s;return((s=a.racoes)==null?void 0:s.nome)||""},numPedido:a=>a.numero_pedido||"",peso:a=>String(a.peso_solicitado),produtor:a=>{var s;return((s=a.produtores)==null?void 0:s.nome)||""},grade:a=>a.numero_grade||"",ordemProducao:a=>a.ordem_producao||"",lote:a=>a.lote_producao||"",prioridade:a=>a.prioridade?String(a.prioridade):"â",silo:a=>{var m;const s=(m=a.silos_expedicao)==null?void 0:m.nome;if(s)return s;const o=(a.ordens_carregamento||[]).find(l=>l.silo_expedicao);return(o==null?void 0:o.silo_expedicao)||""},status:a=>a.cancelado?"cancelado":(a.ordens_carregamento||[]).some(t=>t.status==="finalizado")?"entregue":a.silo_expedicao_id?"finalizado":a.status_producao==="em_andamento"?"em andamento":"pendente"}),[]),{filters:Fe,setFilter:Ie,filtered:Wr}=sn(Me,go),{sort:Oe,toggleSort:Be,sorted:La}=on(Wr,go),fs=d.useRef(new Map),[fo,_o]=d.useState(new Set),Jr=async a=>{const s=(a.programacao_diaria_itens||[]).map(m=>
183m.pedido_id).filter(Boolean),t=Me.filter(m=>s.includes(m.id)),o=Array.from(new Set(t.map(m=>m.lote_producao).filter(m=>m!=null&&String(m).trim()!==""))).map(m=>String(m));if(o.length===0){W({title:"Nenhum lote para sincronizar",description:"Esta programação ainda não tem produções com lote vinculado."});return}_o(m=>{const l=new Set(m);return l.add(a.id),l});for(const m of o)fs.current.delete(m);try{if(!await Ro())throw new Error("Sua sessão expirou. Entre novamente para sincronizar as produções.");const l=(await Promise.allSettled(o.map(p=>{const D=parseInt(p,10);return Number.isFinite(D)?Fo({filterProducao:D,page_size:50,maxPages:20,skipRecheck:!1}):Promise.resolve()}))).filter(p=>p.status==="rejected").length;await se.invalidateQueries({queryKey:["pedidos"]}),await se.invalidateQueries({queryKey:["programacoes_diarias"]}),l>0?W({title:"Atualização parcial",description:`${o.length-l}/${o.length} lotes sincronizados.`,variant:"destructive"}):W({title:"Silos atualizados",description:`${o.length} lote(s) sincronizado(s).`})}catch(m){W({title:"Erro ao atualizar silos",description:(m==null?void 0:m.message)||String(m),variant:"destructive"})}finally{_o(m=>{const l=new Set(m);return l.delete(a.id),l})}};d.useEffect(()=>{if(!Me||Me.length===0)return;const a=10*60*1e3,s=Me.filter(m=>{if(m.cancelado||m.silo_expedicao_id||!m.lote_producao)return!1;const l=m.ordens_carregamento||[];return l.length===0||!l.some(D=>!!D.silo_expedicao)||!0}),t=Date.now(),o=[];for(const m of s){const l=String(m.lote_producao),p=fs.current.get(l)||0;if(!(t-p<a)&&(fs.current.set(l,t),o.push(l),o.length>=3))break}o.length!==0&&(async()=>{if(await Ro()){for(const m of o)try{const l=parseInt(m,10);if(!Number.isFinite(l))continue;await Fo({filterProducao:l,page_size:50,maxPages:20,skipRecheck:!1})}catch{}se.invalidateQueries({queryKey:["pedidos"]})}})()},[Me,se]);const _s=a=>{const s=a.ordens_carregamento||[];return!a.cancelado&&s.some(t=>t.status==="finalizado")},jo=a=>!a.cancelado&&!_s(a)&&!!a.silo_expedicao_id,Da=a=>{var o,m;const s=((o=a.racoes)==null?void 0:o.tag)||"",t=(((m=a.racoes)==null?void 0:m.nome)||"").toUpperCase();return s==="Pesadinha"||t.includes("PESADINHA")},vo=a=>!!a.lote_producao,bo=La.filter(a=>!a.cancelado&&Da(a)),Ja=bo.filter(a=>!vo(a)),xa=bo.filter(a=>vo(a)),Xa=30,[Ya,ht]=d.useState(1);d.useEffect(()=>{ht(1)},[xa.length]);const yo=xa.slice((Ya-1)*Xa,Ya*Xa),Xr=La.filter(a=>!a.cancelado&&!Da(a)&&!_s(a)&&!jo(a)),No=La.filter(a=>!Da(a)&&jo(a)),Yr=La.filter(a=>!Da(a)&&_s(a)),Zr=I(sa,"yyyy-MM-dd"),ei=I(G,"yyyy-MM-dd"),Za=Yr.filter(a=>a.data_producao?a.data_producao>=Zr&&a.data_producao<=ei:!1),wo=La.filter(a=>a.cancelado),ai=I(g,"yyyy-MM-dd"),ti=I(v,"yyyy-MM-dd"),si=Xr.filter(a=>a.data_producao?a.data_producao>=ai&&a.data_producao<=ti:!1),{data:fe=[],isLoading:Rt}=ve({queryKey:["programacoes_diarias"],queryFn:async()=>{const{data:a,error:s}=await f.from("programacoes_diarias").select("*, programacao_diaria_itens:programacao_diaria_itens(id, pedido_id, prioridade)").order("created_at",{ascending:!1});if(s)throw s;return a}}),{data:gt=[]}=ve({queryKey:["programacao_alteracoes"],queryFn:async()=>{const{data:a,error:s}=await f.from("programacao_alteracoes").select("*").order("created_at",{ascending:!0});if(s)throw s;return a||[]}}),oi=async a=>{if(!(!to||!oo))try{const{error:s}=await f.from("programacao_alteracoes").insert({programacao_id:to,justificativa:a,user_id:(pe==null?void 0:pe.id)??null,user_nome:(_==null?void 0:_.full_name)??null,user_codigo:(_==null?void 0:_.codigo)??null});if(s)throw s;await oo(a),se.invalidateQueries({queryKey:["programacao_alteracoes"]}),eo(!1),ro(null),so(null),ao("")}catch(s){W({title:"Erro ao registrar alteração",description:s.message,variant:"destructive"})}},ft=async(a,s)=>{try{const{error:t}=await f.from("programacao_alteracoes").insert({programacao_id:a,justificativa:s,user_id:(pe==null?void 0:pe.id)??null,user_nome:(_==null?void 0:_.full_name)??null,user_codigo:(_==null?void 0:_.codigo)??null});if(t)throw t;se.invalidateQueries({queryKey:["programacao_alteracoes"]})}catch(t){W({title:"Erro ao registrar alteração",description:t.message,variant:"destructive"})}},ri=d.useMemo(()=>{const a=new Set;return fe.forEach(s=>{s.status_liberacao==="devolvida"||s.status_liberacao==="em_alteracao_pcp"||(s.programacao_diaria_itens||[]).forEac
183h(t=>{t.pedido_id&&a.add(t.pedido_id)})}),a},[fe]),Ra=si.filter(a=>!ri.has(a.id)),{conflitosPendentesIds:ii,conflitosPorData:js}=d.useMemo(()=>{var o,m,l,p;const a=new Set,s=new Map,t=new Map;for(const D of Ra){if(!D.data_producao||((o=D.racoes)==null?void 0:o.tag)==="Pesadinha"||(((m=D.racoes)==null?void 0:m.nome)||"").toUpperCase().startsWith("PESADINHA")||!Number(D.prioridade)||Number(D.prioridade)<=0)continue;const T=t.get(D.data_producao)||[];T.push(D),t.set(D.data_producao,T)}for(const[D,b]of t){b.sort((U,C)=>Number(U.prioridade)-Number(C.prioridade));const T=Q(b.map(U=>{var C;return{racao_id:U.racao_id,racao_nome:(C=U.racoes)==null?void 0:C.nome}}));if(T.length===0)continue;const N=[];for(const U of T){const C=b[U.index],r=b[U.index-1];C!=null&&C.id&&a.add(C.id),N.push({prevNome:((l=r==null?void 0:r.racoes)==null?void 0:l.nome)||"â",nextNome:((p=C==null?void 0:C.racoes)==null?void 0:p.nome)||"â"})}s.set(D,N)}return{conflitosPendentesIds:a,conflitosPorData:s}},[Ra,Q]),vs=d.useMemo(()=>{var s,t,o,m;const a=new Map;for(const l of Ra){if(!l.data_producao||((s=l.racoes)==null?void 0:s.tag)==="Pesadinha"||(((t=l.racoes)==null?void 0:t.nome)||"").toUpperCase().startsWith("PESADINHA")||Number(l.prioridade)>0)continue;const D=a.get(l.data_producao)||[];D.push({id:l.id,nome:((o=l.racoes)==null?void 0:o.nome)||"â",cliente:((m=l.clientes)==null?void 0:m.nome)||l.cliente_nome||""}),a.set(l.data_producao,D)}return a},[Ra]),Po=d.useRef(null);d.useEffect(()=>{if(k)return;const a=i.get("prog"),s=i.get("action");if(!a||!s||Rt)return;const t=fe.find(m=>m.id===a);if(!t)return;const o=`${a}:${s}`;Po.current!==o&&(Po.current=o,s==="view"?ua(a):s==="assinar"?t.status_liberacao==="aguardando_qualidade"?bs(a):ua(a):s==="devolver"&&(t.status_liberacao==="aguardando_qualidade"?ys(a):ua(a)),i.delete("prog"),i.delete("action"),x(i,{replace:!0}))},[fe,Rt,i]);const ni=async()=>{Hs(!0);try{if(P){W({title:"Aguarde â carregando regras de contaminação",description:"Tente novamente em alguns segundos.",variant:"destructive"});return}const a=I(E,"yyyy-MM-dd"),s=fe.filter(U=>U.data_producao===a),t=new Set;s.forEach(U=>{(U.programacao_diaria_itens||[]).forEach(C=>{C.pedido_id&&t.add(C.pedido_id)})});const o=Me.filter(U=>{var C,r;return U.data_producao===a&&!U.cancelado&&!U.previsao&&!t.has(U.id)&&!(((C=U.racoes)==null?void 0:C.tag)==="Pesadinha"||(((r=U.racoes)==null?void 0:r.nome)||"").toUpperCase().startsWith("PESADINHA"))});if(o.length===0){W({title:s.length>0?"Nenhum pedido restante para uma nova grade nesta data":"Nenhum pedido oficial ativo para esta data (pedidos em Previsão não entram na programação)",variant:"destructive"});return}o.sort((U,C)=>(Number(U.prioridade)||9999)-(Number(C.prioridade)||9999));const m=Q(o.map(U=>{var C;return{racao_id:U.racao_id,racao_nome:(C=U.racoes)==null?void 0:C.nome}}));if(m.length>0){const U=m.slice(0,3).map(C=>`⢠${C.racaoOrigemNome||"â"} â ${C.racaoDestinoNome||"â"}`).join(` 184`);W({title:`Grade bloqueada: ${m.length} conflito(s) de contaminação`,description:`Reordene as prioridades antes de gerar a grade. 185${U}${m.length>3?` 186â¦`:""}`,variant:"destructive"});return}const{data:l,error:p}=await f.from("programacoes_diarias").insert({data_producao:a,created_by:pe==null?void 0:pe.id,observacoes:null}).select().single();if(p)throw p;const D=o.map((U,C)=>({programacao_id:l.id,pedido_id:U.id,prioridade:U.prioridade||C+1})),{error:b}=await f.from("programacao_diaria_itens").insert(D);if(b)throw b;se.invalidateQueries({queryKey:["programacoes_diarias"]});const T=l.grade_numero||s.length+1,N=T===1?"1ª Grade":T===2?"2ª Grade":`${T}ª Grade`;W({title:`${N} gerada com ${o.length} pedidos!`})}catch(a){W({title:"Erro ao gerar programação",description:a.message,variant:"destructive"})}finally{Hs(!1)}},di=Sa({mutationFn:async a=>{const{error:s}=await f.from("programacoes_diarias").delete().eq("id",a);if(s)throw s},onSuccess:()=>{se.invalidateQueries({queryKey:["programacoes_diarias"]}),W({title:"Programação removida!"})},onError:a=>W({title:"Erro",description:a.message,variant:"destructive"})}),So=Sa({mutationFn:async({progId:a,pedidoId:s})=>{const{error:t}=await f.from("programacao_diaria_itens").delete().eq("programacao_id",a).eq("pedido_id",s);if(t)throw t},onSuccess:()=>{se.invalidateQueries({queryKey:["programacoes_diarias"]}),W({title:"Pedido removido da programação"})},onError:a=>W({title:"Erro",description:a.message,variant:"destructive"})}),li=Sa({mutationFn:async({progId:a,pedidoId:s,prioridade:t})=>{const o=Me.find(l=>l.id===s);if(o&&za(o))throw new Error(`Pedido bloqueado pela Qualidade â ${Ut(o)}. Resolva a pendência em Qualidade ⺠Pendências de Fórmulas.`);const{error:m}=await f.from("programacao_diaria_itens").insert({programacao_id:a,pedido_id:s,prioridade:t});if(m)throw m},onSuccess:()=>{se.invalidateQueries({queryKey:["programacoes_diarias"]}),W({title:"Pedido adicionado à programação"})},onError:a=>W({title:"Erro",description:a.message,variant:"destructive"})}),Co=a=>
186{if(!(_!=null&&_.assinatura_url)){W({title:"Nenhuma assinatura cadastrada",description:"Cadastre sua assinatura em Meu Perfil antes de assinar a programação.",variant:"destructive"});return}ns(a),Gs(!0)},ci=async()=>{if(!(!is||!(_!=null&&_.assinatura_url)||!pe))try{const a=fe.find(C=>C.id===is);if(!a)throw new Error("Programação não encontrada");const s=(a.programacao_diaria_itens||[]).map(C=>C.pedido_id),t=Me.filter(C=>s.includes(C.id)&&!C.cancelado).filter(C=>{var r,K;return!(((r=C.racoes)==null?void 0:r.tag)==="Pesadinha"||(((K=C.racoes)==null?void 0:K.nome)||"").toUpperCase().startsWith("PESADINHA"))}).sort((C,r)=>(C.prioridade||999)-(r.prioridade||999)),o=Q(t.map(C=>{var r;return{racao_id:C.racao_id,racao_nome:(r=C.racoes)==null?void 0:r.nome}}));if(o.length>0){const C=o[0];W({title:"Não é possÃvel assinar: contaminação na sequência",description:`Conflito entre "${C.racaoOrigemNome||"?"}" â "${C.racaoDestinoNome||"?"}". Reordene os pedidos antes de assinar.`,variant:"destructive"}),ns(null);return}const{data:m,error:l}=await f.storage.from("assinaturas-usuarios").download(_.assinatura_url);if(l)throw l;const p=await new Promise((C,r)=>{const K=new FileReader;K.onload=()=>C(K.result),K.onerror=r,K.readAsDataURL(m)}),D=new Date().toISOString(),b=`Programação Nº ${a.numero} ⢠${a.data_producao}`,T=await sr({programacao_id:a.id,numero:a.numero,data_producao:a.data_producao,assinante:_.full_name,codigo:_.codigo||null,assinado_em:D,papel:"pcp"}),{error:N}=await f.from("programacoes_diarias").update({assinatura_pcp_url:p,assinatura_pcp_user_id:pe.id,assinatura_pcp_nome:_.full_name,assinatura_pcp_codigo:_.codigo||null,assinatura_pcp_funcao:_.funcao||null,assinatura_pcp_em:D,assinatura_pcp_hash:T}).eq("id",a.id);if(N)throw N;const{error:U}=await f.from("assinaturas_documentos").insert({user_id:pe.id,tipo_documento:"programacao_producao",documento_id:a.id,documento_ref:b,papel:"pcp",assinatura_url:_.assinatura_url,nome_assinante:_.full_name,funcao_assinante:_.funcao||null,codigo_assinante:_.codigo||null,hash_conteudo:T,assinado_em:D,user_agent:navigator.userAgent});W({title:"Programação assinada pelo PCP â"}),se.invalidateQueries({queryKey:["programacoes_diarias"]}),ns(null)}catch(a){W({title:"Erro ao assinar",description:a.message,variant:"destructive"})}},bs=a=>{if(!Et){W({title:"Acesso negado",description:"Apenas usuários da Qualidade (ou Master) podem liberar a programação.",variant:"destructive"});return}if(!(_!=null&&_.assinatura_url)){W({title:"Nenhuma assinatura cadastrada",description:"Cadastre sua assinatura em Meu Perfil antes de liberar a programação.",variant:"destructive"});return}Ws(a),Js(!0)},mi=async()=>{if(!(!ds||!(_!=null&&_.assinatura_url)||!pe))try{const a=fe.find(T=>T.id===ds);if(!a)throw new Error("Programação não encontrada");if(!a.assinatura_pcp_url)throw new Error("Programação ainda não foi assinada pelo PCP");const{data:s,error:t}=await f.storage.from("assinaturas-usuarios").download(_.assinatura_url);if(t)throw t;const o=await new Promise((T,N)=>{const U=new FileReader;U.onload=()=>T(U.result),U.onerror=N,U.readAsDataURL(s)}),m=new Date().toISOString(),l=`Programação Nº ${a.numero} ⢠${a.data_producao}`,p=await sr({programacao_id:a.id,numero:a.numero,data_producao:a.data_producao,hash_pcp:a.assinatura_pcp_hash,assinante:_.full_name,codigo:_.codigo||null,assinado_em:m,papel:"qualidade"}),{error:D}=await f.from("programacoes_diarias").update({assinatura_qualidade_url:o,assinatura_qualidade_user_id:pe.id,assinatura_qualidade_nome:_.full_name,assinatura_qualidade_codigo:_.codigo||null,assinatura_qualidade_funcao:_.funcao||null,assinatura_qualidade_em:m,assinatura_qualidade_hash:p}).eq("id",a.id);if(D)throw D;const{error:b}=await f.from("assinaturas_documentos").insert({user_id:pe.id,tipo_documento:"programacao_producao",documento_id:a.id,documento_ref:l,papel:"qualidade",assinatura_url:_.assinatura_url,nome_assinante:_.full_name,funcao_assinante:_.funcao||null,codigo_assinante:_.codigo||null,hash_conteudo:p,assinado_em:m,user_agent:navigator.userAgent});await f.from("programacoes_historico_liberacao").insert({programacao_id:a.id,acao:"liberado_qualidade",autor_user_id:pe.id,autor_nome:_.full_name,autor_codigo:_.codigo||null,autor_funcao:_.funcao||null,hash_documento:p}),W({title:"Programação Liberada para Produção â"}),se.invalidateQueries({queryKey:["programacoes_diarias"]}),Ws(null)}catch(a){W({title:"Erro ao liberar",description:a.message,variant:"destructive"})}},ys=a=>{ls(a)},ui=async()=>
186{if(!(!qt||!cs||!pe))try{const a=fe.find(t=>t.id===qt);if(!a)throw new Error("Programação não encontrada");const{error:s}=await f.from("programacoes_diarias").update({status_liberacao:"devolvida",assinatura_pcp_url:null,assinatura_pcp_user_id:null,assinatura_pcp_nome:null,assinatura_pcp_codigo:null,assinatura_pcp_funcao:null,assinatura_pcp_em:null,assinatura_pcp_hash:null,devolucao_motivo:cs,devolucao_por_user_id:pe.id,devolucao_por_nome:(_==null?void 0:_.full_name)||null,devolucao_em:new Date().toISOString(),devolucao_count:(a.devolucao_count||0)+1}).eq("id",a.id);if(s)throw s;await f.from("programacoes_historico_liberacao").insert({programacao_id:a.id,acao:"devolvida",motivo:cs,autor_user_id:pe.id,autor_nome:(_==null?void 0:_.full_name)||null,autor_codigo:(_==null?void 0:_.codigo)||null,autor_funcao:(_==null?void 0:_.funcao)||null}),W({title:"Programação devolvida à PCP"}),se.invalidateQueries({queryKey:["programacoes_diarias"]}),ls(null),ms("")}catch(a){W({title:"Erro ao devolver",description:a.message,variant:"destructive"})}},Mo=a=>{Dt(a),pt(""),gs(!0)},pi=async a=>{if(!hs)return;const{data:s,error:t}=await f.rpc("programacao_reabrir_pcp",{_programacao_id:hs,_justificativa:Rr,_senha:a});if(t)throw new Error(t.message);if(s&&s.ok===!1)throw new Error(s.mensagem||"Falha ao reabrir programação");W({title:"Programação reaberta para alteração â",description:"Após ajustar, reenvie para a Qualidade assinando novamente como PCP."}),se.invalidateQueries({queryKey:["programacoes_diarias"]}),se.invalidateQueries({queryKey:["programacao_alteracoes"]}),Dt(null),pt("")},xi=d.useCallback(async()=>{var D;const a=!!be;if(a&&(a&&dt!=="pendente"&&!Ga)){const{error:b}=await f.from("pedidos").update({observacoes:Ct||null}).eq("id",be);if(b)throw b;se.invalidateQueries({queryKey:["pedidos"]}),Ze(!1),$a(),W({title:"Pedido atualizado!"});return}const t={cliente_id:aa&&de?de.cliente_id:q,data_producao:aa&&de?de.data_producao:h?I(h,"yyyy-MM-dd"):"",racao_id:aa&&de?de.racao_id:Ve||null,numero_pedido:Aa,peso_solicitado:parseFloat(ea),produtor_id:aa&&de?de.produtor_id:wa,numero_grade:lt,cancelado:qa,observacoes:Ct||null,ordem_producao:as||null};aa&&de&&(t.pedido_pai_id=de.id);const o=Wa.find(b=>b.id===t.racao_id);if(o!=null&&o.is_medicada){const b=!!ut.path,T=!!Ee;if(!b&&!T){W({title:"Receituário obrigatório",description:`A ração "${o.nome}" é Medicada. Anexe o Receituário ou solicite Liberação da Qualidade.`,variant:"destructive"});return}t.receituario_url=ut.path,t.receituario_nome=ut.nome,b&&(t.receituario_uploaded_at=new Date().toISOString(),t.receituario_uploaded_by=((D=(await f.auth.getUser()).data.user)==null?void 0:D.id)||null),t.liberacao_sem_receituario=T,t.liberacao_sem_receituario_motivo=(Ee==null?void 0:Ee.motivo)||null,t.liberacao_sem_receituario_por=(Ee==null?void 0:Ee.liberador_id)||null,t.liberacao_sem_receituario_por_nome=(Ee==null?void 0:Ee.liberador_nome)||null,t.liberacao_sem_receituario_codigo=(Ee==null?void 0:Ee.liberador_codigo)||null,t.liberacao_sem_receituario_em=T?new Date().toISOString():null}const m=t.racao_id,l=t.cliente_id,p=t.peso_solicitado;if(!a&&m&&l&&p>0)try{const{data:b}=await f.from("racao_formula_versoes").select("id, peso_padrao_snapshot").eq("racao_id",m).eq("is_active",!0).maybeSingle();if(b){const{data:T}=await f.from("racoes").select("peso_padrao").eq("id",m).single(),{data:N}=await f.from("configuracoes").select("valor").eq("chave","peso_padrao_global").maybeSingle(),U=b.peso_padrao_snapshot||(T==null?void 0:T.peso_padrao)||(N!=null&&N.valor?Number(N.valor):2e3),C=p/U,{data:r=[]}=await f.from("racao_materias_primas").select("codigo_mp, nome_mp, quantidade").eq("versao_id",b.id);if(r.length>0){const K=r.map(je=>je.codigo_mp).filter(Boolean),Ae=new Map;for(let je=0;je<K.length;je+=100){const qe=K.slice(je,je+100),{data:ta=[]}=await f.from("vw_estoque_cliente_saldo").select("codigo_produto, saldo_kg").eq("cliente_id",l).in("codigo_produto",qe);(ta||[]).forEach(ra=>Ae.set(ra.codigo_produto,Number(ra.saldo_kg??0)))}const Ge=[];if(r.forEach(je=>{if(!je.codigo_mp||!je.quantidade)return;const qe=Number(je.quantidade)*C,ta=Ae.get(je.codigo_mp)||0,ra=ta-qe;ra<0&&Ge.push({mp:je.nome_mp||je.codigo_mp,codigo:je.codigo_mp,necessario:Math.round(qe*1e3)/1e3,saldo:Math.round(ta*1e3)/1e3,novoSaldo:Math.round(ra*1e3)/1e3})}),Ge.length>0){Tt(Ge),Lt({payload:t,ingredientes:r,fator:C,selectedClienteId:l}),zt(!0);return}await Ao(t,r,C,l);return}}}catch{}await hi(t,a)},[be,dt,Ga,aa,de,q,h,Ve,Aa,ea,wa,lt,qa,Ct,as]),Ft=async(a,s)=>{const t=`PED-${a}`,{data:o}=await f.from("estoque_clientes_movimentacoes").select("*").eq("cliente_id",s).or(`codigo_movimentacao.eq.${t}
186,codigo_movimentacao.like.${t}/L%`);if(!o||o.length===0)return;const{data:m}=await f.from("estoque_clientes_movimentacoes").select("id").eq("cliente_id",s).or(`codigo_movimentacao.eq.CANC-${a},codigo_movimentacao.like.CANC-${a}/L%`).limit(1);if(!(m&&m.length>0)){for(const l of o){const p=Number(l.saida)||0;p<=0||await f.from("estoque_clientes_movimentacoes").insert({cliente_id:s,codigo_produto:l.codigo_produto,descricao_movimentacao:`Cancelamento pedido #${a} - devolução estoque (lote ${l.lote})`,codigo_movimentacao:(l.codigo_movimentacao||`PED-${a}`).replace(`PED-${a}`,`CANC-${a}`),data_movimentacao:I(new Date,"yyyy-MM-dd"),entrada:p,saida:0,lote:l.lote,nf:l.nf,data_fabricacao:l.data_fabricacao,data_validade:l.data_validade,lote_legado:l.lote_legado??void 0,origem_pagina:"pedido",id_proprietario:s})}se.invalidateQueries({queryKey:["estoque-cliente"]})}},hi=async(a,s)=>{if(s){if(a.cancelado===!0){const{data:o}=await f.from("pedidos").select("numero, cancelado, cliente_id").eq("id",be).single();o&&!o.cancelado&&await Ft(o.numero,o.cliente_id),a.prioridade=0,await f.from("programacao_diaria_itens").update({prioridade:0}).eq("pedido_id",be)}const{error:t}=await f.from("pedidos").update(a).eq("id",be);if(t)throw t}else{if(pa&&(!a.prioridade||a.prioridade<=0)){const{data:l}=await f.from("programacao_diaria_itens").select("prioridade, pedidos:pedido_id(prioridade, cancelado)").eq("programacao_id",pa),p=(l||[]).map(b=>{var T;return Number(((T=b.pedidos)==null?void 0:T.prioridade)||b.prioridade)||0}).filter(b=>b>0),D=p.length?Math.max(...p)+1:1;a.prioridade=D}const t={...a,previsao:!pa},{data:o,error:m}=await f.from("pedidos").insert(t).select("id").single();if(m)throw m;pa&&(o!=null&&o.id)&&(await f.from("programacao_diaria_itens").insert({programacao_id:pa,pedido_id:o.id,prioridade:a.prioridade||999}),se.invalidateQueries({queryKey:["programacoes_diarias"]}))}se.invalidateQueries({queryKey:["pedidos"]}),se.invalidateQueries({queryKey:["estoque-clientes"]}),se.invalidateQueries({queryKey:["estoque-clientes-mov"]}),Ze(!1),$a(),W({title:s?"Pedido atualizado!":"Pedido cadastrado!"})},Ao=async(a,s,t,o)=>{if(pa&&(!a.prioridade||a.prioridade<=0)){const{data:b}=await f.from("programacao_diaria_itens").select("prioridade, pedidos:pedido_id(prioridade, cancelado)").eq("programacao_id",pa),T=(b||[]).map(U=>{var C;return Number(((C=U.pedidos)==null?void 0:C.prioridade)||U.prioridade)||0}).filter(U=>U>0),N=T.length?Math.max(...T)+1:1;a.prioridade=N}const m={...a,previsao:!pa},{data:l,error:p}=await f.from("pedidos").insert(m).select("id, numero").single();if(p)throw p;const D=(l==null?void 0:l.numero)||"";pa&&(l!=null&&l.id)&&(await f.from("programacao_diaria_itens").insert({programacao_id:pa,pedido_id:l.id,prioridade:a.prioridade||999}),se.invalidateQueries({queryKey:["programacoes_diarias"]}));for(const b of s){if(!b.codigo_mp||!b.quantidade)continue;const T=Number(b.quantidade)*t,N=`PED-${D}`;let U=[];try{U=await _n(o,b.codigo_mp,T)}catch(r){W({title:"Reserva sem lote disponÃvel",description:(r==null?void 0:r.message)||`Produto ${b.codigo_mp} sem lote com saldo.`,variant:"destructive"});continue}for(let r=0;r<U.length;r++){const K=U[r];await f.from("estoque_clientes_movimentacoes").insert({cliente_id:o,codigo_produto:b.codigo_mp,descricao_movimentacao:`Reserva pedido #${D} - ${b.nome_mp||b.codigo_mp} (lote ${K.lote})`,codigo_movimentacao:jn(N,r,U.length),data_movimentacao:I(new Date,"yyyy-MM-dd"),entrada:0,saida:K.quantidade,lote:K.lote,nf:K.nf,data_fabricacao:K.data_fabricacao,data_validade:K.data_validade,origem_pagina:"pedido",id_proprietario:o})}const{data:C}=await f.from("estoque_clientes").select("id").eq("cliente_id",o).eq("codigo_produto",b.codigo_mp).maybeSingle();C||await f.from("estoque_clientes").insert({cliente_id:o,produto:b.nome_mp||b.codigo_mp,codigo_produto:b.codigo_mp,quantidade:0})}se.invalidateQueries({queryKey:["pedidos"]}),se.invalidateQueries({queryKey:["estoque-clientes",o]}),se.invalidateQueries({queryKey:["estoque-clientes-mov",o]}),se.invalidateQueries({queryKey:["estoque-cliente"]}),Ze(!1),$a(),W({title:"Pedido cadastrado e estoque reservado!"})},gi=async()=>
186{if(lo){mo(!0);try{const{payload:a,ingredientes:s,fator:t,selectedClienteId:o}=lo;await Ao(a,s,t,o)}catch(a){W({title:"Erro",description:a.message,variant:"destructive"})}finally{mo(!1),zt(!1),Lt(null),Tt([])}}},Ns=Sa({mutationFn:xi,onError:a=>W({title:"Erro",description:a.message,variant:"destructive"})}),ws=Sa({mutationFn:async({pedidoId:a,prioridade:s})=>{const{error:t}=await f.from("pedidos").update({prioridade:s}).eq("id",a);if(t)throw t;const{error:o}=await f.from("programacao_diaria_itens").update({prioridade:s}).eq("pedido_id",a);if(o)throw o},onSuccess:()=>{se.invalidateQueries({queryKey:["pedidos"]}),se.invalidateQueries({queryKey:["programacoes_diarias"]})},onError:a=>W({title:"Erro",description:a.message,variant:"destructive"})}),qo=Sa({mutationFn:async a=>{const{error:s}=await f.from("pedidos").update({previsao:!1}).eq("id",a);if(s)throw s},onSuccess:()=>{se.invalidateQueries({queryKey:["pedidos"]}),W({title:"Pedido oficializado!",description:"Agora ele pode entrar na programação."})},onError:a=>W({title:"Erro ao oficializar",description:a.message,variant:"destructive"})}),fi=Sa({mutationFn:async a=>{const{data:s}=await f.from("pedidos").select("numero, cancelado, cliente_id").eq("id",a).single();s&&!s.cancelado&&await Ft(s.numero,s.cliente_id);const{error:t}=await f.from("pedidos").delete().eq("id",a);if(t)throw t},onSuccess:()=>{se.invalidateQueries({queryKey:["pedidos"]}),W({title:"Pedido removido!"})},onError:a=>W({title:"Erro",description:a.message,variant:"destructive"})}),et=Sa({mutationFn:async a=>{const{data:s}=await f.from("pedidos").select("numero, cancelado, cliente_id").eq("id",a).single();s&&!s.cancelado&&await Ft(s.numero,s.cliente_id);const{error:t}=await f.from("pedidos").update({cancelado:!0}).eq("id",a);if(t)throw t},onSuccess:()=>{se.invalidateQueries({queryKey:["pedidos"]}),se.invalidateQueries({queryKey:["estoque-clientes"]}),se.invalidateQueries({queryKey:["estoque-clientes-mov"]}),W({title:"Pesadinha cancelada!"}),Ss(null)},onError:a=>W({title:"Erro",description:a.message,variant:"destructive"})}),[Ps,Ss]=d.useState(null),[ko,_i]=d.useState("lista"),[Cs,ji]=d.useState("normais"),[It,Ms]=d.useState(null),vi=Sa({mutationFn:async({id:a,justificativa:s})=>{const{data:t}=await f.from("pedidos").select("numero, cancelado, cliente_id").eq("id",a).single();t&&!t.cancelado&&await Ft(t.numero,t.cliente_id);const{error:o}=await f.rpc("cancelar_pedido_com_justificativa",{_pedido_id:a,_justificativa:s});if(o)throw o},onSuccess:()=>{se.invalidateQueries({queryKey:["pedidos"]}),se.invalidateQueries({queryKey:["estoque-clientes"]}),se.invalidateQueries({queryKey:["estoque-clientes-mov"]}),W({title:"Pedido cancelado!",description:"Justificativa registrada no histórico."}),Ms(null)},onError:a=>W({title:"Erro ao cancelar",description:a.message,variant:"destructive"})}),$o=a=>{Pt(a.id),St(a.status_producao||"pendente"),S(a.cliente_id),te(a.data_producao?new Date(a.data_producao+"T00:00:00"):void 0),ba(a.racao_id||""),ya(a.numero_pedido),Na(String(a.peso_solicitado)),oa(a.produtor_id),ct(a.numero_grade),Zt(a.cancelado),es(a.observacoes||""),ts(a.ordem_producao||""),ss(a.prioridade??0),Mt({path:a.receituario_url||null,nome:a.receituario_nome||null}),a.liberacao_sem_receituario?Va({motivo:a.liberacao_sem_receituario_motivo||"",liberador_id:a.liberacao_sem_receituario_por||"",liberador_nome:a.liberacao_sem_receituario_por_nome||"",liberador_codigo:a.liberacao_sem_receituario_codigo||null}):Va(null),Ze(!0)},ha=(a,s={})=>e.jsx(qs,{ariaLabel:"Pedidos operacionais",children:e.jsxs(ja,{className:"min-w-[1500px]",children:[e.jsxs(Ma,{children:[e.jsxs(ge,{className:"table-header",children:[e.jsx(Qe,{sortKey:"numero",currentSort:Oe,onToggle:Be,children:"Nº"}),e.jsx(Qe,{sortKey:"dataPedido",currentSort:Oe,onToggle:Be,children:"Data Pedido"}),e.jsx(Qe,{sortKey:"codCliente",currentSort:Oe,onToggle:Be,children:"Cód. Cliente"}),e.jsx(Qe,{sortKey:"dataProducao",currentSort:Oe,onToggle:Be,children:"Data Produção"}),e.jsx(Qe,{sortKey:"codRacao",currentSort:Oe,onToggle:Be,children:"Cód. Ração"}),e.jsx(Qe,{sortKey:"produto",currentSort:Oe,onToggle:Be,children:"Produto"}),e.jsx(Qe,{sortKey:"numPedido",currentSort:Oe,onToggle:Be,children:"Nº Pedido"}),e.jsx(Qe,{sortKey:"peso",currentSort:Oe,onToggle:Be,children:"Peso (kg)"}),e.jsx(Qe,{sortKey:"produtor",currentSort:Oe,onToggle:Be,children:"Produtor"}),e.jsx(Qe,{sortKey:"grade",currentSort:Oe,onToggle:Be,children:"Nº Grade"}),e.jsx(Qe,{sortKey:"ordemProducao",currentSort:Oe,onToggle:Be,children:"Ordem Produção"}),e.jsx(Qe,{sortKey:"lote",currentSort:Oe,onToggle:Be,children:"Lote"}),!s.hidePrioridade&&e.jsx(Qe,{sortKey:"prioridade",currentSort:Oe,onToggle:Be,children:"Prioridade"}),!s.hideSilo&&e.jsx(Qe,{sortKey:"silo",currentSort:Oe,onToggle:Be,children:"Silo Expedição"}),e.jsx(Qe,{sortKey:"status",currentSort:Oe,onToggle:Be,children:"Status"}),e.jsx($,{className:"w-24",children:"Ações"})]}),e.jsxs(ge,{children:[e.jsx($,{children:e.jsx(Ke,{value:Fe.numero||"",onChange:t=>Ie("numero",t)})}),e.jsx($,{children:e.jsx(Ke,{value:Fe.dataPedido||"",onChange:t=>Ie("dataPedido",t)})}),e.jsx($,{children:e.jsx(Ke,{value:Fe.codCliente||"",onChange:t=>Ie("codCliente",t)})}),e.jsx($,{children:e.jsx(Ke,{value:Fe.dataProducao||"",onChange:t=>Ie("dataProducao",t)})}),e.jsx($,{children:e.jsx(Ke,{value:Fe.codRacao||"",onChange:t=>Ie("codRacao",t)})}),e.jsx($,{children:e.jsx(Ke,{value:Fe.produto||"",onChange:t=>Ie("produto",t)})}),e.jsx($,{children:e.jsx(Ke,{value:Fe.numPedido||"",onChange:t=>Ie("numPedido",t)})}),e.jsx($,{children:e.jsx(Ke,{value:Fe.peso||"",onChange:t=>Ie("peso",t)})}),e.jsx($,{children:e.jsx(Ke,{value:Fe.produtor||"",onChange:t=>Ie("produtor",t)})}),e.jsx($,{children:e.jsx(Ke,{value:Fe.grade||"",onChange:t=>Ie("grade",t)})}),e.jsx($,{children:e.jsx(Ke,{value:Fe.ordemProducao||"",onChange:t=>Ie("ordemProducao",t)})}),e.jsx($,{children:e.jsx(Ke,{value:Fe.lote||"",onChange:t=>Ie("lote",t)})}),!s.hidePrioridade&&e.jsx($,{children:e.jsx(Ke,{value:Fe.prioridade||"",onChange:t=>Ie("prioridade",t)})}),!s.hideSilo&&e.jsx($,{children:e.jsx(Ke,{value:Fe.silo||"",onChange:t=>Ie("silo",t)})}),e.jsx($,{children:e.jsx(Ke,{value:Fe.status||"",onChange:t=>Ie("status",t)})}),e.jsx($,{})]})]}),e.jsx(va,{children:Qr?e.jsx(ge,{children:e.jsx(c,{colSpan:16,className:"text-center text-muted-foreground",children:"Carregando..."})}):a.length===0?e.jsx(ge,{children:e.jsx(c,{colSpan:16,className:"text-center text-muted-foreground",children:"Nenhum pedido encontrado"})}):a.map(t=>{var o,m,l,p,D;return e.jsxs(ge,{className:rt(!t.produtor_id&&!t.cancelado&&"bg-amber-500/10"),children:[e.jsxs(c,{className:"font-medium",children:["PP-",t.numero,t.pedido_pai_id&&(()=>{const b=Me.find(T=>T.id===t.pedido_pai_id);return b?e.jsxs(J,{variant:"outline",className:"ml-1 text-xs",children:["Inc. #",b.numero]}):e.jsx(J,{variant:"outline",className:"ml-1 text-xs",children:"Inc."})})()]}),e.jsx(c,{children:t.created_at?I(new Date(t.created_at),"dd/MM/yyyy"):"â"}),e.jsx(c,{children:((o=t.clientes)==null?void 0:o.codigo)||(t.cliente_id?"â":e.jsx("span",{className:"text-muted-foreground italic",children:"Cliente a definir"}))}),e.jsx(c,{children:t.data_producao?I(new Date(t.data_producao+"T00:00:00"),"dd/MM/yyyy"):"â"}),e.jsx(c,{children:ir(t).codigo}),e.jsxs(c,{children:[ir(t).nome,((m=t.racoes)==null?void 0:m.is_medicada)&&e.jsx("span",{style:{color:"#dc2626",fontWeight:600},children:" (Medicada)"}),t.ultra_des_versao&&e.jsxs("span",{className:"ml-1 text-[10px] text-muted-foreground",children:["v",t.ultra_des_versao]})]}),e.jsx(c,{children:Wi(t.numero_pedido)}),e.jsx(c,{className:"text-right",children:Number(t.peso_solicitado).toLocaleStr
186ing("pt-BR")}),e.jsx(c,{children:((l=t.produtores)==null?void 0:l.nome)||"â"}),e.jsx(c,{children:t.numero_grade}),e.jsx(c,{children:t.ordem_producao||"â"}),e.jsx(c,{children:t.lote_producao||"â"}),!s.hidePrioridade&&e.jsx(c,{children:e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsxs(Oa,{value:String(t.prioridade??0),onValueChange:b=>ws.mutate({pedidoId:t.id,prioridade:Number(b)}),children:[e.jsx(Ba,{className:"h-8 text-xs w-20",children:e.jsx(Ka,{})}),e.jsxs(Qa,{children:[e.jsx(ca,{value:"0",children:"â"}),(()=>{const b=Me.filter(T=>T.data_producao===t.data_producao&&!T.cancelado);return Array.from({length:b.length+1},(T,N)=>N+1).filter(T=>T===(t.prioridade??0)||!b.some(N=>N.prioridade===T&&N.id!==t.id)).map(T=>e.jsxs(ca,{value:String(T),children:[T,"º"]},T))})()]})]}),ii.has(t.id)&&e.jsxs(J,{variant:"destructive",className:"text-[10px] gap-1",title:"Esta ração não pode ser produzida logo após a anterior pela tabela de contaminação. Reordene as prioridades.",children:[e.jsx(ga,{className:"h-3 w-3"})," Contaminação"]})]})}),!s.hideSilo&&e.jsx(c,{children:((p=t.silos_expedicao)==null?void 0:p.nome)||((D=(t.ordens_carregamento||[]).find(b=>b.silo_expedicao))==null?void 0:D.silo_expedicao)||"â"}),e.jsxs(c,{children:[!t.produtor_id&&!t.cancelado&&e.jsx(J,{className:"bg-amber-500 text-white mr-1",children:"Incompleto"}),za(t)&&!t.cancelado&&e.jsxs(J,{variant:"destructive",className:"mr-1 gap-1",title:Ut(t),children:[e.jsx(ga,{className:"h-3 w-3"})," ",Ts(t)]}),t.cancelado?e.jsx(J,{variant:"destructive",children:"Cancelado"}):t.previsao?e.jsx(J,{className:"bg-sky-500 text-white",title:"Pedido em Previsão â não entra na programação até ser Oficializado",children:"Previsão"}):(t.ordens_carregamento||[]).some(N=>N.status==="finalizado")?e.jsx(J,{className:"bg-emerald-600 text-white",children:"Entregue"}):t.silo_expedicao_id?e.jsx(J,{className:"bg-green-500 text-white",children:"Finalizado"}):t.status_producao==="em_andamento"?e.jsx(J,{className:"bg-amber-500 text-white",children:"Em Andamento"}):e.jsx(J,{variant:"secondary",children:"Pendente"})]}),e.jsx(c,{children:e.jsxs("div",{className:"flex gap-1",children:[t.previsao&&!t.cancelado&&e.jsx(O,{variant:"ghost",size:"icon",title:"Oficializar pedido (libera para entrar na programação)",onClick:()=>qo.mutate(t.id),disabled:qo.isPending||za(t),children:e.jsx(Qt,{className:"h-4 w-4 text-emerald-600"})}),e.jsx(O,{variant:"ghost",size:"icon",onClick:()=>$o(t),children:e.jsx(jt,{className:"h-4 w-4"})}),Da(t)&&!t.cancelado&&e.jsx(O,{variant:"ghost",size:"icon",title:"Cancelar pesadinha",onClick:()=>Ss(t.id),children:e.jsx(Ds,{className:"h-4 w-4 text-destructive"})}),!Da(t)&&!t.cancelado&&e.jsx(O,{variant:"ghost",size:"icon",title:"Cancelar ração (com justificativa)",onClick:()=>Ms(t.id),children:e.jsx(Ds,{className:"h-4 w-4 text-destructive"})}),e.jsx(O,{variant:"ghost",size:"icon",onClick:()=>fi.mutate(t.id),disabled:t.status_producao!=="pendente"&&!Ga,children:e.jsx(ks,{className:"h-4 w-4 text-destructive"})})]})})]},t.id)})})]})}),Do=()=>{const a=fe.find(r=>r.id===At);if(!a)return null;const s=(a.programacao_diaria_itens||[]).map(r=>r.pedido_id),t=Me.filter(r=>s.includes(r.id)).filter(r=>{var K,Ae;return!(((K=r.racoes)==null?void 0:K.tag)==="Pesadinha"||(((Ae=r.racoes)==null?void 0:Ae.nome)||"").toUpperCase().startsWith("PESADINHA"))}).sort((r,K)=>(r.prioridade||999)-(K.prioridade||999)),o=Q(t.filter(r=>!r.cancelado).map(r=>{var K;return{racao_id:r.racao_id,racao_nome:(K=r.racoes)==null?void 0:K.nome,_id:r.id}})),m=new Set;{const r=t.filter(K=>!K.cancelado);for(const K of o){const Ae=r[K.index];Ae&&m.add(Ae.id)}}const l=(a.devolucao_count||0)+gt.filter(r=>r.programacao_id===a.id).length,p=t.reduce((r,K)=>r+Number(K.peso_solicitado||0),0);vr(t);const D=nr(t),b=a.status_liberacao==="devolvida"||a.status_liberacao==="em_alteracao_pcp",T=a.status_liberacao==="liberado_producao"&&t.some(r=>(r.status_producao||"pendente")==="pendente"&&!r.cancelado),N=new Set(s),U=new Set;fe.filter(r=>r.data_producao===a.data_producao&&r.id!==a.id).forEach(r=>
186{(r.programacao_diaria_itens||[]).forEach(K=>{K.pedido_id&&U.add(K.pedido_id)})});const C=b?Me.filter(r=>{var K,Ae;return r.data_producao===a.data_producao&&!r.cancelado&&!N.has(r.id)&&!U.has(r.id)&&!(((K=r.racoes)==null?void 0:K.tag)==="Pesadinha"||(((Ae=r.racoes)==null?void 0:Ae.nome)||"").toUpperCase().startsWith("PESADINHA"))}):[];return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"mb-4 flex flex-col gap-2 pr-6 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("h2",{className:"break-words text-lg font-semibold leading-tight tracking-tight",children:["Programação Nº ",a.numero,a.grade_numero?` â ${a.grade_numero}ª Grade`:""]}),e.jsxs(O,{size:"sm",variant:"outline",onClick:()=>Us(a.id),children:[e.jsx(fr,{className:"h-4 w-4 mr-1"})," Histórico"]})]}),e.jsx("div",{className:"mb-3",children:a.assinatura_pcp_url?e.jsxs("div",{className:"flex items-center gap-2 rounded-md border border-green-200 bg-green-50 px-3 py-2 text-sm",children:[e.jsx(Qt,{className:"h-4 w-4 text-green-700"}),e.jsxs("span",{className:"text-green-800",children:["Assinada pelo PCP por ",e.jsx("strong",{children:a.assinatura_pcp_nome}),a.assinatura_pcp_codigo?` (${a.assinatura_pcp_codigo})`:"",a.assinatura_pcp_em?` em ${I(new Date(a.assinatura_pcp_em),"dd/MM/yyyy HH:mm")}`:""]})]}):e.jsxs("div",{className:"flex flex-col gap-2 rounded-md border border-amber-200 bg-amber-50 px-3 py-2 text-sm sm:flex-row sm:items-center sm:justify-between",children:[e.jsx("span",{className:"text-amber-800",children:"Programação ainda não assinada pelo PCP."}),e.jsxs(O,{size:"sm",onClick:()=>Co(a.id),children:[e.jsx(or,{className:"h-4 w-4 mr-1"})," Assinar PCP"]})]})}),a.status_liberacao==="devolvida"&&a.devolucao_motivo&&e.jsxs("div",{className:"mb-3 rounded-md border border-red-200 bg-red-50 px-3 py-2 text-sm",children:[e.jsxs("div",{className:"flex items-center gap-2 text-red-800",children:[e.jsx(yt,{className:"h-4 w-4"}),e.jsx("strong",{children:"Devolvida pela Qualidade"}),a.devolucao_por_nome?` por ${a.devolucao_por_nome}`:"",a.devolucao_em?` em ${I(new Date(a.devolucao_em),"dd/MM/yyyy HH:mm")}`:""]}),e.jsxs("div",{className:"mt-1 text-red-700",children:[e.jsx("span",{className:"font-medium",children:"Motivo:"})," ",a.devolucao_motivo]})]}),a.status_liberacao==="em_alteracao_pcp"&&e.jsxs("div",{className:"mb-3 rounded-md border border-purple-200 bg-purple-50 px-3 py-2 text-sm",children:[e.jsxs("div",{className:"flex items-center gap-2 text-purple-800",children:[e.jsx(jt,{className:"h-4 w-4"}),e.jsx("strong",{children:"Programação reaberta para alteração pelo PCP"})]}),e.jsxs("div",{className:"mt-1 text-purple-700",children:["Pedidos já em produção/finalizados ficam bloqueados. Após ajustar, ",e.jsx("strong",{children:"assine novamente como PCP"})," para reenviar à Qualidade."]})]}),T&&e.jsxs("div",{className:"mb-3 flex flex-col gap-2 rounded-md border border-purple-200 bg-purple-50/60 px-3 py-2 text-sm sm:flex-row sm:items-center sm:justify-between",children:[e.jsx("span",{className:"text-purple-800",children:"Esta programação está liberada. Para alterar pedidos pendentes, é necessário reabrir e reenviar para a Qualidade."}),e.jsxs(O,{size:"sm",variant:"outline",className:"border-purple-300 text-purple-800 hover:bg-purple-100",onClick:()=>Mo(a.id),children:[e.jsx(jt,{className:"h-4 w-4 mr-1"})," Solicitar Alteração"]})]}),(()=>{const r=gt.filter(K=>K.programacao_id===a.id);return r.length===0?null:e.jsxs("div",{className:"mb-3 rounded-md border border-amber-200 bg-amber-50 px-3 py-2 text-sm",children:[e.jsxs("div",{className:"font-semibold text-amber-900 mb-1",children:["Justificativas de Alteração (",r.length,")"]}),e.jsx("div",{className:"flex flex-col gap-1 text-amber-900",children:r.map((K,Ae)=>e.jsxs("div",{className:"break-words",children:[e.jsxs("span",{className:"font-semibold",children:["Alteração N° ",Ae+1,":"]})," ",e.jsx("span",{className:"font-medium",children:K.justificativa}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[" â ",K.user_nome||"â",K.user_codigo?` (${K.user_codigo})`:"",K.created_at?` em ${I(new Date(K.created_at),"dd/MM/yyyy HH:mm")}`:""]})]},K.id))})]})})(),e.jsx("div",{className:"mb-3",children:a.assinatura_qualidade_url?D?e.jsxs(Fa,{variant:"destructive",children:[e.jsx(ga,{className:"h-4 w-4"}),e.jsxs(Ia,{children:[e.jsx("div",{className:"font-semibold",children:"Liberação inválida â pendência da Qualidade"}),e.jsx("div",{className:"text-xs mt-1",children:D})]})]}):e.jsxs("div",{className:"flex items-center gap-2 rounded-md border border-emerald-200 bg-emerald-50 px-3 py-2 text-sm",children:[e.jsx($s,{className:"h-4 w-4 text-emerald-700"}),e.jsxs("span",{className:"text-emerald-800",children:["Liberada para Produção pela Qualidade â ",e.jsx("strong",{children:a.assinatura_qualidade_nome}),a.assinatura_qualidade_codigo?` (${a.assinatura_qualidade_codigo})`:"",a.assinatura_qualidade_em?` em ${I(new Date(a.assinatura_qualidade_em),"dd/MM/yyyy HH:mm")}`:""]})]}):a.assinatura_pcp_url?e.jsxs("div",{className:"flex flex-col gap-2 rounded-md border border-blue-200 bg-blue-50 px-3 py-2 text-sm sm:flex-row sm:items-center sm:justify-between",children:[e.jsx("span",{className:"text-blue-800",children:D||(Et?"Aguardando Liberação da Qualidade.":"Aguardando Liberação da Qualidade. Apenas usuários da Qualidade podem liberar.")}),Et&&e.jsxs("div",{className:"grid grid-cols-1 gap-2 min-[420px]:grid-cols-2",children:[e.jsxs(O,{size:"sm",variant:"destructive",onClick:()=>ys(a.id),children:[e.jsx(yt,{className:"h-4 w-4 mr-1"})," Devolver"]}),e.jsxs(O,{size:"sm",className:"bg-emerald-600 hover:bg-emerald-700 text-white",disabled:!!D,title:D||void 0,onClick:()=>bs(a.id),children:[e.jsx($s,{className:"h-4 w-4 mr-1"})," Liberar"]})]})]}):null}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-3 text-sm mb-4 text-center",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Data Produção:"}),e.jsx("p",{className:"font-medium",children:I(new Date(a.data_producao+"T00:00:00"),"dd/MM/yyyy")})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Criado em:"}),e.jsx("p",{className:"font-medium",children:I(new Date(a.created_at),"dd/MM/yyyy HH:mm")}
186)]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Nº Alteração:"}),e.jsx("p",{className:"font-medium",children:l})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Total Pedidos:"}),e.jsx("p",{className:"font-medium",children:t.length})]})]}),o.length>0?e.jsxs(Fa,{variant:"destructive",className:"mb-3",children:[e.jsx(ga,{className:"h-4 w-4"}),e.jsxs(Ia,{children:[e.jsxs("div",{className:"font-semibold mb-1",children:[o.length," conflito(s) de contaminação na sequência"]}),e.jsx("ul",{className:"list-disc list-inside text-xs space-y-0.5",children:o.map((r,K)=>e.jsxs("li",{children:["Posição ",r.index+1,": ",e.jsx("strong",{children:r.racaoOrigemNome||"?"})," â ",e.jsx("strong",{children:r.racaoDestinoNome||"?"})]},K))}),e.jsx("div",{className:"mt-2 text-xs",children:"Ajuste a ordem dos pedidos respeitando a tabela de contaminação entre grupos antes de assinar/iniciar a produção."})]})]}):t.length>1?e.jsxs("div",{className:"mb-3 flex items-center gap-2 rounded-md border border-emerald-200 bg-emerald-50 px-3 py-2 text-xs text-emerald-800",children:[e.jsx(Qt,{className:"h-4 w-4"})," Sequência válida â sem conflito de contaminação entre grupos."]}):null,e.jsx(qs,{ariaLabel:"Pedidos da programação",children:e.jsxs(ja,{className:"min-w-[920px]",children:[e.jsx(Ma,{children:e.jsxs(ge,{className:"table-header",children:[e.jsx($,{className:"text-center",children:"Prioridade"}),e.jsx($,{className:"text-center",children:"Nº Grade"}),e.jsx($,{className:"text-center",children:"Cód. Ração"}),e.jsx($,{className:"text-center",children:"Produto"}),e.jsx($,{className:"text-center",children:"Produtor"}),e.jsx($,{className:"text-center",children:"Cliente"}),e.jsx($,{className:"text-center",children:"Qtd (kg)"}),e.jsx($,{className:"text-center",children:"Silo"}),b&&e.jsx($,{className:"w-12 text-center",children:"Ação"})]})}),e.jsxs(va,{children:[t.map(r=>{var K,Ae,Ge,je,qe,ta,ra;return e.jsxs(ge,{className:(()=>{var we;const le=[];if(r.status_producao==="finalizado")return"";const ke=String(r.numero_grade||"").trim();return(!ke||ke==="-")&&le.push("Grade"),!r.produtor_id&&!((we=r.produtores)!=null&&we.nome)&&le.push("Produtor"),r.ordem_producao||le.push("OP"),!r.cancelado&&le.length>0?"animate-blink-red outline outline-2 outline-red-500":""})(),title:(()=>{var we;const le=[];if(r.status_producao==="finalizado")return;const ke=String(r.numero_grade||"").trim();return(!ke||ke==="-")&&le.push("Grade"),!r.produtor_id&&!((we=r.produtores)!=null&&we.nome)&&le.push("Produtor"),r.ordem_producao||le.push("OP"),le.length>0?`Informações faltando: ${le.join(", ")}`:void 0})(),children:[e.jsx(c,{className:"text-center",children:r.cancelado?e.jsx(J,{variant:"outline",className:"text-[10px] bg-red-50 text-red-700 border-red-200",children:"Cancelado"}):b&&(r.status_producao||"pendente")==="pendente"?e.jsxs(Oa,{value:String(r.prioridade??0),onValueChange:le=>{const ke=Number(le);ke!==(r.prioridade??0)&&(async()=>{var we;try{const We=t.find(Ea=>Ea.id!==r.id&&(Ea.prioridade??0)===ke&&ke!==0);We&&await ws.mutateAsync({pedidoId:We.id,prioridade:r.prioridade??0}),await ws.mutateAsync({pedidoId:r.id,prioridade:ke}),Ta(Ea=>{var zo;const Ot=`Troca de prioridade do pedido ${r.numero_grade||""} (${((zo=r.racoes)==null?void 0:zo.nome)||"ração"}) de ${r.prioridade??0} para ${ke}`;return Ea&&Ea.progId===a.id?{progId:a.id,descricoes:[...Ea.descricoes,Ot]}:{progId:a.id,descricoes:[Ot]}}),await ft(a.id,`Troca de prioridade do pedido ${r.numero_grade||""} (${((we=r.racoes)==null?void 0:we.nome)||"ração"}) de ${r.prioridade??0} para ${ke}`)}catch(We){W({title:"Erro ao trocar ordem",description:We.message,variant:"destructive"})}})()},children:[e.jsx(Ba,{className:"h-8 text-xs w-20 mx-auto",children:e.jsx(Ka,{})}),e.jsxs(Qa,{children:[e.jsx(ca,{value:"0",children:"â"}),(()=>{const le=Math.max(t.length,...t.map(ke=>Number(ke.prioridade)||0));return Array.from({length:le+1},(ke,we)=>we+1)})().map(le=>e.jsxs(ca,{value:String(le),children:[le,"º"]},le))]})]}):r.prioridade||"â"}),e.jsx(c,{className:"text-center",children:r.numero_grade}),e.jsx(c,{className:"text-center",children:((K=r.racoes)==null?void 0:K.co
186digo)||"â"}),e.jsxs(c,{className:"text-center",children:[((Ae=r.racoes)==null?void 0:Ae.nome)||"â",((Ge=r.racoes)==null?void 0:Ge.is_medicada)&&e.jsx("span",{style:{color:"#dc2626",fontWeight:600},children:" (Medicada)"}),m.has(r.id)&&e.jsx(J,{variant:"outline",className:"ml-2 text-[10px] bg-red-50 text-red-700 border-red-300",children:"â Contaminação c/ anterior"}),(r.status_producao||"pendente")!=="pendente"&&e.jsx(J,{variant:"outline",className:"ml-2 text-[10px] "+(r.status_producao==="finalizado"?"bg-green-100 text-green-800 border-green-300":"bg-amber-50 text-amber-700 border-amber-200"),children:r.status_producao==="finalizado"?"Produzido":"Em Produção"})]}),e.jsx(c,{className:"text-center",children:((je=r.produtores)==null?void 0:je.nome)||"â"}),e.jsx(c,{className:"text-center",children:((qe=r.clientes)==null?void 0:qe.nome)||"â"}),e.jsx(c,{className:"text-center",children:Number(r.peso_solicitado).toLocaleString("pt-BR")}),e.jsx(c,{className:"text-center",children:((ta=r.silos_expedicao)==null?void 0:ta.nome)||((ra=(r.ordens_carregamento||[]).find(le=>le.silo_expedicao))==null?void 0:ra.silo_expedicao)||"â"}),b&&e.jsx(c,{className:"text-center",children:e.jsxs("div",{className:"flex gap-1 justify-center",children:[e.jsx(O,{variant:"ghost",size:"icon",title:(r.status_producao||"pendente")!=="pendente"?"Pedido em produção â bloqueado":"Editar pedido",disabled:(r.status_producao||"pendente")!=="pendente",onClick:()=>{ua(null),$o(r)},children:e.jsx(jt,{className:"h-4 w-4"})}),e.jsx(O,{variant:"ghost",size:"icon",title:r.cancelado?"Pedido já cancelado":(r.status_producao||"pendente")!=="pendente"?"Pedido em produção â não pode ser cancelado":"Cancelar pedido",disabled:r.cancelado||et.isPending||(r.status_producao||"pendente")!=="pendente",onClick:()=>{var le;confirm(`Cancelar o pedido ${r.numero_grade||""} (${((le=r.racoes)==null?void 0:le.nome)||"ração"})?`)&&(async()=>{var ke;try{await new Promise((We,Ea)=>{et.mutate(r.id,{onSuccess:()=>We(),onError:Ot=>Ea(Ot)})});const we=`Cancelamento do pedido ${r.numero_grade||""} (${((ke=r.racoes)==null?void 0:ke.nome)||"ração"})`;Ta(We=>We&&We.progId===a.id?{progId:a.id,descricoes:[...We.descricoes,we]}:{progId:a.id,descricoes:[we]}),await ft(a.id,we)}catch(we){W({title:"Erro ao cancelar",description:we.message,variant:"destructive"})}})()},children:e.jsx(Ds,{className:"h-4 w-4 text-destructive"})}),e.jsx(O,{variant:"ghost",size:"icon",title:(r.status_producao||"pendente")!=="pendente"?"Pedido em produção â não pode ser removido":"Remover da grade (volta para a aba Pedidos)",disabled:(r.status_producao||"pendente")!=="pendente"||So.isPending,onClick:()=>{var le;confirm(`Remover o pedido ${r.numero_grade||""} (${((le=r.racoes)==null?void 0:le.nome)||"ração"}) desta programação? O pedido voltará para a aba Pedidos.`)&&(async()=>{var ke;try{await So.mutateAsync({progId:a.id,pedidoId:r.id});const we=`Remoção do pedido ${r.numero_grade||""} (${((ke=r.racoes)==null?void 0:ke.nome)||"ração"}) da programação`;Ta(We=>We&&We.progId===a.id?{progId:a.id,descricoes:[...We.descricoes,we]}:{progId:a.id,descricoes:[we]}),await ft(a.id,we)}catch(we){W({title:"Erro ao remover",description:we.message,variant:"destructive"})}})()},children:e.jsx(ks,{className:"h-4 w-4 text-destructive"})})]})})]},r.id)}),e.jsxs(ge,{className:"font-bold border-t-2",children:[e.jsx(c,{colSpan:6,className:"text-right",children:"Total:"}),e.jsxs(c,{className:"text-right",children:[p.toLocaleString("pt-BR")," kg"]}),e.jsx(c,{}),b&&e.jsx(c,{})]})]})]})}),b&&e.jsxs("div",{className:"mt-4 rounded-md border border-amber-200 bg-amber-50/40 p-3",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("div",{className:"text-sm font-medium text-amber-900",children:a.status_liberacao==="em_alteracao_pcp"?"Edição liberada â Programação reaberta pelo PCP":"Edição liberada â Programação devolvida pela Qualidade"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(O,{size:"sm",onClick:()=>{const r="Inclusão de novo pedido na programação";Ta(K=>K&&K.progId===a.id?{progId:a.id,descricoes:[...K.descricoes,r]}:{progId:a.id,descricoes:[r]}),ft(a.id,r),$a(),Vs(a.id),te(new Date(a.data_producao+"T00:00:00")),ss(t.length+1),ua(null),Ze(!0)},children:[e.jsx(_t,{className:"h-4 w-4 mr-1"})," Novo Pedido"]}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:["Após ajustar, ",e.jsx("strong",{children:"assine novamente como PCP"}),"."]})]})]}),C.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Nenhum outro pedido desta data disponÃvel para incluir."}):e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"text-xs font-medium text-muted-foreground",children:["Pedidos da mesma data fora desta programação (",C.length,"):"]}),e.jsx("div",{className:"max-h-48 overflow-y-auto rounded border bg-card",children:e.jsx(ja,{children:e.jsx(va,{children:C.map(r=>{var K,Ae;return e.jsxs(ge,{children:[e.jsx(c,{className:"py-1 text-xs",children:r.numero_grade}),e.jsx(c,{className:"py-1 text-xs",children:((K=r.racoes)==null?void 0:K.nome)||"â"}),e.jsx(c,{className:"py-1 text-xs",children:za(r)&&e.jsx(J,{variant:"destructive",className:"text-[10px]",title:Ut(r),children:Ts(r)})}),e.jsx(c,{className:"py-1 text-xs",children:((Ae=r.clientes)==null?void 0:Ae.nome)||"â"}),e.jsxs(c,{className:"py-1 text-xs text-right",children:[Number(r.peso_solicitado).toLocaleStr
186ing("pt-BR")," kg"]}),e.jsx(c,{className:"py-1 w-12",children:e.jsx(O,{variant:"ghost",size:"icon",disabled:za(r),title:za(r)?`Bloqueado pela Qualidade â ${Ut(r)}`:"Adicionar à programação",onClick:()=>(async()=>{var Ge;try{await li.mutateAsync({progId:a.id,pedidoId:r.id,prioridade:r.prioridade||t.length+1});const je=`Inclusão do pedido ${r.numero_grade||""} (${((Ge=r.racoes)==null?void 0:Ge.nome)||"ração"}) na programação`;Ta(qe=>qe&&qe.progId===a.id?{progId:a.id,descricoes:[...qe.descricoes,je]}:{progId:a.id,descricoes:[je]}),await ft(a.id,je)}catch(je){W({title:"Erro ao incluir",description:je.message,variant:"destructive"})}})(),children:e.jsx(_t,{className:"h-4 w-4 text-primary"})})})]},r.id)})})})})]})]})]})};return e.jsxs("div",{className:"animate-fade-in",children:[e.jsxs("div",{className:"print:hidden",children:[H==="menu"&&e.jsxs("div",{className:"flex flex-col items-center text-center gap-2 mb-6",children:[e.jsx("div",{className:"flex h-12 w-12 items-center justify-center rounded-xl bg-primary/20 text-primary",children:e.jsx(As,{className:"h-6 w-6"})}),e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Pedidos"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Gerencie os pedidos de produção"})]}),e.jsx(st,{open:Yt,onOpenChange:a=>{Ze(a),a||$a()},children:e.jsxs(ot,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx(Nt,{children:e.jsxs(wt,{children:[be?"Editar":"Novo"," Pedido"]})}),e.jsxs("form",{onSubmit:a=>{a.preventDefault(),Ns.mutate()},className:"space-y-4",children:[(()=>{var t;const a=!!be&&dt!=="pendente"&&!Ga,s=aa&&!!de;return e.jsxs(e.Fragment,{children:[!be&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-md border border-border bg-muted/50",children:[e.jsx(rr,{checked:aa,onCheckedChange:o=>{Bs(o),o||os("")}}),e.jsx(Le,{children:"à incremento de pedido existente?"})]}),aa&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(Le,{children:"Nº do Pedido Original *"}),e.jsx(Ca,{value:mt,onChange:o=>{os(o.target.value)},placeholder:"Digite o número do pedido"}),mt&&!de&&e.jsx("p",{className:"text-sm text-destructive",children:"Pedido não encontrado"}),de&&e.jsxs("p",{className:"text-sm text-primary",children:["Pedido #",de.numero," encontrado â ",((t=de.clientes)==null?void 0:t.nome)||"Cliente"," â ",Number(de.peso_solicitado).toLocaleString("pt-BR")," kg"]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Le,{children:"Cliente *"}),e.jsxs(Oa,{value:s?de.cliente_id:q,onValueChange:o=>{S(o),oa(""),ba("")},disabled:a||s,children:[e.jsx(Ba,{children:e.jsx(Ka,{placeholder:"Selecione o cliente"})}),e.jsx(Qa,{children:Kr.map(o=>e.jsxs(ca,{value:o.id,children:[o.codigo?`${o.codigo} - `:"",o.nome]},o.id))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Le,{children:"Data de Produção *"}),s?e.jsx(Ca,{value:de.data_producao?I(new Date(de.data_producao+"T00:00:00"),"dd/MM/yyyy"):"",disabled:!0}):e.jsxs(na,{open:a?!1:Ce,onOpenChange:a?void 0:X,children:[e.jsx(da,{asChild:!0,children:e.jsxs(O,{variant:"outline",className:rt("w-full justify-start text-left font-normal",!h&&"text-muted-foreground"),disabled:a,children:[e.jsx(fa,{className:"mr-2 h-4 w-4"}),h?I(h,"dd/MM/yyyy"):"Selecione a data"]})}),e.jsx(la,{className:"w-auto p-0",align:"start",children:e.jsx(_a,{mode:"single",selected:h,onSelect:o=>{te(o),X(!1)},initialFocus:!0,className:"p-3 pointer-events-auto"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Le,{children:"Ração"}),(()=>{let o;s?o=Wa:Nr?o=Vr:o=Ur;const m=s?de.racao_id||"":Ve,l=o.find(p=>p.id===m);return e.jsxs(e.Fragment,{children:[Ii(po.data)&&e.jsx("p",{className:"text-xs text-muted-foreground mb-1",children:"Status Ultra não confirmado (catálogo pendente de atualização): só produtos já confirmados como baixados ficam ocultos."}),e.jsxs(na,{open:Gr,onOpenChange:ho,children:[e.jsx(da,{asChild:!0,children:e.jsxs(O,{type:"button",variant:"outline",role:"combobox",disabled:a||s,className:"w-full justify-between font-normal",children:[e.jsx("span",{className:"truncate",children:l?`${l.codigo?l.codigo+" - ":""}${l.nome}`:"Selecione a ração"}),e.jsx(rn,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(la,{className:"w-[--radix-popover-trigger-width] p-0",align:"start",children:e.jsxs(Oi,{filter:(p,D)=>D?p.toLowerCase().includes(D.toLowerCase())?1:0:1,children:[e.jsx(Bi,{placeholder:"Buscar por código ou nome..."}),e.jsxs(Ki,{children:[e.jsx(Qi,{children:"Nenhuma ração encontrada."}),e.jsx(Hi,{children:o.map(p=>{const D=`${p.codigo?p.codigo+" - ":""}${p.nome}`;return e.jsxs(Ui,{value:`${p.codigo||""} ${p.nome||""}`,onSelect:()=>{ba(p.id),ho(!1)},children:[e.jsx(Vi,{className:`mr-2 h-4 w-4 ${m===p.id?"opacity-100":"opacity-0"}`}),D]},p.id)})})]})]})})]})]})})(),(()=>{const o=s?(de==null?void 0:de.racao_id)||"":Ve,m=Wa.find(l=>l.id===o);return m!=null&&m.is_medicada?e.jsxs("div",{className:"mt-2 rounded-md border border-destructive/40 bg-destructive/5 p-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-destructive",children:[e.jsx(ga,{className:"h-4 w-4"})," Ração Medicada â Receituário obrigatório"]}),e.jsx($n,{value:ut,onChange:l=>{Mt(l),l.path&&Va(null)},scope:q||"geral",disabled:a||!!Ee}),!ut.path&&!Ee&&e.jsxs(O,{type:"button",variant:"outline",size:"sm",className:"w-full",onClick:()=>Ks(!0),children:[e.jsx(nn,{className:"h-3.5 w-3.5 mr-1.5"})," Solicitar Liberação da Qualidade"]}
186),Ee&&e.jsx(Fa,{children:e.jsxs(Ia,{className:"text-xs",children:[e.jsx("strong",{children:"Liberado sem receituário"})," por ",Ee.liberador_nome,Ee.liberador_codigo?` (${Ee.liberador_codigo})`:"",".",e.jsxs("div",{className:"mt-1",children:[e.jsx("em",{children:"Motivo:"})," ",Ee.motivo]}),!a&&e.jsx(O,{type:"button",variant:"ghost",size:"sm",className:"h-6 mt-1 text-xs",onClick:()=>Va(null),children:"Remover liberação"})]})})]}):null})()]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Le,{children:"Nº Pedido *"}),e.jsx(Ca,{value:Aa,onChange:o=>ya(o.target.value),required:!0,placeholder:"Número do pedido",disabled:a})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Le,{children:"Peso do Incremento (kg) *"}),e.jsx(Ca,{type:"number",step:"0.01",value:ea,onChange:o=>Na(o.target.value),required:!0,placeholder:"0.00",disabled:a}),aa&&de&&ea&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Peso original: ",Number(de.peso_solicitado).toLocaleString("pt-BR")," kg + Incremento: ",Number(ea).toLocaleString("pt-BR")," kg = Total: ",(Number(de.peso_solicitado)+Number(ea)).toLocaleString("pt-BR")," kg"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Le,{children:"Produtor *"}),e.jsxs(Oa,{value:s?de.produtor_id:wa,onValueChange:oa,disabled:a||s,children:[e.jsx(Ba,{children:e.jsx(Ka,{placeholder:"Selecione o produtor"})}),e.jsx(Qa,{children:(s?uo:Hr).map(o=>e.jsx(ca,{value:o.id,children:o.nome},o.id))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Le,{children:"Nº Grade *"}),e.jsx(Ca,{value:lt,onChange:o=>ct(o.target.value.replace(/[,\s]/g,"")),required:!0,placeholder:"Número da grade",disabled:a})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(rr,{checked:qa,onCheckedChange:Zt,disabled:a}),e.jsx(Le,{children:"Cancelado"}),a&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"Produção em andamento"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Le,{children:"Cód. Produção"}),e.jsx(Ca,{value:as,onChange:o=>ts(o.target.value),placeholder:"Cód. produção",disabled:a})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Le,{children:"Observações"}),e.jsx(Fs,{value:Ct,onChange:o=>es(o.target.value),placeholder:"Observações do pedido..."})]})]})})(),e.jsx(O,{type:"submit",className:"w-full",disabled:Ns.isPending,children:Ns.isPending?"Salvando...":"Salvar"})]})]})}),e.jsx(st,{open:Ir,onOpenChange:a=>{a||(zt(!1),Lt(null),Tt([]))},children:e.jsxs(ot,{className:"max-w-lg max-h-[80vh] overflow-y-auto",children:[e.jsxs(Nt,{children:[e.jsx(wt,{className:"text-destructive flex items-center gap-2",children:"â ï¸ Saldo Insuficiente de Matéria-Prima"}),e.jsx(Rs,{children:"As seguintes matérias-primas ficarão com saldo negativo após a reserva para este pedido:"})]}),e.jsx("div",{className:"rounded-md border overflow-x-auto",children:e.jsxs(ja,{children:[e.jsx(Ma,{children:e.jsxs(ge,{children:[e.jsx($,{children:"Matéria-Prima"}),e.jsx($,{className:"text-right",children:"Necessário"}),e.jsx($,{className:"text-right",children:"Saldo Atual"}),e.jsx($,{className:"text-right",children:"Novo Saldo"})]})}),e.jsx(va,{children:Or.map((a,s)=>e.jsxs(ge,{children:[e.jsxs(c,{className:"text-sm",children:[e.jsx("span",{className:"font-medium",children:a.mp}),e.jsxs("span",{className:"text-muted-foreground text-xs ml-1",children:["(",a.codigo,")"]})]}),e.jsxs(c,{className:"text-right text-sm",children:[a.necessario.toLocaleString("pt-BR",{minimumFractionDigits:3,maximumFractionDigits:3})," kg"]}),e.jsxs(c,{className:"text-right text-sm",children:[a.saldo.toLocaleString("pt-BR",{minimumFractionDigits:3,maximumFractionDigits:3})," kg"]}),e.jsxs(c,{className:"text-right text-sm font-semibold text-destructive",children:[a.novoSaldo.toLocaleString("pt-BR",{minimumFractionDigits:3,maximumFractionDigits:3})," kg"]})]},s))})]})}),e.jsxs(Is,{className:"gap-2 sm:gap-0",children:[e.jsx(O,{variant:"outline",onClick:()=>{zt(!1),Lt(null),Tt([])},children:"Cancelar"}),e.jsx(O,{variant:"destructive",onClick:gi,disabled:co,children:co?"Salvando...":"Prosseguir mesmo assim"})]})]})}),H==="menu"&&e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-
1865 max-w-5xl mx-auto print:hidden",children:[{key:"pedidos",label:"Pedido Ração",icon:e.jsx(Io,{className:"h-6 w-6"}),description:"Pedidos ativos de produção",count:Ra.length},{key:"pesadinhas",label:"Pedidos Pesadinha",icon:e.jsx(Oo,{className:"h-6 w-6"}),description:"Pedidos de pesadinhas (pesagem assistida)",count:Ja.length+xa.length},{key:"aguardando",label:"Aguardando Carreg.",icon:e.jsx(Bo,{className:"h-6 w-6"}),description:"Pedidos finalizados aguardando carregamento",count:No.length},{key:"entregue",label:"Entregue",icon:e.jsx(Ko,{className:"h-6 w-6"}),description:"Pedidos já entregues",count:Za.length},{key:"cancelados",label:"Cancelados",icon:e.jsx(Qo,{className:"h-6 w-6"}),description:"Pedidos cancelados",count:wo.length},{key:"todos",label:"Todos os Pedidos",icon:e.jsx(Bt,{className:"h-6 w-6"}),description:"Lista completa, inclusive cancelados",count:La.length},{key:"consumo",label:"Consumo",icon:e.jsx(Ho,{className:"h-6 w-6"}),description:"Consumo e necessidade de matérias-primas"}].map(a=>e.jsx(Ha,{className:"group cursor-pointer border-border bg-card shadow transition-all duration-200 hover:shadow-xl hover:border-primary/50 active:scale-[0.97] relative",onClick:()=>Y(a.key),children:e.jsxs(Ua,{className:"p-6 flex flex-col items-center gap-4 text-center",children:[e.jsx("div",{className:"flex h-14 w-14 items-center justify-center rounded-xl bg-primary/20 text-primary transition-colors group-hover:bg-primary/30",children:a.icon}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-base font-semibold text-foreground",children:a.label}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1 leading-relaxed",children:a.description}),a.count!==void 0&&e.jsx(J,{variant:"secondary",className:"mt-2",children:a.count})]})]})},a.key))}),H==="consumo"&&e.jsxs("div",{className:"print:hidden",children:[e.jsxs("div",{className:"flex flex-col items-center text-center gap-2 mb-6",children:[e.jsx("div",{className:"flex h-12 w-12 items-center justify-center rounded-xl bg-primary/20 text-primary",children:e.jsx(Ho,{className:"h-6 w-6"})}),e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Consumo"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Consumo e necessidade de matérias-primas"})]}),e.jsxs(O,{variant:"ghost",size:"sm",className:"mb-4",onClick:()=>Y("menu"),children:[e.jsx(Uo,{className:"h-4 w-4 mr-1"})," Voltar"]}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-5 max-w-3xl mx-auto",children:[{key:"materia-prima",label:"Matéria Prima",icon:e.jsx(As,{className:"h-6 w-6"}),description:"Fórmulas e consumo de matérias-primas por perÃodo"},{key:"mp-pendente",label:"MP Pendente",icon:e.jsx(lr,{className:"h-6 w-6"}),description:"Matérias-primas pendentes para ordens não finalizadas"},{key:"consumo-cliente",label:"Consumo por Cliente",icon:e.jsx(Vo,{className:"h-6 w-6"}),description:"Relatório de consumo de MP por pedido de cada cliente"},{key:"consumo-nexxus",label:"Consumo Nexxus",icon:e.jsx(Go,{className:"h-6 w-6"}),description:"Importar e visualizar consumo da produção Nexxus"}].map(a=>e.jsx(Ha,{className:"group cursor-pointer border-border bg-card shadow transition-all duration-200 hover:shadow-xl hover:border-primary/50 active:scale-[0.97]",onClick:()=>Y(a.key),children:e.jsxs(Ua,{className:"p-6 flex flex-col items-center gap-4 text-center",children:[e.jsx("div",{className:"flex h-14 w-14 items-center justify-center rounded-xl bg-primary/20 text-primary transition-colors group-hover:bg-primary/30",children:a.icon}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-base font-semibold text-foreground",children:a.label}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1 leading-relaxed",children:a.description})]})]})},a.key))})]}),H!=="menu"&&H!=="consumo"&&(()=>{const s={pedidos:{icon:Io,label:"Pedido Ração"},pesadinhas:{icon:Oo,label:"Pedidos Pesadinha"},aguardando:{icon:Bo,label:"Aguardando Carregamento"},entregue:{icon:Ko,label:"Entregue"},cancelados:{icon:Qo,label:"Cancelados"},todos:{icon:Bt,label:"Todos os Pedidos"},programacoes:{icon:Bt,label:"Programações"},"materia-prima":{icon:As,label:"Matéria Prima"},"mp-pendente":{icon:lr,label:"MP Pendente"},"consumo-cliente":{icon:Vo,label:"Consumo por Cliente"},"consumo-nexxus":{icon:Go,label:"Consumo Nexxus"}}[H];if(!s)return null;const t=s.icon;return e.jsxs("div",{className:"print:hidden",children:[e.jsxs("div",{className:"flex flex-col items-center text-center gap-2 mb-3",children:[e.jsx("div",{className:"flex h-10 w-10 items-center justify-center rounded-xl bg-primary/20 text-primary",children:e.jsx(t,{className:"h-5 w-5"})}),e.jsx("h2",{className:"text-xl font-bold text-foreground tracking-tight",children:k?"Visualizar Programação":s.label})]}),e.jsxs(O,{variant:"ghost",size:"sm",className:"-ml-2 mb-4",onClick:()=>
186{if(k){j("/programacao");return}if(i.get("from")==="balanca"){j("/balanca");return}const m=i.get("from")==="producao",l=H==="programacoes"&&i.get("tab")==="producao";if(m||l){j("/producao-hub");return}if(u.pathname==="/programacao"){j("/pcp");return}Y(H==="materia-prima"||H==="mp-pendente"||H==="consumo-cliente"||H==="consumo-nexxus"?"consumo":"menu")},children:[e.jsx(Uo,{className:"h-4 w-4 mr-1"})," Voltar"]}),H==="pedidos"&&e.jsxs("div",{children:[e.jsx(at,{value:Cs,onValueChange:o=>ji(o),className:"w-full mb-4",children:e.jsxs(tt,{children:[e.jsxs(Je,{value:"normais",children:["Pedidos Normais (",Ra.length,")"]}),e.jsxs(Je,{value:"pesagem",children:["Pesagem Assistida (",Ja.length+xa.length,")"]})]})}),Cs==="normais"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"mb-4 flex flex-col gap-2 sm:flex-row sm:flex-wrap sm:items-center sm:justify-end",children:[e.jsxs(na,{open:De,onOpenChange:oe,children:[e.jsx(da,{asChild:!0,children:e.jsxs(O,{variant:"outline",size:"sm",className:rt("w-full justify-start text-left font-normal text-xs sm:w-[150px]"),children:[e.jsx(fa,{className:"mr-1 h-3.5 w-3.5"}),I(E,"dd/MM/yyyy")]})}),e.jsx(la,{className:"w-auto p-0",align:"end",children:e.jsx(_a,{mode:"single",selected:E,onSelect:o=>{o&&xe(o),oe(!1)},initialFocus:!0,className:"p-3 pointer-events-auto"})})]}),e.jsxs(O,{variant:"outline",size:"sm",onClick:()=>{const o=I(E,"yyyy-MM-dd");A(o);const m=fe.filter(l=>l.data_producao===o&&l.assinatura_pcp_url).sort((l,p)=>new Date(p.created_at).getTime()-new Date(l.created_at).getTime())[0];if(m){kt(m.assinatura_pcp_url),$t({nome:m.assinatura_pcp_nome||"â",codigo:m.assinatura_pcp_codigo,em:m.assinatura_pcp_em});const l=(m.programacao_diaria_itens||[]).map(p=>p.pedido_id).filter(Boolean);us(l),ps(m.grade_numero||null)}else kt(null),$t(null),us(null),ps(null);setTimeout(()=>window.print(),100)},children:[e.jsx(nt,{className:"h-4 w-4 mr-1"})," Imprimir"]}),(()=>{const o=I(E,"yyyy-MM-dd"),m=fe.filter(r=>r.data_producao===o).length,l=m+1,p=m===0?"Gerar Programação":`Gerar ${l}ª Grade`,D=js.get(o),b=vs.get(o),T=!!D&&D.length>0,N=!!b&&b.length>0,U=T||N,C=N?`Existem ${b.length} pedido(s) sem prioridade nesta data. Defina a prioridade de todos antes de gerar a grade.`:T?"Existem conflitos de contaminação na ordem de prioridade desta data. Reordene antes de gerar a grade.":void 0;return e.jsxs(O,{variant:"secondary",size:"sm",onClick:ni,disabled:Qs||U,title:C,children:[e.jsx(_r,{className:"h-4 w-4 mr-1"})," ",Qs?"Gerando...":p]})})(),e.jsxs(O,{variant:"outline",size:"sm",onClick:()=>Y("programacoes"),children:[e.jsx(Bt,{className:"h-4 w-4 mr-1"})," Programações"]}),e.jsxs(O,{onClick:()=>{$a(),Ze(!0)},children:[e.jsx(_t,{className:"h-4 w-4 mr-2"})," Novo Pedido"]})]}),e.jsxs("div",{className:"bg-card rounded-lg border",children:[e.jsxs("div",{className:"flex flex-col gap-2 border-b px-4 py-2 sm:flex-row sm:flex-wrap sm:items-center",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"PerÃodo:"}),e.jsxs(na,{open:F,onOpenChange:ae,children:[e.jsx(da,{asChild:!0,children:e.jsxs(O,{variant:"outline",size:"sm",className:"w-full justify-start text-left font-normal text-xs sm:w-[130px]",children:[e.jsx(fa,{className:"mr-1 h-3.5 w-3.5"}),I(g,"dd/MM/yyyy")]})}),e.jsx(la,{className:"w-auto p-0",align:"start",children:e.jsx(_a,{mode:"single",selected:g,onSelect:o=>{o&&w(o),ae(!1)},initialFocus:!0,className:"p-3 pointer-events-auto"})})]}),e.jsx("span",{className:"hidden text-sm text-muted-foreground sm:inline",children:"até"}),e.jsxs(na,{open:ye,onOpenChange:me,children:[e.jsx(da,{asChild:!0,children:e.jsxs(O,{variant:"outline",size:"sm",className:"w-full justify-start text-left font-normal text-xs sm:w-[130px]",children:[e.jsx(fa,{className:"mr-1 h-3.5 w-3.5"}),I(v,"dd/MM/yyyy")]})}),e.jsx(la,{className:"w-auto p-0",align:"start",children:e.jsx(_a,{mode:"single",selected:v,onSelect:o=>{o&&V(o),me(!1)},initialFocus:!0,className:"p-3 pointer-events-auto"})})]})]}),js.size>0&&e.jsxs(Fa,{variant:"destructive",className:"mx-4 my-3",children:[e.jsx(ga,{className:"h-4 w-4"}),e.jsxs(Ia,{children:[e.jsx("div",{className:"font-semibold mb-1",children:"Conflitos de contaminação detectados na ordem de prioridade"}),e.jsx("ul",{className:"text-xs space-y-1 list-disc pl-4",children:Array.from(js.entries()).map(([o,m])=>e.jsxs("li",{children:[e.jsxs("span",{className:"font-medium",children:[I(new Date(o+"T00:00:00"),"dd/MM/yyyy"),":"]})," ",m.map((l,p)=>e.jsxs("span",{children:[p>0?"; ":"",l.prevNome," â ",l.nextNome]},p))]},o))}),e.jsx("div",{className:"text-xs mt-2 opacity-90",children:"Reordene as prioridades antes de gerar a grade."})]})]}),vs.size>0&&e.jsxs(Fa,{variant:"destructive",className:"mx-4 my-3",children:[e.jsx(ga,{className:"h-4 w-4"}),e.jsxs(Ia,{children:[e.jsx("div",{className:"font-semibold mb-1",children:"Pedidos sem prioridade definida"}),e.jsx("ul",{className:"text-xs space-y-1 list-disc pl-4",children:Array.from(vs.entries()).map(([o,m])=>e.jsxs("li",{children:[e.jsxs("span",{className:"font-medium",children:[I(new Date(o+"T00:00:00"),"dd/MM/yyyy"),":"]})," ",m.map((l,p)=>e.jsxs("span",{children:[p>0?"; ":"",l.nome,l.cliente?` (${l.cliente})`:""]},l.id))]},o))}),e.jsx("div",{className:"text-xs mt-2 opacity-90",children:"Defina a prioridade de todos os pedidos da data antes de gerar a grade."})]})]}),ha(Ra)]})]}
186),Cs==="pesagem"&&e.jsxs("div",{children:[e.jsx("div",{className:"flex items-center justify-end gap-2 mb-4",children:e.jsxs(O,{onClick:()=>{$a(),rs(!0),Ze(!0)},children:[e.jsx(_t,{className:"h-4 w-4 mr-2"})," Novo Pedido"]})}),e.jsxs(at,{defaultValue:"ativas",className:"w-full",children:[e.jsxs(tt,{children:[e.jsxs(Je,{value:"ativas",children:["Ativas (",Ja.length,")"]}),e.jsxs(Je,{value:"finalizadas",children:["Finalizadas (",xa.length,")"]})]}),e.jsx(ia,{value:"ativas",children:e.jsx("div",{className:"bg-card rounded-lg border",children:ha(Ja,{hidePrioridade:!0,hideSilo:!0})})}),e.jsx(ia,{value:"finalizadas",children:e.jsxs("div",{className:"bg-card rounded-lg border",children:[e.jsx(Ht,{page:Ya,pageSize:Xa,total:xa.length,onPageChange:ht}),ha(yo,{hidePrioridade:!0,hideSilo:!0}),e.jsx(Ht,{page:Ya,pageSize:Xa,total:xa.length,onPageChange:ht})]})})]})]})]}),H==="pesadinhas"&&e.jsxs("div",{children:[e.jsx("div",{className:"flex items-center justify-end gap-2 mb-4",children:e.jsxs(O,{onClick:()=>{$a(),rs(!0),Ze(!0)},children:[e.jsx(_t,{className:"h-4 w-4 mr-2"})," Novo Pedido"]})}),e.jsxs(at,{value:ko,onValueChange:o=>_i(o),className:"w-full",children:[e.jsxs(tt,{children:[e.jsx(Je,{value:"lista",children:"Lista"}),e.jsx(Je,{value:"analise",children:"Análise de MP"})]}),e.jsx(ia,{value:"lista",children:e.jsxs(at,{defaultValue:"ativas",className:"w-full",children:[e.jsxs(tt,{children:[e.jsxs(Je,{value:"ativas",children:["Ativas (",Ja.length,")"]}),e.jsxs(Je,{value:"finalizadas",children:["Finalizadas (",xa.length,")"]})]}),e.jsx(ia,{value:"ativas",children:e.jsx("div",{className:"bg-card rounded-lg border",children:ha(Ja,{hidePrioridade:!0,hideSilo:!0})})}),e.jsx(ia,{value:"finalizadas",children:e.jsxs("div",{className:"bg-card rounded-lg border",children:[e.jsx(Ht,{page:Ya,pageSize:Xa,total:xa.length,onPageChange:ht}),ha(yo,{hidePrioridade:!0,hideSilo:!0}),e.jsx(Ht,{page:Ya,pageSize:Xa,total:xa.length,onPageChange:ht})]})})]})}),e.jsx(ia,{value:"analise",children:e.jsx(Tn,{enabled:H==="pesadinhas"&&ko==="analise"})})]})]}),H==="aguardando"&&e.jsx("div",{className:"bg-card rounded-lg border",children:ha(No)}),H==="entregue"&&(()=>{const o=new Map;Za.forEach(p=>{var T;const D=((T=p.clientes)==null?void 0:T.nome)||"Sem cliente",b=o.get(D);b?(b.count+=1,b.pesoTotal+=p.peso_solicitado||0):o.set(D,{nome:D,count:1,pesoTotal:p.peso_solicitado||0})});const m=Array.from(o.values()).sort((p,D)=>D.count-p.count),l=["hsl(var(--primary))","hsl(var(--accent))","hsl(142, 76%, 36%)","hsl(38, 92%, 50%)","hsl(280, 65%, 60%)","hsl(200, 80%, 50%)","hsl(350, 80%, 55%)","hsl(170, 70%, 40%)"];return e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"bg-card rounded-lg border",children:e.jsxs("div",{className:"flex items-center gap-2 px-4 py-2 border-b",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"PerÃodo:"}),e.jsxs(na,{open:ze,onOpenChange:_e,children:[e.jsx(da,{asChild:!0,children:e.jsxs(O,{variant:"outline",size:"sm",className:"w-[130px] justify-start text-left font-normal text-xs",children:[e.jsx(fa,{className:"mr-1 h-3.5 w-3.5"}),I(sa,"dd/MM/yyyy")]})}),e.jsx(la,{className:"w-auto p-0",align:"start",children:e.jsx(_a,{mode:"single",selected:sa,onSelect:p=>{p&&B(p),_e(!1)},initialFocus:!0,className:"p-3 pointer-events-auto"})})]}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"até"}),e.jsxs(na,{open:Ne,onOpenChange:ce,children:[e.jsx(da,{asChild:!0,children:e.jsxs(O,{variant:"outline",size:"sm",className:"w-[130px] justify-start text-left font-normal text-xs",children:[e.jsx(fa,{className:"mr-1 h-3.5 w-3.5"}),I(G,"dd/MM/yyyy")]})}),e.jsx(la,{className:"w-auto p-0",align:"start",children:e.jsx(_a,{mode:"single",selected:G,onSelect:p=>{p&&re(p),ce(!1)},initialFocus:!0,className:"p-3 pointer-events-auto"})})]}),e.jsxs("span",{className:"ml-auto text-sm font-medium text-muted-foreground",children:[Za.length," pedido",Za.length!==1?"s":""," entregue",Za.length!==1?"s":""]})]})}),m.length>0&&e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-4",children:[e.jsx(Ha,{children:e.jsxs(Ua,{className:"p-4",children:[e.jsx("h3",{className:"text-sm font-semibold text-foreground mb-3",children:"Pedidos por Cliente"}),e.jsx("div",{className:"space-y-2 max-h-[280px] overflow-y-auto",children:m.map((p,D)=>e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx("div",{className:"w-3 h-3 rounded-full shrink-0",style:{backgroundColor:l[D%l.length]}}),e.jsx("span",{className:"truncate",children:p.nome})]}),e.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[e.jsxs(J,{variant:"secondary",className:"text-xs",children:[p.count," pedido",p.count>1?"s":""]}),e.jsxs("span",{className:"text-xs text-muted-foreground w-[80px] text-right",children:[(p.pesoTotal/1e3).toFixed(1)," ton"]})]})]},p.nome))})]})}),e.jsx(Ha,{children:e.jsxs(Ua,{className:"p-4",children:[e.jsx("h3",{className:"text-sm font-semibold text-foreground mb-3",children:"Desempenho por Cliente"}),e.jsx(dn,{width:"100%",height:260,children:e.jsxs(ln,{data:m,layout:"vertical",margin:{left:0,right:16,top:0,bottom:0},children:[e.jsx(cn,{type:"number",tick:{fontSize:11},allowDecimals:!1}),e.jsx(mn,{dataKey:"nome",type:"category",width:120,tick:{fontSize:11}
186,tickFormatter:p=>p.length>16?p.slice(0,14)+"â¦":p}),e.jsx(un,{formatter:(p,D)=>[p,D==="count"?"Pedidos":D],labelFormatter:p=>p}),e.jsx(pn,{dataKey:"count",name:"Pedidos",radius:[0,4,4,0],children:m.map((p,D)=>e.jsx(xn,{fill:l[D%l.length]},D))})]})})]})})]}),e.jsx("div",{className:"bg-card rounded-lg border",children:ha(Za)})]})})(),H==="cancelados"&&e.jsx("div",{className:"bg-card rounded-lg border",children:ha(wo)}),H==="todos"&&(()=>{const o=I(ue,"yyyy-MM-dd"),m=I(He,"yyyy-MM-dd"),l=La.filter(b=>b.data_producao?b.data_producao>=o&&b.data_producao<=m:!1),p=l.filter(b=>!Da(b)),D=l.filter(b=>Da(b));return e.jsxs("div",{className:"bg-card rounded-lg border",children:[e.jsxs("div",{className:"flex items-center gap-2 px-4 py-2 border-b flex-wrap",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"PerÃodo:"}),e.jsxs(na,{open:ma,onOpenChange:Ye,children:[e.jsx(da,{asChild:!0,children:e.jsxs(O,{variant:"outline",size:"sm",className:"w-[130px] justify-start text-left font-normal text-xs",children:[e.jsx(fa,{className:"mr-1 h-3.5 w-3.5"}),I(ue,"dd/MM/yyyy")]})}),e.jsx(la,{className:"w-auto p-0",align:"start",children:e.jsx(_a,{mode:"single",selected:ue,onSelect:b=>{b&&he(b),Ye(!1)},initialFocus:!0,className:"p-3 pointer-events-auto"})})]}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"até"}),e.jsxs(na,{open:Re,onOpenChange:Ue,children:[e.jsx(da,{asChild:!0,children:e.jsxs(O,{variant:"outline",size:"sm",className:"w-[130px] justify-start text-left font-normal text-xs",children:[e.jsx(fa,{className:"mr-1 h-3.5 w-3.5"}),I(He,"dd/MM/yyyy")]})}),e.jsx(la,{className:"w-auto p-0",align:"start",children:e.jsx(_a,{mode:"single",selected:He,onSelect:b=>{b&&Xe(b),Ue(!1)},initialFocus:!0,className:"p-3 pointer-events-auto"})})]}),e.jsxs("span",{className:"text-xs text-muted-foreground ml-auto",children:[l.length," pedido",l.length!==1?"s":""]})]}),e.jsxs(at,{defaultValue:"racoes",className:"w-full",children:[e.jsx("div",{className:"px-4 pt-3",children:e.jsxs(tt,{children:[e.jsxs(Je,{value:"racoes",children:["Rações (",p.length,")"]}),e.jsxs(Je,{value:"pesadinhas",children:["Pesadinhas (",D.length,")"]})]})}),e.jsx(ia,{value:"racoes",className:"mt-2",children:ha(p)}),e.jsx(ia,{value:"pesadinhas",className:"mt-2",children:ha(D,{hidePrioridade:!0,hideSilo:!0})})]})]})})(),H==="programacoes"&&e.jsxs("div",{className:"bg-card rounded-lg border p-4",children:[k?null:Rt?e.jsx("p",{className:"text-center text-muted-foreground",children:"Carregando..."}):fe.length===0?e.jsx("p",{className:"text-center text-muted-foreground",children:"Nenhuma programação gerada ainda"}):(()=>{const o=T=>{const N=(T.programacao_diaria_itens||[]).map(r=>r.pedido_id);if(N.length===0)return!1;const U=Me.filter(r=>N.includes(r.id));if(U.length===0)return!1;const C=U.filter(r=>!r.cancelado);return C.length===0?!1:C.every(r=>r.status_producao==="finalizado"||!!r.silo_expedicao_id)},m=fe.filter(T=>(T.status_liberacao||"rascunho")!=="liberado_producao"),l=fe.filter(T=>T.status_liberacao==="liberado_producao"&&!o(T)),p=fe.filter(T=>T.status_liberacao==="liberado_producao"&&o(T)),D=T=>{if(T.status_liberacao!=="liberado_producao")return!1;const N=(T.programacao_diaria_itens||[]).map(C=>C.pedido_id);return N.length===0?!1:Me.filter(C=>N.includes(C.id)).some(C=>(C.status_producao||"pendente")==="pendente"&&!C.cancelado)},b=T=>T.length===0?e.jsx("p",{className:"text-center text-muted-foreground py-8",children:"Nenhuma programação nesta categoria"}):e.jsx(qs,{ariaLabel:"Programações de produção",children:e.jsxs(ja,{className:"min-w-[980px]",children:[e.jsx(Ma,{children:e.jsxs(ge,{className:"table-header",children:[e.jsx($,{className:"text-center",children:"Nº"}),e.jsx($,{className:"text-center",children:"Data Produção"}),e.jsx($,{className:"text-center",children:"Criado em"}),e.jsx($,{className:"text-center",children:"Nº Alteração"}),e.jsx($,{className:"text-center",children:"Qtd. Pedidos"}),e.jsx($,{className:"text-center",children:"Finalizada"}),e.jsx($,{className:"text-center",children:"Assinatura PCP"}),e.jsx($,{className:"text-center",children:"Status"}),e.jsx($,{className:"w-28 text-center",children:"Ações"})]})}),e.jsx(va,{children:T.map(N=>{var je;const U=(N.devolucao_count||0)+gt.filter(qe=>
186qe.programacao_id===N.id).length,C=N.status_liberacao||(N.assinatura_pcp_url?"aguardando_qualidade":"rascunho"),r={rascunho:{label:"Rascunho",cls:"bg-muted text-muted-foreground border-border"},aguardando_qualidade:{label:"Aguardando Qualidade",cls:"bg-blue-50 text-blue-700 border-blue-200"},devolvida:{label:"Devolvida",cls:"bg-red-50 text-red-700 border-red-200"},liberado_producao:{label:"Liberado p/ Produção",cls:"bg-emerald-50 text-emerald-700 border-emerald-200"},em_alteracao_pcp:{label:"Em Alteração (PCP)",cls:"bg-purple-50 text-purple-700 border-purple-200"}},K=r[C]||r.rascunho,Ae=(N.programacao_diaria_itens||[]).map(qe=>qe.pedido_id),Ge=nr(Me.filter(qe=>Ae.includes(qe.id)));return e.jsxs(ge,{children:[e.jsxs(c,{className:"font-medium text-center",children:[N.numero,N.grade_numero&&N.grade_numero>1?e.jsxs(J,{variant:"outline",className:"ml-2 bg-indigo-50 text-indigo-700 border-indigo-200",children:[N.grade_numero,"ª Grade"]}):N.grade_numero===1?e.jsx(J,{variant:"outline",className:"ml-2 bg-slate-50 text-slate-700 border-slate-200",children:"1ª Grade"}):null]}),e.jsx(c,{className:"text-center",children:I(new Date(N.data_producao+"T00:00:00"),"dd/MM/yyyy")}),e.jsx(c,{className:"text-center",children:I(new Date(N.created_at),"dd/MM/yyyy HH:mm")}),e.jsx(c,{className:"text-center",children:U}),e.jsx(c,{className:"text-center",children:((je=N.programacao_diaria_itens)==null?void 0:je.length)||0}),e.jsx(c,{className:"text-center",children:e.jsx(J,{variant:"outline",className:o(N)?"bg-green-50 text-green-700 border-green-200":"bg-slate-50 text-slate-700 border-slate-200",children:o(N)?"S":"N"})}),e.jsx(c,{className:"text-center",children:N.assinatura_pcp_url?e.jsxs(J,{variant:"outline",className:"bg-green-50 text-green-700 border-green-200",children:[e.jsx(Qt,{className:"h-3 w-3 mr-1"}),N.assinatura_pcp_nome||"Assinada"]}):e.jsx(J,{variant:"outline",className:"bg-amber-50 text-amber-700 border-amber-200",children:"Pendente"})}),e.jsxs(c,{className:"text-center",children:[e.jsx(J,{variant:"outline",className:K.cls,title:C==="devolvida"&&N.devolucao_motivo?`Motivo: ${N.devolucao_motivo}`:void 0,children:K.label}),Ge&&e.jsxs(J,{variant:"outline",className:"ml-1 bg-red-50 text-red-700 border-red-200",title:Ge,children:[e.jsx(ga,{className:"h-3 w-3 mr-1"})," Bloqueado pela Qualidade"]})]}),e.jsx(c,{className:"text-center",children:e.jsxs("div",{className:"flex gap-1 justify-center",children:[e.jsx(O,{variant:"ghost",size:"icon",title:"Visualizar",onClick:()=>j(`/programacao/${N.id}`),children:e.jsx(Ji,{className:"h-4 w-4"})}),e.jsx(O,{variant:"ghost",size:"icon",title:"Atualizar silos da programação",disabled:fo.has(N.id),onClick:()=>Jr(N),children:e.jsx(Xi,{className:`h-4 w-4 text-blue-600 ${fo.has(N.id)?"animate-spin":""}`})}),!N.assinatura_pcp_url&&e.jsx(O,{variant:"ghost",size:"icon",title:"Assinar como PCP",onClick:()=>Co(N.id),children:e.jsx(or,{className:"h-4 w-4 text-primary"})}),C==="aguardando_qualidade"&&Et&&e.jsxs(e.Fragment,{children:[e.jsx(O,{variant:"ghost",size:"icon",title:Ge||"Liberar (Assinar Qualidade)",disabled:!!Ge,onClick:()=>bs(N.id),children:e.jsx($s,{className:"h-4 w-4 text-emerald-600"})}),e.jsx(O,{variant:"ghost",size:"icon",title:"Devolver para PCP",onClick:()=>ys(N.id),children:e.jsx(yt,{className:"h-4 w-4 text-destructive"})})]}),D(N)&&e.jsx(O,{variant:"ghost",size:"icon",title:"Solicitar alteração (reabrir programação)",onClick:()=>Mo(N.id),children:e.jsx(jt,{className:"h-4 w-4 text-purple-600"})}),e.jsx(O,{variant:"ghost",size:"icon",title:"Reimprimir",onClick:()=>{xe(new Date(N.data_producao+"T00:00:00")),A(N.data_producao||null);const qe=(N.programacao_diaria_itens||[]).map(ta=>ta.pedido_id).filter(Boolean);us(qe),ps(N.grade_numero||null),N.assinatura_pcp_url?(kt(N.assinatura_pcp_url),$t({nome:N.assinatura_pcp_nome||"â",codigo:N.assinatura_pcp_codigo,em:N.assinatura_pcp_em})):(kt(null),$t(null)),N.assinatura_qualidade_url?(Ys(N.assinatura_qualidade_url),Zs({nome:N.assinatura_qualidade_nome||"â",codigo:N.assinatura_qualidade_codigo,em:N.assinatura_qualidade_em})):(Ys(null),Zs(null)),setTimeout(()=>window.print(),300)},children:e.jsx(nt,{className:"h-4 w-4"})}),Ga&&(()=>{var ra;const qe=(N.programacao_diaria_itens||[]).map(le=>le.pedido_id),ta=Me.some(le=>
186qe.includes(le.id)&&["em_andamento","finalizado"].includes(le.status_producao||"pendente"));return e.jsxs(Wo,{children:[e.jsx(Yi,{asChild:!0,children:e.jsx(O,{variant:"ghost",size:"icon",title:ta?"Não é possÃvel excluir: há pedidos em produção/finalizados":"Excluir programação (Master)",disabled:ta,children:e.jsx(ks,{className:"h-4 w-4 text-destructive"})})}),e.jsxs(Jo,{children:[e.jsxs(Xo,{children:[e.jsxs(Yo,{children:["Excluir Programação Nº ",N.numero,"?"]}),e.jsxs(Zo,{children:["Esta ação remove a programação e desvincula os ",((ra=N.programacao_diaria_itens)==null?void 0:ra.length)||0," pedido(s) (os pedidos voltam a ficar disponÃveis para nova programação). Não pode ser desfeita."]})]}),e.jsxs(er,{children:[e.jsx(ar,{children:"Cancelar"}),e.jsx(tr,{className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",onClick:()=>di.mutate(N.id),children:"Excluir"})]})]})]})})()]})})]},N.id)})})]})});return e.jsxs(at,{defaultValue:i.get("tab")||"andamento",className:"space-y-4",children:[e.jsxs(tt,{className:"max-w-full",children:[e.jsxs(Je,{value:"andamento",children:["Em Andamento (",m.length,")"]}),e.jsxs(Je,{value:"producao",children:["Para Produção (",l.length,")"]}),e.jsxs(Je,{value:"produzidas",children:["Produzidas (",p.length,")"]})]}),e.jsx(ia,{value:"andamento",children:b(m)}),e.jsx(ia,{value:"producao",children:b(l)}),e.jsx(ia,{value:"produzidas",children:b(p)})]})})(),k?e.jsx("div",{className:"mt-2",children:Rt?e.jsx("p",{className:"text-center text-muted-foreground",children:"Carregando..."}):fe.find(o=>o.id===At)?Do():e.jsx("p",{className:"text-center text-muted-foreground",children:"Programação não encontrada."})}):e.jsx(st,{open:!!At,onOpenChange:o=>{if(!o){if(ka&&ka.progId===At&&ka.descricoes.length>0){xs(!0);return}ua(null)}},children:e.jsx(ot,{className:"max-h-[90dvh] max-w-[calc(100vw-1rem)] overflow-y-auto sm:max-w-4xl",children:Do()})})]}),H==="materia-prima"&&e.jsx("div",{className:"bg-card rounded-lg border p-4",children:e.jsx(an,{})}),H==="mp-pendente"&&e.jsx("div",{className:"bg-card rounded-lg border p-4",children:e.jsx(tn,{})}),H==="consumo-cliente"&&e.jsx("div",{className:"bg-card rounded-lg border p-4",children:e.jsx(En,{})}),H==="consumo-nexxus"&&e.jsx("div",{className:"bg-card rounded-lg border p-4",children:e.jsx(zn,{})})]})})()]}),e.jsx(bn,{pedidos:Me,dataProducao:E,dataProducaoStr:Z,logoUrl:Br,operadorNome:(_==null?void 0:_.full_name)||null,numeroAlteracao:(()=>{const a=I(E,"yyyy-MM-dd"),s=fe.filter(l=>l.data_producao!==a?!1:Pa?(l.programacao_diaria_itens||[]).some(p=>Pa.includes(p.pedido_id)):!0),t=new Set(s.map(l=>l.id)),o=s.reduce((l,p)=>l+(p.devolucao_count||0),0),m=gt.filter(l=>t.has(l.programacao_id)).length;return o+m})(),justificativasAlteracao:(()=>{const a=I(E,"yyyy-MM-dd"),s=Pa?new Set(fe.filter(t=>t.data_producao===a&&(t.programacao_diaria_itens||[]).some(o=>Pa.includes(o.pedido_id))).map(t=>t.id)):new Set(fe.filter(t=>t.data_producao===a).map(t=>t.id));return gt.filter(t=>s.has(t.programacao_id)).map(t=>({justificativa:t.justificativa,user_nome:t.user_nome,user_codigo:t.user_codigo,created_at:t.created_at,user_id:t.user_id}))})(),rqData:xt?{codigo:xt.codigo,criado_em:xt.criado_em,revisado_em:xt.revisado_em,numero_revisao:xt.numero_revisao}:void 0,assinaturaPcpUrl:Ar,assinaturaPcpInfo:qr,assinaturaQualidadeUrl:kr,assinaturaQualidadeInfo:$r,pedidoIdsFilter:Pa,gradeNumero:Dr,paradasInicio:(()=>{if(!Pa)return null;const a=I(E,"yyyy-MM-dd"),s=fe.find(t=>t.data_producao===a&&(t.programacao_diaria_itens||[]).some(o=>Pa.includes(o.pedido_id)));return(s==null?void 0:s.created_at)||null})(),paradasFim:(()=>{if(!Pa)return null;const a=I(E,"yyyy-MM-dd"),s=fe.find(o=>o.data_producao===a&&(o.programacao_diaria_itens||[]).some(m=>Pa.includes(m.pedido_id)));if(!s)return null;const t=fe.filter(o=>o.data_producao===a&&new Date(o.created_at).getTime()>new Date(s.created_at).getTime()).sort((o,m)=>new Date(o.created_at).getTime()-new Date(m.created_at).getTime())[0];return(t==null?void 0:t.created_at)||`${a}T23:59:59`})()}),e.jsx(Kt,{open:Sr,onOpenChange:Gs,documentoLabel:(()=>{const a=fe.find(s=>
186s.id===is);return a?`Programação Nº ${a.numero} ⢠${I(new Date(a.data_producao+"T00:00:00"),"dd/MM/yyyy")}`:"Programação de Produção"})(),papelLabel:"PCP",assinanteNome:(_==null?void 0:_.full_name)||"",assinanteCodigo:(_==null?void 0:_.codigo)||null,onConfirmed:ci}),e.jsx(Kt,{open:Cr,onOpenChange:Js,documentoLabel:(()=>{const a=fe.find(s=>s.id===ds);return a?`Programação Nº ${a.numero} ⢠${I(new Date(a.data_producao+"T00:00:00"),"dd/MM/yyyy")}`:"Programação de Produção"})(),papelLabel:"Qualidade",assinanteNome:(_==null?void 0:_.full_name)||"",assinanteCodigo:(_==null?void 0:_.codigo)||null,onConfirmed:mi}),e.jsx(Vt,{open:Er,onOpenChange:a=>{eo(a),a||(ro(null),so(null),ao(""))},acaoLabel:zr,onConfirm:oi}),e.jsx(Vt,{open:Tr,onOpenChange:a=>{xs(a),a||(Ta(null),ua(null))},acaoLabel:ka==null?void 0:ka.descricoes.join(" ⢠"),onConfirm:async a=>{if(ka)try{const{error:s}=await f.from("programacao_alteracoes").insert({programacao_id:ka.progId,justificativa:`Resumo do ciclo: ${a}`,user_id:(pe==null?void 0:pe.id)??null,user_nome:(_==null?void 0:_.full_name)??null,user_codigo:(_==null?void 0:_.codigo)??null});if(s)throw s;se.invalidateQueries({queryKey:["programacao_alteracoes"]}),Ta(null),xs(!1),ua(null)}catch(s){W({title:"Erro ao registrar alteração",description:s.message,variant:"destructive"})}}}),e.jsx(Dn,{open:wr,onOpenChange:Ks,racaoNome:(Eo=Wa.find(a=>a.id===Ve))==null?void 0:Eo.nome,onConfirmed:a=>{Va(a),Mt({path:null,nome:null})}}),e.jsx(Vt,{open:!!It,onOpenChange:a=>{a||Ms(null)},acaoLabel:(()=>{var s;const a=Me.find(t=>t.id===It);return a?`Cancelar pedido PP-${a.numero} â ${((s=a.racoes)==null?void 0:s.nome)||""}`:"Cancelar pedido"})(),onConfirm:async a=>{It&&await vi.mutateAsync({id:It,justificativa:a})}}),e.jsx(yn,{open:!!qt,onOpenChange:a=>{a||(ls(null),ms(""))},documentoLabel:(()=>{const a=fe.find(s=>s.id===qt);return a?`Programação Nº ${a.numero} ⢠${I(new Date(a.data_producao+"T00:00:00"),"dd/MM/yyyy")}`:"Programação de Produção"})(),onConfirm:a=>{ms(a),Xs(!0)}}),e.jsx(kn,{progId:Pr,onClose:()=>Us(null)}),e.jsx(Kt,{open:Mr,onOpenChange:Xs,documentoLabel:"Devolução de Programação à PCP",papelLabel:"Qualidade",assinanteNome:(_==null?void 0:_.full_name)||"",assinanteCodigo:(_==null?void 0:_.codigo)||null,onConfirmed:async()=>{await ui()}}),e.jsx(Vt,{open:Lr,onOpenChange:a=>{gs(a),!a&&!io&&(Dt(null),pt(""))},acaoLabel:"Reabrir programação para alteração",onConfirm:a=>{pt(a),gs(!1),no(!0)}}),e.jsx(Kt,{open:io,onOpenChange:a=>{no(a),a||(Dt(null),pt(""))},documentoLabel:(()=>{const a=fe.find(s=>s.id===hs);return a?`Reabrir Programação Nº ${a.numero}`:"Reabrir Programação"})(),papelLabel:"PCP",assinanteNome:(_==null?void 0:_.full_name)||"",assinanteCodigo:(_==null?void 0:_.codigo)||null,onConfirmed:async a=>{try{await pi(a||"")}catch(s){W({title:"Erro ao reabrir programação",description:s.message,variant:"destructive"})}}}),e.jsx(Wo,{open:!!Ps,onOpenChange:a=>!a&&Ss(null),children:e.jsxs(Jo,{children:[e.jsxs(Xo,{children:[e.jsx(Yo,{children:"Cancelar pesadinha?"}),e.jsx(Zo,{children:"O pedido será marcado como cancelado e a reserva de estoque (se houver) será revertida. Esta ação pode ser revertida editando o pedido."})]}),e.jsxs(er,{children:[e.jsx(ar,{disabled:et.isPending,children:"Voltar"}),e.jsx(tr,{onClick:a=>{a.preventDefault(),Ps&&et.mutate(Ps)},disabled:et.isPending,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:et.isPending?"Cancelando...":"Cancelar pesadinha"})]})]})})]})}export{dd 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.