PageSourceSearch

https://floraflor.lovable.app/assets/Finanzas-C5OMiDJS.js

js floraflor.lovable.app collected 2026-10-03 03:32:03 UTC 45,389 bytes, 19 lines download raw bytes

1import{n as ue,k as z,u as K,r as L,j as e,B as T,s as y,J as V,C as v,c as q,d as D,a as C,b as _,q as he,w as je,T as B,h as ee,e as Q,P as fe,l as R,ai as pe,a6 as ge,t as Ne}from"./index-RxDZGo8S.js";import{T as se,a as te,b as O,c as I}from"./tabs-Cxar0bnu.js";import{D as ae,a as oe,b as ne,c as re,e as be}from"./dialog-Kd5QqSd7.js";import{I as P}from"./input-CS9s6izM.js";import{L as S}from"./label-Fqe9mk9Y.js";import{S as ve,a as ye,b as Ce,c as we,d as _e}from"./select-B3f6lReZ.js";import{L as G}from"./loader-circle-CaA3DVt2.js";import{B as k}from"./badge-Kwp9j7fd.js";import{C as ie}from"./calendar-DWLwoYri.js";import{T as Se}from"./trash-2-DXjGIb-t.js";import{C as J}from"./credit-card-DWJIIm3_.js";import{T as W}from"./trending-down-11aaqO8-.js";import{S as ce}from"./switch-DlmmwpKa.js";import{C as Le}from"./chevron-up-DbNI7lUd.js";import{S as Y}from"./save-O8uKCrCu.js";import{T as Me}from"./triangle-alert-tJx7Lrdn.js";import{D as H}from"./dollar-sign-ByZbfka1.js";import{P as le,D as qe}from"./DashboardFinanzas-CM2-qv69.js";import{u as De,P as Fe}from"./usePullToRefresh-D5ecjpgO.js";import{R as Pe}from"./refresh-cw-DBr1zaJK.js";import{f as E}from"./format-DuJJlbci.js";import{s as X,e as Z}from"./startOfMonth-CgcY1Hmt.js";import{e as U}from"./es-DhgJzuV8.js";import"./index-BnR4gmtC.js";import"./index-Da3vg3Bj.js";import"./check-dsJNWiFz.js";import"./shopping-cart-CV1unszX.js";import"./endOfDay-CVKAevRd.js";import"./eye-CB4j9jLn.js";import"./addMonths-CtX9b_RZ.js";/**
2 * @license lucide-react v0.462.0 - ISC
3 *
4 * This source code is licensed under the ISC license.
5 * See the LICENSE file in the root directory of this source tree.
6 */const de=ue("Calculator",[["rect",{width:"16",height:"20",x:"4",y:"2",rx:"2",key:"1nb95v"}],["line",{x1:"8",x2:"16",y1:"6",y2:"6",key:"x4nwl0"}],["line",{x1:"16",x2:"16",y1:"14",y2:"18",key:"wjye3r"}],["path",{d:"M16 10h.01",key:"1m94wz"}],["path",{d:"M12 10h.01",key:"1nrarc"}],["path",{d:"M8 10h.01",key:"19clt8"}],["path",{d:"M12 14h.01",key:"1etili"}],["path",{d:"M8 14h.01",key:"6423bh"}],["path",{d:"M12 18h.01",key:"mhygvu"}],["path",{d:"M8 18h.01",key:"lrp35t"}]]),Te=[{value:1,label:"Enero"},{value:2,label:"Febrero"},{value:3,label:"Marzo"},{value:4,label:"Abril"},{value:5,label:"Mayo"},{value:6,label:"Junio"},{value:7,label:"Julio"},{value:8,label:"Agosto"},{value:9,label:"Septiembre"},{value:10,label:"Octubre"},{value:11,label:"Noviembre"},{value:12,label:"Diciembre"}];function $e({open:l,onOpenChange:j}){const{user:f}=z(),i=K(),[x,p]=L.useState(!1),r=new Date().getFullYear(),c=new Date().getMonth()+1,[m,s]=L.useState({mes:c,anio:r,monto:"",tarjeta:"",descripcion:"",categoria:""}),a=async n=>{if(n.preventDefault(),!!f){p(!0);try{const{error:g}=await y.from("gastos").insert({mes:m.mes,anio:m.anio,monto:parseFloat(m.monto),tarjeta:m.tarjeta,descripcion:m.descripcion,categoria:m.categoria||null,created_by:f.id});if(g)throw g;i.invalidateQueries({queryKey:["gastos"]}),j(!1),s({mes:c,anio:r,monto:"",tarjeta:"",descripcion:"",categoria:""})}catch(g){console.error("Error:",g),V.error("Error al agregar el gasto")}finally{p(!1)}}};return e.jsx(ae,{open:l,onOpenChange:j,children:e.jsxs(oe,{className:"max-w-md pb-24",children:[e.jsx(ne,{children:e.jsx(re,{children:"Agregar Gasto"})}),e.jsxs("form",{onSubmit:a,className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(S,{children:"Mes"}),e.jsxs(ve,{value:m.mes.toString(),onValueChange:n=>s({...m,mes:parseInt(n)}),children:[e.jsx(ye,{children:e.jsx(Ce,{})}),e.jsx(we,{children:Te.map(n=>e.jsx(_e,{value:n.value.toString(),children:n.label},n.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(S,{children:"Año"}),e.jsx(P,{type:"number",value:m.anio,onChange:n=>s({...m,anio:parseInt(n.target.value)}),required:!0})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(S,{children:"Monto"}),e.jsx(P,{type:"number",step:"0.01",value:m.monto,onChange:n=>s({...m,monto:n.target.value}),placeholder:"0.00",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(S,{children:"Tarjeta"}),e.jsx(P,{value:m.tarjeta,onChange:n=>s({...m,tarjeta:n.target.value}),placeholder:"Ej: Visa **1234",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(S,{children:"Descripción"}),e.jsx(P,{value:m.descripcion,onChange:n=>s({...m,descripcion:n.target.value}),placeholder:"¿Para qué fue el gasto?",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(S,{children:"Categoría (Opcional)"}),e.jsx(P,{value:m.categoria,onChange:n=>s({...m,categoria:n.target.value}),placeholder:"Ej: Transporte, Suministros, etc."})]}),e.jsxs("div",{className:"flex gap-3 pt-4",children:[e.jsx(T,{type:"button",variant:"outline",onClick:()=>j(!1),className:"flex-1",children:"Cancelar"}),e.jsxs(T,{type:"submit",disabled:x,className:"flex-1",children:[x&&e.jsx(G,{className:"mr-2 h-4 w-4 animate-spin"}),"Guardar"]})]})]})]})})}const Ve=["Ene","Feb","Mar","Abr","May","Jun","Jul","Ago","Sep","Oct","Nov","Dic"];function Ee({gastos:l,isLoading:j}){const[f,i]=L.useState(null),x=K(),p=async r=>{i(r);try{const{error:c}=await y.from("gastos").delete().eq("id",r);
6if(c)throw c;x.invalidateQueries({queryKey:["gastos"]})}catch(c){console.error("Error:",c),V.error("Error al eliminar el gasto")}finally{i(null)}};return j?e.jsx(v,{className:"p-8 flex items-center justify-center",children:e.jsx(G,{className:"h-8 w-8 animate-spin text-primary"})}):!l||l.length===0?e.jsx(v,{className:"p-8 text-center text-muted-foreground",children:"No hay gastos registrados"}):e.jsx("div",{className:"grid gap-4",children:l.map(r=>e.jsxs(v,{className:"hover:shadow-lg transition-shadow",children:[e.jsx(q,{className:"pb-3",children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(D,{className:"text-lg",children:r.descripcion}),e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(ie,{className:"h-4 w-4"}),e.jsxs("span",{children:[Ve[r.mes-1]," ",r.anio]})]})]}),e.jsx(T,{variant:"ghost",size:"sm",disabled:f===r.id,onClick:()=>p(r.id),className:"text-destructive hover:text-destructive hover:bg-destructive/10",children:f===r.id?e.jsx(G,{className:"h-4 w-4 animate-spin"}):e.jsx(Se,{className:"h-4 w-4"})})]})}),e.jsx(C,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx(J,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"font-medium",children:r.tarjeta})]}),r.categoria&&e.jsx(k,{variant:"outline",children:r.categoria})]}),e.jsxs("div",{className:"text-2xl font-bold text-primary",children:["$",Number(r.monto).toLocaleString("es-CL")]})]})})]},r.id))})}function ke({gastos:l}){const j=new Date().getMonth()+1,f=new Date().getFullYear(),i=l.reduce((r,c)=>r+Number(c.monto),0),x=l.filter(r=>r.mes===j&&r.anio===f).reduce((r,c)=>r+Number(c.monto),0),p=l.length>0?i/new Set(l.map(r=>`${r.anio}-${r.mes}`)).size:0;return e.jsxs("div",{className:"grid gap-4 md:grid-cols-3",children:[e.jsxs(v,{children:[e.jsxs(q,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(D,{className:"text-sm font-medium",children:"Total Gastado"}),e.jsx(W,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(C,{children:[e.jsxs("div",{className:"text-2xl font-bold",children:["$",i.toLocaleString("es-CL")]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Todos los períodos"})]})]}),e.jsxs(v,{children:[e.jsxs(q,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(D,{className:"text-sm font-medium",children:"Mes Actual"}),e.jsx(ie,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(C,{children:[e.jsxs("div",{className:"text-2xl font-bold",children:["$",x.toLocaleString("es-CL")]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Gastos de este mes"})]})]}),e.jsxs(v,{children:[e.jsxs(q,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(D,{className:"text-sm font-medium",children:"Promedio Mensual"}),e.jsx(J,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(C,{children:[e.jsxs("div",{className:"text-2xl font-bold",children:["$",Math.round(p).toLocaleString("es-CL")]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Gasto promedio por mes"})]})]})]})}function Ge(){const[l,j]=L.useState(!1),{data:f,isLoading:i}=_({queryKey:["gastos"],queryFn:async()=>{const{data:x,error:p}=await y.from("gastos").select("*").order("anio",{ascending:!1}).order("mes",{ascending:!1});if(p)throw p;return x}});return e.jsxs("div",{className:"space-y-6",children:[e.jsx("div",{className:"flex justify-between items-center",children:e.jsxs(T,{onClick:()=>j(!0),className:"flex items-center gap-2",children:[e.jsx(he,{className:"h-4 w-4"}),"Agregar Gasto"]})}),e.jsx(ke,{gastos:f||[]}),e.jsx(Ee,{gastos:f||[],isLoading:i}),e.jsx($e,{open:l,onOpenChange:j})]})}const Ae=["MercadoLibre","Shopify","WhatsApp","Instagram","Tienda Física","Otro"];function Ke({productos:l,isLoading:j}){const[f,i]=L.useState(null),[x,p]=L.useState({costo:"",cobraComisionVenta:!0,platformCommissions:{}}),[r,c]=L.useState(!1),m=K(),{user:s}=z(),{data:a}=_({queryKey:["comision-config",s==null?void 0:s.id],queryFn:async()=>
6{if(!(s!=null&&s.id))return null;const{data:h,error:b}=await y.from("comision_config").select("porcentaje_comision").eq("user_id",s.id).maybeSingle();if(b)throw b;return h},enabled:!!(s!=null&&s.id)}),n=(a==null?void 0:a.porcentaje_comision)||0,g=h=>{var b;if(f===h.id)i(null);else{i(h.id);const d={};h.platform_commissions&&Object.entries(h.platform_commissions).forEach(([N,w])=>{d[N]=w.toString()}),p({costo:((b=h.costo)==null?void 0:b.toString())||"",cobraComisionVenta:h.cobra_comision_venta!==!1,platformCommissions:d})}},t=async h=>{const b=parseFloat(x.costo)||0,d={};Object.entries(x.platformCommissions).forEach(([N,w])=>{const o=parseFloat(w);isNaN(o)||(d[N]=o)}),c(!0);try{if(h.esDelCatalogo&&h.catalogoId){const{error:N}=await y.from("catalogo_productos").update({costo:b,cobra_comision_venta:x.cobraComisionVenta,platform_commissions:d}).eq("id",h.catalogoId);if(N)throw N;m.invalidateQueries({queryKey:["catalogo-productos-costos"]})}else{const{error:N}=await y.from("boleta_productos").update({costo:b,cobra_comision_venta:x.cobraComisionVenta,platform_commissions:d}).eq("producto",h.producto);if(N)throw N}m.invalidateQueries({queryKey:["productos-boletas"]}),m.invalidateQueries({queryKey:["boletas-con-productos"]}),i(null)}catch(N){console.error("Error:",N),V.error("Error al actualizar los datos")}finally{c(!1)}};return j?e.jsx(v,{className:"p-8 flex items-center justify-center",children:e.jsx(G,{className:"h-8 w-8 animate-spin text-primary"})}):l.length===0?e.jsx(v,{className:"p-8 text-center text-muted-foreground",children:"No hay productos registrados"}):e.jsx("div",{className:"space-y-2",children:l.map(h=>{const b=f===h.id;return e.jsxs(v,{className:"overflow-hidden",children:[e.jsxs("div",{className:"p-4 flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"font-semibold text-lg",children:h.producto}),h.esDelCatalogo&&e.jsx(k,{variant:"default",className:"text-xs",children:"Catálogo"})]}),e.jsx(T,{size:"sm",variant:"outline",onClick:()=>g(h),children:b?e.jsxs(e.Fragment,{children:[e.jsx(Le,{className:"h-4 w-4 mr-2"}),"Cerrar"]}):e.jsxs(e.Fragment,{children:[e.jsx(je,{className:"h-4 w-4 mr-2"}),"Datos"]})})]}),b&&e.jsxs("div",{className:"border-t p-4 space-y-4 bg-muted/30",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground mb-1",children:"Precio de venta"}),e.jsxs("p",{className:"text-xl font-bold",children:["$",h.precio.toLocaleString("es-CL")]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(S,{htmlFor:`costo-${h.id}`,children:"Costo del Producto"}),e.jsx(P,{id:`costo-${h.id}`,type:"number",step:"0.01",placeholder:"0.00",value:x.costo,onChange:d=>p({...x,costo:d.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(S,{htmlFor:`comision-venta-${h.id}`,children:"Cobra Comisión de Venta"}),e.jsxs("div",{className:"flex items-center space-x-2 h-10",children:[e.jsx(ce,{id:`comision-venta-${h.id}`,checked:x.cobraComisionVenta,onCheckedChange:d=>p({...x,cobraComisionVenta:d})}),e.jsx("span",{className:"text-sm text-muted-foreground",children:x.cobraComisionVenta?`Sí (${n}%)`:"No"})]})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(S,{className:"text-base font-semibold",children:"Comisiones por Plataforma (%)"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Define el porcentaje de comisión que cobra cada plataforma"})]}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 gap-3",children:Ae.map(d=>e.jsxs("div",{className:"space-y-2",children:[e.jsx(S,{htmlFor:`platform-${h.id}-${d}`,className:"text-sm",children:d==="MercadoLibre"?"Mercado Libre":d}),e.jsx(P,{id:`platform-${h.id}-${d}`,type:"number",step:"0.1",placeholder:"0",min:"0",max:"100",value:x.platformCommissions[d]||"",onChange:N=>p({...x,platformCommissions:{...x.platformCommissions,[d]:N.target.value}})})]},d))})]}),e.jsx(T,{onClick:()=>t(h),disabled:r,className:"w-full",children:r?e.jsxs(e.Fragment,{children:[e.jsx(G,{className:"h-4 w-4 animate-spin mr-2"}),"Guardando..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Y,{className:"h-4 w-4 mr-2"}),"Guardar Cambios"]})})]})]}
6,h.id)})})}const Oe=["MercadoLibre","Shopify","WhatsApp","Instagram","Tienda Física","Otro"];function Ie({productosSinCosto:l}){const[j,f]=L.useState(!1),[i,x]=L.useState(0),[p,r]=L.useState(!1),c=K(),{user:m}=z(),{data:s}=_({queryKey:["comision-config",m==null?void 0:m.id],queryFn:async()=>{if(!(m!=null&&m.id))return null;const{data:d,error:N}=await y.from("comision_config").select("porcentaje_comision").eq("user_id",m.id).maybeSingle();if(N)throw N;return d},enabled:!!(m!=null&&m.id)}),a=(s==null?void 0:s.porcentaje_comision)||0,[n,g]=L.useState({costo:"",cobraComisionVenta:!0,platformCommissions:{}}),t=l[i],h=async()=>{if(!t)return;const d=parseFloat(n.costo)||0,N={};Object.entries(n.platformCommissions).forEach(([w,o])=>{const u=parseFloat(o);isNaN(u)||(N[w]=u)}),r(!0);try{const{error:w}=await y.from("boleta_productos").update({costo:d,cobra_comision_venta:n.cobraComisionVenta,platform_commissions:N}).eq("producto",t.nombre);if(w)throw w;V.success(`Producto "${t.nombre}" configurado`),c.invalidateQueries({queryKey:["productos-boletas"]}),c.invalidateQueries({queryKey:["boletas-con-productos"]}),c.invalidateQueries({queryKey:["productos-sin-costo"]}),g({costo:"",cobraComisionVenta:!0,platformCommissions:{}}),i<l.length-1?x(i+1):(f(!1),x(0))}catch(w){console.error("Error:",w),V.error("Error al configurar el producto")}finally{r(!1)}},b=()=>{g({costo:"",cobraComisionVenta:!0,platformCommissions:{}}),i<l.length-1?x(i+1):(f(!1),x(0))};return e.jsxs(ae,{open:j,onOpenChange:d=>{f(d),d||(x(0),g({costo:"",cobraComisionVenta:!0,platformCommissions:{}}))},children:[e.jsx(be,{asChild:!0,children:e.jsxs(T,{variant:"destructive",className:"gap-2",children:[e.jsx(Me,{className:"h-4 w-4"}),l.length," ",l.length===1?"Producto":"Productos"," sin Costo"]})}),e.jsxs(oe,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(ne,{children:e.jsxs(re,{children:["Configurar Productos sin Costo (",i+1,"/",l.length,")"]})}),t&&e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"bg-muted p-4 rounded-lg space-y-2",children:[e.jsx("h3",{className:"font-semibold text-lg",children:t.nombre}),e.jsxs("div",{className:"flex gap-4 text-sm",children:[e.jsxs(k,{variant:"outline",children:["Precio: $",t.precio.toLocaleString("es-CL")]}),e.jsxs(k,{variant:"outline",children:[t.apariciones," ",t.apariciones===1?"venta":"ventas"]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(S,{htmlFor:"costo",children:"Costo del Producto *"}),e.jsx(P,{id:"costo",type:"number",step:"0.01",placeholder:"0.00",value:n.costo,onChange:d=>g({...n,costo:d.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(S,{htmlFor:"comision-venta",children:"Cobra Comisión de Venta"}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(ce,{id:"comision-venta",checked:n.cobraComisionVenta,onCheckedChange:d=>g({...n,cobraComisionVenta:d})}),e.jsx("span",{className:"text-sm text-muted-foreground",children:n.cobraComisionVenta?`Sí (${a}%)`:"No"})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(S,{className:"text-base font-semibold",children:"Comisiones por Plataforma (%)"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Define el porcentaje de comisión que cobra cada plataforma (opcional)"})]}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 gap-3",children:Oe.map(d=>e.jsxs("div",{className:"space-y-2",children:[e.jsx(S,{htmlFor:`platform-${d}`,className:"text-sm",children:d==="MercadoLibre"?"Mercado Libre":d}),e.jsx(P,{id:`platform-${d}`,type:"number",step:"0.1",placeholder:"0",min:"0",max:"100",value:n.platformCommissions[d]||"",onChange:N=>g({...n,platformCommissions:{...n.platformCommissions,[d]:N.target.value}})})]},d))})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(T,{onClick:h,disabled:p||!n.costo,className:"flex-1",children:p?e.jsxs(e.Fragment,{children:[e.jsx(G,{className:"h-4 w-4 animate-spin mr-2"}),"Guardando..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Y,{className:"h-4 w-4 mr-2"}),"Guardar y Continuar"]})}),e.jsx(T,{onClick:b,variant:"outline",disabled:p,children:"Omitir"})]})]})]})]})}function Be(){const{data:l}=_({queryKey:["catalogo-productos-costos"],queryFn:async()=>{const{data:r,error:c}=await y.from("catalogo_productos").select("id, nombre, precio, costo, comision_porcentaje, platform_commissions, cobra_comision_venta");if(c)throw c;return r}}),{data:j,isLoading:f}=_({queryKey:["productos-boletas"],queryFn:async()=>{const{data:r,error:c}=await y.from("boleta_productos").select("id, producto, precio, costo, comision_porcentaje, platform_commissions, cobra_comision_venta").order("created_at",{ascending:!1});if(c)throw c;const m=(l==null?void 0:l.map(a=>a.nombre))||[],s=r.reduce((a,n)=>{if(!a[n.producto]){const g=m.includes(n.producto),t=l==null?void 0:l.find(h=>h.nombre===n.producto);a[n.producto]={id:n.id,producto:n.producto,precio:(t==null?void 0:t.precio)||n.precio,costo:(t==null?void 0:t.costo)||n.costo,comision_porcentaje:(t==null?void 0:t.comision_porcentaje)||n.comision_porcentaje,platform_commissions:(t==null?void 0:t.platform_commissions)||n.platform_commissions||{},cobra_comision_venta:t?t.cobra_comision_venta!==!1:n.cobra_comision_venta!==!1,esDelCatalogo:g,catalogoId:t==null?void 0:t.id}}return a},{});return Object.values(s)},enabled:!!l}),{data:i}=_({queryKey:["catalogo-productos-nombres"],queryFn:async()=>{const{data:r,error:c}=await y.from("catalogo_productos").select("nombre");if(c)throw c;return r.map(m=>m.nombre)}}),{data:x}=_({queryKey:["productos-sin-costo"],queryFn:async()=>{const{data:r,error:c}=await y.from("boleta_productos").select("producto, precio, costo");if(c)throw c;const m=r.reduce((s,a)=>(s[a.producto]||(s[a.producto]={nombre:a.producto,precio:a.precio,apariciones:0,tieneCosto:a.costo&&a.costo>0}),s[a.producto].apariciones+=1,a.costo&&a.costo>0&&(s[a.producto].tieneCosto=!0),s),{});return Object.values(m)}}),p=(x==null?void 0:x.filter(r=>{const c=!r.tieneCosto,m=!(i!=null&&i.includes(r.nombre));return c&&m}))||[];return e.jsxs("div",{className:"space-y-6",children:[p.length>0&&e.jsx("div",{className:"flex justify-end",children:e.jsx(Ie,{productosSinCosto:p})}),e.jsx(Ke,{productos:j||[],isLoading:f})]})}function Qe({boletas:l}){const{user:j}=z(),{data:f}=_({queryKey:["comision-config",j==null?void 0:j.id],queryFn:async()=>
6{if(!(j!=null&&j.id))return null;const{data:s,error:a}=await y.from("comision_config").select("porcentaje_comision").eq("user_id",j.id).maybeSingle();if(a)throw a;return s},enabled:!!(j!=null&&j.id)}),i=(f==null?void 0:f.porcentaje_comision)||0,x=l.reduce((s,a)=>{var g;const n=a.plataforma||"Sin plataforma";return s[n]||(s[n]={totalVentas:0,totalCostos:0,totalComisiones:0,cantidad:0}),(g=a.boleta_productos)==null||g.forEach(t=>{const b=(t.platform_commissions||{})[a.plataforma]||0,d=t.cobra_comision_venta!==!1?i:0,N=b+d,w=t.precio*N/100;s[n].totalVentas+=t.precio,s[n].totalCostos+=t.costo||0,s[n].totalComisiones+=w,s[n].cantidad+=1}),s},{}),p=l.reduce((s,a)=>{var g;const n=a.plataforma||"";return(g=a.boleta_productos)==null||g.forEach(t=>{s[t.producto]||(s[t.producto]={nombre:t.producto,ventas:0,totalVentas:0,totalCostos:0,totalComisiones:0,precio:t.precio,costo:t.costo||0,comision:t.comision_porcentaje||0,platformCommissions:t.platform_commissions||{},ventasPorPlataforma:{},ventasPorPrecio:{}}),s[t.producto].ventasPorPlataforma[n]||(s[t.producto].ventasPorPlataforma[n]=0),s[t.producto].ventasPorPlataforma[n]+=1,s[t.producto].ventasPorPrecio[t.precio]||(s[t.producto].ventasPorPrecio[t.precio]=0),s[t.producto].ventasPorPrecio[t.precio]+=1;const b=(t.platform_commissions||{})[n]||0,d=t.cobra_comision_venta!==!1?i:0,N=b+d,w=t.precio*N/100;s[t.producto].ventas+=1,s[t.producto].totalVentas+=t.precio,s[t.producto].totalCostos+=t.costo||0,s[t.producto].totalComisiones+=w}),s},{}),r=Object.values(p).sort((s,a)=>{const n=s.totalVentas-s.totalCostos-s.totalComisiones;return a.totalVentas-a.totalCostos-a.totalComisiones-n}),c=r.reduce((s,a)=>{const n=a.totalVentas-a.totalCostos-a.totalComisiones;return{ventas:s.ventas+a.totalVentas,costos:s.costos+a.totalCostos,comisiones:s.comisiones+a.totalComisiones,ganancia:s.ganancia+n}},{ventas:0,costos:0,comisiones:0,ganancia:0}),m=c.ventas>0?(c.ganancia/c.ventas*100).toFixed(1):0;return r.length===0?e.jsx(v,{className:"p-8 text-center text-muted-foreground",children:"No hay datos para el mes seleccionado"}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-semibold mb-4",children:"Ventas por Plataforma"}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:Object.entries(x).map(([s,a])=>{const n=a.totalVentas-a.totalCostos-a.totalComisiones;return e.jsxs(v,{children:[e.jsx(q,{className:"pb-2",children:e.jsx(D,{className:"text-sm font-medium",children:s})}),e.jsxs(C,{className:"space-y-2",children:[e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Unidades:"}),e.jsx("span",{className:"font-semibold",children:a.cantidad})]}),e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Ventas:"}),e.jsxs("span",{className:"font-semibold",children:["$",a.totalVentas.toLocaleString("es-CL")]})]}),e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Ganancia:"}),e.jsxs("span",{className:`font-semibold ${n>=0?"text-green-600":"text-red-600"}`,children:["$",n.toLocaleString("es-CL")]})]})]})]},s)})})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-4 gap-4",children:[e.jsxs(v,{children:[e.jsx(q,{className:"pb-2",children:e.jsxs(D,{className:"text-sm font-medium text-muted-foreground flex items-center gap-2",children:[e.jsx(H,{className:"h-4 w-4"}),"Total Ventas"]})}),e.jsx(C,{children:e.jsxs("p",{className:"text-2xl font-bold",children:["$",c.ventas.toLocaleString("es-CL")]})})]}),e.jsxs(v,{children:[e.jsx(q,{className:"pb-2",children:e.jsxs(D,{className:"text-sm font-medium text-muted-foreground flex items-center gap-2",children:[e.jsx(W,{className:"h-4 w-4"}),"Total Costos"]})}),e.jsx(C,{children:e.jsxs("p",{className:"text-2xl font-bold text-red-600",children:["$",c.costos.toLocaleString("es-CL")]})})]}),e.jsxs(v,{children:[e.jsx(q,{className:"pb-2",children:e.jsxs(D,{className:"text-sm font-medium text-muted-foreground flex items-center gap-2",children:[e.jsx(le,{className:"h-4 w-4"}),"Comisiones"]})}),e.jsx(C,{children:e.jsxs("p",{className:"text-2xl font-bold text-orange-600",children:["$",c.comisiones.toLocaleStr
6ing("es-CL")]})})]}),e.jsxs(v,{children:[e.jsx(q,{className:"pb-2",children:e.jsxs(D,{className:"text-sm font-medium text-muted-foreground flex items-center gap-2",children:[e.jsx(B,{className:"h-4 w-4"}),"Ganancia Neta"]})}),e.jsxs(C,{children:[e.jsxs("p",{className:"text-2xl font-bold text-green-600",children:["$",c.ganancia.toLocaleString("es-CL")]}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:["Margen: ",m,"%"]})]})]})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-semibold mb-4",children:"Ganancias por Producto"}),e.jsx("div",{className:"space-y-3",children:Object.values(p).map(s=>{const a=s.totalVentas-s.totalCostos-s.totalComisiones,n=s.totalVentas>0?(a/s.totalVentas*100).toFixed(1):0,g=Object.keys(s.ventasPorPrecio),t=g.length>1;return e.jsxs(v,{className:"p-4",children:[e.jsxs("div",{className:"flex justify-between items-start mb-3",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"font-semibold",children:s.nombre}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[s.ventas," ",s.ventas===1?"venta":"ventas",t&&e.jsxs("span",{className:"ml-2 text-xs",children:["(vendido a ",g.length," precios diferentes)"]})]}),t&&e.jsx("div",{className:"flex flex-wrap gap-2 mt-2",children:Object.entries(s.ventasPorPrecio).map(([h,b])=>e.jsxs(k,{variant:"outline",className:"text-xs",children:[b,"x a $",Number(h).toLocaleString("es-CL")]},h))}),e.jsx("div",{className:"flex flex-wrap gap-2 mt-2",children:Object.entries(s.ventasPorPlataforma).map(([h,b])=>e.jsxs(k,{variant:"outline",className:"text-xs",children:[h,": ",b]},h))})]}),e.jsxs(k,{variant:Number(n)>=30?"default":Number(n)>=15?"secondary":"destructive",children:["Margen: ",n,"%"]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-3 text-sm",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground text-xs",children:"Ventas"}),e.jsxs("p",{className:"font-semibold",children:["$",s.totalVentas.toLocaleString("es-CL")]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground text-xs",children:"Costos"}),e.jsxs("p",{className:"font-semibold text-red-600",children:["-$",s.totalCostos.toLocaleString("es-CL")]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground text-xs",children:"Comisiones Totales"}),e.jsxs("p",{className:"font-semibold text-orange-600",children:["-$",s.totalComisiones.toLocaleString("es-CL")]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground text-xs",children:"Ganancia Neta"}),e.jsxs("p",{className:`font-semibold ${a>=0?"text-green-600":"text-red-600"}`,children:["$",a.toLocaleString("es-CL")]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground text-xs",children:"Por Unidad"}),e.jsxs("p",{className:"font-semibold",children:["$",(a/s.ventas).toLocaleString("es-CL")]})]})]})]},s.nombre)})})]})]})}function ze(){const[l,j]=L.useState(()=>{const r=new Date;return`${r.getFullYear()}-${String(r.getMonth()+1).padStart(2,"0")}`}),{data:f}=_({queryKey:["catalogo-productos-costos"],queryFn:async()=>{const{data:r,error:c}=await y.from("catalogo_productos").select("nombre, costo, comision_porcentaje, platform_commissions, cobra_comision_venta");if(c)throw c;return r}}),{data:i,isLoading:x}=_({queryKey:["boletas-con-productos"],queryFn:async()=>{const{data:r,error:c}=await y.from("boletas").select(`
7          id,
8          fecha_venta,
9          plataforma,
10          boleta_productos(id, producto, precio, costo, comision_porcentaje, platform_commissions, cobra_comision_venta)
11        `).order("fecha_venta",{ascending:!1});if(c)throw c;return r.map(m=>({...m,boleta_productos:m.boleta_productos.map(s=>{const a=f==null?void 0:f.find(n=>n.nombre===s.producto);return{...s,costo:(a==null?void 0:a.costo)||s.costo,comision_porcentaje:(a==null?void 0:a.comision_porcentaje)||s.comision_porcentaje,platform_commissions:(a==null?void 0:a.platform_commissions)||s.platform_commissions||{},cobra_comision_venta:a?a.cobra_comision_venta!==!1:s.cobra_comision_venta!==!1}})}))},enabled:!!f}),p=i==null?void 0:i.filter(r=>r.fecha_venta.substring(0,7)===l);return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("label",{className:"text-sm font-medium",children:"Mes:"}
11),e.jsx("input",{type:"month",value:l,onChange:r=>j(r.target.value),className:"px-3 py-2 border rounded-md text-sm"})]}),x?e.jsx(v,{className:"p-8 text-center",children:e.jsx("p",{className:"text-muted-foreground",children:"Cargando..."})}):e.jsx(Qe,{boletas:p||[]})]})}function Re(){const[l,j]=L.useState(E(new Date,"yyyy-MM")),f=K(),{data:i}=_({queryKey:["currentUser"],queryFn:async()=>{const{data:{user:o}}=await y.auth.getUser();return o}}),{data:x}=_({queryKey:["comisionConfig",i==null?void 0:i.id],enabled:!!(i!=null&&i.id),queryFn:async()=>{const{data:o,error:u}=await y.from("comision_config").select("*").eq("user_id",i.id).maybeSingle();if(u)throw u;return o}}),p=(x==null?void 0:x.porcentaje_comision)||10,r=(x==null?void 0:x.porcentaje_descuento)||0,{data:c,isLoading:m,refetch:s}=_({queryKey:["meli-orders-month",l],queryFn:async()=>{const o=X(new Date(l+"-01")),u=Z(new Date(l+"-01"));console.log("Fetching ML orders for:",{startDate:o,endDate:u});try{const{data:$,error:A}=await y.functions.invoke("meli-api",{body:{action:"sync-orders",startDate:o.toISOString(),endDate:u.toISOString()}});A?(console.error("Error fetching from ML API:",A),V.error("Error al obtener pedidos de Mercado Libre")):console.log("Orders synced:",$)}catch($){console.error("ML API call failed:",$)}const{data:M,error:F}=await y.from("meli_orders").select("*").gte("purchase_date",o.toISOString()).lte("purchase_date",u.toISOString());if(F)throw F;return console.log("Orders from DB:",(M==null?void 0:M.length)||0),M},enabled:!!l,refetchOnWindowFocus:!1,refetchOnMount:!0,staleTime:5*60*1e3}),{data:a,isLoading:n}=_({queryKey:["meli-boletas-month",l],queryFn:async()=>{const o=X(new Date(l+"-01")),u=Z(new Date(l+"-01")),{data:M,error:F}=await y.from("boletas").select(`
12          *,
13          boleta_productos (
14            id,
15            producto,
16            precio,
17            costo
18          )
19        `).eq("plataforma","Mercado Libre").gte("fecha_venta",E(o,"yyyy-MM-dd")).lte("fecha_venta",E(u,"yyyy-MM-dd"));if(F)throw F;return M},enabled:!!l}),{data:g}=_({queryKey:["meli-commission-calculations"],enabled:!!(i!=null&&i.id),queryFn:async()=>{const{data:o,error:u}=await y.from("meli_commission_calculations").select("*").eq("user_id",i.id).order("month_period",{ascending:!1});if(u)throw u;return o}}),t={totalSales:(c==null?void 0:c.reduce((o,u)=>o+Number(u.total_amount),0))||0,totalCosts:(a==null?void 0:a.reduce((o,u)=>{var F;const M=((F=u.boleta_productos)==null?void 0:F.reduce(($,A)=>$+(Number(A.costo)||0),0))||0;return o+M},0))||0,ordersCount:(c==null?void 0:c.length)||0},b=t.totalSales*(1-r/100)-t.totalCosts,d=b*(p/100),N=ee({mutationFn:async()=>{if(!(i!=null&&i.id))throw new Error("Usuario no autenticado");const{error:o}=await y.from("meli_commission_calculations").upsert({user_id:i.id,month_period:l,total_sales:t.totalSales,total_costs:t.totalCosts,commission_amount:d,commission_percentage:p,orders_count:t.ordersCount},{onConflict:"user_id,month_period"});if(o)throw o},onSuccess:()=>{f.invalidateQueries({queryKey:["meli-commission-calculations"]})},onError:o=>{V.error(`Error al guardar: ${o.message}`)}}),w=g==null?void 0:g.find(o=>o.month_period===l);return e.jsxs("div",{className:"space-y-6",children:[e.jsxs(v,{children:[e.jsxs(q,{children:[e.jsxs(D,{className:"flex items-center gap-2",children:[e.jsx(de,{className:"h-5 w-5"}),"Calculadora de Comisión Mercado Libre"]}),e.jsx(Q,{children:"Calcula la comisión a cobrar basada en las ventas del mes"})]}),e.jsxs(C,{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-1 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(S,{htmlFor:"month",children:"Mes a calcular"}),e.jsx(P,{id:"month",type:"month",value:l,onChange:o=>j(o.target.value),max:E(new Date,"yyyy-MM")})]}),e.jsxs("div",{className:"flex gap-4 p-4 bg-muted rounded-lg",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Descuento"}),e.jsxs("p",{className:"text-lg font-semibold",children:[r,"%"]})]}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Comisión"}),e.jsxs("p",{className:"text-lg font-semibold",children:[p,"%"]})]})]})]}),m?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"Obteniendo pedidos de Mercado Libre..."}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsx(v,{className:"bg-blue-50 dark:bg-blue-950",children:e.jsxs(C,{className:"pt-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Total Ventas ML"}),e.jsxs("p",{className:"text-2xl font-bold",children:["$",t.totalSales.toLocaleStr
19ing("es-CL")]})]}),e.jsx(H,{className:"h-8 w-8 text-blue-600"})]}),e.jsxs("div",{className:"mt-2 text-xs text-muted-foreground",children:[e.jsx(fe,{className:"h-3 w-3 inline mr-1"}),t.ordersCount," pedidos"]})]})}),e.jsx(v,{className:"bg-orange-50 dark:bg-orange-950",children:e.jsxs(C,{className:"pt-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Descuento (",r,"%)"]}),e.jsxs("p",{className:"text-2xl font-bold text-orange-600",children:["-$",(t.totalSales*(r/100)).toLocaleString("es-CL")]})]}),e.jsx(B,{className:"h-8 w-8 text-orange-600"})]}),e.jsx("div",{className:"mt-2 text-xs text-muted-foreground",children:"Descuento configurado"})]})}),e.jsx(v,{className:"bg-purple-50 dark:bg-purple-950",children:e.jsxs(C,{className:"pt-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Costos Programados"}),e.jsxs("p",{className:"text-2xl font-bold text-purple-600",children:["-$",t.totalCosts.toLocaleString("es-CL")]})]}),e.jsx(B,{className:"h-8 w-8 text-purple-600"})]}),e.jsx("div",{className:"mt-2 text-xs text-muted-foreground",children:"De boletas de Mercado Libre"})]})}),e.jsx(v,{className:"bg-green-50 dark:bg-green-950",children:e.jsxs(C,{className:"pt-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Monto Neto"}),e.jsxs("p",{className:"text-2xl font-bold text-green-600",children:["$",b.toLocaleString("es-CL")]})]}),e.jsx(H,{className:"h-8 w-8 text-green-600"})]}),e.jsx("div",{className:"mt-2 text-xs text-muted-foreground",children:"Ventas - Costos"})]})}),e.jsx(v,{className:"bg-indigo-50 dark:bg-indigo-950 border-2 border-indigo-200",children:e.jsxs(C,{className:"pt-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-muted-foreground",children:"Comisión a Cobrar"}),e.jsxs("p",{className:"text-3xl font-bold text-indigo-600",children:["$",d.toLocaleString("es-CL")]})]}),e.jsx(le,{className:"h-8 w-8 text-indigo-600"})]}),e.jsxs("div",{className:"mt-2 text-xs text-muted-foreground",children:[p,"% sobre $",b.toLocaleString("es-CL")," neto"]})]})})]}),e.jsxs("div",{className:"flex justify-end gap-2 items-center",children:[e.jsxs(T,{onClick:()=>s(),variant:"outline",size:"sm",children:[e.jsx(Pe,{className:"h-4 w-4 mr-2"}),"Actualizar Pedidos"]}),w&&e.jsxs(k,{variant:"outline",className:"text-green-600",children:["Guardado el ",E(new Date(w.created_at),"dd/MM/yyyy HH:mm")]}),e.jsxs(T,{onClick:()=>N.mutate(),disabled:N.isPending||t.ordersCount===0,children:[e.jsx(Y,{className:"h-4 w-4 mr-2"}),N.isPending?"Guardando...":"Guardar Cálculo"]})]})]})]})]}),g&&g.length>0&&e.jsxs(v,{children:[e.jsxs(q,{children:[e.jsx(D,{children:"Historial de Cálculos"}),e.jsx(Q,{children:"Cálculos de comisiones guardados anteriormente"})]}),e.jsx(C,{children:e.jsx("div",{className:"space-y-3",children:g.map(o=>e.jsxs("div",{className:"flex items-center justify-between p-4 border rounded-lg",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"font-semibold",children:E(new Date(o.month_period+"-01"),"MMMM yyyy",{locale:require("date-fns/locale/es")})}),e.jsxs("div",{className:"text-sm text-muted-foreground mt-1",children:[e.jsxs("span",{children:[o.orders_count," pedidos"]}),e.jsx("span",{className:"mx-2",children:"•"}),e.jsxs("span",{children:["$",Number(o.total_sales).toLocaleString("es-CL")," ventas"]}),e.jsx("span",{className:"mx-2",children:"•"}),e.jsxs("span",{children:["$",Number(o.total_costs).toLocaleString("es-CL")," costos"]})]})]}),e.jsxs("div",{className:"text-right",children:[e.jsxs("p",{className:"text-lg font-bold text-purple-600",children:["$",Number(o.commission_amount).toLocaleString("es-CL")]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[Number(o.commission_percentage),"% comisión"]})]})]},o.id))})})]})]})}function He(){const l=K(),[j,f]=L.useState(0),[i,x]=L.useState(0),[p,r]=L.useState(!1),[c,m]=L.useState("general"),{data:s}=_({queryKey:["currentUser"],queryFn:async()=>{const{data:{user:o}}=await y.auth.getUser();return o}}),{data:a,isLoading:n}=_({queryKey:["comisionConfig",s==null?void 0:s.id],enabled:!!(s!=null&&s.id),queryFn:async()=>{const{data:o,error:u}=await y.from("comision_config").select("*").eq("user_id",s.id).maybeSingle();if(u)throw u;return o&&(f(Number(o.porcentaje_comision)),x(Number(o.porcentaje_descuento))),o}}),{data:g,isLoading:t}=_({queryKey:["boletas"],queryFn:async()=>{const{data:o,error:u}=await y.from("boletas").select("*, boleta_productos (id, producto, precio)").order("fecha_venta",{ascending:!1});if(u)throw u;return o}}),h=g?Object.entries(g.reduce((o,u)=>{var A;
19const M=E(new Date(u.fecha_venta),"yyyy-MM",{locale:U}),F=E(new Date(u.fecha_venta),"MMMM yyyy",{locale:U});o[M]||(o[M]={month:F,totalBoletado:0,totalDescuento:0,totalNeto:0,comision:0});const $=((A=u.boleta_productos)==null?void 0:A.reduce((me,xe)=>me+Number(xe.precio),0))||0;return o[M].totalBoletado+=$,o},{})).sort(([o],[u])=>u.localeCompare(o)).map(([o,u])=>{const M=u.totalBoletado*(Number(i)/100),F=u.totalBoletado-M,$=F*(Number(j)/100);return{...u,totalDescuento:M,totalNeto:F,comision:$}}):[],b=ee({mutationFn:async()=>{if(!(s!=null&&s.id))throw new Error("No user");const o={user_id:s.id,porcentaje_comision:j,porcentaje_descuento:i};if(a){const{error:u}=await y.from("comision_config").update(o).eq("id",a.id);if(u)throw u}else{const{error:u}=await y.from("comision_config").insert(o);if(u)throw u}},onSuccess:()=>{l.invalidateQueries({queryKey:["comisionConfig"]}),V.success("Configuración guardada"),r(!1)},onError:()=>V.error("Error al guardar configuración")});if(n||t||!s)return e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(G,{className:"h-6 w-6 animate-spin text-primary"})});const d=o=>new Intl.NumberFormat("es-CL",{style:"currency",currency:"CLP",minimumFractionDigits:0}).format(o),N=h.reduce((o,u)=>o+u.totalBoletado,0),w=h.reduce((o,u)=>o+u.comision,0);return e.jsx("div",{className:"space-y-6",children:e.jsxs(se,{value:c,onValueChange:o=>m(o),children:[e.jsxs(te,{className:"grid w-full grid-cols-2",children:[e.jsxs(O,{value:"general",children:[e.jsx(B,{className:"h-4 w-4 mr-2"}),"Comisiones Generales"]}),e.jsxs(O,{value:"mercadolibre",children:[e.jsx(de,{className:"h-4 w-4 mr-2"}),"Mercado Libre"]})]}),e.jsxs(I,{value:"general",className:"mt-6 space-y-6",children:[e.jsxs(v,{children:[e.jsxs(q,{children:[e.jsx(D,{children:"Configuración de Comisiones"}),e.jsx(Q,{children:"Define los porcentajes de comisión y descuento"})]}),e.jsxs(C,{children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4 mb-4",children:[e.jsxs("div",{children:[e.jsx(S,{htmlFor:"comision",children:"Porcentaje de Comisión (%)"}),e.jsx(P,{id:"comision",type:"number",min:"0",max:"100",step:"0.01",value:j,onChange:o=>{f(Number(o.target.value)),r(!0)},className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(S,{htmlFor:"descuento",children:"Porcentaje de Descuento (%)"}),e.jsx(P,{id:"descuento",type:"number",min:"0",max:"100",step:"0.01",value:i,onChange:o=>{x(Number(o.target.value)),r(!0)},className:"mt-1"})]})]}),p&&e.jsx(T,{onClick:()=>b.mutate(),disabled:b.isPending,children:b.isPending?e.jsxs(e.Fragment,{children:[e.jsx(G,{className:"mr-2 h-4 w-4 animate-spin"}),"Guardando..."]}):"Guardar Configuración"})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs(v,{children:[e.jsx(q,{className:"pb-3",children:e.jsx(D,{className:"text-lg",children:"Total Boletado"})}),e.jsx(C,{children:e.jsx("p",{className:"text-3xl font-bold text-primary",children:d(N)})})]}),e.jsxs(v,{children:[e.jsx(q,{className:"pb-3",children:e.jsxs(D,{className:"text-lg flex items-center gap-2",children:[e.jsx(B,{className:"h-5 w-5 text-green-600"}),"Total Comisión"]})}),e.jsx(C,{children:e.jsx("p",{className:"text-3xl font-bold text-green-600",children:d(w)})})]})]}),e.jsxs(v,{children:[e.jsxs(q,{children:[e.jsx(D,{children:"Ventas por Mes"}),e.jsx(Q,{children:"Todo lo boleteado mes a mes"})]}),e.jsx(C,{children:h.length===0?e.jsx("p",{className:"text-muted-foreground text-center py-8",children:"No hay boletas registradas"}):e.jsx("div",{className:"space-y-4",children:h.map((o,u)=>e.jsxs("div",{className:"border rounded-lg p-4 hover:bg-accent/50 transition-colors",children:[e.jsx("h3",{className:"font-semibold text-lg mb-3 capitalize",children:o.month}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4 text-sm",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground",children:"Total Boletado"}),e.jsx("p",{className:"font-semibold text-lg",children:d(o.totalBoletado)})]}),e.jsxs("div",{children:[e.jsxs("p",{className:"text-muted-foreground",children:["Descuento (",i,"%)"]}),e.jsxs("p",{className:"font-semibold text-lg text-orange-600",children:["-",d(o.totalDescuento)]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground",children:"Neto"}),e.jsx("p",{className:"font-semibold text-lg",children:d(o.totalNeto)})]}),e.jsxs("div",{children:[e.jsxs("p",{className:"text-muted-foreground",children:["Comisión (",j,"%)"]}),e.jsx("p",{className:"font-semibold text-lg text-green-600",children:d(o.comision)})]})]})]},u))})})]})]}),e.jsx(I,{value:"mercadolibre",className:"mt-6",children:e.jsx(Re,{})})]})})}function ws(){const l=R("finanzas"),j=R("gastos"),f=R("costos"),i=K(),{isRefreshing:x,pullDistance:p}=De({onRefresh:async()=>{await i.invalidateQueries({queryKey:["catalogo-productos-costos"]}),await i.invalidateQueries({queryKey:["productos-boletas"]}),await i.invalidateQueries({queryKey:["boletas-con-productos"]}),await i.invalidateQueries({queryKey:["gastos"]}),await i.invalidateQueries({queryKey:["boletas"]})},threshold:60});return l?e.jsxs(e.Fragment,{children:[e.jsx(Fe,{isRefreshing:x,pullDistance:p,threshold:60}),e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-background via-background to-primary/5 pb-24",children:e.jsxs("div",{className:"w-full px-4 py-8",children:[e.jsxs("div",{className:"mb-8",children:[e.jsx("h1",{className:"text-4xl font-bold bg-gradient-to-r from-primary to-primary/60 bg-clip-text text-transparent",children:"Finanzas"}),e.jsx("p",{className:"text-muted-foreground mt-2",children:"Gestiona ventas, gastos, costos y comisiones"})]}),e.jsxs(se,{defaultValue:"resumen",className:"w-full",children:[e.jsxs(te,{className:"grid w-full grid-cols-4 mb-8",children:[e.jsxs(O,{value:"resumen",className:"flex items-center gap-2",children:[e.jsx(ge,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Resumen"})]}),f&&e.jsxs(O,{value:"costos",className:"flex items-center gap-2",children:[e.jsx(W,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Costos"})]}),j&&e.jsxs(O,{value:"gastos",className:"flex items-center gap-2",children:[e.jsx(J,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Gastos"})]}),e.jsxs(O,{value:"comisiones",className:"flex items-center gap-2",children:[e.jsx(B,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Comisiones"})]})]}),e.jsx(I,{value:"resumen",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(qe,{}),e.jsx(ze,{})]})}),f&&e.jsx(I,{value:"costos",children:e.jsx(Be,{})}),j&&e.jsx(I,{value:"gastos",children:e.jsx(Ge,{})}),e.jsx(I,{value:"comisiones",children:e.jsx(He,{})})]})]})}),e.jsx(Ne,{})]}):e.jsx(pe,{to:"/",replace:!0})}export{ws 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.