1import{u3 as K,C as B,j as e,c as v,eB as $,dA as ee,u4 as Jt,x,dY as js,dZ as Ns,d_ as Cs,d1 as ws,d2 as Oe,eG as E,eZ as Xt,e9 as $e,bF as Se,cM as Me,cN as Be,d6 as Ie,cH as Re,cJ as Ye,Y as z,bU as ds,aX as me,aW as Ve,b8 as us,df as en,nN as is,f as de,a1 as sn,u5 as st,eP as tn,ch as Ss,ci as Es,cj as ks,ck as Ts,cl as Is,dR as nn,dS as an,mD as rn,u6 as ln,hY as on,u7 as as,av as Rs,aF as Ds,jz as wt,gv as St,V as os,d3 as Ke,d8 as cn,ea as As,u as dn,bl as je,iO as tt,sr as nt,u8 as un,fz as xn,fy as xs,u9 as mn,a7 as at,h3 as rs,jR as Ge,jS as qe,i1 as pn,eH as Ps,eI as Os,eJ as zs,hT as Et,eL as Fs,oj as Ms,jT as Qe,sF as ms,og as cs,t2 as fn,od as kt,pp as gn,aJ as hn,k7 as bn,ua as rt,by as yn,dg as Tt,ep as It,eK as Rt,fd as vn,dj as jn,ub as Nn,bC as Bs,uc as Cn,ud as wn,ue as Sn,iy as En,uf as kn,d7 as Tn,f0 as Dt,K as In,ug as Rn,uh as Dn,J as An,hP as Pn,eg as On,eh as zn,pa as Pe,bf as Fn,bo as Mn,cv as Bn,ui as Vn,f9 as hs,uj as At,h as _n,gx as Ln,uk as Un,ul as $n,N as Kn,aw as Pt,af as Yn,gF as Gn}from"./app-B8dYGn9u.js";import{m as ze,O as qn,Q as Qn,R as lt,V as Hn,W as Ot,X as Wn,x as Ee,Y as Vs,E as Zn,F as Jn,Z as zt,_ as Ft,$ as Xn,a0 as ea,a1 as sa,a2 as Mt,a3 as Bt,a4 as bs,a5 as ta,a6 as Vt,a7 as na,a8 as aa,a9 as ra,aa as la,ab as ia,w as oa,ac as ca,ad as da,ae as ua,f as xa,B as ma,af as pa}from"./feature-bookkeeping-vbS37DpT.js";import{d as ge,a as ts,u as ns}from"./getSubmittedVatDeclaration.generated-Bi9lfwaB.js";import"./bookkeeping-rules-l7Nq5imz.js";import"./feature-auth-CqqVDnIV.js";import"./accountant-invite-token-Bo8fib0o.js";import"./recharts-DCj02xYE.js";(function(){try{var s=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new s.Error().stack;t&&(s._sentryDebugIds=s._sentryDebugIds||{},s._sentryDebugIds[t]="7fa9f979-a423-4db6-b142-e1552f6f19aa",s._sentryDebugIdIdentifier="sentry-dbid-7fa9f979-a423-4db6-b142-e1552f6f19aa")}catch{}})();function Fe(s){if(!s)return!1;const t=s.trim().toLowerCase();return t==="nc"||t==="nota de crédito"||t==="nota de credito"}function Te(s){return!!s.creditNoteParent&&Fe(s.tipoDocumento)}function fa(s){if(!s)return!1;const t=s.trim().toLowerCase();return t==="nd"||t==="nota de débito"||t==="nota de debito"}function ga(s){const t=new Map(s.map(a=>[a.id,a])),n={uncategorizedCount:0,uncategorizedVat:0,businessCountDelta:0,personalCountDelta:0};for(const a of s){if(!Te(a))continue;a.isCategorized||(n.uncategorizedCount+=1,n.uncategorizedVat-=Math.abs(a.iva)),a.expenseType===K.Business?(n.businessCountDelta-=1,(a.businessPercentage??100)<100&&(n.personalCountDelta-=1)):a.expenseType===K.Personal&&(n.personalCountDelta-=1);const r=t.get(a.creditNoteParent.expenseId);r!=null&&r.isCategorized&&r.expenseType===K.Business?(n.businessCountDelta+=1,(r.businessPercentage??100)<100&&(n.personalCountDelta+=1)):r!=null&&r.isCategorized&&r.expenseType===K.Personal&&(n.personalCountDelta+=1)}return n}function ha(s,t){return{uncategorizedCount:Math.max(0,((s==null?void 0:s.uncategorizedCount)??0)-t.uncategorizedCount),uncategorizedVat:((s==null?void 0:s.uncategorizedVat)??0)-t.uncategorizedVat,businessCount:Math.max(0,((s==null?void 0:s.businessCount)??0)+t.businessCountDelta),personalCount:Math.max(0,((s==null?void 0:s.personalCount)??0)+t.personalCountDelta)}}const ba=s=>s&&{EQUIPMENT:"ð¥ï¸",FACILITIES:"ð¢",SUPPLIES:"ð¦",PROFESSIONAL:"ð",BANKING:"ð¦",EDUCATION:"ð",TRANSPORT:"ð",TRAVEL:"âï¸",PARKING:"ð
¿ï¸",FUEL:"â½",VEHICLE:"ð",EVENTS:"ðª",ENTERTAINMENT:"ð½ï¸",OTHER:"ð",SOFTWARE:"ð¿",MARKETING:"ð¢",HEALTH:"ð¥",HOUSING:"ð ",RESTAURANT:"ð´",VEHICLE_REPAIR:"ð§",MOTORCYCLE:"ðï¸",HAIRDRESSER:"ð",ELDERLY_CARE:"ð´",VETERINARY:"ð¾",PUBLIC_TRANSPORT:"ð",GYMS:"ðï¸",NEWSPAPERS:"ð°",BOOKS:"ð",ARTS:"ð",MUSEUMS:"ðï¸"}[s]||"",it=s=>s.toLowerCase().replace(/_([a-z])/g,(t,n)=>n.toUpperCase()),_t=({expenseType:s,businessCategory:t,personalCategory:n,compact:a=!1,businessPercentage:r,showAsPersonalPortion:o=!1})=>{const{t:c}=B(),i=s===K.Business,d=i&&r!==void 0&&r<100,l=i?t:n;if(o&&d){const y=100-(r??100);return e.jsxs("span",{className:v("inline-flex items-center font-semibold",a?"gap-1 rounded-md px-1.5 py-0.5 text-[10px]":"gap-1.5 rounded-lg px-2.5 py-1.5 text-xs","bg-purple-100 text-purple-800"),children:[e.jsx("span",{className:a?"text-xs":"text-sm",children:"ð¤"}),c("expenses.type.personal")," (",y,"%)"]})}if(!i&&!n)return e.jsxs("span",{className:v("inline-flex items-center font-semibold",a?"gap-1 rounded-md px-1.5 py-0.5 text-[10px]":"gap-1.5 rounded-lg px-2.5 py-1.5 text-xs","bg-purple-100 text-purple-800"),children:[e.jsx("span",{className:a?"text-xs":"text-sm",children:"ð¤"}),c("expenses.type.personal")]});const m=()=>{if(i&&t){const y=c(`expenses.category.business.${it(t)}`);return d?`${y} (${r}%)`:y}return!i&&n?c(`expenses.category.personal.${it(n)}`):""};return e.jsxs("span",{className:v("inline-flex items-center font-semibold",a?"gap-1 rounded-md px-1.5 py-0.5 text-[10px]":"gap-1.5 rounded-lg px-2.5 py-1.5 text-xs",i?"bg-blue-100 text-blue-800":"bg-purple-100 text-purple-800"),children:[e.jsx("span",{className:a?"text-xs":"text-sm",children:ba(l)}),m()]})},_s=[$.Transport,$.Travel,$.Entertainment],ya=[{value:$.Equipment,icon:"ð¥ï¸",labelKey:"expenses.category.business.equipment"},{value:$.Facilities,icon:"ð¢",labelKey:"expenses.category.business.facilities",condition:s=>(s==null?void 0:s.worksFromHome)||(s==null?void 0:s.hasOffice)||!s},{value:$.Supplies,icon:"ð¦",labelKey:"expenses.category.business.supplies"},{value:$.Professional,icon:"ð",labelKey:"expenses.category.business.professional"},{value:$.Banking,icon:"ð¦",labelKey:"expenses.category.business.banking"},{value:$.Education,icon:"ð",labelKey:"expenses.category.business.education"},{value:$.Transport,icon:"ð",labelKey:"expenses.category.business.transport"},{value:$.Travel,icon:"âï¸",labelKey:"expenses.category.business.travel",condition:s=>(s==null?void 0:s.hasTravel)||!s},{value:$.Parking,icon:"ð
¿ï¸",labelKey:"expenses.category.business.parking",condition:s=>(s==null?void 0:s.usesCar)||!s},{value:$.Fuel,icon:"â½",labelKey:"expenses.category.business.fuel",condition:s=>(s==null?void 0:s.usesCar)||!s},{value:$.Vehicle,icon:"ð",labelKey:"expenses.category.business.vehicle",condition:s=>(s==null?void 0:s.usesCar)||!s},{value:$.Events,icon:"ðª",labelKey:"expenses.category.business.events",condition:s=>(s==null?void 0:s.hasEvents)||!s},{value:$.Entertainment,icon:"ð½ï¸",labelKey:"expenses.category.business.entertainment",condition:s=>(s==null?void 0:s.hasEntertainment)||!s},{value:$.Software,icon:"ð¿",labelKey:"expenses.category.business.softw
1are",condition:s=>(s==null?void 0:s.hasSoftware)||!s},{value:$.Marketing,icon:"ð¢",labelKey:"expenses.category.business.marketing",condition:s=>(s==null?void 0:s.hasMarketing)||!s},{value:$.Telecommunications,icon:"ð",labelKey:"expenses.category.business.telecommunications"},{value:$.Resale,icon:"ðª",labelKey:"expenses.category.business.resale"},{value:$.Other,icon:"ð",labelKey:"expenses.category.business.other"}],Ls=[{value:ee.Health,icon:"ð¥",labelKey:"expenses.category.personal.health"},{value:ee.Education,icon:"ð",labelKey:"expenses.category.personal.education"},{value:ee.Housing,icon:"ð ",labelKey:"expenses.category.personal.housing"},{value:ee.Restaurant,icon:"ð´",labelKey:"expenses.category.personal.restaurant"},{value:ee.VehicleRepair,icon:"ð§",labelKey:"expenses.category.personal.vehicleRepair"},{value:ee.Motorcycle,icon:"ðï¸",labelKey:"expenses.category.personal.motorcycle"},{value:ee.Hairdresser,icon:"ð",labelKey:"expenses.category.personal.hairdresser"},{value:ee.ElderlyCare,icon:"ð´",labelKey:"expenses.category.personal.elderlyCare"},{value:ee.Veterinary,icon:"ð¾",labelKey:"expenses.category.personal.veterinary"},{value:ee.PublicTransport,icon:"ð",labelKey:"expenses.category.personal.publicTransport"},{value:ee.Gyms,icon:"ðï¸",labelKey:"expenses.category.personal.gyms"},{value:ee.Newspapers,icon:"ð°",labelKey:"expenses.category.personal.newspapers"},{value:ee.Books,icon:"ð",labelKey:"expenses.category.personal.books"},{value:ee.Arts,icon:"ð",labelKey:"expenses.category.personal.arts"},{value:ee.Museums,icon:"ðï¸",labelKey:"expenses.category.personal.museums"},{value:ee.Other,icon:"ð",labelKey:"expenses.category.personal.other"}],va=({companyInfo:s,className:t})=>e.jsx(Jt,{companyInfo:s,personalCategoriesConfig:Ls,className:t}),ot=({companyInfo:s,children:t})=>{const[n,a]=x.useState(!1),{t:r}=B();return s?e.jsxs(js,{open:n,onOpenChange:a,children:[e.jsx(Ns,{asChild:!0,onClick:o=>o.stopPropagation(),children:t}),e.jsxs(Cs,{className:"w-80 p-4",side:"bottom",align:"start",children:[e.jsx("p",{className:"mb-2 text-[11px] font-medium uppercase tracking-wide text-gray-400",children:r("label.issuerInfo")}),e.jsx(va,{companyInfo:s})]})]}):e.jsx(e.Fragment,{children:t})},ct=({isLinked:s})=>{const{t}=B();return e.jsx("span",{className:v("inline-flex flex-shrink-0 items-center rounded-full px-1.5 py-0.5 text-[10px] font-semibold",s?"bg-gray-200 text-gray-600":"bg-amber-100 text-amber-800"),children:t("expenses.creditNote.badge")})},ja=s=>ya.filter(t=>!t.condition||t.condition(s)),dt=(s,t)=>{const n=Ls.filter(a=>!a.condition||a.condition(s));return!t||t.length===0?n:n.filter(a=>t.includes(a.value)||a.value===ee.Other)};function Na(s,t){if(!s||s.length===0)return{isValid:!1,hasApiData:!1,invalidRates:[],validRates:[]};if(t===ws.Unknown)return{isValid:!1,hasApiData:!0,invalidRates:s.map(o=>o.taxPercentage),validRates:[]};const n=[0,ze(t,Oe.Normal),ze(t,Oe.Intermediate),ze(t,Oe.Reduced)],a=[],r=[];for(const o of s)o.taxPercentage!==0&&(n.includes(o.taxPercentage)?r.push(o.taxPercentage):a.push(o.taxPercentage));return{isValid:a.length===0,hasApiData:!0,invalidRates:a,validRates:r}}function Ca(s){if(s===ws.Unknown)return"";const t=ze(s,Oe.Normal),n=ze(s,Oe.Intermediate);return`${ze(s,Oe.Reduced)}%, ${n}%, ${t}%`}const wa=["expenses.ai.prompt.isDeductible","expenses.ai.prompt.rightCategory","expenses.ai.prompt.vatRate","expenses.ai.prompt.shouldPartial"],Sa=s=>{const t=new Date(s);return isNaN(t.getTime())?s:t.toLocaleDateString("pt-PT",{day:"2-digit",month:"2-digit",year:"numeric"})},Ea=s=>{const n=[`Expense from ${ge(s.nomeEmitente)} (NIF: ${s.nifEmitente})`,`Total: ${E(s.total)}, VAT: ${E(s.iva)}`,`Date: ${Sa(s.emissionDate)}`];if(s.vendorCae&&s.vendorCaeDescription?n.push(`Vendor activity: ${s.vendorCae} â ${ge(s.vendorCaeDescription)}`):s.vendorCae?n.push(`Vendor CAE: ${s.vendorCae}`):s.actividadeEmitente&&n.push(`Sector: ${ge(s.actividadeEmitente)}`),s.expenseType){let a=`Current classification: ${s.expenseType}`;s.businessCategory&&(a+=` > ${s.businessCategory}`),s.personalCategory&&(a+=` (Personal: ${s.personalCategory})`),s.businessPercentage!=null&&s.businessPercentage<100&&(a+=` (${s.businessPercentage}% business use)`),n.push(a)}return n.join(` 2`)},ka=({context:s})=>{const{t}=B();return e.jsxs("div",{className:"mx-4 mt-3 rounded-lg border border-amber-200/60 bg-amber-50/50 px-3 py-2",children:[e.jsx("p",{className:"mb-1 text-[11px] font-medium uppercase tracking-wider text-amber-700/70",children:t("expenses.ai.askingAbout")}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Xt,{className:"h-3.5 w-3.5 flex-shrink-0 text-amber-600"}),e.jsx("span",{className:"truncate text-xs font-medium text-amber-900",children:ge(s.nomeEmitente)}),e.jsx("span",{className:"ml-auto flex-shrink-0 text-xs font-semibold text-amber-800",children:E(s.total)})]})]})},Ta=({isOpen:s,onClose:t,expenseContext:n,expenseId:a,openNonce:r})=>{const{t:o}=B(),c=x.useMemo(()=>n?Ea(n):null,[n]);return e.jsx(qn,{isOpen:s,onClose:t,title:o("expenses.ai.title"),placeholder:o("expenses.ai.placeholder"),errorText:o("expenses.ai.error"),context:c,contextChip:n?e.
2jsx(ka,{context:n}):null,quickPromptKeys:wa,resetKey:a!=null?String(a):(n==null?void 0:n.nifEmitente)??null,openNonce:r})},Ia=({value:s,onChange:t,className:n})=>{const{t:a}=B();return e.jsxs("div",{className:v("space-y-2",n),children:[e.jsx("p",{className:"text-sm font-medium text-gray-700",children:a("expenses.assetClassification.title")}),e.jsx("div",{className:"space-y-2",children:Qn.map(r=>{const o=s===r.value;return e.jsxs("label",{className:v("flex cursor-pointer items-start gap-3 rounded-xl border-2 p-3 transition-colors",o?"border-[#FFC850] bg-[#FFC850]/5":"border-gray-200 bg-white hover:border-gray-300"),children:[e.jsx("input",{type:"radio",name:"assetClassification",checked:o,onChange:()=>t(r.value),className:"mt-0.5 h-4 w-4 accent-[#FFC850]"}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-medium text-gray-900",children:a(r.labelKey)}),r.recommendedKey&&e.jsx("span",{className:"text-xs text-gray-500",children:a(r.recommendedKey)})]}),e.jsx("p",{className:"mt-0.5 text-xs text-gray-500",children:a(r.descriptionKey)})]})]},String(r.value))})}),s===!0&&e.jsxs($e,{variant:"warning",children:[e.jsx("p",{className:"text-sm font-medium",children:a("expenses.assetClassification.fixedAsset.alertTitle")}),e.jsx("p",{className:"mt-1 text-xs",children:a("expenses.assetClassification.fixedAsset.alertDescription")})]}),e.jsx("p",{className:"text-[11px] leading-relaxed text-gray-400",children:a("expenses.assetClassification.disclaimer")})]})},Ra="https://faturas.portaldasfinancas.gov.pt/detalheDocumentoAdquirente.action",Da="auto",Aa="sync_failed",ut=s=>{const t=new URLSearchParams({idDocumento:s.idDocumento,dataEmissaoDocumento:Se(s.emissionDate).format("YYYY-MM-DD")});return`${Ra}?${t.toString()}`},vs=s=>{var t,n;return((t=s.companyInfo)==null?void 0:t.brandName)??((n=s.companyInfo)==null?void 0:n.name)??ge(s.nomeEmitente)},Pa=(s,t,n)=>[...s].sort((a,r)=>{let o=0;switch(t){case"date":o=new Date(a.emissionDate).getTime()-new Date(r.emissionDate).getTime();break;case"amount":o=a.total-r.total;break;case"vat":o=a.iva-r.iva;break;case"category":{const c=a.isCategorized?1:0,i=r.isCategorized?1:0;o=c-i;break}}return n==="asc"?o:-o}),Oa=s=>!s.isCategorized,za=s=>s.isCategorized&&s.expenseType===K.Personal,Fa=s=>s.isCategorized&&s.expenseType===K.Business&&s.businessPercentage!==void 0&&s.businessPercentage<100,Ma=(s,t=!1,n=!1)=>s.categorizedBy===Aa?"failed":s.isCategorized&&s.categorizedBy!==Da&&!s.efaturaSyncedAt?n?"synced":t?"syncing":"pending":"synced",Ba=({isOpen:s,onOpenChange:t,expenses:n,expenseType:a,category:r,businessPercentage:o,onConfirm:c,isLoading:i})=>{const{t:d}=B(),l=a===K.Business,m=n.reduce((p,f)=>p+f.total,0),y=n.reduce((p,f)=>p+f.iva,0);return e.jsx(Me,{open:s,onOpenChange:t,children:e.jsxs(Be,{className:"max-w-md",children:[e.jsxs(Ie,{className:"min-w-0",children:[e.jsx(Re,{children:d("expenses.batchPreview.title",{count:n.length})}),e.jsx(Ye,{className:"truncate",children:d("expenses.batchPreview.description")})]}),e.jsxs("div",{className:"flex min-w-0 flex-col gap-4 pt-2",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-2 rounded-lg border border-border bg-muted/50 px-3 py-2.5",children:[e.jsx("span",{className:"shrink-0 text-sm text-muted-foreground",children:d("expenses.batchPreview.applyingAs")}),e.jsx(_t,{expenseType:a,businessCategory:l?r:void 0,personalCategory:l?void 0:r,businessPercentage:o,compact:!0})]}),e.jsx("div",{className:"max-h-64 min-w-0 overflow-x-hidden overflow-y-auto rounded-lg border border-border",children:e.jsx("ul",{className:"divide-y divide-border",children:n.map(p=>e.jsxs("li",{className:"flex items-center justify-between gap-3 px-3 py-2.5",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"truncate text-sm font-medium text-foreground",children:vs(p)}),e.jsxs("p",{className:"truncate text-xs text-muted-foreground",children:[Se(p.emissionDate).format("D MMM YYYY"),p.invoiceNumber&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"mx-1 text-border",children:"·"}),p.invoiceNumber]})]})]}),e.jsxs("div",{className:"flex shrink-0 flex-col items-end",children:[e.jsx("span",{className:"text-sm font-semibold text-foreground",children:E(p.total)}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[d("expenses.batchPreview.vatLabel")," ",E(p.iva)]})]})]}
2,p.id))})}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg bg-muted/50 px-3 py-2.5",children:[e.jsx("span",{className:"text-sm font-medium text-muted-foreground",children:d("expenses.batchPreview.total")}),e.jsxs("div",{className:"flex flex-col items-end",children:[e.jsx("span",{className:"text-sm font-bold text-foreground",children:E(m)}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[d("expenses.batchPreview.vatLabel")," ",E(y)]})]})]}),e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:justify-end",children:[e.jsx(z,{variant:"neutralSecondary",onClick:()=>t(!1),disabled:i,className:"w-full sm:w-auto",children:d("button.label.cancel")}),e.jsx(z,{variant:"fizPrime",onClick:c,loading:i,className:"w-full sm:w-auto",children:d("expenses.batchPreview.confirm",{count:n.length})})]})]})]})})},xt=({value:s,onChange:t,categories:n,className:a,isBusiness:r=!0})=>{const{t:o}=B();return e.jsx("div",{className:v("grid grid-cols-2 gap-1.5 sm:flex sm:flex-wrap sm:gap-2",a),children:n.map(c=>{const i=s===c.value;return e.jsxs("button",{type:"button",onClick:()=>t(i?null:c.value),className:v("flex items-center justify-center gap-1 rounded-lg px-2 py-2 text-[11px] font-medium transition-all duration-200 sm:justify-start sm:gap-2 sm:px-3.5 sm:py-2 sm:text-sm",i?r?"bg-blue-600 text-white shadow-md shadow-blue-500/20":"bg-violet-600 text-white shadow-md shadow-purple-500/20":"bg-white text-gray-700 ring-1 ring-gray-200 hover:bg-gray-50 hover:ring-gray-300"),children:[e.jsx("span",{className:"text-sm sm:text-base",children:c.icon}),e.jsx("span",{className:"truncate",children:o(c.labelKey)})]},c.value)})})},Va={},_a=me` 3 mutation ConfirmCreditNoteParent($expenseId: String!, $parentExpenseId: String) { 4 confirmCreditNoteParent(expenseId: $expenseId, parentExpenseId: $parentExpenseId) { 5 id 6 creditNoteParent { 7 expenseId 8 source 9 confirmedByUserId 10 confirmedAt 11 } 12 } 13 } 14`;function Lt(s){const t={...Va,...s};return ds(_a,t)}const La={},Ua=me` 15 query CreditNoteParentCandidates($expenseId: String!) { 16 creditNoteParentCandidates(expenseId: $expenseId) { 17 exactAmountMatch 18 expense { 19 id 20 idDocumento 21 invoiceNumber 22 nifEmitente 23 nomeEmitente 24 tipoDocumento 25 emissionDate 26 total 27 iva 28 taxBase 29 quarter 30 year 31 isCategorized 32 expenseType 33 businessCategory 34 businessPercentage 35 } 36 } 37 } 38`;function Ut(s){const t={...La,...s};return Ve(Ua,t)}function $a({isOpen:s,onOpenChange:t,expense:n}){var g,w;const{t:a}=B(),[r,o]=x.useState(null),{data:c,loading:i}=Ut({variables:{expenseId:n.id},skip:!s,fetchPolicy:"cache-and-network"}),d=c==null?void 0:c.creditNoteParentCandidates,[l,{loading:m}]=Lt({update(h){h.evict({id:"ROOT_QUERY",fieldName:"getVatDeductionsFromExpenses"}),h.evict({id:"ROOT_QUERY",fieldName:"getAnnualBusinessExpenses"}),h.gc()}});x.useEffect(()=>{if(!s||r||!d)return;const h=d.filter(b=>b.exactAmountMatch);h.length===1&&o(h[0].expense.id)},[s,r,d]),x.useEffect(()=>{s||o(null)},[s]);const y=async()=>{if(r)try{await l({variables:{expenseId:n.id,parentExpenseId:r}}),de.success(a("expenses.creditNote.confirmSuccess")),t(!1)}catch(h){console.error("Error confirming credit-note parent:",h),de.error(a("expenses.creditNote.error"))}},p=()=>{is({source:"expense_credit_note_parent_picker"}),t(!1)},f=((g=n.companyInfo)==null?void 0:g.brandName)??((w=n.companyInfo)==null?void 0:w.name)??ge(n.nomeEmitente);return e.jsx(Me,{open:s,onOpenChange:t,children:e.jsxs(Be,{className:"max-w-lg",children:[e.jsxs(Ie,{children:[e.jsx(Re,{children:a("expenses.creditNote.picker.title")}),e.jsx(Ye,{children:a("expenses.creditNote.picker.description",{vendor:f,total:E(n.total)})})]}),i&&!d?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(us,{color:"#FFC850",size:24})}):!d||d.length===0?e.jsxs("div",{className:"flex flex-col gap-4 pt-2",children:[e.jsxs("div",{className:"rounded-lg border border-border bg-muted/50 p-3",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:a("expenses.creditNote.picker.empty")}),e.jsx("p",{className:"mt-1.5 text-sm text-muted-foreground",children:a("expenses.creditNote.picker.emptyHint")})]}),e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:justify-end",children:[e.jsx(z,{variant:"neutralSecondary",onClick:()=>t(!1),className:"w-full sm:w-auto",children:a("button.label.close")}),e.jsx(z,{variant:"fizPrime",onClick:p,className:"w-full sm:w-auto",children:a("expenses.creditNote.picker.contactSupport")})]})]}):e.jsxs("div",{className:"flex flex-col gap-4 pt-2",children:[e.jsx("div",{className:"flex max-h-72 flex-col gap-2 overflow-y-auto pr-1",children:d.map(h=>{const b=h.expense,D=r===b.id;return e.jsxs("button",{type:"button",onClick:()=>o(b.id),className:v("flex items-center justify-between gap-3 rounded-lg border p-3 text-left transition-colors",D?"border-amber-400 bg-amber-50 ring-1 ring-amber-400":"border-gray-200 hover:bg-gray-50"),children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"truncate text-sm font-medium text-gray-900",children:b.invoiceNumber||b.idDocumento}),h.exactAmountMatch&&e.jsx("span",{className:"shrink-0 rounded-full bg-emerald-100 px-1.5 py-0.5 text-[10px] font-semibold text-emerald-700",children:a("expenses.creditNote.picker.exactMatch")})]}),e.jsxs("p",{className:"mt-0.5 text-xs text-gray-500",children:[Se(b.emissionDate).format("DD/MM/YYYY")," · ",a("expenses.creditNote.picker.vatLabel",{vat:E(b.iva)})]})]}),e.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[e.jsx("span",{className:"text-sm font-semibold text-gray-900",children:E(b.total)}),D&&e.jsx(en,{className:"h-4 w-4 text-amber-600"})]})]},b.id)})}),e.jsxs("div",{className:"flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",children:[e.jsx(z,{variant:"neutralSecondary",onClick:()=>t(!1),className:"w-full sm:w-auto",children:a("button.label.cancel")}),e.jsx(z,{variant:"fizPrime",onClick:y,disabled:!r,loading:m,className:"w-full sm:w-auto",children:a("expenses.creditNote.picker.confirm")})]})]})]})})}const mt=({expense:s,allExpenses:t})=>{var g,w;const{t:n}
38=B(),[a,r]=x.useState(!1),[o,{loading:c}]=Lt({update(h){h.evict({id:"ROOT_QUERY",fieldName:"getVatDeductionsFromExpenses"}),h.evict({id:"ROOT_QUERY",fieldName:"getAnnualBusinessExpenses"}),h.gc()}}),i=sn(),d=!!s.idDocumento,l=(g=s.creditNoteParent)==null?void 0:g.expenseId,m=x.useMemo(()=>l?t==null?void 0:t.find(h=>h.id===l):void 0,[t,l]),{data:y}=Ut({variables:{expenseId:s.id},skip:!l||!!m}),p=m??((w=y==null?void 0:y.creditNoteParentCandidates.find(h=>h.expense.id===l))==null?void 0:w.expense),f=async()=>{try{await o({variables:{expenseId:s.id}}),de.success(n("expenses.creditNote.unlinkSuccess"))}catch(h){console.error("Error unlinking credit-note parent:",h),de.error(n("expenses.creditNote.error"))}};return s.creditNoteParent?e.jsx("div",{className:"mb-4 sm:mb-5",children:e.jsxs("div",{className:"rounded-lg border border-emerald-200 bg-emerald-50 p-3 sm:p-4",children:[e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[e.jsx(tn,{className:"h-4 w-4 shrink-0 text-emerald-600"}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-gray-900",children:p?n("expenses.creditNote.linkedTo",{number:p.invoiceNumber||p.idDocumento}):n("expenses.creditNote.linkedGeneric")}),p&&e.jsxs("p",{className:"mt-0.5 text-xs text-gray-500",children:[Se(p.emissionDate).format("DD/MM/YYYY")," · ",E(p.total)]})]})]}),d?e.jsx(z,{size:"small",variant:"neutralSecondary",onClick:()=>i(st.documents),className:"w-full whitespace-nowrap sm:w-auto",children:n("expenses.creditNote.openBookkeeping")}):e.jsx(z,{size:"small",variant:"neutralSecondary",loading:c,onClick:f,className:"w-full whitespace-nowrap sm:w-auto",children:n("expenses.creditNote.unlink")})]}),e.jsx("p",{className:"mt-2 text-xs text-gray-500",children:n("expenses.creditNote.inheritsCategory")})]})}):e.jsxs("div",{className:"mb-4 sm:mb-5",children:[e.jsx($e,{variant:"warning",action:d?{label:n("expenses.creditNote.openBookkeeping"),onClick:()=>i(st.documents)}:{label:n("expenses.creditNote.selectParentButton"),onClick:()=>r(!0)},children:n(d?"expenses.creditNote.managedInBookkeeping":"expenses.creditNote.alertUnlinked")}),e.jsx($a,{isOpen:a,onOpenChange:r,expense:s})]})},Ka=({value:s,onChange:t,rateFor:n,className:a})=>{const{t:r}=B(),o=lt.find(i=>i.value===s),c=i=>{const d=n==null?void 0:n(i);return d===void 0?null:`(${Math.round(d*100)}% IVA)`};return e.jsxs(Ss,{value:s??void 0,onValueChange:i=>t(i),children:[e.jsx(Es,{className:v("h-11 rounded-xl bg-white px-4",a),children:e.jsx(ks,{placeholder:r("expenses.eventRole.placeholder"),children:o&&e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{children:r(o.labelKey)}),e.jsx("span",{className:"text-xs text-gray-500",children:c(o.value)})]})})}),e.jsx(Ts,{children:lt.map(i=>e.jsx(Is,{value:i.value,children:e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsx("span",{children:r(i.labelKey)}),e.jsx("span",{className:"text-xs text-gray-500",children:c(i.value)})]})},i.value))})]})},Ya=8,Ga=[$.Professional,$.Other];function qa({value:s,onChange:t,suggestedBusinessCategory:n,expenses:a,disabled:r}){const{t:o}=B(),[c,i]=x.useState(!1),{categories:d,isLoading:l,hasError:m,reload:y}=Hn(),{catalogRates:p,supersededIds:f}=Ot(),g=x.useMemo(()=>new Map(d.map(k=>[k.id,k])),[d]),w=x.useMemo(()=>n?Ga.includes(n)?[]:p.filter(k=>k.businessCategory===n).filter(k=>k.supersededBy.length===0).map(k=>k.catalogCategoryId):[],[p,n]),h=x.useMemo(()=>new Set(w),[w]),b=x.useMemo(()=>{const k=[],T=C=>{!C||!g.has(C)||k.includes(C)||f.has(C)&&C!==s||k.push(C)};w.forEach(T);const j=new Map;for(const C of a??[]){const P=C.catalogCategoryId;P&&j.set(P,(j.get(P)??0)+1)}return[...j.entries()].sort((C,P)=>P[1]-C[1]).forEach(([C])=>T(C)),T(s),k.slice(0,Ya)},[g,w,f,a,s]),D=s?g.get(s)??null:null,I=D?`${D.icon?`${D.icon} `:""}${D.label}`:null,_=!!s&&!b.includes(s);return m&&d.length===0?e.jsxs("div",{className:"rounded-lg border border-amber-200 bg-amber-50 px-3.5 py-2.5 text-[13px] leading-snug text-amber-900",children:[o("expenses.panel.catalogUnavailable"),e.jsx("button",{type:"button",onClick:()=>{y()},disabled:l,className:"mt-1.5 block text-[13px] font-semibold underline decoration-dashed underline-offset-2 disabled:opacity-50",children:o("button.label.retry")})]}):e.jsxs(e.Fragment,{children:[b.length>0&&e.jsx("div",{className:"mb-2 grid grid-cols-2 gap-1.5 sm:flex sm:flex-wrap sm:gap-2",children:b.map(k=>{const T=g.get(k),j=k===s,C=h.has(k);return e.jsxs("button",{type:"button",disabled:r,onClick:()=>t(j?null:k),title:T.label,className:v("flex items-center justify-center gap-1 rounded-lg px-2 py-2 text-[11px] font-medium transition-all duration-200 sm:justify-start sm:gap-2 sm:px-3.5 sm:py-2 sm:text-sm",j?"bg-blue-600 text-white shadow-md shadow-blue-500/20":"bg-white text-gray-700 ring-1 ring-gray-200 hover:bg-gray-50 hover:ring-gray-300"),children:[C&&!j&&e.jsx(nn,{className:"h-3 w-3 shrink-0 text-amber-500"}),e.jsx("span",{className:"text-sm sm:text-base",children:T.icon}),e.jsx("span",{className:"truncate",children:T.label})]},k)})}),e.jsxs("button",{type:"button",disabled:r,onClick:()=>i(!0),className:v("flex w-full items-center justify-between gap-2 rounded-lg border px-3.5 py-2.5 text-left text-sm transition-colors",_?"border-blue-200 bg-blue-50 text-gray-900 hover:bg-blue-100":"border-dashed border-gray-300 bg-white text-gray-500 hover:bg-gray-50",r&&"curs
38or-not-allowed opacity-60"),children:[e.jsx("span",{className:"min-w-0 truncate",children:_?I:o("expenses.panel.allCategories")}),e.jsx(an,{className:"h-4 w-4 shrink-0 text-gray-400"})]}),e.jsx(Wn,{open:c,onOpenChange:i,value:s,onSelect:k=>{t(k),i(!1)},direction:"out",afetacao:"Business"})]})}const Qa=[{value:"business",labelKey:"expenses.type.business",icon:e.jsx(rn,{size:18}),activeClass:"bg-blue-600 text-white shadow-lg shadow-blue-500/25"},{value:"partial",labelKey:"expenses.type.partial",icon:e.jsx(ln,{size:18}),activeClass:"bg-blue-600 text-white shadow-lg shadow-blue-500/25"},{value:"personal",labelKey:"expenses.type.personal",icon:e.jsx(on,{size:18}),activeClass:"bg-violet-600 text-white shadow-lg shadow-purple-500/25"}],Ha=({value:s,onChange:t,businessPercentage:n=75,onBusinessPercentageChange:a,className:r})=>{const{t:o}=B();return Ee()?null:e.jsxs("div",{className:v("flex flex-col gap-2",r),children:[e.jsx("div",{className:"flex flex-col gap-2 sm:flex-row sm:gap-3",children:Qa.map(i=>{const d=s===i.value;return e.jsxs("button",{type:"button",onClick:()=>t(i.value),className:v("flex items-center justify-center gap-2 rounded-xl px-3 py-2.5 text-sm font-semibold transition-all duration-200 sm:px-5",d?i.activeClass:"bg-white text-gray-700 ring-1 ring-gray-200 hover:bg-gray-50 hover:ring-gray-300"),children:[i.icon,o(i.labelKey)]},i.value)})}),s==="partial"&&a&&e.jsx("div",{className:"mt-3 flex gap-1.5 sm:gap-2",children:[75,50,25].map(i=>e.jsxs("button",{type:"button",onClick:()=>a(i),className:v("flex-1 rounded-lg px-2 py-2 text-sm font-semibold transition-all duration-200 sm:flex-initial sm:px-4",n===i?"bg-blue-600 text-white shadow-md shadow-blue-500/20":"bg-white text-gray-700 ring-1 ring-gray-200 hover:bg-gray-50 hover:ring-gray-300"),children:[i,"%"]},i))})]})},Wa=s=>s===null?null:s==="personal"?K.Personal:K.Business,Za=(s,t)=>s?s===K.Personal?"personal":t!==void 0&&t<100?"partial":"business":null,pt=[{value:as.Acquisition,labelKey:"expenses.vehicleExpenseType.acquisition",rateHint:"0-100%"},{value:as.Leasing,labelKey:"expenses.vehicleExpenseType.leasing",rateHint:"0-100%"},{value:as.Ongoing,labelKey:"expenses.vehicleExpenseType.ongoing",rateHint:"0%"}],Ja=({value:s,onChange:t,className:n})=>{const{t:a}=B(),r=pt.find(o=>o.value===s);return e.jsxs(Ss,{value:s,onValueChange:o=>t(o),children:[e.jsx(Es,{className:v("h-11 rounded-xl bg-white px-4",n),children:e.jsx(ks,{placeholder:a("expenses.panel.vehicleExpenseType"),children:r&&e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{children:a(r.labelKey)}),e.jsxs("span",{className:"text-xs text-gray-500",children:["(",r.rateHint," ",a("expenses.iva"),")"]})]})})}),e.jsx(Ts,{children:pt.map(o=>e.jsx(Is,{value:o.value,children:e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsx("span",{children:a(o.labelKey)}),e.jsxs("span",{className:"text-xs text-gray-500",children:["(",o.rateHint," ",a("expenses.iva"),")"]})]})},o.value))})]})},ft=({expense:s,onSave:t,onCancel:n,onSyncExpenses:a,isSyncing:r,isCategorySyncing:o,className:c,allExpenses:i,onBatchSave:d})=>{var Ws,Zs,Js,Xs,et;const{t:l}=B(),{settings:m}=Vs(),y=Ot(),p=Rs(Ds),f=(p==null?void 0:p.territory)??ws.Unknown,g=Ee(),w=s.businessPercentage??100,h=g?s.businessCategory??null:(s.expenseType===K.Business?s.businessCategory:s.personalCategory)??null,[b,D]=x.useState(g?"business":Za(s.expenseType,w)),[I,_]=x.useState(h),[k,T]=x.useState(w<100?w:75),[j,C]=x.useState(s.eventRole??null),[P,F]=x.useState(s.isFixedAsset??!1),[R,M]=x.useState(s.catalogCategoryId??null),u=s.derivedCatalogCategoryId??null,N=R??u,[S,L]=x.useState(s.vehicleExpenseType??as.Ongoing),[V,A]=x.useState(s.businessPercentage&&s.businessPercentage<100?s.personalCategory??null:null),[Y,G]=x.useState(!1),[q,H]=x.useState(!1),[se,re]=x.useState(!1),[he,te]=x.useState(!1),[be,ue]=x.useState(!1),[xe,pe]=x.useState(0),[Z,ie]=x.useState(!1),[J,le]=x.useState(!1),{access:W}=Zn(),{hasAccess:Ne,blockIfUnresolved:Q}=wt(St.ExpenseManagement),oe=x.useMemo(()=>!s.nifEmitente||!i?[]:i.filter(U=>
38U.nifEmitente===s.nifEmitente&&!U.isCategorized&&U.id!==s.id),[i,s.nifEmitente,s.id]),ce=oe.length>0&&d,De=Fe(s.tipoDocumento),ps=De&&!!s.creditNoteParent,fs=fa(s.tipoDocumento),fe=Wa(b),X=fe===K.Business,He=X?ja(m):dt(m,(Ws=s.companyInfo)==null?void 0:Ws.allowedPersonalCategories),We=!X&&((Zs=s.companyInfo)==null?void 0:Zs.allowedPersonalCategories)&&s.companyInfo.allowedPersonalCategories.length>0&&s.companyInfo.allowedPersonalCategories.length<Ls.length,O=(Js=p==null?void 0:p.vatSettings)==null?void 0:Js.selectedVATRegime,Ce=O===os.ExemptionArticle_53||O===os.ExemptionArticle_9||!g&&(m==null?void 0:m.operatingMode)===Ke.IrsOnly,Ae=(g||(m==null?void 0:m.operatingMode)===Ke.IvaOnly)&&fe===K.Personal,ye=N?y.catalogRates.find(U=>U.catalogCategoryId===N):void 0,Je=ye==null?void 0:ye.businessCategory,ve=X?Je??I:null,ne=!!ve&&_s.includes(ve),we=ve===$.Equipment&&(ye==null?void 0:ye.isFixedAsset)==null,_e=!N&&ve===$.Vehicle,Xe=ve===$.Resale,Us=s.iva===0||s.iva==null,ke=x.useMemo(()=>{var U;return Xe&&!Us?Na((U=s.apiData)==null?void 0:U.vatBreakdown,f):null},[Xe,Us,(Xs=s.apiData)==null?void 0:Xs.vatBreakdown,f]),$s=(X&&N?y.lookupCatalog(N,ne?j:null):null)??y.lookup({businessCategory:X?I:null,vehicleExpenseType:_e?S:void 0,eventRole:j}),Yt=U=>(N?y.lookupCatalog(N,U):y.lookup({businessCategory:ve,vehicleExpenseType:_e?S:void 0,eventRole:U})).rate,Le=X&&!!R||!!I,Ks=(()=>{if(!b||b==="personal")return 0;const U=b==="partial"?k/100:1;return!Le||!X?s.iva*U:s.iva*U*($s.rate??1)})(),gs=X&&Le?$s.restrictionCode:void 0,Ys=!!gs,Gs=gs?l(`expenses.deductionRestriction.${gs}`):null,qs=async()=>{if(!Q()){if(!Ne){le(!0);return}if(fe&&!(!Le&&!Ae)){G(!0);try{const U=b==="partial"?k:b==="business"?100:void 0;await t({expenseId:s.id,expenseType:fe,category:I,catalogCategoryId:X?R??void 0:void 0,businessPercentage:X?U:void 0,eventRole:ne?j??void 0:void 0,isFixedAsset:we?P:void 0,personalCategoryForPartial:b==="partial"?V??void 0:void 0,vehicleExpenseType:_e?S:void 0})}finally{G(!1)}}}},Gt=async()=>{if(!Q()){if(!Ne){le(!0);return}if(!(!fe||!d)&&!(!I&&!Ae)){H(!0);try{const U=b==="partial"?k:b==="business"?100:void 0,Ue=b==="partial"?V??void 0:void 0,es=oe.map(Zt=>Zt.id),ss=[s.id,...es];await d(ss,fe,I,X?U:void 0,ne?j??void 0:void 0,we?P:void 0,Ue,_e?S:void 0),te(!1),n()}finally{H(!1)}}}},qt=U=>{D(U),_(null),U!=="partial"&&A(null)},Qs=fe&&(Le||Ae)&&(b!=="partial"||Le&&V)&&!(Xe&&ke&&!ke.isValid),Qt=ce&&!!I&&!N,Ht=x.useMemo(()=>{var U,Ue,es,ss;return{nomeEmitente:ge(s.nomeEmitente)||s.nifEmitente,nifEmitente:s.nifEmitente,total:s.total,iva:s.iva,emissionDate:typeof s.emissionDate=="string"?s.emissionDate:s.emissionDate.toISOString().split("T")[0],actividadeEmitente:s.actividadeEmitenteDesc??s.actividadeEmitente,vendorCae:((Ue=(U=s.companyInfo)==null?void 0:U.activity)==null?void 0:Ue.cae)??null,vendorCaeDescription:((ss=(es=s.companyInfo)==null?void 0:es.activity)==null?void 0:ss.description)??null,expenseType:s.expenseType??null,businessCategory:s.businessCategory??null,personalCategory:s.personalCategory??null,businessPercentage:s.businessPercentage??null}},[s]),Wt=()=>{if(!W.isAvailable){ie(!0);return}ue(!0),pe(U=>U+1)},Hs=s.nifEmitente?e.jsxs(z,{variant:"neutralSecondary",size:"small",onClick:Wt,leftSection:e.jsx(cn,{className:"h-3.5 w-3.5"}),className:"!h-7 !px-2.5 !text-xs",children:[e.jsx("span",{className:"hidden sm:inline",children:l("expenses.ai.askAboutExpense")}),e.jsx("span",{className:"sm:hidden",children:l("expenses.ai.title")})]}):null;return ps?e.jsxs("div",{className:v("border-t border-gray-200 px-3 py-4 sm:px-5 sm:py-5",c),children:[e.jsx(mt,{expense:s,allExpenses:i}),e.jsx("div",{className:"flex flex-col-reverse gap-2 pt-2 sm:flex-row sm:justify-start sm:gap-3",children:e.jsx(z,{variant:"neutralSecondary",onClick:n,className:"w-full sm:w-auto",children:l("button.label.close")})})]}):e.jsxs("div",{className:v("border-t border-gray-200 px-3 py-4 sm:px-5 sm:py-5",c),children:[De&&e.jsx(mt,{expense:s,allExpenses:i}),fs&&X&&(s.iva||0)>0&&e.jsx("div",{className:"mb-4 sm:mb-5",children:e.jsx($e,{variant:"info",action:{label:l("expenses.debitNote.contactSupport"),onClick:()=>is({source:"expense_debit_note_business_vat"})},children:l("expenses.debitNote.businessVatHint")})}),!g&&e.jsxs("div",{className:"mb-4 sm:mb-5",children:[e.jsxs("div",{className:"mb-2 flex items-center justify-between sm:mb-3",children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-wider text-gray-400",children:l("expenses.panel.type")}),Hs]}),e.jsx(Ha,{value:b,onChange:qt,businessPercentage:k,onBusinessPercentageChange:T})]}),!Ce&&b&&b!=="personal"&&e.jsxs("div",{className:v("mb-4 rounded-lg px-3 py-2.5 sm:mb-5 sm:px-4 sm:py-3",Ys?"bg-amber-50":"bg-gray-50"),children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-[13px] text-gray-600 sm:text-sm",children:l("expenses.panel.vatRefund")}),e.jsx("span",{className:v("text-[15px] font-bold sm:text-base",Ks>0?"text-emerald-600":"text-gray-400"),children:E(Ks)})]}),Ys&&Gs&&e.jsx("p",{className:"mt-1.5 text-[11px] text-amber-700 sm:text-xs",children:Gs})]}),b&&e.jsxs("div",{className:"mb-4 sm:mb-5",children:[e.jsxs("div",{className:"mb-2 flex items-center justify-between sm:mb-3",children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-wider text-gray-400",children:l(b==="partial"?"expenses.panel.businessCategory":"expenses.panel.category")}),g&&Hs]}),X?e.jsx(qa,{value:N,onChange:U=>{M(U??(R?null:u)),_(null)},suggestedBusinessCategory:(et=s.companyInfo)==null?void 0:et.suggestedBusinessCategory,expenses:i}):e.jsx(xt,{value:I,onChange:_,categories:He,isBusiness:X}),!X&&We&&e.jsx("p",{className:"mt-2 text-xs text-gray-500",children:l("expenses.panel.categoriesFilteredByCAE")})]}),b==="partial"&&e.jsxs("div",{className:"mb-4 sm:mb-5",children:[e.jsx("p",{className:"mb-2 text-xs font-semibold uppercase tracking-wider text-gray-400 sm:mb-3",children:l("expenses.panel.personalCategory")}),e.jsx(xt,{value:V,onChange:U=>A(U),categories:dt(m),isBusiness:!1})]}),Xe&&ke&&e.jsxs(e.Fragment,{children:[!ke.hasApiData&&e.jsx("div",{className:"mb-4 sm:mb-5",children:e.jsx($e,{variant:"warning",action:a?{label:l("expenses.resale.updateButton"),onClick:a,isLoading:r}:void 0,children:l("expenses.resale.noApiDataWarning")})}),ke.hasApiData&&ke.invalidRates.length>0&&e.jsx("div",{className:"mb-4 sm:mb-5",children:e.jsx($e,{variant:"error",action:{label:l("expenses.resale.contactSupport"),onClick:()=>is({source:"expense_resale_vat_mismatch"})},children:l("expenses.resale.vatMismatchError",{invalidRates:ke.invalidRates.join(", "),expectedRates:Ca(f)})})})]}),ne&&e.jsxs("div",{className:"mb-4 sm:mb-5",children:[e.jsx("p",{className:"mb-2 text-xs font-semibold uppercase tracking-wider text-gray-400 sm:mb-3",children:l("expenses.panel.eventRole")}
38),e.jsx(Ka,{value:j,onChange:C,rateFor:Yt})]}),we&&e.jsx("div",{className:"mb-4 sm:mb-5",children:e.jsx(Ia,{value:P,onChange:F})}),_e&&e.jsxs("div",{className:"mb-4 sm:mb-5",children:[e.jsx("p",{className:"mb-2 text-xs font-semibold uppercase tracking-wider text-gray-400 sm:mb-3",children:l("expenses.panel.vehicleExpenseType")}),e.jsx(Ja,{value:S,onChange:L})]}),e.jsxs("div",{className:"flex flex-col-reverse gap-2 pt-2 sm:flex-row sm:justify-start sm:gap-3",children:[e.jsx(z,{variant:"neutralSecondary",onClick:n,className:"w-full sm:w-auto",children:l("button.label.cancel")}),Qt?e.jsxs(js,{open:se,onOpenChange:re,children:[e.jsx(Ns,{asChild:!0,children:e.jsx(z,{variant:"fizPrime",disabled:!Qs||o,loading:Y||q,className:"w-full sm:w-auto",rightSection:e.jsx(As,{className:"ml-1 h-4 w-4"}),children:l("button.label.save")})}),e.jsx(Cs,{className:"w-auto p-1",align:"start",children:e.jsxs("div",{className:"flex flex-col",children:[e.jsx("button",{onClick:()=>{re(!1),qs()},className:"rounded px-3 py-2 text-left text-sm hover:bg-gray-100",children:l("button.label.save")}),e.jsx("button",{onClick:()=>{re(!1),te(!0)},className:"rounded px-3 py-2 text-left text-sm hover:bg-gray-100",children:l("expenses.saveAndApplyToSimilar",{count:oe.length})})]})})]}):e.jsx(z,{variant:"fizPrime",onClick:qs,disabled:!Qs||o,loading:Y,className:"w-full sm:w-auto",children:l("button.label.save")})]}),e.jsx(Ta,{isOpen:be,onClose:()=>ue(!1),expenseContext:Ht,expenseId:s.id,openNonce:xe}),W.messagesLimit!=null&&e.jsx(Jn,{isOpen:Z,onClose:()=>ie(!1),messagesUsed:W.messagesUsed,messagesLimit:W.messagesLimit,isCompany:g,isTrial:W.isTrial}),e.jsx(zt,{isOpen:J,onClose:()=>le(!1)}),ce&&e.jsx(Ba,{isOpen:he,onOpenChange:te,expenses:[s,...oe],expenseType:fe,category:I,businessPercentage:b==="partial"?k:void 0,onConfirm:Gt,isLoading:q})]})},gt=()=>{const{t:s}=B();return e.jsx("span",{className:"rounded-[6px] bg-[#FFF4D6] px-1.5 py-0.5 text-[10px] font-semibold text-[#B8860B]",title:s("expenses.fizBadge.tooltip"),children:"FIZ"})},ht=[{key:"vendor",labelKey:"expenses.table.vendor",sortable:!0,sortField:"date"},{key:"total",labelKey:"expenses.table.total",sortable:!0,sortField:"amount"},{key:"vat",labelKey:"expenses.table.vat",sortable:!0,sortField:"vat"},{key:"sync",labelKey:"table.col.status",sortable:!1,sortField:void 0},{key:"category",labelKey:"expenses.table.category",sortable:!0,sortField:"category"}],Xa=({expenses:s,isLoading:t,selectedFilter:n,onCategorize:a,onBatchCategorize:r,onSyncExpenses:o,isSyncing:c,isCategorySyncing:i,initialExpandedExpenseId:d})=>{const{t:l}=B(),m=Ee(),[y,p]=x.useState(d??null),[f,g]=x.useState("date"),[w,h]=x.useState("desc"),b=dn("(min-width: 768px)"),D=x.useRef(!1),I=x.useCallback(u=>{u&&d&&!D.current&&(D.current=!0,u.scrollIntoView({block:"center",behavior:"smooth"}))},[d]),_=x.useMemo(()=>Pa(s,f,w),[s,f,w]),k=u=>{u===f?h(w==="asc"?"desc":"asc"):(g(u),h("desc"))},T=u=>f!==u?e.jsx(un,{size:14,className:"opacity-40"}):w==="asc"?e.jsx(xn,{size:14}):e.jsx(xs,{size:14});if(t||c){const u=Array.from({length:b?5:4});return e.jsx("div",{className:"space-y-2",children:b?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"grid grid-cols-[minmax(280px,1fr)_110px_90px_120px_180px] items-center gap-4 roun
38ded-lg bg-stone-600 px-5 py-3",children:ht.map(N=>e.jsx("div",{className:v("h-3 rounded bg-white/30",N.key==="vendor"&&"w-24",N.key==="total"&&"ml-auto w-12",N.key==="vat"&&"ml-auto w-10",N.key==="sync"&&"w-16",N.key==="category"&&"w-20")},N.key))}),u.map((N,S)=>e.jsxs("div",{className:v("grid grid-cols-[minmax(280px,1fr)_110px_90px_120px_180px] items-center gap-4 rounded-xl px-5 py-4",S%2===0?"bg-gray-100":"bg-gray-50"),children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-10 w-10 animate-pulse rounded-xl bg-gray-200"}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"h-3 w-40 animate-pulse rounded bg-gray-200"}),e.jsx("div",{className:"h-2.5 w-20 animate-pulse rounded bg-gray-200"})]})]}),e.jsx("div",{className:"ml-auto h-3 w-16 animate-pulse rounded bg-gray-200"}),e.jsx("div",{className:"ml-auto h-3 w-12 animate-pulse rounded bg-gray-200"}),e.jsx("div",{className:"h-6 w-16 animate-pulse rounded-full bg-gray-200"}),e.jsx("div",{className:"h-7 w-28 animate-pulse rounded-lg bg-gray-200"})]},S))]}):u.map((N,S)=>e.jsx("div",{className:"rounded-xl bg-white-vanilla px-3 py-2.5",children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-2",children:[e.jsx("div",{className:"h-8 w-8 animate-pulse rounded-lg bg-gray-200"}),e.jsxs("div",{className:"min-w-0 flex-1 space-y-2",children:[e.jsx("div",{className:"h-3 w-36 animate-pulse rounded bg-gray-200"}),e.jsx("div",{className:"h-2.5 w-14 animate-pulse rounded bg-gray-200"})]})]}),e.jsxs("div",{className:"flex flex-col items-end gap-1",children:[e.jsx("div",{className:"h-3 w-16 animate-pulse rounded bg-gray-200"}),e.jsx("div",{className:"h-2.5 w-12 animate-pulse rounded bg-gray-200"})]})]})},S))})}if(s.length===0)return e.jsx("div",{className:"flex h-64 flex-col items-center justify-center rounded-lg border border-dashed border-gray-300 bg-gray-50",children:e.jsx("p",{className:"text-lg font-medium text-gray-600",children:l("expenses.noExpenses")})});const C=u=>{p(y===u?null:u)},P=async u=>{await a(u),p(null)},F=()=>{p(null)},R=u=>{var L;if(Te(u))return{amount:0,isPersonal:!1,colorClass:"text-gray-400",isLinkedCreditNote:!0};const N=za(u),S=N?u.iva:u.isCategorized?((L=u.vatDeduction)==null?void 0:L.deductibleVat)??null:u.iva;return{amount:S,isPersonal:N,colorClass:N||(S??0)<0?"text-gray-400":Oa(u)?"text-amber-600":"text-emerald-600",isLinkedCreditNote:!1}},M=u=>{switch(Ma(u,i,m)){case"syncing":return{label:l("expenses.syncStatus.syncing"),pillClass:"bg-sky-100 text-sky-700",dotClass:"text-sky-500",showSpinner:!0};case"pending":return{label:l("expenses.syncStatus.pending"),pillClass:"bg-amber-100 text-amber-700",dotClass:"bg-amber-500",showSpinner:!1};case"failed":return{label:l("expenses.syncStatus.failed"),pillClass:"bg-red-100 text-red-700",dotClass:"bg-red-500",showSpinner:!1};case"synced":default:return{label:l("expenses.syncStatus.synced"),pillClass:"bg-emerald-100 text-emerald-700",dotClass:"bg-emerald-500",showSpinner:!1}}};return b?e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"grid grid-cols-[minmax(280px,1fr)_110px_90px_120px_180px] items-center gap-4 roun
38ded-lg bg-stone-600 px-5 py-3",children:ht.map(u=>e.jsxs("button",{type:"button",onClick:()=>u.sortField&&k(u.sortField),className:v("flex items-center gap-1 text-sm font-semibold text-white transition-colors",u.sortField?"hover:text-gray-200":"cursor-default",(u.key==="total"||u.key==="vat")&&"justify-end",u.key==="sync"&&"justify-center"),children:[l(u.labelKey),u.sortField&&T(u.sortField)]},u.key))}),_.map((u,N)=>{var G,q,H;const S=y===u.id,L=N%2===0,V=((G=u.companyInfo)==null?void 0:G.brandName)??((q=u.companyInfo)==null?void 0:q.name)??ge(u.nomeEmitente),A=R(u),Y=M(u);return e.jsxs("div",{ref:u.id===d?I:void 0,className:v("overflow-hidden rounded-xl",S&&"ring-2 ring-amber-400/50"),children:[e.jsxs("div",{onClick:()=>C(u.id),className:v("grid cursor-pointer grid-cols-[minmax(280px,1fr)_110px_90px_120px_180px] items-center gap-4 px-5 py-4",L?"bg-gray-100":"bg-gray-50",u.isCategorized&&"border-l-[6px] border-light-green",!S&&"hover:bg-gray-200",S&&"rounded-b-none"),children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-3",children:[(H=u.companyInfo)!=null&&H.logoUrl?e.jsx("img",{src:u.companyInfo.logoUrl,alt:V,className:"h-10 w-10 flex-shrink-0 rounded-xl object-contain"}):e.jsx("div",{className:v("flex h-10 w-10 flex-shrink-0 items-center justify-center rounded-xl text-xs font-semibold transition-colors",u.isCategorized?"bg-emerald-100 text-emerald-700":"bg-amber-100 text-amber-700"),children:V.substring(0,2).toUpperCase()}),e.jsxs("div",{className:"min-w-0",children:[e.jsx(ot,{companyInfo:u.companyInfo,children:e.jsxs("p",{className:"flex cursor-pointer items-center gap-1 text-sm font-medium text-gray-900 hover:text-blue-700 hover:underline",children:[e.jsx("span",{className:"truncate",children:V}),u.companyInfo&&e.jsx(je,{size:15,className:"flex-shrink-0 text-gray-400"})]})}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"text-xs text-gray-500",children:Se(u.emissionDate).format("MMM D")}),u.invoiceNumber&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-gray-300",children:"·"}),e.jsx("span",{className:"truncate text-[11px] text-gray-400",children:u.invoiceNumber})]}),u.isInFiz&&e.jsx(gt,{}),Fe(u.tipoDocumento)&&e.jsx(ct,{isLinked:!!u.creditNoteParent}),e.jsx("a",{href:ut(u),target:"_blank",rel:"noopener noreferrer",onClick:se=>se.stopPropagation(),className:"flex-shrink-0 text-blue-500 transition-colors hover:text-blue-600","aria-label":"e-Fatura",children:e.jsx(tt,{size:16})})]})]})]}),e.jsx("div",{className:"text-right",children:e.jsx("span",{className:"text-sm font-semibold text-gray-900",children:E(u.total)})}),e.jsx("div",{className:"text-right",children:e.jsx("span",{className:v("text-sm font-medium",A.colorClass),children:A.isLinkedCreditNote||A.amount==null?"â":E(A.amount)})}),e.jsx("div",{className:"flex justify-center",children:e.jsxs("span",{className:v("inline-flex items-center gap-1 rounded-full px-2 py-1 text-[11px] font-medium",Y.pillClass),children:[Y.showSpinner?e.jsx(nt,{size:11,className:v("animate-spin",Y.dotClass)}):e.jsx("span",{className:v("h-1.5 w-1.5 rounded-full",Y.dotClass)}),Y.label]})}),e.jsx("div",{children:Fe(u.tipoDocumento)&&u.creditNoteParent?e.jsx("span",{className:"inline-flex items-center rounded-lg bg-gray-200 px-2.5 py-1.5 text-xs font-semibold text-gray-600",children:l("expenses.creditNote.inheritedBadge")}):u.isCategorized?e.jsx(_t,{expenseType:u.expenseType,businessCategory:u.businessCategory,personalCategory:u.personalCategory,businessPercentage:u.businessPercentage,showAsPersonalPortion:n==="personal"&&Fa(u)}):e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-lg bg-amber-100 px-2.5 py-1.5 text-xs font-semibold text-amber-800",children:[e.jsx("span",{className:"text-amber-600",children:"?"}),l("expenses.classify")]})})]}),S&&e.jsx(ft,{expense:u,onSave:P,onCancel:F,onSyncExpenses:o,isSyncing:c,isCategorySyncing:i,allExpenses:s,onBatchSave:r,className:v(L?"bg-gray-100":"bg-gray-50","rounded-b-xl")})]},u.id)})]}):e.jsx("div",{className:"w-full space-y-1.5 overflow-hidden",children:_.map(u=>{var A,Y,G;const N=y===u.id,S=((A=u.companyInfo)==null?void 0:A.brandName)??((Y=u.companyInfo)==null?void 0:Y.name)??ge(u.nomeEmitente),L=R(u),V=M(u);return e.jsxs("div",{ref:u.id===d?I:void 0,className:v("overflow-hidden bg-white-vanilla",N&&"ring-2 ring-amber-400/50"),children:[e.jsx("div",{onClick:()=>C(u.id),className:v("cursor-pointer overflow-hidden px-3 py-2.5 transition-colors duration-150",u.isCategorized&&"border-l-3 border-light-green",!N&&"active:bg-gray-100"),children:e.jsxs("div",{className:"flex w-full items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-2",children:[(G=u.companyInfo)!=null&&G.logoUrl?e.jsx("img",{src:u.companyInfo.logoUrl,alt:S,className:"h-8 w-8 flex-shrink-0 rounded-lg object-contain"}):e.jsx("div",{className:v("flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-lg text-[10px] font-bold",u.isCategorized?"bg-emerald-100 text-emerald-700":"bg-amber-100 text-amber-700"),children:S.substring(0,2).toUpperCase()}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx(ot,{companyInfo:u.companyInfo,children:e.jsxs("p",{className:"flex cursor-pointer items-center gap-1 text-[13px] font-medium text-gray-900 hover:text-blue-700 hover:underline",children:[e.jsx("span",{className:"truncate",children:S}),u.companyInfo&&e.jsx(je,{size:14,className:"flex-shrink-0 text-gray-400"})]})}),e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsx("span",{className:"text-[11px] text-gray-400",children:Se(u.emissionDate).format("D MMM")}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[u.invoiceNumber&&e.jsx("span",{className:"truncate text-[11px] text-gray-500",children:u.invoiceNumber}),u.isInFiz&&e.jsx(gt,{}),Fe(u.tipoDocumento)&&e.jsx(ct,{isLinked:!!u.creditNoteParent}),e.jsx("button",{type:"button",onClick:q=>{q.stopPropagation(),window.open(ut(u),"_blank","noopener,noreferrer")},className:"-m-1.5 flex-shrink-0 rounded-md p-1.5 text-blue-500 active:bg-blue-100","aria-label":"e-Fatura",children:e.jsx(tt,{size:18})})]})]})]})]}),e.jsxs("div",{className:"flex flex-shrink-0 flex-col items-end",children:[e.jsx("span",{className:"text-[13px] font-bold text-gray-900",children:E(u.total)}),e.jsxs("span",{className:v("text-[11px] font-medium",L.colorClass),children:["VAT: ",L.isLinkedCreditNote||L.amount==null?"â":E(L.amount)]}),e.jsxs("span",{className:v("mt-1 inline-flex items-center gap-1 rounded-full px-1.5 py-0.5 text-[10px] font-medium",V.pillClass),children:[V.showSpinner?e.jsx(nt,{size:10,
38className:v("animate-spin",V.dotClass)}):e.jsx("span",{className:v("h-1.5 w-1.5 rounded-full",V.dotClass)}),V.label]})]})]})}),N&&e.jsx(ft,{expense:u,onSave:P,onCancel:F,onSyncExpenses:o,isSyncing:c,isCategorySyncing:i,allExpenses:s,onBatchSave:r,className:"rounded-b-xl bg-gray-100"})]},u.id)})})};function er(s){const{quarter:t,year:n}=mn(),a=n-1,r=[];r.push({value:String(a),label:`${a} (${s("expenses.periodSelector.fullYear")})`}),r.push({value:String(n),label:`${n} (${s("expenses.periodSelector.fullYear")})`});for(let o=1;o<=4;o++)r.push({value:`${a}-Q${o}`,label:s("expenses.periodSelector.quarter",{n:o,year:a})});for(let o=1;o<=t;o++)r.push({value:`${n}-Q${o}`,label:s("expenses.periodSelector.quarter",{n:o,year:n})});return r}function sr(s){if(s.includes("-Q")){const[t,n]=s.split("-Q");return{year:parseInt(t,10),quarter:parseInt(n,10)}}return{year:parseInt(s,10),quarter:null}}function tr(s,t){return t===null?String(s):`${s}-Q${t}`}const nr=({selectedYear:s,selectedQuarter:t,onPeriodChange:n})=>{const{t:a}=B(),r=er(a),o=tr(s,t),c=i=>{const{year:d,quarter:l}=sr(i);n(d,l)};return e.jsx("div",{className:"w-full max-w-[240px]",children:e.jsxs(Ss,{value:o,onValueChange:c,children:[e.jsx(Es,{className:"h-9 w-full rounded-md border-gray-200 bg-white px-3 text-sm font-medium",children:e.jsx(ks,{})}),e.jsx(Ts,{children:r.map(i=>e.jsx(Is,{value:i.value,children:i.label},i.value))})]})})},ar={success:"text-emerald-600",warning:"text-amber-600",info:"text-gray-500"},ys=({color:s,label:t,count:n,amount:a,sublabel:r,sublabelAmount:o,notes:c,isSelected:i,onClick:d,isLoading:l})=>l?e.jsx("div",{className:"flex flex-1 rounded-lg bg-white-vanilla p-3 sm:p-4",children:e.jsxs(at,{className:"w-full gap-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(rs,{className:"h-5 w-8 rounded-full"}),e.jsx(rs,{className:"h-4 w-16 sm:w-24"})]}),e.jsx(rs,{className:"h-4 w-14 sm:w-20"})]})}):e.jsx("div",{className:v("flex flex-1 rounded-lg bg-white-vanilla p-3 transition-all sm:rounded-xl sm:p-4",{"outline outline-[3px] outline-moroccan-blue":i,"cursor-pointer active:bg-gray-50 sm:hover:bg-gray-50":!!d}),onClick:d,children:e.jsxs(at,{className:"w-full gap-0.5 sm:gap-1",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex items-center gap-1.5 sm:gap-2",children:[n!==void 0&&e.jsx("span",{className:`rounded-full px-2 py-0.5 text-[12px] font-semibold text-white sm:px-3 sm:text-[14px] ${s}`,children:n}),e.jsx("span",{className:"text-[13px] font-bold text-dark-resin sm:text-[17px]",children:t})]}),a&&e.jsx("span",{className:"text-[13px] font-bold text-black-magic sm:text-[17px]",children:a})]}),(r||o)&&e.jsxs("div",{className:"flex items-center justify-between",children:[r&&e.jsx("span",{className:"text-[11px] text-gray-500 sm:text-[13px]",children:r}),o&&e.jsx("span",{className:"text-[11px] text-gray-500 sm:text-[13px]",children:o})]}),c==null?void 0:c.map((m,y)=>e.jsxs("div",{className:v("flex items-center justify-between text-[11px] sm:text-[13px]",ar[m.variant]),children:[e.jsx("span",{children:m.text}),m.amount&&e.jsx("span",{children:m.amount})]},y))]})}),rr=({isLoading:s,onFilterClick:t,selectedFilter:n,categoryTotals:a,uncategorizedCount:r,businessCount:o,personalCount:c,actualDeductibleVat:i,isDeductibleVatLoading:d=!1,hideVatDeduction:l,businessVatNotes:m,uncategorizedVat:y})=>{const{t:p}=B(),f=Ee(),g=l?void 0:p("expenses.stats.vatAmount"),w=h=>{t&&t(n===h?"all":h)};return e.jsxs("div",{className:v("mb-3 flex flex-col gap-2 sm:mb-6 sm:grid sm:gap-3",f?"sm:grid-cols-2":"sm:grid-cols-3"),children:[e.jsx(ys,{color:"bg-amber-500",label:p("expenses.stats.uncategorized"),count:r,amount:E(a.uncategorizedTotal,"EUR"),sublabel:g,sublabelAmount:l?void 0:E(y,"EUR"),isSelected:n==="uncategorized",onClick:()=>w("uncategorized"),isLoading:s}),e.jsx(ys,{color:"bg-blue-600",label:p("expenses.stats.business"),count:o,amount:E(a.businessTotal,"EUR"),sublabel:g,sublabelAmount:l||d?void 0:E(i,"EUR"),notes:l?void 0:m,isSelected:n==="business",onClick:()=>w("business"),isLoading:s}),!f&&e.jsx(ys,{color:"bg-violet-600",label:p("expenses.stats.personal"),count:c,amount:E(a.personalTotal,"EUR"),sublabel:g,sublabelAmou
38nt:l?void 0:E(a.personalVat,"EUR"),isSelected:n==="personal",onClick:()=>w("personal"),isLoading:s})]})},lr=({expenseJustificationData:s,statusConfig:t,progressCapped:n})=>{const{t:a}=B(),[r,o]=x.useState(!1),{grossIncome:c,requiredExpenses:i,status:d,shortfall:l,surplus:m,verifiedExpenses:y}=s,p=d==="protected"?"success":"warning",f={info:"bg-blue-50 border-blue-200 text-blue-800",warning:"bg-amber-50 border-amber-200 text-amber-800",success:"bg-green-50 border-green-200 text-green-800"};return e.jsxs(Ge,{open:r,onOpenChange:o,children:[e.jsx(qe,{asChild:!0,children:e.jsxs("button",{type:"button",className:v("flex w-full items-center justify-between rounded-xl border border-border bg-card p-3 text-left transition-all","hover:bg-muted/30 focus:outline-none focus-visible:ring-2 focus-visible:ring-ring",r&&"rounded-b-none border-b-0"),children:[e.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-2.5",children:[e.jsx("div",{className:v("flex h-8 w-8 items-center justify-center rounded-lg",t.bg),children:e.jsx(pn,{className:v("h-4 w-4",t.text)})}),e.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[e.jsx("span",{className:"text-sm font-medium leading-tight text-foreground",children:a("expenses.irs.expenseJustification")}),e.jsx(Ps,{children:e.jsxs(Os,{children:[e.jsx(zs,{asChild:!0,onClick:g=>g.stopPropagation(),children:e.jsx(Et,{className:"h-3.5 w-3.5 text-muted-foreground/50 hover:text-muted-foreground"})}),e.jsx(Fs,{className:"max-w-xs",children:e.jsx("p",{className:"text-xs",children:a("expenses.irs.expenseJustificationTooltip")})})]})})]})]}),e.jsxs("div",{className:"ml-2 flex flex-shrink-0 items-center gap-2",children:[e.jsxs("div",{className:"flex flex-col items-end gap-1 sm:flex-row sm:items-center sm:gap-2",children:[e.jsx("div",{className:v(!r&&"hidden sm:block"),children:e.jsx("span",{className:v("rounded-full px-2 py-0.5 text-xs font-medium",t.bg,t.text),children:a(Ft[d])})}),e.jsx("span",{className:"whitespace-nowrap text-sm font-semibold tabular-nums text-foreground",children:d==="protected"?`+${E(m)}`:E(l)})]}),e.jsx(Ms,{className:v("h-4 w-4 text-muted-foreground transition-transform duration-200",r&&"rotate-90")})]})]})}),e.jsx(Qe,{children:e.jsx("div",{className:"rounded-b-xl border border-t-0 border-border bg-card p-3 pt-0",children:e.jsxs("div",{className:"space-y-3 pt-3",children:[e.jsxs("div",{className:v("flex items-start gap-2 rounded-lg border px-3 py-2 text-xs",f[p]),children:[e.jsx(je,{className:"mt-0.5 h-3.5 w-3.5 flex-shrink-0 opacity-70"}),e.jsxs("div",{children:[e.jsx("strong",{children:a("expenses.irs.whatIsThis")})," ",a("expenses.irs.expenseThresholdExplanation")]})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-2 text-center",children:[e.jsxs("div",{className:"rounded-lg bg-muted/50 p-2",children:[e.jsx("p",{className:"text-base font-bold sm:text-lg",children:E(c)}),e.jsx("p",{className:"text-[10px] uppercase text-muted-foreground",children:a("expenses.irs.grossIncome")})]}),e.jsxs("div",{className:"flex flex-col items-center justify-center rounded-lg bg-muted/50 p-2",children:[e.jsx("p",{className:"text-base font-bold sm:text-lg",children:"Ã15%"}),e.jsx("p",{className:"text-[10px] uppercase text-muted-foreground",children:a("expenses.irs.fifteenPercentRule")})]}),e.jsxs("div",{className:v("rounded-lg p-2",t.bg),children:[e.jsx("p",{className:v("text-base font-bold sm:text-lg",t.text),children:E(i)}),e.jsx("p",{className:v("text-[10px] uppercase",t.text,"opacity-80"),children:a("expenses.irs.expenseTarget")})]})]}),e.jsxs("div",{className:"flex items-start gap-2 rounded-lg border bg-blue-50 border-blue-200 text-blue-800 px-3 py-2 text-xs",children:[e.jsx(je,{className:"mt-0.5 h-3.5 w-3.5 flex-shrink-0 opacity-70"}),e.jsxs("div",{children:[e.jsx("strong",{children:a("expenses.irs.ssCountsTitle")})," ",a("expenses.irs.ssCountsExplanation")]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"relative",children:[e.jsx(ms,{value:n,className:"h-4",indicatorClassName:t.progress}),e.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:e.jsxs("span",{className:"text-[10px] font-bold text-white drop-shadow-sm",children:[Math.round(n),"%"]})})]}),e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsxs("span",{className:"text-muted-foreground",children:[E(y)," / ",E(i)]}),e.jsx("span",{className:v("font-medium",t.text),children:d==="protected"?a("expenses.irs.statusMessage.protectedS
38hort"):a("expenses.irs.statusMessage.penaltyShort",{amount:E(l)})})]})]}),d==="penalty"&&e.jsxs("div",{className:"flex items-start gap-2 rounded-lg border bg-amber-50 border-amber-200 text-amber-800 px-3 py-2 text-xs",children:[e.jsx(je,{className:"mt-0.5 h-3.5 w-3.5 flex-shrink-0 opacity-70"}),e.jsx("div",{children:a("expenses.irs.shortfallCallout",{amount:E(l)})})]})]})})})]})},bt="fiz:irs:checkCirsAlertDismissed";function ir(s){switch(s){case"protected":return kt;case"at-risk":return cs;case"penalty":return rt;default:return rt}}const yt=({icon:s,title:t,summaryValue:n,summaryBadge:a,helpText:r,children:o,defaultOpen:c=!1,iconBgClass:i="bg-muted",iconTextClass:d="text-muted-foreground"})=>{const[l,m]=x.useState(c);return e.jsxs(Ge,{open:l,onOpenChange:m,children:[e.jsx(qe,{asChild:!0,children:e.jsxs("button",{type:"button",className:v("flex w-full items-center justify-between rounded-xl border border-border bg-card p-3 text-left transition-all","hover:bg-muted/30 focus:outline-none focus-visible:ring-2 focus-visible:ring-ring",l&&"rounded-b-none border-b-0"),children:[e.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-2.5",children:[e.jsx("div",{className:v("flex h-8 w-8 items-center justify-center rounded-lg",i),children:e.jsx(s,{className:v("h-4 w-4",d)})}),e.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[e.jsx("span",{className:"text-sm font-medium leading-tight text-foreground",children:t}),r&&e.jsx(Ps,{children:e.jsxs(Os,{children:[e.jsx(zs,{asChild:!0,onClick:y=>y.stopPropagation(),children:e.jsx(Et,{className:"h-3.5 w-3.5 text-muted-foreground/50 hover:text-muted-foreground"})}),e.jsx(Fs,{className:"max-w-xs",children:e.jsx("p",{className:"text-xs",children:r})})]})})]})]}),e.jsxs("div",{className:"ml-2 flex flex-shrink-0 items-center gap-2",children:[e.jsxs("div",{className:"flex flex-col items-end gap-1 sm:flex-row sm:items-center sm:gap-2",children:[a&&e.jsx("div",{className:v(!l&&"hidden sm:block"),children:a}),e.jsx("span",{className:"whitespace-nowrap text-sm font-semibold tabular-nums text-foreground",children:n})]}),e.jsx(Ms,{className:v("h-4 w-4 text-muted-foreground transition-transform duration-200",l&&"rotate-90")})]})]})}),e.jsx(Qe,{children:e.jsx("div",{className:"rounded-b-xl border border-t-0 border-border bg-card p-3 pt-0",children:o})})]})},vt=({children:s,variant:t="info"})=>{const n={info:"bg-blue-50 border-blue-200 text-blue-800",warning:"bg-amber-50 border-amber-200 text-amber-800",success:"bg-green-50 border-green-200 text-green-800"};return e.jsxs("div",{className:v("flex items-start gap-2 rounded-lg border px-3 py-2 text-xs",n[t]),children:[e.jsx(je,{className:"mt-0.5 h-3.5 w-3.5 flex-shrink-0 opacity-70"}),e.jsx("div",{children:s})]})},or=({icon:s,label:t,value:n,sublabel:a,limit:r,formula:o})=>{const[c,i]=x.useState(!1),d=r&&r>0?Math.min(100,n/r*100):null;return e.jsxs("div",{className:"space-y-1 py-1.5",children:[e.jsxs("div",{className:v("flex items-center justify-between",o&&"cursor-pointer"),onClick:o?()=>i(!c):void 0,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[s&&e.jsx(s,{className:"h-4 w-4 text-muted-foreground"}),o&&e.jsx(xs,{className:v("h-3 w-3 text-muted-foreground/60 transition-transform duration-150",!c&&"-rotate-90")}),e.jsxs("div",{children:[e.jsx("span",{className:"text-sm text-foreground",children:t}),a&&e.jsxs("span",{className:"ml-1 text-xs text-muted-foreground",children:["(",a,")"]})]})]}),e.jsxs("div",{className:"text-right",children:[e.jsx("span",{className:"text-sm font-medium tabular-nums text-foreground",children:E(n)}),r&&e.jsxs("span",{className:"ml-1 text-xs text-muted-foreground",children:["/ ",E(r)]})]})]}),d!==null&&e.jsx("div",{className:"h-1.5 w-full overflow-hidden rounded-full bg-gray-100",children:e.jsx("div",{className:v("h-full rounded-full transition-all",d>=100?"bg-green-500":d>=50?"bg-amber-400":"bg-gray-300"),style:{width:`${d}%`}})}),o&&c&&e.jsx("p",{className:"pl-5 text-[11px] text-muted-foreground",children:o})]})},cr=({sharedCategories:s,sharedActualDeduction:t,sharedPotentialDeduction:n,getCategoryLabel:a,t:r})=>{const[o,c]=x.useState(!1),i=s.filter(l=>l.totalSpent>0),d=Math.min(100,t/bs*100);return e.jsxs("div",{className:"py-1.5",children:[e.jsxs("div",{className:"flex cursor-pointer items-center justify-between",onClick:()=>c(!o),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(xs,{className:v("h-3 w-3 text-muted-foreground
38/60 transition-transform duration-150",!o&&"-rotate-90")}),e.jsxs("div",{children:[e.jsx("span",{className:"text-sm text-foreground",children:r("expenses.irs.sharedCategories")}),!o&&i.length>0&&e.jsxs("span",{className:"ml-1 text-xs text-muted-foreground",children:["(",i.map(l=>a(l.category)).join(", "),")"]})]})]}),e.jsxs("div",{className:"text-right",children:[e.jsx("span",{className:"text-sm font-medium tabular-nums text-foreground",children:E(t)}),e.jsxs("span",{className:"ml-1 text-xs text-muted-foreground",children:["/ ",E(bs)]})]})]}),e.jsx("div",{className:"mt-1 h-1.5 w-full overflow-hidden rounded-full bg-gray-100",children:e.jsx("div",{className:v("h-full rounded-full transition-all",d>=100?"bg-green-500":d>=50?"bg-amber-400":"bg-gray-300"),style:{width:`${d}%`}})}),t<n&&n>0&&e.jsx("p",{className:"mt-1 pl-5 text-[11px] text-muted-foreground",children:r("expenses.irs.formulaCapped",{limit:E(bs)})}),o&&e.jsx("div",{className:"ml-5 mt-2 space-y-1 border-l border-border pl-3",children:i.length>0?i.map(l=>
38{const m=Bt[l.category],y=`${Math.round(m.percentage*100)}%`,p=`IVA ${E(l.vatPaid)} à ${y} = ${E(l.potentialDeduction)}`;return e.jsxs("div",{className:"flex items-center justify-between py-0.5",children:[e.jsx("span",{className:"text-xs text-foreground",children:a(l.category)}),e.jsx("span",{className:"text-[11px] tabular-nums text-muted-foreground",children:p})]},l.category)}):e.jsx("p",{className:"text-xs text-muted-foreground",children:r("expenses.irs.noSharedExpenses")})})]})},dr=({businessExpensesTotal:s=0,personalExpensesByCategory:t=[],grossIncome:n,withholdingTax:a=0,cirsInfo:r,isLoading:o=!1,defaultOpen:c=!1,taxYear:i=Mt()})=>{const{t:d}=B(),[l,m]=x.useState(c),[y,p]=x.useState(!1),[f,g]=x.useState(!1);x.useEffect(()=>{try{localStorage.getItem(bt)==="true"&&g(!0)}catch{}},[]);const w=()=>{g(!0);try{localStorage.setItem(bt,"true")}catch{}},h=(r==null?void 0:r.coefficient)??.75,b=(r==null?void 0:r.canCalculate)??!1,D=(r==null?void 0:r.activityType)??null,I=(r==null?void 0:r.hasCIRS)??!1,_=D!=="GOODS",k=(r==null?void 0:r.hasArt151CAE)??!1,T=D==="SERVICE"&&!I&&!k&&b&&!f,j=D==="MIXED"||!b&&D!=="GOODS",C=x.useMemo(()=>Xn(s,n),[s,n]),P=x.useMemo(()=>(n||0)*h+C.shortfall,[n,h,C.shortfall]),F=x.useMemo(()=>ea(t,P),[t,P]),R=sa[C.status],M=ir(C.status),u=Math.min(C.progressPercent,100),N=S=>d(`expenses.irs.categories.${S.toLowerCase().replace(/_/g,"")}`);return o?e.jsx("div",{className:"mb-4 space-y-2",children:[1,2,3].map(S=>e.jsx(rs,{className:"h-14 w-full rounded-xl"},S))}):e.jsxs("div",{className:"mb-4 space-y-2",children:[e.jsxs(Ge,{open:l,onOpenChange:m,children:[e.jsx(qe,{asChild:!0,children:e.jsxs("button",{type:"button",className:v("flex w-full flex-col rounded-xl border border-border bg-card p-3 text-left transition-all","hover:bg-muted/30 focus:outline-none focus-visible:ring-2 focus-visible:ring-ring",l&&"rounded-b-none border-b-0"),children:[e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:v("flex h-10 w-10 items-center justify-center rounded-full",R.bg),children:e.jsx(M,{className:v("h-5 w-5",R.text)})}),e.jsxs("div",{children:[e.jsxs("h3",{className:"text-sm font-semibold text-foreground",children:[d("expenses.irs.widgetTitle")," · ",i]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:d(l?"expenses.irs.clickToCollapse":"expenses.irs.clickToExpand")})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[C.hasIncomeData&&b&&_&&e.jsx("div",{className:"hidden sm:block",children:e.jsx(Ps,{children:e.jsxs(Os,{children:[e.jsx(zs,{asChild:!0,children:e.jsxs("div",{className:v("rounded-full px-3 py-1 text-xs font-medium",R.bg,R.text),children:[R.icon," ",d(Ft[C.status])]})}),C.status==="penalty"&&e.jsx(Fs,{className:"max-w-xs",children:e.jsx("p",{className:"text-xs",children:d("expenses.irs.shortfallTooltip")})})]})})}),e.jsx(Ms,{className:v("h-5 w-5 text-muted-foreground transition-transform duration-200",l&&"rotate-90")})]})]}),!l&&C.hasIncomeData&&b&&_&&e.jsxs("div",{className:"mt-3 w-full space-y-1.5",children:[e.jsxs("div",{className:"relative",children:[e.jsx(ms,{value:u,className:"h-3",indicatorClassName:R.progress}),e.jsx("div",{className:"absolute right-0 top-0 h-3 w-0.5 bg-foreground
38/30"})]}),e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsxs("span",{className:"text-muted-foreground",children:[E(C.verifiedExpenses)," /"," ",E(C.requiredExpenses)]}),e.jsx("span",{className:v("font-medium",R.text),children:C.status==="protected"?`+${E(C.surplus)} ${d("expenses.irs.buffer")}`:d("expenses.irs.amountMissing",{amount:E(C.shortfall)})})]}),C.status==="penalty"&&e.jsxs("p",{className:"text-[10px] leading-tight text-muted-foreground",children:["ð¡ ",d("expenses.irs.penaltyHint",{amount:E(C.shortfall)})]})]}),!l&&!C.hasIncomeData&&e.jsxs("div",{className:"mt-3 flex w-full items-center gap-2 rounded-lg bg-amber-50 px-3 py-2 text-xs text-amber-700",children:[e.jsx(cs,{className:"h-4 w-4 flex-shrink-0"}),e.jsx("span",{children:d("expenses.irs.noIncomeDataForYear",{year:i})})]})]})}),e.jsx(Qe,{children:e.jsxs("div",{className:"space-y-2 rounded-b-xl border border-t-0 border-border bg-card p-3",children:[C.hasIncomeData&&b&&e.jsx(yt,{icon:fn,title:d("expenses.irs.incomeSummary"),summaryValue:E((n||0)*h),helpText:d("expenses.irs.incomeSummaryTooltip"),iconBgClass:"bg-amber-100",iconTextClass:"text-amber-600",children:e.jsxs("div",{className:"space-y-3 pt-3",children:[e.jsxs(vt,{children:[e.jsx("strong",{children:d("expenses.irs.whatIsThis")})," ",d("expenses.irs.incomeSummaryExplanation")]}),e.jsxs("div",{className:"grid grid-cols-3 gap-2 text-center",children:[e.jsxs("div",{className:"rounded-lg bg-muted/50 p-2",children:[e.jsx("p",{className:"text-base font-bold sm:text-lg",children:E(n||0)}),e.jsx("p",{className:"text-[10px] uppercase text-muted-foreground",children:d("expenses.irs.grossIncome")})]}),e.jsxs("div",{className:"flex flex-col items-center justify-center rounded-lg bg-muted/50 p-2",children:[e.jsxs("p",{className:"text-base font-bold sm:text-lg",children:["Ã",(h*100).toFixed(0),"%"]}),e.jsx("p",{className:"text-[10px] uppercase text-muted-foreground",children:d("expenses.irs.caeCoefficient")})]}),e.jsxs("div",{className:"rounded-lg bg-amber-100 p-2",children:[e.jsx("p",{className:"text-base font-bold text-amber-800 sm:text-lg",children:E((n||0)*h)}),e.jsx("p",{className:"text-[10px] uppercase text-amber-700",children:d("expenses.irs.taxableBase")})]})]}),a>0&&e.jsxs("div",{className:"flex items-center justify-between rounded-lg border border-green-200 bg-green-50 px-3 py-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(kt,{className:"h-4 w-4 text-green-600"}),e.jsx("span",{className:"text-sm text-green-800",children:d("expenses.irs.withholdingTax")})]}),e.jsx("span",{className:"font-semibold text-green-700",children:E(a)})]})]})}),j?e.jsx("div",{className:"rounded-xl border border-amber-200 bg-amber-50 p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-lg bg-amber-100",children:e.jsx(cs,{className:"h-4 w-4 text-amber-600"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h4",{className:"text-sm font-medium text-amber-800",children:d("expenses.irs.mixedActivityTitle")}),e.jsx("p",{className:"mt-1 text-xs text-amber-700",children:d("expenses.irs.mixedActivityDescription")}),e.jsx(z,{variant:"neutralSecondary",size:"small",className:"mt-3",onClick:()=>p(!0),children:d("expenses.irs.viewActivityCodes")})]})]})}):_&&b?e.jsx(lr,{expenseJustificationData:C,statusConfig:R,progressCapped:u}):null,T&&e.jsx("div",{className:"rounded-xl border border-blue-200 bg-blue-50 p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-lg bg-blue-100",children:e.jsx(je,{className:"h-4 w-4 text-blue-600"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h4",{className:"text-sm font-medium text-blue-800",children:d("expenses.irs.checkCIRSTitle")}),e.jsx("p",{className:"mt-1 text-xs text-blue-700",children:d("expenses.irs.checkCIRSDescription")}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-2",children:[e.jsx(z,{variant:"neutralSecondary",size:"small",onClick:()=>window.open("https://info.portaldasfinancas.gov.pt/pt/informacao_fiscal/codigos_tributarios/irs/Pages/irs155.aspx","_blank"),children:d("expenses.irs.viewArt151Table")}),e.jsx(z,{variant:"neutralSecondary",size:"small",onClick:()=>p(!0),children:d("expenses.irs.updateActivityCodes")}),e.jsx(z,{variant:"neutralGhost",size:"small",onClick:w,children:d("expenses.irs.dismissAlert")})]})]})]})}),e.jsx(yt,{icon:gn,title:d("expenses.irs.personalDeductions"),summaryValue:E(F.totalDeductible),helpText:d("expenses.irs.deductionsTooltip"),iconBgClass:"bg-pink-100",iconTextClass:"text-pink-600",defaultOpen:!0,children:e.jsxs("div",{className:"space-y-3 pt-3",children:[e.jsxs(vt,{children:[e.jsx("strong",{children:d("expenses.irs.whatIsThis")})," ",d("expenses.irs.deductionsExplanation")]}),e.jsxs("div",{className:"space-y-1",children:[F.independentCategories.map(S=>{const L=Bt[S.category],V=`${Math.round(L.percentage*100)}%`;let A;return S.totalSpent>0&&(L.calculationType==="percent_of_amount"?A=`${E(S.totalSpent)}
38 Ã ${V} = ${E(S.potentialDeduction)}`:A=`IVA ${E(S.vatPaid)} Ã ${V} = ${E(S.potentialDeduction)}`,S.actualDeduction<S.potentialDeduction&&(A+=` â ${d("expenses.irs.formulaCapped",{limit:E(S.categoryLimit)})}`)),e.jsx(or,{label:N(S.category),value:S.actualDeduction,limit:S.categoryLimit,formula:A},S.category)}),e.jsx(cr,{sharedCategories:F.sharedCategories,sharedActualDeduction:F.sharedActualDeduction,sharedPotentialDeduction:F.sharedPotentialDeduction,getCategoryLabel:N,t:d})]})]})})]})})]}),e.jsx(hn,{title:d("expenses.irs.addCirsModalTitle"),open:y,onOpenChange:p,children:e.jsx(bn,{closeModal:()=>p(!1)})})]})},jt=s=>{var t;return!!((t=s==null?void 0:s.getSubmittedVatDeclarationForCurrentPeriod)!=null&&t.declaration)},Nt=s=>{var n,a;const t=(a=(n=s==null?void 0:s.getSubmittedVatDeclarationForCurrentPeriod)==null?void 0:n.deductibles)==null?void 0:a.totalVat;return t!=null?t/100:null},ur=(s,t,n=!1)=>{const a=t===null,r=ts({variables:{quarter:1,year:s},skip:n||!a&&t!==1}),o=ts({variables:{quarter:2,year:s},skip:n||!a&&t!==2}),c=ts({variables:{quarter:3,year:s},skip:n||!a&&t!==3}),i=ts({variables:{quarter:4,year:s},skip:n||!a&&t!==4});return x.useMemo(()=>{var p;if(n)return{allFiled:!1,filedQuarters:[],declaredVatByQuarter:{},loading:!1,error:void 0};const d=[r,o,c,i],l=(p=d.find(f=>f.error))==null?void 0:p.error;if(!a){const f=(t??1)-1,g=d[f],w=jt(g==null?void 0:g.data),h=Nt(g==null?void 0:g.data),b=h!=null?{[t]:h}:{};return{allFiled:w,filedQuarters:w?[t]:[],declaredVatByQuarter:b,loading:(g==null?void 0:g.loading)??!1,error:g==null?void 0:g.error}}const m=[1,2,3,4].filter((f,g)=>jt(d[g].data)),y={};for(const f of[1,2,3,4]){const g=Nt(d[f-1].data);g!=null&&(y[f]=g)}return{allFiled:m.length===4,filedQuarters:m,declaredVatByQuarter:y,loading:d.some(f=>f.loading),error:l}},[r,o,c,i,t,a,n])};function xr(s){let t=0,n=0,a=0,r=0;const o=new Map(s.map(c=>[c.id,c]));for(const c of s){if(Te(c)){const m=o.get(c.creditNoteParent.expenseId);m!=null&&m.isCategorized&&m.expenseType===K.Business?n-=c.total:m!=null&&m.isCategorized&&m.expenseType===K.Personal&&(a-=c.total,r-=c.iva);continue}const i=Fe(c.tipoDocumento),d=i?-Math.abs(c.total):c.total,l=i?-Math.abs(c.iva):c.iva;c.isCategorized?c.expenseType===K.Business?n+=d:c.expenseType===K.Personal&&(a+=d,r+=l):t+=d}return{uncategorizedTotal:t,businessTotal:n,personalTotal:a,personalVat:r}}const mr=.01,ls=(s,t)=>Math.abs(s-t)<=mr;function pr(s,t,n,a,r,o,c=!1){if(c)return{displayAmount:0,savedAmount:0,mode:"NO_DATA",declaredTotal:0,expenseVatForFiled:0};const i=Object.keys(o).length>0,d=f=>f.reduce((g,w)=>g+(s[w]??0),0);if(!t&&!i)return{displayAmount:0,savedAmount:0,mode:"NO_DATA",declaredTotal:0,expenseVatForFiled:0};const l=Object.values(o).reduce((f,g)=>f+g,0);if(!r){if(n.length===0||!i)return{displayAmount:a,savedAmount:0,mode:"NOT_FILED",declaredTotal:0,expenseVatForFiled:0};const f=a;return ls(f,l)?{displayAmount:l,savedAmount:0,mode:"CONFIRMED_SAVED",declaredTotal:l,expenseVatForFiled:f}:{displayAmount:l,savedAmount:0,mode:"DECLARED_DIFFERS",declaredTotal:l,expenseVatForFiled:f}}if(n.length===0)return{displayAmount:a,savedAmount:0,mode:"NOT_FILED",declaredTotal:0,expenseVatForFiled:0};const m=d(n),y=d([1,2,3,4].filter(f=>!n.includes(f)));if(n.length===4)return ls(m,l)?{displayAmount:l,savedAmount:0,mode:"CONFIRMED_SAVED",declaredTotal:l,expenseVatForFiled:m}:{displayAmount:l,savedAmount:0,mode:"DECLARED_DIFFERS",declaredTotal:l,expenseVatForFiled:m};const p=ls(m,l)?"CONFIRMED_SAVED":"DECLARED_DIFFERS";return{displayAmount:y,savedAmount:l,mode:p,declaredTotal:l,expenseVatForFiled:m}}const fr=(s,t,n,a,r)=>{if(n)return[];if(s.mode==="NO_DATA")return[];if(s.declaredTotal>0){const o=ls(t,s.declaredTotal);return[{text:r("expenses.stats.vatDeclared"),amount:E(s.declaredTotal,"EUR"),variant:o?"success":"warning"}]}return s.mode==="NOT_FILED"&&a?[{text:r("expenses.stats.checkDeclaration"),variant:"info"}]:[]},gr=new Date("2026-02-11T00:00:00.000Z"),hr=({expenses:s,filteredExpenses:t,businessExpensesTotal:n,personalExpensesByCategory:a,isLoading:r,isSyncing:o,isCategorySyncing:c,syncProgress:i,onCategorize:d,onBatchCategorize:l,onSyncExpenses:m,stats:y,selectedFilter:p,onFilterChange:f,deductibleVatTotal:g,deductibleVatUnavailable:w,deductibleByQuarter:h,isDeductibleVatLoading:b,grossIncome:D,withholdingTax:I,cirsInfo:_,isIRSDataLoading:k,taxYear:T,operatingMode:j,hideVatDeduction:C,lastSyncDate:P,selectedYear:F,selectedQuarter:R,onPeriodChange:M,initialExpandedExpenseId:u})=>{const{t:N}=B(),S=Ee(),[L,V]=x.useState(!1),A=x.useMemo(()=>s.some(ce=>ce.isInFiz),[s]),Y=x.useMemo(()=>L?t.filter(ce=>ce.isInFiz):t,[L,t]),{filedQuarters:G,declaredVatByQuarter:q}=ur(F,R,C),H=x.useMemo(()=>pr(h,s.length>0,G,g,R===null,q,w),[h,g,s.length,G,R,q,w]),se=x.useMemo(()=>xr(s),[s]),re=x.useMemo(()=>ga(s),[s]),{uncategorizedCount:he,uncategorizedVat:te,businessCount:be,personalCount:ue}=ha(y,re),xe=new Date,pe=Math.ceil((xe.getMonth()+1)/3),Z=xe.getFullYear(),ie=R!==null?F<Z||F===Z&&R<pe:F<Z,J=b?void 0:fr(H,g,C,ie,N),le=(i==null?void 0:i.percent)??0,W=le>0?le:Vt,Ne=i==null?void 0:i.phase,Q=!S&&j!==Ke.IvaOnly,oe=!r&&!o&&F===2025&&((y==null?void 0:y.totalCount)??0)>0&&(!P||P<gr);return e.jsxs("div",{className:"min-h-screen w-[calc(100vw-24px)] pb-8 sm:w-full",children:[o&&e.jsx("div",{className:"sticky top-3 z-20 mb-4 px-2 sm:px-0",children:e.jsxs("div",{className:"mx-auto flex w-full max-w-2xl items-start gap-3 rounded-xl border border-amber-200 bg-white/95 p-4 shadow-sm backdrop-blur",children:[e.jsx("div",{className:"pt-0.5",children:e.jsx(us,{color:"#FFC850",size:24})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"text-sm font-medium text-gray-700",children:N(ta(Ne))}),e.jsx("div",{className:"mt-2",children:e.jsx(ms,{value:W,className:"h-2.5"})}),(i==null?void 0:i.current)!==void 0&&(i==null?void 0:i.total)!==void 0&&e.jsx("p",{className:"mt-1 text-xs text-gray-500",children:N("expenses.syncProgress.counter",{current:i.current,total:i.total})}),typeof(i==null?void 0:i.etaSec)=="number"&&i.etaSec>0&&e.jsx("p",{className:"mt-1 text-xs text-gray-500",children:N("expenses.syncProgress.eta",{seconds:i.etaSec})})]}),e.jsxs("p",{className:"shrink-0 pl-2 text-sm font-semibold text-gray-700",children:[Math.round(W),"%"]})]})}),o&&!i&&e.jsx("div",{className:"mb-3 px-2 sm:px-0",children:e.jsx("div",{className:"mx-auto w-full max-w-2xl rounded-lg border border-amber-100 bg-amber-50/60 px-3 py-2 text-xs text-amber-900",children:N("expenses.syncing")})}),e.jsxs("div",{className:"mx-auto w-full",children:[e.jsx(rr,{isLoading:r,selectedFilter:p,onFilterClick:f,categoryTotals:se,uncategorizedCount:he,businessCount:be,personalCount:ue,actualDeductibleVat:g,isDeductibleVatLoading:b,hideVatDeduction:C,businessVatNotes:J,uncategorizedVat:te}),Q&&e.jsx(dr,{businessExpensesTotal:n,personalExpensesByCategory:a,grossIncome:D,withholdingTax:I,cirsInfo:_,isLoading:r||k,taxYear:T}),e.jsxs("div",{className:"mb-3 mt-3 flex w-full flex-wrap items-center justify-between gap-3",children:[e.jsx(nr,{selectedYear:F,selectedQuarter:R,onPeriodChange:M}),A&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(yn,{id:"only-fiz-invoices",checked:L,onCheckedChange:ce=>V(ce===!0)}),e.jsx("label",{htmlFor:"only-fiz-invoices",className:"cursor-pointer text-sm text-dark-bronze",children:N("expenses.fizFilter.label")})]})]}),oe&&e.jsxs("div",{className:"mb-3 flex items-center justify-between gap-3 rounded-lg border border-amber-200 bg-amber-50 px-3 py-2",children:[e.jsx("p",{className:"text-xs text-amber-900 sm:text-sm",children:N("expenses.yearSyncMigration.notice")}),m&&e.jsx(z,{variant:"neutralSecondary",className:"!h-8 whitespace-nowrap !px-3",onClick:m,children:N("expenses.yearSyncMigration.action")})]}),e.jsx(Xa,{expenses:Y,isLoading:r,selectedFilter:p??"all",onCategorize:d,onBatchCategorize:l,onSyncExpenses:m,isSyncing:o&&s.length===0,isCategorySyncing:c,initialExpandedExpenseId:u})]})]})};function $t({errors:s}){const{t}=B(),[n,a]=x.useState(!1),r=s.filter(o=>!o.locked);return r.length===0?null:e.jsxs(Ge,{open:n,onOpenChange:a,children:[e.jsx(qe,{asChild:!0,children:e.jsx(z,{variant:"neutralGhost",className:"h-auto w-full rounded-lg border border-red-200 bg-red-50 p-3 text-left hover:bg-red-100 [&>span]:w-full",children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Tt,{className:"h-4 w-4 flex-shrink-0 text-red-600"}),e.jsx("span",{className:"text-sm font-medium text-red-800",children:t("expenses.syncToEfatura.modal.result.errorsTitle",{count:r.length})})]}),e.jsx(As,{className:`h-4 w-4 text-red-600 transition-transform ${n?"rotate-180":""}`})]})})}),e.jsx(Qe,{children:e.jsx("div",{className:"mt-2 max-h-40 overflow-y-auto rounded-lg border border-red-100 bg-red-50/50",children:e.jsx("ul",{className:"divide-y divide-red-100",children:r.map((o,c)=>e.jsxs("li",{className:"px-3 py-2",children:[e.jsx("p",{className:"truncate text-xs font-medium text-red-800",children:o.expenseTitle?ge(o.expenseTitle):"-"}),e.jsx("p",{className:"text-xs font-medium text-red-700",children:o.invoiceNumber||o.idDocumento}),e.jsx("p",{className:"mt-0.5 text-xs text-red-600",children:o.error})]},o.idDocumento||c))})})})]})}function br({isOpen:s,onOpenChange:t,result:n}){const{t:a}=B(),r=(n.lockedCount||0)>0,o=(n.failedCount||0)>0,c=n.errors&&n.errors.length>0;return e.jsx(Me,{open:s,onOpenChange:t,children:e.jsxs(Be,{className:"max-w-md",children:[e.jsxs(Ie,{children:[e.jsxs(Re,{className:"flex items-center gap-2",children:[e.jsx(It,{className:"h-5 w-5 text-red-500"}),a("expenses.autoSyncErrorModal.title")]}),e.jsx(Ye,{children:a("expenses.autoSyncErrorModal.description")})]}),e.jsxs("div",{className:"flex flex-col gap-4 pt-4",children:[e.jsx("div",{className:"rounded-lg border border-border bg-muted/50 p-4",children:e.jsxs("div",{className:"grid grid-cols-2 gap-4 text-center",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-semibold text-green-600",children:n.syncedCount||0}),e.jsx("p",{className:"text-sm text-muted-foreground",children:a("expenses.syncToEfatura.modal.result.synced")})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-semibold text-red-600",children:n.failedCount||0}),e.jsx("p",{className:"text-sm text-muted-foreground",children:a("expenses.syncToEfatura.modal.result.failed")})]})]})}),r&&e.jsxs("div",{className:"flex items-start gap-2 rounded-lg border border-amber-200 bg-amber-50 p-3",children:[e.jsx(Rt,{className:"mt-0.5 h-4 w-4 flex-shrink-0 text-amber-600"}),e.jsx("p",{className:"text-sm text-amber-800",children:a("expenses.syncToEfatura.modal.result.lockedInfo",{count:n.lockedCount||0})})]}),o&&c&&n.errors&&e.jsx($t,{errors:n.errors}),e.jsx("div",{className:"flex justify-end",children:e.jsx(z,{variant:"neutralSecondary",onClick:()=>t(!1),className:"w-full sm:w-auto",children:a("button.label.close")})})]})]})})}const yr=(s,t)=>s.expenseType===K.Personal?t("expenses.type.personal"):s.businessPercentage&&s.businessPercentage<100?`${t("expenses.type.partial")} (${s.businessPercentage}%)`:t("expenses.type.business");function vr({expenses:s,t}){const[n,a]=x.useState(!0);return s.length===0?null:e.jsxs(Ge,{open:n,onOpenChange:a,children:[e.jsx(qe,{asChild:!0,children:e.jsx(z,{variant:"neutralGhost",className:"h-auto w-full rounded-lg border border-border bg-muted/50 p-3 text-left hover:bg-muted [&>span]:w-full",children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(jn,{className:"h-4 w-4 flex-shrink-0 text-muted-foreground"}),e.jsx("span",{className:"text-sm font-medium",children:t("expenses.syncToEfatura.modal.expensesList")})]}),e.jsx(As,{className:`h-4 w-4 text-muted-foreground transition-transform ${n?"rotate-180":""}`})]})})}),e.jsx(Qe,{children:e.jsx("div",{className:"mt-2 max-h-48 overflow-hidden overflow-y-auto rounded-lg border border-border",children:e.jsx("ul",{className:"divide-y divide-border",children:s.map(r=>e.jsxs("li",{className:"flex items-center gap-3 px-3 py-2",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"truncate text-sm font-medium text-foreground",title:vs(r),children:vs(r)}),e.jsxs("p",{className:"truncate text-xs text-muted-foreground",children:[r.invoiceNumber||r.idD
38ocumento," · ",e.jsx("span",{className:"text-xs",children:yr(r,t)})]})]}),e.jsx("span",{className:"flex-shrink-0 whitespace-nowrap text-sm font-medium",children:E(r.total)})]},r.id))})})})]})}function jr({isOpen:s,onOpenChange:t,year:n,quarter:a,personalExpensesCount:r,expensesReadyToSync:o=[],onSuccess:c}){const{t:i}=B(),{status:d,result:l,progress:m,start:y,reset:p,isLoading:f}=na(c),g=d==="success"||d==="error",w=d==="idle";x.useEffect(()=>{s||p()},[s,p]);const h=async()=>{await y(n,a??void 0)},b=()=>{p(),t(!1)},D=()=>e.jsxs(e.Fragment,{children:[e.jsxs(Ie,{children:[e.jsx(Re,{children:i("expenses.syncToEfatura.modal.title")}),e.jsx(Ye,{children:i("expenses.syncToEfatura.modal.description",{count:r})})]}),e.jsxs("div",{className:"flex min-w-0 flex-col gap-4 overflow-hidden pt-4",children:[o.length>0&&e.jsx(vr,{expenses:o,t:i}),e.jsx("div",{className:"rounded-lg border border-border bg-muted/50 p-4",children:e.jsx("p",{className:"text-sm text-muted-foreground",children:i("expenses.syncToEfatura.modal.info")})}),e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:justify-end",children:[e.jsx(z,{variant:"neutralSecondary",onClick:b,className:"w-full sm:w-auto",children:i("button.label.cancel")}),e.jsx(z,{variant:"fizPrime",onClick:h,className:"w-full sm:w-auto",children:i("expenses.syncToEfatura.modal.startSync")})]})]})]}),I=()=>e.jsxs("div",{className:"flex flex-col items-center justify-center gap-4 py-8",children:[e.jsx(us,{size:48,color:"#FFC850"}),e.jsxs("div",{className:"text-center",children:[e.jsx("p",{className:"text-sm font-medium text-foreground",children:i(aa(m==null?void 0:m.phase))}),e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:i("expenses.syncToEfatura.modal.syncingDescription",{count:r})}),e.jsx("div",{className:"mx-auto mt-3 w-72 max-w-full",children:e.jsx(ms,{value:(m==null?void 0:m.percent)??Vt,className:"h-2.5"})}),e.jsxs("div",{className:"mt-2 space-y-0.5",children:[(m==null?void 0:m.current)!==void 0&&(m==null?void 0:m.total)!==void 0&&e.jsx("p",{className:"text-xs text-muted-foreground",children:i("expenses.syncToEfatura.modal.progress",{current:m.current,total:m.total})}),typeof(m==null?void 0:m.etaSec)=="number"&&m.etaSec>0&&e.jsx("p",{className:"text-xs text-muted-foreground",children:i("expenses.syncProgress.eta",{seconds:m.etaSec})})]})]})]}),_=()=>{const T=l==null?void 0:l.success,j=((l==null?void 0:l.lockedCount)||0)>0,C=((l==null?void 0:l.failedCount)||0)>0,P=(l==null?void 0:l.errors)&&l.errors.length>0;return e.jsxs(e.Fragment,{children:[e.jsx(Ie,{children:e.jsxs(Re,{className:"flex items-center gap-2",children:[T?e.jsx(vn,{className:"h-5 w-5 text-green-500"}):e.jsx(It,{className:"h-5 w-5 text-red-500"}),i(T?"expenses.syncToEfatura.modal.result.title":"expenses.syncToEfatura.modal.result.titleError")]})}),e.jsxs("div",{className:"flex flex-col gap-4 pt-4",children:[T?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"rounded-lg border border-border bg-muted/50 p-4",children:e.jsxs("div",{className:"grid grid-cols-3 gap-4 text-center",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-semibold text-green-600",children:(l==null?void 0:l.syncedCount)||0}),e.jsx("p",{className:"text-sm text-muted-foreground",children:i("expenses.syncToEfatura.modal.result.synced")})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-semibold text-yellow-600",children:(l==null?void 0:l.skippedCount)||0}),e.jsx("p",{className:"text-sm text-muted-foreground",children:i("expenses.syncToEfatura.modal.result.skipped")})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-semibold text-red-600",children:(l==null?void 0:l.failedCount)||0}),e.jsx("p",{className:"text-sm text-muted-foreground",children:i("expenses.syncToEfatura.modal.result.failed")})]})]})}),j&&e.jsxs("div",{className:"flex items-start gap-2 rounded-lg border border-amber-200 bg-amber-50 p-3",children:[e.jsx(Rt,{className:"mt-0.5 h-4 w-4 flex-shrink-0 text-amber-600"}),e.jsx("p",{className:"text-sm text-amber-800",children:i("expenses.syncToEfatura.modal.result.lockedInfo",{count:(l==null?void 0:l.lockedCount)||0})})]}),C&&P&&(l==null?void 0:l.errors)&&e.jsx($t,{errors:l.errors})]}):e.jsx("div",{className:"rounded-lg border border-destructive/50 bg-destructive/10 p-4",children:e.jsx("p",{className:"text-sm text-destructive",children:l!=null&&l.message?i(l.message):i("error.syncFailed")})}),e.jsx("div",{className:"flex justify-end",children:e.jsx(z,{variant:"neutralSecondary",onClick:b,className:"w-full sm:w-auto",children:i("button.label.close")})})]})]})},k=T=>{!T&&f||T||b()};return e.jsx(Me,{open:s,onOpenChange:k,children:e.jsxs(Be,{className:"max-w-md",hideXButton:f,onInteractOutside:T=>f&&T.preventDefault(),onEscapeKeyDown:T=>f&&T.preventDefault(),children:[w&&D(),f&&I(),g&&_()]})})}const Nr=({personalExpensesCount:s,expensesReadyToSync:t,year:n,quarter:a,onSyncToEfaturaSuccess:r,isCategorySyncing:o})=>{const{t:c}=B(),[i,d]=x.useState(!1),[l,m]=x.useState(!1),{hasAccess:y,blockIfUnresolved:p}=wt(St.ExpenseManagement);if(s===0)return null;const f=()=>{if(!p()){if(!y){m(!0);return}d(!0)}};return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"sticky bottom-0 z-10 mt-6 border-t border-border bg-background/95 backdrop-blur-sm",children:e.jsx("div",{className:"mx-auto w-full px-4 py-4 sm:px-6 sm:py-5",children:e.jsxs("div",{className:"flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"flex h-12 w-12 shrink-0 items-center justify-center rounded-xl bg-gradient-to-br from-amber-50 to-orange-50 ring-1 ring-amber-100",children:e.jsx(Nn,{size:24,className:"text-amber-600"})}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-baseline gap-2",children:[e.jsx("span",{className:"text-2xl font-bold text-foreground sm:text-3xl",children:s}),e.jsx("span",{className:"text-sm font-medium text-amber-600",children:c("expenses.footer.readyToSync")})]}),e.jsx("p",{className:"mt-0.5 text-xs text-muted-foreground sm:text-sm",children:c("expenses.footer.syncDescription")})]})]}),e.jsx(z,{variant:"fizPrime",size:"medium",onClick:f,className:"w-full shrink-0 sm:w-auto",disabled:o,loading:o,children:c("expenses.syncToEfatura.button.label")})]})})}),e.jsx(jr,{isOpen:i,onOpenChange:d,year:n,quarter:a,personalExpensesCount:s,expensesReadyToSync:t,onSuccess:r}),e.jsx(zt,{isOpen:l,onClose:()=>m(!1)})]})},Cr=s=>{const t=Bs.language==="pt"?Cn:wn;return Sn(s,"d MMM",{locale:t})},wr=({onSync:s,isSyncing:t,onOpenSettings:n,onUploadReceipt:a,lastSyncDate:r,isResyncMode:o=!1,hasExpensesMissingData:c=!1})=>{const{t:i}=B(),d=c&&!t,l=i(o?"expenses.resyncFromEfatura":"expenses.syncFromEfatura");return e.jsx("div",{className:"flex w-full max-w-full flex-col gap-3 sm:flex-row sm:items-center sm:justify-end",children:e.jsx("div",{className:"flex flex-col gap-1",children:e.jsxs("div",{className:"flex items-center gap-2",children:[d&&e.jsxs(js,{children:[e.jsx(Ns,{asChild:!0,children:e.jsx(z,{variant:"neutralGhost",size:"small",className:"!h-8 !w-8 !rounded-full !p-0 bg-amber-100 hover:bg-amber-200",children:e.jsx(cs,{size:16,className:"text-amber-600"})})}),e.jsx(Cs,{side:"bottom",className:"max-w-xs text-sm",children:i("expenses.syncHint")})]}),e.jsxs("div",{className:"relative",children:[r&&!t&&e.jsx("span",{className:"absolute -top-4 left-0 whitespace-nowrap text-xs text-gray-400",children:i("expenses.syncedToDate",{date:Cr(r)})}),e.jsx(z,{variant:"neutralSecondary",onClick:s,loading:t,leftSection:e.jsx(En,{size:18}),children:e.jsx("span",{className:"hidden xs:inline",children:t?i("expenses.syncing"):l})})]}),e.jsx(z,{variant:"neutralSecondary",onClick:a,leftSection:e.jsx(kn,{size:18}),children:e.jsx("span",{className:"hidden xs:inline",children:i("expenses.receiptUpload.buttonTitle")})}),e.jsx(z,{variant:"neutralGhost",onClick:n,className:"!h-10 !w-10 !p-0",title:i("expenses.settings.title"),children:e.jsx(Tn,{size:18})})]})})})},Sr=({totalVatDeductible:s,categorizedCount:t,selectedYear:n,selectedQuarter:a})=>{const{t:r}=B();if(s===0)return null;const o=a!==null?{quarter:a,year:n}:void 0;return e.jsx("div",{className:"sticky bottom-0 z-10 mt-6 border-t border-gray-200 bg-white/95 backdrop-blur-sm",children:e.jsx("div",{className:"mx-auto w-full px-4 py-4 sm:px-6 sm:py-5",children:e.jsxs("div",{className:"flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"flex h-12 w-12 shrink-0 items-center justify-center rounded-xl bg-gradient-to-br from-emerald-50 to-teal-50 ring-1 ring-emerald-100",children:e.jsx(Dt,{size:24,className:"text-emerald-600"})}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-baseline gap-2",children:[e.jsx("span",{className:"text-2xl font-bold text-gray-900 sm:text-3xl",children:E(s)}),e.jsx("span",{className:"text-sm font-medium text-emerald-600",children:r("expenses.footer.vatDeductible")})]}),e.jsx("p",{className:"mt-0.5 text-xs text-gray-500 sm:text-sm",children:r("expenses.footer.fromExpenses",{count:t})})]})]}),e.jsx(In,{to:"/declarations/vat",state:o,className:"shrink-0",children:e.jsx(z,{variant:"fizPrime",size:"medium",className:"w-full sm:w-auto",children:r("expenses.footer.fillVatDeclaration")})})]})})})},Er=s=>{const t=Se(new Date(s+1,1,1)).endOf("month").startOf("day"),n=t.day();return n===6?t.add(2,"day"):n===0?t.add(1,"day"):t},kr="fiz_irs_deadline_banner_dismissed_",Tr=({taxYear:s})=>{const{t}=B(),[n,a]=x.useState(!0),[r,o]=x.useState(!1),c=s??new Date().getFullYear()-1,i=`${kr}${c}`,d=Er(c),l=d.toISOString(),m=d.format("DD/MM/YYYY");x.useEffect(()=>{const g=localStorage.getItem(i)==="true";a(g)},[i]);const y=x.useCallback(()=>{localStorage.setItem(i,"true"),a(!0)},[i]),p=x.useCallback(()=>{o(g=>!g)},[]);if(n||Rn(l))return null;const f=Dn(l);return e.jsxs("div",{className:"mb-3 rounded-lg border border-blue-200 bg-blue-50",children:[e.jsxs("button",{type:"button",onClick:p,className:"flex w-full items-center gap-2 px-3 py-2 text-left",children:[e.jsx(je,{size:18,className:"shrink-0 text-blue-600"}),e.jsx("span",{className:"flex-1 text-sm font-medium text-blue-800",children:t("expenses.irsDeadline.shortTitle",{days:f,date:m})}),e.jsx(xs,{size:16,className:`shrink-0 text-blue-500 transition-transform ${r?"rotate-180":""}`})]}),r&&e.jsxs("div",{className:"border-t border-blue-200 px-3 pb-3 pt-2",children:[e.jsx("p",{className:"text-sm text-blue-700",children:e.jsx(An,{i18nKey:"expenses.irsDeadline.description",values:{year:c,date:m},components:{strong:e.jsx("strong",{})}})}),e.jsxs("ul",{className:"mt-2 space-y-1 text-xs text-blue-600",children:[e.jsxs("li",{children:["⢠",t("expenses.irsDeadline.point1")]}),e.jsxs("li",{children:["⢠",t("expenses.irsDeadline.point2")]}),e.jsxs("li",{children:["⢠",t("expenses.irsDeadline.point3")]})]}),e.jsx("div",{className:"mt-3",children:e.jsx(z,{variant:"neutralSecondary",size:"medium",onClick:y,className:"w-full sm:w-auto",children:t("expenses.irsDeadline.dismiss")})})]})]})},Ir={},Rr=me` 39 mutation RecognizeExpenseReceipt($fileBase64: String!, $mimeType: String!) { 40 recognizeExpenseReceipt(fileBase64: $fileBase64, mimeType: $mimeType) { 41 sellerName 42 sellerNif 43 customerNif 44 date 45 total 46 number 47 atcud 48 type 49 vatBase6 50 vatValue6 51 vatBase13 52 vatValue13 53 vatBase23 54 vatValue23 55 vatRegion 56 otherTax 57 items { 58 name 59 quantity 60 price 61 vatRate 62 } 63 } 64 } 65`;function Dr(s){const t={...Ir,...s};return ds(Rr,t)}function Ar(s){return new Promise((t,n)=>{const a=new FileReader;a.onload=()=>{const r=a.result;t(r.split(",")[1])},a.onerror=n,a.readAsDataURL(s)})}const Kt=({message:s})=>e.jsxs("div",{className:"flex items-start gap-2 rounded-md border border-blue-200 bg-blue-50 px-3 py-2.5 text-xs text-blue-700 dark:border-blue-800 dark:bg-blue-950/40 dark:text-blue-300",children:[e.jsx(je,{className:"mt-0.5 h-3.5 w-3.5 shrink-0"}),e.jsx("span",{children:s})]}),Pr=(s,t="pt")=>{if(!s)return"";const n=new Date(s);if(isNaN(n.getTime()))return s;const a=t==="en"?"en-GB":"pt-PT";return n.toLocaleDateString(a,{day:"numeric",month:"long",year:"numeric"})},Or=(s,t,n)=>{const a=[s,t,n].filter(o=>o!=null).map(Number).filter(o=>!isNaN(o));if(a.length===0)return null;const r=a.reduce((o,c)=>o+c,0);return Math.round(r*100)/100},zr=({imageUrl:s,data:t,isProcessing:n,onScanAgain:a,onAddExpense:r,isAddingExpense:o})=>{var w;const{t:c,i18n:i}=B(),[d,{data:l,loading:m}]=Pn({fetchPolicy:"network-only"});x.useEffect(()=>{var h;(h=t==null?void 0:t.sellerNif)!=null&&h.startsWith("5")&&!t.sellerName&&d({variables:{taxpayerNumber:t.sellerNif}})},[t==null?void 0:t.sellerNif,t==null?void 0:t.sellerName,d]);const y=((w=l==null?void 0:l.businessDataByTaxInfo)==null?void 0:w.name)??(t==null?void 0:t.sellerName)??"",p=!!(t!=null&&t.sellerNif&&(t!=null&&t.number)&&(t!=null&&t.date)&&(t!=null&&t.total)),f=t?Or(t.vatValue6,t.vatValue13,t.vatValue23):null,g=x.useMemo(()=>
65{if(!t)return[];const h=[];return t.sellerNif||h.push(c("expenses.receiptUpload.sellerNif")),t.number||h.push(c("expenses.receiptUpload.invoiceNumber")),t.date||h.push(c("expenses.receiptUpload.date")),t.total||h.push(c("expenses.receiptUpload.total")),h},[t==null?void 0:t.sellerNif,t==null?void 0:t.number,t==null?void 0:t.date,t==null?void 0:t.total,c]);return e.jsxs("div",{className:"flex min-h-0 flex-col gap-4 sm:flex-row",children:[e.jsx("div",{className:"relative flex min-h-[240px] flex-1 items-center justify-center overflow-hidden rounded-xl bg-muted sm:min-h-[320px]",children:e.jsxs(On,{minScale:.5,maxScale:5,initialScale:1,centerOnInit:!0,wheel:{step:.15},panning:{velocityDisabled:!0},doubleClick:{mode:"reset"},children:[e.jsx(zn,{wrapperStyle:{width:"100%",height:"100%"},contentStyle:{width:"100%",height:"100%",display:"flex",alignItems:"center",justifyContent:"center"},children:e.jsx("img",{src:s,alt:"receipt",className:"max-h-full max-w-full select-none rounded object-contain",draggable:!1})}),e.jsx(ra,{})]})}),e.jsx("div",{className:"flex w-full flex-col gap-3 sm:w-[320px] sm:flex-shrink-0",children:n?e.jsx("div",{className:"flex flex-1 items-center justify-center py-12",children:e.jsx(us,{color:"#FFC850",size:32})}):t?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex flex-col gap-3",children:[e.jsx(Pe,{id:"receipt-date",label:c("expenses.receiptUpload.date"),value:Pr(t.date,i.language),disabled:!0}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Pe,{id:"receipt-seller",label:c("expenses.receiptUpload.seller"),value:m?"...":y,disabled:!0,className:"min-w-0 flex-1"}),e.jsx(Pe,{id:"receipt-seller-nif",label:c("expenses.receiptUpload.sellerNif"),value:t.sellerNif??"",disabled:!0,classNames:{input:"font-mono"},className:"w-[150px] flex-shrink-0"})]}),e.jsx(Pe,{id:"receipt-buyer-nif",label:c("expenses.receiptUpload.buyerNif"),value:t.customerNif??"",disabled:!0,classNames:{input:"font-mono"}}),e.jsx(Pe,{id:"receipt-total",label:c("expenses.receiptUpload.total"),value:t.total!=null?E(Number(t.total)):"",disabled:!0}),f!=null&&e.jsx(Pe,{id:"receipt-vat",label:c("expenses.receiptUpload.vatAmount"),value:E(f),disabled:!0})]}),g.length>0&&e.jsx("p",{className:"rounded-md bg-destructive/10 px-3 py-2 text-xs text-destructive",children:c("expenses.receiptUpload.missingFields",{fields:g.join(", ")})}),e.jsxs("div",{className:"mt-auto flex gap-2 pt-2",children:[e.jsx(z,{variant:"neutralGhost",size:"medium",onClick:a,className:"flex-1",children:c("expenses.receiptUpload.scanAgain")}),e.jsx(z,{variant:"fizPrime",size:"medium",onClick:r,loading:o,disabled:!p,className:"flex-1",children:c("expenses.receiptUpload.addExpense")})]})]}):e.jsxs(e.Fragment,{children:[e.jsx(Kt,{message:c("expenses.receiptUpload.notRecognized")}),e.jsx("div",{className:"mt-auto pt-2",children:e.jsx(z,{variant:"neutralSecondary",size:"medium",onClick:a,className:"w-full",children:c("expenses.receiptUpload.scanAgain")})})]})})]})},Fr=({success:s,message:t,title:n,onUploadAnother:a,onClose:r})=>{const{t:o}=B(),c=n??o(s?"expenses.receiptUpload.successTitle":"expenses.receiptUpload.errorTitle");return e.jsxs("div",{className:"flex flex-col items-center gap-6 py-8 text-center",children:[e.jsx("div",{className:s?"rounded-full bg-green-100 p-4 dark:bg-green-900/30":"rounded-full bg-destructive/10 p-4",children:s?e.jsx(Fn,{className:"h-10 w-10 text-green-600 dark:text-green-400"}):e.jsx(Mn,{className:"h-10 w-10 text-destructive"})}),e.jsxs("div",{className:"max-w-sm",children:[e.jsx("p",{className:"text-base font-semibold text-foreground",children:c}),e.jsx("p",{className:"mt-1.5 text-sm text-muted-foreground",children:t})]}),e.jsxs("div",{className:"flex w-full max-w-xs flex-col gap-2",children:[e.jsx(z,{variant:"neutralSecondary",size:"medium",className:"w-full",onClick:a,children:o("expenses.receiptUpload.uploadAnother")}),e.jsx(z,{variant:s?"fizPrime":"neutralGhost",size:"medium",className:"w-full",onClick:r,children:o("expenses.receiptUpload.close")})]})]})},Mr="registado anteriormente",Br=({open:s,onClose:t,onExpenseAdded:n})=>{const{t:a}=B(),[r,o]=x.useState(!1),[c,i]=x.useState(null),[d,l]=x.useState(null),[m,y]=x.useState(null),[p,f]=x.use
65State(null),[g,w]=x.useState(!1),[h,b]=x.useState(null),D=x.useRef(!1),[I]=Dr(),[_,{loading:k}]=la(),T=async R=>{const M=R[0];if(!M)return;m&&URL.revokeObjectURL(m);const u=URL.createObjectURL(M);l(M),y(u),i(null),f(null),o(!0);try{const N=await Ar(M),{data:S}=await I({variables:{fileBase64:N,mimeType:M.type}});S!=null&&S.recognizeExpenseReceipt&&i(S.recognizeExpenseReceipt)}catch(N){console.error("[ReceiptRecognizer] Error:",N)}finally{o(!1)}},j=()=>{m&&URL.revokeObjectURL(m),y(null),l(null),i(null),f(null)},C=()=>{D.current||(D.current=!0,m&&URL.revokeObjectURL(m),y(null),l(null),i(null),f(null),g&&h!==null&&(n==null||n(h)),w(!1),b(null),t(),D.current=!1)},P=async()=>{var R;if(c){if(!c.sellerNif||!c.number||!c.date||!c.total){f({success:!1,message:a("expenses.receiptUpload.addError")});return}try{const{data:M}=await _({variables:{input:{sellerNif:c.sellerNif,invoiceType:c.type??"FR",invoiceNumber:c.number,date:c.date,total:c.total,atcud:c.atcud??void 0,vatBase6:c.vatBase6??void 0,vatValue6:c.vatValue6??void 0,vatBase13:c.vatBase13??void 0,vatValue13:c.vatValue13??void 0,vatBase23:c.vatBase23??void 0,vatValue23:c.vatValue23??void 0,vatRegion:c.vatRegion??void 0,otherTax:c.otherTax??void 0}}});if(M!=null&&M.registerReceiptOnEfatura.success){const u=parseInt(((R=c.date.match(/\d{4}/))==null?void 0:R[0])??String(new Date().getFullYear()),10);w(!0),b(u),f({success:!0,year:u,message:a("expenses.receiptUpload.successBody")})}else{const u=(M==null?void 0:M.registerReceiptOnEfatura.message)||(M==null?void 0:M.registerReceiptOnEfatura.error),N=u==null?void 0:u.toLowerCase().includes(Mr);f({success:!1,title:N?a("expenses.receiptUpload.duplicateTitle"):void 0,message:N?a("expenses.receiptUpload.duplicateBody"):u||a("expenses.receiptUpload.addError")})}}catch(M){console.error("[RegisterReceipt] Error:",M),f({success:!1,message:a("expenses.receiptUpload.addError")})}}},F=(c==null?void 0:c.sellerName)??a("expenses.receiptUpload.title");return e.jsx(Me,{open:s,onOpenChange:R=>!R&&C(),children:e.jsxs(Be,{className:"max-h-[85vh] sm:max-w-4xl",children:[e.jsx(Ie,{children:e.jsx(Re,{children:p?a("expenses.receiptUpload.title"):F})}),e.jsx("div",{className:"overflow-y-auto pr-1",children:p?e.jsx(Fr,{success:p.success,message:p.message,title:p.success?void 0:p.title,onUploadAnother:j,onClose:C}):d&&m?e.jsx(zr,{imageUrl:m,data:c,isProcessing:r,onScanAgain:j,onAddExpense:P,isAddingExpense:k}):e.jsxs("div",{className:"flex flex-col gap-3",children:[e.jsx(Kt,{message:a("expenses.receiptUpload.hint")}),e.jsx(ia,{onFilesDropped:T,isUploading:r,showEmailOption:!1})]})})]})})};function Vr({isOpen:s,onOpenChange:t,skippedCount:n}){const{t:a}=B(),r=()=>{is({source:"expense_skipped_atcud"}),t(!1)};return e.jsx(Me,{open:s,onOpenChange:t,children:e.jsxs(Be,{className:"max-w-md",children:[e.jsxs(Ie,{children:[e.jsxs(Re,{className:"flex items-center gap-2",children:[e.jsx(Tt,{className:"h-5 w-5 text-amber-500"}),a("expenses.skippedModal.title")]}),e.jsx(Ye,{children:a("expenses.skippedModal.description")})]}),e.jsxs("div",{className:"flex flex-col gap-4 pt-4",children:[e.jsx("div",{className:"rounded-lg border border-border bg-muted/50 p-3",children:e.jsx("p",{className:"text-sm text-muted-foreground",children:a("expenses.skippedModal.skippedInfo",{count:n})})}),e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:justify-end",children:[e.jsx(z,{variant:"neutralSecondary",onClick:()=>t(!1),className:"w-full sm:w-auto",children:a("button.label.close")}),e.jsx(z,{variant:"fizPrime",onClick:r,className:"w-full sm:w-auto",children:a("expenses.skippedModal.contactSupport")})]})]})]})})}function _r(s,t,n=!1){const a=p=>!n&&(t===null||t===p),r=ns({variables:{quarter:1,year:s},skip:!a(1),fetchPolicy:"cache-and-network"}),o=ns({variables:{quarter:2,year:s},skip:!a(2),fetchPolicy:"cache-and-network"}),c=ns({variables:{quarter:3,year:s},skip:!a(3),fetchPolicy:"cache-and-network"}),i=ns({variables:{quarter:4,year:s},skip:!a(4),fetchPolicy:"cache-and-network"}),d=[1,2,3,4].map((p,f)=>{var g,w;return((w=(g=[r,o,c,i][f].data)==null?void 0:g.getVatDeductionsFromExpenses)==null?void 0:w.totalDeductibleVat)??null}),l=r.loading||o.loading||c.loading||i.loading,m=d.join(","),y=!l&&[1,2,3,4].some(p=>a(p)&&d[p-1]==null);return x.useMemo(()=>{const p={};let f=0;return d.forEach((g,w)=>{if(g==null)return;const h=g/100;p[w+1]=h,f+=h}),{byQuarter:p,total:f,isLoading:l,unavailable:y}},[m,l,y])}const Lr={},Ur=me`
66 mutation BatchCategorizeExpenses($input: BatchCategorizeExpensesInput!) { 67 batchCategorizeExpenses(input: $input) { 68 success 69 categorizedCount 70 categorizedExpenses { 71 id 72 expenseType 73 businessCategory 74 personalCategory 75 businessPercentage 76 eventRole 77 isFixedAsset 78 vehicleExpenseType 79 isCategorized 80 categorizedAt 81 } 82 } 83 } 84`;function $r(s){const t={...Lr,...s};return ds(Ur,t)}const Kr={},Yr=me` 85 mutation CategorizeExpense($input: CategorizeExpenseInput!) { 86 categorizeExpense(input: $input) { 87 id 88 expenseType 89 businessCategory 90 personalCategory 91 businessPercentage 92 eventRole 93 isFixedAsset 94 vehicleExpenseType 95 isCategorized 96 categorizedAt 97 categorizedBy 98 catalogCategoryId 99 derivedCatalogCategoryId 100 vatDeduction { 101 deductibleVat 102 rate 103 ivaField 104 restrictionCode 105 } 106 } 107 } 108`;function Gr(s){const t={...Kr,...s};return ds(Yr,t)}const qr={},Qr=me` 109 query GetExpenses($quarter: Int, $year: Int!, $isCategorized: Boolean, $expenseType: ExpenseType) { 110 getExpenses(quarter: $quarter, year: $year, isCategorized: $isCategorized, expenseType: $expenseType) { 111 id 112 idDocumento 113 invoiceNumber 114 atcud 115 detailUrl 116 nifEmitente 117 nomeEmitente 118 actividadeEmitente 119 actividadeEmitenteDesc 120 tipoDocumento 121 documentType 122 emissionDate 123 total 124 iva 125 taxBase 126 status 127 setorAtividade 128 setorAtividadeDesc 129 quarter 130 year 131 expenseType 132 businessCategory 133 personalCategory 134 businessPercentage 135 eventRole 136 isFixedAsset 137 vehicleExpenseType 138 isCategorized 139 categorizedAt 140 categorizedBy 141 creditNoteParent { 142 expenseId 143 source 144 confirmedByUserId 145 confirmedAt 146 } 147 efaturaSyncedAt 148 isInFiz 149 catalogCategoryId 150 derivedCatalogCategoryId 151 vatDeduction { 152 deductibleVat 153 rate 154 ivaField 155 restrictionCode 156 } 157 apiData { 158 vatBreakdown { 159 taxCode 160 taxPercentage 161 taxAmount 162 netAmount 163 } 164 } 165 companyInfo { 166 nif 167 name 168 brandName 169 url 170 logoUrl 171 activity { 172 cae 173 description 174 } 175 location { 176 address 177 postal_code 178 city 179 google_maps_url 180 } 181 contact { 182 email 183 phone 184 website 185 } 186 founded_date 187 status 188 allowedPersonalCategories 189 suggestedBusinessCategory 190 } 191 } 192 } 193`;function Hr(s){const t={...qr,...s};return Ve(Qr,t)}const Wr=me` 194 query AutoSyncEfaturaTaskId { 195 autoSyncEfaturaTaskId 196 } 197`,Ct=2e3,Zr=2e3;function Jr(s){return typeof s=="object"&&s!==null&&"success"in s&&"failedCount"in s}const Xr=(s,t)=>{const n=Bn(),[a,r]=x.useState(!1),o=x.useRef(s),c=x.useRef(t);x.useEffect(()=>{o.current=s},[s]),x.useEffect(()=>{c.current=t},[t]);const i=x.useRef(null),d=x.useRef(new Set),l=x.useRef(null),m=x.useRef(null),y=x.useRef(!0),p=x.useRef(!1),f=x.useRef(()=>{});x.useEffect(()=>(y.current=!0,()=>{y.current=!1,l.current&&clearInterval(l.current),m.current&&clearInterval(m.current)}),[]);const g=x.useCallback(()=>{l.current&&(clearInterval(l.current),l.current=null)},[]),w=x.useCallback(()=>{m.current&&(clearInterval(m.current),m.current=null)},[]),h=x.useCallback(k=>{d.current.add(k),i.current=null,r(!1),w(),g(),p.current&&(p.current=!1,setTimeout(()=>{y.current&&!l.current&&!i.current&&(f.current(),l.current=setInterval(f.current,Ct))},0))},[w,g]),b=x.useCallback(async()=>{const k=i.current;if(k)try{const{data:T}=await n.query({query:Vn,variables:{taskId:k},fetchPolicy:"network-only"});if(!y.current)return;const j=T==null?void 0:T.backgroundTaskData;if(!j){h(k),o.current();return}if(j.status===hs.InProgress)return;j.status===hs.Completed&&(Jr(j.result)&&(j.result.failedCount>0||!j.result.success)?c.current(j.result):o.current(),h(k)),j.status===hs.Failed&&(c.current(void 0),h(k))}catch{if(!y.current)return;h(k),c.current(void 0)}},[n,h]),D=x.useCallback(()=>{w(),b(),m.current=setInterval(b,Zr)},[w,b]),I=x.useCallback(async()=>{try{const{data:k}=await n.query({query:Wr,fetchPolicy:"network-only"});if(!y.current)return;const T=k==null?void 0:k.autoSyncEfaturaTaskId;T&&T!==i.current&&!d.current.has(T)&&(i.current=T,r(!0),g(),D())}catch{}},[n,g,D]);x.useEffect(()=>{f.current=I},[I]);const _=x.useCallback(()=>
197{if(i.current){p.current=!0;return}l.current||(I(),l.current=setInterval(I,Ct))},[I]);return{isSyncing:a,startWatching:_}};function el(s,t){if(t==="all")return s;const n=new Map(s.map(r=>[r.id,r])),a=r=>{const o=r.creditNoteParent?n.get(r.creditNoteParent.expenseId):void 0;return o!=null&&o.isCategorized?o:void 0};switch(t){case"business":return s.filter(r=>{var o;return Te(r)?((o=a(r))==null?void 0:o.expenseType)===K.Business:r.expenseType===K.Business});case"personal":return s.filter(r=>{const o=c=>c.expenseType===K.Personal||c.expenseType===K.Business&&(c.businessPercentage??100)<100;if(Te(r)){const c=a(r);return!!c&&o(c)}return r.isCategorized&&r.expenseType!=null&&o(r)});case"uncategorized":return s.filter(r=>!r.isCategorized&&!Te(r));default:return s}}function sl(s,t){const n={year:s};return t!==null&&(n.quarter=t),n}function tl({expenseId:s,expenseType:t,category:n,catalogCategoryId:a,businessPercentage:r,eventRole:o,isFixedAsset:c,personalCategoryForPartial:i,vehicleExpenseType:d}){const l={expenseId:s,expenseType:t};return t===K.Business?(a?l.catalogCategoryId=a:l.businessCategory=n,l.businessPercentage=r??100,a?(o&&(l.eventRole=o),c!==void 0&&(l.isFixedAsset=c)):(_s.includes(n)&&o&&(l.eventRole=o),n===$.Equipment&&c!==void 0&&(l.isFixedAsset=c),n===$.Vehicle&&d&&(l.vehicleExpenseType=d)),r&&r<100&&i&&(l.personalCategory=i)):n&&(l.personalCategory=n),l}const nl=s=>({fromDate:new Date(Date.UTC(s,0,1,0,0,0,0)),toDate:new Date(Date.UTC(s,11,31,23,59,59,999))}),al=s=>{var He,We;const{t}=B(),n=Ee(),a=new Date().getFullYear(),r=(s==null?void 0:s.initialYear)??a,o=(s==null?void 0:s.initialQuarter)??null,c=o!==null?At(o,r):nl(r),[i,d]=x.useState(c),[l,m]=x.useState("all"),[y,p]=x.useState(o),f=i.fromDate?new Date(i.fromDate).getUTCFullYear():a,g=(s==null?void 0:s.autoSyncOnInitialLoad)??!1,w=s==null?void 0:s.onSyncComplete,h=`year-${f}`,b=x.useRef(new Set),D=x.useRef(!1),{data:I,loading:_,error:k,refetch:T}=Hr({variables:sl(f,y),fetchPolicy:"cache-and-network"}),{data:j,loading:C,refetch:P}=oa({variables:{year:f,quarter:y??void 0},fetchPolicy:"cache-and-network"}),{data:F,refetch:R}=ca({fetchPolicy:"cache-and-network"}),M=O=>{O.evict({id:"ROOT_QUERY",fieldName:"getVatDeductionsFromExpenses"}),O.evict({id:"ROOT_QUERY",fieldName:"getAnnualBusinessExpenses"}),O.gc()},[u]=Gr({update:M}),[N]=$r({update:M}),S=da(()=>{T(),P(),R(),w==null||w()},void 0,f),{isLoading:L,progress:V,result:A,status:Y,start:G,reset:q}=S,[H,se]=x.useState(null),re=x.useCallback(()=>se(null),[]),[he,te]=x.useState(null),be=x.useCallback(()=>te(null),[]),ue=x.useCallback(()=>{de.success(t("expenses.autoSyncSuccess")),T(),P()},[T,P,t]),xe=x.useCallback(O=>{O?se(O):de.error(t("expenses.autoSyncFailed"))},[t]),{isSyncing:pe,startWatching:Z}=Xr(ue,xe),ie=x.useRef(0);x.useEffect(()=>{const O=(V==null?void 0:V.percent)??0;O>=50&&ie.current<50&&(T(),P(),R()),ie.current=O},[V==null?void 0:V.percent,T,P,R]),x.useEffect(()=>{!g||L||C||b.current.has(h)||!(j!=null&&j.getExpenseStats)||(b.current.add(h),(j.getExpenseStats.totalCount??0)>0)||(D.current=!0,G(f))},[g,L,C,j,h,f,G]),x.useEffect(()=>{!_&&I&&R()},[_,I,f,R]);const J=x.useMemo(()=>(I==null?void 0:I.getExpenses)||[],[I==null?void 0:I.getExpenses]),le=x.useMemo(()=>el(J,l),[J,l]),W=J.some(O=>{var ae;return((ae=O.apiData)==null?void 0:ae.vatBreakdown)&&O.apiData.vatBreakdown.length>0}),Ne=J.length>0&&!W,Q=x.useMemo(()=>J.filter(O=>Te(O)||!O.isCategorized||O.categorizedBy==="auto"||O.efaturaSyncedAt?!1:O.expenseType===K.Personal?!!O.personalCategory:O.expenseType===K.Business?O.businessPercentage&&O.businessPercentage<100?!!O.personalCategory:!!O.businessCategory:!1),[J]),oe=j!=null&&j.getExpenseStats?{totalCount:j.getExpenseStats.totalCount,categorizedCount:j.getExpenseStats.categorizedCount,uncategorizedCount:j.getExpenseStats.uncategorizedCount,businessCount:j.getExpenseStats.businessCount,personalCount:j.getExpenseStats.personalCount,readyToSyncCount:j.getExpenseStats.readyToSyncCount,totalAmount:j.getExpenseStats.totalAmount,totalVat:j.getExpenseStats.totalVat,uncategorizedVat:j.getExpenseStats.uncategorizedVat,businessVatDeductible:j.getExpenseStats.businessVatDeductible}:null,ce=(He=F==null?void 0:F.getExpenseSettings)!=null&&He.lastSyncDate?new Date(F.getExpenseSettings.lastSyncDate):null,De=O=>{d({fromDate:O[0],toDate:O[1]})};x.useEffect(()=>{if(Y==="success"&&A){if(A.skippedCount&&A.skippedCount>0&&te(A.skippedCount),D.current){D.current=!1,q();return}const{newCount:O,updatedCount:ae}=A;O>0||ae>0?de.success(t("expenses.syncSuccessWithUpdates",{new:O,updated:ae})):de.info(t("expenses.syncNoNew")),q()}else if(Y==="error"){if(D.current){D.current=!1,q();return}de.error(_n(A==null?void 0:A.errorType,t,"expenses.syncError")),q()}},[q,A,Y,t]);const ps=x.useCallback(async()=>{D.current=!1,await G(f,y??void 0)},[G,f,y]),fs=x.useCallback(async O=>{try{const ae=tl(O);await u({variables:{input:ae}}),n||Z(),await Promise.all([T(),P()])}catch(ae){console.error("Error categorizing expense:",ae),de.error(t("expenses.categorizeError"))}},[u,Z,T,P,t,n]),fe=x.useCallback(async(O,ae,Ce,Ze,Ae,ye,Je,ve)=>{try{const ne={expenseIds:O,expenseType:ae};ae===K.Business?(ne.businessCategory=Ce,ne.businessPercentage=Ze??100,_s.includes(Ce)&&Ae&&(ne.eventRole=Ae),Ce===$.Equipment&&ye!==void 0&&(ne.isFixedAsset=ye),Ce===$.Vehicle&&ve&&(ne.vehicleExpenseType=ve),Ze&&Ze<100&&Je&&(ne.personalCategory=Je)):Ce&&(ne.personalCategory=Ce);const{data:we}=await N({variables:{input:ne}});n||Z(),we!=null&&we.batchCategorizeExpenses.success&&(de.success(t("expenses.batchCategorizeSuccess",{count:we.batchCategorizeExpenses.categorizedCount})),await Promise.all([T(),P()]))}catch(ne){console.error("Error batch categorizing expenses:",ne),de.error(t("expenses.categorizeError"))}},[N,Z,T,P,t,n]),X=g&&!L&&!C&&!b.current.has(h)&&(((We=j==null?void 0:j.getExpenseStats)==null?void 0:We.totalCount)??-1)===0;return{expenses:J,filteredExpenses:le,selectedRange:i,setSelectedRange:De,selectedFilter:l,setSelectedFilter:m,selectedQuarter:y,setSelectedQuarter:p,isLoading:_||C||X,isSyncing:L,isCategorySyncing:pe,syncProgress:V,error:k||null,syncExpenses:ps,categorizeExpense:fs,batchCategorizeExpenses:fe,stats:oe,lastSyncDate:ce,hasExpensesMissingData:Ne,expensesReadyToSync:Q,autoSyncResult:H,clearAutoSyncResult:re,syncSkippedCount:he,clearSyncSkippedCount:be}},rl=s=>{var ue,xe,pe,Z,ie,J,le;const t=Rs(Ds),n=Ee(),a=Bs.language,r=((ue=t==null?void 0:t.credentials)==null?void 0:ue.verified)??!1,o=Ln({reason:"expenses"}),[c,i]=x.useState(!1),[d,l]=x.useState(!1),{settings:m,updateSettings:y,isLoading:p}=Vs(),{expenses:f,filteredExpenses:g,selectedRange:w,setSelectedRange:h,selectedFilter:b,setSelectedFilter:D,selectedQuarter:I,setSelectedQuarter:_,isLoading:k,isSyncing:T,isCategorySyncing:j,syncProgress:C,error:P,syncExpenses:F,categorizeExpense:R,batchCategorizeExpenses:M,stats:u,lastSyncDate:N,hasExpensesMissingData:S,expensesReadyToSync:L,autoSyncResult:V,clearAutoSyncResult:A,syncSkippedCount:Y,clearSyncSkippedCount:G}=al({initialQuarter:s==null?void 0:s.initialQuarter,initialYear:s==null?void 0:s.initialYear,autoSyncOnInitialLoad:r,onSyncComplete:s==null?void 0:s.onSyncComplete}),q=x.useMemo(()=>
197{if(((u==null?void 0:u.totalCount)??0)===0)return!1;const W=w.fromDate?w.fromDate.getUTCFullYear():null;return W==null?!1:I===null?Un(W):$n(I,W)},[u==null?void 0:u.totalCount,w.fromDate,I]),H=(m==null?void 0:m.hasCompletedOnboarding)??!1,se={cae:((xe=t==null?void 0:t.cae)==null?void 0:xe[0])??void 0,caeName:((ie=(Z=(pe=t==null?void 0:t.caeData)==null?void 0:pe[0])==null?void 0:Z.label)==null?void 0:ie[a])??void 0,isVatExempt:((J=t==null?void 0:t.vatSettings)==null?void 0:J.selectedVATRegime)===os.ExemptionArticle_53||((le=t==null?void 0:t.vatSettings)==null?void 0:le.selectedVATRegime)===os.ExemptionArticle_9},re=x.useRef(!1);x.useEffect(()=>{if(t){if(!r){o.ensureConnected(()=>F());return}if(!(p||H)){if(n){if(re.current)return;re.current=!0,y({hasCompletedOnboarding:!0,operatingMode:Ke.IvaOnly}).catch(()=>{re.current=!1});return}l(!0)}}},[t,r,H,p,n,y,F]);const he=x.useCallback(()=>{if(!r){o.ensureConnected(()=>F());return}F()},[r,F,o]),te=x.useCallback(async W=>{await y(ua(W))},[y]);return{expenses:f,filteredExpenses:g,stats:u,tenantInfo:se,hasExpensesMissingData:S,expensesReadyToSync:L,isResyncMode:q,autoSyncResult:V,clearAutoSyncResult:A,syncSkippedCount:Y,clearSyncSkippedCount:G,selectedRange:w,setSelectedRange:h,selectedFilter:b,setSelectedFilter:D,selectedQuarter:I,setSelectedQuarter:_,isLoading:k,isSyncing:T,isCategorySyncing:j,syncProgress:C,error:P,lastSyncDate:N,atGate:o,modals:{isSettingsModalOpen:c,isOnboardingWizardOpen:d},modalActions:{openSettingsModal:()=>i(!0),closeSettingsModal:()=>i(!1),closeOnboardingWizard:()=>l(!1)},actions:{handleSync:he,handleOnboardingComplete:te},categorizeExpense:R,batchCategorizeExpenses:M}},ll={},il=me` 198 query GetAnnualBusinessExpenses($year: Int!) { 199 getAnnualBusinessExpenses(year: $year) { 200 year 201 totalCount 202 totalAmount 203 categoryBreakdown { 204 category 205 count 206 amount 207 } 208 } 209 } 210`;function ol(s){const t={...ll,...s};return Ve(il,t)}const cl={},dl=me` 211 query GetAnnualPersonalExpenses($year: Int!) { 212 getAnnualPersonalExpenses(year: $year) { 213 year 214 totalCount 215 totalAmount 216 categoryBreakdown { 217 category 218 count 219 amount 220 } 221 } 222 } 223`;function ul(s){const t={...cl,...s};return Ve(dl,t)}const xl={},ml=me` 224 query GetCIRSCoefficient { 225 getCIRSCoefficient { 226 coefficient 227 hasCIRS 228 cirsCode 229 isArt151 230 canCalculate 231 applies15PercentRule 232 activityType 233 hasArt151CAE 234 } 235 } 236`;function pl(s){const t={...xl,...s};return Ve(ml,t)}const fl={},gl=me` 237 query GetIRSAnnualData($fromDate: DateTime!, $toDate: DateTime!) { 238 invoicesStats(fromDate: $fromDate, toDate: $toDate, filterAllStatusesByDate: true) { 239 paid { 240 count 241 total 242 amountWithoutTax 243 withholdingTax 244 } 245 unpaid { 246 count 247 total 248 amountWithoutTax 249 withholdingTax 250 } 251 } 252 } 253`;function hl(s){const t={...fl,...s};return Ve(gl,t)}function bl(s){const t=new Date(s,0,1,0,0,0,0).toISOString(),n=new Date(s,11,31,23,59,59,999).toISOString();return{fromDate:t,toDate:n}}function yl(s={}){const{year:t=Mt(),skip:n=!1}=s,{fromDate:a,toDate:r}=x.useMemo(()=>bl(t),[t]),{data:o,loading:c,error:i,refetch:d}=hl({variables:{fromDate:a,toDate:r},skip:n}),{data:l,loading:m,error:y,refetch:p}=ol({variables:{year:t},skip:n}),{data:f,loading:g,error:w,refetch:h}=ul({variables:{year:t},skip:n}),{data:b,loading:D,error:I,refetch:_}=pl({skip:n});return{data:x.useMemo(()=>{if(!(o!=null&&o.invoicesStats))return null;const{paid:j,unpaid:C}=o.invoicesStats,P=(j==null?void 0:j.amountWithoutTax)??0,F=(C==null?void 0:C.amountWithoutTax)??0,R=P+F,M=(j==null?void 0:j.withholdingTax)??0,u=((j==null?void 0:j.count)??0)+((C==null?void 0:C.count)??0),N=l==null?void 0:l.getAnnualBusinessExpenses,S=(N==null?void 0:N.totalAmount)??0,L=(N==null?void 0:N.totalCount)??0,V=(N==null?void 0:N.categoryBreakdown)??[],A=f==null?void 0:f.getAnnualPersonalExpenses,Y=(A==null?void 0:A.totalAmount)??0,G=(A==null?void 0:A.totalCount)??0,q=(A==null?void 0:A.categoryBreakdown)??[],H=b!=null&&b.getCIRSCoefficient?{coefficient:b.getCIRSCoefficient.coefficient??null,hasCIRS:b.getCIRSCoefficient.hasCIRS,cirsCode:b.getC
253IRSCoefficient.cirsCode??null,isArt151:b.getCIRSCoefficient.isArt151,canCalculate:b.getCIRSCoefficient.canCalculate,applies15PercentRule:b.getCIRSCoefficient.applies15PercentRule,activityType:b.getCIRSCoefficient.activityType??null,hasArt151CAE:b.getCIRSCoefficient.hasArt151CAE}:null;return{year:t,grossIncome:R,withholdingTax:M,invoiceCount:u,isLoaded:!0,businessExpensesTotal:S,businessExpensesCount:L,businessExpensesByCategory:V,personalExpensesTotal:Y,personalExpensesCount:G,personalExpensesByCategory:q,cirsCoefficient:H}},[o,l,f,b,t]),isLoading:c||m||g||D,error:i??y??w??I??null,refetch:async()=>{await Promise.all([d(),p(),h(),_()])}}}function vl(){const s=Rs(Ds),n=Pt().state;return s!=null&&s.usesBookkeepingExpenses?e.jsx(Yn,{to:"/bookkeeping/documents",replace:!0,state:{fromLegacyExpenses:!0,...n!=null&&n.year?{expensesPeriod:{year:n.year,quarter:n.quarter??null}}:{},...n!=null&&n.expandDocumentNumber?{expensesDocumentSearch:n.expandDocumentNumber}:{}}}):e.jsx(jl,{})}function jl(){const{t:s}=B(),n=Pt().state;Se.locale(Bs.language);const a=new Date().getFullYear(),r=(n==null?void 0:n.year)??a,[o,c]=x.useState(!1),i=Ee(),{settings:d}=Vs(),l=a,{data:m,isLoading:y,refetch:p}=yl({year:l,skip:i}),{atGate:f,expenses:g,filteredExpenses:w,stats:h,tenantInfo:b,hasExpensesMissingData:D,expensesReadyToSync:I,autoSyncResult:_,clearAutoSyncResult:k,syncSkippedCount:T,clearSyncSkippedCount:j,isResyncMode:C,selectedRange:P,setSelectedRange:F,selectedFilter:R,setSelectedFilter:M,selectedQuarter:u,setSelectedQuarter:N,isLoading:S,isSyncing:L,isCategorySyncing:V,syncProgress:A,error:Y,lastSyncDate:G,modals:q,modalActions:H,actions:se,categorizeExpense:re,batchCategorizeExpenses:he}=rl({initialYear:r,initialQuarter:n==null?void 0:n.quarter,onSyncComplete:i?void 0:p}),te=P.fromDate?new Date(P.fromDate).getUTCFullYear():r,be=(Q,oe)=>{if(oe===null)F([new Date(Date.UTC(Q,0,1,0,0,0,0)),new Date(Date.UTC(Q,11,31,23,59,59,999))]),N(null);else{const{fromDate:ce,toDate:De}=At(oe,Q);F([ce,De]),N(oe)}},ue=async(...Q)=>{await re(...Q),i||await p()},xe=async(...Q)=>{await he(...Q),i||await p()},pe=()=>{C&&!window.confirm(s("expenses.resync.confirm"))||se.handleSync()},Z=b.isVatExempt||!i&&(d==null?void 0:d.operatingMode)===Ke.IrsOnly,{byQuarter:ie,total:J,isLoading:le,unavailable:W}=_r(te,u,Z),Ne=x.useMemo(()=>i?s("expenses.pageTitleCompany"):b.isVatExempt?s("expenses.pageTitle"):s("expenses.pageTitleWithVat"),[i,b.isVatExempt,s]);return xa({title:Ne,icon:e.jsx("div",{className:"rounded-full bg-[#FFC850]/10 p-1.5",children:e.jsx(Dt,{className:"h-5 w-5 text-[#FFC850]"})}),toolsSection:e.jsx(wr,{onSync:pe,isSyncing:L,onOpenSettings:H.openSettingsModal,onUploadReceipt:()=>c(!0),lastSyncDate:G,isResyncMode:C,hasExpensesMissingData:D})}),Y?e.jsx("div",{className:"flex h-64 flex-col items-center justify-center",children:e.jsx("p",{className:"text-red-600",children:s("expenses.error.loading")})}):e.jsxs(e.Fragment,{children:[!i&&e.jsx(Tr,{taxYear:l}),e.jsx(hr,{expenses:g,filteredExpenses:w,businessExpensesTotal:m==null?void 0:m.businessExpensesTotal,personalExpensesByCategory:m==null?void 0:m.personalExpensesByCategory,isLoading:S,isSyncing:L,isCategorySyncing:V,syncProgress:A,onCategorize:ue,onBatchCategorize:xe,onSyncExpenses:se.handleSync,stats:h,selectedFilter:R,deductibleVatTotal:J,deductibleVatUnavailable:W,deductibleByQuarter:ie,isDeductibleVatLoading:le,onFilterChange:M,grossIncome:m==null?void 0:m.grossIncome,withholdingTax:m==null?void 0:m.withholdingTax,cirsInfo:m==null?void 0:m.cirsCoefficient,isIRSDataLoading:y,taxYear:l,operatingMode:d==null?void 0:d.operatingMode,hideVatDeduction:Z,lastSyncDate:G,selectedYear:te,selectedQuarter:u,onPeriodChange:be,initialExpandedExpenseId:n==null?void 0:n.expandExpenseId}),!i&&((h==null?void 0:h.readyToSyncCount)??0)>0?e.jsx(Nr,{personalExpensesCount:(h==null?void 0:h.readyToSyncCount)??0,expensesReadyToSync:I,year:te,quarter:u,onSyncToEfaturaSuccess:se.handleSync,isCategorySyncing:V}):Z?null:e.jsx(Sr,{totalVatDeductible:J,categorizedCount:(h==null?void 0:h.businessCount)??0,selectedYear:te,selectedQuarter:u}),e.jsx(Gn,{...f.modalProps}),e.jsx(ma,{open:q.isSettingsModalOpen,onClose:H.closeSettingsModal}),e.jsx(Br,{open:o,onClose:()=>c(!1),onExpenseAdded:Q=>{Q!==te&&be(Q,null),se.handleSync()}}),!i&&e.jsx(pa,{open:q.isOnboardingWizardOpen,onClose:H.closeOnboardingWizard,onComplete:se.handleOnboardingComplete,tenantCae:b.cae,tenantCaeName:b.caeName,isVatExempt:b.isVatExempt}),!i&&_&&e.jsx(br,{isOpen:!0,onOpenChange:Q=>{Q||k()},result:_}),!i&&T!=null&&T>0&&e.jsx(Vr,{isOpen:!0,onOpenChange:Q=>{Q||j()},skippedCount:T})]})}vl.displayName="ExpenseManagementPage";const Al=Kn;export{vl as Component,Al as ErrorBoundary,jl as LegacyExpensesPage};
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.