PageSourceSearch

https://carregamento3bs.lovable.app/assets/AuditoriaRastreabilidadePage-lq5J9u5O.js

js carregamento3bs.lovable.app collected 2026-10-03 05:37:22 UTC 17,007 bytes, 31 lines download raw bytes

1import{u as te,r as M,j as e}from"./react-vendor-BorBU4Bs.js";import{u as oe,a as J,b as Y}from"./query-vendor-dlntIC_S.js";import{a as re,B as R,A as se,K as S,an as q,ao as P,M as D,L as E,I as G,G as ie,N as X,O as Z,Q as k,U as x,V as ee,W as m,m as b,p as w,n as I,dD as ne,T as de,s as F,D as le,i as ce,j as me,k as ue,cn as he,o as xe,bZ as pe,b_ as ge,db as Q,aX as ae,ci as _e,bV as fe,d$ as be}from"./index-DkhxOMdR.js";import{P as je}from"./PageHeader-BP8oDBUm.js";import{D as ye}from"./dice-5-4w00rxo3.js";import"./radix-vendor-CazrR58L.js";import"./charts-vendor-BxJanGhU.js";import"./supabase-vendor-BxTHC7hl.js";import"./xlsx-vendor-DOnNs5_d.js";import"./qr-vendor-Ca1-Dxvv.js";const y=s=>s==null?"—":Number(s).toLocaleString("pt-BR",{minimumFractionDigits:3,maximumFractionDigits:3}),W=s=>s==null?"—":`${s>=0?"+":""}${Number(s).toLocaleString("pt-BR",{minimumFractionDigits:2,maximumFractionDigits:2})}%`;function $(s,p){const i=s??0,j=p??0;return j===0?null:(i-j)/j*100}function we(){const s=new Date;return`${s.getFullYear()}-${String(s.getMonth()+1).padStart(2,"0")}`}function De(){const s=te(),{user:p}=re(),i=oe(),[j,v]=M.useState(we()),[z,A]=M.useState(5),[H,B]=M.useState(""),[n,d]=M.useState(null),{data:a=[],isLoading:u}=J({queryKey:["auditoria_rast_sorteios"],queryFn:async()=>{const{data:t,error:l}=await F.from("auditoria_rastreabilidade_sorteios").select("*").order("referencia_mes",{ascending:!1}).order("created_at",{ascending:!1});if(l)throw l;return t??[]}}),h=Y({mutationFn:async()=>{var f;const[t,l]=j.split("-").map(Number),g=pe(new Date(t,l-1,1)),T=ge(g),{data:O,error:L}=await F.from("producoes_externas").select("id").gte("data_producao",g.toISOString()).lte("data_producao",T.toISOString()).eq("tip_ordem_cancelada",!1).gt("total_realizado",0);if(L)throw L;const C=(O??[]).map(c=>c.id);if(C.length===0)throw new Error("Nenhuma produção encontrada no mês selecionado.");const N=Math.min(z,C.length),o=[...C].sort(()=>Math.random()-.5).slice(0,N),{error:_}=await F.from("auditoria_rastreabilidade_sorteios").insert({referencia_mes:`${j}-01`,quantidade:N,producao_externa_ids:o,observacao:H||null,sorteado_por:(p==null?void 0:p.id)??null,sorteado_por_nome:((f=p==null?void 0:p.user_metadata)==null?void 0:f.full_name)??(p==null?void 0:p.email)??null});if(_)throw _},onSuccess:()=>{Q({title:"Sorteio realizado"}),B(""),i.invalidateQueries({queryKey:["auditoria_rast_sorteios"]})},onError:t=>Q({title:"Erro",description:t.message,variant:"destructive"})}),r=Y({mutationFn:async t=>{const{error:l}=await F.from("auditoria_rastreabilidade_sorteios").delete().eq("id",t);if(l)throw l},onSuccess:()=>{Q({title:"Sorteio excluído"}),i.invalidateQueries({queryKey:["auditoria_rast_sorteios"]})}});return e.jsxs("div",{className:"space-y-6 animate-fade-in",children:[e.jsx("div",{className:"flex items-center gap-3",children:e.jsxs(R,{variant:"outline",size:"sm",onClick:()=>s("/qualidade"),className:"gap-2",children:[e.jsx(se,{className:"h-4 w-4"})," Voltar"]})}),e.jsx(je,{title:"Auditoria de Rastreabilidade",description:"Sorteio mensal aleatório de produções para auditoria da rastreabilidade"}),e.jsxs(S,{children:[e.jsx(q,{children:e.jsx(P,{className:"text-base",children:"Novo sorteio"})}),e.jsxs(D,{className:"grid gap-4 md:grid-cols-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(E,{children:"Mês de referência"}),e.jsx(G,{type:"month",value:j,onChange:t=>v(t.target.value)})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(E,{children:"Quantidade"}),e.jsx(G,{type:"number",min:1,max:200,value:z,onChange:t=>A(Math.max(1,Number(t.target.value)||1))})]}),e.jsxs("div",{className:"space-y-1 md:col-span-2",children:[e.jsx(E,{children:"Observação (opcional)"}),e.jsx(ie,{rows:1,value:H,onChange:t=>B(t.target.value),placeholder:"Ex.: auditoria interna trimestral"})]}),e.jsx("div",{className:"md:col-span-4",children:e.jsxs(R,{onClick:()=>h.mutate(),disabled:h.isPending,className:"gap-2",children:[e.jsx(ye,{className:"h-4 w-4"}),h.isPending?"Sorteando...":"Realizar sorteio"]})})]})]}),e.jsxs(S,{children:[e.jsx(q,{children:e.jsx(P,{className:"text-base",children:"Histórico de sorteios"})}),e.jsx(D,{children:u?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Carregando..."}):a.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Nenhum sorteio realizado."}):e.jsxs(X,{children:[e.jsx(Z,{children:e.jsxs(k,{children:[e.jsx(x,{children:"Mês"}),e.jsx(x,{children:"Sorteado em"}),e.jsx(x,{children:"Responsável"}),e.jsx(x,{children:"Quantidade"}),e.jsx(x,{children:"Observação"}),e.jsx(x,{className:"text-right",children:"Ações"})]})}),e.jsx(ee,{children:a.map(t=>e.jsxs(k,{children:[e.jsx(m,{className:"font-medium",children:b(w(t.referencia_mes),"MMMM/yyyy",{locale:ae})}),e.jsx(m,{children:b(w(t.created_at),"dd/MM/yyyy HH:mm")}
1),e.jsx(m,{children:t.sorteado_por_nome??"—"}),e.jsx(m,{children:e.jsx(I,{variant:"secondary",children:t.quantidade})}),e.jsx(m,{className:"max-w-[240px] truncate",children:t.observacao??"—"}),e.jsxs(m,{className:"text-right space-x-2",children:[e.jsxs(R,{size:"sm",variant:"outline",className:"gap-1",onClick:()=>d(t.id),children:[e.jsx(ne,{className:"h-3.5 w-3.5"})," Ver"]}),e.jsx(R,{size:"sm",variant:"ghost",onClick:()=>{confirm("Excluir este sorteio?")&&r.mutate(t.id)},children:e.jsx(de,{className:"h-3.5 w-3.5"})})]})]},t.id))})]})})]}),n&&e.jsx(Ne,{sorteio:a.find(t=>t.id===n),onClose:()=>d(null)})]})}function Ne({sorteio:s,onClose:p}){const{data:i,isLoading:j}=J({queryKey:["auditoria_rast_sorteio_detalhe",s.id],queryFn:async()=>{const n=s.producao_externa_ids;if(!n.length)return{producoes:[],ingredientes:{}};const{data:d,error:a}=await F.from("producoes_externas").select("id,num_producao,nom_produto,nom_linha_producao,total_realizado,total_requisitado,bateladas_realizadas,data_producao").in("id",n);if(a)throw a;const{data:u,error:h}=await F.from("producoes_rastreabilidade").select("producao_externa_id,nom_produto,lote_materia_prima,num_nota_fiscal,ordem_recebimento,nom_origem,peso_realizado,peso_requisitado,aditivo,num_batelada").in("producao_externa_id",n).order("num_batelada",{ascending:!0});if(h)throw h;const r={};return(u??[]).forEach(t=>{var l;(r[l=t.producao_externa_id]||(r[l]=[])).push(t)}),{producoes:d??[],ingredientes:r}}}),v=b(w(s.referencia_mes),"MMMM/yyyy",{locale:ae}),z=M.useMemo(()=>((i==null?void 0:i.producoes)??[]).reduce((n,d)=>n+(d.total_realizado??0),0),[i]);function A(){if(!i)return;const n=_e([{label:"Mês",value:v},{label:"Quantidade sorteada",value:s.quantidade},{label:"Peso produzido total (kg)",value:y(z)},{label:"Responsável",value:s.sorteado_por_nome??"—"},{label:"Sorteado em",value:b(w(s.created_at),"dd/MM/yyyy HH:mm")}]),d=i.producoes.sort((a,u)=>(a.num_producao??0)-(u.num_producao??0)).map(a=>{const u=(i.ingredientes[a.id]??[]).slice().sort((r,t)=>{const l=r.num_batelada??0,g=t.num_batelada??0;return l!==g?l-g:(r.nom_produto??"").localeCompare(t.nom_produto??"")}),h=u.length?u.map(r=>`<tr>
2          <td>${r.num_batelada??"—"}</td>
3          <td>${r.nom_produto??"—"}${r.aditivo?' <span style="color:#b45309;font-weight:600">(Aditivo)</span>':""}</td>
4          <td>${r.lote_materia_prima??"—"}</td>
5          <td>${r.num_nota_fiscal??"—"}</td>
6          <td>${r.ordem_recebimento??"—"}</td>
7          <td>${r.nom_origem??"—"}</td>
8          <td class="text-right mono">${y(r.peso_realizado)}</td>
9          <td class="text-right mono">${y(r.peso_requisitado)}</td>
10          <td class="text-right mono" style="color:${($(r.peso_realizado,r.peso_requisitado)??0)>=0?"#15803d":"#dc2626"}">${W($(r.peso_realizado,r.peso_requisitado))}</td>
11        </tr>`).join(""):'<tr><td colspan="9" class="text-center" style="color:#64748b">Sem ingredientes registrados.</td></tr>';return`
12      <h2>PP-${a.num_producao??"—"} — ${a.nom_produto??""}</h2>
13      <table class="id-table">
14        <tbody>
15          <tr><td>Linha de produção</td><td>${a.nom_linha_producao??"—"}</td></tr>
16          <tr><td>Data</td><td>${a.data_producao?b(w(a.data_producao),"dd/MM/yyyy HH:mm"):"—"}</td></tr>
17          <tr><td>Bateladas realizadas</td><td>${a.bateladas_realizadas??"—"}</td></tr>
18          <tr><td>Total realizado (kg)</td><td>${y(a.total_realizado)}</td></tr>
19          <tr><td>Total requisitado (kg)</td><td>${y(a.total_requisitado)}</td></tr>
20        </tbody>
21      </table>
22      <table class="compact">
23        <thead>
24          <tr>
25            <th>Bat.</th><th>
25Matéria-Prima</th><th>Lote</th><th>NF</th><th>OR</th><th>Origem</th>
26            <th class="text-right">Peso Real. (kg)</th><th class="text-right">Peso Req. (kg)</th><th class="text-right">Dif. %</th>
27          </tr>
28
29        </thead>
30        <tbody>${h}</tbody>
31      </table>`}).join("");fe({title:`Auditoria de Rastreabilidade — ${v}`,subtitle:`${s.quantidade} produção(ões) sorteada(s)`,orientation:"landscape",documentCode:`AUD-${b(w(s.created_at),"yyyyMMdd-HHmm")}`,headerVariant:"laudo",content:n+d})}async function H(){if(!i)return;const n=i.producoes.slice().sort((o,_)=>(o.num_producao??0)-(_.num_producao??0)),d=new be.Workbook;d.creator="3B Agro",d.created=new Date;const a=d.addWorksheet("Rastreabilidade",{views:[{state:"frozen",ySplit:4,showGridLines:!1}]}),u=`${window.location.origin}/logo-3bs.png`;try{const o=await fetch(u);if(o.ok){const _=await o.arrayBuffer(),f=d.addImage({buffer:_,extension:"png"});a.addImage(f,{tl:{col:.1,row:.1},ext:{width:140,height:60},editAs:"oneCell"})}}catch{}a.getRow(1).height=22,a.getRow(2).height=22,a.getRow(3).height=18,a.mergeCells("C1:Q1");const h=a.getCell("C1");h.value="Auditoria de Rastreabilidade",h.font={name:"Calibri",size:16,bold:!0,color:{argb:"FF1E3A8A"}},h.alignment={vertical:"middle",horizontal:"left"},a.mergeCells("C2:Q2");const r=a.getCell("C2");r.value=`Sorteio — ${v}   •   ${s.quantidade} produções   •   Peso total: ${z.toLocaleString("pt-BR",{minimumFractionDigits:3,maximumFractionDigits:3})} kg`,r.font={name:"Calibri",size:11,color:{argb:"FF475569"}},r.alignment={vertical:"middle",horizontal:"left"},a.mergeCells("C3:Q3");const t=a.getCell("C3");t.value=`Responsável: ${s.sorteado_por_nome??"—"}   •   Gerado em ${b(new Date,"dd/MM/yyyy HH:mm")}`,t.font={name:"Calibri",size:10,italic:!0,color:{argb:"FF64748B"}},t.alignment={vertical:"middle",horizontal:"left"};const l=[{name:"Produção",width:12},{name:"Produto",width:40},{name:"Linha",width:22},{name:"Data",width:18},{name:"Bat. Realizadas",width:14,alignment:{horizontal:"center"}},{name:"Total Realizado (kg)",width:20,numFmt:"#,##0.000",alignment:{horizontal:"right"}},{name:"Total Requisitado (kg)",width:20,numFmt:"#,##0.000",alignment:{horizontal:"right"}},{name:"Bat.",width:8,alignment:{horizontal:"center"}},{name:"Matéria-Prima",width:36},{name:"Aditivo",width:10,alignment:{horizontal:"center"}},{name:"Lote",width:16},{name:"NF",width:12},{name:"OR",width:12},{name:"Origem",width:22},{name:"Peso Realizado (kg)",width:20,numFmt:"#,##0.000",alignment:{horizontal:"right"}},{name:"Peso Requisitado (kg)",width:20,numFmt:"#,##0.000",alignment:{horizontal:"right"}},{name:"Diferença %",width:16,numFmt:"0.00%;-0.00%;—",alignment:{horizontal:"right"}}],g=[];n.forEach(o=>{const _=(i.ingredientes[o.id]??[]).slice().sort((c,U)=>{const K=c.num_batelada??0,V=U.num_batelada??0;return K!==V?K-V:(c.nom_produto??"").localeCompare(U.nom_produto??"")}),f=[`PP-${o.num_producao??""}`,o.nom_produto??"",o.nom_linha_producao??"",o.data_producao?b(w(o.data_producao),"dd/MM/yyyy HH:mm"):"",o.bateladas_realizadas??null,o.total_realizado??null,o.total_requisitado??null];_.length?_.forEach(c=>{g.push([...f,c.num_batelada??null,c.nom_produto??"",c.aditivo?"Sim":"",c.lote_materia_prima??"",c.num_nota_fiscal??"",c.ordem_recebimento??"",c.nom_origem??"",c.peso_realizado??null,c.peso_requisitado??null,$(c.peso_realizado,c.peso_requisitado)??null])}):g.push([...f,null,"","","","","","",null,null,null])}),a.addTable({name:"Rastreabilidade",ref:"A5",headerRow:!0,totalsRow:!1,style:{theme:"TableStyleMedium2",showRowStripes:!0},columns:l.map(o=>({name:o.name,filterButton:!0})),rows:g.length?g:[l.map(()=>"")]}),l.forEach((o,_)=>{const f=a.getColumn(_+1);f.width=o.width,o.numFmt&&(f.numFmt=o.numFmt),o.alignment&&(f.alignment={vertical:"middle",...o.alignment})});const T=a.getRow(5);T.height=26,T.eachCell(o=>{o.font={bold:!0,color:{argb:"FFFFFFFF"},size:11},o.alignment={vertical:"middle",horizontal:"center",wrapText:!0}});for(let o=6;o<=g.length+5;o++)a.getRow(o).alignment={vertical:"middle"};a.pageSetup={orientation:"landscape",fitToPage:!0,fitToWidth:1,fitToHeight:0,margins:{left:.4,right:.4,top:.5,bottom:.5,header:.3,footer
31:.3}},a.headerFooter.oddHeader=`&L&B3B Agro&R&BAuditoria de Rastreabilidade — ${v}`,a.headerFooter.oddFooter="&LGerado em "+b(new Date,"dd/MM/yyyy HH:mm")+"&RPágina &P de &N";const O=await d.xlsx.writeBuffer(),L=new Blob([O],{type:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"}),C=URL.createObjectURL(L),N=document.createElement("a");N.href=C,N.download=`auditoria-rastreabilidade-${b(w(s.created_at),"yyyyMMdd-HHmm")}.xlsx`,document.body.appendChild(N),N.click(),N.remove(),URL.revokeObjectURL(C)}const B=M.useMemo(()=>((i==null?void 0:i.producoes)??[]).slice().sort((n,d)=>(n.num_producao??0)-(d.num_producao??0)),[i]);return e.jsx(le,{open:!0,onOpenChange:p,children:e.jsxs(ce,{className:"max-w-6xl max-h-[90vh] overflow-y-auto",children:[e.jsx(me,{children:e.jsxs(ue,{className:"flex items-center justify-between gap-4",children:[e.jsxs("span",{children:["Sorteio — ",v]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(R,{size:"sm",variant:"outline",onClick:H,disabled:!i,className:"gap-2",children:[e.jsx(he,{className:"h-4 w-4"})," Exportar Excel"]}),e.jsxs(R,{size:"sm",variant:"outline",onClick:A,disabled:!i,className:"gap-2",children:[e.jsx(xe,{className:"h-4 w-4"})," Imprimir relatório"]})]})]})}),s.observacao&&e.jsx("p",{className:"text-sm text-muted-foreground italic",children:s.observacao}),!j&&e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-3",children:[e.jsxs(S,{children:[e.jsx(q,{className:"pb-2",children:e.jsx(P,{className:"text-xs text-muted-foreground uppercase",children:"Quantidade sorteada"})}),e.jsx(D,{className:"pt-0",children:e.jsx("p",{className:"text-2xl font-semibold",children:s.quantidade})})]}),e.jsxs(S,{children:[e.jsx(q,{className:"pb-2",children:e.jsx(P,{className:"text-xs text-muted-foreground uppercase",children:"Peso produzido total"})}),e.jsx(D,{className:"pt-0",children:e.jsxs("p",{className:"text-2xl font-semibold font-mono",children:[y(z)," kg"]})})]})]}),j?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Carregando produções..."}):e.jsx("div",{className:"space-y-6",children:B.map(n=>{const d=((i==null?void 0:i.ingredientes[n.id])??[]).slice().sort((a,u)=>{const h=a.num_batelada??0,r=u.num_batelada??0;return h!==r?h-r:(a.nom_produto??"").localeCompare(u.nom_produto??"")});return e.jsxs(S,{children:[e.jsx(q,{className:"pb-2",children:e.jsxs(P,{className:"text-sm flex flex-wrap items-center gap-2",children:[e.jsxs(I,{children:["PP-",n.num_producao]}),e.jsx("span",{children:n.nom_produto}),e.jsx("span",{className:"text-xs text-muted-foreground",children:n.data_producao?b(w(n.data_producao),"dd/MM/yyyy HH:mm"):""}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:["· ",n.nom_linha_producao??""," · ",n.bateladas_realizadas??0," bat. · ",y(n.total_realizado)," kg"]})]})}),e.jsx(D,{className:"pt-0",children:e.jsxs(X,{children:[e.jsx(Z,{children:e.jsxs(k,{children:[e.jsx(x,{children:"Bat."}),e.jsx(x,{children:"Matéria-Prima"}),e.jsx(x,{children:"Lote"}),e.jsx(x,{children:"NF"}),e.jsx(x,{children:"OR"}),e.jsx(x,{children:"Origem"}),e.jsx(x,{className:"text-right",children:"Peso Real. (kg)"}),e.jsx(x,{className:"text-right",children:"Peso Req. (kg)"}),e.jsx(x,{className:"text-right",children:"Dif. %"})]})}),e.jsx(ee,{children:d.length===0?e.jsx(k,{children:e.jsx(m,{colSpan:9,className:"text-center text-muted-foreground",children:"Sem ingredientes registrados."})}):d.map((a,u)=>e.jsxs(k,{children:[e.jsx(m,{children:a.num_batelada??"—"}),e.jsxs(m,{children:[a.nom_produto??"—",a.aditivo&&e.jsx(I,{variant:"outline",className:"ml-1 text-[10px]",children:"Aditivo"})]}),e.jsx(m,{className:"font-mono text-xs",children:a.lote_materia_prima??"—"}),e.jsx(m,{className:"font-mono text-xs",children:a.num_nota_fiscal??"—"}),e.jsx(m,{className:"font-mono text-xs",children:a.ordem_recebimento??"—"}),e.jsx(m,{className:"text-xs",children:a.nom_origem??"—"}),e.jsx(m,{className:"text-right font-mono",children:y(a.peso_realizado)}),e.jsx(m,{className:"text-right font-mono",children:y(a.peso_requisitado)}
31),e.jsx(m,{className:`text-right font-mono ${($(a.peso_realizado,a.peso_requisitado)??0)>=0?"text-emerald-600":"text-red-600"}`,children:W($(a.peso_realizado,a.peso_requisitado))})]},u))})]})})]},n.id)})})]})})}export{De 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.