1var cn=Object.defineProperty,rn=Object.defineProperties;var on=Object.getOwnPropertyDescriptors;var Ee=Object.getOwnPropertySymbols;var Fe=Object.prototype.hasOwnProperty,Ie=Object.prototype.propertyIsEnumerable;var Pe=(s,t,i)=>t in s?cn(s,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):s[t]=i,Ve=(s,t)=>{for(var i in t||(t={}))Fe.call(t,i)&&Pe(s,i,t[i]);if(Ee)for(var i of Ee(t))Ie.call(t,i)&&Pe(s,i,t[i]);return s},$e=(s,t)=>rn(s,on(t));var De=(s,t)=>{var i={};for(var c in s)Fe.call(s,c)&&t.indexOf(c)<0&&(i[c]=s[c]);if(s!=null&&Ee)for(var c of Ee(s))t.indexOf(c)<0&&Ie.call(s,c)&&(i[c]=s[c]);return i};var I=(s,t,i)=>new Promise((c,a)=>{var n=u=>{try{d(i.next(u))}catch(g){a(g)}},o=u=>{try{d(i.throw(u))}catch(g){a(g)}},d=u=>u.done?c(u.value):Promise.resolve(u.value).then(n,o);d((i=i.apply(s,t)).next())});import{r as f,j as e}from"./react-vendor-BEafpyAm.js";import{s as oe,u as Be,b as Le,E as Ue,F as Ye,G as Re,J as Je,K as Ge,j as D,I as fe,S as U,k as Y,l as R,m as J,n as w,aG as ze,aH as qe,aI as dn,t as Te,B as G,M as Qe,C as We,e as un,f as xn,i as Xe,T as mn,v as hn,w as fn,x as gn}from"./index-UpiwJGUq.js";import{a as Ze,b as jn,u as pn,c as bn,d as en}from"./useBudget-Bwi7Q4ID.js";import{T as yn,a as _n,b as te,c as Se,d as vn,e as b}from"./table-BQSg_nPU.js";import{A as Nn,a as Cn,b as Sn,c as wn,d as An,e as En,f as Dn,g as Mn}from"./alert-dialog-hzuhfFuN.js";import{u as ge,b as je}from"./react-query-vendor-BhLAuXR4.js";import{u as Tn,C as Bn}from"./CurrencyDisplay-qcC-h_j9.js";import{a as kn,d as Ln,i as Pn,e as Fn,g as In,h as Vn,u as $n}from"./useFinancialLookups-C7_U9gOF.js";import{T as zn}from"./textarea-D6faDY44.js";import{e as qn}from"./useTransactionMutations-OdlhAi88.js";import{t as Kn}from"./financialLabels-_mJD5CjX.js";import{bU as Hn,bV as On,ai as Un,b8 as Yn,k as Rn,az as Jn}from"./icons-vendor-CNOaxIm9.js";import"./crypto-vendor-DdVgyv-Y.js";import"./recharts-vendor-C3BwgIm8.js";import"./supabase-vendor-DUUDoC-1.js";import"./date-fns-core-p4ULazqZ.js";import"./date-fns-locales-Csbs7Iu2.js";const Gn=["financial-budget-lines","financial-budget-period","financial-budget-actuals","financial-annual-projection","financial-planned-revenue-ramp"];function pe(s){Gn.forEach(t=>s.invalidateQueries({queryKey:[t]}))}function Qn(){const s=ge();return je({mutationFn:t=>I(null,null,function*(){const o=t,{id:i}=o,c=De(o,["id"]),{data:a,error:n}=yield oe.from("financial_budget_line").insert(c).select().single();if(n)throw n;return a}),onSuccess:()=>pe(s)})}function Wn(){const s=ge();return je({mutationFn:t=>I(null,null,function*(){if(!t.id)throw new Error("Budget line ID required");const o=t,{id:i}=o,c=De(o,["id"]),{data:a,error:n}=yield oe.from("financial_budget_line").update(c).eq("id",i).select().single();if(n)throw n;return a}),onSuccess:()=>pe(s)})}function Xn(){const s=ge();return je({mutationFn:t=>I(null,null,function*(){if(t.lineIds.length===0)return;const{error:i}=yield oe.from("financial_budget_line").update({vendor:t.vendor}).in("id",t.lineIds);if(i)throw i}),onSuccess:()=>pe(s)})}function Zn(){const s=ge();return je({mutationFn:t=>I(null,null,function*(){const{error:i}=yield oe.from("financial_budget_line").delete().eq("id",t);if(i)throw i}),onSuccess:()=>pe(s)})}function et(){const s=ge();return je({mutationFn:t=>I(null,null,function*(){if(t.monthlyPlanned.length!==12)throw new Error("monthlyPlanned must have 12 entries");const i=t.monthlyPlanned.map((n,o)=>{var d,u,g;return{period_id:t.period_id,category:t.category,cost_center_id:(d=t.cost_center_id)!=null?d:null,item_description:t.item_description,vendor:(u=t.vendor)!=null?u:null,month:o+1,planned:n,currency_code:t.currency_code,business_line:t.business_line,notes:(g=t.notes)!=null?g:null}}),{data:c,error:a}=yield oe.from("financial_budget_line").insert(i).select();if(a)throw a;return c}),onSuccess:()=>pe(s)})}function nt(){const s=ge();return je({mutationFn:t=>I(null,null,function*(){var u,g;let i=oe.from("financial_budget_line").select("*").eq("period_id",t.source_period_id);(u=t.only_categories)!=null&&u.length&&(i=i.in("category",t.only_categories));const{data:c,error:a}=yield i;if(a)throw a;if(!(c!=null&&c.length))throw new Error("Source period has no lines to clone");const n=c.map(N=>{const j=N,{id:E,created_at:B,updated_at:M}=j,h=De(j,["id","created_at","updated_at"]);return $e(Ve({},h),{period_id:t.target_period_id,planned:Number((Number(h.planned)*t.growth_factor).toFixed(2)),notes:h.notes?`${h.notes} (cloned from previous year Ã${t.growth_factor})`:`Cloned from previous year Ã${t.growth_factor}`})}),{data:o,error:d}=yield oe.from("financial_budget_line").insert(n).select("id");if(d)throw d;return{inserted:(g=o==null?void 0:o.length)!=null?g:0}}),onSuccess:()=>pe(s)})}function tt(s,t,i){var a;const c=Array.from({length:12},()=>0);for(const n of s)n.year===t&&(n.month<1||n.month>12||n.business_line&&(i!=="all"&&n.business_line!==i||(c[n.month-1]+=Number((a=n.mrr_cad)!=null?a:0))));return c}function st(s){return s.some(t=>t>0)}const nn=["CAD","BRL","USD"];function at(s){var i;const t=new Map;for(const c of s!=null?s:[]){if(c.to_ccy!=="CAD")continue;const a=(i=t.get(c.from_ccy))!=null?i:[];a.push({date:c.date,rate:Number(c.rate)}),t.set(c.from_ccy,a)}for(const c of t.values())c.sort((a,n)=>a.date.localeCompare(n.date));return t}function it(s,t){const i=new Date(Date.UTC(s,t,0)).getUTCDate();return`${s}
1-${String(t).padStart(2,"0")}-${String(i).padStart(2,"0")}`}function tn(s,t,i,c){if(t==="CAD")return 1;const a=s.get(t);if(!(a!=null&&a.length))return null;const n=it(i,c);let o=null;for(const d of a)if(d.date<=n)o=d.rate;else break;return o!=null?o:a[0].rate}function lt(s,t,i,c,a){const n=tn(a,t,i,c);return n===null?null:s*n}function ct(s,t,i,c,a){const n=tn(a,t,i,c);return n===null||n===0?null:s/n}const sn=["direct_expense","indirect_expense","other_expense","tax"];function Ke(s){return(s!=null?s:"").trim().toLowerCase()||null}function rt(s,t,i,c){var d,u;const a=new Map;for(const g of s){const N=Ke(g.vendor);if(!N)continue;const E=`${g.business_line}::${N}`;a.has(E)||a.set(E,g.key)}const n=new Map,o=Array(12).fill(0);for(const g of t!=null?t:[]){if(g.category!==i||c!=="all"&&g.business_line!==c)continue;const N=Ke(g.vendor),E=N?a.get(`${g.business_line}::${N}`):void 0,B=Number((d=g.actual_cad)!=null?d:0);if(E){const M=(u=n.get(E))!=null?u:Array(12).fill(0);M[g.month-1]+=B,n.set(E,M)}else o[g.month-1]+=B}return{byRow:n,unbudgeted:o}}const ot=["b2b","b2c","internal"],He=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function dt({open:s,onOpenChange:t,periodId:i,defaultCategory:c,aggregatedRow:a}){var re;const{t:n}=Be(),{toast:o}=Le(),{data:d}=kn(),{data:u}=Ln(),{data:g}=Pn(),{data:N}=Fn(),E=et(),B=Qn(),M=Wn(),h=Xn(),{data:j}=In(),{data:ae}=Vn(),k=!!a,V=(re=a==null?void 0:a.linesByMonth.find(l=>l!==null))!=null?re:null,$=c==="revenue",de=c==="people",ie=sn.includes(c),[be,le]=f.useState("flat"),[Q,ye]=f.useState(""),[ee,z]=f.useState(""),[L,ue]=f.useState("internal"),[q,K]=f.useState("CAD"),[W,xe]=f.useState(null),[T,P]=f.useState(null),[H,me]=f.useState(null),[O,se]=f.useState(null),[_e,ve]=f.useState(0),[F,we]=f.useState(Array(12).fill(0)),[Ne,Ae]=f.useState(0),[X,ce]=f.useState([]),[ne,r]=f.useState("");f.useEffect(()=>{var l,v,y,x;if(a&&V){ye(a.item_description),z((l=a.vendor)!=null?l:""),ue(a.business_line),K((v=V.currency_code)!=null?v:"CAD"),xe(V.cost_center_id),P(null),me(V.contract_id),se(V.employee_id),Ae(Number((y=V.planned)!=null?y:0));const S=a.plannedByMonth.map((C,Ce)=>C>0?Ce+1:null).filter(C=>C!==null);ce(S.length>0?S:[V.month]),r((x=V.notes)!=null?x:"")}else ye(""),z(""),ue($?"b2b":"internal"),K("CAD"),xe(null),P(null),me(null),se(null),ve(0),we(Array(12).fill(0)),ce([]),r(""),le("flat")},[a,V,s,$]);const m=_e>0?_e/12:0,p=F.reduce((l,v)=>l+v,0),A=l=>I(null,null,function*(){if(l.preventDefault(),!Q.trim()){o({title:n("financial.transaction.errorTitle"),description:n("financial.budgetEntry.errorDesc"),variant:"destructive"});return}const v=ie&&ee.trim()||null;try{if(k&&a){if(X.length===0){o({title:n("financial.transaction.errorTitle"),description:n("financial.budgetEntry.noMonthsSelected"),variant:"destructive"});return}const y=X.map(S=>I(null,null,function*(){const C=a.linesByMonth[S-1];return C?M.mutateAsync({id:C.id,period_id:C.period_id,category:C.category,cost_center_id:W,employee_id:de?O:C.employee_id,contract_id:$?H:C.contract_id,category_id:C.category_id,item_description:Q,vendor:v,month:S,planned:Ne,currency_code:q,business_line:L,notes:ne||null}):B.mutateAsync({period_id:i,category:c,cost_center_id:W,employee_id:de?O:null,contract_id:$?H:null,category_id:null,item_description:Q,vendor:v,month:S,planned:Ne,currency_code:q,business_line:L,notes:ne||null})}));yield Promise.all(y);const x=a.linesByMonth.filter(S=>{var C;return S!==null&&!X.includes(S.month)&&((C=S.vendor)!=null?C:null)!==v});ie&&x.length>0&&(yield h.mutateAsync({lineIds:x.map(S=>S.id),vendor:v}))}else{const y=be==="flat"?Array(12).fill(m):F,x={period_id:i,category:c,cost_center_id:W,item_description:Q,vendor:v,currency_code:q,business_line:L,monthlyPlanned:y,notes:ne||null};yield E.mutateAsync(x)}o({title:n("financial.budgetEntry.savedTitle")}),t(!1)}catch(y){o({title:n("financial.transaction.errorTitle"),description:y.message,variant:"destructive"})}}),_=E.isPending||M.isPending||h.isPending;return e.jsx(Ue,{open:s,onOpenChange:t,children:e.jsxs(Ye,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(Re,{children:[e.jsx(Je,{children:n(k?"financial.budgetEntry.editTitle":"financial.budgetEntry.newTitle")}),e.jsx(Ge,{children:n(k?"financial.budgetEntry.editDescription":"financial.budgetEntry.newDescription")})]}),e.jsxs("form",{onSubmit:A,className:"space-y-4 py-2",children:[e.jsxs("div",{children:[e.jsxs(D,{children:[n("financial.budget.item")," *"]}),e.jsx(fe,{value:Q,onChange:l=>ye(l.target.value),placeholder:n($?"financial.budgetEntry.placeholderRevenue":de?"financial.budgetEntry.placeholderPeople":"financial.budgetEntry.placeholderDefault"),maxLength:200,required:!0,onBlur:()=>{ie&&!ee.trim()&&Q.includes(" â ")&&z(Q.split(" â ")[0].trim())}})]}),ie&&e.jsxs("div",{children:[e.jsx(D,{children:n("financial.vend
1or.label")}),e.jsx(fe,{value:ee,onChange:l=>z(l.target.value),placeholder:n("financial.vendor.placeholder"),list:"budget-vendor-options",maxLength:120}),e.jsx("datalist",{id:"budget-vendor-options",children:(ae!=null?ae:[]).map(l=>e.jsx("option",{value:l},l))}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:n("financial.vendor.hint")})]}),$&&!k&&(()=>{const l=T?`client::${T}`:"",v=(u!=null?u:[]).filter(x=>x.source==="company"),y=(u!=null?u:[]).filter(x=>x.source==="financial_client");return e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(D,{children:n("financial.transaction.client")}),e.jsxs(U,{value:l||"__none__",onValueChange:x=>I(null,null,function*(){if(x==="__none__"){P(null);return}if(x.startsWith("company::")){const S=x.slice(9);try{const C=yield qn(S);P(C)}catch(C){P(null)}}else x.startsWith("client::")&&P(x.slice(8))}),children:[e.jsx(Y,{children:e.jsx(R,{placeholder:n("financial.transaction.none")})}),e.jsxs(J,{children:[e.jsx(w,{value:"__none__",children:n("financial.transaction.none")}),v.length>0&&e.jsxs(ze,{children:[e.jsx(qe,{children:n("financial.transaction.clientSection.companies")}),v.map(x=>e.jsx(w,{value:`company::${x.company_id}`,children:e.jsxs("span",{className:"flex items-center gap-1.5",children:[x.name,x.financial_client_id&&e.jsx(Hn,{className:"h-3 w-3 text-gray-400"})]})},`company::${x.company_id}`))]}),v.length>0&&y.length>0&&e.jsx(dn,{}),y.length>0&&e.jsxs(ze,{children:[e.jsx(qe,{children:n("financial.transaction.clientSection.b2cAggregates")}),y.map(x=>e.jsx(w,{value:`client::${x.financial_client_id}`,children:x.name},`client::${x.financial_client_id}`))]})]})]})]}),e.jsxs("div",{children:[e.jsx(D,{children:n("financial.budgetEntry.contract")}),e.jsxs(U,{value:H!=null?H:"__none__",onValueChange:x=>me(x==="__none__"?null:x),children:[e.jsx(Y,{children:e.jsx(R,{placeholder:n("financial.transaction.none")})}),e.jsxs(J,{children:[e.jsx(w,{value:"__none__",children:n("financial.transaction.none")}),(g!=null?g:[]).filter(x=>!T||x.client_id===T).map(x=>{var S;return e.jsx(w,{value:x.id,children:(S=x.description)!=null?S:x.id.slice(0,8)},x.id)})]})]})]})]})})(),de&&!k&&e.jsxs("div",{children:[e.jsx(D,{children:n("financial.transaction.employee")}),e.jsxs(U,{value:O!=null?O:"__none__",onValueChange:l=>se(l==="__none__"?null:l),children:[e.jsx(Y,{children:e.jsx(R,{placeholder:n("financial.transaction.none")})}),e.jsxs(J,{children:[e.jsx(w,{value:"__none__",children:n("financial.transaction.none")}),(N!=null?N:[]).filter(l=>l.active).map(l=>{var y;const v=l.contract_type==="founder"?"default":l.contract_type==="contractor"?"outline":"secondary";return e.jsx(w,{value:l.financial_employee_id,children:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsxs("span",{children:[l.full_name," â ",(y=l.role_financial)!=null?y:"â"]}),e.jsx(Te,{variant:v,className:"text-[10px] py-0 px-1.5",children:n(`financial.contractType.${l.contract_type}`)}),l.has_platform_access&&e.jsx(On,{className:"h-3.5 w-3.5 text-equilybrium-navy","aria-label":n("financial.transaction.hasPlatformAccess")})]})},l.financial_employee_id)})]})]}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:n("financial.budgetEntry.employeeHint")})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[e.jsxs("div",{children:[e.jsx(D,{children:n("financial.cashFlow.line")}),e.jsxs(U,{value:L,onValueChange:l=>ue(l),children:[e.jsx(Y,{children:e.jsx(R,{})}),e.jsx(J,{children:ot.map(l=>e.jsx(w,{value:l,children:l.toUpperCase()},l))})]})]}),e.jsxs("div",{children:[e.jsx(D,{children:n("financial.transaction.currency")}),e.jsxs(U,{value:q,onValueChange:K,children:[e.jsx(Y,{children:e.jsx(R,{})}),e.jsx(J,{children:(d!=null?d:[]).map(l=>e.jsx(w,{value:l.code,children:l.code},l.code))})]})]}),e.jsxs("div",{children:[e.jsx(D,{children:n("financial.settings.costCentersTitle")}),e.jsxs(U,{value:W!=null?W:"__none__",onValueChange:l=>xe(l==="__none__"?null:l),children:[e.jsx(Y,{children:e.jsx(R,{placeholder:n("financial.transaction.none")})}),e.jsxs(J,{children:[e.jsx(w,{value:"__none__",children:n("financial.transaction.none")}
1),(j!=null?j:[]).map(l=>e.jsxs(w,{value:l.id,children:[l.code," â ",Kn(n,l.code,l.name)]},l.id))]})]})]})]}),k&&a?e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx(D,{children:n("financial.budgetEntry.applyToMonths")}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(G,{type:"button",size:"sm",variant:"outline",onClick:()=>ce([1,2,3,4,5,6,7,8,9,10,11,12]),children:n("financial.budgetEntry.selectAll")}),e.jsx(G,{type:"button",size:"sm",variant:"outline",onClick:()=>ce([]),children:n("financial.budgetEntry.selectNone")})]})]}),e.jsx("div",{className:"grid grid-cols-6 sm:grid-cols-12 gap-1",children:He.map((l,v)=>{const y=v+1,x=X.includes(y),S=a.plannedByMonth[v];return e.jsxs(G,{type:"button",size:"sm",variant:x?"default":"outline",onClick:()=>{ce(C=>C.includes(y)?C.filter(Ce=>Ce!==y):[...C,y].sort((Ce,ln)=>Ce-ln))},className:"flex flex-col h-auto py-1 text-xs",children:[e.jsx("span",{children:l}),S>0&&e.jsx("span",{className:"text-[10px] opacity-70",children:new Intl.NumberFormat("en-CA",{notation:"compact",maximumFractionDigits:0}).format(S)})]},l)})}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:n("financial.budgetEntry.selectedCount",{count:String(X.length)})})]}),e.jsxs("div",{children:[e.jsx(D,{children:n("financial.budgetEntry.valueToApply")}),e.jsx(fe,{type:"number",step:"0.01",min:"0",value:Ne,onChange:l=>Ae(Number(l.target.value)),onFocus:l=>l.target.select(),required:!0}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:n("financial.budgetEntry.valueToApplyHint")})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:[e.jsx(D,{children:n("financial.budgetEntry.distributionMode")}),e.jsxs(U,{value:be,onValueChange:l=>le(l),children:[e.jsx(Y,{children:e.jsx(R,{})}),e.jsxs(J,{children:[e.jsx(w,{value:"flat",children:n("financial.budgetEntry.distFlat")}),e.jsx(w,{value:"custom",children:n("financial.budgetEntry.distCustom")})]})]})]}),be==="flat"?e.jsxs("div",{children:[e.jsxs(D,{children:[n("financial.budgetEntry.annualAmount")," *"]}),e.jsx(fe,{type:"number",step:"0.01",min:"0",value:_e,onChange:l=>ve(Number(l.target.value)),onFocus:l=>l.target.select(),required:!0}),e.jsxs("p",{className:"text-xs text-gray-500 mt-1",children:[n("financial.budgetEntry.flatHint"),": ",new Intl.NumberFormat("en-CA",{style:"currency",currency:q}).format(m)]})]}):e.jsxs("div",{children:[e.jsxs(D,{children:[n("financial.budgetEntry.monthlyAmounts")," *"]}),e.jsx("div",{className:"grid grid-cols-4 gap-2 mt-2",children:He.map((l,v)=>e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-0.5",children:l}),e.jsx(fe,{type:"number",step:"0.01",min:"0",value:F[v],onChange:y=>{const x=[...F];x[v]=Number(y.target.value),we(x)},onFocus:y=>y.target.select(),className:"text-sm"})]},l))}),e.jsxs("p",{className:"text-xs text-gray-500 mt-2",children:[n("financial.budgetEntry.totalAnnual"),": ",new Intl.NumberFormat("en-CA",{style:"currency",currency:q}).format(p)]})]})]}),e.jsxs("div",{children:[e.jsx(D,{children:n("financial.transaction.notes")}),e.jsx(zn,{value:ne,onChange:l=>r(l.target.value),rows:2,maxLength:500})]})]}),e.jsxs(Qe,{children:[e.jsx(G,{variant:"outline",onClick:()=>t(!1),disabled:_,children:n("common.cancel")}),e.jsx(G,{onClick:A,disabled:_,children:n(_?"common.saving":k?"common.save":"financial.transaction.create")})]})]})})}const ut=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],ke=s=>`${s.business_line}::${s.item_description}`;function xt(s){var i,c,a,n;if(!(s!=null&&s.length))return[];const t=new Map;for(const o of s){const d=ke(o);let u=t.get(d);u||(u={key:d,item_description:o.item_description,business_line:o.business_line,vendor:null,plannedByMonth:Array(12).fill(0),linesByMonth:Array(12).fill(null),totalPlanned:0},t.set(d,u)),u.vendor=(c=(i=u.vendor)!=null?i:o.vendor)!=null?c:null,u.plannedByMonth[o.month-1]+=Number((a=o.planned)!=null?a:0),u.linesByMonth[o.month-1]=o,u.totalPlanned+=Number((n=o.planned)!=null?n:0)}return Array.from(t.values()).sort((o,d)=>d.totalPlanned-o.totalPlanned)}const he=s=>s.reduce((t,i)=>t+i,0);function Z({value:s,currency:t,showSign:i=!1}){return e.jsx(Bn,{value:s,currency:t,compact:!0,showSign:i})}function mt({category:s,year:t,title:i,subtitle:c,displayCurrency:a="CAD"}){const{t:n}=Be(),{toast:o}=Le(),[d,u]=f.useState("all"),[g,N]=f.useState(!1),[E,B]=f.useState(null),[M,h]=f.useState(null),j=sn.includes(s),{data:ae}=Ze(t),{data:k,isLoading:V}=jn(t,s),{data:$,isLoading:de}=pn(t),{data:ie,isLoading:be}=bn(t),{data:le}=Tn(),{data:Q}=$n(),ye=Zn(),ee=f.useMemo(()=>at(Q),[Q]),z=f.useMemo(()=>(k!=null?k:[]).filter(r=>d==="all"||r.business_line===d),[k,d]),L=f.useMemo(()=>xt(z),[z]),ue=f.useMemo(()=>[...new Set([a,...z.map(m=>{var p;return(p=m.currency_code)!=null?p:"CAD"})])].filter(m=>{var p;return m!=="CAD"&&!((p=ee.get(m))!=null&&p.length)}),[a,z,ee]),q=f.useCallback((r,m,p)=>{const A=lt(r,m,t,p,ee),_=A===null?null:ct(A,a,t,p,ee);return _!=null?_:0}
1,[ee,t,a]),K=f.useCallback(r=>r.map((m,p)=>q(m,"CAD",p+1)),[q]),W=f.useMemo(()=>{var m,p,A;const r=new Map;for(const _ of z){const re=(m=r.get(ke(_)))!=null?m:Array(12).fill(0);re[_.month-1]+=q(Number((p=_.planned)!=null?p:0),(A=_.currency_code)!=null?A:"CAD",_.month),r.set(ke(_),re)}return r},[z,q]),xe=f.useMemo(()=>{const r=Array(12).fill(0);return($!=null?$:[]).filter(m=>m.category===s&&(d==="all"||m.business_line===d)).forEach(m=>{var p;r[m.month-1]+=Number((p=m.actual_cad)!=null?p:0)}),K(r)},[$,s,d,K]),T=f.useMemo(()=>{if(!j)return null;const{byRow:r,unbudgeted:m}=rt(L,ie,s,d),p=new Map;return r.forEach((A,_)=>p.set(_,K(A))),{byRow:p,unbudgeted:K(m)}},[j,L,ie,s,d,K]),P=f.useMemo(()=>K(tt(le!=null?le:[],t,d)),[le,t,d,K]),H=s==="revenue"&&L.length===0&&st(P),me=f.useMemo(()=>{if(H)return P;const r=Array(12).fill(0);return W.forEach(m=>m.forEach((p,A)=>r[A]+=p)),r},[W,H,P]),O=he(me),se=he(xe),_e=se-O,ve=O>0?se/O*100:0,F=V||de||j&&be,we=!!(T&&T.unbudgeted.some(r=>r>0)),Ne=()=>{B(null),N(!0)},Ae=r=>{B(r),N(!0)},X=L.find(r=>r.key===M),ce=()=>I(null,null,function*(){if(X)try{const r=X.linesByMonth.filter(m=>m!==null).map(m=>m.id);yield Promise.all(r.map(m=>ye.mutateAsync(m))),o({title:n("financial.budgetEntry.deletedTitle")})}catch(r){o({title:n("financial.transaction.errorTitle"),description:r.message,variant:"destructive"})}finally{h(null)}}),ne=(r,m,p)=>r.map((A,_)=>e.jsx(b,{className:`text-right font-mono text-xs ${p!=null&&p(A,_)?"text-amber-700":m}`,children:A>0?e.jsx(Z,{value:A,currency:a}):e.jsx("span",{className:"text-gray-300",children:"â"})},_));return e.jsxs(e.Fragment,{children:[e.jsxs(We,{children:[e.jsx(un,{children:e.jsxs("div",{className:"flex items-start justify-between flex-wrap gap-3",children:[e.jsxs("div",{children:[e.jsx(xn,{children:i}),c&&e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:c})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(U,{value:d,onValueChange:r=>u(r),children:[e.jsx(Y,{className:"w-40",children:e.jsx(R,{})}),e.jsxs(J,{children:[e.jsx(w,{value:"all",children:n("common.all")}),e.jsx(w,{value:"b2b",children:"B2B"}),e.jsx(w,{value:"b2c",children:"B2C"}),e.jsx(w,{value:"internal",children:"Internal"})]})]}),ae&&e.jsxs(G,{onClick:Ne,size:"sm",children:[e.jsx(Un,{className:"h-4 w-4 mr-1"}),n("financial.budgetEntry.newButton")]})]})]})}),e.jsxs(Xe,{children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3 mb-4",children:[e.jsx(Me,{label:n("financial.budget.totalPlanned"),value:O,currency:a}),e.jsx(Me,{label:n("financial.budget.totalActual"),value:se,currency:a}),e.jsx(Me,{label:n("financial.budget.variance"),value:_e,currency:a,showSign:!0}),e.jsx(Me,{label:n("financial.budget.utilization"),value:ve,currency:a,unit:"%",raw:ve})]}),e.jsx("p",{className:"text-xs text-gray-500 mb-2",children:n("financial.budget.actualHint")}),ue.length>0&&e.jsx("p",{className:"text-xs text-amber-700 mb-2",children:n("financial.budget.missingFx",{currencies:ue.join(", ")})}),e.jsx("div",{className:"overflow-x-auto border rounded-md mt-2",children:e.jsxs(yn,{children:[e.jsx(_n,{children:e.jsxs(te,{children:[e.jsx(Se,{className:"sticky left-0 bg-white z-10 min-w-[250px]",children:n("financial.budget.item")}),e.jsx(Se,{className:"whitespace-nowrap",children:n("financial.cashFlow.line")}),ut.map(r=>e.jsx(Se,{className:"text-right text-xs",children:r},r)),e.jsx(Se,{className:"text-right font-semibold",children:n("financial.budget.total")}),e.jsx(Se,{className:"text-right w-20",children:n("common.actions")})]})}),e.jsxs(vn,{children:[F&&e.jsx(te,{children:e.jsx(b,{colSpan:16,className:"text-center text-gray-400 py-8",children:n("common.loading")})}),!F&&L.length===0&&!H&&e.jsx(te,{children:e.jsx(b,{colSpan:16,className:"text-center text-gray-400 py-8",children:n("financial.budget.noLines")})}),!F&&H&&e.jsxs(te,{children:[e.jsx(b,{className:"sticky left-0 bg-white z-10 font-medium",children:e.jsxs("span",{className:"inline-flex items-center gap-2",children:[n("financial.budget.liveMrrItem"),e.jsx(Te,{variant:"outline",className:"text-[10px] uppercase tracking-wide",children:n("financial.indicators.liveBadge")})]})}),e.jsx(b,{children:e.jsx(Te,{variant:"outline",className:"text-xs",children:d==="all"?n("common.all"):d.toUpperCase()})}),ne(P,"text-gray-700"),e.jsx(b,{className:"text-right font-mono font-semibold",children:e.jsx(Z,{value:he(P),currency:a})}),e.jsx(b,{})]}),!F&&L.map(r=>{var A,_;const m=(A=W.get(r.key))!=null?A:Array(12).fill(0),p=(_=T==null?void 0:T.byRow.get(r.key))!=null?_:Array(12).fill(0);return e.jsxs(f.Fragment,{children:[e.jsxs(te,{children:[e.jsx(b,{className:"sticky left-0 bg-white z-10 font-medium truncate max-w-xs",title:r.item_description,children:r.item_description}),e.jsx(b,{children:e.jsx(Te,{variant:"outline",className:"text-xs",children:r.business_line.toUpperCase()})}),ne(m,"text-gray-700"),e.jsx(b,{className:"text-right font-mono font-semibold",children:e.jsx(Z,{value:he(m),currency:a})}),e.jsx(b,{children:e.jsxs("div",{className:"flex justify-end gap-1",children:[e.jsx(G,{size:"icon",variant:"ghost",onClick:()=>Ae(r),title:n("common.edit"),children:e.jsx(Yn,{className:"h-4 w-4"})}),e.jsx(G,{size:"icon",variant:"ghost",onClick:()=>h(r.key),title:n("common.delete"),children:e.jsx(Rn,{className:"h-4 w-4 text-red-600"})})]})})]}),T&&e.jsxs(te,{className:"bg-slate-50/60 border-b-2",children:[e.jsxs(b,{className:"sticky left-0 bg-slate-50 z-10 pl-8 text-xs text-gray-500",children:["â³ ",n("financial.budget.realizedRow")]}),e.jsx(b,{}),r.vendor?e.jsxs(e.Fragment,{children:[ne(p,"text-gray-500",(re,l)=>re>
1m[l]+.005),e.jsx(b,{className:"text-right font-mono text-xs font-semibold text-gray-600",children:e.jsx(Z,{value:he(p),currency:a})})]}):e.jsx(b,{colSpan:13,className:"text-xs text-gray-400 italic",children:n("financial.budget.noVendorHint")}),e.jsx(b,{})]})]},r.key)}),!F&&T&&we&&e.jsxs(te,{className:"bg-amber-50/50",children:[e.jsx(b,{className:"sticky left-0 bg-amber-50 z-10 text-sm text-gray-700",children:n("financial.budget.unbudgetedRow")}),e.jsx(b,{}),ne(T.unbudgeted,"text-gray-700"),e.jsx(b,{className:"text-right font-mono font-semibold",children:e.jsx(Z,{value:he(T.unbudgeted),currency:a})}),e.jsx(b,{})]}),!F&&(L.length>0||H)&&e.jsxs(te,{className:"bg-gray-50 border-t-2 border-gray-300",children:[e.jsx(b,{className:"sticky left-0 bg-gray-50 z-10 font-bold",children:n("financial.budget.plannedTotal")}),e.jsx(b,{}),me.map((r,m)=>e.jsx(b,{className:"text-right font-mono text-xs font-semibold",children:e.jsx(Z,{value:r,currency:a})},m)),e.jsx(b,{className:"text-right font-mono font-bold",children:e.jsx(Z,{value:O,currency:a})}),e.jsx(b,{})]}),!F&&e.jsxs(te,{className:"bg-blue-50",children:[e.jsx(b,{className:"sticky left-0 bg-blue-50 z-10 font-bold text-equilybrium-navy",children:n("financial.budget.actualTotal")}),e.jsx(b,{}),xe.map((r,m)=>e.jsx(b,{className:"text-right font-mono text-xs font-semibold",children:r>0?e.jsx(Z,{value:r,currency:a}):e.jsx("span",{className:"text-gray-300",children:"â"})},m)),e.jsx(b,{className:"text-right font-mono font-bold",children:e.jsx(Z,{value:se,currency:a})}),e.jsx(b,{})]})]})]})})]})]}),ae&&e.jsx(dt,{open:g,onOpenChange:N,periodId:ae.id,defaultCategory:s,aggregatedRow:E}),e.jsx(Nn,{open:!!M,onOpenChange:r=>!r&&h(null),children:e.jsxs(Cn,{children:[e.jsxs(Sn,{children:[e.jsx(wn,{children:n("financial.budgetEntry.deleteConfirmTitle")}),e.jsx(An,{children:X?`"${X.item_description}" â ${n("financial.budgetEntry.deleteConfirmDescription")}`:""})]}),e.jsxs(En,{children:[e.jsx(Dn,{children:n("common.cancel")}),e.jsx(Mn,{onClick:ce,className:"bg-red-600 hover:bg-red-700",children:n("common.delete")})]})]})})]})}function Me({label:s,value:t,currency:i,showSign:c=!1,unit:a,raw:n}){return e.jsxs("div",{className:"bg-gray-50 rounded-md p-3",children:[e.jsx("p",{className:"text-xs text-gray-500",children:s}),e.jsx("p",{className:"text-lg font-semibold",children:a==="%"&&n!==void 0?e.jsxs("span",{className:n>100?"text-amber-600":"text-gray-900",children:[n.toFixed(1),"%"]}):e.jsx(Z,{value:t,currency:i,showSign:c})})]})}function ht({open:s,onOpenChange:t,targetPeriodId:i,targetYear:c}){const{t:a}=Be(),{toast:n}=Le(),{data:o}=en(),d=nt(),[u,g]=f.useState(""),[N,E]=f.useState(0),B=(o!=null?o:[]).filter(j=>j.id!==i),M=1+N/100,h=()=>I(null,null,function*(){if(!u){n({title:a("financial.transaction.errorTitle"),description:a("financial.budgetClone.selectSourceError"),variant:"destructive"});return}try{const j=yield d.mutateAsync({source_period_id:u,target_period_id:i,growth_factor:M});n({title:a("financial.budgetClone.successTitle"),description:a("financial.budgetClone.successDescription",{count:String(j.inserted),year:String(c)})}),t(!1)}catch(j){n({title:a("financial.transaction.errorTitle"),description:j.message,variant:"destructive"})}});return e.jsx(Ue,{open:s,onOpenChange:t,children:e.jsxs(Ye,{children:[e.jsxs(Re,{children:[e.jsx(Je,{children:a("financial.budgetClone.title")}),e.jsx(Ge,{children:a("financial.budgetClone.description",{year:String(c)})})]}),e.jsxs("div",{className:"space-y-4 py-2",children:[e.jsxs("div",{children:[e.jsx(D,{children:a("financial.budgetClone.sourceYear")}),e.jsxs(U,{value:u,onValueChange:g,children:[e.jsx(Y,{children:e.jsx(R,{placeholder:a("financial.budgetClone.selectSource")})}),e.jsx(J,{children:B.map(j=>e.jsx(w,{value:j.id,children:j.fiscal_year},j.id))})]})]}),e.jsxs("div",{children:[e.jsx(D,{children:a("financial.budgetClone.growthPct")}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(fe,{type:"number",step:"1",value:N,onChange:j=>E(Number(j.target.value)),onFocus:j=>j.target.select(),className:"flex-1"}),e.jsx("span",{className:"text-gray-500",children:"%"})]}),e.jsxs("p",{className:"text-xs text-gray-500 mt-1",children:[a("financial.budgetClone.growthHint"),": ",e.jsxs("strong",{children:["à ",M.toFixed(2)]}),N===0&&` â ${a("financial.budgetClone.sameAsSource")}`]})]}),e.jsxs("div",{className:"bg-amber-50 border border-amber-200 rounded p-3 text-sm text-amber-900",children:[e.jsxs("strong",{children:["â ï¸ ",a("financial.budgetClone.warningTitle")]}),e.jsx("br",{}),a("financial.budgetClone.warningBody")]})]}),e.jsxs(Qe,{children:[e.jsx(G,{variant:"outline",onClick:()=>t(!1),disabled:d.isPending,children:a("common.cancel")}),e.jsx(G,{onClick:h,disabled:d.isPending||!u,children:d.isPending?a("common.saving"):a("financial.budgetClone.cta")})]})]})})}const Oe=[{key:"revenue",labelKey:"financial.budget.cat.revenue"},{key:"people",labelKey:"financial.budget.cat.people"},{key:"cogs",labelKey:"financial.budget.cat.cogs"},{key:"direct_expense",labelKey:"financial.budget.cat.directExpense"},{key:"indirect_expense",labelKey:"financial.budget.cat.indirectExpense"},{key:"other_expense",labelKey:"financial.budget.cat.otherExpense"},{key:"tax",labelKey:"financial.budget.cat.tax"},{key:"sales",labelKey:"financial.budget.cat.sales"},{key:"investment",labelKey:"financial.budget.cat.investment"}],an="financial-budget-display-currency";function ft(){try{const s=localStorage.getItem(an);return nn.includes(s)?s:"CAD"}catch(s){return"CAD"}}const Lt=()=>{var M;const{t:s}=Be(),t=new Date().getFullYear(),[i,c]=f.useState(t),{data:a}=Ze(i),{data:n}=en(),[o,d]=f.useState(!1),[u,g]=f.useState(ft),N=h=>{g(h);try{localStorage.setItem(an,h)}catch(j){}},E=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],B=Array.from(new Set([...(M=n==null?void 0:n.map(h=>h.fiscal_year))!=null?M:[],t,t+1])).sort((h,j)=>j-h);return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-start justify-between flex-wrap gap-3",children:[e.jsxs("div",{children:[e.jsxs("h2",{className:"text-2xl font-semibold text-gray-900",children:[s("financial.budget.title")," ",i]}),e.jsx("p",{className:"text-sm text-gray-500",children:s("financial.budget.subtitle")}),u!=="CAD"&&e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:s("financial.budget.fxHint")})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(U,{value:u,onValueChange:h=>N(h),children:[e.jsx(Y,{className:"w-24","aria-label":s("financial.budget.displayCurrency"),children:e.jsx(R,{})}),e.jsx(J,{children:nn.map(h=>e.jsx(w,{value:h,children:h},h))})]}),e.jsxs(U,{value:String(i),onValueChange:h=>c(Number(h)),children:[e.jsx(Y,{className:"w-28",children:e.jsx(R,{})}),e.jsx(J,{children:B.map(h=>e.jsx(w,{value:String(h),children:h},h))})]}),a&&e.jsxs(G,{variant:"outline",size:"sm",onClick:()=>d(!0),children:[e.jsx(Jn,{className:"h-4 w-4 mr-1"}),s("financial.budgetClone.ctaShort")]})]})]}),a&&e.jsx(We,{children:e.jsx(Xe,{className:"p-5",children:e.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 uppercase tracking-wide",children:s("financial.budget.fiscalYear")}),e.jsx("p",{className:"text-2xl font-bold text-equilybrium-navy",children:a.fiscal_year}),e.jsxs("p",{className:"text-xs text-gray-500 mt-1",children:[s("financial.budget.startsIn"),": ",E[a.fiscal_year_start_month-1]]})]}),e.jsxs("div",{className:"text-right",children:[e.jsx("p",{className:"text-xs text-gray-500 uppercase tracking-wide",children:s("financial.budget.currentMonth")}),e.jsx("p",{className:"text-2xl font-bold text-equilybrium-navy",children:E[a.current_month-1]}),e.jsx("p",{className:"text-xs text-gray-500 mt-1 max-w-xs",children:s("financial.budget.annualObjectiveExplanation")})]})]})})}),e.jsxs(mn,{defaultValue:"revenue",className:"w-full",children:[e.jsx(hn,{className:"flex flex-wrap h-auto gap-1",children:Oe.map(({key:h,labelKey:j})=>e.jsx(fn,{value:h,children:s(j)},h))}),Oe.map(({key:h,labelKey:j})=>e.jsx(gn,{value:h,className:"mt-4",children:e.jsx(mt,{category:h,year:i,title:s(j),displayCurrency:u})},h))]}),a&&e.jsx(ht,{open:o,onOpenChange:d,targetPeriodId:a.id,targetYear:a.fiscal_year})]})};export{Lt as default};
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.