PageSourceSearch

https://www.ecomdroptv.com/assets/Envios99Tab-C7pfeev6.js

js ecomdroptv.com collected 2026-10-02 01:28:31 UTC 37,194 bytes, 2 lines download raw bytes

1import{u as Te,h as rt,a as it,j as e,E as Oe,P as lt,c as dt}from"./index-D_T1XJ3U.js";import{r as n}from"./vendor-react-Bxgxa9T6.js";import{c as Y,a as ne}from"./coDates-BxYjNlB-.js";import{u as ct}from"./useAutoRefresh-80V06G0k.js";import{u as ut,P as pt}from"./PlatformLoadingState-DJXH2Kfu.js";import{I as gt}from"./InlineLoadingPill-CYMKS3P3.js";import{L as ft,c as mt,a as ht,S as xt,A as bt,b as vt}from"./LogisticsDashboard-nywkNmdL.js";import{P as yt,C as jt}from"./PlatformLoadingPill-DjtYP4Tz.js";import{P as St,U as Ct}from"./UtilityAdvertisingHero-C5ic1Uhk.js";import"./csvExport-DQyG9sid.js";import"./tasa-de-entrega-Ddtfuka5.js";import"./vendor-dnd-DkGDz49K.js";import"./customComponents-Dqinyoc5.js";const $="#FF4D4F",oe=a=>new Intl.NumberFormat("es-CO",{style:"currency",currency:"COP",maximumFractionDigits:0}).format(a||0),$e={padding:"6px 8px",fontSize:12.5,fontWeight:600,borderRadius:7,border:"1px solid var(--border)",background:"var(--bg-card)",color:"var(--text-primary)",fontFamily:"inherit",cursor:"pointer"},Pe={padding:"6px 8px",fontSize:12.5,borderRadius:7,border:"1px solid var(--border)",background:"var(--bg-card)",color:"var(--text-primary)",fontFamily:"inherit"},_t={width:"100%",borderCollapse:"collapse",fontSize:13},E={textAlign:"left",padding:"8px 10px",fontSize:11.5,fontWeight:700,color:"var(--text-muted)",textTransform:"uppercase",letterSpacing:"0.05em",borderBottom:"1px solid var(--border)"},se={...E,textAlign:"right"},kt={borderBottom:"1px solid var(--border)"},N={padding:"10px",color:"var(--text-primary)"},ae={...N,textAlign:"right",fontVariantNumeric:"tabular-nums"},We={padding:"6px 10px",fontSize:16,fontWeight:700,borderRadius:7,border:"none",background:"transparent",cursor:"pointer",color:"var(--text-secondary)",fontFamily:"inherit"};function wt({bucket:a,raw:i}){const u={entregado:{bg:"rgba(34,197,94,0.15)",fg:"#15803D",label:"Entregado"},devuelto:{bg:"rgba(239,68,68,0.15)",fg:"#B91C1C",label:"Devuelto"},cancelado:{bg:"rgba(148,163,184,0.18)",fg:"#475569",label:"Cancelado"},novedad:{bg:"rgba(245,158,11,0.18)",fg:"#92400E",label:"Novedad"},en_camino:{bg:"rgba(59,130,246,0.15)",fg:"#1E40AF",label:"En camino"},pendiente_confirmar:{bg:"rgba(168,85,247,0.15)",fg:"#6B21A8",label:"Por confirmar"},pendiente:{bg:"rgba(99,102,241,0.15)",fg:"#3730A3",label:"Pendiente"},guia_generada:{bg:"rgba(59,130,246,0.10)",fg:"#1E40AF",label:"Guía generada"},guia_por_generar:{bg:"rgba(148,163,184,0.12)",fg:"#475569",label:"Por alistar"},otro:{bg:"rgba(148,163,184,0.12)",fg:"#475569",label:i||"Otro"}},l=u[a]||u.otro;return e.jsx("span",{style:{display:"inline-block",padding:"3px 8px",borderRadius:4,fontSize:10.5,fontWeight:700,background:l.bg,color:l.fg,whiteSpace:"nowrap"},title:i||"",children:l.label})}const zt=["Enero","Febrero","Marzo","Abril","Mayo","Junio","Julio","Agosto","Septiembre","Octubre","Noviembre","Diciembre"];function Ft(a,i){const u=`${a}-${String(i+1).padStart(2,"0")}-01`,l=new Date(a,i+1,0).getDate(),h=`${a}-${String(i+1).padStart(2,"0")}-${String(l).padStart(2,"0")}`;return{since:u,until:h,label:`${zt[i]} ${a}`}}function qt(){var Fe,Re,Be,Ee;const a=Te(),{token:i,user:u}=rt(),{isHidden:l}=it(),h=l?"sensitive-hidden":"",f=new Date,x=Y(),[c,w]=n.useState("custom"),[S,z]=n.useState(f.getFullYear()),[C,b]=n.useState(f.getMonth()),[_,re]=n.useState(x),[F,ie]=n.useState(x),[k,Ie]=n.useState(""),s=n.useMemo(()=>c==="month"?Ft(S,C):{since:_,until:F,label:_&&F?`${_} → ${F}`:"Rango personalizado"},[c,S,C,_,F]),[v,me]=n.useState(null),[j,he]=n.useState(null),[He,xe]=n.useState(!1),[M,le]=n.useState(!0);ut("envios99",M);const[A,be]=n.useState(null),[Ue,de]=n.useState(!1),[ce,Ve]=n.useState(null),[te,Me]=n.useState(null),[ve,q]=n.useState(!1),[L,ye]=n.useState(!1),[qe,Ke]=n.useState(0),je=n.useRef(!1),Se=n.useRef(!1),[Ge,ue]=n.useState(!1),[Ce,Ye]=n.useState([]),[J,Je]=n.useState(0),[R,pe]=n.useState(0),[Qe,_e]=n.useState(!1),[T,Xe]=n.useState(""),[O,Ze]=n.useState(""),[D,et]=n.useState(""),[I,tt]=n.useState(""),H=50,ke=n.useRef(!1),we="envios99_hero_filters_v1",[g,Q]=n.useState(()=>{try{const t=localStorage.getItem(we);if(t)return JSON.parse(t)}catch{}return{products:null,meta_campaigns:[],tiktok_campaigns:[]}});n.useEffect(()=>{try{localStorage.setItem(we,JSON.stringify(g))}catch{}},[g]);const[m,nt]=n.useState(g);n.useEffect(()=>{const t=setTimeout(()=>nt(g),400);return()=>clearTimeout(t)},[g]);const X=ct(6e4),U=n.useCallback(async()=>
1{if(c==="custom"&&(!_||!F)){he(null),le(!1);return}je.current||le(!0);try{const t=new URLSearchParams;if(t.set("since",s.since),t.set("until",s.until),k&&t.set("store",k),m.products&&m.products.length>0)for(const y of m.products)t.append("products",y);m.meta_campaigns.length>0&&t.set("meta_campaigns",m.meta_campaigns.join(",")),m.tiktok_campaigns.length>0&&t.set("tiktok_campaigns",m.tiktok_campaigns.join(","));const d=await a(`/api/envios99/analytics?${t}`);if(!d.ok)throw new Error(`http ${d.status}`);const o=await d.json();he(o&&typeof o=="object"&&o.totals?o:null),xe(!1)}catch(t){console.warn("[envios99] analytics failed:",t),xe(!0)}finally{le(!1),je.current=!0}},[a,c,_,F,s.since,s.until,k,m]),K=n.useCallback(async()=>{if(c==="custom"&&(!_||!F)){be(null),de(!1);return}Se.current||de(!0);try{const t=new URLSearchParams;if(t.set("since",s.since),t.set("until",s.until),k&&t.set("store",k),m.products&&m.products.length>0)for(const o of m.products)t.append("products",o);m.meta_campaigns.length>0&&t.set("meta_campaigns",m.meta_campaigns.join(",")),m.tiktok_campaigns.length>0&&t.set("tiktok_campaigns",m.tiktok_campaigns.join(","));const d=await a(`/api/envios99/metrics?${t}`);if(d.ok){const o=await d.json();be({utilidad_real:o.utilidad_real||0,margen:o.margen||0,publicidad_meta:o.publicidad_meta||0,publicidad_tiktok:o.publicidad_tiktok||0,publicidad_total:o.publicidad_total||0,utilidad_neta:o.utilidad_neta||0,roas:o.roas||0,pauta_sobre_venta:o.pauta_sobre_venta||0,fuentes:o.fuentes||{meta_conectado:!1,tiktok_conectado:!1}})}}catch(t){console.warn("[envios99] hero failed:",t)}finally{de(!1),Se.current=!0}},[a,c,_,F,s.since,s.until,k,m]),G=n.useCallback(async()=>{try{const d=await(await a("/api/envios99/connection")).json();me(d)}catch{me({connected:!1})}},[a]);n.useEffect(()=>{G()},[G]),n.useEffect(()=>{U()},[U,X]),n.useEffect(()=>{if((u==null?void 0:u.role)!=="admin")return;const t="env99_inspect_raw_done_v2";sessionStorage.getItem(t)||a("/api/envios99/admin/inspect-raw").then(()=>{try{sessionStorage.setItem(t,"1")}catch{}}).catch(()=>{})},[u==null?void 0:u.role,a]),n.useEffect(()=>{if((u==null?void 0:u.role)!=="admin")return;const t="env99_diag_novedades_v1";sessionStorage.getItem(t)||a("/api/envios99/admin/diag-novedades").then(()=>{try{sessionStorage.setItem(t,"1")}catch{}}).catch(()=>{})},[u==null?void 0:u.role,a]),n.useEffect(()=>{let t=!0;return(async()=>{if(i)try{const o=new URLSearchParams;s.since&&o.set("since",s.since),s.until&&o.set("until",s.until);const y=await a(`/api/envios99/pending-status?${o}`,{headers:{Authorization:`Bearer ${i}`}});if(!y.ok)return;const r=await y.json();t&&Ve(r)}catch{}})(),()=>{t=!1}},[i,s.since,s.until,X]),n.useEffect(()=>{let t=!0;return(async()=>{if(i)try{const o=new URLSearchParams;s.since&&o.set("since",s.since),s.until&&o.set("until",s.until);const y=await a(`/api/envios99/balance?${o}`);if(!y.ok)return;const r=await y.json();t&&Me(r)}catch{}})(),()=>{t=!1}},[i,a,s.since,s.until,X]),n.useEffect(()=>{K()},[K,X]);const ze=n.useCallback(async()=>{ke.current||_e(!0);try{const t=new URLSearchParams;if(s.since&&t.set("since",s.since),s.until&&t.set("until",s.until),k&&t.set("sucursal_id",k),T&&t.set("bucket",T),O&&t.set("carrier",O),D&&t.set("city",D),I&&t.set("q",I),m.products&&m.products.length>0)for(const y of m.products)t.append("products",y);t.set("limit",String(H)),t.set("offset",String(R));const o=await(await a(`/api/envios99/orders?${t}`)).json();Ye(o.rows||[]),Je(o.total||0)}finally{_e(!1),ke.current=!0}},[a,s.since,s.until,k,T,O,D,I,R,m.products]);n.useEffect(()=>{ze()},[ze,X]),n.useEffect(()=>{pe(0)},[s.since,s.until,k,T,O,D,I]);const ot=async()=>{const t=new URLSearchParams;if(s.since&&t.set("since",s.since),s.until&&t.set("until",s.until),k&&t.set("sucursal_id",k),T&&t.set("bucket",T),O&&t.set("carrier",O),D&&t.set("city",D),I&&t.set("q",I),g.products&&g.products.length>0)for(const p of g.products)t.append("products",p);t.set("limit","500"),t.set("offset","0");const y=(await(await a(`/api/envios99/orders?${t}`)).json()).rows||[],r=["Guía","ID","Fecha","Entregado el","Estado","Bucket","Cliente","Teléfono","Ciudad","Departamento","Producto","Transportadora","Total","Flete","Seguro","Consignado","Costo Proveedor","Utilidad","Sucursal"],W=p=>`"${(p==null?"":String(p)).replace(/"/g,'""')}"`,V=[r.map(W).join(",")];for(const p of y)V.push([p.guia_preenvio,p.envios99_order_id,p.ordered_at,p.fecha_entrega,p.estado_envio,p.bucket,p.customer_name,p.phone,p.city,p.state,p.product_name,p.carrier,p.total,p.valor_flete,p.valor_seguro,p.valor_consignado,p.provider_cost,p.real_profit,p.sucursal_id].map(W).join(","));const fe=new Blob(["\uFEFF"+V.join(`
2`)],{type:"text/csv;charset=utf-8"}),Ne=URL.createObjectURL(fe),ee=document.createElement("a");ee.href=Ne,ee.download=`99envios-pedidos-${s.since||""}-${s.until||""}.csv`,document.body.appendChild(ee),ee.click(),document.body.removeChild(ee),URL.revokeObjectURL(Ne)},st=async()=>{ye(!0);try{await a("/api/envios99/sync",{method:"POST"}),await Promise.all([G(),U(),K()])}finally{ye(!1)}},at=async()=>{confirm("¿Desvincular tu cuenta de 99envíos? Las órdenes ya sincronizadas se conservan.")&&(await a("/api/envios99/connection",{method:"DELETE"}),await G())},P=!!j&&(j.totals.orders>0||Number(j.totals.orders_all)>0),Z=!!(v!=null&&v.connected),ge=(v==null?void 0:v.sucursales)||[],B=((Fe=j==null?void 0:j.financials)==null?void 0:Fe.desglose)||null;return!M&&!Z&&!P?e.jsxs(e.Fragment,{children:[e.jsx("div",{style:{maxWidth:640,margin:"40px auto",padding:"0 18px"},children:e.jsxs("div",{style:{background:"var(--bg-card)",border:"1px solid var(--border)",borderRadius:16,padding:32,textAlign:"center"},children:[e.jsxs("div",{style:{display:"inline-flex",alignItems:"center",gap:14,marginBottom:14},children:[e.jsx(Oe,{size:48}),e.jsxs("div",{style:{display:"inline-flex",alignItems:"center",gap:6,fontSize:11,fontWeight:800,color:"#fff",background:$,padding:"5px 10px",borderRadius:999,letterSpacing:"0.06em"},children:[e.jsx("span",{style:{fontSize:11},children:"✓"})," API OFICIAL"]})]}),e.jsx("h2",{style:{fontSize:22,fontWeight:800,color:"var(--text-primary)",margin:"8px 0 12px"},children:"Conecta tu cuenta de 99envíos"}),e.jsx("p",{style:{fontSize:14,color:"var(--text-secondary)",lineHeight:1.6,maxWidth:480,margin:"0 auto 22px"},children:"Sincroniza tus pedidos en tiempo real. Cruza ventas con tu pauta de Meta y TikTok."}),e.jsx("button",{onClick:()=>q(!0),style:{padding:"12px 24px",background:$,color:"#fff",border:"none",borderRadius:10,fontSize:14,fontWeight:700,cursor:"pointer",fontFamily:"inherit",boxShadow:`0 4px 14px ${$}40`},children:"Conectar 99envíos →"}),e.jsx("div",{style:{fontSize:11,color:"var(--text-muted)",marginTop:14},children:"Usa el mismo email y contraseña que en 99envios.app · Guardamos cifrado per-user"})]})}),ve&&e.jsx(Ae,{onClose:()=>q(!1),onConnected:()=>{q(!1),G(),U(),K()}})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{style:{padding:"0 4px 80px"},children:[He&&e.jsxs("div",{style:{background:"#FFFBEB",border:"1px solid #FCD34D",color:"#92400E",borderRadius:10,padding:"10px 13px",marginBottom:12,fontSize:13,fontWeight:700,display:"flex",alignItems:"center",gap:10,flexWrap:"wrap"},children:[e.jsx("span",{children:"No se pudieron actualizar los números. Los que ves s
2on del rango anterior, no del que tienes seleccionado."}),e.jsx("button",{onClick:()=>U(),style:{background:"#92400E",color:"#fff",border:"none",borderRadius:8,padding:"6px 12px",fontSize:12.5,fontWeight:700,cursor:"pointer",fontFamily:"inherit"},children:"Reintentar"})]}),e.jsx(lt,{platform:"envios99",subtitle:v!=null&&v.connected?(()=>{const t=v.last_sync_at?new Date(v.last_sync_at):null,d=t?Math.floor((Date.now()-t.getTime())/6e4):null,o=!!v.last_sync_partial_at&&v.last_sync_partial_at===v.last_sync_at,y=L?"🟡":o?"🟠":d!==null&&d<30?"🟢":"⚪",r=L?"Sincronizando…":o?"Conectado, con pedidos sin traer":"Conectado",W=t?`· última sync hace ${d} min`:"· sin sincronizar todavía",V=(v.sucursales_count||0)>1?` · ${v.sucursales_count} sucursales`:"",fe=o?" · 99envíos no respondió a todo; se reintenta solo en la siguiente pasada":"";return`${y} ${r}${v.email?` · ${v.email}`:""} ${W}${V}${fe}`})():"⚪ No conectado — conecta tu cuenta para sincronizar pedidos automáticamente",rightSlot:Z?e.jsxs("div",{style:{display:"flex",gap:8},children:[e.jsx("button",{onClick:st,disabled:L,style:{padding:"7px 14px",background:L?"#94A3B8":$,color:"#fff",border:"none",borderRadius:8,fontSize:12,fontWeight:700,cursor:L?"default":"pointer",fontFamily:"inherit",opacity:L?.7:1},children:L?"Sincronizando…":"Sincronizar ahora"}),e.jsx("button",{onClick:at,style:{padding:"7px 12px",background:"transparent",color:"var(--text-muted)",border:"1px solid var(--border)",borderRadius:8,fontSize:11.5,fontWeight:600,cursor:"pointer",fontFamily:"inherit"},children:"Desconectar"})]}):e.jsx("button",{onClick:()=>q(!0),style:{padding:"8px 14px",background:$,color:"#fff",border:"none",borderRadius:8,fontSize:12,fontWeight:700,cursor:"pointer",fontFamily:"inherit"},children:"Conectar 99envíos"})}),e.jsxs("div",{className:"date-filter-row",children:[e.jsxs("div",{className:"date-filter-pill",children:[[{key:"today",label:"Hoy",fn:()=>{const t=Y();return{s:t,u:t}}},{key:"yest",label:"Ayer",fn:()=>{const t=ne(Y(),1);return{s:t,u:t}}},{key:"7d",label:"7d",fn:()=>{const t=Y();return{s:ne(t,6),u:t}}},{key:"15d",label:"15d",fn:()=>{const t=Y();return{s:ne(t,14),u:t}}},{key:"30d",label:"30d",fn:()=>{const t=Y();return{s:ne(t,29),u:t}}}].map(t=>{const{s:d,u:o}=t.fn(),y=c==="custom"&&_===d&&F===o;return e.jsx("button",{onClick:()=>
2{re(d),ie(o),w("custom")},className:`date-pill-btn${y?" active":""}`,title:`${d} → ${o}`,children:t.label},t.key)}),e.jsx("button",{onClick:()=>{re(""),ie(""),w("custom")},className:`date-pill-btn${c==="custom"&&!_&&!F?" active":""}`,children:"Personalizado"})]}),c==="custom"&&e.jsxs(e.Fragment,{children:[e.jsx("input",{type:"date",value:_,onChange:t=>re(t.target.value),className:"date-input-compact"}),e.jsx("span",{className:"date-arrow-sep",children:"→"}),e.jsx("input",{type:"date",value:F,onChange:t=>ie(t.target.value),className:"date-input-compact"})]}),e.jsxs("div",{className:"range-indicator",children:[s.label," ",j&&!M&&`· ${j.totals.orders} pedidos`]}),M&&P&&e.jsx(yt,{platform:"envios99"})]}),e.jsxs("div",{className:"filters-row",children:[ge.length>1&&e.jsx("div",{className:"filters-row-item",children:e.jsxs("select",{value:k,onChange:t=>Ie(t.target.value),className:"filters-row-select",title:"Filtrar por sucursal",children:[e.jsxs("option",{value:"",children:["🏪 Todas las sucursales (",ge.length,")"]}),ge.map(t=>e.jsxs("option",{value:t.id,children:["🏪 ",dt(t.name,l)]},t.id))]})}),e.jsxs("button",{onClick:()=>ue(t=>!t),className:`product-filter-header-btn filters-row-item${(((Re=g.products)==null?void 0:Re.length)??0)>0?" active":""}`,"aria-label":"Filtrar productos",children:["📦 ",(((Be=g.products)==null?void 0:Be.length)??0)>0?`${g.products.length} producto${g.products.length>1?"s":""}`:"Todos los productos"]})]}),(((Ee=g.products)==null?void 0:Ee.length)??0)>0&&e.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:6,marginTop:-8,marginBottom:16},children:[g.products.map(t=>e.jsxs("span",{className:"filter-chip",children:[e.jsx("span",{style:{maxWidth:200,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:t}),e.jsx("button",{onClick:()=>{const d=g.products.filter(o=>o!==t);Q({...g,products:d.length>0?d:null})},"aria-label":`Quitar ${t}`,className:"filter-chip-remove",children:"×"})]},t)),e.jsx("button",{onClick:()=>Q({...g,products:null}),className:"filter-chip-clear",children:"Limpiar todos"})]}),Ge&&e.jsx(St,{rango:{desde:s.since,hasta:s.until},token:i,platform:"envios99",selected:g.products||[],onApply:t=>{Q({...g,products:t.length>0?t:null}),ue(!1)},onClose:()=>ue(!1)}),e.jsx(jt,{tab:"envios99",position:"top"}),e.jsx(gt,{platform:"envios99"}),P&&e.jsx(Ct,{metrics:A,loading:Ue,currency:"COP",rango:{desde:s.since,hasta:s.until},token:i,platform:"envios99",filters:g,onFiltersChange:Q}),(()=>{var o;const t=((o=g.products)==null?void 0:o.length)||0,d=g.meta_campaigns.length+g.tiktok_campaigns.length;return t===0&&d===0?null:e.jsxs("div",{style:{background:"rgba(99, 102, 241, 0.08)",border:"1px solid rgba(99, 102, 241, 0.3)",borderRadius:10,padding:"10px 14px",margin:"12px 0",display:"flex",alignItems:"center",justifyContent:"space-between",fontSize:13,color:"var(--text-primary)",gap:12,flexWrap:"wrap"},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[e.jsx("span",{style:{fontSize:16},children:"🔍"}),e.jsxs("span",{children:[e.jsx("b",{children:"Dashboard filtrado"})," ·",t>0&&e.jsxs("span",{children:[" ",t," producto",t>1?"s":""]}),t>0&&d>0&&e.jsx("span",{children:" ·"}),d>0&&e.jsxs("span",{children:[" ",d," campaña",d>1?"s":""," (solo afecta publicidad)"]})]})]}),e.jsx("button",{onClick:()=>Q({products:null,meta_campaigns:[],tiktok_campaigns:[]}),style:{background:"transparent",border:"1px solid rgba(99, 102, 241, 0.4)",color:"rgb(99, 102, 241)",padding:"4px 10px",borderRadius:6,fontSize:12,cursor:"pointer"},children:"Limpiar filtros"})]})})(),P&&j&&(()=>{const t=[];if(B){const r=B.breakdown;if(r&&r.flete+r.servicio+r.seguro+r.contrapago+r.descuento_4x1000+Math.max(0,r.otros)>=1)r.flete>=1&&t.push({label:"Flete",desc:"Costo de envío cobrado por 99envíos",amount:r.flete}),r.servicio>=1&&t.push({label:"Servicio",desc:"Tarifa de servicio operativo",amount:r.servicio}),r.seguro>=1&&t.push({label:"Seguro",desc:"Cubre devoluciones — no pagas flete extra al devolver",amount:r.seguro}),r.contrapago>=1&&t.push({label:"Contraentrega",desc:"Costo de gestión del recaudo COD",amount:r.contrapago}),r.descuento_4x1000>=1&&t.push({label:"Retención 4×1000",desc:"GMF sobre el recaudo bancario",amount:r.descuento_4x1000}),Math.abs(r.otros)>=1&&t.push({label:"Otros",desc:"Diferencia residual no clasificada",amount:r.otros});else if(B.comisiones_99envios>=1){const W=B.comisiones_pct?(B.comisiones_pct*100).toFixed(1):"0";t.push({label:`Comisiones 99envíos · ${W}%`,desc:"99envíos no expone el desglose para este rango — total descontado del recaudo",amount:B.comisiones_99envios})}}const d=(B==null?void 0:B.breakdown)&&B.breakdown.seguro>=1,o=j.tipos_novedad_90d,y=Array.isArray(o)&&o.length>0?o.map(r=>
2({name:r.tipo,count:r.count,entregado:r.entregado,devuelto:r.devuelto,activa:r.activa})):void 0;return e.jsx(ft,{analytics:j,brandColor:$,platformName:"99envíos",currency:"COP",rango:{desde:s.since,hasta:s.until},token:i,onCostsChanged:()=>{Ke(r=>r+1),U(),K()},costsRefetchTrigger:qe,adsSpend:(A==null?void 0:A.publicidad_total)??0,novedadBreakdown:y,costLines:t.length>0?t:void 0,lossLines:[],costNote:d?{icon:"🛡️",tint:"green",text:"Pagaste seguro este rango. 99envíos cubre la devolución: entregue o no entregue, no te cobran flete extra por traer el paquete de vuelta."}:void 0,productCostNote:{icon:"📦",text:"Costo de producto: no se incluye en este desglose. En 99envíos la mayoría de sellers son dueños del producto que envían. Si quieres tu utilidad neta real, resta tu costo de producción/compra manualmente."},trasKpis:j.totals.orders>0?(()=>{var V;const r=mt(j,(A==null?void 0:A.publicidad_total)??0),W=ht(j);return e.jsxs(e.Fragment,{children:[e.jsx(xt,{score:r.score,label:r.label,color:r.color,breakdown:r.breakdown}),ce&&ce.en_proceso.count>0&&e.jsx(Rt,{data:ce}),te&&(te.total_entregadas>0||(((V=te.devoluciones_sin_seguro)==null?void 0:V.count)??0)>0)&&e.jsx(Bt,{data:te}),e.jsx(bt,{alerts:W})]})})():null})})(),Z&&P&&e.jsx(vt,{endpoint:"/api/envios99/address-quality",since:s.since,until:s.until,platformName:"99 envíos"}),M&&Z&&!P&&e.jsx(pt,{platform:"envios99"}),!M&&Z&&!P&&e.jsxs("div",{style:{padding:40,textAlign:"center",color:"var(--text-muted)",background:"var(--bg-card)",border:"1px solid var(--border)",borderRadius:12,marginTop:12},children:[e.jsx("div",{style:{fontSize:42,marginBottom:8},children:"📦"}),e.jsxs("div",{style:{fontSize:15,fontWeight:600,color:"var(--text-primary)",marginBottom:4},children:["Sin pedidos en ",s.label]}),e.jsx("div",{style:{fontSize:13},children:"Cambia de mes o sincroniza manualmente con el botón ↻ Sync."})]}),P&&j&&e.jsxs("div",{className:"dashboard-card",style:{background:"var(--bg-card)",border:"1px solid var(--border)",borderRadius:12,padding:16,marginTop:20},children:[e.jsxs("div",{style:{marginBottom:12},children:[e.jsx("h3",{style:{fontSize:15,fontWeight:800,color:"var(--text-primary)",margin:0,letterSpacing:"-0.01em"},children:"Listado detallado de pedidos"}),e.jsx("div",{style:{fontSize:11,color:"var(--text-muted)",marginTop:2},children:"Filtra, busca y exporta como CSV para analizar fuera del panel"})]}),e.jsxs("div",{style:{display:"flex",gap:8,flexWrap:"wrap",marginBottom:14},children:[e.jsxs("select",{value:T,onChange:t=>Xe(t.target.value),style:{...$e,padding:"7px 10px"},children:[e.jsx("option",{value:"",children:"Todos los estados"}),e.jsx("option",{value:"entregado",children:"Entregados"}),e.jsx("option",{value:"devuelto",children:"Devueltos"}),e.jsx("option",{value:"en_camino",children:"En camino"}),e.jsx("option",{value:"novedad",children:"Con novedad"}),e.jsx("option",{value:"pendiente_confirmar",children:"Por confirmar"}),e.jsx("option",{value:"cancelado",children:"Cancelados"})]}),e.jsxs("select",{value:O,onChange:t=>Ze(t.target.value),style:{...$e,padding:"7px 10px"},children:[e.jsx("option",{value:"",children:"Todas las transportadoras"}),j.by_carrier.map(t=>e.jsx("option",{value:t.name,children:t.name},t.name))]}),e.jsx("input",{placeholder:"Filtrar por ciudad…",value:D,onChange:t=>et(t.target.value),style:{...Pe,minWidth:140}}),e.jsx("input",{placeholder:"Buscar (ID, cliente, producto)…",value:I,onChange:t=>tt(t.target.value),style:{...Pe,flex:1,minWidth:200}}),e.jsx("button",{onClick:ot,style:{padding:"7px 14px",fontSize:12.5,fontWeight:700,borderRadius:7,border:"none",background:$,color:"#fff",cursor:"pointer",fontFamily:"inherit"},children:"↓ Exportar CSV"})]}),e.jsx("div",{style:{overflowX:"auto",overscrollBehaviorX:"contain",WebkitOverflowScrolling:"touch"},children:e.jsxs("table",{style:_t,children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{style:E,children:"Guía"}),e.jsx("th",{style:E,children:"Fecha"}),e.jsx("th",{style:E,children:"Estado"}),e.jsx("th",{style:E,children:"Cliente"}),e.jsx("th",{style:E,children:"Producto"}),e.jsx("th",{style:E,children:"Ciudad"}),e.jsx("th",{style:E,children:"Transp."}),e.jsx("th",{style:se,children:"Total"}),e.jsx("th",{style:se,children:"Flete"}),e.jsx("th",{style:se,children:"Seguro"}),e.jsx("th",{style:E,children:"Pagado"}),e.jsx("th",{style:se,children:"Utilidad"})]})}),e.jsxs("tbody",{children:[Ce.length===0&&!Qe&&e.jsx("tr",{children:e.jsx("td",{colSpan:12,style:{padding:20,textAlign:"center",color:"var(--text-muted)"},children:"Sin pedidos con estos filtros"})}),Ce.map(t=>e.jsxs("tr",{style:kt,children:[e.jsx("td",{className:"censor-blur",style:{...N,fontWeight:700,fontSize:12,whiteSpace:"nowrap"},title:t.envios99_order_id,children:t.guia_preenvio||t.envios99_order_id}),e.jsx("td",{style:{...N,color:"var(--text-muted)",whiteSpace:"nowrap",fontSize:12},children:t.ordered_at?String(t.ordered_at).slice(0,10):"—"}),e.jsx("td",{style:N,children:e.jsx(wt,{bucket:t.bucket,raw:t.estado_envio})}),e.jsx("td",{className:h,style:{...N,maxWidth:140,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:t.customer_name||"—"}),e.jsx("td",{className:"censor-blur",style:{...N,maxWidth:180,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:t.product_name||"—"}),e.jsx("td",{style:N,children:t.city||"—"}),e.jsx("td",{style:{...N,fontSize:12},children:t.carrier||"—"}),e.jsx("td",{className:h,style:ae,children:oe(t.total||0)}),e.jsx("td",{className:h,style:{...ae,color:"var(--text-muted)"},children:t.valor_flete?oe(t.valor_flete):"—"}),e.jsx("td",{className:h,style:{...ae,color:t.valor_seguro?"#3F8636":"var(--text-muted)"},children:t.valor_seguro?oe(t.valor_seguro):"—"}),e.jsx("td",{style:N,children:t.bucket==="entregado"?Number(t.valor_consignado)>=1?e.jsx("span",{style:{display:"inline-block",padding:"2px 8px",borderRadius:999,fontSize:11,fontWeight:700,color:"#15803D",background:"rgba(22,163,74,0.12)"},children:"Sí"}):e.jsx("span",{style:{display:"inline-block",padding:"2px 8px",borderRadius:999,fontSize:11,fontWeight:700,color:"#B45309",background:"rgba(217,119,6,0.12)"},children:"Pendiente"}):e.jsx("span",{style:{color:"var(--text-muted)"},children:"—"})}),e.jsx("td",{className:h,style:{...ae,color:(t.real_profit||0)>=0?"#15803D":"#B91C1C",fontWeight:700},children:oe(t.real_profit||0)})]},t.envios99_order_id))]})]})}),J>H&&e.jsxs("div",{style:{marginTop:14,display:"flex",alignItems:"center",justifyContent:"space-between",fontSize:12.5,color:"var(--text-secondary)"},children:[e.jsxs("div",{children:["Mostrando ",e.jsx("b",{children:R+1}),"–",e.jsx("b",{children:Math.min(R+H,J)})," de ",e.jsx("b",{children:J})]}),e.jsxs("div",{style:{display:"flex",gap:6},children:[e.jsx("button",{disabled:R===0,onClick:()=>pe(Math.max(0,R-H)),style:{...We,opacity:R===0?.4:1},children:"‹ Anterior"}),e.jsx("button",{disabled:R+H>=J,onClick:()=>pe(R+H),style:{...We,opacity:R+H>=J?.4:1},children:"Siguiente ›"})]})]})]})]}),ve&&e.jsx(Ae,{onClose:()=>q(!1),onConnected:()=>{q(!1),G(),U(),K()}})]})}function Ae({onClose:a,onConnected:i}){const u=Te(),[l,h]=n.useState(""),[f,x]=n.useState(""),[c,w]=n.useState(!1),[S,z]=n.useState(null),C=async()=>
2{if(z(null),!l.trim()||!f){z("Email y contraseña son obligatorios.");return}w(!0);try{const b=await u("/api/envios99/connect",{method:"POST",body:JSON.stringify({email:l.trim(),password:f})}),_=await b.json();if(!b.ok){z(_.message||_.error||"No se pudo conectar"),w(!1);return}i()}catch(b){z((b==null?void 0:b.message)||"Error de red"),w(!1)}};return e.jsxs(e.Fragment,{children:[e.jsx("div",{onClick:a,style:{position:"fixed",inset:0,zIndex:1e3,background:"rgba(0,0,0,0.55)"}}),e.jsxs("div",{onClick:b=>b.stopPropagation(),style:{position:"fixed",top:"50%",left:"50%",transform:"translate(-50%, -50%)",zIndex:1001,background:"var(--bg-card)",border:"1px solid var(--border)",borderRadius:14,padding:24,width:"min(480px, calc(100vw - 32px))",maxHeight:"85vh",overflowY:"auto",boxShadow:"0 20px 60px rgba(0,0,0,0.30)"},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12,marginBottom:14},children:[e.jsx(Oe,{size:32}),e.jsx("h2",{style:{fontSize:18,fontWeight:800,margin:0,color:"var(--text-primary)"},children:"Conectar 99envíos"})]}),e.jsxs("div",{style:{fontSize:13,color:"var(--text-secondary)",lineHeight:1.55,marginBottom:16},children:["Ingresa el ",e.jsx("strong",{children:"email + contraseña"})," con que entras a ",e.jsx("code",{style:{background:"rgba(0,0,0,0.05)",padding:"1px 4px",borderRadius:3},children:"99envios.app"}),". Hacemos login y guardamos un token de sesión cifrado en nuestra base."]}),e.jsxs("label",{style:{display:"block",marginBottom:12},children:[e.jsx("div",{style:{fontSize:11,fontWeight:700,color:"var(--text-secondary)",marginBottom:6},children:"Email 99envíos *"}),e.jsx("input",{type:"email",value:l,onChange:b=>h(b.target.value),placeholder:"[email protected]",autoFocus:!0,style:Le,disabled:c})]}),e.jsxs("label",{style:{display:"block",marginBottom:14},children:[e.jsx("div",{style:{fontSize:11,fontWeight:700,color:"var(--text-secondary)",marginBottom:6},children:"Contraseña *"}),e.jsx("input",{type:"password",value:f,onChange:b=>x(b.target.value),placeholder:"••••••••",style:Le,disabled:c,onKeyDown:b=>{b.key==="Enter"&&C()}})]}),S&&e.jsx("div",{style:{padding:"8px 10px",background:"rgba(239,68,68,0.08)",border:"1px solid #EF444440",borderRadius:6,fontSize:12,color:"#DC2626",marginBottom:12},children:S}),e.jsxs("div",{style:{display:"flex",gap:8,justifyContent:"flex-end"},children:[e.jsx("button",{onClick:a,style:{padding:"10px 16px",background:"transparent",color:"var(--text-secondary)",border:"1px solid var(--border)",borderRadius:8,fontSize:13,fontWeight:600,cursor:"pointer",fontFamily:"inherit"},children:"Cancelar"}),e.jsx("button",{onClick:C,disabled:c,style:{padding:"10px 18px",background:c?"#94A3B8":$,color:"#fff",border:"none",borderRadius:8,fontSize:13,fontWeight:700,cursor:c?"default":"pointer",fontFamily:"inherit",boxShadow:c?"none":`0 4px 14px ${$}40`},children:c?"Validando…":"Validar y conectar"})]})]})]})}function Rt({data:a}){const{en_proceso:i,diagnostics:u}=a,l=f=>new Intl.NumberFormat("es-CO",{style:"currency",currency:"COP",maximumFractionDigits:0}).format(f||0),h=f=>new Intl.NumberFormat("es-CO").format(f||0);return i.count===0?e.jsxs("div",{style:{background:"rgba(63,134,54,0.06)",border:"1px solid rgba(63,134,54,0.25)",borderRadius:12,padding:"16px 20px",marginBottom:20,display:"flex",alignItems:"center",gap:14},children:[e.jsx("div",{style:{fontSize:22,lineHeight:1,flexShrink:0,width:28,textAlign:"center"},children:"✅"}),e.jsxs("div",{style:{flex:1,minWidth:0},children:[e.jsx("div",{style:{fontSize:14,fontWeight:700,color:"#27500A",marginBottom:2},children:"Todos los pedidos del período están definidos"}),e.jsxs("div",{style:{fontSize:12,color:"var(--text-secondary)"},children:["Tus ",h(u.entregados_total)," entregas ya están pagadas. No hay pedidos pendientes con 99envíos."]})]})]}):e.jsx(Et,{emoji:"📦",bg:"rgba(59,130,246,0.06)",border:"rgba(59,130,246,0.30)",titleColor:"#1E40AF",title:i.count===1?`1 pedido en proceso — ${l(i.total)} por definir`:`${h(i.count)} pedidos en proceso — ${l(i.total)} por definir`,subtitle:"Pedidos no entregados ni devueltos todavía. Cuando 99envíos los defina, vas a saber cuánto recibes.",list:i.list,amountColor:"#1E40AF",toggleKey:"e99-proceso",showStatusInItem:!0})}function Bt({data:a}){const i=a.devoluciones_sin_seguro||{count:0,list:[]},u=a.pendientes.count>0?"pendientes":i.count>0?"devSinSeg":"pagadas",[l,h]=n.useState(u),f=z=>new Intl.NumberFormat("es-CO").format(z||0),{pagadas:x,pendientes:c,total_entregadas:w}=a,S=l==="pagadas"?x.list:l==="pendientes"?c.list:i.list;return c.count===0&&i.count===0&&x.count>0?e.jsxs("div",{style:{background:"rgba(63,134,54,0.06)",border:"1px solid rgba(63,134,54,0.25)",borderRadius:12,padding:"16px 20px",marginBottom:20,display:"flex",alignItems:"center",gap:14},children:[e.jsx("div",{style:{fontSize:22,lineHeight:1,flexShrink:0,width:28,textAlign:"center"},children:"💰"}),e.jsxs("div",{style:{flex:1,minWidth:0},children:[e.jsx("div",{style:{fontSize:14,fontWeight:700,color:"#27500A",marginBottom:2},children:"99envíos te pagó todas tus entregas"}),e.jsxs("div",{style:{fontSize:12,color:"var(--text-secondary)"},children:["Tus ",f(x.count)," entregas del período ya fueron consignadas. No hay nada pendiente."]})]})]}):e.jsxs("div",{style:{background:"var(--bg-card)",border:"1px solid var(--border)",borderRadius:12,padding:16,marginBottom:20},children:[e.jsxs("div",{style:{marginBottom:12},children:[e.jsx("h3",{style:{fontSize:14,fontWeight:700,color:"var(--text-primary)",margin:0},children:"💰 Balance con 99envíos"}),e.jsxs("div",{style:{fontSize:11,color:"var(--text-muted)",marginTop:2},children:["De ",f(w)," entregas: qué te pagaron, qué falta, y qué van a cobrarte por devoluciones sin seguro"]})]}),e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(min(180px, 100%), 1fr))",gap:10,marginBottom:14},children:[c.count>0&&e.jsxs("div",{onClick:()=>h("pendientes"),style:{background:l==="pendientes"?"rgba(245,158,11,0.10)":"var(--bg-tertiary)",border:`1px solid ${l==="pendientes"?"#F59E0B":"var(--border)"}`,borderRadius:8,padding:"12px 14px",cursor:"pointer"},children:[e.jsx("div",{style:{fontSize:10,fontWeight:700,color:"var(--text-muted)",textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:4},children:"⏳ 99envíos te debe"}),e.jsx("div",{style:{fontSize:26,fontWeight:800,color:"#92400E",fontVariantNumeric:"tabular-nums",lineHeight:1.1},children:f(c.count)}),e.jsx("div",{style:{fontSize:11,color:"var(--text-muted)",marginTop:4},children:c.count===1?"entrega sin consignar":"entregas sin consignar"})]}),i.count>0&&e.jsxs("div",{onClick:()=>h("devSinSeg"),style:{background:l==="devSinSeg"?"rgba(185,28,28,0.08)":"var(--bg-tertiary)",border:`1px solid ${l==="devSinSeg"?"#B91C1C":"var(--border)"}`,borderRadius:8,padding:"12px 14px",cursor:"pointer"},children:[e.jsx("div",{style:{fontSize:10,fontWeight:700,color:"var(--text-muted)",textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:4},children:"↩ Le debes a 99envíos"}),e.jsx("div",{style:{fontSize:26,fontWeight:800,color:"#B91C1C",fontVariantNumeric:"tabular-nums",lineHeight:1.1},children:f(i.count)}),e.jsx("div",{style:{fontSize:11,color:"var(--text-muted)",marginTop:4},children:i.count===1?"devolución sin seguro":"devoluciones sin seguro"})]}),x.count>0&&e.jsxs("div",{onClick:()=>h("pagadas"),style:{background:l==="pagadas"?"rgba(63,134,54,0.10)":"var(--bg-tertiary)",border:`1px solid ${l==="pagadas"?"#3F8636":"var(--border)"}`,borderRadius:8,padding:"12px 14px",cursor:"pointer"},children:[e.jsx("div",{style:{fontSize:10,fontWeight:700,color:"var(--text-muted)",textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:4},children:"✅ Ya te pagaron"}),e.jsx("div",{style:{fontSize:26,fontWeight:800,color:"#27500A",fontVariantNumeric:"tabular-nums",lineHeight:1.1},children:f(x.count)}
2),e.jsx("div",{style:{fontSize:11,color:"var(--text-muted)",marginTop:4},children:x.count===1?"entrega consignada":"entregas consignadas"})]})]}),S.length>0&&e.jsx(De,{items:S,toggleKey:`e99-balance-${l}`,amountColor:l==="pendientes"?"#92400E":l==="devSinSeg"?"#B91C1C":"#27500A",countLabel:`${S.length} ${S.length===1?"pedido":"pedidos"}`,showStatus:!1,hideAmounts:!0})]})}function De({items:a,toggleKey:i,amountColor:u,countLabel:l,showStatus:h=!1,hideAmounts:f=!1}){const x=`order_list_expanded_${i}`,[c,w]=n.useState(()=>{try{return localStorage.getItem(x)==="1"}catch{return!1}}),S=C=>new Intl.NumberFormat("es-CO",{style:"currency",currency:"COP",maximumFractionDigits:0}).format(C||0),z=()=>{w(C=>{const b=!C;try{localStorage.setItem(x,b?"1":"0")}catch{}return b})};return e.jsxs("div",{children:[e.jsx("div",{onClick:z,style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:10,padding:"8px 12px",background:"var(--bg-tertiary)",borderRadius:6,cursor:"pointer",userSelect:"none"},children:e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,minWidth:0},children:[e.jsx("span",{style:{fontSize:10,color:"var(--text-muted)",transition:"transform 200ms ease-out",transform:c?"rotate(90deg)":"rotate(0deg)",display:"inline-block",width:10},children:"▶"}),e.jsx("span",{style:{fontSize:12.5,fontWeight:600,color:"var(--text-primary)"},children:c?"Ocultar lista":"Ver lista"}),e.jsxs("span",{style:{fontSize:11,color:"var(--text-muted)"},children:["(",l,")"]})]})}),c&&e.jsx("div",{style:{display:"flex",flexDirection:"column",gap:4,marginTop:8,maxHeight:360,overflowY:"auto",paddingRight:4},children:a.map(C=>e.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",background:"var(--bg-tertiary)",borderRadius:6,padding:"8px 12px",gap:10},children:[e.jsxs("span",{className:"censor-blur",style:{fontWeight:800,color:"var(--text-primary)",fontSize:13,fontVariantNumeric:"tabular-nums"},title:`Buscalo en 99envíos con este ID: ${C.order_id}`,children:["#",C.order_id]}),!f&&e.jsx("span",{style:{fontWeight:700,color:u,fontVariantNumeric:"tabular-nums",whiteSpace:"nowrap",fontSize:13},children:S(C.amount)})]},C.order_id))})]})}function Et({emoji:a,bg:i,border:u,titleColor:l,title:h,subtitle:f,list:x,amountColor:c,toggleKey:w,showStatusInItem:S,hideAmounts:z}){return e.jsxs("div",{style:{background:i,border:`1px solid ${u}`,borderRadius:12,padding:"16px 20px",marginBottom:20},children:[e.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:14,marginBottom:12},children:[e.jsx("div",{style:{fontSize:30,lineHeight:1},children:a}),e.jsxs("div",{style:{flex:1,minWidth:0},children:[e.jsx("div",{style:{fontSize:14,fontWeight:700,color:l,marginBottom:4},children:h}),e.jsx("div",{style:{fontSize:12,color:"var(--text-secondary)"},children:f})]})]}),x.length>0&&e.jsx(De,{items:x,toggleKey:w,amountColor:c,countLabel:`${x.length} pedido${x.length===1?"":"s"}`,showStatus:S,hideAmounts:z})]})}const Le={width:"100%",padding:"10px 12px",background:"var(--bg-tertiary)",border:"1px solid var(--border)",borderRadius:8,fontSize:13,fontFamily:"inherit",color:"var(--text-primary)",outline:"none"};export{qt as Envios99Tab};

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.