PageSourceSearch

https://app.stoqui.com.br/assets/OrderPage-B_L7I5Yw.js

js stoqui.com.br collected 2026-09-24 11:57:38 UTC 115,358 bytes, 8 lines download raw bytes

1function __vite__mapDeps(indexes) {
2  if (!__vite__mapDeps.viteFileDeps) {
3    __vite__mapDeps.viteFileDeps = ["assets/react-pdf.browser-1EhQzxMi.js","assets/vendor-Dwao9eNC.js","assets/index-TALscxEc.js","assets/mui-CRsYZxVY.js","assets/query-8ViTdhdk.js","assets/datePickers-BIJXYOKG.js","assets/icons-D8aatgQ4.js","assets/lab-DSem1Osk.js","assets/index-TuPg2doO.css","assets/index-BNv7yOC_.js","assets/VectorizedPrintOrder-o2QTzEOv.js","assets/stoqui_logo-C1JOQLy2.js","assets/VectorizedPrintThermalReceipt-DV9mnvng.js","assets/VectorizedPrintLabel-CXd76K0r.js","assets/VectorizedPrintContentDeclaration-CsvSmyoR.js"]
4  }
5  return indexes.map((i) => __vite__mapDeps.viteFileDeps[i])
6}
7import{j as e,R as Gr,as as Jt,az as Hr,ac as Y,T as n,aS as $r,I as ce,a7 as j,ad as Qe,ab as h,N as ee,aP as co,at as lo,n as K,ar as oe,ao as ye,a2 as fe,Q as qt,aj as Xo,a6 as Ar,am as Qr,aB as Yt,S as ht,X as Ie,ai as We,Z as Ne,aq as Rt,O as Xe,ap as Xr,aA as Kr,z as Ko,F as Jr,x as Yr,ag as jr,an as yr,H as Zt}from"./mui-CRsYZxVY.js";import{r as y,b as Jo}from"./vendor-Dwao9eNC.js";import{eK as Zr,f as en,cR as tn,aK as ot,w as _e,b as xt,u as _r,jm as br,jn as on,fV as rn,cd as vr,bC as nn,i6 as an,bo as Ue,dt as uo,c1 as Ke,eE as Lt,d as Je,e as rt,L as kt,N as Ot,x as ft,cX as po,b2 as Pe,eO as eo,eP as to,jo as Yo,cI as Ce,cJ as we,cK as mt,O as He,e6 as oo,dO as sn,dk as cn,bN as Pr,aP as Be,aR as Vt,aS as pt,aT as Ct,d4 as Et,bp as Gt,fC as ln,f0 as Dt,ce as Cr,b3 as dn,eJ as un,fD as wt,fE as St,d0 as pn,eZ as de,cE as hn,r as mn,jp as Zo,hy as ro,dL as gn,jq as xn,jd as Ht,bv as fn,t as ue,l as pe,e_ as An,e$ as er,c5 as gt,bJ as jn,bd as wr,be as yn,cc as _n,c4 as bn,cf as vn,J as Pn,v as Cn,bc as wn,T as $t,eC as Qt,d2 as Sn,fG as Rn,dU as En,c0 as Dn,eo as Fn,jr as Ln}from"./index-TALscxEc.js";import{C as kn,u as On,a as Tn,E as tr,D as zn}from"./CouponAutocomplete-BexDkgcw.js";import{d as ho}from"./WhatsApp-BptyU9R8.js";import{O as Bn}from"./OrderItem-CsdOOeix.js";import{b as At,u as Tt,a as Ye}from"./query-8ViTdhdk.js";import{u as Mn}from"./useCoupons-CuAoKPbZ.js";import{u as qe}from"./useOrder-LNg72HR0.js";import{u as In}from"./useEditOrder-huvS-0Uk.js";import{u as Wn}from"./useManuallyMarkAsPaid--R2QrhA2.js";import{u as Nn}from"./useUpsertShipping-BtB9W1wN.js";import{u as jt}from"./useOrderPayments-CFbAn2A1.js";import{u as zt}from"./useCustomerAddresses-DvZt7JUJ.js";import{C as Un}from"./CopyMenuItem-BcRtSJPl.js";import{d as qn}from"./Store-BexQoHku.js";import{P as no}from"./PaymentMethodIcon-CIdwzC1T.js";import{f as Me}from"./formatDueDateRelative-DwwUQMjj.js";import{a as Vn}from"./installmentAdjustmentUtils-BOi-cx_o.js";import{g as Gn}from"./paymentMethodIcons-Ckq94o3a.js";import{u as Hn,C as $n}from"./CreditCardFlag-BE87Kgx3.js";import{b as Qn,r as Xn,z as Kn,l as or,p as rr,M as Jn,ag as Yn,ah as Zn}from"./icons-D8aatgQ4.js";import{n as ea,b as ta}from"./notaFiscalDanfe-BoR-dr4F.js";import{C as oa}from"./CertificadoReenvioAlert-4LpNdURr.js";import{u as ra}from"./useFiscalConfig-CQEKyhOW.js";import{L as Ft}from"./lab-DSem1Osk.js";import{J as na}from"./JsBarcode-CTZHrd1V.js";import{B as aa,a as ia}from"./BluetoothPermissionDialog-BXZtrYiq.js";import{u as mo}from"./useSuperfreteLabel-B1foOU7S.js";import{d as $e}from"./Edit-BiqqVQWD.js";import{u as sa}from"./useEditOrderProducts-DOTx1POv.js";import{d as ao}from"./NavigateNext-uXnLAjyH.js";import{I as ca}from"./InlineEditText-O-PTkbvc.js";import{u as la}from"./useSuperfrete-Od49r8js.js";import{d as da}from"./HourglassEmpty-DSysZohU.js";import{d as ua}from"./Refresh-C4waymBA.js";import{a as pa}from"./datePickers-BIJXYOKG.js";import"./ProductAvatar-BTM6y7KS.js";import"./OrderItemPersonalizationSummary-D7xeZSuv.js";import"./sortOrderItems-DQf7TVvt.js";import"./mercado-pago-color-B_n0DTpx.js";import"./pagaleve-icon-D0kfWVyv.js";import"./isTomorrow-w9r6QR7N.js";import"./index-BxYBTvZk.js";import"./comboCart-DscpHqAi.js";(function(){try{var o=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{};o.SENTRY_RELEASE={id:"2ad85febf9735404429b0670d4acf56a0af5a0a2"}}catch{}})();try{(function(){var o=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},i=new o.Error().stack;i&&(o._sentryDebugIds=o._sentryDebugIds||{},o._sentryDebugIds[i]="9df13109-d029-4f99-be83-56dd888a26bf",o._sentryDebugIdIdentifier="sentry-dbid-9df13109-d029-4f99-be83-56dd888a26bf")})()}catch{}const ha=({name:o,phone:i="",imageUrl:d,userId:u,onClick:f})=>e.jsx(Gr,{disablePadding:!0,children:e.jsxs(Jt,{onClick:f,sx:{padding:2,display:"flex",justifyContent:"space-between",width:"100%"},children:[e.jsx(Hr,{children:e.jsx(Zr,{alt:o,id:`customer-avatar-${u}`,imageUrl:d,sx:{width:56,height:56,marginRight:2}})}),e.jsx(Y,{primary:e.jsx("span",{children:o}),secondary:e.jsx(n,{variant:"body2",sx:{color:"text.secondary",fontSize:"11px"},children:en(i)}),primaryTypographyProps:{noWrap:!0}})," ",e.jsx($r,{children:e.jsx(ce,{edge:"end","aria-label":"details",color:"primary",size:"small",children:e.jsx(tn,{})})}),e.jsx("div",{style:{height:64,width:"36px",minWidth:"36px",visibility:"hidden"}})]})}),ma=()=>At({mutationFn:async o=>{await ot.post("/digital-goods/order-item",{pedido_id:o})}}),ga=async o=>(await ot.get(`/order/${o}
7/signed-url`)).data,Sr=o=>Tt({queryKey:["signedOrderUrl",o],queryFn:()=>ga(o),enabled:!!o,staleTime:1e3*60*60*24});function io(o){return`${o.produto_id}:${o.produto_variacao_id??"base"}`}const xa=o=>{const i=y.useMemo(()=>o.map(io).sort().join(","),[o]);return Tt({enabled:o.length>0,queryKey:["unused-codigo-pools",i],queryFn:async()=>{const d=Array.from(new Set(o.map(c=>c.produto_id)));if(d.length===0)return new Set;const{data:u,error:f}=await _e.from("produto_codigo_digital").select("produto_id, produto_variacao_id").in("produto_id",d).is("usado_em",null);if(f)throw f;const C=new Set;for(const c of u||[])C.add(io({produto_id:c.produto_id,produto_variacao_id:c.produto_variacao_id??null}));return C},staleTime:30*1e3})};function nr(o,i){return o?o.has(io(i)):!0}const fa=2e3;function Aa(o,i){const d=[...o].sort((u,f)=>u-f).join(",");return Tt({enabled:o.length>0&&!!i,queryKey:["order-digital-item-fontes",i,d],queryFn:async()=>{const{data:u,error:f}=await _e.from("produto_arquivo_digital").select("produto_id, produto_variacao_id, fonte").in("produto_id",o);if(f)throw f;return u||[]}})}function ar(o){return Array.isArray(o.digital_codigos)&&o.digital_codigos.length>0?o.digital_codigos:o.digital_codigo?[o.digital_codigo]:[]}function Xt(o,i,d){if(!o)return null;if(d!==null){const f=o.find(C=>C.produto_id===i&&C.produto_variacao_id===d);if(f)return f.fonte}const u=o.find(f=>f.produto_id===i&&f.produto_variacao_id===null);return(u==null?void 0:u.fonte)??null}function ja(o){const{orderStatus:i,deliveredAt:d,accessedAt:u,accessCount:f,fonte:C,deliveredCount:c,quantidade:g,poolEmpty:s}=o;if(!br.has(i))return i==="canceled"||i==="returned"?{text:"Acesso encerrado com o pedido",tone:"warning"}:{text:"Aguardando pagamento",tone:"muted"};if(C==="codigo"){if(c===0)return s?{text:g>1?`Aguardando ${g} códigos - adicione mais códigos`:"Aguardando código - adicione mais códigos",tone:"warning"}:{text:"Aguardando comprador acessar o código",tone:"muted"};if(c<g)return{text:s?`${c} de ${g} entregues - adicione mais códigos`:`${c} de ${g} entregues - aguardando comprador`,tone:s?"warning":"muted"}}if(u){const _=Ue(new Date(u),"dd/MM 'às' HH:mm"),l=C==="codigo"?"Visto":"Baixado";return{text:f>1?`${l} ${f}x · última em ${_}`:`${l} em ${_}`,tone:"success"}}if(d){const _=Ue(new Date(d),"dd/MM 'às' HH:mm");return{text:`${C==="codigo"?"Código entregue":"Disponibilizado"} em ${_}`,tone:"muted"}}return{text:"Ainda não acessado",tone:"muted"}}const ya=({pedidoId:o,items:i,orderStatus:d,customerPhone:u,customerEmail:f,orderNumber:C})=>{const c=xt(),{user:g}=_r(),s=y.useMemo(()=>i.filter(a=>{var F;return(F=a.produto)==null?void 0:F.digital}),[i]),_=y.useMemo(()=>Array.from(new Set(s.map(a=>a.produto_id))),[s]),{data:l}=Aa(_,g==null?void 0:g.id),T=y.useMemo(()=>s.map(a=>({produto_id:a.produto_id,produto_variacao_id:a.produto_variacao_id})).filter(a=>Xt(l,a.produto_id,a.produto_variacao_id)==="codigo"),[s,l]),{data:z}=xa(T),H=ma(),{data:b}=Sr(o),[w,U]=y.useState("idle");if(s.length===0)return null;const D=br.has(d),Q=s.some(a=>{if(!D||Xt(l,a.produto_id,a.produto_variacao_id)!=="codigo")return!1;const A=ar(a),P=Math.max(1,Number(a.quantidade)||1);return A.length>=P?!1:!nr(z,{produto_id:a.produto_id,produto_variacao_id:a.produto_variacao_id})}),E=async()=>{if(!(w!=="idle"||H.isPending)){try{await H.mutateAsync(o),U("sent")}catch{U("error")}setTimeout(()=>U("idle"),fa)}},Z=()=>{if(!u||!(b!=null&&b.signedUrl))return;const a=`Olá! Seu pedido #${C} está pronto. Acesse aqui: ${b.signedUrl}`,F=`https://wa.me/${u}?text=${encodeURIComponent(a)}`;window.open(F,"_blank","noopener,noreferrer")};return e.jsxs(j,{sx:{backgroundColor:"white",p:2.5,borderRadius:2,mb:2},children:[e.jsx(n,{variant:"h6",fontWeight:600,sx:{mb:2},children:"Entrega digital"}),Q&&e.jsx(Qe,{severity:"warning",sx:{mb:2},children:"Um ou mais itens estão aguardando código. Adicione mais códigos na página de entrega do produto para liberar o acesso."}),e.jsx(h,{spacing:1.5,children:s.map(a=>{var N,re;const F=`${a.produto_id}-${a.produto_variacao_id||"base"}`,A=a.produto_variacao?`${(N=a.produto)==null?void 0:N.nome} · ${a.produto_variacao.nome}`:((re=a.produto)==null?void 0:re.nome)||"Produto",P=Xt(l,a.produto_id,a.produto_variacao_id),S=P==="codigo"&&!nr(z,{produto_id:a.produto_id,produto_variacao_id:a.produto_variacao_id}),v=ar(a),m=Math.max(1,Number(a.quantidade)||1),{text:X,tone:k}=ja({orderStatus:d,deliveredAt:a.digital_entregue_em,accessedAt:a.digital_acessado_em,accessCount:a.digital_acessos??0,fonte:P,deliveredCount:v.length,quantidade:m,poolEmpty:S}),M=k==="success"?"success.dark":k==="warning"?"warning.dark":"text.secondary",t=P==="codigo"&&D&&v.length>0,O=P==="codigo"&&D&&v.length<m&&S;return e.jsxs(h,{direction:"row",spacing:1.5,alignItems:"flex-start",children:[e.jsx(j,{sx:{width:32,height:32,borderRadius:1,bgcolor:"grey.100",color:"text.secondary",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0},children:P==="codigo"?e.jsx(on,{size:18}):e.jsx(rn,{size:18})}),e.jsxs(j,{sx:{flex:1,minWidth:0},children:[e.jsx(n,{variant:"body2",fontWeight:500,sx:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:A}),e.jsx(n,{variant:"caption",sx:{color:M},children:X}),t&&e.jsx(h,{spacing:.5,sx:{mt:.5},children:v.map((r,x)=>e.jsxs(h,{direction:"row",alignItems:"center",spacing:.5,children:[e.jsx(n,{variant:"body2",sx:{fontFamily:"monospace",fontWeight:600,wordBreak:"break-all",flex:1,minWidth:0},children:r}),e.jsx(vr,{text:r,size:"small",iconSize:16})]},`${r}-${x}`))}),O&&e.jsx(ee,{size:"small",onClick:()=>c(`/products/${a.produto_id}/digital-delivery`),sx:{mt:.5,minHeight:32,px:0},children:"Adicionar códigos"})]})]},F)})}),D&&(f||u&&(b==null?void 0:b.signedUrl))&&e.jsxs(h,{direction:"row",spacing:.5,justifyContent:"flex-end",sx:{mt:2},children:[u&&(b==null?void 0:b.signedUrl)&&e.jsx(ee,{size:"small",startIcon:e.jsx(ho,{sx:{fontSize:16}}),onClick:Z,sx:{minHeight:36},children:"WhatsApp"}),f&&e.jsx(ee,{size:"small",onClick:E,disabled:H.isPending||w!=="idle",color:w==="sent"?"success":w==="error"?"error":"primary",startIcon:w==="sent"?e.jsx(nn,{size:16}):e.jsx(an,{size:16}),sx:{minHeight:36},children:w==="sent"?"Enviado":w==="error"?"Tente novamente":"E-mail"})]})]})};var go={},_a=co;Object.defineProperty(go,"__esModule",{value:!0});var Rr=go.default=void 0,ba=_a(uo()),ir=e;Rr=go.default=(0,ba.default)([(0,ir.jsx)("path",{d:"M19.5 3.5 18 2l-1.5 1.5L15 2l-1.5 1.5L12 2l-1.5 1.5L9 2 7.5 3.5 6 2v14H3v3c0 1.66 1.34 3 3 3h12c1.66 0 3-1.34 3-3V2zM15 20H6c-.55 0-1-.45-1-1v-1h10zm4-1c0 .55-.45 1-1 1s-1-.45-1-1v-3H8V5h11z"},"0"),(0,ir.jsx)("path",{d:"M9 7h6v2H9zm7 0h2v2h-2zm-7 3h6v2H9zm7 0h2v2h-2z"},"1")],"ReceiptLongOutlined");const Er=o=>{const[i,d]=y.useState(!1),[u,f]=y.useState(null),[C,c]=y.useState(""),g=Ke.isNativePlatform(),{data:s}=qe(o),{data:_}=Lt(),{data:l}=Je(),{data:T}=jt(o),{data:z}=rt(),{data:H}=zt(s==null?void 0:s.cliente_id),{data:b}=kt(),{storeUrl:w}=Ot(),U=ft(z),D=po(b==null?void 0:b.configuracao_impressao).incluir_fotos_no_comprovante,Q=()=>{const a=Ue(new Date,"yyyy-MM-dd_HH-mm-ss");return`pedido-stoqui_${(s==null?void 0:s.numero_pedido)||(s==null?void 0:s.pedido_id)||o}_${a}.pdf`};return{isGenerating:i,error:u,progress:C,isMobile:g,generateAndShareOrderPDF:async()=>{var a,F;d(!0),f(null),c("Preparando comprovante...");try{const[{pdf:A},{default:P}]=await Promise.all([Pe(()=>import("./react-pdf.browser-1EhQzxMi.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9])),Pe(()=>import("./VectorizedPrintOrder-o2QTzEOv.js"),__vite__mapDeps([10,3,1,0,2,4,5,6,7,8,9,11]))]),S=Q();c("Processando imagens...");let v=l;if(l!=null&&l.logo_url)if(eo(l.logo_url)){const M=await to(l.logo_url,300,78,.8);v={...l,processed_logo_url:M}}else v={...l,processed_logo_url:l.logo_url};const m=D?await Yo(s==null?void 0:s.itens_pedido):void 0;c("Gerando PDF...");const k=await A(e.jsx(P,{order:s,storeAddress:_,webCatalog:v,paymentData:T,customerAddresses:H,storeUrl:w,isPro:U,includePhotos:D,productImagesMap:m})).toBlob();if(g){c("Preparando para compartilhar...");const M=new FileReader,t=await new Promise(N=>{M.onloadend=()=>{const re=M.result.split(",")[1];N(re)},M.readAsDataURL(k)});await Ce.writeFile({path:S,data:t,directory:we.Cache,recursive:!0});const O=await Ce.getUri({directory:we.Cache,path:S});await mt.share({title:"Comprovante do pedido",text:"Comprovante PDF gerado",url:O.uri,dialogTitle:"Compartilhar PDF"})}else{const M=URL.createObjectURL(k),t=window.open(M,"_blank");if(t)t.onload=()=>{t.print(),setTimeout(()=>{URL.revokeObjectURL(M)},1e3)};else{const O=document.createElement("a");O.href=M,O.download=S,document.body.appendChild(O),O.click(),document.body.removeChild(O),URL.revokeObjectURL(M)}}c("Concluído!")}catch(A){A!=null&&A.message&&!((F=(a=A==null?void 0:A.message)==null?void 0:a.toLowerCase())!=null&&F.includes("cancel"))&&(f("Ocorreu um erro ao gerar o PDF. Por favor, tente novamente."),console.error("Error generating PDF:",A))}finally{d(!1),c("")}},generateAndDownloadOrderPDF:async()=>{var a,F;d(!0),f(null),c("Preparando comprovante...");try{const[{pdf:A},{default:P}]=await Promise.all([Pe(()=>import("./react-pdf.browser-1EhQzxMi.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9])),Pe(()=>import("./VectorizedPrintOrder-o2QTzEOv.js"),__vite__mapDeps([10,3,1,0,2,4,5,6,7,8,9,11]))]),S=Q();c("Processando imagens...");let v=l;if(l!=null&&l.logo_url)if(eo(l.logo_url)){const M=await to(l.logo_url,300,78,.8);v={...l,processed_logo_url:M}}else v={...l,processed_logo_url:l.logo_url};const m=D?await Yo(s==null?void 0:s.itens_pedido):void 0;c("Gerando PDF...");const k=await A(e.jsx(P,{order:s,storeAddress:_,webCatalog:v,paymentData:T,customerAddresses:H,storeUrl:w,isPro:U,includePhotos:D,productImagesMap:m})).toBlob();if(g){c("Preparando para compartilhar...");const M=new FileReader,t=await new Promise(N=>{M.onloadend=()=>{const re=M.result.split(",")[1];N(re)},M.readAsDataURL(k)});await Ce.writeFile({path:S,data:t,directory:we.Cache,recursive:!0});const O=await Ce.getUri({directory:we.Cache,path:S});await mt.share({title:"Comprovante do pedido",text:"Comprovante PDF gerado",url:O.uri,dialogTitle:"Compartilhar PDF"})}else{const M=URL.createObjectURL(k),t=document.createElement("a");t.href=M,t.download=S,document.body.appendChild(t),t.click(),document.body.removeChild(t),URL.revokeObjectURL(M)}c("Concluído!")}catch(A){A!=null&&A.message&&!((F=(a=A==null?void 0:A.message)==null?void 0:a.toLowerCase())!=null&&F.includes("cancel"))&&(f("Ocorreu um erro ao gerar o PDF. Por favor, tente novamente."),console.error("Error generating PDF:",A))}finally{d(!1),c("")}},setError:f}}
7,va=({anchorEl:o,open:i,onClose:d,onMoveOrder:u,onDeleteOrder:f,orderNumber:C,orderId:c,customerPhone:g})=>{const{data:s}=Je(),{storeUrl:_}=Ot(),{data:l}=qe(c),{data:T}=rt(),{data:z}=Sr(c||null),{isGenerating:H,isMobile:b,generateAndShareOrderPDF:w}=Er(c||0),U=ft(T),[D,Q]=y.useState(!1),E=()=>z!=null&&z.signedUrl?z.signedUrl:s?`${_}/conta/pedidos/${C}`:"",Z=async()=>{if(!c||!l||!s){console.error("Order data not ready yet");return}await w(),d()},a=()=>{const P=E();if(!P){console.error("Unable to share: Web catalog not available");return}const S=`Olá! Aqui estão os detalhes do seu Pedido #${C}:
8${P}`;window.open(`https://wa.me/${g}?text=${encodeURIComponent(S)}`,"_blank"),d()},F=()=>{u(),d()},A=()=>{f&&f(),d()};return e.jsx(e.Fragment,{children:e.jsxs(lo,{anchorEl:o,open:i,onClose:()=>{D||d()},children:[e.jsxs(K,{onClick:Z,disabled:H||!c||!l||!s,children:[e.jsx(oe,{children:e.jsx(Rr,{})}),e.jsxs(h,{direction:"row",spacing:1,alignItems:"center",justifyContent:"space-between",width:"100%",children:[e.jsx(Y,{primary:b?"Compartilhar comprovante":"Baixar comprovante"}),e.jsx(He,{fontSize:"0.75rem",variant:U?"cutout":"text"})]})]}),e.jsxs(K,{onClick:a,children:[e.jsx(oe,{children:e.jsx(ho,{})}),e.jsx(Y,{primary:"Compartilhar link"})]}),e.jsx(Un,{text:E(),onCopied:d,onCopyStateChange:Q}),e.jsxs(K,{onClick:F,children:[e.jsx(oe,{children:e.jsx(oo,{})}),e.jsx(Y,{primary:"Mudar status"})]}),f?e.jsxs(K,{onClick:A,children:[e.jsx(oe,{children:e.jsx(sn,{color:"primary"})}),e.jsx(Y,{primary:"Excluir pedido"})]}):null]})})},Pa=o=>o==="manual"?{label:"Presencial",icon:e.jsx(qn,{}),bg:"#F3E8FF",color:"#7C3AED"}:{label:"Online",icon:e.jsx(cn,{}),bg:"#EFF6FF",color:"#2563EB"},sr=({paymentId:o})=>{const{data:i}=Hn(o);if(!(i!=null&&i.payment))return null;const d=i.payment,u=d.billingType==="CREDIT_CARD",f=d.billingType==="DEBIT_CARD",C=u||f;return e.jsxs(h,{direction:"row",spacing:.5,alignItems:"center",sx:{mt:.25},children:[C&&d.creditCard&&e.jsxs(e.Fragment,{children:[e.jsx($n,{brand:d.creditCard.creditCardBrand,size:"small"}),e.jsxs(n,{variant:"caption",color:"text.secondary",sx:{fontSize:"0.7rem"},children:["•••• ",d.creditCard.creditCardNumber]})]}),d.billingType==="PIX"&&e.jsx(n,{variant:"caption",color:"text.secondary",sx:{fontSize:"0.7rem"},children:"Pix"})]})};function Ca({orderId:o,orderStatus:i,onVisibilityChange:d}){const u=xt(),f=Ye(),[C,c]=Jo.useState(!1),{data:g,isLoading:s,isError:_}=jt(o),{data:l}=qe(o),z=!((g==null?void 0:g.parcelas.some(r=>r.status_parcela==="cancelada"||r.status_parcela==="reembolsada"))||!1),H=["new","pending_payment"].includes(i),b=["paid","processing","shipped","delivered"].includes(i),w=()=>{const r=(l==null?void 0:l.condicao_pagamento)==="parcelado",x=(l==null?void 0:l.condicao_pagamento)==="fiado",B=(g==null?void 0:g.parcelas)&&g.parcelas.length>0;u(r&&B?`/orders/${o}/payment/installments`:x&&B?`/orders/${o}/payment/fiado/view`:`/orders/${o}/payment/config`)},U=()=>{if(!(g!=null&&g.parcelas.length))return null;switch((l==null?void 0:l.condicao_pagamento)||"a_vista"){case"a_vista":return"À Vista";case"parcelado":return"Parcelado";case"fiado":return"Fiado";default:return"À Vista"}},D=()=>{var q;if(!l)return 0;const r=(l.itens_pedido||[]).reduce((ne,G)=>ne+G.quantidade*G.preco_snapshot,0),x=((q=l.frete_pedido)==null?void 0:q.valor_frete)||0,B=l.taxa_de_venda||0,R=l.valor_desconto||0;return Number((r+x+B-R).toFixed(2))},Q=()=>g!=null&&g.parcelas.length?g.parcelas.reduce((r,x)=>r+x.valor_original,0):0,E=()=>{const r=D(),x=Q(),B=Math.abs(r-x);return{hasMismatch:B>.06,orderTotal:r,installmentTotal:x,difference:B}},Z=async()=>{c(!0);try{const r=D(),x=await Vn(o,r);x.success?(await f.invalidateQueries({queryKey:["orderPayments",o]}),await f.invalidateQueries({queryKey:["pedido",o]}),await f.invalidateQueries({queryKey:["allInstallments"]}),await f.invalidateQueries({queryKey:["receivedPayments"]})):console.error("Failed to recalculate installments:",x.error)}catch(r){console.error("Error recalculating installments:",r)}finally{c(!1)}},a=r=>({cash:1,pix:2,custom:3,credit_card:4,debit_card:5,mercadopago:6,pagaleve:7})[r]||3,F=async()=>
8{if(g!=null&&g.parcelas.length){c(!0);try{const r=[];for(const x of g.parcelas){const B=x.pagamentos||[];if(B.length===0)continue;const R=Be(B.filter(W=>W.status==="pago").map(W=>W.valor)),q=x.valor_original,ne=Ct(R,q);if(pt(ne)<=1)continue;const G=[...B].sort((W,ie)=>{var xe,ae;return a(((xe=W.forma_pagamento)==null?void 0:xe.codigo_padrao)||"custom")-a(((ae=ie.forma_pagamento)==null?void 0:ae.codigo_padrao)||"custom")});let I=ne;for(const W of G){if(pt(I)<=1)break;const ie=Math.min(I,W.valor),xe=Number((W.valor-ie).toFixed(2));r.push({paymentId:W.id,newValue:Math.max(0,xe),oldValue:W.valor}),I-=ie}}for(const x of r)x.newValue===0?await _e.from("pagamento").delete().eq("id",x.paymentId):await _e.from("pagamento").update({valor:x.newValue}).eq("id",x.paymentId);await f.invalidateQueries({queryKey:["orderPayments",o]}),await f.invalidateQueries({queryKey:["pedido",o]}),await f.invalidateQueries({queryKey:["allInstallments"]}),await f.invalidateQueries({queryKey:["receivedPayments"]})}catch(r){console.error("Error correcting payments:",r)}finally{c(!1)}}},A=g&&g.parcelas.length>0,P=(l==null?void 0:l.condicao_pagamento)==="parcelado",S=(l==null?void 0:l.condicao_pagamento)==="fiado";if(Jo.useEffect(()=>{d&&d(s||_||A||b)},[s,_,A,b,d]),s)return e.jsx(j,{sx:{backgroundColor:"white",borderRadius:2,p:2},children:e.jsxs(h,{spacing:2,children:[e.jsx(ye,{variant:"rounded",width:"100%",height:60}),e.jsx(ye,{variant:"rounded",width:"100%",height:40})]})});if(_)return e.jsx(j,{sx:{backgroundColor:"white",borderRadius:2,p:2},children:e.jsx(Qe,{severity:"error",children:"Erro ao carregar informações de pagamento"})});if(!A&&H)return null;if(!A&&b)return e.jsx(j,{sx:{backgroundColor:"white",borderRadius:2,p:2},children:e.jsxs(h,{spacing:2,alignItems:"center",sx:{py:2},children:[e.jsx(Pr,{size:40,style:{color:"rgba(0, 0, 0, 0.26)"}}),e.jsx(n,{variant:"body1",color:"text.secondary",textAlign:"center",children:"Nenhum pagamento está registrado no sistema"}),e.jsx(n,{variant:"body2",color:"text.secondary",textAlign:"center",sx:{fontSize:"0.875rem"},children:"Este pedido foi marcado como pago mas não há registros de pagamento"}),z&&e.jsx(ee,{variant:"contained",onClick:w,sx:{mt:1,textTransform:"none",fontWeight:500},children:"Adicionar pagamento"})]})});if(!A)return null;const{parcelas:v}=g,m=r=>Be((r.pagamentos||[]).filter(x=>x.status==="pago").map(x=>x.valor)),X=Be(v.map(m)),k=Be(v.map(r=>Vt(r.valor_original,m(r)))),M=v.flatMap(r=>{var x;return((x=r.pagamentos)==null?void 0:x.map(B=>({...B,parcela_numero:r.numero_parcela})))||[]}),t=U(),O=v.filter(r=>pt(Ct(m(r),r.valor_original))>1),N=Be(O.map(r=>Ct(m(r),r.valor_original))),re=O.length>0;return e.jsx(j,{sx:{backgroundColor:"white",borderRadius:2,p:2},children:e.jsxs(h,{spacing:2,children:[e.jsxs(h,{direction:"row",justifyContent:"space-between",alignItems:"center",children:[t&&e.jsx(n,{variant:"caption",color:"primary.main",fontWeight:600,sx:{letterSpacing:"0.5px",fontSize:"0.75rem"},children:t}),e.jsx(j,{sx:{flex:1}}),z&&e.jsx(ce,{size:"small",onClick:w,children:e.jsx(Qn,{fontSize:"small"})})]}),(()=>{const r=E();return r.hasMismatch&&e.jsx(Qe,{severity:"warning",sx:{borderRadius:2,".MuiAlert-message":{width:"100%"}},action:e.jsx(ee,{color:"warning",size:"small",onClick:Z,disabled:C,startIcon:e.jsx(Xn,{}),sx:{textTransform:"none",fontWeight:500,minWidth:"auto"},children:C?"Recalculando...":"Recalcular"}),children:e.jsx(h,{spacing:1,children:(()=>{const x=(l==null?void 0:l.condicao_pagamento)||"a_vista";return x==="a_vista"||x==="fiado"?e.jsxs(e.Fragment,{children:[e.jsx(n,{variant:"body2",fontWeight:500,children:"Valores de pagamento não coincidem com o total do pedido"}),e.jsxs(h,{direction:"row",spacing:2,sx:{fontSize:"0.875rem"},children:[e.jsxs(n,{variant:"caption",color:"text.secondary",children:["Total do pedido:"," ",r.orderTotal.toLocaleString("pt-BR",{style:"currency",currency:"BRL"})]}),e.jsxs(n,{variant:"caption",color:"text.secondary",children:["Valor configurado:"," ",r.installmentTotal.toLocaleString("pt-BR",{style:"currency",currency:"BRL"})]})]})]}):e.jsxs(e.Fragment,{children:[e.jsx(n,{variant:"body2",fontWeight:500,children:"Valores das parcelas não coincidem c
8om o total do pedido"}),e.jsxs(h,{direction:"row",spacing:2,sx:{fontSize:"0.875rem"},children:[e.jsxs(n,{variant:"caption",color:"text.secondary",children:["Pedido:"," ",r.orderTotal.toLocaleString("pt-BR",{style:"currency",currency:"BRL"})]}),e.jsxs(n,{variant:"caption",color:"text.secondary",children:["Parcelas:"," ",r.installmentTotal.toLocaleString("pt-BR",{style:"currency",currency:"BRL"})]})]})]})})()})})})(),re&&e.jsx(Qe,{severity:"info",sx:{borderRadius:2,".MuiAlert-message":{width:"100%"}},action:e.jsx(ee,{color:"info",size:"small",onClick:F,disabled:C,startIcon:e.jsx(Kn,{}),sx:{textTransform:"none",fontWeight:500,minWidth:"auto"},children:C?"Corrigindo...":"Corrigir"}),children:e.jsx(h,{spacing:1,children:(()=>{const r=(l==null?void 0:l.condicao_pagamento)||"a_vista";if(r==="a_vista"||r==="fiado"){const R=D();return e.jsxs(e.Fragment,{children:[e.jsx(n,{variant:"body2",fontWeight:500,children:"Foi pago a mais neste pedido"}),e.jsxs(h,{direction:"row",spacing:2,sx:{fontSize:"0.875rem"},children:[e.jsxs(n,{variant:"caption",color:"text.secondary",children:["Valor do pedido:"," ",R.toLocaleString("pt-BR",{style:"currency",currency:"BRL"})]}),e.jsxs(n,{variant:"caption",color:"text.secondary",children:["Total pago:"," ",X.toLocaleString("pt-BR",{style:"currency",currency:"BRL"})]}),e.jsxs(n,{variant:"caption",color:"info.main",fontWeight:500,children:["Excesso:"," ",N.toLocaleString("pt-BR",{style:"currency",currency:"BRL"})]})]})]})}return e.jsxs(e.Fragment,{children:[e.jsx(n,{variant:"body2",fontWeight:500,children:O.length===1?`Parcela #${O[0].numero_parcela} foi paga a mais`:`${O.length} parcelas foram pagas a mais`}),e.jsxs(h,{direction:"column",spacing:.5,children:[O.map(R=>{const q=Be((R.pagamentos||[]).filter(G=>G.status==="pago").map(G=>G.valor)),ne=Ct(q,R.valor_original);return e.jsxs(h,{direction:"row",spacing:2,sx:{fontSize:"0.875rem"},children:[e.jsxs(n,{variant:"caption",color:"text.secondary",children:["Parcela #",R.numero_parcela,":"]}),e.jsxs(n,{variant:"caption",color:"text.secondary",children:["Valor:"," ",R.valor_original.toLocaleString("pt-BR",{style:"currency",currency:"BRL"})]}),e.jsxs(n,{variant:"caption",color:"text.secondary",children:["Pago:"," ",q.toLocaleString("pt-BR",{style:"currency",currency:"BRL"})]}),e.jsxs(n,{variant:"caption",color:"info.main",fontWeight:500,children:["Excesso:"," ",ne.toLocaleString("pt-BR",{style:"currency",currency:"BRL"})]})]},R.id)}),O.length>1&&e.jsx(h,{direction:"row",spacing:2,sx:{fontSize:"0.875rem",pt:.5},children:e.jsxs(n,{variant:"caption",color:"info.main",fontWeight:600,children:["Total em excesso:"," ",N.toLocaleString("pt-BR",{style:"currency",currency:"BRL"})]})})]})]})})()})}),(()=>{const r=(l==null?void 0:l.condicao_pagamento)||"a_vista",x=D(),B=X,R=k,q=B-x;return B>0||r==="a_vista"&&R>0?e.jsx(j,{sx:{bgcolor:"grey.50",borderRadius:1,p:2},children:e.jsxs(h,{spacing:1,children:[B>0&&e.jsxs(h,{direction:"row",justifyContent:"space-between",children:[e.jsx(n,{variant:"body2",color:"text.secondary",children:"Total pago:"}),e.jsx(n,{variant:"body2",fontWeight:500,color:"success.main",children:B.toLocaleString("pt-BR",{style:"currency",currency:"BRL"})})]}),R>0&&r!=="a_vista"&&e.jsxs(h,{direction:"row",justifyContent:"space-between",children:[e.jsx(n,{variant:"body2",color:"text.secondary",children:"Restante:"}),e.jsx(n,{variant:"body2",fontWeight:500,color:"error.main",children:R.toLocaleString("pt-BR",{style:"currency",currency:"BRL"})})]}),q>.01&&e.jsxs(h,{direction:"row",justifyContent:"space-between",children:[e.jsx(n,{variant:"body2",color:"text.secondary",children:"Pago a mais:"}),e.jsx(n,{variant:"body2",fontWeight:500,color:"info.main",children:q.toLocaleString("pt-BR",{style:"currency",currency:"BRL"})})]}),r==="a_vista"&&R>0&&q<=.01&&e.jsxs(h,{direction:"row",justifyContent:"space-between",children:[e.jsx(n,{variant:"body2",color:"text.secondary",children:"Falta:"}),e.jsx(n,{variant:"body2",fontWeight:500,color:"error.main",children:R.toLocaleString("pt-BR",{style:"currency",currency:"BRL"})})]})]})}):null})(),P&&v.length>0?e.jsxs(e.Fragment,{children:[e.jsx(fe,{}),e.jsx(n,{variant:"subtitle2",fontWeight:500,color:"text.secondary",children:"Parcelas"}),e.jsx(qt,{sx:{p:0},children:v.map(r=>{const x=Be((r.pagamentos??[]).filter(I=>I.status==="pago").map(I=>I.valor)),B=Vt(r.valor_original,x),R=r.status_parcela==="paga",q=r.status_parcela==="cancelada",ne=r.status_parcela==="reembolsada",G=q||ne;return e.jsxs(j,{onClick:()=>{G||u(R?`/orders/${o}/payment/installments`:`/orders/${o}/payment/installment/${r.id}/payment`)},sx:{p:2,borderRadius:1,mb:1,bgcolor:"white",cursor:G?"default":"pointer",opacity:G?.6:1,"&:hover":G?{}:{bgcolor:"grey.50"}},children:[e.jsxs(h,{direction:"row",alignItems:"center",justifyContent:"space-between",sx:{mb:1},children:[e.jsxs(h,{direction:"row",alignItems:"center",spacing:1,children:[e.jsx(Xo,{sx:{width:24,height:24,bgcolor:G?"grey.400":R?"success.main":Me(new Date(r.data_vencimento)).isOverdue?"error.main":"warning.main"},children:R?e.jsx(or,{sx:{fontSize:16}}):e.jsx(rr,{sx:{fontSize:16}})}),e.jsxs(n,{variant:"body2",fontWeight:500,children:["Parcela #",r.numero_parcela]}),G&&e.jsx(n,{variant:"caption",sx:{bgcolor:"grey.200",px:1,py:.25,borderRadius:1,color:"grey.700",fontWeight:500,fontSize:"0.65rem"},children:Et(r.status_parcela)})]}),e.jsx(n,{variant:"body2",fontWeight:600,children:r.valor_original.toLocaleStr
8ing("pt-BR",{style:"currency",currency:"BRL"})})]}),e.jsxs(h,{direction:"row",alignItems:"center",justifyContent:"space-between",sx:{mb:r.pagamentos&&r.pagamentos.length>0?1:0},children:[e.jsxs(n,{variant:"caption",color:"text.secondary",sx:{fontSize:"0.75rem"},children:[Ue(new Date(r.data_vencimento),"dd/MM/yyyy",{locale:Gt}),!R&&(()=>{const I=Me(new Date(r.data_vencimento));let W="";return I.relativeText&&(W+=` (${I.relativeText})`),W})()]}),!R&&!G&&pt(B)>0&&e.jsxs(n,{variant:"caption",color:Me(new Date(r.data_vencimento)).isOverdue?"error.main":"warning.main",fontWeight:500,sx:{fontSize:"0.75rem"},children:[Me(new Date(r.data_vencimento)).isOverdue?"Atrasado":"Pendente",":"," ",B.toLocaleString("pt-BR",{style:"currency",currency:"BRL"})]})]}),r.pagamentos&&r.pagamentos.length>0&&e.jsx(h,{spacing:.75,children:r.pagamentos.map((I,W)=>{var Se,Ae,je,he,be,Re;const ie=((Se=I.forma_pagamento)==null?void 0:Se.codigo_padrao)==="asaas",xe=((Ae=I.forma_pagamento)==null?void 0:Ae.codigo_padrao)==="asaas_direct",ae=ie||xe,me=((je=I.forma_pagamento)==null?void 0:je.codigo_padrao)==="pix",ke=I.status==="pago"||!I.status&&r.status_parcela==="paga";return e.jsxs(h,{direction:"row",alignItems:"center",justifyContent:"space-between",sx:{pl:1},children:[e.jsxs(h,{direction:"row",alignItems:"center",spacing:1,sx:{flex:1,minWidth:0},children:[e.jsx(no,{codigoPadrao:(he=I.forma_pagamento)==null?void 0:he.codigo_padrao,icone:(be=I.forma_pagamento)==null?void 0:be.icone,size:16}),e.jsx(n,{variant:"caption",color:"text.secondary",sx:{fontSize:"0.75rem"},children:((Re=I.forma_pagamento)==null?void 0:Re.nome)||"Forma não identificada"}),ie&&I.asaas_payment_id&&e.jsx(sr,{paymentId:I.asaas_payment_id}),(ae||me)&&!ke&&e.jsx(n,{variant:"caption",color:"warning.main",fontWeight:500,sx:{fontSize:"0.7rem"},children:"Aguardando pagamento"})]}),e.jsx(n,{variant:"caption",fontWeight:500,color:ke?"success.main":"text.secondary",sx:{fontSize:"0.75rem"},children:I.valor.toLocaleString("pt-BR",{style:"currency",currency:"BRL"})})]},`${I.id}-${W}`)})})]},r.id)})})]}):S&&v.length>0?e.jsxs(e.Fragment,{children:[e.jsx(fe,{}),e.jsx(n,{variant:"subtitle2",fontWeight:500,color:"text.secondary",children:"Fiado"}),e.jsx(qt,{sx:{p:0},children:v.map(r=>{const x=Be((r.pagamentos??[]).filter(I=>I.status==="pago").map(I=>I.valor)),B=Vt(r.valor_original,x),R=r.status_parcela==="paga",q=r.status_parcela==="cancelada",ne=r.status_parcela==="reembolsada",G=q||ne;return e.jsxs(Jt,{disabled:G,onClick:()=>{G||u(R?`/orders/${o}/payment/fiado/view`:`/orders/${o}/payment/installment/${r.id}/payment`)},sx:{py:1,px:2,borderRadius:1,mb:1,bgcolor:"white"},children:[e.jsx(oe,{sx:{minWidth:40},children:e.jsx(Xo,{sx:{width:32,height:32,bgcolor:G?"grey.400":R?"success.main":Me(new Date(r.data_vencimento)).isOverdue?"error.main":"warning.main"},children:R?e.jsx(or,{fontSize:"small"}):e.jsx(rr,{fontSize:"small"})})}),e.jsx(Y,{primary:e.jsxs(h,{direction:"row",alignItems:"center",spacing:1,children:[e.jsx(n,{variant:"body2",fontWeight:500,children:"Pagamento fiado"}),G&&e.jsx(n,{variant:"caption",sx:{bgcolor:"grey.200",px:1,py:.25,borderRadius:1,color:"grey.700",fontWeight:500},children:Et(r.status_parcela)})]}),secondary:e.jsxs(h,{spacing:.5,children:[e.jsxs(n,{variant:"caption",color:"text.secondary",children:["Venc:"," ",Ue(new Date(r.data_vencimento),"dd/MM/yyyy",{locale:Gt}),!R&&(()=>{const I=Me(new Date(r.data_vencimento));let W="";return I.relativeText&&(W+=` (${I.relativeText})`),W})()]}),!R&&!G&&pt(B)>0&&e.jsxs(n,{variant:"caption",color:Me(new Date(r.data_vencimento)).isOverdue?"error.main":"warning.main",fontWeight:500,children:[Me(new Date(r.data_vencimento)).isOverdue?"Atrasado":"Pendente",":"," ",B.toLocaleString("pt-BR",{style:"currency",currency:"BRL"})]})]})}),e.jsxs(j,{children:[e.jsx(n,{variant:"body2",fontWeight:600,children:r.valor_original.toLocaleString("pt-BR",{style:"currency",currency:"BRL"})}),x>0&&e.jsxs(n,{variant:"caption",color:"success.main",fontWeight:500,children:["Pago:"," ",x.toLocaleString("pt-BR",{style:"currency",currency:"BRL"})]})]})]},r.id)})})]}):M.length>0&&e.jsxs(e.Fragment,{children:[e.jsx(fe,{}),e.jsx(n,{variant:"subtitle2",fontWeight:500,color:"text.secondary",children:"Formas de pagamento"}),e.jsx(qt,{sx:{p:0},children:M.map((r,x)=>{var Se,Ae,je,he,be,Re,Ze,Ee;const B=((Se=r.forma_pagamento)==null?void 0:Se.codigo_padrao)==="mercadopago",R=((Ae=r.forma_pagamento)==null?void 0:Ae.codigo_padrao)==="pagaleve",q=((je=r.forma_pagamento)==null?void 0:je.codigo_padrao)==="asaas",ne=((he=r.forma_pagamento)==null?void 0:he.codigo_padrao)==="asaas_direct",G=q||ne,I=((be=r.forma_pagamento)==null?void 0:be.codigo_padrao)==="pix",W=v.find(ge=>{var De;return(De=ge.pagamentos)==null?void 0:De.some(Oe=>Oe.id===r.id)}),ie=(W==null?void 0:W.status_parcela)==="paga",xe=(W==null?void 0:W.status_parcela)==="cancelada",ae=(W==null?void 0:W.status_parcela)==="reembolsada",me=xe||ae,ke=B&&ie&&!r.mercadopago_payment_id||R&&ie&&!r.pagaleve_payment_id||G&&ie&&!r.asaas_payment_id;return e.jsxs(Jt,{disabled:me,onClick:()=>{me||(q?u(`/orders/${o}/payment/stoqui-pay/${r.id}`):ne?u(`/orders/${o}/payment/asaas-direct/${r.id}`):B?u(`/orders/${o}/payment/mercadopago/${r.id}`):R?u(`/orders/${o}/payment/pagaleve/${r.id}`):I&&u(`/orders/${o}/payment/pix/${r.id}`))},sx:{p:1},children:[e.jsx(oe,{sx:{minWidth:36}
8,children:e.jsx(no,{codigoPadrao:(Re=r.forma_pagamento)==null?void 0:Re.codigo_padrao,icone:(Ze=r.forma_pagamento)==null?void 0:Ze.icone,size:20})}),e.jsx(Y,{primary:e.jsxs(h,{direction:"row",justifyContent:"space-between",alignItems:"center",children:[e.jsxs(h,{direction:"row",alignItems:"center",spacing:1,children:[e.jsx(n,{variant:"body2",fontWeight:500,color:me?"text.disabled":"text.primary",children:((Ee=r.forma_pagamento)==null?void 0:Ee.nome)||"Forma não identificada"}),me&&e.jsx(n,{variant:"caption",sx:{bgcolor:"grey.200",px:1,py:.25,borderRadius:1,color:"grey.700",fontWeight:500},children:"Cancelado"})]}),e.jsx(n,{variant:"body2",fontWeight:600,color:me?"text.disabled":"text.primary",children:r.valor.toLocaleString("pt-BR",{style:"currency",currency:"BRL"})})]}),secondary:e.jsxs(h,{spacing:.5,children:[e.jsx(n,{variant:"caption",color:me?"text.disabled":"text.secondary",children:Ue(new Date(r.data_pagamento),"dd/MM/yyyy 'às' HH:mm",{locale:Gt})}),(B||R||G||I)&&!me&&e.jsx(n,{variant:"caption",color:r.status==="pago"||!r.status&&ie?"success.main":"warning.main",fontWeight:500,children:r.status==="pago"||!r.status&&ie?ke?"Confirmado manualmente":"Pagamento confirmado":"Aguardando pagamento"}),r.chave_pix&&!me&&e.jsxs(h,{direction:"row",alignItems:"center",spacing:1,children:[Gn(r.chave_pix.banco,16),e.jsx(n,{variant:"caption",color:"text.secondary",sx:{fontSize:"0.75rem"},children:r.chave_pix.valor_chave})]}),q&&r.asaas_payment_id&&e.jsx(sr,{paymentId:r.asaas_payment_id})]})})]},`${r.id}-${x}`)})})]})]})})}const wa="CERTIFICADO_REENVIO_NECESSARIO",Dr=o=>{var i,d,u;return((i=o==null?void 0:o.response)==null?void 0:i.status)===409&&((u=(d=o==null?void 0:o.response)==null?void 0:d.data)==null?void 0:u.code)===wa},cr={pendente:{backgroundColor:"#EEF4FF",color:"#2D6FE5"},autorizado:{backgroundColor:"#D1FAE5",color:"#065F46"},rejeitado:{backgroundColor:"#FEE2E2",color:"#991B1B"},cancelado:{backgroundColor:"#F3F4F6",color:"#374151"},erro:{backgroundColor:"#FEE2E2",color:"#991B1B"}},Sa={pendente:"Processando",autorizado:"Autorizada",rejeitado:"Rejeitada",cancelado:"Cancelada",erro:"Erro"},Kt={nfe:"NF-e",nfce:"NFC-e"},lr=Ke.isNativePlatform(),Ra=12e4,so=o=>o.status==="pendente",Ea=o=>{const i=Ye(),d=Tt({queryKey:["notas-fiscais",o],queryFn:async()=>{const{data:u}=await ot.get(`/fiscal/notas?pedido_id=${o}`);return u.data||[]}});return y.useEffect(()=>{if(!o)return;const u=_e.channel(`notas-fiscais-${o}`).on("postgres_changes",{event:"*",schema:"public",table:"nota_fiscal",filter:`pedido_id=eq.${o}`},()=>{i.invalidateQueries({queryKey:["notas-fiscais",o]})}).subscribe();return()=>{_e.removeChannel(u)}},[o,i]),d},Da=()=>{const o=Ye();return At({mutationFn:async({pedidoId:i,tipo:d})=>{const{data:u}=await ot.post("/fiscal/emitir",{pedido_id:i,tipo:d});return u},onSuccess:(i,{pedidoId:d})=>{o.invalidateQueries({queryKey:["notas-fiscais",d]})}})},Fa=()=>{const o=Ye();return At({mutationFn:async({nfId:i})=>{const{data:d}=await ot.delete(`/fiscal/nota/${i}`);return d},onSuccess:(i,{pedidoId:d})=>{o.invalidateQueries({queryKey:["notas-fiscais",d]})}})},dr=({nf:o,pedidoId:i,processamentoDemorado:d,onErro:u,onCertificadoBloqueado:f})=>{const C=Fa(),[c,g]=y.useState(!1),[s,_]=y.useState(null),[l,T]=y.useState(null),z=cr[o.status]||cr.erro,H=ea(o),b=()=>ta(o),w=`Nota fiscal ${Kt[o.tipo]||o.tipo.toUpperCase()} #${o.numero}`,U=async()=>{T("pdf");try{const{blob:a,fileName:F}=await b();await wt(a,F,{title:w,dialogTitle:"Salvar ou compartilhar a DANFE"})}catch(a){if(St(a))return;console.error("Error downloading PDF:",a),u==null||u("Não foi possível baixar a DANFE. Tente novamente.")}finally{T(null)}},D=async()=>{T("xml");try{const a=await ot.get(`/fiscal/nota/${o.id}/xml`,{responseType:"blob"});await wt(new Blob([a.data],{type:"application/xml"}),`${H}.xml`,{title:w,dialogTitle:"Salvar ou compartilhar o XML"})}catch(a){if(St(a))return;console.error("Error downloading XML:",a),u==null||u("Não foi possível baixar o XML. Tente novamente.")}finally{T(null)}},Q=async()=>{T("print");try{const{blob:a,fileName:F}=await b();if(lr){await wt(a,F,{title:w,dialogTitle:"Imprimir ou compartilhar a DANFE"});return}const A=window.URL.createObjectURL(a),P=window.open(A);P&&P.addEventListener("load",()=>{P.print()}),window.setTimeout(()=>window.URL.revokeObjectURL(A),6e4)}catch(a){if(St(a))return;console.error("Error printing NF:",a),u==null||u("Não foi possível abrir a DANFE. Tente novamente.")}finally{T(null)}},E=async()=>{T("share");try{const{blob:a,contentType:F,fileName:A}=await b();if(!lr&&navigator.share&&navigator.canShare){const P=new File([a],A,{type:F});if(navigator.canShare({files:[P]})){await navigator.share({title:w,files:[P]});return}}await wt(a,A,{title:w,dialogTitle:"Compartilhar nota fiscal"})}catch(a){St(a)||console.error("Error sharing NF:",a)}finally{T(null)}},Z=async()=>{var a,F;g(!1),_(null);try{await C.mutateAsync({nfId:o.id,pedidoId:i})}catch(A){if(console.error("Error cancelling NF:",A),Dr(A)){f==null||f();return}u==null||u(((F=(a=A==null?void 0:A.response)==null?void 0:a.data)==null?void 0:F.error)||"Não foi possível cancelar a nota fiscal. Tente novamente.")}};return e.jsxs(e.Fragment,{children:[e.jsxs(h,{direction:"row",alignItems:"center",spacing:1.5,children:[e.jsxs(j,{sx:{flex:1},children:[e.jsxs(h,{direction:"row",alignItems:"center",spacing:1,children:[e.jsxs(n,{variant:"body2",fontWeight:600,children:[Kt[o.tipo]||o.tipo.toUpperCase(),o.numero?` #${o.numero}`:""]}),e.jsx(ht,{label:Sa[o.status]||o.status,size:"small",sx:{height:22,fontSize:"0.7rem",fontWeight:600,...z}})]}),e.jsxs(n,{variant:"caption",color:"text.secondary",children:[new Date(o.data_emissao).toLocaleDateString("pt-BR")," ·"," ",Number(o.valor_total).toLocaleStr
8ing("pt-BR",{style:"currency",currency:"BRL"}),o.configuracao_fiscal&&e.jsxs(e.Fragment,{children:[" · ",o.configuracao_fiscal.nome_razao_social]})]}),o.motivo_rejeicao&&!so(o)&&e.jsx(n,{variant:"caption",color:"error.main",display:"block",children:o.motivo_rejeicao})]}),o.status==="autorizado"&&e.jsxs(h,{direction:"row",sx:{flexShrink:0},children:[e.jsx(ce,{onClick:Q,disabled:!!l,children:e.jsx(Dt,{})}),e.jsx(ce,{onClick:E,disabled:!!l,children:e.jsx(Cr,{})}),e.jsx(ce,{onClick:a=>_(a.currentTarget),disabled:!!l,children:e.jsx(Jn,{})})]})]}),so(o)&&e.jsx(dn,{severity:"info",icon:d?void 0:e.jsx(Ar,{size:16,thickness:5,color:"inherit"}),sx:{mt:1.5},children:d?"A SEFAZ está demorando mais que o normal. Você pode continuar usando o sistema, a nota será atualizada automaticamente.":"Estamos processando sua nota fiscal na SEFAZ. Isso costuma levar alguns segundos e atualiza sozinho."}),e.jsxs(lo,{anchorEl:s,open:!!s,onClose:()=>_(null),children:[e.jsxs(K,{onClick:()=>{_(null),U()},children:[e.jsx(oe,{children:e.jsx(un,{fontSize:"small"})}),e.jsx(Y,{children:"Baixar PDF"})]}),e.jsxs(K,{onClick:()=>{_(null),D()},children:[e.jsx(oe,{children:e.jsx(Yn,{fontSize:"small"})}),e.jsx(Y,{children:"Baixar XML"})]}),e.jsxs(K,{onClick:()=>{_(null),g(!0)},sx:{color:"error.main"},children:[e.jsx(oe,{sx:{color:"inherit"},children:e.jsx(Zn,{fontSize:"small"})}),e.jsx(Y,{children:"Cancelar nota"})]})]}),e.jsxs(Ie,{open:c,onClose:()=>g(!1),children:[e.jsx(We,{children:"Cancelar nota fiscal"}),e.jsx(Ne,{children:e.jsxs(Rt,{children:["A ",Kt[o.tipo]||o.tipo.toUpperCase()," #",o.numero," será cancelada junto à SEFAZ. Esta ação não pode ser desfeita."]})}),e.jsxs(Xe,{children:[e.jsx(ee,{onClick:()=>g(!1),children:"Manter nota"}),e.jsx(ee,{onClick:Z,color:"error",disabled:C.isPending,children:"Sim, cancelar"})]})]})]})},ur={autorizado:0,pendente:1,rejeitado:2,erro:3,cancelado:4},La=({pedidoId:o,clienteId:i,clienteCpfCnpj:d,orderHasAddress:u})=>{var re,r;const[f,C]=y.useState(!1),{data:c,isLoading:g}=Ea(o),{data:s}=ra(),{data:_}=zt(i),l=Da(),[T,z]=y.useState(null),[H,b]=y.useState(!1),[w,U]=y.useState(!1),D=(c==null?void 0:c.some(so))??!1,Q=(s==null?void 0:s.formData.nfe_habilitado)??!1,E=(s==null?void 0:s.formData.nfce_habilitado)??!1,Z=Q?"nfe":"nfce",a=Q&&E,F=!d,A=!u&&((_==null?void 0:_.length)??0)===0,[P,S]=y.useState(null),v=P??Z;y.useEffect(()=>{if(!D){C(!1);return}const x=setTimeout(()=>C(!0),Ra);return()=>clearTimeout(x)},[D]),y.useEffect(()=>{(s==null?void 0:s.precisaEnviarCertificado)===!1&&b(!1)},[s==null?void 0:s.precisaEnviarCertificado]);const{primaryNf:m,historyNotas:X}=y.useMemo(()=>{if(!c||c.length===0)return{primaryNf:null,historyNotas:[]};const x=[...c].sort((B,R)=>(ur[B.status]??9)-(ur[R.status]??9));return{primaryNf:x[0],historyNotas:x.slice(1)}},[c]);if(!s||!Q&&!E)return null;const k=async x=>{var B,R;try{z(null),b(!1),await l.mutateAsync({pedidoId:o,tipo:x})}catch(q){if(Dr(q)){b(!0);return}z(((R=(B=q.response)==null?void 0:B.data)==null?void 0:R.error)||"Erro ao emitir nota fiscal")}},M=(m==null?void 0:m.status)==="pendente"||(m==null?void 0:m.status)==="autorizado",t=H||!!s.precisaEnviarCertificado&&!M,O=[];F&&O.push("Adicione o CPF/CNPJ do cliente para emitir a NF-e."),A&&O.push("Adicione um endereço de entrega ao pedido ou ao cliente para emitir a NF-e.");const N=O.length>0&&v==="nfe";return e.jsxs(j,{children:[e.jsx(h,{direction:"row",justifyContent:"space-between",alignItems:"center",sx:{mb:1.5},children:e.jsx(n,{variant:"h6",fontWeight:600,color:"text.primary",children:"Nota fiscal"})}),e.jsx(j,{sx:{backgroundColor:"white",borderRadius:2,boxShadow:"none",p:2},children:g?e.jsx(j,{display:"flex",justifyContent:"center",py:2,children:e.jsx(Ar,{size:24})}):e.jsxs(h,{spacing:0,children:[m&&e.jsx(dr,{nf:m,pedidoId:o,processamentoDemorado:f,onErro:z,onCertificadoBloqueado:()=>b(!0)}),X.length>0&&e.jsxs(j,{sx:{mt:1.5},children:[e.jsx(ee,{size:"small",onClick:()=>U(!w),sx:{textTransform:"none",color:"text.secondary",fontWeight:500,fontSize:"0.75rem",p:0,minWidth:0,"&:hover":{backgroundColor:"transparent"}},children:w?"Ocultar histórico":`Ver histórico (${X.length})`}),e.jsx(Qr,{in:w,children:e.jsx(h,{spacing:1.5,divider:e.jsx(j,{sx:{borderBottom:"1px solid",borderColor:"divider"}}),sx:{mt:1.5},children:X.map(x=>e.jsx(j,{sx:{opacity:.6},children:e.jsx(dr,{nf:x,pedidoId:o,processamentoDemorado:f,onErro:z,onCertificadoBloqueado:()=>b(!0)})},x.id))})})]}),t&&e.jsx(oa,{variant:"emissao",primeiroEnvio:!((re=s.certificado)!=null&&re.validade)&&!((r=s.certificado)!=null&&r.serial),sx:{mt:2}}),T&&!t&&e.jsx(Qe,{severity:"error",onClose:()=>z(null),sx:{mt:2},children:T}),!M&&(m?e.jsxs(j,{sx:{mt:2,pt:2,borderTop:"1px solid",borderColor:"divider"},children:[e.jsxs(h,{direction:"row",spacing:1,alignItems:"center",children:[a&&e.jsxs(Yt,{size:"small",value:v,onCh
8ange:x=>S(x.target.value),sx:{width:120,height:36},children:[e.jsx(K,{value:"nfe",children:"NF-e"}),e.jsx(K,{value:"nfce",children:"NFC-e"})]}),e.jsxs(Ft,{variant:"contained",fullWidth:!0,loading:l.isPending,disabled:N,onClick:()=>k(v),sx:{textTransform:"none",fontWeight:500,height:36},children:["Emitir"," ",a?"nota fiscal":v==="nfe"?"NF-e":"NFC-e"]})]}),N&&e.jsx(h,{spacing:.5,sx:{mt:1.5},children:O.map(x=>e.jsx(n,{variant:"caption",sx:{display:"block",px:1.5,py:.75,borderRadius:1,backgroundColor:"#FEF3C7",color:"#92400E"},children:x},x))})]}):e.jsxs(h,{spacing:1.5,alignItems:"center",sx:{py:1.5},children:[e.jsx(ln,{sx:{fontSize:32,color:"rgba(0, 0, 0, 0.18)"}}),e.jsx(n,{variant:"body2",color:"text.secondary",textAlign:"center",children:"Nenhuma nota fiscal emitida"}),e.jsxs(h,{direction:"row",spacing:1,alignItems:"center",sx:{pt:.5},children:[a&&e.jsxs(Yt,{size:"small",value:v,onChange:x=>S(x.target.value),sx:{width:120,height:36},children:[e.jsx(K,{value:"nfe",children:"NF-e"}),e.jsx(K,{value:"nfce",children:"NFC-e"})]}),e.jsxs(Ft,{variant:"contained",loading:l.isPending,disabled:N,onClick:()=>k(v),sx:{textTransform:"none",fontWeight:500,height:36},children:["Emitir"," ",a?"nota fiscal":v==="nfe"?"NF-e":"NFC-e"]})]}),N&&e.jsx(h,{spacing:.5,sx:{width:"100%"},children:O.map(x=>e.jsx(n,{variant:"caption",sx:{px:1.5,py:.75,borderRadius:1,backgroundColor:"#FEF3C7",color:"#92400E",textAlign:"center"},children:x},x))})]}))]})})]})},ka=o=>{const[i,d]=y.useState(!1),[u,f]=y.useState(null),[C,c]=y.useState(""),g=Ke.isNativePlatform(),{data:s}=qe(o),{data:_}=Je(),{data:l}=jt(o),{data:T}=rt(),{data:z}=zt(s==null?void 0:s.cliente_id),{storeUrl:H}=Ot(),{data:b}=kt(),w=ft(T),D=po(b==null?void 0:b.configuracao_impressao).tamanho_impressao_termica_usb,Q=D==="desativado"?"80mm":D,E=()=>{const a=Ue(new Date,"yyyy-MM-dd_HH-mm-ss");return`comprovante-termico-stoqui_${(s==null?void 0:s.numero_pedido)||(s==null?void 0:s.pedido_id)||o}_${a}.pdf`};return{isGenerating:i,error:u,progress:C,isMobile:g,generateAndPrintThermalPDF:async()=>{var a,F,A;d(!0),f(null),c("Preparando comprovante térmico...");try{const[{pdf:P},{default:S}]=await Promise.all([Pe(()=>import("./react-pdf.browser-1EhQzxMi.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9])),Pe(()=>import("./VectorizedPrintThermalReceipt-DV9mnvng.js"),__vite__mapDeps([12,3,1,0,2,4,5,6,7,8,9]))]),v=E(),m=(_==null?void 0:_.nome_loja)||"Stoqui",X=((a=s==null?void 0:s.frete_pedido)==null?void 0:a.tipo_frete)==="retirada"&&z&&z.length>0?z[0]:null;c("Gerando PDF...");const M=await P(e.jsx(S,{order:s,storeName:m,storeUrl:w?H:void 0,paymentData:l,customerAddress:X,size:Q})).toBlob();if(g){c("Preparando para compartilhar...");const t=new FileReader,O=await new Promise(re=>{t.onloadend=()=>{const r=t.result.split(",")[1];re(r)},t.readAsDataURL(M)});await Ce.writeFile({path:v,data:O,directory:we.Cache,recursive:!0});const N=await Ce.getUri({directory:we.Cache,path:v});await mt.share({title:"Comprovante térmico",text:"Comprovante térmico PDF gerado",url:N.uri,dialogTitle:"Compartilhar PDF"})}else{const t=URL.createObjectURL(M),O=window.open(t,"_blank");if(O)O.onload=()=>{O.print(),setTimeout(()=>{URL.revokeObjectURL(t)},1e3)};else{const N=document.createElement("a");N.href=t,N.download=v,document.body.appendChild(N),N.click(),document.body.removeChild(N),URL.revokeObjectURL(t)}}c("Concluído!")}catch(P){P!=null&&P.message&&!((A=(F=P==null?void 0:P.message)==null?void 0:F.toLowerCase())!=null&&A.includes("cancel"))&&(f("Ocorreu um erro ao gerar o PDF. Por favor, tente novamente."),console.error("Error generating thermal PDF:",P))}finally{d(!1),c("")}},setError:f}},Oa=o=>{if(!o)return null;try{const i=document.createElement("canvas");na(i,o,{format:"CODE128",width:2,height:50,displayValue:!0,fontSize:14,background:"#ffffff",lineColor:"#000000",margin:4});const d=i.toDataURL("image/jpeg",.95);return i.remove(),d}catch(i){return console.warn("Failed to generate barcode:",i),null}},Ta=o=>{var w;const[i,d]=y.useState(!1),[u,f]=y.useState(null),[C,c]=y.useState(""),g=Ke.isNativePlatform(),{data:s}=qe(o),{data:_}=Lt(),{data:l}=Je(),{data:T}=kt(),z=((w=T==null?void 0:T.configuracao_impressao)==null?void 0:w.tamanho_etiqueta_envio)??pn.tamanho_etiqueta_envio,H=()=>`etiqueta_entrega_pedido_${(s==null?void 0:s.numero_pedido)||(s==null?void 0:s.pedido_id)||o}.pdf`;return{isGenerating:i,error:u,progress:C,generateShippingLabelPDF:async()=>{var U,D,Q;d(!0),f(null),c("Preparando etiqueta...");try{const[{pdf:E},{default:Z}]=await Promise.all([Pe(()=>import("./react-pdf.browser-1EhQzxMi.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9])),Pe(()=>import("./VectorizedPrintLabel-CXd76K0r.js"),__vite__mapDeps([13,3,1,0,2,4,5,6,7,8,9]))]),a=H();c("Processando imagens...");let F=l;if(l!=null&&l.logo_url)if(eo(l.logo_url)){const m=await to(l.logo_url,300,78,.8);F={...l,processed_logo_url:m}}else F={...l,processed_logo_url:l.logo_url};const A=((U=s==null?void 0:s.endereco_entrega)==null?void 0:U.cep)||"",P=Oa(A);c("Gerando PDF...");const v=await E(e.jsx(Z,{order:s,storeAddress:_,webCatalog:F,size:z,barcodeDataUrl:P})).toBlob();if(g){c("Preparando para compartilhar...");const m=new FileReader,X=await new Promise(M=>{m.onloadend=()=>{const t=m.result.split(",")[1];M(t)}
8,m.readAsDataURL(v)});await Ce.writeFile({path:a,data:X,directory:we.Cache,recursive:!0});const k=await Ce.getUri({directory:we.Cache,path:a});await mt.share({title:"Etiqueta de entrega",text:"Etiqueta de entrega PDF",url:k.uri,dialogTitle:"Compartilhar etiqueta"})}else{const m=URL.createObjectURL(v),X=window.open(m,"_blank");if(X)X.onload=()=>{X.print(),setTimeout(()=>{URL.revokeObjectURL(m)},1e3)};else{const k=document.createElement("a");k.href=m,k.download=a,document.body.appendChild(k),k.click(),document.body.removeChild(k),URL.revokeObjectURL(m)}}c("Concluido!")}catch(E){E!=null&&E.message&&!((Q=(D=E==null?void 0:E.message)==null?void 0:D.toLowerCase())!=null&&Q.includes("cancel"))&&(f("Ocorreu um erro ao gerar a etiqueta. Por favor, tente novamente."),console.error("Error generating shipping label PDF:",E))}finally{d(!1),c("")}},setError:f,labelSize:z}},za=o=>{const[i,d]=y.useState(!1),[u,f]=y.useState(null),[C,c]=y.useState(""),g=Ke.isNativePlatform(),{data:s}=qe(o),{data:_}=Lt(),{data:l}=Je(),{user:T}=_r(),z=()=>`declaracao_conteudo_pedido_${(s==null?void 0:s.numero_pedido)||(s==null?void 0:s.pedido_id)||o}.pdf`;return{isGenerating:i,error:u,progress:C,generateContentDeclarationPDF:async()=>{var b,w,U;d(!0),f(null),c("Preparando declaração...");try{const[{pdf:D},{default:Q,prepareContentDeclarationData:E}]=await Promise.all([Pe(()=>import("./react-pdf.browser-1EhQzxMi.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9])),Pe(()=>import("./VectorizedPrintContentDeclaration-CsvSmyoR.js"),__vite__mapDeps([14,3,1,0,2,4,5,6,7,8,9]))]),Z=z();c("Gerando PDF...");const a=E(s,_,l,((b=T==null?void 0:T.user_metadata)==null?void 0:b.cpf_cnpj)||""),A=await D(e.jsx(Q,{data:a})).toBlob();if(g){c("Preparando para compartilhar...");const P=new FileReader,S=await new Promise(m=>{P.onloadend=()=>{const X=P.result.split(",")[1];m(X)},P.readAsDataURL(A)});await Ce.writeFile({path:Z,data:S,directory:we.Cache,recursive:!0});const v=await Ce.getUri({directory:we.Cache,path:Z});await mt.share({title:"Declaração de Conteúdo",text:"Declaração de Conteúdo PDF",url:v.uri,dialogTitle:"Compartilhar declaração"})}else{const P=URL.createObjectURL(A),S=window.open(P,"_blank");if(S)S.onload=()=>{S.print(),setTimeout(()=>{URL.revokeObjectURL(P)},1e3)};else{const v=document.createElement("a");v.href=P,v.download=Z,document.body.appendChild(v),v.click(),document.body.removeChild(v),URL.revokeObjectURL(P)}}c("Concluido!")}catch(D){D!=null&&D.message&&!((U=(w=D==null?void 0:D.message)==null?void 0:w.toLowerCase())!=null&&U.includes("cancel"))&&(f("Ocorreu um erro ao gerar a declaração. Por favor, tente novamente."),console.error("Error generating content declaration PDF:",D))}finally{d(!1),c("")}},setError:f}},Ba=({orderID:o,iconOnly:i=!1})=>{var tt,dt;const[d,u]=y.useState(null),[f,C]=y.useState(!1),[c,g]=y.useState(null),[s,_]=y.useState(!1),[l,T]=y.useState(!1),[z,H]=y.useState(!1),[b,w]=y.useState(!1),[U,D]=y.useState(de.isDeviceConnected()),[Q,E]=y.useState(!1),[Z,a]=y.useState(""),[F,A]=y.useState(void 0),P=xt(),{data:S,isLoading:v}=rt(),{data:m,isLoading:X}=Lt(),{data:k}=qe(o),{data:M}=jt(o),{data:t}=zt(k==null?void 0:k.cliente_id),{data:O}=mo(String(o),{enabled:!!((tt=k==null?void 0:k.frete_pedido)!=null&&tt.superfrete_etiqueta_id)}),{data:N}=Je(),{storeUrl:re}=Ot(),r=!!((dt=O==null?void 0:O.print)!=null&&dt.url&&(O.status==="released"||O.status==="posted"||O.status==="delivered")),x=(k==null?void 0:k.frete_pedido)&&k.frete_pedido.tipo_frete!=="retirada"&&k.endereco_entrega,{data:B}=kt(),R=po(B==null?void 0:B.configuracao_impressao),q=R.tamanho_impressao_termica_bluetooth,ne=R.tamanho_impressao_termica_usb,G=q!=="desativado",I=ne!=="desativado",W=ft(S),ie=hn(S,"lite"),{triggerPaywall:xe}=mn(),{isGenerating:ae,error:me,progress:ke,generateAndShareOrderPDF:Se,generateAndDownloadOrderPDF:Ae,setError:je}=Er(o),{isGenerating:he,error:be,progress:Re,generateAndPrintThermalPDF:Ze,setError:Ee}=ka(o),{isGenerating:ge,error:De,progress:Oe,generateShippingLabelPDF:yt,setError:_t}=Ta(o),{isGenerating:se,error:nt,progress:at,generateContentDeclarationPDF:Bt,setError:Mt}=za(o);y.useEffect(()=>{const L=de.subscribeToConnectionStatus(V=>{D(V.isConnected)});return()=>{L()}},[]);const it=L=>{u(L.currentTarget)},et=()=>{u(null)},st=async()=>{var L;if(!k){a("Dados do pedido não disponíveis"),A("error"),E(!0);return}
8if(Ke.isNativePlatform()&&!await er()){g("thermal"),T(!0);return}try{try{await de.initialize(!1)}catch(le){console.error("Failed to initialize Bluetooth:",le),a("Falha ao inicializar Bluetooth. Verifique as permissões."),A("error"),E(!0);return}const V=de.isDeviceConnected(),$=de.getCurrentDevice();if(console.log("Checking cached bluetooth connection status:",V),console.log("Current device:",$),!V){g("thermal"),_(!0),ue(pe.ORDER.PRINTER_SEARCH,{order_id:o,reason:"not_connected"});return}w(!0);try{if(console.log("Validating actual printer connection..."),!await de.validateConnection()){console.log("Validation failed: Printer is physically disconnected"),g("thermal"),_(!0),w(!1),ue(pe.ORDER.PRINTER_ERROR,{order_id:o,error_type:"physically_disconnected",device_name:($==null?void 0:$.name)||"unknown"});return}console.log("Validation successful: Printer is physically connected")}catch(le){throw console.error("Validation error:",le),ue(pe.ORDER.PRINTER_ERROR,{order_id:o,error_type:"validation_error",error_message:String(le)}),le}const te=(N==null?void 0:N.nome_loja)||"Stoqui",Fe=((L=k.frete_pedido)==null?void 0:L.tipo_frete)==="retirada"&&t&&t.length>0?t[0]:null;await de.printOrder({order:k,storeName:te,storeUrl:re,paymentData:M,customerAddress:Fe,paperSize:q!=="desativado"?q:void 0}),ue(pe.ORDER.PRINT_SUCCESS,{order_id:o,print_type:"thermal",device_name:($==null?void 0:$.name)||"unknown"}),a("Pedido enviado para impressão"),A("success"),E(!0),setTimeout(()=>{F==="success"&&E(!1)},2e3)}catch(V){console.error("Error printing order:",V);const $=String(V);$.includes("não conectada")||$.includes("desconectada")||$.includes("disconnected")||$.includes("connection")||$.includes("característica")?(g("thermal"),_(!0),ue(pe.ORDER.PRINTER_ERROR,{order_id:o,error_type:"connection_error",error_message:$})):(a(`Erro ao imprimir: ${V}`),A("error"),E(!0),ue(pe.ORDER.PRINT_ERROR,{order_id:o,print_type:"thermal",error_message:String(V)}))}finally{w(!1)}},ct=async()=>{if(!k){a("Dados do pedido não disponíveis"),A("error"),E(!0);return}if(Ke.isNativePlatform()&&!await er()){g("thermal-label"),T(!0);return}try{try{await de.initialize(!1)}catch(le){console.error("Failed to initialize Bluetooth:",le),a("Falha ao inicializar Bluetooth. Verifique as permissões."),A("error"),E(!0);return}const L=de.isDeviceConnected(),V=de.getCurrentDevice();if(console.log("Checking cached bluetooth connection status:",L),console.log("Current device:",V),!L){g("thermal-label"),_(!0),ue(pe.ORDER.PRINTER_SEARCH,{order_id:o,reason:"not_connected"});return}w(!0);try{if(console.log("Validating actual printer connection..."),!await de.validateConnection()){console.log("Validation failed: Printer is physically disconnected"),g("thermal-label"),_(!0),w(!1),ue(pe.ORDER.PRINTER_ERROR,{order_id:o,error_type:"physically_disconnected",device_name:(V==null?void 0:V.name)||"unknown"});return}console.log("Validation successful: Printer is physically connected")}catch(le){throw console.error("Validation error:",le),ue(pe.ORDER.PRINTER_ERROR,{order_id:o,error_type:"validation_error",error_message:String(le)}),le}const $=(m==null?void 0:m.nome_remetente)||(N==null?void 0:N.nome_loja)||"Stoqui",te=(m==null?void 0:m.ocultar_logo_etiqueta)===!0,Fe=m?{nome:$,logradouro:m.logradouro,numero:m.numero,complemento:m.complemento||"",bairro:m.bairro,localidade:m.localidade,uf:m.uf,cep:m.cep}:null;await de.printShippingLabel({order:k,storeName:$,storeAddress:Fe,hideLogo:te,paperSize:q!=="desativado"?q:void 0}),ue(pe.ORDER.PRINT_SUCCESS,{order_id:o,print_type:"thermal-label",device_name:(V==null?void 0:V.name)||"unknown"}),a("Etiqueta enviada para impressão"),A("success"),E(!0),setTimeout(()=>{F==="success"&&E(!1)},2e3)}catch(L){console.error("Error printing shipping label:",L);const V=String(L);V.includes("não conectada")||V.includes("desconectada")||V.includes("disconnected")||V.includes("connection")||V.includes("característica")?(g("thermal-label"),_(!0),ue(pe.ORDER.PRINTER_ERROR,{order_id:o,error_type:"connection_error",error_message:V})):(a(`Erro ao imprimir etiqueta: ${L}`),A("error"),E(!0),ue(pe.ORDER.PRINT_ERROR,{order_id:o,print_type:"thermal-label",error_message:String(L)}))}finally{w(!1)}},bt=()=>{var L;(L=O==null?void 0:O.print)!=null&&L.url&&(window.open(O.print.url,"_blank"),et())},Te=async L=>{if(et(),ue(pe.ORDER.PRINT_CLICK,{order_id:o,print_type:L}),L==="superfrete-label"){if(!ie){xe("superfrete_label",{pageAction:()=>P("/profile/paywall?initialPlan=lite"),source:"order_print_button"});return}bt();return}if(!W){xe(L==="thermal"||L==="thermalReceipt"?"print_thermal":L==="label"||L==="thermal-label"?"print_shipping_label":L==="content"?"print_declaracao":L==="vector-receipt"||L==="vector-download"?"order_receipt":"order_print",{pageAction:()=>P("/profile/paywall"),source:"order_print_button"});return}if(L==="vector-receipt"){Se();return}if(L==="vector-download"){Ae();return}if(L==="label"){if(W&&!m&&!X){g(L),C(!0);return}yt();return}if(L==="thermalReceipt"){Ze();return}if(L==="thermal"){st();return}if(L==="thermal-label"){if(W&&!m&&!X){g(L),C(!0);return}ct();return}if(L==="content"){if(W&&!m&&!X){g(L),C(!0);return}Bt();return}},vt=()=>{C(!1),g(null),P("/profile/shipping/address")},It=()=>{C(!1),c==="label"?yt():c==="content"?Bt():c==="thermal-label"&&ct(),g(null)},lt=async()=>{const L=c;ue(pe.ORDER.PRINTER_SEARCH,{order_id:o,reason:"permission_rationale_accepted"}),H(!0);try{const V=await de.initialize(!1);if(T(!1),!V){_(!0);return}await An(),L==="thermal"?st():L==="thermal-label"&&ct()}catch(V){console.error("Error initializing after permission rationale:",V),T(!1),_(!0)}finally{H(!1)}},Wt=()=>{T(!1),g(null)},Pt=async L=>{var V;if(console.log("Printer connected:",L),ue(pe.ORDER.PRINTER_CONNECTED,{order_id:o,device_name:L.name,device_id:L.deviceId}),ue(pe.ORDER.PRINTER_SELECTED,{order_id:o,device_name:L.name}),_(!1),c==="thermal"){g(null),w(!0);try{if(!await de.validateConnection())throw new Error("Não foi possível validar a conexão com a impressora");const te=(N==null?void 0:N.nome_loja)||"Stoqui",Fe=((V=k.frete_pedido)==null?void 0:V.tipo_frete)==="retirada"&&t&&t.length>0?t[0]:null;await de.printOrder({order:k,storeName:te,storeUrl:re,paymentData:M,customerAddress:Fe,paperSize:q!=="desativado"?q:void 0}
8),a("Pedido enviado para impressão"),A("success"),E(!0),setTimeout(()=>{F==="success"&&E(!1)},2e3)}catch($){console.error("Error printing after connection:",$);const te=String($);te.includes("não conectada")||te.includes("desconectada")||te.includes("disconnected")||te.includes("connection")||te.includes("característica")?(g("thermal"),_(!0)):(a(`Erro ao imprimir: ${$}`),A("error"),E(!0))}finally{w(!1)}}else if(c==="thermal-label"){g(null),w(!0);try{if(!await de.validateConnection())throw new Error("Não foi possível validar a conexão com a impressora");const te=(m==null?void 0:m.nome_remetente)||(N==null?void 0:N.nome_loja)||"Stoqui",Fe=(m==null?void 0:m.ocultar_logo_etiqueta)===!0,le=m?{nome:te,logradouro:m.logradouro,numero:m.numero,complemento:m.complemento||"",bairro:m.bairro,localidade:m.localidade,uf:m.uf,cep:m.cep}:null;await de.printShippingLabel({order:k,storeName:te,storeAddress:le,hideLogo:Fe,paperSize:q!=="desativado"?q:void 0}),a("Etiqueta enviada para impressão"),A("success"),E(!0),setTimeout(()=>{F==="success"&&E(!1)},2e3)}catch($){console.error("Error printing shipping label after connection:",$);const te=String($);te.includes("não conectada")||te.includes("desconectada")||te.includes("disconnected")||te.includes("connection")||te.includes("característica")?(g("thermal-label"),_(!0)):(a(`Erro ao imprimir etiqueta: ${$}`),A("error"),E(!0))}finally{w(!1)}}};return e.jsxs(e.Fragment,{children:[i?e.jsx(Xr,{title:"Imprimir",children:e.jsx(ce,{color:"inherit",onClick:it,disabled:b||ae||he||ge||se,size:"medium",children:e.jsx(Dt,{})})}):e.jsx(ee,{variant:"outlined",color:"primary",onClick:it,startIcon:e.jsx(Dt,{}),disabled:v||b||ae||he||ge||se,size:"small",children:b||ae||he||ge||se?ke||Re||Oe||at||"Aguarde...":"Imprimir"}),e.jsxs(lo,{anchorEl:d,open:!!d,onClose:et,children:[G&&e.jsxs(K,{onClick:()=>Te("thermal"),disabled:b||ae||he||ge||se,children:[e.jsx(oe,{children:e.jsx(Zo,{size:20,color:U?"#1976d2":"#bdbdbd"})}),e.jsxs(h,{direction:"row",spacing:1,alignItems:"center",justifyContent:"space-between",width:"100%",children:[e.jsx(Y,{primary:"Comprovante",secondary:"Impressora térmica Bluetooth"}),e.jsx(He,{fontSize:"0.75rem",variant:W?"cutout":"text"})]})]}),x&&(r?e.jsx(K,{onClick:()=>Te("superfrete-label"),disabled:b||ae||ge||se,children:e.jsxs(h,{direction:"row",alignItems:"center",spacing:1,flex:1,children:[e.jsx(oe,{children:e.jsx("img",{src:ro,alt:"SuperFrete",style:{width:20,height:20}})}),e.jsx(Y,{primary:"Etiqueta de entrega",secondary:"SuperFrete"}),e.jsx(gn,{fontSize:"0.75rem",variant:ie?"cutout":"text"})]})}):G?e.jsxs(K,{onClick:()=>Te("thermal-label"),disabled:b||ae||ge||se,children:[e.jsx(oe,{children:e.jsx(Zo,{size:20,color:U?"#1976d2":"#bdbdbd"})}),e.jsxs(h,{direction:"row",spacing:1,alignItems:"center",justifyContent:"space-between",width:"100%",children:[e.jsx(Y,{primary:"Etiqueta de entrega",secondary:"Impressora térmica Bluetooth"}),e.jsx(He,{fontSize:"0.75rem",variant:W?"cutout":"text"})]})]}):null),I&&e.jsxs(K,{onClick:()=>Te("thermalReceipt"),disabled:b||se||ae||he||ge,children:[e.jsx(oe,{children:e.jsx(xn,{size:20})}),e.jsxs(h,{direction:"row",spacing:1,alignItems:"center",justifyContent:"space-between",width:"100%",children:[e.jsx(Y,{primary:"Comprovante",secondary:"Impressora térmica USB"}),e.jsx(He,{fontSize:"0.75rem",variant:W?"cutout":"text"})]})]}),x&&!r&&e.jsxs(K,{onClick:()=>Te("label"),disabled:b||se||ae||he||ge,children:[e.jsx(oe,{children:e.jsx(Ht,{size:20})}),e.jsxs(h,{direction:"row",spacing:1,alignItems:"center",justifyContent:"space-between",width:"100%",children:[e.jsx(Y,{primary:"Etiqueta de entrega",secondary:"PDF"}),e.jsx(He,{fontSize:"0.75rem",variant:W?"cutout":"text"})]})]}),e.jsxs(K,{onClick:()=>Te("content"),disabled:b||se||ae||he||ge,children:[e.jsx(oe,{children:e.jsx(Ht,{size:20})}),e.jsxs(h,{direction:"row",spacing:1,alignItems:"center",justifyContent:"space-between",width:"100%",children:[e.jsx(Y,{primary:"Declaração de Conteúdo",secondary:"PDF"}),e.jsx(He,{fontSize:"0.75rem",variant:W?"cutout":"text"})]})]}),e.jsxs(K,{onClick:()=>Te("vector-receipt"),disabled:b||ae||he||ge||se,children:[e.jsx(oe,{children:e.jsx(Ht,{size:20})}),e.jsxs(h,{direction:"row",spacing:1,alignItems:"center",justifyContent:"space-between",width:"100%",children:[e.jsx(Y,{primary:"Comprovante",secondary:"PDF"}),e.jsx(He,{fontSize:"0.75rem",variant:W?"cutout":"text"})]})]}),e.jsx(fe,{}),e.jsxs(K,{onClick:()=>{et(),P("/profile/app-preferences")},children:[e.jsx(oe,{children:e.jsx(fn,{})}),e.jsx(Y,{primary:"Configurar impressora"})]})]}),e.jsxs(Ie,{open:!!me||!!be||!!De||!!nt,onClose:()=>{je(null),Ee(null),_t(null),Mt(null)},children:[e.jsx(We,{children:"Erro ao Gerar PDF"}),e.jsx(Ne,{children:me||be||De||nt}),e.jsx(Xe,{children:e.jsx(ee,{onClick:()=>{je(null),Ee(null),_t(null),Mt(null)},color:"primary",children:"Fechar"})})]}),e.jsxs(Ie,{open:f,onClose:()=>{C(!1),g(null)},PaperProps:{sx:{borderRadius:2,width:"90%",maxWidth:"400px"}},children:[e.jsx(We,{children:"Endereço da loja não configurado"}),e.jsx(Ne,{children:e.jsx(Rt,{children:"Você deseja configurar ou imprimir sem o endereço do remetente?"})}),e.jsxs(h,{direction:"column",spacing:1,justifyContent:"space-between",px:2,pt:1,pb:3,children:[e.jsx(ee,{onClick:It,color:"warning",variant:"contained",fullWidth:!0,children:"Continuar sem Endereço"}),e.jsx(ee,{onClick:vt,color:"primary",variant:"contained",fullWidth:!0,children:"Configurar endereço"})]})]}),e.jsx(aa,{open:l,onClose:Wt,onContinue:lt,loading:z}),e.jsx(ia,{open:s,onClose:()=>_(!1),onPrinterConnected:Pt}),e.jsx(Kr,{open:Q,autoHideDuration:5e3,onClose:()=>E(!1),sx:{mb:"var(--safe-area-inset-bottom)"},anchorOrigin:{vertical:"bottom",horizontal:"center"},children:e.jsx(Qe,{onClose:()=>E(!1),severity:F,variant:"filled",sx:{width:"100%"},children:Z})})]})},Ma=()=>{const o=Ye();return At({mutationFn:async i=>{const{data:d,error:u}=await _e.from("pedido").update({deletado_em:new Date().toISOString()}).eq("pedido_id",i).select("pedido_id, numero_pedido").single();if(u)throw new Error(u.message||"Erro ao excluir pedido");return d},onSuccess:i=>{ue(pe.DELETE.ORDER,{orderId:i.pedido_id,orderNumber:i.numero_pedido}),o.invalidateQueries({queryKey:["pedidos"]}),o.invalidateQueries({queryKey:["pedido"]}),o.invalidateQueries({queryKey:["newOrdersCount"]}),o.invalidateQueries({queryKey:["manual-orders-count"]}),o.invalidateQueries({queryKey:["report-metrics"]}),o.invalidateQueries({queryKey:["report-top-products"]}),o.invalidateQueries({queryKey:["report-top-customers"]})}})};var xo={},Ia=co;Object.defineProperty(xo,"__esModule",{value:!0});var Fr=xo.default=void 0,Wa=Ia(uo()),Na=e;Fr=xo.default=(0,Wa.default)((0,Na.jsx)("path",{d:"m3.5 18.49 6-6.01 4 4L22 6.92l-1.41-1.41-7.09 7.97-4-4L2 16.99z"}),"ShowChart");var fo={},Ua=co;Object.defineProperty(fo,"__esModule",{value:!0});var Lr=fo.default=void 0,qa=Ua(uo()),Va=e;Lr=fo.default=(0,qa.default)((0,Va.jsx)("path",{d:"M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2m0 18c-4.42 0-8-3.58-8-8 0-1.85.63-3.55 1.69-4.9L16.9 18.31C15.55 19.37 13.85 20 12 20m6.31-3.1L7.1 5.69C8.45 4.63 10.15 4 12 4c4.42 0 8 3.58 8 8 0 1.85-.63 3.55-1.69 4.9"}),"DoDisturbAlt");const Ge="#0fae79",Ga=({orderId:o,superfreteEtiquetaId:i})=>{const d=xt(),{data:u}=la(),{data:f,isLoading:C,isError:c}=mo(o,{enabled:!!i});if(C)return e.jsx(ye,{variant:"rounded",width:"100%",height:64});if(c||!f){const l=()=>{!u||!u.token?d("/profile/shipping/superfrete"):d(`/orders/${o}/superfrete-label`)};return e.jsx(j,{sx:{p:2,bgcolor:"grey.50",borderRadius:2,cursor:"pointer",transition:"all 0.2s ease","&:hover":{backgroundColor:"grey.100"}},onClick:l,children:e.jsxs(h,{direction:"row",spacing:2,alignItems:"center",children:[e.jsx(j,{sx:{width:40,height:40,display:"flex",alignItems:"center",justifyContent:"center",bgcolor:"white",borderRadius:1,flexShrink:0},children:e.jsx("img",{src:ro,alt:"SuperFrete",style:{width:28,height:28}})}),e.jsxs(j,{sx:{flex:1,minWidth:0},children:[e.jsx(h,{direction:"row",spacing:.5,alignItems:"center",children:e.jsx(n,{variant:"body2",fontWeight:700,sx:{color:Ge},children:"SuperFrete"})}),e.jsx(n,{variant:"caption",color:"text.secondary",children:"Emitir etiqueta com desconto"})]}),e.jsx(ao,{color:"action"})]})})}const s=(l=>
8{switch(l){case"pending":return{icon:e.jsx(Pr,{size:20,style:{color:Ge}}),title:"Aguardando pagamento",subtitle:"Complete o pagamento da etiqueta",chipLabel:"Pendente",chipStyles:{backgroundColor:"#FEF3C7",color:"#92400E"}};case"released":return{icon:e.jsx(Dt,{size:20,style:{color:Ge}}),title:"Etiqueta liberada",subtitle:f.tracking||"Pronta para impressão",chipLabel:"Paga",chipStyles:{backgroundColor:"#D1FAE5",color:"#065F46"}};case"posted":return{icon:e.jsx(gt,{style:{fontSize:20,color:Ge}}),title:"Pedido postado",subtitle:f.tracking||"Em trânsito",chipLabel:"Postada",chipStyles:{backgroundColor:"#DBEAFE",color:"#1E40AF"}};case"delivered":return{icon:e.jsx(jn,{sx:{fontSize:20,color:Ge}}),title:"Entregue",subtitle:f.tracking||"Pedido entregue",chipLabel:"Entregue",chipStyles:{backgroundColor:"#D1FAE5",color:"#065F46"}};case"canceled":return{icon:e.jsx(Lr,{sx:{fontSize:20,color:"text.disabled"}}),title:"Etiqueta cancelada",subtitle:"Crie uma nova etiqueta",chipLabel:"Cancelada",chipStyles:{backgroundColor:"#FEE2E2",color:"#991B1B"}};default:return{icon:e.jsx(gt,{style:{fontSize:20,color:Ge}}),title:"Etiqueta criada",subtitle:f.tracking||"Ver detalhes",chipLabel:l,chipStyles:{backgroundColor:"#F3F4F6",color:"#374151"}}}})(f.status),_=()=>{f.status==="canceled"?d(`/orders/${o}/superfrete-label`):d(`/orders/${o}/superfrete-label/${i}`)};return e.jsx(j,{sx:{p:2,bgcolor:"grey.50",borderRadius:2,cursor:"pointer",transition:"all 0.2s ease","&:hover":{backgroundColor:"grey.100"}},onClick:_,children:e.jsxs(h,{spacing:1.5,children:[e.jsxs(h,{direction:"row",justifyContent:"space-between",alignItems:"center",children:[e.jsxs(h,{direction:"row",spacing:.75,alignItems:"center",children:[e.jsx("img",{src:ro,alt:"SuperFrete",style:{width:16,height:16}}),e.jsx(n,{variant:"body2",fontWeight:700,sx:{color:Ge},children:"SuperFrete"})]}),e.jsx(ht,{label:s.chipLabel,size:"small",sx:{height:24,fontSize:"0.75rem",fontWeight:600,backgroundColor:s.chipStyles.backgroundColor,color:s.chipStyles.color,border:"none","& .MuiChip-label":{px:1.5}}})]}),e.jsxs(h,{direction:"row",spacing:2,alignItems:"center",children:[e.jsx(j,{sx:{width:40,height:40,display:"flex",alignItems:"center",justifyContent:"center",bgcolor:"white",borderRadius:1,flexShrink:0},children:s.icon}),e.jsxs(j,{sx:{flex:1,minWidth:0},children:[e.jsx(n,{variant:"body2",fontWeight:600,color:"text.primary",children:s.title}),e.jsx(n,{variant:"caption",color:"text.secondary",sx:{display:"block",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:s.subtitle})]}),e.jsx(ao,{color:"action"})]})]})})},Ha=o=>{const i=o.trim().toUpperCase();return/^[A-Z]{2}\d{9}[A-Z]{2}$/.test(i)?{name:"Correios",url:`https://rastreamento.correios.com.br/app/index.php?objeto=${i}`,detected:!0}:/^JT[A-Z0-9]{8,}$/.test(i)?{name:"J&T Express",url:`https://www.jtexpress.com.br/trajectoryQuery?waybillNo=${i}&type=0`,detected:!0}:/^\d{10,15}$/.test(i)?{name:"Jadlog",url:`https://www.jadlog.com.br/rastreamento/rastreamento.jad?cte=${i}`,detected:!0}:/^LOG[A-Z0-9-]{8,}$/i.test(i)?{name:"Loggi",url:`https://www.loggi.com/rastreamento/${i}`,detected:!0}:{name:"17track",url:`https://www.17track.net/pt/track?nums=${i}`,detected:!1}},$a=o=>{const i=o.trim();return/^[A-Za-z0-9\s-]{8,}$/.test(i)},Qa=async(o,i)=>{const{rastreio_codigo:d,rastreio_url:u,should_update_status:f}=i,{data:C}=await _e.from("frete_pedido").select("id").eq("pedido_id",o).single();if(C){const{error:c}=await _e.from("frete_pedido").update({rastreio_codigo:d,rastreio_url:u}).eq("pedido_id",o);if(c)throw c}else{const{error:c}=await _e.from("frete_pedido").insert({pedido_id:Number(o),rastreio_codigo:d,rastreio_url:u,tipo_frete:"a_combinar",valor_frete:0});if(c)throw c}if(f){const{error:c}=await _e.from("pedido").update({status_pedido:"shipped"}).eq("pedido_id",o);if(c)throw c}return{success:!0}},Xa=o=>{const i=Ye();return At({mutationFn:async d=>Qa(o,d),onSuccess:()=>{i.invalidateQueries({queryKey:["pedido",Number(o)]})}})},pr="/assets/correios-DFO7b07o.png",hr="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAHgAAAB4CAMAAAAOusbgAAABm1BMVEX///9BQELcADLMADNJSUpGRUfAADPFADPs7OxSUVP//f5qaWv99ffIADO7u7vTADLq6ur75+vfGEW5ADOrqquIh4lWVVdDQkT5+fnaADLVADLSADL29va/v8DZADL7+/vv7+/GxsaxsbGNjY5nZmf9/Pz++/x8e3xxcHJNTE6jo6PgQWZhYGLPADO8ADPh4OHg3+DT09PEw8S4t7inp6eZmJlbWltMS03fEkDc29zX19fLy8vyuMZ1dXbjQWbdCDjHADP75ev40tvQz9DuiqGfn6DoZILjSGxkY2TgI07OATT98PL86+/66Ozm5eb42N/2wc20tLTularsgZqUlJWQkJHqdY9/fn/bRWpdXF7+9/nz8/Pq6er64efi4uL2zdfyr76ura6cm53qcIyCgYPjXHzfQ2jjOWDLLFbhKlPfHkvYDDzCADPa2dnS0tO1tbbwo7WzsrPrnrHdZ4bnWHnjS27cN17iMlrWIEzbHEjLG0jBCzz23eTyvMnijqTkhZ3jepTfeJKMi4yFhIbVVXbiUHPaP2XYN17QEkExEifsAAAEFUlEQVRo3u3W93fSUBTA8fs
8oMyIuGoaEEdmi7FKWKJSC1tFaq3ZYO6xd7r33+rO9L0FKjgzxVNRz3ueHlqQ5fMlLbigwDMMwDMMwDMMwDM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K1f22JsZRP7DdoO4vh6V4r7j8BRVcVI+KCeiG08Jx3iIfpanLusxhnfEMsZ2z0ROx0z7JG684gbxSCP8rhJW+IBCbua2Fhr38UrezpiT7G3VTHo1Yb4PCdsK2KQ44RUxun7iLXfFGu3IR7mammeim1eRz2BDS3FTk/05aixLj7H4vFcfMQhKzGVU534WxUPsVpWxaad8LDAk/GuFJ8W4nv9HqNyI+GqGOW+hUW5dVXFTIzgS/HotOgr4t2csN8S50uEeqkBqmalVuvrPIH3z+JULSXuttjBMtdL9KJq2pX4FaOOcvADzWdxrpZ6S5x+fYMsvomqiRVNXMpRBndqLc7Vskc4cBeFcEIKAQsLkgENerv2Fq3e9GlU+Q+EEEIIIYQQQgghhBBCCCHfjP+tlI40J+ox7wAAAABJRU5ErkJggg==",fr=({open:o,onClose:i,orderId:d,currentCode:u,currentUrl:f,orderStatus:C})=>{const[c,g]=y.useState(u||""),[s,_]=y.useState(f||""),[l,T]=y.useState("correios"),[z,H]=y.useState(""),[b,w]=y.useState(!1),[U,D]=y.useState(null),{data:Q}=rt(),E=wr(Q),{mutate:Z,isPending:a}=Xa(d),F=["new","paid","processing"].includes(C);y.useEffect(()=>{F&&w(!0)},[F]),y.useEffect(()=>{if(c.trim()&&!u){const S=Ha(c);if(S.detected){const m={Correios:"correios",Jadlog:"jadlog",Loggi:"loggi","J&T Express":"jt"}[S.name];m&&T(m)}}},[c,u]),y.useEffect(()=>{if(l!=="other"){const S=c.trim(),v={correios:`https://rastreamento.correios.com.br/app/index.php?objeto=${S}`,jadlog:`https://www.jadlog.com.br/rastreamento/rastreamento.jad?cte=${S}`,loggi:`https://www.loggi.com/rastreamento/${S}`,jt:`https://www.jtexpress.com.br/trajectoryQuery?waybillNo=${S}&type=0`,"17track":`https://www.17track.net/pt/track?nums=${S}`};_(v[l]||"")}else _(z)},[l,c,z]);const A=()=>{if(D(null),!c.trim()){D("Por favor, insira um código de rastreamento");return}if(!$a(c)){D("Código de rastreamento inválido");return}if(!s.trim()){D("URL de rastreamento é obrigatória");return}Z({rastreio_codigo:c.trim(),rastreio_url:s.trim(),should_update_status:b},{onSuccess:()=>{i()},onError:S=>{var v,m;D(((m=(v=S.response)==null?void 0:v.data)==null?void 0:m.error)||S.message||"Erro ao atualizar código de rastreamento")}})},P=()=>{a||(D(null),i())};return e.jsxs(Ie,{open:o,onClose:P,maxWidth:"sm",fullWidth:!0,children:[e.jsx(We,{children:e.jsxs(h,{direction:"row",spacing:1,alignItems:"center",children:[e.jsx(gt,{size:24}),e.jsxs(n,{variant:"h6",component:"span",children:[u?"Editar":"Adicionar"," código de rastreamento"]})]})}),e.jsx(Ne,{children:e.jsxs(h,{spacing:2.5,sx:{mt:1},children:[e.jsx(j,{children:e.jsx(Ko,{fullWidth:!0,label:"Código de rastreamento",value:c,onChange:S=>g(S.target.value.toUpperCase()),placeholder:"Ex: AA123456789BR",autoFocus:!0,disabled:a})}),c.trim()&&e.jsxs(Jr,{fullWidth:!0,children:[e.jsx(Yr,{children:"Site"}),e.jsxs(Yt,{value:l,label:"Site",onChange:S=>T(S.target.value),disabled:a,renderValue:S=>{const m={correios:{logo:pr,name:"Correios"},jadlog:{logo:hr,name:"Jadlog"},loggi:{logo:mr,name:"Loggi"},jt:{logo:gr,name:"J&T Express"},"17track":{logo:xr,name:"17track (universal)"},other:{logo:"",name:"Outro"}}[S];return e.jsxs(j,{sx:{display:"flex",alignItems:"center",gap:1},children:[m.logo&&e.jsx("img",{src:m.logo,alt:m.name,style:{height:20}}),e.jsx(n,{children:m.name})]})},children:[e.jsxs(K,{value:"correios",children:[e.jsx(oe,{sx:{minWidth:32},children:e.jsx("img",{src:pr,alt:"Correios",style:{height:20}})}),e.jsx(Y,{children:"Correios"})]}),e.jsxs(K,{value:"jadlog",children:[e.jsx(oe,{sx:{minWidth:32},children:e.jsx("img",{src:hr,alt:"Jadlog",style:{height:20}})}),e.jsx(Y,{children:"Jadlog"})]}),e.jsxs(K,{value:"loggi",children:[e.jsx(oe,{sx:{minWidth:32},children:e.jsx("img",{src:mr,alt:"Loggi",style:{height:20}})}),e.jsx(Y,{children:"Loggi"})]}),e.jsxs(K,{value:"jt",children:[e.jsx(oe,{sx:{minWidth:32},children:e.jsx("img",{src:gr,alt:"J&T Express",style:{height:20}})}),e.jsx(Y,{children:"J&T Express"})]}),e.jsxs(K,{value:"17track",children:[e.jsx(oe,{sx:{minWidth:32},children:e.jsx("img",{src:xr,alt:"17track",style:{height:20}})}),e.jsx(Y,{children:"17track (universal)"})]}),e.jsx(K,{value:"other",children:e.jsx(Y,{children:"Outro"})})]})]}),l==="other"&&e.jsx(Ko,{fullWidth:!0,label:"URL de Rastreamento",value:z,onChange:S=>H(S.target.value),placeholder:"https://...",disabled:a}),F&&e.jsx(j,{sx:{borderRadius:1,p:1.5},children:e.jsx(jr,{control:e.jsx(yr,{checked:b,onChange:S=>w(S.target.checked),disabled:a}),label:e.jsx(n,{variant:"body2",children:"Marcar pedido como enviado"})})}),e.jsxs(j,{sx:{display:"flex",alignItems:"center",gap:1,py:1},children:[e.jsx(n,{variant:"caption",color:"text.secondary",children:E?"Email será enviado automaticamente":"Envio automático de email disponível no plano"}),!E&&e.jsx(yn,{variant:"label",fontSize:"0.75rem"})]}),U&&e.jsx(Qe,{severity:"error",onClose:()=>D(null),children:U})]})}),e.jsxs(Xe,{sx:{px:3,pb:2},children:[e.jsx(ee,{onClick:P,disabled:a,children:"Cancelar"}),e.jsx(Ft,{variant:"contained",onClick:A,loading:a,disabled:!c.trim()||!s.trim(),children:"Salvar"})]})]})},Ka=({orderId:o,trackingCode:i,trackingUrl:d,orderStatus:u,superfreteEtiquetaId:f})=>{const[C,c]=y.useState(!1),[g,s]=y.useState(!1),_=Ye(),{isSharing:l,runShare:T}=_n(),{data:z}=mo(o,{enabled:!!f}),H=async()=>{s(!0);try{await _.refetchQueries({queryKey:["pedido",Number(o)]})}finally{s(!1)}},b=!!i,w=!b&&z&&(z.status==="released"||z.status==="posted")&&!z.tracking;if(!b)return w?e.jsx(Zt,{sx:{p:2,backgroundColor:"white",opacity:.7},children:e.jsxs(h,{direction:"row",spacing:2,alignItems:"center",children:[e.jsx(j,{sx:{width:40,height:40,display:"flex",alignItems:"center",justifyContent:"center",bgcolor:"grey.300",borderRadius:1,color:"grey.600"},children:e.jsx(da,{sx:{fontSize:20}})}),e.jsxs(j,{sx:{flex:1},children:[e.jsx(n,{variant:"body2",fontWeight:600,color:"text.secondary",children:"Aguardando código de rastreio"}),e.jsx(n,{variant:"caption",color:"text.secondary",children:"Será adicionado automaticamente em breve"})]}),e.jsx(ce,{size:"small",onClick:H,disabled:g,sx:{color:"text.secondary","&:hover":{bgcolor:"grey.200"}},children:e.jsx(ua,{fontSize:"small",sx:{animation:g?"spin 1s linear infinite":"none","@keyframes spin":{"0%":{transform:"rotate(0deg)"},"100%":{transform:"rotate(360deg)"}}}})})]})}):e.jsxs(e.Fragment,{children:[e.jsx(Zt,{sx:{p:2,backgroundColor:"white",cursor:"pointer",transition:"all 0.2s","&:hover":{bgcolor:"grey.50"}},onClick:()=>c(!0),children:e.jsxs(h,{direction:"row",spacing:2,alignItems:"center",children:[e.jsx(j,{sx:{width:40,height:40,display:"flex",alignItems:"center",justifyContent:"center",bgcolor:"primary.main",borderRadius:1,color:"white"},children:e.jsx(gt,{size:20})}),e.jsxs(j,{sx:{flex:1},children:[e.jsx(n,{variant:"body2",fontWeight:600,children:"Adicionar código de rastreio"}),e.jsx(n,{variant:"caption",color:"text.secondary",children:"Mantenha seu cliente informado sobre o envio"})]}),e.jsx(bn,{sx:{color:"text.secondary"}})]})}),e.jsx(fr,{open:C,onClose:()=>c(!1),orderId:o,orderStatus:u})]});const U=()=>
8{if(i)return T(()=>vn({title:"Código de rastreamento",url:d||"",text:d?`Rastreie seu pedido: ${d}`:`Código de rastreamento: ${i}`}))};return e.jsxs(e.Fragment,{children:[e.jsxs(j,{children:[e.jsx(n,{variant:"body2",fontWeight:600,gutterBottom:!0,children:"Código de rastreamento:"}),e.jsxs(h,{direction:"row",alignItems:"center",spacing:.5,children:[e.jsx(n,{variant:"body2",fontWeight:500,color:"text.secondary",sx:{flex:1,fontFamily:"monospace",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:i}),e.jsx(vr,{text:i,size:"small"}),e.jsx(ce,{size:"small",onClick:U,disabled:l,sx:{width:24,height:24},children:e.jsx(Cr,{size:20})}),e.jsx(ce,{size:"small",onClick:()=>c(!0),sx:{width:24,height:24},children:e.jsx($e,{fontSize:"small"})})]})]}),e.jsx(fr,{open:C,onClose:()=>c(!1),orderId:o,currentCode:i,currentUrl:d,orderStatus:u})]})};function Ja({open:o,onClose:i,onConfirm:d,currentCoupon:u,subtotal:f,loading:C=!1,computeDiscount:c}){const[g,s]=y.useState(null);y.useEffect(()=>{o&&s(u)},[o,u]);const _=()=>{s(null),i()},l=()=>{d(g)};return e.jsxs(Ie,{open:o,onClose:_,maxWidth:"sm",fullWidth:!0,children:[e.jsx(We,{children:"Cupom de desconto"}),e.jsx(Ne,{sx:{pt:"20px !important"},children:e.jsx(kn,{value:g,onChange:s,subtotal:f,computeDiscount:c})}),e.jsxs(Xe,{children:[e.jsx(ee,{onClick:_,children:"Cancelar"}),e.jsx(Ft,{onClick:l,variant:"contained",loading:C,autoFocus:!0,children:"Confirmar"})]})]})}const Ya=(o,i)=>({frete_gratis:"Frete grátis",frete_distancia:"Entrega por distância",frete_personalizado:"Entrega personalizada",correios:"Correios",melhor_envio:"Melhor Envio",superfrete:"SuperFrete",uber:"Uber",a_combinar:"A combinar",retirada:i?"Entrega digital":"Retirada na loja"})[o],Vi=()=>{var wo,So,Ro,Eo,Do,Fo,Lo,ko,Oo,To,zo,Bo,Mo,Io,Wo,No,Uo,qo,Vo,Go,Ho,$o,Qo;const{orderId:o}=Pn(),i=xt(),[d]=Cn(),{data:u,isLoading:f}=rt(),C=ft(u),c=wr(u),g=d.get("navigateBack")==="true",[s,_]=y.useState(!1),[l,T]=y.useState(null),[z,H]=y.useState(null),[b,w]=y.useState(!1),[U,D]=y.useState(null),[Q,E]=y.useState(!0),[Z,a]=y.useState(!1),[F,A]=y.useState(!1),[P,S]=y.useState(!1),[v,m]=y.useState(null),[X,k]=y.useState(!1),M=y.useRef(null),{data:t,isLoading:O,isError:N}=qe(Number(o)),{data:re}=Je(),r=(re==null?void 0:re.retirada_modo)==="digital",{data:x,isLoading:B}=jt(Number(o)),R=In(),q=Wn(),ne=Nn(),G=On(),I=Tn(),{data:W=[]}=Mn(),{initializeItems:ie,resetToOriginal:xe,setTabelaPrecoId:ae}=sa(),me=Ma(),ke=["new","pending_payment"].includes((t==null?void 0:t.status_pedido)||""),Se=x&&x.parcelas.length>0,Ae=x==null?void 0:x.parcelas.filter(p=>p.status_parcela==="pendente").flatMap(p=>p.pagamentos||[]).find(p=>{var J;return((J=p.forma_pagamento)==null?void 0:J.codigo_padrao)==="pix"&&p.status!=="pago"}),je=(x==null?void 0:x.parcelas.filter(p=>p.status_parcela==="pendente").flatMap(p=>p.pagamentos||[]).filter(p=>{var J;return((J=p.forma_pagamento)==null?void 0:J.codigo_padrao)==="pix"&&p.status!=="pago"}))||[],he=((wo=t==null?void 0:t.itens_pedido)==null?void 0:wo.reduce((p,J)=>p+J.quantidade*J.preco_snapshot,0))||0,be=((So=t==null?void 0:t.frete_pedido)==null?void 0:So.valor_frete)||0,Re=(t==null?void 0:t.taxa_de_venda)||0,Ze=(t==null?void 0:t.valor_desconto)||0,Ee=he+be+Re-Ze,ge=(x==null?void 0:x.parcelas.reduce((p,J)=>{var ze;const ve=((ze=J.pagamentos)==null?void 0:ze.reduce((Le,Ve)=>Le+Ve.valor,0))||0;return p+ve},0))||0,De=ge<Ee?Math.round((Ee-ge)*100)/100:0,Oe=p=>p.toLocaleString("pt-BR",{style:"currency",currency:"BRL"}),yt=!!(x!=null&&x.parcelas.length)&&x.parcelas.every(p=>p.status_parcela!=="pendente"),_t=(t==null?void 0:t.origem)==="catalogo"&&(t==null?void 0:t.pagamento_entrega_escolha)==="na_entrega"&&!!(t!=null&&t.pagamento_entrega_metodo_nome)&&!yt&&(t==null?void 0:t.status_pedido)!=="canceled",se=(t==null?void 0:t.pagamento_entrega_troco_para)!=null?Number(t.pagamento_entrega_troco_para):null,nt=((Ro=t==null?void 0:t.frete_pedido)==null?void 0:Ro.tipo_frete)==="a_combinar",at=se!==null&&!nt?Math.max(0,se-Ee):0,it=!!U&&["paid","processing","shipped","delivered"].includes(U)&&je.length>0,et=!O&&!B&&ke&&!Se,st=!O&&!B&&!!Ae,ct=et||st,bt=O||B,vt=bt||ct,{appBarMarginLeft:It}=wn(),lt=()=>{g?i(-1):i("/orders",{replace:!0})};if(O||f)return e.jsxs(j,{sx:{display:"flex",flexDirection:"column",height:"70vh"},children:[e.jsx($t,{title:"Carregando...",navigateBack:lt,children:e.jsx(ce,{color:"inherit",disabled:!0,children:e.jsx(Qt,{})})}),e.jsx(j,{sx:{p:2},children:e.jsxs(h,{spacing:2,children:[e.jsxs(h,{direction:"row",justifyContent:"space-between",children:[e.jsx(ye,{width:120,height:24}),e.jsx(ye,{width:100,height:32})]}),e.jsx(ye,{variant:"rounded",width:"100%",height:80}),e.jsx(fe,{}),e.jsx(n,{variant:"h6",children:"Entrega"}),e.jsx(ye,{variant:"rounded",width:"100%",height:120}),e.jsx(fe,{}),e.jsx(n,{variant:"h6",children:"Produtos"}),e.jsx(ye,{variant:"rounded",width:"100%",height:80}),e.jsx(ye,{variant:"rounded",width:"100%",height:80}),e.jsx(ye,{variant:"rounded",width:"100%",height:160})]})})]});if(N||!t)return e.jsxs(j,{sx:{p:2},children:[e.jsx($t,{title:"Erro",navigateBack:lt,children:e.jsx(ce,{color:"inherit",children:e.jsx(Qt,{})})}),e.jsx(n,{variant:"h6",color:"error",children:"Pedido não encontrado"})]});const Wt=p=>{T(p.currentTarget)},Pt=()=>{T(null)},tt=p=>{H(p),Pt()},dt=()=>{H(null)},L=p=>{D(p),E(!0),w(!0),dt()},V=async()=>
8{if(!U){w(!1);return}if(await R.mutateAsync({pedido_id:t.pedido_id,status_pedido:U}),it&&Q){let p=De;for(const J of je)await q.mutateAsync({paymentId:J.id,pixDiscountValue:p>0?p:void 0}),p=0}w(!1),D(null)},$=()=>{A(!0)},te=()=>{me.mutate(Number(o),{onSuccess:()=>{i("/orders",{replace:!0})}}),A(!1)},Fe=p=>{var J,ve,ze,Le,Ve;ne.mutate({id:(J=t.frete_pedido)==null?void 0:J.id,pedido_id:t.pedido_id,tipo_frete:((ve=t.frete_pedido)==null?void 0:ve.tipo_frete)||"a_combinar",valor_frete:p,distancia_km:(ze=t.frete_pedido)==null?void 0:ze.distancia_km,faixa_frete_distancia_id:(Le=t.frete_pedido)==null?void 0:Le.faixa_frete_distancia_id,regiao_frete_personalizado_id:(Ve=t.frete_pedido)==null?void 0:Ve.regiao_frete_personalizado_id})},le=p=>{R.mutate({pedido_id:t.pedido_id,valor_desconto:p})},kr=p=>{R.mutate({pedido_id:t.pedido_id,taxa_de_venda:p})},ut=t.valor_desconto||0,Ao=((Eo=t.frete_pedido)==null?void 0:Eo.valor_frete)||0,jo=t.taxa_de_venda||0,Or=t.subtotal+Ao+jo-ut,Tr=t.total_custo||0,Nt=t.subtotal-ut,yo=Nt-Tr,zr=Nt>0?yo/Nt*100:0,Br="999,45",Mr="10%",_o={filter:"blur(3px)",userSelect:"none",display:"inline-block"},bo={position:"relative",display:"inline-block",margin:"3px"},Ir=()=>{t&&(m(new Date(t.data_pedido)),S(!0))},Ut=()=>{S(!1),m(null)},Wr=()=>{t&&v&&R.mutate({pedido_id:t.pedido_id,data_pedido:v.toISOString()}),Ut()},Nr=()=>{i(`/orders/${o}/payment-selection`)},Ur=()=>{Ae&&i(`/orders/${o}/payment/pix/${Ae.id}`)},qr=async p=>{t&&R.mutate({pedido_id:t.pedido_id,observacoes:p})},vo=((t==null?void 0:t.itens_pedido)??[]).map(p=>({produto_id:p.produto_id,produto_variacao_id:p.produto_variacao_id??null,preco_snapshot:p.preco_snapshot,quantidade:p.quantidade})),Po=p=>{t!=null&&t.frete_pedido&&ne.mutate({id:t.frete_pedido.id,pedido_id:t.pedido_id,tipo_frete:t.frete_pedido.tipo_frete||"a_combinar",valor_frete:p,distancia_km:t.frete_pedido.distancia_km,faixa_frete_distancia_id:t.frete_pedido.faixa_frete_distancia_id,regiao_frete_personalizado_id:t.frete_pedido.regiao_frete_personalizado_id})},Vr=p=>{var J,ve;if(t)if(p){const ze=G(p,vo,((J=t.frete_pedido)==null?void 0:J.valor_frete)||0),Le=I(p);if(ze.freeShipping){const Ve=((ve=t.frete_pedido)==null?void 0:ve.valor_frete)||0;Ve>0&&(M.current=Ve,Po(0))}R.mutate({pedido_id:t.pedido_id,cupom_id:p.id,cupom_codigo:p.codigo,cupom_tipo_desconto:p.tipo_desconto,cupom_valor_desconto:p.valor_desconto,cupom_aplicado_em:new Date().toISOString(),cupom_tipo_aplicacao:Le.cupom_tipo_aplicacao,cupom_frete_gratis:Le.cupom_frete_gratis,cupom_produtos_elegiveis:Le.cupom_produtos_elegiveis,cupom_categorias_elegiveis:Le.cupom_categorias_elegiveis,valor_desconto:ze.discount},{onSuccess:()=>{k(!1)}})}else t.cupom_frete_gratis&&M.current!=null&&M.current>0&&Po(M.current),M.current=null,R.mutate({pedido_id:t.pedido_id,cupom_id:null,cupom_codigo:null,cupom_tipo_desconto:null,cupom_valor_desconto:null,cupom_aplicado_em:null,cupom_tipo_aplicacao:"todos",cupom_frete_gratis:!1,cupom_produtos_elegiveis:null,cupom_categorias_elegiveis:null,valor_desconto:0},{onSuccess:()=>{k(!1)}})},Co=Sn(t.status_pedido);return e.jsxs(j,{sx:{p:2,overflowY:"auto",pb:vt?"calc(85px + 1rem)":2},children:[e.jsxs($t,{title:`Pedido #${t.numero_pedido}`,navigateBack:lt,children:[e.jsx(Ba,{orderID:t.pedido_id,iconOnly:!0}),e.jsx(ce,{color:"inherit",onClick:Wt,children:e.jsx(Qt,{})})]}),e.jsxs(h,{spacing:2,children:[e.jsxs(h,{direction:"row",justifyContent:"space-between",alignItems:"center",sx:{mb:1.5},children:[e.jsxs(j,{children:[e.jsxs(h,{direction:"row",alignItems:"center",spacing:.5,children:[e.jsx(n,{variant:"body1",color:"text.secondary",fontWeight:600,sx:{fontSize:"0.9rem"},children:Ue(new Date(t.data_pedido),"dd/MM/yyyy - HH:mm")}),["new","pending_payment"].includes(t.status_pedido)&&e.jsx(ce,{size:"small",onClick:Ir,children:e.jsx($e,{fontSize:"small"})})]}),e.jsxs(j,{sx:{display:"flex",gap:.5},children:[(()=>{const p=Pa(t.origem);return e.jsx(ht,{icon:p.icon,label:p.label,size:"small",sx:{height:18,fontSize:"0.65rem",backgroundColor:p.bg,color:p.color,border:"none","& .MuiChip-label":{px:1,fontWeight:500},"& .MuiChip-icon":{fontSize:"0.7rem",width:"0.7rem",height:"0.7rem",color:p.color}}})})(),t.importado_do_carrinho&&e.jsx(ht,{icon:e.jsx(ho,{}),label:"Importado",size:"small",sx:{height:18,fontSize:"0.65rem",backgroundColor:"#DCFCE7",color:"#16A34A",border:"none","& .MuiChip-label":{px:1,fontWeight:500},"& .MuiChip-icon":{fontSize:"0.7rem",color:"#16A34A"}}})]})]}),e.jsx(ht,{label:Et(t.status_pedido),onClick:p=>tt(p.currentTarget),deleteIcon:e.jsx(Rn,{}),onDelete:p=>{p.stopPropagation(),tt(p.currentTarget)},sx:{cursor:"pointer",pr:.5,height:28,backgroundColor:Co.backgroundColor,color:Co.color,border:"none","& .MuiChip-label":{fontSize:"0.8rem",fontWeight:600,px:1.5}}})]}),e.jsxs(h,{direction:"row",justifyContent:"space-between",alignItems:"center",sx:{mb:1.5},children:[e.jsx(n,{variant:"h6",fontWeight:600,color:"text.primary",children:"Cliente"}),["pending_payment","new"].includes(t.status_pedido)&&e.jsx(ce,{size:"small",onClick:()=>i(`/orders/${o}/edit/customer`),children:e.jsx($e,{fontSize:"small"})})]}),e.jsx(j,{sx:{mb:2},children:t.cliente?e.jsx(ha,{name:(Do=t.cliente)==null?void 0:Do.nome,phone:(Fo=t.cliente)==null?void 0:Fo.telefone,imageUrl:(Lo=t.cliente)==null?void 0:Lo.profile_url,userId:((ko=t.cliente)==null?void 0:ko.customer_user_id
8)||"",onClick:()=>{t.cliente_id&&i(`/customers/${t.cliente_id}`)}}):e.jsxs(j,{sx:{p:2,backgroundColor:"white",borderRadius:2,boxShadow:"none",display:"flex",alignItems:"center",gap:2},children:[e.jsx(j,{sx:{width:40,height:40,borderRadius:"50%",backgroundColor:"grey.100",display:"flex",alignItems:"center",justifyContent:"center"},children:e.jsx(En,{color:"disabled"})}),e.jsxs(j,{children:[e.jsx(n,{variant:"body1",fontWeight:600,children:"Outro cliente"}),e.jsx(n,{variant:"body2",color:"text.secondary",fontWeight:500,children:"Pedido sem cliente registrado"})]})]})}),t.tabela_preco&&e.jsxs(j,{sx:{mt:1.5,display:"flex",alignItems:"center",gap:1},children:[e.jsx(Dn,{size:16,style:{color:"var(--mui-palette-text-secondary)"}}),e.jsxs(n,{variant:"body2",color:"text.secondary",children:["Tabela: ",t.tabela_preco.nome]})]}),e.jsx(fe,{sx:{my:2.5}}),e.jsxs(h,{direction:"row",justifyContent:"space-between",alignItems:"center",sx:{mb:1.5},children:[e.jsx(n,{variant:"h6",fontWeight:600,color:"text.primary",children:"Entrega"}),["pending_payment","new"].includes(t.status_pedido)&&e.jsx(ce,{size:"small",onClick:()=>i(`/orders/${o}/edit/address`),children:e.jsx($e,{fontSize:"small"})})]}),e.jsxs(j,{sx:{backgroundColor:"white",borderRadius:2,boxShadow:"none",p:2,mb:2},children:[t.frete_pedido?e.jsxs(h,{spacing:2,children:[e.jsxs(h,{direction:"row",justifyContent:"space-between",alignItems:"center",children:[e.jsxs(h,{direction:"row",alignItems:"center",spacing:1,children:[e.jsx(j,{component:"span",sx:{color:"primary.main",display:"flex"},children:e.jsx(gt,{size:20})}),t.frete_pedido.tipo_frete==="frete_personalizado"&&((Oo=t.frete_pedido.regiao_frete_personalizado)!=null&&Oo.nome)?e.jsxs(j,{sx:{display:"flex",flexDirection:"column",alignItems:"flex-start"},children:[e.jsx(n,{variant:"body1",fontWeight:600,sx:{lineHeight:1.2},children:t.frete_pedido.regiao_frete_personalizado.nome}),e.jsx(n,{variant:"caption",color:"text.secondary",fontWeight:500,sx:{fontSize:"0.75rem",lineHeight:1.2},children:"Entrega personalizada"})]}):e.jsx(n,{variant:"body1",fontWeight:600,children:Ya(t.frete_pedido.tipo_frete,r)})]}),t.frete_pedido.valor_frete>0&&e.jsx(n,{variant:"body2",fontWeight:600,children:t.frete_pedido.valor_frete.toLocaleString("pt-BR",{style:"currency",currency:"BRL"})})]}),t.frete_pedido.distancia_km&&e.jsxs(n,{variant:"body2",color:"text.secondary",fontWeight:500,children:["Distância calculada: ",t.frete_pedido.distancia_km," km"]}),t.frete_pedido.tipo_frete==="melhor_envio"||t.frete_pedido.tipo_frete==="superfrete"&&t.frete_pedido.transportadora&&t.frete_pedido.modalidade&&e.jsxs(j,{sx:{pt:1,borderTop:1,borderColor:"divider"},children:[e.jsx(n,{variant:"body2",fontWeight:600,children:"Método de envio:"}),e.jsxs(n,{variant:"body2",fontWeight:500,children:[t.frete_pedido.transportadora," -"," ",t.frete_pedido.modalidade]})]})]}):e.jsx(n,{variant:"body2",color:"text.secondary",fontWeight:500,children:"Sem informações de entrega."}),t.endereco_entrega?e.jsxs(j,{sx:{pt:2,mt:1,borderTop:1,borderColor:"divider"},children:[e.jsx(n,{variant:"body2",fontWeight:600,gutterBottom:!0,children:"Endereço de entrega:"}),e.jsxs(n,{variant:"body2",fontWeight:500,color:"text.secondary",children:[t.endereco_entrega.nome_destinatario||""," ",e.jsx("br",{}),t.endereco_entrega.logradouro,","," ",t.endereco_entrega.numero," ",e.jsx("br",{}),t.endereco_entrega.complemento&&e.jsxs(e.Fragment,{children:[t.endereco_entrega.complemento," ",e.jsx("br",{})]}),t.endereco_entrega.bairro," ",e.jsx("br",{}),t.endereco_entrega.localidade," -"," ",t.endereco_entrega.uf," ",e.jsx("br",{}),t.endereco_entrega.cep]})]}):((To=t.frete_pedido)==null?void 0:To.tipo_frete)!=="retirada"&&e.jsx(j,{sx:{pt:2,mt:1,borderTop:1,borderColor:"divider"},children:e.jsx(n,{variant:"body2",fontWeight:500,color:"text.secondary",children:"Endereço de entrega não informado"})}),((zo=t.frete_pedido)==null?void 0:zo.tipo_frete)==="retirada"&&e.jsx(j,{sx:{pt:2,mt:1,borderTop:1,borderColor:"divider"},children:e.jsx(n,{variant:"body2",fontWeight:600,color:"primary",children:r?"Entrega digital: enviaremos o produto digital ao cliente":"Cliente retirará o pedido diretamente na loja"})}),_t&&e.jsxs(j,{sx:{pt:2,mt:1,borderTop:1,borderColor:"divider"},children:[e.jsxs(h,{direction:"row",justifyContent:"space-between",alignItems:"center",children:[e.jsxs(h,{direction:"row",alignItems:"center",spacing:1,children:[e.jsx(no,{co
8digoPadrao:t.pagamento_entrega_metodo_codigo,size:20}),e.jsxs(j,{children:[e.jsx(n,{variant:"body1",fontWeight:600,sx:{lineHeight:1.2},children:t.pagamento_entrega_metodo_nome}),e.jsxs(n,{variant:"caption",color:"text.secondary",fontWeight:500,sx:{fontSize:"0.75rem",lineHeight:1.2},children:["Cliente paga na"," ",((Bo=t.frete_pedido)==null?void 0:Bo.tipo_frete)==="retirada"?"retirada":"entrega"]})]})]}),se!==null&&at>0&&e.jsxs(n,{variant:"body2",fontWeight:600,children:["Troco: ",Oe(at)]})]}),se!==null&&e.jsx(n,{variant:"caption",color:"text.secondary",fontWeight:500,sx:{display:"block",mt:.75},children:nt?`Troco para ${Oe(se)} (frete a combinar)`:at>0?`Vai pagar com ${Oe(se)}`:`Vai pagar com ${Oe(se)} (sem troco)`})]}),((Mo=t.frete_pedido)==null?void 0:Mo.tipo_frete)!=="retirada"&&t.endereco_entrega&&["new","pending_payment","paid","processing"].includes(t.status_pedido)&&e.jsx(j,{sx:{pt:2,mt:1,borderTop:1,borderColor:"divider"},children:e.jsx(Ga,{orderId:o||"",superfreteEtiquetaId:(Io=t.frete_pedido)==null?void 0:Io.superfrete_etiqueta_id})}),((Wo=t.frete_pedido)==null?void 0:Wo.tipo_frete)!=="retirada"&&t.endereco_entrega&&e.jsx(j,{sx:{pt:2,mt:1,borderTop:1,borderColor:"divider"},children:e.jsx(Ka,{orderId:o||"",trackingCode:(No=t.frete_pedido)==null?void 0:No.rastreio_codigo,trackingUrl:(Uo=t.frete_pedido)==null?void 0:Uo.rastreio_url,orderStatus:t.status_pedido,superfreteEtiquetaId:(qo=t.frete_pedido)==null?void 0:qo.superfrete_etiqueta_id})})]}),e.jsx(fe,{sx:{my:2.5}}),e.jsx(n,{variant:"h6",fontWeight:600,color:"text.primary",sx:{mb:1.5},children:"Observações"}),e.jsx(j,{sx:{backgroundColor:"white",borderRadius:2,boxShadow:"none",p:2,mb:2},children:e.jsxs(h,{spacing:2,children:[t.observacoes_cliente&&e.jsxs(j,{children:[e.jsx(n,{variant:"body2",fontWeight:600,color:"text.primary",gutterBottom:!0,children:"Observações do cliente"}),e.jsx(n,{variant:"body2",color:"text.secondary",fontWeight:500,sx:{wordBreak:"break-word",whiteSpace:"pre-wrap",overflow:"hidden"},children:t.observacoes_cliente})]}),e.jsxs(j,{children:[e.jsx(n,{variant:"body2",fontWeight:600,color:"text.primary",gutterBottom:!0,children:"Suas observações"}),e.jsx(ca,{value:t.observacoes||"",onSave:qr,placeholder:"Adicione observações sobre este pedido...",multiline:!0,rows:3,maxLength:400,emptyText:"Nenhuma observação"})]})]})}),e.jsx(fe,{sx:{my:2.5}}),e.jsxs(h,{direction:"row",justifyContent:"space-between",alignItems:"center",sx:{mb:1.5},children:[e.jsx(n,{variant:"h6",fontWeight:600,color:"text.primary",children:"Produtos"}),["pending_payment","new"].includes(t.status_pedido)&&e.jsx(ce,{size:"small",onClick:()=>{ie(Number(o),t.itens_pedido,t.tabela_preco_id??null),ae(t.tabela_preco_id??null),xe(),i(`/orders/${o}/edit/products`)},children:e.jsx($e,{fontSize:"small"})})]}),e.jsx(j,{sx:{mb:2},children:((Vo=t.itens_pedido)==null?void 0:Vo.length)>0&&e.jsx(j,{children:t.itens_pedido.map(p=>{var J,ve;return e.jsx(Bn,{name:p.produto.nome,imageUrl:((J=p.produto_variacao)==null?void 0:J.image_url)||((ve=p.produto.image_url)==null?void 0:ve[0]),price:p.preco_snapshot,quantity:p.quantidade,productId:p.produto_id.toString(),productVariation:p.produto_variacao,product:p.produto,comboComponents:p.combo_componentes??null,personalizations:(p==null?void 0:p.item_pedido_personalizacao)??null},p.id?`i-${p.id}`:`${p.produto_id}-${p.produto_variacao_id||"main"}`)})})}),e.jsx(ya,{pedidoId:Number(o),items:t.itens_pedido,orderStatus:t.status_pedido,customerPhone:((Go=t.cliente)==null?void 0:Go.telefone)||null,customerEmail:((Ho=t.cliente)==null?void 0:Ho.email)||null,orderNumber:t.numero_pedido||t.pedido_id}),e.jsx(j,{sx:{backgroundColor:"white",p:2.5,borderRadius:2,boxShadow:"none",mb:2},children:e.jsxs(h,{spacing:2,children:[e.jsxs(h,{direction:"row",justifyContent:"space-between",alignItems:"center",children:[e.jsx(n,{variant:"body2",color:"text.secondary",fontWeight:600,children:"Subtotal"}),e.jsx(n,{variant:"body1",fontWeight:600,children:t.subtotal.toLocaleString("pt-BR",{style:"currency",currency:"BRL"})})]}),e.jsxs(h,{direction:"row",justifyContent:"space-between",alignItems:"center",children:[e.jsx(n,{variant:"body2",color:"text.secondary",fontWeight:600,children:"Frete"}),t.cupom_frete_gratis?e.jsx(n,{variant:"body1",fontWeight:600,color:"success.main",children:"Grátis"}):e.jsx(tr,{disabled:!["pending_payment","new"].includes(t.status_pedido),text:Ao.toLocaleStr
8ing("pt-BR",{style:"currency",currency:"BRL"}),onValueChange:Fe,fontSize:"body1.fontSize",typographyProps:{fontWeight:600}})]}),e.jsxs(h,{direction:"row",justifyContent:"space-between",alignItems:"center",children:[e.jsx(n,{variant:"body2",color:"text.secondary",fontWeight:600,children:"Taxa de venda"}),e.jsx(tr,{disabled:!["pending_payment","new"].includes(t.status_pedido),text:jo.toLocaleString("pt-BR",{style:"currency",currency:"BRL"}),onValueChange:kr,fontSize:"body1.fontSize",typographyProps:{fontWeight:600}})]}),e.jsxs(h,{direction:"row",justifyContent:"space-between",alignItems:"center",sx:{mb:1},children:[e.jsx(n,{variant:"body2",color:"text.secondary",fontWeight:600,children:"Cupom"}),e.jsxs(j,{sx:{display:"flex",alignItems:"center"},children:[["pending_payment","new"].includes(t.status_pedido)&&e.jsx(ce,{size:"small",onClick:()=>k(!0),sx:{mr:.5},children:e.jsx($e,{fontSize:"small"})}),e.jsx(n,{variant:"body1",fontWeight:t.cupom_id?600:400,color:t.cupom_id?"text.primary":"text.secondary",fontStyle:t.cupom_id?"normal":"italic",children:t.cupom_id?t.cupom_codigo:"Nenhum"})]})]}),e.jsxs(h,{direction:"row",justifyContent:"space-between",alignItems:"center",children:[e.jsx(n,{variant:"body2",color:"text.secondary",fontWeight:600,children:"Desconto"}),e.jsxs(j,{sx:{display:"flex",alignItems:"center"},children:[["pending_payment","new"].includes(t.status_pedido)&&e.jsx(ce,{size:"small",onClick:()=>a(!0),sx:{mr:.5},children:e.jsx($e,{fontSize:"small"})}),e.jsx(n,{variant:"body1",fontWeight:600,children:ut>0?`- ${ut.toLocaleString("pt-BR",{style:"currency",currency:"BRL"})}`:"R$ 0,00"})]})]}),e.jsx(fe,{sx:{borderStyle:"dashed",my:.5}}),e.jsxs(h,{direction:"row",justifyContent:"space-between",alignItems:"center",children:[e.jsx(n,{variant:"subtitle1",color:"text.primary",fontWeight:700,children:"Total"}),e.jsx(n,{variant:"subtitle1",fontWeight:700,children:Or.toLocaleString("pt-BR",{style:"currency",currency:"BRL"})})]})]})}),e.jsx(e.Fragment,{children:e.jsxs(Zt,{elevation:0,sx:{p:2,bgcolor:"white",borderRadius:2,cursor:"pointer",display:"flex",justifyContent:"space-between",alignItems:"center",mb:2,transition:"all 0.2s ease","&:hover":{backgroundColor:"grey.50"}},onClick:()=>i(`/orders/${o}/profitability`),children:[e.jsxs(j,{sx:{display:"flex",alignItems:"center",gap:1.5},children:[e.jsx(j,{sx:{bgcolor:"rgba(76, 175, 80, 0.1)",color:"success.main",width:36,height:36,borderRadius:1.5,display:"flex",alignItems:"center",justifyContent:"center"},children:e.jsx(Fr,{fontSize:"small"})}),e.jsxs(j,{children:[e.jsx(n,{variant:"subtitle1",fontWeight:600,children:"Análise de lucratividade"}),C?e.jsx(n,{variant:"body2",color:"text.secondary",fontWeight:500,children:`Lucro: ${yo.toLocaleString("pt-BR",{style:"currency",currency:"BRL"})} (${Fn(zr,1)}%)`}):e.jsxs(n,{variant:"body2",color:"text.secondary",fontWeight:500,children:["Lucro:"," ",e.jsx(j,{component:"span",sx:bo,children:e.jsx(n,{component:"span",variant:"body2",color:"text.secondary",sx:_o,children:Br})})," ",e.jsx(j,{component:"span",sx:bo,children:e.jsx(n,{component:"span",variant:"body2",color:"text.secondary",sx:_o,children:`(${Mr})`})})]})]})]}),e.jsx(ao,{color:"action"})]})}),s&&e.jsxs(e.Fragment,{children:[e.jsx(fe,{sx:{my:2.5}}),e.jsx(n,{variant:"h6",fontWeight:600,color:"text.primary",sx:{mb:1.5},children:"Pagamento"})]}),e.jsx(Ca,{orderId:t.pedido_id,orderStatus:t.status_pedido,onVisibilityChange:_}),c&&e.jsxs(e.Fragment,{children:[e.jsx(fe,{sx:{my:2.5}}),e.jsx(La,{pedidoId:t.pedido_id,clienteId:t.cliente_id,clienteCpfCnpj:($o=t.cliente)==null?void 0:$o.cpf_cnpj,orderHasAddress:!!t.endereco_entrega})]})]}),vt&&e.jsx(j,{sx:{position:"fixed",bottom:0,left:It,right:0,bgcolor:"white",p:2,pb:"calc(1rem + var(--safe-area-inset-bottom, 0px))",borderTop:"1px solid",borderColor:"divider"},children:bt?e.jsx(ye,{variant:"rounded",width:"100%",height:56,sx:{borderRadius:2}}):st?e.jsxs(ee,{variant:"contained",color:"success",onClick:Ur,fullWidth:!0,size:"large",sx:{textTransform:"none",fontWeight:600,fontSize:"1rem",py:1.5},children:["Ir para pagamento",e.jsx(oo,{sx:{ml:1}})]}):e.jsxs(ee,{variant:"contained",color:"success",onClick:Nr,fullWidth:!0,size:"large",sx:{textTransform:"none",fontWeight:600,fontSize:"1rem",py:1.5},children:["Ir para pagamento",e.jsx(oo,{sx:{ml:1}})]})}),e.jsx(va,{anchorEl:l,open:!!l,onClose:Pt,onMoveOrder:()=>tt(l),orderNumber:t.numero_pedido,orderId:t.pedido_id,customerPhone:((Qo=t.cliente)==null?void 0:Qo.telefone)||"",onDeleteOrder:$}),e.jsx(Ln,{anchorEl:z,open:!!z,onClose:dt,onSelectStatus:L}),e.jsxs(Ie,{open:b,onClose:()=>w(!1),children:[e.jsx(We,{children:"Mudar status?"}),e.jsxs(Ne,{children:[e.jsx(Rt,{children:`Quer marcar o pedido como "${Et(U||"")}"?`}),it&&e.jsx(jr,{sx:{mt:1.5,alignItems:"flex-start"},control:e.jsx(yr,{checked:Q,onChange:p=>E(p.target.checked),sx:{pt:.25}}),label:e.jsxs(h,{spacing:.25,children:[e.jsx(n,{variant:"body2",children:"Confirmar pagamento PIX"}),De>0&&e.jsx(n,{variant:"caption",color:"text.secondary",children:`R$ ${De.toLocaleStr
8ing("pt-BR",{minimumFractionDigits:2,maximumFractionDigits:2})} será aplicado como desconto`})]})})]}),e.jsxs(Xe,{children:[e.jsx(ee,{onClick:()=>w(!1),color:"primary",children:"Cancelar"}),e.jsx(ee,{onClick:V,color:"primary",autoFocus:!0,disabled:R.isPending||q.isPending,children:"Confirmar"})]})]}),e.jsx(zn,{open:Z,onClose:()=>a(!1),onApply:le,currentDiscount:ut,orderSubtotal:t.subtotal}),e.jsxs(Ie,{open:F,onClose:()=>A(!1),"aria-labelledby":"alert-dialog-title","aria-describedby":"alert-dialog-description",children:[e.jsx(We,{id:"alert-dialog-title",children:"Confirmar exclusão?"}),e.jsx(Ne,{children:e.jsx(Rt,{id:"alert-dialog-description",children:"Tem certeza de que deseja excluir este pedido? Esta ação não pode ser desfeita."})}),e.jsxs(Xe,{children:[e.jsx(ee,{onClick:()=>A(!1),color:"primary",children:"Cancelar"}),e.jsx(ee,{onClick:te,color:"primary",autoFocus:!0,children:"Confirmar"})]})]}),e.jsxs(Ie,{open:P,onClose:Ut,maxWidth:"xs",fullWidth:!0,children:[e.jsx(We,{children:"Alterar data do pedido"}),e.jsx(Ne,{sx:{pt:"20px !important"},children:t&&e.jsx(pa,{label:"Nova data",value:v,onChange:p=>m(p),ampm:!1,format:"dd/MM/yyyy HH:mm",maxDate:new Date,slotProps:{textField:{fullWidth:!0}},localeText:{okButtonLabel:"Confirmar",cancelButtonLabel:"Cancelar"}})}),e.jsxs(Xe,{children:[e.jsx(ee,{onClick:Ut,children:"Cancelar"}),e.jsx(ee,{onClick:Wr,variant:"contained",autoFocus:!0,children:"Confirmar"})]})]}),t&&e.jsx(Ja,{open:X,onClose:()=>k(!1),onConfirm:Vr,currentCoupon:t.cupom_id?W.find(p=>p.id===t.cupom_id)??{id:t.cupom_id,codigo:t.cupom_codigo,tipo_desconto:t.cupom_tipo_desconto,valor_desconto:t.cupom_valor_desconto,valor_minimo_compra:null,uso_maximo:null,uso_atual:0,data_expiracao:null,deletado_em:null,criado_em:t.cupom_aplicado_em||"",user_id:"",frete_gratis:t.cupom_frete_gratis??!1,tipo_aplicacao:t.cupom_tipo_aplicacao??"todos",produtos_elegiveis:t.cupom_produtos_elegiveis??[],categorias_seed:[]}:null,subtotal:t.subtotal,loading:R.isPending,computeDiscount:p=>{var J;return G(p,vo,((J=t.frete_pedido)==null?void 0:J.valor_frete)||0).discount}})]})};export{Vi 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.