1(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[517],{5921:function(e,s,a){(window.__NEXT_P=window.__NEXT_P||[]).push(["/veterinarios",function(){return a(8104)}])},8104:function(e,s,a){"use strict";a.r(s),a.d(s,{default:function(){return Q}});var n=a(5893),i=a(7294),t=a(3148),l=a(1163),r=a(9529),o=a(9072),d=a(699),c=a(5660),u=a(3879),m=a(6147),x=a(6540),h=a(610);async function g(e){let s=await fetch(e,{headers:await (0,h.us)()});if(401===s.status)return window.location.href="/login?reason=session_expired",null;let a=await s.json().catch(()=>({}));if(!s.ok)throw j(Error(a.error||"".concat(s.status)),a);return a}async function p(e,s,a){let n=await fetch(e,{method:s,headers:await (0,h.us)(),body:a?JSON.stringify(a):void 0}),i=await n.json().catch(()=>({}));if(!n.ok)throw j(Error(i.error||"".concat(n.status)),i);return i}function j(e,s){return e.needsSchema=!!s.needs_schema,e.missingScope=s.missing_scope,e}let b=e=>null==e||""===e?"â":"".concat((Number(e)/100).toLocaleString("es-ES",{minimumFractionDigits:2,maximumFractionDigits:2})," â¬"),v=e=>null==e||""===e?"â":"".concat(Math.round(Number(e)/100).toLocaleString("es-ES")," â¬"),y=e=>null==e?"â":Number(e).toLocaleString("es-ES"),f=e=>null==e?"â":"".concat(Number(e).toLocaleString("es-ES",{maximumFractionDigits:2})," %"),_=e=>{if(!e)return"â";try{return new Date(e).toLocaleDateString("es-ES",{day:"2-digit",month:"2-digit",year:"2-digit"})}catch(s){return String(e)}},N=e=>{if(!e)return"nunca";try{return new Date(e).toLocaleString("es-ES",{timeZone:"Europe/Madrid",day:"2-digit",month:"2-digit",hour:"2-digit",minute:"2-digit"})}catch(s){return String(e)}},S=e=>String(e||"").split("/").pop(),C="https://admin.shopify.com/store/visan-industrias-zootecnicas";function w(e){let{label:s,value:a,sub:i,tone:t,hint:l}=e;return(0,n.jsxs)("div",{className:"glass p-4 relative",children:[l&&(0,n.jsxs)("div",{className:"absolute top-2 right-2 group z-10",children:[(0,n.jsx)("span",{className:"flex items-center justify-center w-4 h-4 rounded-full border border-gray-300 text-gray-400 text-2xs font-semibold cursor-help",children:"i"}),(0,n.jsx)("div",{className:"hidden group-hover:block absolute right-0 top-6 z-30 w-64 p-3 bg-gray-900 text-white text-xs rounded-lg shadow-xl leading-relaxed",children:l})]}),(0,n.jsx)("div",{className:"text-xs text-gray-500 mb-2 pr-5",children:s}),(0,n.jsx)("div",{className:"text-2xl font-semibold tabular-nums ".concat("bad"===t?"text-rose-600":"good"===t?"text-emerald-600":"warn"===t?"text-amber-600":"text-gray-900"),children:a}),i&&(0,n.jsx)("div",{className:"mt-1 text-xs text-gray-500",children:i})]})}function T(e){let{checked:s,onChange:a,label:i,hint:t,disabled:l}=e;return(0,n.jsxs)("label",{className:"flex items-start gap-3 ".concat(l?"opacity-50":"cursor-pointer"),children:[(0,n.jsx)("button",{type:"button",role:"switch","aria-checked":!!s,disabled:l,onClick:()=>!l&&a(!s),className:"mt-0.5 relative w-10 h-[22px] rounded-full transition-colors shrink-0 ".concat(s?"bg-gray-900":"bg-gray-300"),children:(0,n.jsx)("span",{className:"absolute top-[3px] w-4 h-4 rounded-full bg-white transition-all ".concat(s?"left-[21px]":"left-[3px]")})}),(0,n.jsxs)("span",{children:[(0,n.jsx)("span",{className:"block text-sm font-medium text-gray-900",children:i}),t&&(0,n.jsx)("span",{className:"block text-xs text-gray-500 mt-0.5 leading-relaxed",children:t})]})]})}function k(e){let{title:s,subtitle:a,onClose:i,children:t,wide:l}=e;return(0,n.jsxs)("div",{className:"fixed inset-0 z-50 flex items-start sm:items-center justify-center p-0 sm:p-6 overflow-y-auto",children:[(0,n.jsx)("div",{className:"fixed inset-0 bg-black/40",onClick:i}),(0,n.jsxs)("div",{className:"relative glass-strong w-full ".concat(l?"max-w-4xl":"max-w-xl"," my-0 sm:my-8"),children:[(0,n.jsxs)("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-gray-200",children:[(0,n.jsxs)("div",{children:[(0,n.jsx)(u.x,{as:"h3",variant:"headingMd",children:s}),a&&(0,n.jsx)("p",{className:"text-xs text-gray-500 mt-0.5",children:a})]}),(0,n.jsx)("button",{onClick:i,"aria-label":"Cerrar",className:"p-1 rounded-md hover:bg-gray-100 text-gray-500",children:(0,n.jsxs)("svg",{className:"w-5 h-5 stroke-current",viewBox:"0 0 24 24",fill:"none",strokeWidth:"2",strokeLinecap:"round",children:[(0,n.jsx)("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),(0,n.jsx)("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),(0,n.jsx)("div",{className:"p-5",children:t})]})]})}function E(e){let{tone:s="info",title:a,children:i,action:t}=e;return(0,n.jsxs)("div",{className:"rounded-lg ring-1 ring-inset px-4 py-3 text-sm ".concat({info:"bg-blue-50 text-blue-900 ring-blue-200",warn:"bg-amber-50 text-amber-900 ring-amber-200",bad:"bg-rose-50 text-rose-900 ring-rose-200",good:"bg-emerald-50 text-emerald-900 ring-emerald-200"}[s]),children:[a&&(0,n.jsx)("div",{className:"font-semibold mb-0.5",children:a}),(0,n.jsx)("div",{className:"leading-relaxed",children:i}),t&&(0,n.jsx)("div",{className:"mt-2",children:t})]})}function q(e){let{value:s}=e,a="link"===s;return(0,n.jsx)("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-md text-xs font-medium ring-1 ring-inset ".concat(a?"bg-violet-50 text-violet-700 ring-violet-200":"bg-gray-100 text-gray-700 ring-gray-200"),children:a?"cliente ligado":"c\xf3digo"})}function I(e){let{value:s}=e,a={pending:{label:"Pendiente",cls:"bg-amber-50 text-amber-800 ring-amber-200"},paid:{label:"Liquidada",cls:"bg-emerald-50 text-emerald-700 ring-emerald-200"},reversed:{label:"Anulada",cls:"bg-gray-100 text-gray-500 ring-gray-200"},active:{label:"Activo",cls:"bg-emerald-50 text-emerald-700 ring-emerald-200"},paused:{label:"Pausado",cls:"bg-amber-50 text-amber-800 ring-amber-200"},archived:{label:"Archivado",cls:"bg-gray-100 text-gray-500 ring-gray-200"},confirmed:{label:"Emitida",cls:"bg-emerald-50 text-emerald-700 ring-emerald-200"},cancelled:{label:"Anulada",cls:"bg-rose-50 text-rose-700 ring-rose-200"}}[s]||{label:s,cls:"bg-gray-100 text-gray-600 ring-gray-200"};return(0,n.jsx)("span",{className:"inline-flex px-2 py-0.5 rounded-md text-xs font-medium ring-1 ring-inset ".concat(a.cls),children:a.label})}function P(e){let{text:s="Cargandoâ¦"}=e;return(0,n.jsxs)("div",{className:"flex items-center justify-center gap-2 py-10 text-sm text-gray-500",children:[(0,n.jsx)(x.$j,{size:"sm"}),(0,n.jsx)("span",{children:s})]})}function L(e){let{onRun:s,children:a,variant:t="btn-secondary",confirm:l,className:r=""}=e,[o,d]=(0,i.useState)(!1),[c,u]=(0,i.useState)(null);return(0,n.jsxs)("span",{className:"inline-block",children:[(0,n.jsx)("button",{type:"button",disabled:o,className:"btn ".concat(t," ").concat(r),onClick:async()=>
1{if(!l||window.confirm(l)){d(!0),u(null);try{await s()}catch(e){u(e.message)}finally{d(!1)}}},children:o?"Un momentoâ¦":a}),c&&(0,n.jsx)("span",{className:"block text-xs text-rose-600 mt-1 max-w-xs",children:c})]})}let z={all:"Todos los productos",collections:"Colecciones elegidas",products:"Productos elegidos",vendors:"Marcas elegidas"},A={name:"",commission_pct:10,discount_pct:10,scope:"all",scope_ids:[],lock_customer:!0,lock_conflict:"last",lock_ttl_days:"",include_subscription_renewals:!0,include_promo_orders:!0,active:!0,notes:""};function D(e){let{onChanged:s}=e,[a,t]=(0,i.useState)(null),[l,r]=(0,i.useState)(null),[c,h]=(0,i.useState)(null),[j,b]=(0,i.useState)(null),v=(0,i.useCallback)(async()=>{r(null);try{t((await g("/api/vet/groups")).groups)}catch(e){r(e.message)}},[]);return((0,i.useEffect)(()=>{v()},[v]),l)?(0,n.jsx)(x.ub,{title:"No se pueden leer los grupos",description:l}):a?(0,n.jsxs)(o.E,{gap:"500",children:[(0,n.jsxs)(m.g,{align:"space-between",blockAlign:"center",gap:"300",children:[(0,n.jsx)("p",{className:"text-sm text-gray-600 max-w-3xl",children:"Cada grupo fija el descuento del c\xf3digo, la comisi\xf3n del veterinario y sobre qu\xe9 productos se calcula. La opci\xf3n de ligar el cliente al veterinario viene activada: es lo que hace que el vet siga cobrando en los pedidos siguientes, cuando el cliente ya no tiene descuento."}),(0,n.jsx)(x.zx,{onClick:()=>h({...A}),children:"Nuevo grupo"})]}),a.length?(0,n.jsx)(d.Z,{padding:"0",children:(0,n.jsx)("div",{className:"overflow-x-auto",children:(0,n.jsxs)("table",{className:"w-full",children:[(0,n.jsx)("thead",{className:"bg-black/[0.02] border-b border-gray-200",children:(0,n.jsxs)("tr",{children:[(0,n.jsx)(x.Th,{children:"Grupo"}),(0,n.jsx)(x.Th,{align:"right",children:"Descuento"}),(0,n.jsx)(x.Th,{align:"right",children:"Comisi\xf3n"}),(0,n.jsx)(x.Th,{children:"\xc1mbito"}),(0,n.jsx)(x.Th,{children:"Cliente ligado"}),(0,n.jsx)(x.Th,{align:"right",children:"Vets"}),(0,n.jsx)(x.Th,{})]})}),(0,n.jsx)("tbody",{className:"divide-y divide-gray-200",children:a.map(e=>(0,n.jsxs)("tr",{className:e.active?"":"opacity-50",children:[(0,n.jsxs)(x.Td,{children:[(0,n.jsx)("div",{className:"font-medium text-gray-900",children:e.name}),!e.active&&(0,n.jsx)(u.x,{as:"p",variant:"bodySm",tone:"subdued",children:"Inactivo, no genera comisiones"}),e.notes&&(0,n.jsx)("div",{className:"text-xs text-gray-500 mt-0.5",children:e.notes})]}),(0,n.jsx)(x.Td,{align:"right",className:"tabular-nums",children:f(e.discount_pct)}),(0,n.jsx)(x.Td,{align:"right",className:"tabular-nums font-medium",children:f(e.commission_pct)}),(0,n.jsxs)(x.Td,{children:[(0,n.jsx)(u.x,{as:"p",variant:"bodyMd",children:z[e.scope]}),("collections"===e.scope||"products"===e.scope)&&(0,n.jsx)("div",{className:"text-xs ".concat(e.scope_products?"text-gray-500":"text-rose-600"),children:e.scope_products?"".concat(y(e.scope_products)," productos resueltos"):"sin productos resueltos, no generar\xe1 comisiones"}),"vendors"===e.scope&&(0,n.jsx)(u.x,{as:"p",variant:"bodySm",tone:"subdued",children:(e.scope_ids||[]).join(", ")})]}),(0,n.jsx)(x.Td,{children:e.lock_customer?(0,n.jsxs)("div",{children:[(0,n.jsx)(u.x,{as:"p",variant:"bodyMd",children:"S\xed"}),(0,n.jsxs)(u.x,{as:"p",variant:"bodySm",tone:"subdued",children:["first"===e.lock_conflict?"gana el primero":"gana el \xfaltimo c\xf3digo",e.lock_ttl_days?" \xb7 caduca a ".concat(e.lock_ttl_days," d\xedas"):" \xb7 sin caducidad"]})]}):(0,n.jsx)(u.x,{as:"span",variant:"bodyMd",tone:"subdued",children:"No"})}),(0,n.jsx)(x.Td,{align:"right",className:"tabular-nums",children:y(e.partners_count)}),(0,n.jsx)(x.Td,{align:"right",children:(0,n.jsxs)(m.g,{align:"end",blockAlign:"center",gap:"200",wrap:!1,children:["collections"===e.scope&&(0,n.jsx)(L,{variant:"btn-ghost",className:"btn-sm",onRun:async()=>{await p("/api/vet/groups","PUT",{id:e.id}),await v()},children:"Refrescar \xe1mbito"}),(0,n.jsx)(x.zx,{size:"sm",variant:"secondary",onClick:()=>b(e),children:"C\xf3digos"}),(0,n.jsx)(x.zx,{size:"sm",variant:"secondary",onClick:()=>{var s;return h({...e,lock_ttl_days:null!==(s=e.lock_ttl_days)&&void 0!==s?s:"",scope_ids:e.scope_ids||[]})},children:"Editar"})]})})]},e.id))})]})})}
1):(0,n.jsx)(x.ub,{title:"Todav\xeda no hay grupos",description:"Crea el primero con la comisi\xf3n y los productos sobre los que se calcula. Despu\xe9s se dan de alta los veterinarios dentro del grupo.",action:(0,n.jsx)(x.zx,{onClick:()=>h({...A}),children:"Crear el primer grupo"})}),j&&(0,n.jsx)(F,{group:j,onClose:()=>b(null),onChanged:v}),c&&(0,n.jsx)(R,{group:c,onClose:()=>h(null),onSaved:async()=>{h(null),await v(),null==s||s()}})]}):(0,n.jsx)(P,{})}function F(e){var s,a,t;let{group:l,onClose:r,onChanged:d}=e,[c,u]=(0,i.useState)(null),[h,g]=(0,i.useState)(null),[j,b]=(0,i.useState)(null),v=(0,i.useCallback)(async()=>{g(null),u(null);try{u(await p("/api/vet/code","POST",{action:"group_status",group_id:l.id}))}catch(e){g(e.message)}},[l.id]);return(0,i.useEffect)(()=>{v()},[v]),(0,n.jsx)(k,{title:"C\xf3digos de ".concat(l.name," en Shopify"),subtitle:"Un solo descuento por grupo, con todos los c\xf3digos de sus veterinarios dentro",onClose:r,wide:!0,children:(0,n.jsxs)(o.E,{gap:"400",children:[h&&(0,n.jsx)(E,{tone:"bad",title:"No se ha podido leer el estado",children:h}),!h&&!c&&(0,n.jsx)(P,{text:"Preguntando a Shopifyâ¦"}),c&&(0,n.jsxs)(n.Fragment,{children:[c.ready?(0,n.jsxs)(E,{tone:"good",t
1itle:"Todo en orden",children:["Los ",y(c.present.length)," c\xf3digos del grupo existen en Shopify y el descuento est\xe1 activo. Ning\xfan veterinario se queda sin c\xf3digo."]}):(0,n.jsx)(E,{tone:"warn",title:c.missing.length?"Faltan ".concat(y(c.missing.length)," c\xf3digos"):"Revisar",children:c.reason||'Hay c\xf3digos de este grupo que no existen en Shopify. Con "Poner en orden" se crean sin tocar los que ya est\xe1n.'}),c.discount&&(0,n.jsxs)("div",{className:"text-xs text-gray-500",children:["Descuento: ",(0,n.jsx)("b",{className:"text-gray-900",children:c.discount.title})," \xb7 ",c.discount.codes," c\xf3digos \xb7 estado ",String(c.discount.status||"").toLowerCase(),c.discount.discovered_from&&(0,n.jsxs)(n.Fragment,{children:[" \xb7 reconocido a partir de ",(0,n.jsx)("span",{className:"mono",children:c.discount.discovered_from})]})]}),(0,n.jsxs)("div",{className:"grid sm:grid-cols-2 gap-4",children:[(0,n.jsxs)("div",{children:[(0,n.jsxs)("div",{className:"text-sm font-medium text-gray-900 mb-1",children:["En Shopify (",y(c.present.length),")"]}),(0,n.jsxs)("div",{className:"max-h-52 overflow-y-auto text-xs text-gray-600 space-y-0.5",children:[c.present.map(e=>(0,n.jsxs)("div",{children:[(0,n.jsx)("span",{className:"mono",children:e.code})," \xb7 ",e.name]},e.code)),!c.present.length&&(0,n.jsx)("span",{className:"text-gray-400",children:"ninguno"})]})]}),(0,n.jsxs)("div",{children:[(0,n.jsxs)("div",{className:"text-sm font-medium text-rose-700 mb-1",children:["Faltan (",y(c.missing.length),")"]}),(0,n.jsxs)("div",{className:"max-h-52 overflow-y-auto text-xs text-rose-700 space-y-0.5",children:[c.missing.map(e=>(0,n.jsxs)("div",{children:[(0,n.jsx)("span",{className:"mono",children:e.code})," \xb7 ",e.name]},e.code)),!c.missing.length&&(0,n.jsx)("span",{className:"text-gray-400",children:"ninguno"})]})]})]}),!!(null===(s=c.extra)||void 0===s?void 0:s.length)&&(0,n.jsxs)("div",{className:"text-xs text-gray-500",children:["En el descuento hay adem\xe1s ",y(c.extra.length)," c\xf3digos que no son de ning\xfan veterinario de este grupo: ",c.extra.slice(0,8).join(", "),c.extra.length>8&&" â¦",". No se tocan."]}),j&&(0,n.jsxs)(E,{tone:(null===(a=j.failed)||void 0===a?void 0:a.length)?"warn":"good",title:"Hecho",children:[j.created?"Descuento creado. ":"",y(j.added)," c\xf3digos a\xf1adidos, ",y(j.linked)," enlazados.",(null===(t=j.failed)||void 0===t?void 0:t.length)?" ".concat(j.failed.length," rechazados por Shopify: ").concat(j.failed.map(e=>e.code).join(", ")):"",j.pending?" Shopify sigue procesando: vuelve a mirar en un momento.":""]}),(0,n.jsxs)(m.g,{align:"end",gap:"200",children:[(0,n.jsx)(x.zx,{variant:"ghost",onClick:r,children:"Cerrar"}),(0,n.jsx)(L,{variant:"btn-primary",onRun:async()=>{b(await p("/api/vet/code","POST",{action:"group_sync",group_id:l.id})),await v(),await (null==d?void 0:d())},children:"Poner en orden"})]})]})]})})}function R(e){let{group:s,onClose:a,onSaved:l}=e,[r,d]=(0,i.useState)(s),[c,u]=(0,i.useState)(null),[m,h]=(0,i.useState)(null),[j,b]=(0,i.useState)(!1),v=(e,s)=>d(a=>({...a,[e]:s}));(0,i.useEffect)(()=>{("collections"===r.scope||"vendors"===r.scope)&&(c||g("/api/vet/scope-options").then(u).catch(e=>h(e.message)))},[r.scope,c]);let y=async()=>{b(!0),h(null);try{await p("/api/vet/groups","POST",{...r,lock_ttl_days:""===r.lock_ttl_days?null:Number(r.lock_ttl_days)}),await l()}catch(e){h(e.message)}finally{b(!1)}},f=e=>v("scope_ids",(r.scope_ids||[]).includes(e)?r.scope_ids.filter(s=>s!==e):[...r.scope_ids||[],e]);return(0,n.jsx)(k,{title:r.id?"Editar ".concat(r.name):"Nuevo grupo",subtitle:"Los cambios afectan a los pedidos que se calculen a partir de ahora. Para recalcular pedidos ya procesados usa Ajustes â Recalcular.",onClose:a,wide:!0,children:(0,n.jsxs)(o.E,{gap:"500",children:[(0,n.jsxs)("div",{className:"grid sm:grid-cols-3 gap-3",children:[(0,n.jsx)(x.II,{label:"Nombre del grupo",value:r.name,onChange:e=>v("name",e),autoFocus:!0,className:"sm:col-span-3"}),(0,n.jsx)(x.II,{label:"Descuento del c\xf3digo (%)",type:"number",value:r.discount_pct,onChange:e=>v("discount_pct",e),hint:"Solo en el primer pedido del cliente"}),(0,n.jsx)(x.II,{label:"Comisi\xf3n del veterinario (%)",type:"number",value:r.commission_pct,onChange:e=>v("commission_pct",e),hint:"Sobre el importe con IVA, ya descontado"}),(0,n.jsx)(x.Ph,{label:"Estado",value:r.active?"1":"0",onChange:e=>v("active","1"===e),options:[{value:"1",label:"Activo"},{value:"0",label:"Inactivo"}],hint:r.active?void 0:"Inactivo deja de generar comisiones"})]}),(0,n.jsxs)("div",{className:"border-t border-gray-200 pt-4 space-y-3",children:[(0,n.jsx)(x.Ph,{label:"\xbfSobre qu\xe9 productos se calcula la comisi\xf3n?",value:r.scope,onCh
1ange:e=>{v("scope",e),v("scope_ids",[])},options:Object.entries(z).map(e=>{let[s,a]=e;return{value:s,label:a}})}),"collections"===r.scope&&(0,n.jsx)(M,{items:((null==c?void 0:c.collections)||[]).map(e=>{var s;return{id:e.id,label:e.title,sub:"".concat(null!==(s=e.products)&&void 0!==s?s:"?"," productos")}}),selected:r.scope_ids||[],onToggle:f,loading:!c,error:null==c?void 0:c.collections_error,emptyText:"No se han podido leer las colecciones de Shopify"}),"vendors"===r.scope&&(0,n.jsx)(M,{items:((null==c?void 0:c.vendors)||[]).map(e=>({id:e,label:e})),selected:r.scope_ids||[],onToggle:f,loading:!c,emptyText:"No hay marcas en el cat\xe1logo sincronizado. Escr\xedbelas a mano abajo.",allowFree:!0,onAddFree:e=>f(e)}),"products"===r.scope&&(0,n.jsxs)("div",{children:[(0,n.jsx)("label",{className:"block text-xs font-medium text-gray-700 mb-1",children:"GIDs de producto, uno por l\xednea"}),(0,n.jsx)(t.oi,{label:"Campo",labelHidden:!0,value:(r.scope_ids||[]).join("\n"),onChange:e=>v("scope_ids",e.split("\n").map(e=>e.trim()).filter(Boolean)),multiline:5}),(0,n.jsx)("div",{className:"text-xs text-gray-500 mt-1",children:"El GID se ve en la URL del producto en el admin de Shopify, o se copia desde Recomendaciones."})]})]}),(0,n.jsxs)("div",{className:"border-t border-gray-200 pt-4 space-y-4",children:[(0,n.jsx)(T,{checked:r.lock_customer,onChange:e=>v("lock_customer",e),label:"Ligar el cliente al veterinario de forma permanente",hint:"Cuando un cliente compra con el c\xf3digo, queda asociado a ese veterinario. En los pedidos siguientes el cliente ya paga precio completo (el c\xf3digo solo vale la primera vez) pero el veterinario sigue cobrando su comisi\xf3n."}),r.lock_customer&&(0,n.jsxs)("div",{className:"grid sm:grid-cols-2 gap-3 pl-[52px]",children:[(0,n.jsx)(x.Ph,{label:"Si el cliente usa el c\xf3digo de otro veterinario",value:r.lock_conflict,onChange:e=>v("lock_conflict",e),options:[{value:"last",label:"Pasa al nuevo veterinario"},{value:"first",label:"Se queda con el primero"}],hint:"Las comisiones ya generadas del anterior no se tocan nunca"}),(0,n.jsx)(x.II,{label:"Caducidad del v\xednculo (d\xedas)",type:"number",value:r.lock_ttl_days,onChange:e=>v("lock_ttl_days",e),placeholder:"sin caducidad",hint:"Vac\xedo = para siempre"})]})]}),(0,n.jsxs)("div",{className:"border-t border-gray-200 pt-4 space-y-4",children:[(0,n.jsx)(T,{checked:r.include_subscription_renewals,onChange:e=>v("include_subscription_renewals",e),label:"Las renovaciones de suscripci\xf3n generan comisi\xf3n",hint:"En una suscripci\xf3n el descuento queda congelado en el contrato, as\xed que el c\xf3digo sigue valiendo en cada renovaci\xf3n."}),(0,n.jsx)(T,{checked:r.include_promo_orders,onChange:e=>v("include_promo_orders",e),label:"Los pedidos con otras promociones generan comisi\xf3n",hint:"Si se desactiva, un cliente que use puntos de fidelidad o una promo del mes no dar\xe1 comisi\xf3n al veterinario."})]}),(0,n.jsx)(x.II,{label:"Notas internas",value:r.notes||"",onChange:e=>v("notes",e)}),m&&(0,n.jsx)(E,{tone:"bad",children:m}),(0,n.jsxs)("div",{className:"flex items-center justify-end gap-2 border-t border-gray-200 pt-4",children:[(0,n.jsx)(x.zx,{variant:"ghost",onClick:a,children:"Cancelar"}),(0,n.jsx)(x.zx,{onClick:y,disabled:j,children:j?"Guardandoâ¦":"Guardar grupo"})]})]})})}function M(e){let{items:s,selected:a,onToggle:t,loading:l,error:r,emptyText:d,allowFree:c,onAddFree:h}=e,[g,p]=(0,i.useState)(""),[j,b]=(0,i.useState)(""),v=s.filter(e=>!g||e.label.toLowerCase().includes(g.toLowerCase()));return(0,n.jsxs)(o.E,{gap:"200",children:[l&&(0,n.jsx)(P,{text:"Leyendo de Shopifyâ¦"}),r&&(0,n.jsx)(E,{tone:"warn",children:r}),!l&&(0,n.jsxs)(n.Fragment,{children:[s.length>8&&(0,n.jsx)(x.II,{value:g,onChange:p,placeholder:"Buscarâ¦"}),!s.length&&!c&&(0,n.jsx)(E,{tone:"warn",children:d}),!!s.length&&(0,n.jsx)("div",{className:"max-h-64 overflow-y-auto rounded-lg ring-1 ring-inset ring-gray-200 divide-y divide-gray-200",children:v.map(e=>{let s=a.includes(e.id);return(0,n.jsxs)("button",{type:"button",onClick:()=>t(e.id),className:"w-full flex items-center justify-between gap-3 px-3 py-2 text-left text-sm ".concat(s?"bg-gray-900/[0.04]":"hover:bg-black/[0.02]"),children:[(0,n.jsx)("span",{className:s?"font-medium text-gray-900":"text-gray-700",children:e.label}),(0,n.jsxs)("span",{className:"flex items-center gap-2 shrink-0",children:[e.sub&&(0,n.jsx)(u.x,{as:"span",variant:"bodySm",tone
1:"subdued",children:e.sub}),(0,n.jsx)("span",{className:"w-4 h-4 rounded border flex items-center justify-center ".concat(s?"bg-gray-900 border-gray-900":"border-gray-300"),children:s&&(0,n.jsx)("svg",{className:"w-3 h-3 stroke-white",viewBox:"0 0 24 24",fill:"none",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",children:(0,n.jsx)("polyline",{points:"20 6 9 17 4 12"})})})]})]},e.id)})}),c&&(0,n.jsxs)(m.g,{blockAlign:"end",gap:"200",wrap:!1,children:[(0,n.jsx)(x.II,{label:"A\xf1adir a mano",value:j,onChange:b,className:"flex-1"}),(0,n.jsx)(x.zx,{variant:"secondary",onClick:()=>{let e=j.trim();e&&(h(e),b(""))},children:"A\xf1adir"})]}),!!a.length&&(0,n.jsx)(m.g,{gap:"150",children:a.map(e=>{let a=s.find(s=>s.id===e);return(0,n.jsxs)("button",{type:"button",onClick:()=>t(e),className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-md text-xs bg-gray-900 text-white",title:"Quitar",children:[(null==a?void 0:a.label)||e,(0,n.jsx)("span",{"aria-hidden":!0,children:"\xd7"})]},e)})})]})]})}function V(e){let{groups:s,onChanged:a}=e,[t,l]=(0,i.useState)(null),[r,c]=(0,i.useState)(null),[h,p]=(0,i.useState)(""),[j,v]=(0,i.useState)(""),[_,N]=(0,i.useState)(""),[S,C]=(0,i.useState)(null),[w,T]=(0,i.useState)(null),[k,q]=(0,i.useState)(!1),L=(0,i.useCallback)(async()=>{c(null);try{let e=new URLSearchParams;h&&e.set("q",h),j&&e.set("group_id",j),_&&e.set("status",_),l((await g("/api/vet/partners?".concat(e))).partners)}catch(e){c(e.message)}},[h,j,_]);(0,i.useEffect)(()=>{let e=setTimeout(L,h?300:0);return()=>clearTimeout(e)},[L,h]);let z=(s||[]).filter(e=>!1!==e.active);return(0,n.jsxs)(o.E,{gap:"500",children:[(0,n.jsxs)(m.g,{blockAlign:"end",gap:"300",children:[(0,n.jsx)(x.II,{value:h,onChange:p,placeholder:"Buscar por nombre, c\xf3digo, cl\xednica o correoâ¦",className:"flex-1 min-w-[240px]"}),(0,n.jsx)(x.Ph,{value:j,onChange:v,placeholder:"Todos los grupos",options:(s||[]).map(e=>({value:String(e.id),label:e.name}))}),(0,n.jsx)(x.Ph,{value:_,onChange:N,placeholder:"Todos los estados",options:[{value:"active",label:"Activos"},{value:"paused",label:"Pausados"},{value:"archived",label:"Archivados"}]}),(0,n.jsx)(x.zx,{variant:"secondary",onClick:()=>q(!0),children:"Importar CSV"}),(0,n.jsx)(x.zx,{onClick:()=>{var e;return C({group_id:(null===(e=z[0])||void 0===e?void 0:e.id)||"",status:"active"})},disabled:!z.length,children:"Nuevo veterinario"})]}),!z.length&&(0,n.jsx)(E,{tone:"warn",title:"Primero hace falta un grupo",children:"Los veterinarios van siempre dentro de un grupo, que es el que define la comisi\xf3n. Crea uno en la pesta\xf1a Grupos."}),r&&(0,n.jsx)(x.ub,{title:"No se pueden leer los veterinarios",description:r}),!r&&!t&&(0,n.jsx)(P,{}),!r&&t&&!t.length&&(0,n.jsx)(x.ub,{title:"Sin veterinarios",description:"Importa un CSV con sus c\xf3digos y su saldo pendiente, o da de alta uno a mano.",action:(0,n.jsx)(x.zx,{variant:"secondary",onClick:()=>q(!0),children:"Importar CSV"})}),!r&&!!(null==t?void 0:t.length)&&(0,n.jsx)(d.Z,{padding:"0",children:(0,n.jsx)("div",{className:"overflow-x-auto",children:(0,n.jsxs)("table",{className:"w-full",children:[(0,n.jsx)("thead",{className:"bg-black/[0.02] border-b border-gray-200",children:(0,n.jsxs)("tr",{children:[(0,n.jsx)(x.Th,{children:"Veterinario"}),(0,n.jsx)(x.Th,{children:"C\xf3digo"}),(0,n.jsx)(x.Th,{children:"Grupo"}),(0,n.jsx)(x.Th,{align:"right",children:"Comisi\xf3n"}),(0,n.jsx)(x.Th,{align:"right",children:"Clientes"}),(0,n.jsx)(x.Th,{align:"right",children:"Pendiente"}),(0,n.jsx)(x.Th,{align:"right",children:"Liquidado"}),(0,n.jsx)(x.Th,{children:"Estado"}),(0,n.jsx)(x.Th,{})]})}),(0,n.jsx)("tbody",{className:"divide-y divide-gray-200",children:t.map(e=>(0,n.jsxs)("tr",{className:"hover:bg-black/[0.02]",children:[(0,n.jsx)(x.Td,{children:(0,n.jsxs)("button",{onClick:()=>T(e.id),className:"text-left",children:[(0,n.jsx)("div",{className:"font-medium text-gray-900 hover:underline",children:e.name}),e.clinic&&(0,n.jsx)(u.x,{as:"p",variant:"bodySm",tone:"subdued",children:e.clinic})]})}),(0,n.jsxs)(x.Td,{children:[(0,n.jsx)("span",{className:"mono text-sm",children:e.code}
1),!e.shopify_discount_gid&&(0,n.jsx)(u.x,{as:"p",variant:"bodyXs",tone:"subdued",children:"sin enlazar a Shopify"})]}),(0,n.jsx)(x.Td,{className:"text-sm text-gray-600",children:e.group_name}),(0,n.jsxs)(x.Td,{align:"right",className:"tabular-nums",children:[f(e.effective_commission_pct),null!=e.commission_pct&&(0,n.jsx)(u.x,{as:"p",variant:"bodyXs",tone:"subdued",children:"propia"})]}),(0,n.jsx)(x.Td,{align:"right",className:"tabular-nums",children:y(e.linked_customers)}),(0,n.jsx)(x.Td,{align:"right",className:"tabular-nums font-medium",children:b(e.pending_cents)}),(0,n.jsx)(x.Td,{align:"right",className:"tabular-nums text-gray-500",children:b(e.paid_cents)}),(0,n.jsx)(x.Td,{children:(0,n.jsx)(I,{value:e.status})}),(0,n.jsx)(x.Td,{align:"right",children:(0,n.jsx)(x.zx,{size:"sm",variant:"secondary",onClick:()=>C(e),children:"Editar"})})]},e.id))})]})})}),S&&(0,n.jsx)(O,{partner:S,groups:s||[],onClose:()=>C(null),onSaved:async()=>{C(null),await L(),null==a||a()}}),w&&(0,n.jsx)(B,{partnerId:w,onClose:()=>T(null),onChanged:async()=>{await L(),null==a||a()}}),k&&(0,n.jsx)(H,{groups:z,onClose:()=>q(!1),onDone:async()=>{q(!1),await L(),null==a||a()}})]})}function O(e){var s,a;let{partner:t,groups:l,onClose:r,onSaved:d}=e,[c,u]=(0,i.useState)({...t,opening_balance_eur:null!=t.opening_balance_cents?(Number(t.opening_balance_cents)/100).toFixed(2):"",commission_pct:null!==(s=t.commission_pct)&&void 0!==s?s:"",discount_pct:null!==(a=t.discount_pct)&&void 0!==a?a:""}),[h,g]=(0,i.useState)(null),[j,b]=(0,i.useState)(!1),[v,f]=(0,i.useState)(null),[_,N]=(0,i.useState)(!1),S=(e,s)=>u(a=>({...a,[e]:s})),C=l.find(e=>String(e.id)===String(c.group_id)),w=async()=>{f(null),f(await p("/api/vet/code","POST",{action:"verify",code:c.code}))},T=async()=>{S("code",(await p("/api/vet/code","POST",{action:"suggest",prefix:"VET"})).code),f(null)},q=async()=>{b(!0),g(null);try{let e=await p("/api/vet/partners","POST",c);e.warning&&window.alert(e.warning),await d()}catch(e){g(e.message)}finally{b(!1)}};return(0,n.jsx)(k,{title:c.id?"Editar ".concat(c.name):"Nuevo veterinario",subtitle:c.id?void 0:"Si ya tiene un c\xf3digo repartido, escr\xedbelo tal cual: se mapea y sigue funcionando.",onClose:r,wide:!0,children:(0,n.jsxs)(o.E,{gap:"400",children:[(0,n.jsxs)("div",{className:"grid sm:grid-cols-2 gap-3",children:[(0,n.jsx)(x.II,{label:"Nombre y apellidos",value:c.name||"",onChange:e=>S("name",e),autoFocus:!0}),(0,n.jsx)(x.II,{label:"Cl\xednica",value:c.clinic||"",onChange:e=>S("clinic",e)}),(0,n.jsx)(x.II,{label:"Correo",type:"email",value:c.email||"",onChange:e=>S("email",e),hint:"Necesario para que entre en el portal del veterinario"}),(0,n.jsx)(x.II,{label:"Tel\xe9fono",value:c.phone||"",onChange:e=>S("phone",e)}),(0,n.jsx)(x.II,{label:"NIF o CIF",value:c.tax_id||"",onChange:e=>S("tax_id",e),hint:"Aparece en la liquidaci\xf3n"}),(0,n.jsx)(x.II,{label:"Pa\xeds",value:c.country||"",onChange:e=>S("country",e),placeholder:"ES"})]}),(0,n.jsxs)("div",{className:"border-t border-gray-200 pt-4 grid sm:grid-cols-2 gap-3",children:[(0,n.jsx)(x.Ph,{label:"Grupo",value:String(c.group_id||""),onChange:e=>S("group_id",e),options:l.map(e=>({value:String(e.id),label:"".concat(e.name," (").concat(e.commission_pct," %)")})),placeholder:"Elige el grupo"}),(0,n.jsx)(x.Ph,{label:"Estado",value:c.status||"active",onChange:e=>S("status",e),options:[{value:"active",label:"Activo"},{value:"paused",label:"Pausado, deja de generar comisiones"},{value:"archived",label:"Archivado"}]})]}),(0,n.jsxs)("div",{className:"border-t border-gray-200 pt-4 space-y-3",children:[(0,n.jsxs)(m.g,{blockAlign:"end",gap:"200",wrap:!1,children:[(0,n.jsx)(x.II,{label:"C\xf3digo de descuento",value:c.code||"",onChange:e=>{S("code",String(e).toUpperCase()),f(null)},className:"flex-1",disabled:!!c.id,hint:c.id?"El c\xf3digo no se edita aqu\xed: cambiarlo toca tambi\xe9n Shopify":"El mismo que ya usa el veterinario, o uno nuevo"}),c.id?(0,n.jsx)(x.zx,{variant:"secondary",onClick:()=>N(!0),children:"Cambiar c\xf3digo"}):(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(L,{onRun:w,children:"Comprobar"}),(0,n.jsx)(L,{onRun:T,children:"Generar uno"})]})]}),v&&(0,n.jsx)(E,{tone:v.already_assigned?"bad":v.shopify?"good":"info",children:v.already_assigned?(0,n.jsxs)(n.Fragment,{children:["El c\xf3digo ",(0,n.jsx)("span",{className:"mono",children:v.code})," ya est\xe1 asignado a ",(0,n.jsx)("b",{children:v.already_assigned.name}),"."]}):v.shopify?(0,n.jsxs)(n.Fragment,{children:["Existe en Shopify: ",null!=v.shopify.percentage?"".concat(v.shopify.percentage," % de descuento"):"descuento de importe fijo",", estado ",String(v.shopify.status||"").toLowerCase(),", usado ",y(v.shopify.usage_count)," veces",!1===v.shopify.once_per_customer&&(0,n.jsxs)(n.Fragment,{children:[". ",(0,n.jsx)("b",{children:"Atenci\xf3n:"})," no est\xe1 limitado a un uso por cliente, as\xed que el cliente tendr\xeda descuento en todos sus pedidos, no solo el primero."]})]}):v.verifiable?(0,n.jsx)(n.Fragment,{children:"No existe ning\xfan c\xf3digo as\xed en Shopify. Puedes mapearlo igualmente, pero no descontar\xe1 nada hasta que se cree."}):(0,n.jsxs)(n.Fragment,{children:["No se ha podido comprobar en
1Shopify (",v.shopify_error,"). El mapeo funciona igual: el motor solo compara el texto del c\xf3digo con el del pedido."]})}),(0,n.jsxs)("div",{className:"grid sm:grid-cols-3 gap-3",children:[(0,n.jsx)(x.II,{label:"Comisi\xf3n propia (%)",type:"number",value:c.commission_pct,onChange:e=>S("commission_pct",e),placeholder:C?String(C.commission_pct):"",hint:"Vac\xedo = la del grupo"}),(0,n.jsx)(x.II,{label:"Descuento propio (%)",type:"number",value:c.discount_pct,onChange:e=>S("discount_pct",e),placeholder:C?String(C.discount_pct):"",hint:"Vac\xedo = el del grupo"}),(0,n.jsx)(x.II,{label:"Saldo de apertura (â¬)",type:"number",value:c.opening_balance_eur,onChange:e=>S("opening_balance_eur",e),hint:"Lo que se le deb\xeda antes de empezar aqu\xed"})]})]}),(0,n.jsx)(x.II,{label:"Notas internas",value:c.notes||"",onChange:e=>S("notes",e)}),h&&(0,n.jsx)(E,{tone:"bad",children:h}),(0,n.jsxs)("div",{className:"flex items-center justify-end gap-2 border-t border-gray-200 pt-4",children:[(0,n.jsx)(x.zx,{variant:"ghost",onClick:r,children:"Cancelar"}),(0,n.jsx)(x.zx,{onClick:q,disabled:j,children:j?"Guardandoâ¦":"Guardar"})]}),_&&(0,n.jsx)(G,{partner:c,onClose:()=>N(!1),onDone:async e=>{N(!1),S("code",e),await d()}})]})})}function G(e){let{partner:s,onClose:a,onDone:t}=e,[l,r]=(0,i.useState)(""),[d,c]=(0,i.useState)(!1),[u,h]=(0,i.useState)(null),[g,j]=(0,i.useState)(!1),[b,v]=(0,i.useState)(null),f=async()=>{j(!0),h(null);try{v(await p("/api/vet/code","POST",{action:"change",partner_id:s.id,code:l,keep_old:d}))}catch(e){h(e.message)}finally{j(!1)}};return(0,n.jsx)(k,{title:"Cambiar el c\xf3digo de ".concat(s.name),subtitle:"Ahora mismo es ".concat(s.code),onClose:a,children:b?(0,n.jsxs)(o.E,{gap:"400",children:[(0,n.jsxs)(E,{tone:"good",t
1itle:"C\xf3digo cambiado",children:["De ",(0,n.jsx)("span",{className:"mono",children:b.from})," a ",(0,n.jsx)("span",{className:"mono",children:b.to}),"."," ","Sus ",y(b.linked_customers)," clientes ligados siguen contando para \xe9l.",b.old_removed?" El c\xf3digo anterior ya no funciona.":" El c\xf3digo anterior sigue activo, como pediste."]}),(0,n.jsx)(m.g,{align:"end",children:(0,n.jsx)(x.zx,{onClick:()=>t(b.to),children:"Cerrar"})})]}):(0,n.jsxs)(o.E,{gap:"400",children:[(0,n.jsxs)(E,{tone:"info",children:["El c\xf3digo nuevo se da de alta en Shopify ",(0,n.jsx)("b",{children:"antes"})," de retirar el viejo, as\xed que no hay ni un segundo sin c\xf3digo v\xe1lido. Los clientes que ya est\xe1n ligados a este veterinario no se ven afectados: siguen generando comisi\xf3n para \xe9l aunque no usen ning\xfan c\xf3digo. Las comisiones ya generadas conservan el c\xf3digo con el que se hicieron."]}),(0,n.jsx)(x.II,{label:"C\xf3digo nuevo",value:l,onChange:e=>r(String(e).toUpperCase()),autoFocus:!0,placeholder:"#4050ABC",hint:"Letras, n\xfameros, almohadilla, punto, guion y guion bajo"}),(0,n.jsxs)("label",{className:"flex items-start gap-2 text-sm text-gray-700",children:[(0,n.jsx)("input",{type:"checkbox",checked:d,onChange:e=>c(e.target.checked),className:"mt-0.5 rounded border-gray-300"}),(0,n.jsxs)("span",{children:["Dejar activo tambi\xe9n el c\xf3digo anterior",(0,n.jsx)("span",{className:"block text-xs text-gray-500",children:"\xdatil si est\xe1 impreso en tarjetas o folletos que siguen circulando. Seguir\xe1 dando descuento y seguir\xe1 contando para este veterinario, pero ya no ser\xe1 el que se le ense\xf1a en su portal."})]})]}),u&&(0,n.jsx)(E,{tone:"bad",children:u}),(0,n.jsxs)(m.g,{align:"end",gap:"200",children:[(0,n.jsx)(x.zx,{variant:"ghost",onClick:a,children:"Cancelar"}),(0,n.jsx)(x.zx,{onClick:f,disabled:g||l.length<3,children:g?"Cambiandoâ¦":"Cambiar el c\xf3digo"})]})]})})}function B(e){let{partnerId:s,onClose:a,onChanged:t}=e,[l,r]=(0,i.useState)(null),[d,c]=(0,i.useState)(null),[m,h]=(0,i.useState)("comisiones"),j=(0,i.useCallback)(async()=>{c(null);try{r(await g("/api/vet/partners?id=".concat(s)))}catch(e){c(e.message)}},[s]);(0,i.useEffect)(()=>{j()},[j]);let v=null==l?void 0:l.partner;return(0,n.jsxs)(k,{title:v?v.name:"Ficha del veterinario",subtitle:v?"".concat(v.group_name," \xb7 c\xf3digo ").concat(v.code," \xb7 comisi\xf3n ").concat(f(v.effective_commission_pct)):void 0,onClose:a,wide:!0,children:[d&&(0,n.jsx)(E,{tone:"bad",children:d}),!d&&!l&&(0,n.jsx)(P,{}),!d&&l&&(0,n.jsxs)(o.E,{gap:"500",children:[(0,n.jsxs)("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-3",children:[(0,n.jsx)(U,{label:"Pendiente",value:b(l.pending.total_cents)}),(0,n.jsx)(U,{label:"L\xedneas pendientes",value:y(l.pending.lines)}),(0,n.jsx)(U,{label:"Clientes ligados",value:y(l.links.length)}),(0,n.jsx)(U,{label:"Saldo de apertura",value:b(l.pending.opening_balance_cents)})]}),!v.shopify_discount_gid&&(0,n.jsx)(E,{tone:"info",title:"El c\xf3digo no est\xe1 enlazado a Shopify",action:(0,n.jsx)(L,{onRun:async()=>{await p("/api/vet/code","POST",{action:"create",partner_id:v.id}),await j(),await t()},children:"Crear el c\xf3digo en Shopify"}),children:"Esto es lo normal si el c\xf3digo ya estaba repartido: ya existe en Shopify y funciona igual, el motor solo compara el texto. Crea el c\xf3digo solo si el veterinario es nuevo y todav\xeda no tiene ninguno. Hace falta el permiso write_discounts en el token."}),(0,n.jsxs)("div",{className:"tabs-top",children:[(0,n.jsx)("button",{onClick:()=>h("comisiones"),className:"comisiones"===m?"active":"",children:"Comisiones"}),(0,n.jsxs)("button",{onClick:()=>h("clientes"),className:"clientes"===m?"active":"",children:["Clientes ligados",l.links.length>0&&(0,n.jsx)("span",{className:"tab-count",children:l.links.length})]})]}),"comisiones"===m&&(l.commissions.rows.length?(0,n.jsx)("div",{className:"overflow-x-auto",children:(0,n.jsxs)("table",{className:"w-full",children:[(0,n.jsx)("thead",{className:"border-b border-gray-200",children:(0,n.jsxs)("tr",{children:[(0,n.jsx)(x.Th,{children:"Pedido"}),(0,n.jsx)(x.Th,{children:"Producto"}),(0,n.jsx)(x.Th,{children:"Origen"}),(0,n.jsx)(x.Th,{align:"right",children:"Base"}),(0,n.jsx)(x.Th,{align:"right",children:"Comisi\xf3n"}),(0,n.jsx)(x.Th,{children:"Estado"})]})}),(0,n.jsx)("tbody",{className:"divide-y divide-gray-200",children:l.commissions.rows.map(e=>(0,n.jsxs)("tr",{children:[(0,n.jsxs)(x.Td,{children:[(0,n.jsx)(u.x,{as:"p",variant:"bodyMd",fontWeight:"medium",children:e.order_name}
1),(0,n.jsx)(u.x,{as:"p",variant:"bodySm",tone:"subdued",children:_(e.order_created_at)})]}),(0,n.jsxs)(x.Td,{className:"text-sm",children:[e.title,e.is_adjustment&&(0,n.jsx)(u.x,{as:"p",variant:"bodySm",tone:"caution",children:"rectificaci\xf3n"})]}),(0,n.jsx)(x.Td,{children:(0,n.jsx)(q,{value:e.attribution})}),(0,n.jsx)(x.Td,{align:"right",className:"tabular-nums text-sm",children:b(e.base_cents)}),(0,n.jsx)(x.Td,{align:"right",className:"tabular-nums text-sm font-medium ".concat(0>Number(e.commission_cents)?"text-rose-600":""),children:b(e.commission_cents)}),(0,n.jsx)(x.Td,{children:(0,n.jsx)(I,{value:e.status})})]},"".concat(e.order_id,"-").concat(e.line_item_id)))})]})}):(0,n.jsx)(x.ub,{title:"Sin comisiones todav\xeda",description:"Aparecer\xe1n en cuanto un cliente compre con su c\xf3digo."})),"clientes"===m&&(l.links.length?(0,n.jsx)("div",{className:"overflow-x-auto",children:(0,n.jsxs)("table",{className:"w-full",children:[(0,n.jsx)("thead",{className:"border-b border-gray-200",children:(0,n.jsxs)("tr",{children:[(0,n.jsx)(x.Th,{children:"Cliente"}),(0,n.jsx)(x.Th,{children:"Ligado"}),(0,n.jsx)(x.Th,{children:"Origen"}),(0,n.jsx)(x.Th,{align:"right",children:"Pedidos"}),(0,n.jsx)(x.Th,{align:"right",children:"Comisi\xf3n generada"}),(0,n.jsx)(x.Th,{})]})}),(0,n.jsx)("tbody",{className:"divide-y divide-gray-200",children:l.links.map(e=>(0,n.jsxs)("tr",{className:e.active?"":"opacity-50",children:[(0,n.jsx)(x.Td,{children:(0,n.jsx)("a",{href:"".concat(C,"/customers/").concat(S(e.customer_id)),target:"_blank",rel:"noreferrer",className:"text-sm mono hover:underline",children:S(e.customer_id)})}),(0,n.jsx)(x.Td,{className:"text-sm text-gray-600",children:N(e.linked_at)}),(0,n.jsx)(x.Td,{className:"text-xs text-gray-500",children:"manual"===e.source?"a mano":"import"===e.source?"importado":"por c\xf3digo"}),(0,n.jsx)(x.Td,{align:"right",className:"tabular-nums text-sm",children:y(e.orders_count)}),(0,n.jsx)(x.Td,{align:"right",className:"tabular-nums text-sm",children:b(e.commission_cents)}),(0,n.jsx)(x.Td,{align:"right",children:e.active&&(0,n.jsx)(L,{variant:"btn-ghost",className:"btn-sm",confirm:"El veterinario dejar\xe1 de cobrar comisi\xf3n por los pedidos futuros de este cliente. \xbfSeguimos?",onRun:async()=>{await p("/api/vet/links?customer_id=".concat(encodeURIComponent(e.customer_id)),"DELETE"),await j(),await t()},children:"Desligar"})})]},e.customer_id))})]})}):(0,n.jsx)(x.ub,{title:"Ning\xfan cliente ligado",description:"Se ligan solos cuando alguien compra con el c\xf3digo, si el grupo tiene la opci\xf3n activada."}))]})]})}function U(e){let{label:s,value:a}=e;return(0,n.jsxs)("div",{className:"rounded-lg ring-1 ring-inset ring-gray-200 px-3 py-2",children:[(0,n.jsx)(u.x,{as:"p",variant:"bodySm",tone:"subdued",children:s}),(0,n.jsx)(u.x,{as:"p",variant:"headingLg",numeric:!0,children:a})]})}function H(e){var s;let{groups:a,onClose:l,onDone:r}=e,[d,c]=(0,i.useState)(""),[u,m]=(0,i.useState)((null===(s=a[0])||void 0===s?void 0:s.id)?String(a[0].id):""),[h,g]=(0,i.useState)(null),[j,b]=(0,i.useState)(null),[v,f]=(0,i.useState)(!1),[_,N]=(0,i.useState)(null),S=async e=>{f(!0),b(null);try{let s=await p("/api/vet/import","POST",{csv:d,group_id:u,apply:e});e?N(s):g(s)}catch(e){b(e.message)}finally{f(!1)}};return(0,n.jsx)(k,{title:"Importar veterinarios",subtitle:"Pega el CSV con los veterinarios. Primero se ense\xf1a qu\xe9 har\xeda, y solo se escribe cuando lo confirmas.",onClose:l,wide:!0,children:(0,n.jsx)(o.E,{gap:"400",children:_?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)(E,{tone:_.ok?"good":"warn",title:_.ok?"Importaci\xf3n terminada":"Importaci\xf3n con fallos",children:[y(_.imported.length)," veterinarios guardados",_.failed.length?", ".concat(y(_.failed.length)," con error"):"",".",_.summary.opening_balance_eur>0&&(0,n.jsxs)(n.Fragment,{children:[" Saldo de apertura total: ",_.summary.opening_balance_eur.toLocaleString("es-ES")," â¬."]})]}),!!_.failed.length&&(0,n.jsx)("div",{className:"text-xs text-rose-700 space-y-1",children:_.failed.map(e=>(0,n.jsxs)("div",{children:["L\xednea ",e.line," (",e.code,"): ",e.error]},e.line))}),(0,n.jsx)("div",{className:"flex justify-end",children:(0,n.jsx)(x.zx,{onClick:r,children:"Cerrar"})})]}):(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(x.Ph,{label:"Grupo de destino",value:u,onChange:m,options:a.map(e=>({value:String(e.id),label:"".concat(e.name," (").concat(e.commission_pct," %)")}))}),(0,n.jsxs)("div",{children:[(0,n.jsx)("label",{className:"block text-xs font-medium text-gray-700 mb-1",children:"CSV"}),(0,n.jsx)(t.oi,{label:"Campo",labelHidden:!0,value:d,onChange:e=>{c(e),g(null)},multiline:8}),(0,n.jsx)("div",{className:"text-xs text-gray-500 mt-1",children:"Columnas reconocidas en espa\xf1ol o ingl\xe9s: nombre, codigo, email, clinica, nif, telefono, pais, comision, descuento, saldo. El orden no importa."})]}),j&&(0,n.jsx)(E,{tone:"bad",children:j}),h&&(0,n.jsxs)(o.E,{gap:"300",children:[(0,n.jsxs)(E,{tone:h.summary.with_errors?"warn":"good",children:[y(h.summary.to_create)," nuevos, ",y(h.summary.to_update)," actualizaciones",h.summary.with_errors?", ".concat(y(h.summary.with_errors)," filas con errores"):"",".",h.summary.opening_balance_eur>0&&(0,n.jsxs)(n.Fragment,{children:[" Saldo de apertura: ",h.summary.opening_balance_eur.toLocaleStr
1ing("es-ES")," â¬."]})]}),(0,n.jsx)("div",{className:"max-h-64 overflow-y-auto rounded-lg ring-1 ring-inset ring-gray-200",children:(0,n.jsxs)("table",{className:"w-full",children:[(0,n.jsx)("thead",{className:"bg-black/[0.02] border-b border-gray-200 sticky top-0",children:(0,n.jsxs)("tr",{children:[(0,n.jsx)(x.Th,{children:"L\xednea"}),(0,n.jsx)(x.Th,{children:"Nombre"}),(0,n.jsx)(x.Th,{children:"C\xf3digo"}),(0,n.jsx)(x.Th,{align:"right",children:"Saldo"}),(0,n.jsx)(x.Th,{children:"Acci\xf3n"})]})}),(0,n.jsx)("tbody",{className:"divide-y divide-gray-200",children:h.plan.map(e=>(0,n.jsxs)("tr",{className:e.errors.length?"bg-rose-50":"",children:[(0,n.jsx)(x.Td,{className:"text-xs text-gray-500",children:e.line}),(0,n.jsx)(x.Td,{className:"text-sm",children:e.name||(0,n.jsx)("span",{className:"text-rose-600",children:"falta"})}),(0,n.jsx)(x.Td,{className:"mono text-sm",children:e.code}),(0,n.jsx)(x.Td,{align:"right",className:"tabular-nums text-sm",children:e.opening_balance_eur?"".concat(e.opening_balance_eur.toLocaleString("es-ES")," â¬"):"â"}),(0,n.jsx)(x.Td,{className:"text-xs",children:e.errors.length?(0,n.jsx)("span",{className:"text-rose-700",children:e.errors.join(", ")}):"create"===e.action?"crear":"actualizar"})]},e.line))})]})})]}),(0,n.jsxs)("div",{className:"flex items-center justify-end gap-2 border-t border-gray-200 pt-4",children:[(0,n.jsx)(x.zx,{variant:"ghost",onClick:l,children:"Cancelar"}),(0,n.jsx)(x.zx,{variant:"secondary",onClick:()=>S(!1),disabled:v||!d||!u,children:v?"Leyendoâ¦":"Ver qu\xe9 har\xeda"}),(0,n.jsx)(x.zx,{onClick:()=>S(!0),disabled:v||!h||!!h.summary.with_errors,children:"Importar"})]})]})})})}function X(e){let{groups:s,partners:a}=e,[l,r]=(0,i.useState)({partner_id:"",group_id:"",from:"",to:"",status:"",attribution:"",unpaid:""}),[c,h]=(0,i.useState)(null),[p,j]=(0,i.useState)(null),[v,N]=(0,i.useState)(0),T=(0,i.useMemo)(()=>{let e=new URLSearchParams;return Object.entries(l).forEach(s=>{let[a,n]=s;n&&e.set(a,n)}),e},[l]),k=(0,i.useCallback)(async()=>{j(null);try{let e=new URLSearchParams(T);e.set("limit",String(200)),e.set("offset",String(v)),h(await g("/api/vet/commissions?".concat(e)))}catch(e){j(e.message)}},[T,v]);(0,i.useEffect)(()=>{k()},[k]);let L=(e,s)=>{N(0),r(a=>({...a,[e]:s}))},z="/api/vet/commissions?".concat(new URLSearchParams(T),"&format=csv");return(0,n.jsxs)(o.E,{gap:"500",children:[(0,n.jsxs)(t.$0,{children:[(0,n.jsxs)("div",{className:"grid sm:grid-cols-3 lg:grid-cols-6 gap-3",children:[(0,n.jsx)(x.Ph,{label:"Veterinario",value:l.partner_id,onChange:e=>L("partner_id",e),placeholder:"Todos",options:(a||[]).map(e=>({value:String(e.id),label:"".concat(e.name," (").concat(e.code,")")}))}),(0,n.jsx)(x.Ph,{label:"Grupo",value:l.group_id,onChange:e=>L("group_id",e),placeholder:"Todos",options:(s||[]).map(e=>({value:String(e.id),label:e.name}))}),(0,n.jsx)(x.II,{label:"Desde",type:"date",value:l.from,onChange:e=>L("from",e)}),(0,n.jsx)(x.II,{label:"Hasta",type:"date",value:l.to,onChange:e=>L("to",e)}),(0,n.jsx)(x.Ph,{label:"Estado",value:l.status,onChange:e=>L("status",e),placeholder:"Todos",options:[{value:"pending",label:"Pendientes"},{value:"paid",label:"Liquidadas"},{value:"reversed",label:"Anuladas"}]}),(0,n.jsx)(x.Ph,{label:"Origen",value:l.attribution,onChange:e=>L("attribution",e),placeholder:"Todos",options:[{value:"code",label:"Por c\xf3digo"},{value:"link",label:"Cliente ligado"}]})]}),(0,n.jsxs)(m.g,{align:"space-between",blockAlign:"center",gap:"300",children:[(0,n.jsxs)("label",{className:"flex items-center gap-2 text-sm text-gray-700",children:[(0,n.jsx)("input",{type:"checkbox",checked:"1"===l.unpaid,onChange:e=>L("unpaid",e.target.checked?"1":""),className:"rounded border-gray-300"}),"Solo sin liquidar"]}),(0,n.jsx)(x.zx,{variant:"secondary",href:z,target:"_blank",children:"Exportar CSV"})]})]}),p&&(0,n.jsx)(x.ub,{title:"No se pueden leer las comisiones",description:p}),!p&&!c&&(0,n.jsx)(P,{}),!p&&c&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-3",children:[(0,n.jsx)(w,{label:"L\xedneas",value:y(c.total)}),(0,n.jsx)(w,{label:"Base con IVA",value:b(c.base_cents)}),(0,n.jsx)(w,{label:"Comisi\xf3n",value:b(c.commission_cents),tone:0>Number(c.commission_cents)?"bad":void 0})]}),c.rows.length?(0,n.jsxs)(d.Z,{padding:"0",children:[(0,n.jsx)("div",{className:"overflow-x-auto",children:(0,n.jsxs)("table",{className:"w-full",children:[(0,n.jsx)("thead",{className:"bg-black/[0.02] border-b border-gray-200",children:(0,n.jsxs)("tr",{children:[(0,n.jsx)(x.Th,{children:"Pedido"}),(0,n.jsx)(x.Th,{children:"Veterinario"}),(0,n.jsx)(x.Th,{children:"Producto"}),(0,n.jsx)(x.Th,{children:"Cliente"}),(0,n.jsx)(x.Th,{children:"Origen"}),(0,n.jsx)(x.Th,{align:"right",children:"Base"}),(0,n.jsx)(x.Th,{align:"right",children:"Devuelto"}),(0,n.jsx)(x.Th,{align:"right",children:"%"}),(0,n.jsx)(x.Th,{align:"right",children:"Comisi\xf3n"}),(0,n.jsx)(x.Th,{children:"Estado"})]})}),(0,n.jsx)("tbody",{className:"divide-y divide-gray-200",children:c.rows.map(e=>(0,n.jsxs)("tr",{className:"reversed"===e.status?"opacity-50":"",children:[(0,n.jsxs)(x.Td,{children:[(0,n.jsx)(u.x,{as:"p",variant:"bodyMd",fontWeight:"medium",children:e.order_name}
1),(0,n.jsx)(u.x,{as:"p",variant:"bodySm",tone:"subdued",children:_(e.order_created_at)})]}),(0,n.jsxs)(x.Td,{children:[(0,n.jsx)(u.x,{as:"p",variant:"bodyMd",children:e.partner_name}),(0,n.jsx)("div",{className:"text-xs text-gray-500 mono",children:e.partner_code})]}),(0,n.jsxs)(x.Td,{className:"text-sm max-w-[220px]",children:[(0,n.jsx)("div",{className:"truncate",title:e.title,children:e.title}),(0,n.jsxs)(u.x,{as:"p",variant:"bodySm",tone:"subdued",children:[e.quantity>1&&"".concat(e.quantity," uds \xb7 "),e.is_subscription&&"suscripci\xf3n",e.is_adjustment&&(0,n.jsx)("span",{className:"text-amber-600",children:"rectificaci\xf3n"})]})]}),(0,n.jsx)(x.Td,{children:e.customer_id?(0,n.jsx)("a",{href:"".concat(C,"/customers/").concat(S(e.customer_id)),target:"_blank",rel:"noreferrer",className:"text-xs mono text-gray-500 hover:underline",children:S(e.customer_id)}):(0,n.jsx)(u.x,{as:"span",variant:"bodySm",tone:"subdued",children:"invitado"})}),(0,n.jsxs)(x.Td,{children:[(0,n.jsx)(q,{value:e.attribution}),e.code_used&&(0,n.jsx)("div",{className:"text-2xs text-gray-400 mono mt-0.5",children:e.code_used})]}),(0,n.jsx)(x.Td,{align:"right",className:"tabular-nums text-sm",children:b(e.base_cents)}),(0,n.jsx)(x.Td,{align:"right",className:"tabular-nums text-sm",children:Number(e.refunded_cents)>0?(0,n.jsx)("span",{className:"text-rose-600",children:b(e.refunded_cents)}):(0,n.jsx)("span",{className:"text-gray-300",children:"â"})}),(0,n.jsx)(x.Td,{align:"right",className:"tabular-nums text-xs text-gray-500",children:f(e.commission_pct)}),(0,n.jsx)(x.Td,{align:"right",className:"tabular-nums text-sm font-medium ".concat(0>Number(e.commission_cents)?"text-rose-600":""),children:b(e.commission_cents)}),(0,n.jsx)(x.Td,{children:(0,n.jsx)(I,{value:e.status})})]},"".concat(e.order_id,"-").concat(e.line_item_id)))})]})}),c.total>200&&(0,n.jsxs)("div",{className:"flex items-center justify-between px-4 py-3 border-t border-gray-200 text-sm",children:[(0,n.jsxs)("span",{className:"text-gray-500",children:[v+1," a ",Math.min(v+200,c.total)," de ",y(c.total)]}),(0,n.jsxs)("span",{className:"flex gap-2",children:[(0,n.jsx)(x.zx,{size:"sm",variant:"secondary",disabled:0===v,onClick:()=>N(Math.max(0,v-200)),children:"Anteriores"}),(0,n.jsx)(x.zx,{size:"sm",variant:"secondary",disabled:v+200>=c.total,onClick:()=>N(v+200),children:"Siguientes"})]})]})]}):(0,n.jsx)(x.ub,{title:"Sin resultados",description:"Con estos filtros no hay comisiones. Si acabas de dar de alta los veterinarios, espera la siguiente pasada del cron o l\xe1nzala desde Ajustes."}),c.rows.some(e=>0>Number(e.commission_cents))&&(0,n.jsx)(E,{tone:"info",title:"Hay rectificaciones en la lista",children:"Una rectificaci\xf3n es un reembolso que lleg\xf3 cuando la comisi\xf3n ya estaba liquidada. No se reescribe lo pagado: se resta en la liquidaci\xf3n siguiente."})]})]})}function W(e){let{partners:s,onChanged:a}=e,[t,l]=(0,i.useState)(null),[r,d]=(0,i.useState)(null),[c,m]=(0,i.useState)(null),[h,p]=(0,i.useState)(null),j=(0,i.useCallback)(async()=>{d(null);try{l((await g("/api/vet/payouts")).payouts)}catch(e){d(e.message)}},[]);(0,i.useEffect)(()=>{j()},[j]);let v=(s||[]).filter(e=>0!==Number(e.pending_cents)).sort((e,s)=>Number(s.pending_cents)-Number(e.pending_cents)),f=v.reduce((e,s)=>e+Number(s.pending_cents),0);return(0,n.jsxs)(o.E,{gap:"600",children:[(0,n.jsxs)("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-3",children:[(0,n.jsx)(w,{label:"Pendiente de emitir",value:b(f)}),(0,n.jsx)(w,{label:"Veterinarios con saldo",value:y(v.length)}),(0,n.jsx)(w,{label:"Emitido este a\xf1o",value:b((t||[]).filter(e=>"confirmed"===e.status&&new Date(e.confirmed_at).getFullYear()===new Date().getFullYear()).reduce((e,s)=>e+Number(s.total_cents),0))})]}),(0,n.jsxs)("section",{className:"glass overflow-hidden",children:[(0,n.jsxs)("div",{className:"px-4 sm:px-5 py-4 border-b border-gray-200",children:[(0,n.jsx)(u.x,{as:"h2",variant:"headingMd",children:"Por emitir"}),(0,n.jsx)("p",{className:"text-xs text-gray-500 mt-0.5",children:"Comisiones acumuladas que todav\xeda no se han pagado, con el saldo inicial de ca
1da veterinario incluido."})]}),v.length?(0,n.jsx)("div",{className:"overflow-x-auto",children:(0,n.jsxs)("table",{className:"w-full",children:[(0,n.jsx)("thead",{className:"bg-black/[0.02] border-b border-gray-200",children:(0,n.jsxs)("tr",{children:[(0,n.jsx)(x.Th,{children:"Veterinario"}),(0,n.jsx)(x.Th,{children:"Grupo"}),(0,n.jsx)(x.Th,{align:"right",children:"Clientes ligados"}),(0,n.jsx)(x.Th,{align:"right",children:"Pendiente"}),(0,n.jsx)(x.Th,{children:"Estado"}),(0,n.jsx)(x.Th,{})]})}),(0,n.jsx)("tbody",{className:"divide-y divide-gray-200",children:v.map(e=>(0,n.jsxs)("tr",{children:[(0,n.jsxs)(x.Td,{children:[(0,n.jsx)("div",{className:"font-medium text-gray-900",children:e.name}),(0,n.jsxs)("div",{className:"text-xs text-gray-500 mono",children:[e.code,e.tax_id?" \xb7 ".concat(e.tax_id):""]})]}),(0,n.jsx)(x.Td,{className:"text-sm text-gray-600",children:e.group_name}),(0,n.jsx)(x.Td,{align:"right",className:"tabular-nums text-sm",children:y(e.linked_customers)}),(0,n.jsx)(x.Td,{align:"right",className:"tabular-nums font-semibold ".concat(0>Number(e.pending_cents)?"text-rose-600":""),children:b(e.pending_cents)}),(0,n.jsx)(x.Td,{children:(0,n.jsx)(I,{value:e.status})}),(0,n.jsx)(x.Td,{align:"right",children:(0,n.jsx)(x.zx,{size:"sm",onClick:()=>m(e),children:"Revisar y emitir"})})]},e.id))})]})}):(0,n.jsx)(x.ub,{title:"Nada pendiente",description:"Cuando se generen comisiones nuevas aparecer\xe1n aqu\xed."})]}),(0,n.jsxs)("section",{className:"glass overflow-hidden",children:[(0,n.jsx)("div",{className:"px-4 sm:px-5 py-4 border-b border-gray-200",children:(0,n.jsx)(u.x,{as:"h2",variant:"headingMd",children:"Hist\xf3rico"})}),r&&(0,n.jsx)(x.ub,{title:"No se puede leer el hist\xf3rico",description:r}),!r&&!t&&(0,n.jsx)(P,{}),!r&&t&&!t.length&&(0,n.jsx)(x.ub,{title:"Todav\xeda no se ha emitido ninguna liquidaci\xf3n"}),!r&&!!(null==t?void 0:t.length)&&(0,n.jsx)("div",{className:"overflow-x-auto",children:(0,n.jsxs)("table",{className:"w-full",children:[(0,n.jsx)("thead",{className:"bg-black/[0.02] border-b border-gray-200",children:(0,n.jsxs)("tr",{children:[(0,n.jsx)(x.Th,{children:"Fecha"}),(0,n.jsx)(x.Th,{children:"Veterinario"}),(0,n.jsx)(x.Th,{children:"Periodo"}),(0,n.jsx)(x.Th,{align:"right",children:"L\xedneas"}),(0,n.jsx)(x.Th,{align:"right",children:"Importe"}),(0,n.jsx)(x.Th,{children:"Referencia"}),(0,n.jsx)(x.Th,{children:"Estado"}),(0,n.jsx)(x.Th,{})]})}),(0,n.jsx)("tbody",{className:"divide-y divide-gray-200",children:t.map(e=>(0,n.jsxs)("tr",{className:"cancelled"===e.status?"opacity-50":"",children:[(0,n.jsx)(x.Td,{className:"text-sm",children:N(e.confirmed_at)}),(0,n.jsxs)(x.Td,{children:[(0,n.jsx)(u.x,{as:"p",variant:"bodyMd",children:e.partner_name}),(0,n.jsx)("div",{className:"text-xs text-gray-500 mono",children:e.code})]}),(0,n.jsx)(x.Td,{className:"text-xs text-gray-500",children:e.period_from||e.period_to?"".concat(e.period_from?_(e.period_from):"inicio"," a ").concat(e.period_to?_(e.period_to):"hoy"):"todo lo pendiente"}),(0,n.jsx)(x.Td,{align:"right",className:"tabular-nums text-sm",children:y(e.lines_count)}),(0,n.jsx)(x.Td,{align:"right",className:"tabular-nums font-medium",children:b(e.total_cents)}),(0,n.jsx)(x.Td,{className:"text-xs text-gray-500",children:e.reference||"â"}),(0,n.jsx)(x.Td,{children:(0,n.jsx)(I,{value:e.status})}),(0,n.jsx)(x.Td,{align:"right",children:(0,n.jsx)(x.zx,{size:"sm",variant:"secondary",onClick:()=>p(e.id),children:"Ver"})})]},e.id))})]})})]}),c&&(0,n.jsx)(Z,{partner:c,onClose:()=>m(null),onDone:async()=>{m(null),await j(),null==a||a()}}),h&&(0,n.jsx)($,{payoutId:h,onClose:()=>p(null),onChanged:async()=>{await j(),null==a||a()}})]})}function Z(e){var s,a,t,l,r,d;let{partner:c,onClose:m,onDone:h}=e,[j,v]=(0,i.useState)({from:"",to:""}),[N,S]=(0,i.useState)(null),[C,T]=(0,i.useState)(null),[I,L]=(0,i.useState)({reference:"",note:"",include_opening_balance:!0}),[z,A]=(0,i.useState)(!1),[D,F]=(0,i.useState)(!1),R=(0,i.useCallback)(async()=>{T(null),S(null);try{let e=new URLSearchParams({preview:"1",partner_id:String(c.id)});j.from&&e.set("from",j.from),j.to&&e.set("to",j.to),S(await g("/api/vet/payouts?".concat(e)))}catch(e){T(e.message)}},[c.id,j.from,j.to]);(0,i.useEffect)(()=>{R()},[R]);let M=Number((null==N?void 0:null===(s=N.summary)||void 0===s?void 0:s.opening_balance_cents)||0),V=Number((null==N?void 0:null===(a=N.summary)||void 0===a?void 0:a.commission_cents)||0),O=V+(I.include_opening_balance?M:0),G=((null==N?void 0:N.lines)||[]).some(e=>e.is_adjustment),B=I.include_opening_balance&&M>0,U=(null==N?void 0:N.history)||null,H=!!N&&0===N.lines.length&&B,X=async()=>{A(!0),T(null);try{let e=await p("/api/vet/payouts","POST",{action:"confirm",partner_id:c.id,from:j.from||null,to:j.to||null,reference:I.reference||null,note:I.note||null,include_opening_balance:I.include_opening_balance});window.alert("Liquidaci\xf3n ".concat(e.id," emitida por ").concat((e.total_cents/100).toLocaleStr
1ing("es-ES",{minimumFractionDigits:2})," â¬")),await h()}catch(e){T(e.message),F(!1)}finally{A(!1)}};return(0,n.jsx)(k,{title:"Emitir liquidaci\xf3n \xb7 ".concat(c.name),subtitle:"".concat(c.code).concat(c.tax_id?" \xb7 ".concat(c.tax_id):""," \xb7 comisi\xf3n ").concat(f(c.effective_commission_pct)),onClose:m,wide:!0,children:(0,n.jsxs)(o.E,{gap:"400",children:[(0,n.jsxs)("div",{className:"grid sm:grid-cols-2 gap-3",children:[(0,n.jsx)(x.II,{label:"Desde (opcional)",type:"date",value:j.from,onChange:e=>v(s=>({...s,from:e}))}),(0,n.jsx)(x.II,{label:"Hasta (opcional)",type:"date",value:j.to,onChange:e=>v(s=>({...s,to:e})),hint:"Vac\xedo los dos = todo lo pendiente"})]}),C&&(0,n.jsx)(E,{tone:"bad",children:C}),!N&&!C&&(0,n.jsx)(P,{text:"Calculandoâ¦"}),N&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-3",children:H?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(w,{label:"Pedidos que lo generaron",value:y((null==U?void 0:U.orders)||0),sub:(null==U?void 0:U.orders)?"anteriores a la fecha de corte":"sin hist\xf3rico reconstruido"}),(0,n.jsx)(w,{label:"Base de esos pedidos",value:b((null==U?void 0:U.base_cents)||0)}),(0,n.jsx)(w,{label:"Comisi\xf3n que generaron",value:b((null==U?void 0:U.total_cents)||0),sub:U&&Number(U.total_cents)>M?"".concat(b(Number(U.total_cents)-M)," ya pagados antes"):void 0}),(0,n.jsx)(w,{label:"Total a emitir",value:b(O),tone:O>0?"good":"bad",sub:"lo que queda pendiente"})]}):(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(w,{label:"L\xedneas",value:y(N.summary.lines),sub:N.reversed_count>0?"".concat(y(N.reversed_count)," anuladas, fuera"):void 0}),(0,n.jsx)(w,{label:"Base con IVA",value:b(N.summary.base_cents)}),(0,n.jsx)(w,{label:"Comisi\xf3n del periodo",value:b(V),tone:V<0?"bad":void 0}),(0,n.jsx)(w,{label:"Total a emitir",value:b(O),tone:O>0?"good":"bad",sub:B?"".concat(b(V)," del periodo + ").concat(b(M)," de saldo inicial"):void 0})]})}),M>0&&(0,n.jsxs)("label",{className:"flex items-center gap-2 text-sm text-gray-700",children:[(0,n.jsx)("input",{type:"checkbox",checked:I.include_opening_balance,onChange:e=>L(s=>({...s,include_opening_balance:e.target.checked})),className:"rounded border-gray-300"}),"Incluir el saldo inicial pendiente (",b(M),")"]}),G&&(0,n.jsx)(E,{tone:"warn",title:"Hay rectificaciones por reembolsos",children:"Se restan del total. Vienen de pedidos devueltos cuya comisi\xf3n ya se hab\xeda pagado en una liquidaci\xf3n anterior."}),Number(N.summary.adjustments)>0&&V<0&&(0,n.jsx)(E,{tone:"bad",title:"El periodo sale negativo",children:"Los reembolsos superan las comisiones nuevas. No se puede emitir en negativo: deja el saldo como est\xe1 y se compensar\xe1 con las comisiones del mes que viene."}),(0,n.jsxs)("div",{className:"grid sm:grid-cols-2 gap-3 border-t border-gray-200 pt-4",children:[(0,n.jsx)(x.II,{label:"Referencia (n\xba de factura, pagoâ¦)",value:I.reference,onChange:e=>L(s=>({...s,reference:e}))}),(0,n.jsx)(x.II,{label:"Nota",value:I.note,onChange:e=>L(s=>({...s,note:e}))})]}),B&&(null===(l=N.history)||void 0===l?void 0:null===(t=l.rows)||void 0===t?void 0:t.length)>0&&(0,n.jsxs)("details",{className:"glass p-3",open:H,children:[(0,n.jsxs)("summary",{className:"text-sm font-medium text-gray-900 cursor-pointer",children:["De d\xf3nde viene el saldo inicial de ",b(M),(0,n.jsxs)("span",{className:"font-normal text-gray-500",children:[" \xb7 ",y(N.history.orders)," pedidos anteriores al corte"]})]}),(0,n.jsxs)("div",{className:"mt-3 space-y-3",children:[(0,n.jsxs)("p",{className:"text-xs text-gray-500 leading-relaxed",children:["Estos son todos los pedidos de este veterinario anteriores a la fecha de corte, con la comisi\xf3n recalculada por nosotros: ",b(N.history.total_cents)," sobre una base de ",b(N.history.base_cents),".",Math.abs(Number(N.history.total_cents)-M)>100&&(0,n.jsxs)(n.Fragment,{children:[" El saldo que arrastra es ",b(M),", menos que el total: la diferencia es lo que el sistema anterior ya le hab\xeda pagado."]})," ","No se pueden liquidar otra vez: ya est\xe1n dentro del saldo."]}),(0,n.jsx)("div",{className:"max-h-60 overflow-y-auto",children:(0,n.jsxs)("table",{className:"w-full",children:[(0,n.jsx)("thead",{className:"border-b border-gray-200",children:(0,n.jsxs)("tr",{children:[(0,n.jsx)(x.Th,{children:"Pedido"}),(0,n.jsx)(x.Th,{children:"Producto"}),(0,n.jsx)(x.Th,{align:"right",children:"Base"}),(0,n.jsx)(x.Th,{align:"right",children:"Comisi\xf3n"})]})}),(0,n.jsx)("tbody",{className:"divide-y divide-gray-200",children:N.history.rows.map(e=>(0,n.jsxs)("tr",{children:[(0,n.jsxs)(x.Td,{children:[(0,n.jsx)("div",{className:"text-sm",children:e.order_name}),(0,n.jsx)("div",{className:"text-xs text-gray-500",children:_(e.order_created_at)})]}),(0,n.jsx)(x.Td,{className:"text-sm max-w-[220px]",children:(0,n.jsx)("div",{className:"truncate",title:e.title,children:e.title})}),(0,n.jsx)(x.Td,{align:"right",className:"tabular-nums text-sm",children:b(e.base_cents)}),(0,n.jsx)(x.Td,{align:"right",className:"tabular-nums text-sm",children:b(e.commission_cents)})]},"".concat(e.order_id,"-").concat(e.line_item_id)))})]})})]})]}),N.lines.length?(0,n.jsxs)("details",{className:"glass p-3",children:[(0,n.jsx)("summary",{className:"text-sm font-medium text-gray-900 cursor-pointer",children:1===N.lines.length?"Detalle de la l\xednea incluida":"Detalle de las ".concat(y(N.lines.length)," l\xedneas incluidas")}),(0,n.jsx)("div",{className:"mt-3 max-h-72 overflow-y-auto",children:(0,n.jsxs)("table",{className:"w-full",children:[(0,n.jsx)("thead",{className:"border-b border-gray-200",children:(0,n.jsxs)("tr",{children:[(0,n.jsx)(x.Th,{children:"Pedido"}),(0,n.jsx)(x.Th,{children:"Producto"}),(0,n.jsx)(x.Th,{children:"Origen"}),(0,n.jsx)(x.Th,{align:"right",children:"Base"}),(0,n.jsx)(x.Th,{align:"right",children:"Comisi\xf3n"})]})}),(0,n.jsx)("tbody",{className:"divide-y divide-gray-200",children:N.lines.map(e=>(0,n.jsxs)("tr",{children:[(0,n.jsxs)(x.Td,{children:[(0,n.jsx)(u.x,{as:"p",variant:"bodyMd",children:e.order_name}
1),(0,n.jsx)(u.x,{as:"p",variant:"bodySm",tone:"subdued",children:_(e.order_created_at)})]}),(0,n.jsx)(x.Td,{className:"text-sm max-w-[200px]",children:(0,n.jsx)("div",{className:"truncate",title:e.title,children:e.title})}),(0,n.jsx)(x.Td,{children:(0,n.jsx)(q,{value:e.attribution})}),(0,n.jsx)(x.Td,{align:"right",className:"tabular-nums text-sm",children:b(e.base_cents)}),(0,n.jsx)(x.Td,{align:"right",className:"tabular-nums text-sm font-medium ".concat(0>Number(e.commission_cents)?"text-rose-600":""),children:b(e.commission_cents)})]},"".concat(e.order_id,"-").concat(e.line_item_id)))})]})})]}):(0,n.jsxs)(E,{tone:"info",children:["No hay comisiones nuevas en este periodo.",N.reversed_count>0&&" Las ".concat(y(N.reversed_count)," l\xedneas anuladas no cuentan: se anularon al mover la fecha de corte, porque ese periodo ya est\xe1 dentro del saldo inicial."),B?(null===(d=N.history)||void 0===d?void 0:null===(r=d.rows)||void 0===r?void 0:r.length)?" Se emite solo el saldo inicial: arriba tienes el detalle de los pedidos de los que viene.":" Se emite solo el saldo inicial pendiente.":" Sin el saldo inicial no hay nada que emitir."]}),D?(0,n.jsxs)("div",{className:"border-t border-gray-200 pt-4",children:[(0,n.jsxs)(E,{tone:"warn",title:"\xdaltima comprobaci\xf3n",children:["Se van a congelar ",y(N.lines.length)," l\xedneas por ",b(O)," a nombre de"," ",(0,n.jsx)("b",{children:c.name}),". Despu\xe9s ya no se recalculan: si llega un reembolso se descontar\xe1 de la liquidaci\xf3n siguiente."]}),(0,n.jsxs)("div",{className:"flex items-center justify-end gap-2 mt-3",children:[(0,n.jsx)(x.zx,{variant:"ghost",onClick:()=>F(!1),children:"Volver"}),(0,n.jsx)(x.zx,{onClick:X,disabled:z,children:z?"Emitiendoâ¦":"S\xed, emitir"})]})]}):(0,n.jsxs)("div",{className:"flex items-center justify-end gap-2 border-t border-gray-200 pt-4",children:[(0,n.jsx)(x.zx,{variant:"ghost",onClick:m,children:"Cancelar"}),(0,n.jsxs)(x.zx,{onClick:()=>F(!0),disabled:O<=0,children:["Confirmar emisi\xf3n de ",b(O)]})]})]})]})})}function $(e){let{payoutId:s,onClose:a,onChanged:t}=e,[l,r]=(0,i.useState)(null),[d,c]=(0,i.useState)(null),m=(0,i.useCallback)(async()=>{c(null);try{r(await g("/api/vet/payouts?id=".concat(s)))}catch(e){c(e.message)}},[s]);return(0,i.useEffect)(()=>{m()},[m]),(0,n.jsxs)(k,{title:l?"Liquidaci\xf3n ".concat(l.id," \xb7 ").concat(l.partner_name):"Liquidaci\xf3n",subtitle:l?"".concat(N(l.confirmed_at)," \xb7 ").concat(l.confirmed_by||"sin firmar"):void 0,onClose:a,wide:!0,children:[d&&(0,n.jsx)(E,{tone:"bad",children:d}),!d&&!l&&(0,n.jsx)(P,{}),!d&&l&&(0,n.jsxs)(o.E,{gap:"400",children:[(0,n.jsxs)("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-3",children:[(0,n.jsx)(w,{label:"Importe",value:b(l.total_cents)}),(0,n.jsx)(w,{label:"L\xedneas",value:y(l.lines_count)}),(0,n.jsx)(w,{label:"Estado",value:(0,n.jsx)(I,{value:l.status})}),(0,n.jsx)(w,{label:"Referencia",value:l.reference||"â"})]}),l.note&&(0,n.jsx)(E,{tone:"info",children:l.note}),(0,n.jsx)("div",{className:"overflow-x-auto max-h-80 overflow-y-auto",children:(0,n.jsxs)("table",{className:"w-full",children:[(0,n.jsx)("thead",{className:"border-b border-gray-200 sticky top-0 bg-white/80",children:(0,n.jsxs)("tr",{children:[(0,n.jsx)(x.Th,{children:"Pedido"}),(0,n.jsx)(x.Th,{children:"Producto"}),(0,n.jsx)(x.Th,{children:"Origen"}),(0,n.jsx)(x.Th,{align:"right",children:"Base"}),(0,n.jsx)(x.Th,{align:"right",children:"%"}),(0,n.jsx)(x.Th,{align:"right",children:"Comisi\xf3n"})]})}),(0,n.jsx)("tbody",{className:"divide-y divide-gray-200",children:l.lines.map(e=>(0,n.jsxs)("tr",{children:[(0,n.jsxs)(x.Td,{children:[(0,n.jsx)(u.x,{as:"p",variant:"bodyMd",children:e.order_name}),(0,n.jsx)(u.x,{as:"p",variant:"bodySm",tone:"subdued",children:_(e.order_created_at)})]}),(0,n.jsx)(x.Td,{className:"text-sm max-w-[220px]",children:(0,n.jsx)("div",{className:"truncate",title:e.title,children:e.title})}),(0,n.jsx)(x.Td,{children:(0,n.jsx)(q,{value:e.attribution})}),(0,n.jsx)(x.Td,{align:"right",className:"tabular-nums text-sm",children:b(e.base_cents)}),(0,n.jsx)(x.Td,{align:"right",className:"tabular-nums text-xs text-gray-500",children:f(e.commission_pct)}),(0,n.jsx)(x.Td,{align:"right",className:"tabular-nums text-sm font-medium ".concat(0>Number(e.commission_cents)?"text-rose-600":""),children:b(e.commission_cents)})]},"".concat(e.order_id,"-").concat(e.line_item_id)))})]})}),"confirmed"===l.status&&(0,n.jsxs)("div",{className:"border-t border-gray-200 pt-4 flex items-center justify-between gap-3",children:[(0,n.jsx)("p",{className:"text-xs text-gray-500 max-w-md",children:"Anular devuelve estas comisiones a pen
1diente. Solo tiene sentido si la liquidaci\xf3n se emiti\xf3 por error y todav\xeda no se ha pagado al veterinario."}),(0,n.jsx)(L,{variant:"btn-danger",confirm:"Se van a devolver todas las comisiones de esta liquidaci\xf3n a pendiente. \xbfSeguimos?",onRun:async()=>{let e=window.prompt("Motivo de la anulaci\xf3n");e&&(await p("/api/vet/payouts","POST",{action:"cancel",payout_id:l.id,reason:e}),await m(),await t())},children:"Anular liquidaci\xf3n"})]})]})]})}let Y=[{key:"resumen",label:"Resumen"},{key:"grupos",label:"Grupos"},{key:"veterinarios",label:"Veterinarios"},{key:"comisiones",label:"Comisiones"},{key:"liquidaciones",label:"Liquidaciones"},{key:"ajustes",label:"Ajustes"}];function Q(){let e=(0,l.useRouter)(),[s,a]=(0,i.useState)("resumen"),[t,u]=(0,i.useState)(null),[m,h]=(0,i.useState)([]),[p,j]=(0,i.useState)([]),[b,v]=(0,i.useState)(null),[y,f]=(0,i.useState)(!1);(0,i.useEffect)(()=>{if(!e.isReady)return;let s=String(e.query.tab||"resumen");a(Y.some(e=>e.key===s)?s:"resumen")},[e.isReady,e.query.tab]);let _=s=>{a(s),e.push({pathname:"/veterinarios",query:"resumen"===s?{}:{tab:s}},void 0,{shallow:!0})},N=(0,i.useCallback)(async()=>{v(null);try{let[e,s,a]=await Promise.all([g("/api/vet/overview"),g("/api/vet/groups"),g("/api/vet/partners")]);u(e),h(s.groups),j(a.partners),f(!1)}catch(e){v(e.message),f(!!e.needsSchema)}},[]);(0,i.useEffect)(()=>{N()},[N]);let S=Math.max(0,Y.findIndex(e=>e.key===s));return(0,n.jsx)(r.T,{fullWidth:!0,title:"Veterinarios",subtitle:"Comisiones de los veterinarios que recomiendan Onlyfresh. El cliente usa el c\xf3digo en su primer pedido y se lleva el descuento; desde ese momento queda ligado a su veterinario, que sigue cobrando comisi\xf3n en los pedidos siguientes.",children:y?(0,n.jsx)(J,{error:b,onApplied:N}):(0,n.jsxs)(o.E,{gap:"400",children:[(0,n.jsx)(d.Z,{padding:"0",children:(0,n.jsx)(c.m,{tabs:Y.map(e=>({id:e.key,content:e.label})),selected:S,onSelect:e=>_(Y[e].key)})}),b&&(0,n.jsx)(x.ub,{title:"No se puede leer el estado del programa",description:b}),!b&&!t&&(0,n.jsx)(d.Z,{children:(0,n.jsx)("div",{className:"py-10 text-center",children:(0,n.jsx)(x.$j,{})})}),!b&&t&&(0,n.jsxs)(n.Fragment,{children:["resumen"===s&&(0,n.jsx)(K,{data:t,onGoTo:_}),"grupos"===s&&(0,n.jsx)(D,{onChanged:N}),"veterinarios"===s&&(0,n.jsx)(V,{groups:m,onChanged:N}),"comisiones"===s&&(0,n.jsx)(X,{groups:m,partners:p}),"liquidaciones"===s&&(0,n.jsx)(W,{partners:p,onChanged:N}),"ajustes"===s&&(0,n.jsx)(ea,{runs:t.last_runs,onChanged:N})]})]})})}function J(e){let{error:s,onApplied:a}=e,[l,r]=(0,i.useState)(null);return(0,n.jsx)("div",{className:"max-w-2xl",children:(0,n.jsxs)(t.$0,{children:[(0,n.jsx)(u.x,{as:"h2",variant:"headingMd",children:"Falta preparar la base de datos"}),(0,n.jsxs)("p",{className:"text-sm text-gray-600 mt-1",children:["Veterinarios guarda sus datos en el esquema ",(0,n.jsx)("code",{className:"mono",children:"vet"}),", que todav\xeda no existe. Se crea una sola vez y no toca nada de lo que ya hay."]}),(0,n.jsx)("p",{className:"text-xs text-gray-500 mt-2",children:s}),l&&(0,n.jsx)("div",{className:"mt-3",children:(0,n.jsx)(E,{tone:"bad",children:l})}),(0,n.jsx)("div",{className:"mt-4",children:(0,n.jsx)(L,{variant:"btn-primary",onRun:async()=>{r(null);try{await p("/api/vet/migrate","POST"),await a()}catch(e){r("".concat(e.message,". Alternativa: pega scripts/vet-schema.sql en el SQL editor de Supabase."))}},children:"Aplicar esquema"})})]})})}function K(e){var s,a,i,t;let{data:l,onGoTo:r}=e,d=null===(s=l.by_attribution)||void 0===s?void 0:s.code,c=null===(a=l.by_attribution)||void 0===a?void 0:a.link,m=(()=>{let e=Number((null==d?void 0:d.commission_cents)||0),s=Number((null==c?void 0:c.commission_cents)||0);return e+s>0?s/(e+s):0})(),h=Math.max(1,...(l.links_by_month||[]).map(e=>Number(e.n)));return(0,n.jsxs)(o.E,{gap:"600",children:[(0,n.jsxs)("div",{className:"grid grid-cols-2 lg:grid-cols-4 gap-3",children:[(0,n.jsx)(w,{label:"Pendiente de liquidar",value:b(l.pending_cents),sub:"".concat(y(l.active_partners)," veterinarios activos"),hint:"Comisiones generadas que todav\xeda no se han pagado, m\xe1s el saldo inicial de ca
1da veterinario."}),(0,n.jsx)(w,{label:"Comisi\xf3n ".concat(l.days," d\xedas"),value:b(l.window.commission_cents),sub:"".concat(y(l.window.orders)," pedidos")}),(0,n.jsx)(w,{label:"Coste del programa ".concat(l.days," d\xedas"),value:b(l.window.program_cost_cents),sub:"descuento ".concat(v(l.window.discount_cents)," + comisi\xf3n ").concat(v(l.window.commission_cents)),hint:"Lo que cuesta de verdad: el descuento que se lleva el cliente m\xe1s la comisi\xf3n del veterinario."}),(0,n.jsx)(w,{label:"Clientes ligados",value:y(l.linked_customers),sub:l.paused_partners>0?"".concat(y(l.paused_partners)," vets pausados"):void 0,hint:"Clientes asociados a un veterinario de forma permanente. Sus pedidos generan comisi\xf3n aunque no usen ning\xfan c\xf3digo."})]}),(0,n.jsxs)("section",{className:"glass p-4 sm:p-5",children:[(0,n.jsx)(u.x,{as:"h2",variant:"headingMd",children:"De d\xf3nde sale la comisi\xf3n"}),(0,n.jsxs)("p",{className:"text-xs text-gray-500 mt-0.5 mb-4",children:["\xdaltimos ",l.days," d\xedas. Las comisiones por cliente ligado son pedidos a precio completo: el cliente no tiene descuento, pero el veterinario cobra. Esta parte crece sola con el tiempo, conviene mirarla."]}),(0,n.jsxs)("div",{className:"grid sm:grid-cols-2 gap-4",children:[(0,n.jsx)(ee,{title:"Por c\xf3digo",subtitle:"Primer pedido del cliente, con descuento",orders:null==d?void 0:d.orders,base:null==d?void 0:d.base_cents,commission:null==d?void 0:d.commission_cents}),(0,n.jsx)(ee,{title:"Por cliente ligado",subtitle:"Pedidos siguientes, a precio completo",orders:null==c?void 0:c.orders,base:null==c?void 0:c.base_cents,commission:null==c?void 0:c.commission_cents,accent:!0})]}),(0,n.jsxs)("div",{className:"mt-4",children:[(0,n.jsxs)("div",{className:"flex items-center justify-between text-xs text-gray-500 mb-1",children:[(0,n.jsx)("span",{children:"Peso del cliente ligado sobre la comisi\xf3n"}),(0,n.jsxs)("span",{className:"tabular-nums font-medium text-gray-900",children:[(100*m).toFixed(0)," %"]})]}),(0,n.jsx)("div",{className:"h-2 rounded-full bg-gray-100 overflow-hidden",children:(0,n.jsx)("div",{className:"h-full bg-violet-500",style:{width:"".concat(Math.round(100*m),"%")}})})]})]}),(0,n.jsxs)("section",{className:"glass overflow-hidden",children:[(0,n.jsxs)("div",{className:"flex items-center justify-between gap-3 px-4 sm:px-5 py-4 border-b border-gray-200",children:[(0,n.jsxs)("div",{children:[(0,n.jsx)(u.x,{as:"h2",variant:"headingMd",children:"Veterinarios por comisi\xf3n"}),(0,n.jsxs)("p",{className:"text-xs text-gray-500 mt-0.5",children:["\xdaltimos ",l.days," d\xedas"]})]}),(0,n.jsx)(x.zx,{size:"sm",variant:"secondary",onClick:()=>r("veterinarios"),children:"Ver todos"})]}),(null===(i=l.top_partners)||void 0===i?void 0:i.length)?(0,n.jsx)("div",{className:"overflow-x-auto",children:(0,n.jsxs)("table",{className:"w-full",children:[(0,n.jsx)("thead",{className:"bg-black/[0.02] border-b border-gray-200",children:(0,n.jsxs)("tr",{children:[(0,n.jsx)(x.Th,{children:"Veterinario"}),(0,n.jsx)(x.Th,{children:"Grupo"}),(0,n.jsx)(x.Th,{align:"right",children:"Pedidos"}),(0,n.jsx)(x.Th,{align:"right",children:"Por v\xednculo"}),(0,n.jsx)(x.Th,{align:"right",children:"Base"}),(0,n.jsx)(x.Th,{align:"right",children:"Comisi\xf3n"}),(0,n.jsx)(x.Th,{children:"Estado"})]})}),(0,n.jsx)("tbody",{className:"divide-y divide-gray-200",children:l.top_partners.map(e=>(0,n.jsxs)("tr",{children:[(0,n.jsxs)(x.Td,{children:[(0,n.jsx)("div",{className:"font-medium text-gray-900",children:e.name}),(0,n.jsx)("div",{className:"text-xs text-gray-500 mono",children:e.code})]}),(0,n.jsx)(x.Td,{className:"text-sm text-gray-600",children:e.group_name}),(0,n.jsx)(x.Td,{align:"right",className:"tabular-nums text-sm",children:y(e.orders)}),(0,n.jsx)(x.Td,{align:"right",className:"tabular-nums text-sm text-violet-700",children:y(e.link_orders)}),(0,n.jsx)(x.Td,{align:"right",className:"tabular-nums text-sm",children:v(e.base_cents)}),(0,n.jsx)(x.Td,{align:"right",className:"tabular-nums font-medium",children:b(e.commission_cents)}),(0,n.jsx)(x.Td,{children:(0,n.jsx)(I,{value:e.status})})]},e.id))})]})}
1):(0,n.jsx)(x.ub,{title:"Todav\xeda no hay veterinarios",description:"Empieza creando un grupo con la comisi\xf3n, y despu\xe9s da de alta los veterinarios con sus c\xf3digos.",action:(0,n.jsx)(x.zx,{onClick:()=>r("grupos"),children:"Crear el primer grupo"})})]}),!!(null===(t=l.links_by_month)||void 0===t?void 0:t.length)&&(0,n.jsxs)("section",{className:"glass p-4 sm:p-5",children:[(0,n.jsx)(u.x,{as:"h2",variant:"headingMd",children:"Clientes ligados por mes"}),(0,n.jsx)("p",{className:"text-xs text-gray-500 mt-0.5 mb-4",children:"Cada cliente que entra aqu\xed genera comisi\xf3n en todos sus pedidos futuros."}),(0,n.jsx)("div",{className:"flex items-end gap-2 h-32",children:[...l.links_by_month].reverse().map(e=>(0,n.jsxs)("div",{className:"flex-1 flex flex-col items-center gap-1 min-w-0",children:[(0,n.jsx)(u.x,{as:"p",variant:"bodyXs",tone:"subdued",numeric:!0,children:y(e.n)}),(0,n.jsx)("div",{className:"w-full bg-violet-400 rounded-t",style:{height:"".concat(Math.max(4,Number(e.n)/h*96),"px")}}),(0,n.jsx)("div",{className:"text-2xs text-gray-400 truncate w-full text-center",children:new Date(e.month).toLocaleDateString("es-ES",{month:"short"})})]},e.month))})]}),(0,n.jsx)(es,{runs:l.last_runs})]})}function ee(e){let{title:s,subtitle:a,orders:i,base:t,commission:l,accent:r}=e;return(0,n.jsxs)("div",{className:"rounded-lg ring-1 ring-inset p-4 ".concat(r?"ring-violet-200 bg-violet-50":"ring-gray-200"),children:[(0,n.jsx)(u.x,{as:"p",variant:"headingSm",children:s}),(0,n.jsx)("div",{className:"text-xs text-gray-500 mb-3",children:a}),(0,n.jsxs)("div",{className:"grid grid-cols-3 gap-2",children:[(0,n.jsxs)("div",{children:[(0,n.jsx)(u.x,{as:"p",variant:"bodyXs",tone:"subdued",children:"Pedidos"}),(0,n.jsx)(u.x,{as:"p",variant:"headingLg",numeric:!0,children:y(i||0)})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)(u.x,{as:"p",variant:"bodyXs",tone:"subdued",children:"Base"}),(0,n.jsx)(u.x,{as:"p",variant:"headingLg",numeric:!0,children:v(t||0)})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)(u.x,{as:"p",variant:"bodyXs",tone:"subdued",children:"Comisi\xf3n"}),(0,n.jsx)(u.x,{as:"p",variant:"headingLg",numeric:!0,children:v(l||0)})]})]})]})}function es(e){let{runs:s}=e;return(null==s?void 0:s.length)?(0,n.jsxs)("section",{className:"glass overflow-hidden",children:[(0,n.jsxs)("div",{className:"px-4 sm:px-5 py-4 border-b border-gray-200",children:[(0,n.jsx)(u.x,{as:"h2",variant:"headingMd",children:"\xdaltimas pasadas del motor"}),(0,n.jsx)("p",{className:"text-xs text-gray-500 mt-0.5",children:"El cron repasa cada 15 minutos los pedidos nuevos y los modificados, para recoger tambi\xe9n reembolsos y cancelaciones."})]}),(0,n.jsx)("div",{className:"divide-y divide-gray-200",children:s.map(e=>(0,n.jsxs)("div",{className:"px-4 sm:px-5 py-3 flex flex-wrap items-center gap-x-4 gap-y-1 text-sm",children:[(0,n.jsx)("span",{className:"w-2 h-2 rounded-full shrink-0 ".concat("ok"===e.status?"bg-emerald-500":"error"===e.status?"bg-rose-500":"bg-amber-500")}),(0,n.jsx)("span",{className:"text-gray-900 font-medium",children:"links-bootstrap"===e.kind?"v\xednculos":"atribuci\xf3n"}),(0,n.jsxs)(u.x,{as:"span",variant:"bodySm",tone:"subdued",children:[N(e.started_at)," \xb7 ",e.trigger]}),e.stats&&(0,n.jsxs)(u.x,{as:"span",variant:"bodySm",tone:"subdued",children:[y(e.stats.orders_seen)," pedidos \xb7 ",y(e.stats.orders_attributed)," atribuidos \xb7"," ",y(e.stats.lines_upserted)," l\xedneas \xb7 ",y(e.stats.links_created)," v\xednculos nuevos",e.stats.links_moved>0&&" \xb7 ".concat(y(e.stats.links_moved)," movidos"),e.stats.adjustments>0&&" \xb7 ".concat(y(e.stats.adjustments)," rectificaciones"),e.stats.truncated&&" \xb7 pasada truncada"]}),e.error&&(0,n.jsx)(u.x,{as:"span",variant:"bodySm",tone:"critical",children:e.error})]},e.id))})]}):null}function ea(e){var s;let{runs:a,onChanged:t}=e,[l,r]=(0,i.useState)(null),[o,d]=(0,i.useState)(null),[c,h]=(0,i.useState)(null),[j,b]=(0,i.useState)(!1),[v,f]=(0,i.useState)(null),_=(0,i.useCallback)(async()=>{h(null);try{let e=await g("/api/vet/settings");r(e.settings),d(e.env)}catch(e){h(e.message)}},[]);(0,i.useEffect)(()=>{_()},[_]);let N=async e=>{b(!1),await p("/api/vet/settings","POST",e),await _(),b(!0),setTimeout(()=>b(!1),2500)};return c?(0,n.jsx)(x.ub,{title:"No se pueden leer los ajustes",description:c}):l?(0,n.jsxs)("div",{className:"space-y-6 max-w-3xl",children:[(0,n.jsxs)("section",{className:"glass p-4 sm:p-5 space-y-4",children:[(0,n.jsxs)("div",{children:[(0,n.jsx)(u.x,{as:"h2",variant:"headingMd",children:"Fecha de corte"}),(0,n.jsx)("p",{className:"text-xs text-gray-500 mt-0.5",children:"El programa empieza a contar aqu\xed. Los pedidos anteriores no generan comisi\xf3n, porque ese periodo ya est\xe1 cubierto por el saldo inicial de ca
1da veterinario. Si mueves la fecha hacia adelante, las comisiones que queden detr\xe1s se anulan solas en el pr\xf3ximo repaso."})]}),(0,n.jsxs)("div",{className:"grid sm:grid-cols-2 gap-3",children:[(0,n.jsx)(x.II,{label:"Fecha de corte",type:"date",value:l.cutover_date?String(l.cutover_date).slice(0,10):"",onChange:e=>N({cutover_date:e||null}),hint:l.cutover_date?void 0:"Sin fecha se calcula todo lo que entre en la ventana de repaso"}),(0,n.jsx)(x.II,{label:"Ventana de repaso (horas)",type:"number",value:null!==(s=l.lookback_hours)&&void 0!==s?s:48,onChange:e=>r(s=>({...s,lookback_hours:e})),hint:"Cada pasada repasa los pedidos modificados en estas horas"})]}),(0,n.jsxs)(m.g,{blockAlign:"center",gap:"200",wrap:!1,children:[(0,n.jsx)(x.zx,{variant:"secondary",onClick:()=>N({lookback_hours:Number(l.lookback_hours)}),children:"Guardar ventana"}),j&&(0,n.jsx)(u.x,{as:"span",variant:"bodySm",tone:"success",children:"Guardado"})]})]}),(0,n.jsxs)("section",{className:"glass p-4 sm:p-5 space-y-4",children:[(0,n.jsx)(u.x,{as:"h2",variant:"headingMd",children:"Liquidaciones y portal"}),(0,n.jsx)(x.II,{label:"M\xednimo para emitir una liquidaci\xf3n (â¬)",type:"number",value:null!=l.payout_min_cents?Number(l.payout_min_cents)/100:0,onChange:e=>r(s=>({...s,payout_min_cents:Math.round(100*Number(e||0))})),hint:"0 = sin m\xednimo"}),(0,n.jsx)(x.zx,{variant:"secondary",onClick:()=>N({payout_min_cents:Number(l.payout_min_cents||0)}),children:"Guardar m\xednimo"}),(0,n.jsxs)("div",{className:"border-t border-gray-200 pt-4 space-y-4",children:[(0,n.jsx)(T,{checked:!1!==l.portal_enabled,onChange:e=>N({portal_enabled:e}),label:"Portal del veterinario abierto",hint:"Con el portal abierto, cada veterinario entra en /vet con su correo y ve su maturado, sus pedidos y su hist\xf3rico de liquidaciones."}),(0,n.jsx)(T,{checked:!0===l.mirror_vet_code,onChange:e=>N({mirror_vet_code:e}),label:"Escribir el c\xf3digo del vet en la ficha del cliente en Shopify",hint:"Copia el c\xf3digo en el metafield custom.vet_code para verlo desde el admin de Shopify. Necesita el permiso write_customers en el token, que hoy no est\xe1: si falla, el programa sigue funcionando igual."})]})]}),(0,n.jsxs)("section",{className:"glass p-4 sm:p-5 space-y-4",children:[(0,n.jsxs)("div",{children:[(0,n.jsx)(u.x,{as:"h2",variant:"headingMd",children:"Pasadas manuales"}),(0,n.jsx)("p",{className:"text-xs text-gray-500 mt-0.5",children:"El cron ya corre solo cada 15 minutos. Esto es para casos concretos."})]}),(0,n.jsxs)("div",{className:"rounded-lg ring-1 ring-inset ring-gray-200 p-4",children:[(0,n.jsx)(u.x,{as:"p",variant:"bodyMd",fontWeight:"medium",children:"Recalcular los \xfaltimos d\xedas"}),(0,n.jsx)("p",{className:"text-xs text-gray-500 mt-0.5 mb-3",children:"Despu\xe9s de cambiar el \xe1mbito de un grupo, la comisi\xf3n, o de reactivar un veterinario que estaba pausado. No toca las comisiones ya liquidadas."}),(0,n.jsx)(ei,{label:"Recalcular",action:"recalculate",defaultDays:30,onDone:e=>{f(e),null==t||t()}})]}),(0,n.jsxs)("div",{className:"rounded-lg ring-1 ring-inset ring-gray-200 p-4",children:[(0,n.jsx)(u.x,{as:"p",variant:"bodyMd",fontWeight:"medium",children:"Reconstruir v\xednculos del hist\xf3rico"}),(0,n.jsxs)("p",{className:"text-xs text-gray-500 mt-0.5 mb-3",children:["Paso de migraci\xf3n: recorre los pedidos antiguos para saber qu\xe9 cliente vino de qu\xe9 veterinario y deja el v\xednculo creado, ",(0,n.jsx)("b",{children:"sin generar ninguna comisi\xf3n"}),". As\xed los clientes que ya ven\xedan de un veterinario siguen contando para \xe9l desde el primer d\xeda. Con 730 d\xedas cubre dos a\xf1os."]}),(0,n.jsx)(ei,{label:"Reconstruir v\xednculos",action:"bootstrap_links",defaultDays:730,onDone:e=>{f(e),null==t||t()}})]}
1),v&&(0,n.jsxs)(E,{tone:"good",title:"Pasada terminada",children:[y(v.orders_seen)," pedidos le\xeddos",v.links_only?", ".concat(y(v.links_created)," v\xednculos nuevos, ").concat(y(v.links_moved)," movidos"):", ".concat(y(v.orders_attributed)," atribuidos, ").concat(y(v.lines_upserted)," l\xedneas"),v.truncated&&". La pasada se ha truncado: rep\xedtela para seguir donde se qued\xf3."]})]}),(0,n.jsxs)("section",{className:"glass p-4 sm:p-5",children:[(0,n.jsx)("h2",{className:"text-base font-semibold text-gray-900 mb-3",children:"Estado t\xe9cnico"}),(0,n.jsxs)("div",{className:"grid sm:grid-cols-2 gap-2 text-sm",children:[(0,n.jsx)(en,{label:"Token de Shopify en variable",ok:null==o?void 0:o.shopify_token,note:"si no, se usa el guardado en la base"}),(0,n.jsx)(en,{label:"CRON_SECRET",ok:null==o?void 0:o.cron_secret,note:"necesario para el cron de Vercel"}),(0,n.jsx)(en,{label:"VET_PORTAL_SECRET",ok:null==o?void 0:o.portal_secret,note:"firma las sesiones del portal del veterinario"}),(0,n.jsx)(en,{label:"RESEND_API_KEY",ok:null==o?void 0:o.resend,note:"env\xeda el enlace de acceso al veterinario"})]})]}),(0,n.jsx)(es,{runs:a})]}):(0,n.jsx)(P,{})}function en(e){let{label:s,ok:a,note:i}=e;return(0,n.jsxs)(m.g,{blockAlign:"start",gap:"200",wrap:!1,children:[(0,n.jsx)("span",{className:"mt-1.5 w-2 h-2 rounded-full shrink-0 ".concat(a?"bg-emerald-500":"bg-gray-300")}),(0,n.jsxs)("span",{children:[(0,n.jsx)("span",{className:"text-gray-900",children:s}),(0,n.jsx)("span",{className:"block text-xs text-gray-500",children:a?"configurado":"sin configurar, ".concat(i)})]})]})}function ei(e){let{label:s,action:a,defaultDays:t,onDone:l}=e,[r,o]=(0,i.useState)(t);return(0,n.jsxs)(m.g,{blockAlign:"end",gap:"200",wrap:!1,children:[(0,n.jsx)(x.II,{label:"D\xedas",type:"number",value:r,onChange:o,className:"w-28"}),(0,n.jsx)(L,{onRun:async()=>{l(await p("/api/vet/run","POST",{action:a,days:Number(r)}))},children:s})]})}}},function(e){e.O(0,[335,992,928,148,999,888,774,179],function(){return e(e.s=5921)}),_N_E=e.O()}]);
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.