1const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/networthPdf-D9umwphS.js","assets/jspdf.es.min-ChG6RETi.js","assets/index-CWYT4_6c.js","assets/index-BEIl6d2G.css","assets/pdfLogo-D5HuhD1B.js","assets/NetWorthTree-DVcruLZb.js","assets/physicalMetals--tXZLu6Z.js","assets/PortfolioOverview-C_d_23gh.js","assets/theme-HkljNWnE.js","assets/index-qzeeIilw.js","assets/portfolioPrivacy-CX4Ggg13.js","assets/portfolioDisplayCurrency-D0P4IlEP.js","assets/displayCurrency-iZSPZ8P3.js","assets/fx-MWNcQQY0.js","assets/ChartTooltip-CQygqmCl.js","assets/PieChart-Cm70Vikr.js","assets/PolarAngleAxis-DQBAsJYU.js","assets/useFxRates-k_aaKz5r.js","assets/portfolioFormat-PN9qVxqJ.js","assets/globe-Cw5GPRK8.js","assets/map-pin-CAjZ7eSc.js","assets/NetWorthKpiHeader-DD2t91gC.js","assets/AppSelect-Bw2HeWdu.js","assets/buildNetWorthTree-C31DuOYd.js","assets/dividends-BA0o0JjW.js","assets/resolveCompanyCash-BE2aO-ti.js","assets/eye-hoN8MSFy.js","assets/eye-off-DPINZrXi.js","assets/info-Bwjgz-ZU.js","assets/sachwertUpdate-qHIwwjBF.js","assets/assetTermFields-BD8Ottt5.js","assets/decimalInput-BOe5z3Er.js","assets/sachwertKinds-CWhNij-w.js","assets/pencil-DCpGWGzC.js","assets/proxy-ucXDfnEq.js","assets/chevron-right-DX8p9-t9.js","assets/chart-pie-CDdL2MV_.js","assets/chart-column-CGf9mkwR.js","assets/arrow-left-ue94SzTa.js"])))=>i.map(i=>d[i]); 2import{c as So,a as kr,j as e,an as Ot,cd as Po,r as g,C as Ye,cg as jr,l as To,bq as Nt,w as ue,ce as Lo,bU as Nr,ag as wr,cV as Cr,cM as Ao,bW as Qe,ak as Fe,aI as Eo,X as as,Y as is,Z as ls,_ as cs,$ as ds,aE as Sr,m as us,A as lt,dm as Io,I as ct,au as ms,bZ as rt,b$ as Pr,o as te,s as Ee,av as zt,aj as Do,ae as Jt,bS as Mo,ai as $o,ei as Fo,b4 as Tr,n as zo,T as Lr,U as Ar,cu as Ro,u as Oo,h as Bo,i as Vo,be as Wo,bX as Ho,ah as Uo,at as Ko,bY as Go,b3 as qo,dJ as Zo,am as Qo,S as Yo,bT as Xo,b7 as Jo,dK as en,dL as tn,aF as sn}from"./index-CWYT4_6c.js";import{b as rn}from"./returnTarget-DxQOYv72.js";import{u as on}from"./useWatchtowerData-DFUlmam0.js";import{u as nn}from"./useFamilyOverview-HRJppOIY.js";import{u as an}from"./useDeskScope-mXKYvPjQ.js";import{a as ln,F as zs}from"./familyStrings-DCM0e9Wx.js";import{F as cn}from"./FamilyViewSelect-BbAMy-hN.js";import{F as Rs}from"./FamilyScopeBanner-DCoTJBeU.js";import{u as Bt}from"./useFxRates-k_aaKz5r.js";import{A as fs,a as hs,b as ps,c as gs,d as xs,e as bs,g as vs,f as Er}from"./alert-dialog-BaaQJVLX.js";import{S as es}from"./SectionHeader-Cun7FMfF.js";import{P as dn}from"./PortfolioLoadError-D0Xd1v1I.js";import{C as un}from"./CaptureButton-NWUT-rpc.js";import{A as mn}from"./AskKasoButton-BRJ2XZgn.js";import{p as fn}from"./askKasoPrompts-BONrGHwf.js";import{b as hn,p as pn}from"./portfolioCapCopy-CfMNhoOt.js";import{g as Ir,a as gn,C as Dr,D as Mr,P as xn,T as $r,i as bn,c as vn,h as yn}from"./PortfolioOverview-C_d_23gh.js";import{t as qt,f as _n,l as kn,a as Fr,r as jn,L as ts,C as Nn,u as wn,b as Cn,h as Sn,c as Pn,N as Tn,d as Ln,e as An,g as En,i as In}from"./NetWorthTree-DVcruLZb.js";import{b as Os}from"./toggle-group-BB45j9QY.js";import{A as Dn}from"./AppSelect-Bw2HeWdu.js";import{u as et,a as Ve,m as De,P as Mn}from"./portfolioPrivacy-CX4Ggg13.js";import{L as $n}from"./label-DWwd-mkp.js";import{B as zr,E as Fn,G as zn,S as Rn,A as Rr,f as On,i as Bn,s as Vn,P as Bs,t as $t,a as Wn,b as Vs,d as Hn,c as Un,e as Kn,C as Ws}from"./CompassPortfolioSection-BtVQ3PQ1.js";import{u as Gn}from"./useTourAutostart-BC3jnMAr.js";import{p as qn,s as Zn,f as Qn}from"./fx-MWNcQQY0.js";import{m as Oe,f as Or,d as Yn,l as Br,g as ot,P as ft,h as Xn,e as Jn,i as Hs,j as ea,b as ta}from"./portfolioFormat-PN9qVxqJ.js";import{T as sa}from"./TickerName-CcR15P6a.js";import{g as Vr,k as Wr,M as ss,h as Hr,j as Ur,i as ra,s as oa,a as na,c as aa,b as ia,d as la}from"./physicalMetals--tXZLu6Z.js";import{u as Ct,d as ut,P as ca}from"./portfolioDisplayCurrency-D0P4IlEP.js";import{r as ys}from"./displayCurrency-iZSPZ8P3.js";import{F as rs}from"./folder-kanban-BXqeA5EQ.js";import{C as Kr}from"./chevron-right-DX8p9-t9.js";import{T as _s}from"./trash-2-Bc8YU14A.js";import{C as mt}from"./circle-alert-BYHqEK1o.js";import{T as da}from"./trending-up-DWZ3HONs.js";import{T as ua}from"./trending-down-DHsjY2ar.js";import{M as ma}from"./minus-DzpoKqa-.js";import{m as Gr}from"./moveAssetCore-DpGbA_z7.js";import{M as It,P as qr,a as fa}from"./createPortfolioCore-DSTZ0B2E.js";import{f as ha,a as Zr,b as pa,c as os,d as ga,e as xa,g as ba,u as Vt}from"./useFamilyPortfolioMutation-dGKyYFc0.js";import{f as Ue,c as va,w as ya,a as St,C as Qr,b as yt,d as Be,n as Us}from"./mergeSplitStrings-g9Hus-iz.js";import{I as wt}from"./info-Bwjgz-ZU.js";import{U as Yr}from"./user-DgZ4FBnt.js";import{U as Xr}from"./users-BgL4jqMW.js";import{D as _a,a as ka,b as ja,c as _t,d as Ks}from"./dropdown-menu-CB7_se4o.js";import{C as Na,a as Gs,b as wa}from"./collapsible-9QInpg1N.js";import{T as qs}
2from"./textarea-CVks09yQ.js";import{P as Jr}from"./pencil-DCpGWGzC.js";import{m as Zs,r as Qs,a as Ys,f as Xs,p as eo}from"./decimalInput-BOe5z3Er.js";import{u as Ca}from"./useOnLanguageChange-CNuuHnCV.js";import{A as Sa}from"./arrow-right-left-CWzpMEFT.js";import{f as Pa,p as Ta,C as La}from"./sachwertUpdate-qHIwwjBF.js";import{H as Aa}from"./HoldingChangeReviewDialog-DZ2k3tFr.js";import{r as to}from"./ticker-resolver-DWHRDLkJ.js";import{g as Ea}from"./holdingChangeTrades-CLZgC9jg.js";import"./checkbox-Cgo5wGcm.js";import{d as Ia}from"./tradeSyncErrors-DUrqGGqf.js";import{f as Da}from"./format-DNFVR_9-.js";import{g as Ma,h as $a,i as Fa}from"./overflowStash-iV-nEIJH.js";import{c as so,n as Le,N as za}from"./NetWorthKpiHeader-DD2t91gC.js";import{u as Ra,a as Oa}from"./useSavingsPlanAssetClass-zmpm6caN.js";import{d as Ba}from"./sankey-Bv_fuaL_.js";import{e as Va,s as Wa}from"./dividends-BA0o0JjW.js";import{S as Ha}from"./SankeyChart-Bmj785P_.js";import{E as Ua}from"./EmptyReason-BzklC_OV.js";import{v as Ka,b as Ga,n as qa}from"./buildNetWorthTree-C31DuOYd.js";import{I as Za}from"./companyDossierExport-CJVZirw1.js";import{resolvePdfLogo as Qa}from"./pdfLogo-D5HuhD1B.js";import{r as Js}from"./exportEvents-DEd7vQvp.js";import{F as Ya}from"./file-text-FDBzThN_.js";import{F as Xa}from"./file-spreadsheet-CCBbgmop.js";import{T as Ja}from"./target-CAoOoFIx.js";import{H as ei}from"./headphones-CCPOCME3.js";import{F as ti}from"./folder-plus-C5C4l10p.js";import"./useCriteriaMutations-pSz2ENV7.js";import"./watchtowerCriteria-CTIac6u1.js";import"./search-DFQgp5jJ.js";import"./circle-check-CNnVj947.js";import"./factory-DVdhrzC2.js";import"./newspaper-CVSKzwlQ.js";import"./flask-conical-CxvydqaL.js";import"./calendar-clock-BxnD8EO5.js";import"./wallet-ChtJFJHl.js";import"./bell-ring-DmRDnk61.js";import"./bookmark-CyqQ4lhw.js";import"./useMandateNames-BvO6IcDw.js";import"./familyScope--jGD7jjX.js";import"./TickerSearchInput-BL6AcY3s.js";import"./captureStrings-BE-eT8KD.js";import"./useTickerLogos-CEmNaO6o.js";import"./decisionSupersede-B1TzVJ87.js";import"./heldAsset-DxslBttr.js";import"./addDays-Bjltv7Hz.js";import"./en-US-BEuxq60D.js";import"./useResubmissions-DFCYLIDl.js";import"./send-BfswxLhi.js";import"./eye-hoN8MSFy.js";import"./plus-BYP8NQx_.js";import"./kasoChatBridge-CljxGbBd.js";import"./sachwertKinds-CWhNij-w.js";import"./theme-HkljNWnE.js";import"./index-qzeeIilw.js";import"./ChartTooltip-CQygqmCl.js";import"./PieChart-Cm70Vikr.js";import"./PolarAngleAxis-DQBAsJYU.js";import"./globe-Cw5GPRK8.js";import"./map-pin-CAjZ7eSc.js";import"./proxy-ucXDfnEq.js";import"./chart-pie-CDdL2MV_.js";import"./chart-column-CGf9mkwR.js";import"./arrow-left-ue94SzTa.js";import"./index-BSZ0RPJi.js";import"./MetalUnitInput-DLQAYphL.js";import"./briefingLanguage-CllJH1r3.js";import"./investorPersonaPresets-CRIUYATx.js";import"./investorType-CDx1yCiG.js";import"./rocket-CHphhDaz.js";import"./arrow-left-right-CaBw9TIJ.js";import"./shield-check-Bs4R1Cj4.js";import"./mic-DrcITmZA.js";import"./eye-off-DPINZrXi.js";import"./save-1v_wXPDI.js";import"./EmptyState-BqmE_E0R.js";import"./useDividendHistory-C2MPrp4N.js";import"./upload-CjvC8nE6.js";import"./chevron-left-rRQWlzBz.js";import"./BriefingSlotChip-Wwyg9MXc.js";import"./route-DZ3J9lDr.js";import"./gauge-2wWGBqmH.js";import"./chart-line-B9Y_H1ca.js";import"./useCashflowSettingsQuery-jfc3iOvc.js";import"./useProfileDialog-CC44Amfc.js";import"./brain-Dka-aQ55.js";import"./shield-TWXrCrno.js";import"./flame-BNDVGHte.js";import"./dedupeAssetRows-42YxNYvo.js";import"./assetTermFields-BD8Ottt5.js";import"./tradePortfolioSync-D40g-Cqc.js";import"./circle-DrKgUpNr.js";import"./index-djolVIUU.js";import"./CtaButton-DhQaY5eR.js";import"./resolveCompanyCash-BE2aO-ti.js";import"./sentenceSplit-DA4Ce6yf.js";/** 3 * @license lucide-react v0.462.0 - ISC 4 * 5 * This source code is licensed under the ISC license. 6 * See the LICENSE file in the root directory of this source tree. 7 */const er=So("CirclePlus",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M8 12h8",key:"1wcyev"}],["path",{d:"M12 8v8",key:"napkw2"}]]),si={de:{title:"Alle Briefing-Plätze belegt",body:"Neue Portfolios erhalten kein Briefing. Du k
7annst ein bestehendes Portfolio abwählen oder dein Paket erweitern.",continue:"Trotzdem anlegen",upgrade:"Paket erweitern"},en:{title:"All briefing slots in use",body:"New portfolios will not get a briefing. You can unsubscribe an existing portfolio or upgrade your plan.",continue:"Create anyway",upgrade:"Upgrade plan"}},ri=({open:t,onOpenChange:s,onContinue:r})=>{const{language:l}=kr(),o=si[l==="en"?"en":"de"];return e.jsx(fs,{open:t,onOpenChange:s,children:e.jsxs(hs,{children:[e.jsxs(ps,{children:[e.jsx(gs,{children:o.title}),e.jsx(xs,{children:o.body})]}),e.jsxs(bs,{className:"sm:justify-between",children:[e.jsx(Ot,{to:"/upgrade",className:Po({variant:"outline"}),children:o.upgrade}),e.jsx(vs,{onClick:r,children:o.continue})]})]})})},oi=new Set(["Other","Unknown"]),Dt=["hsl(var(--chart-1))","hsl(var(--chart-2))","hsl(var(--chart-3))","hsl(var(--chart-4))","hsl(var(--chart-5))"],ni=8,He="direct",_e="all",ai=t=>new Intl.NumberFormat("de-DE",{style:"currency",currency:"EUR",maximumFractionDigits:0}).format(t),ks=()=>{const t=et();return s=>Ve(ai(s),t)},js=t=>s=>Lo(s,t,{input:"percent",decimals:1,glyph:t==="de"?"spaced":"suffix"})??"",tr=(t,s)=>{const r=new Date(t);return Number.isNaN(r.getTime())?"":r.toLocaleDateString(s==="de"?"de-DE":"en-GB",{day:"2-digit",month:"2-digit",year:"numeric"})},ii=" ",sr=t=>t.replace(/ /g,ii),li=/,?\s+(Inc\.?|Corporation|Corp\.?|Co\.?,?\s*Ltd\.?|Ltd\.?|N\.V\.|plc|PLC|AG|S\.A\.|SE)$/i,ci=t=>t.replace(li,"").trim(),rr=({slices:t,max:s,lang:r})=>{const l=js(r),o=ks();return e.jsx("div",{className:"space-y-2",children:t.map(m=>{const n=Fr(m.name,r);return e.jsxs("div",{"data-lt-slice":m.name,className:"grid grid-cols-[minmax(0,10.5rem)_minmax(3rem,1fr)_3rem] sm:grid-cols-[minmax(0,10.5rem)_minmax(3rem,1fr)_3rem_4.5rem] items-center gap-3 text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",title:n,children:n}),e.jsx("div",{className:"h-2 rounded-sm bg-muted/40",children:e.jsx("div",{className:`h-2 rounded-sm ${oi.has(m.name)?"bg-muted-foreground/40":"bg-primary/80"}`,style:{width:`${s>0?Math.max(m.pct/s*100,1):0}%`}})}),e.jsx("span",{"data-lt-slice-pct":!0,className:"text-right tabular-nums text-foreground",children:l(m.pct)}),e.jsx("span",{className:"hidden sm:block text-right tabular-nums text-muted-foreground truncate",children:o(m.valueEur)})]},m.name)})})},di=({scope:t,onSelect:s,segments:r,totalValueEur:l,unassignedValueEur:o,allLabel:m,lang:n,t:h})=>{const p=js(n),c=ks(),a=b=>l>0?b/l*100:0;return e.jsxs("div",{className:"w-full space-y-3",role:"group","aria-label":h("Nach Fonds filtern","Filter by fund"),children:[e.jsxs("div",{"aria-hidden":"true",className:"flex h-3 w-full gap-0.5 overflow-hidden rounded-sm",children:[r.map((b,i)=>e.jsx("div",{"data-lt-strip":b.key,className:Nt("h-full transition-opacity",t!==_e&&t!==b.key&&"opacity-30"),style:{flexGrow:Math.max(b.valueEur,0),flexBasis:0,minWidth:b.valueEur>0?3:0,backgroundColor:Dt[i%Dt.length]}},b.key)),o>0&&e.jsx("div",{"data-lt-strip":"unassigned",className:Nt("h-full bg-muted transition-opacity",t!==_e&&"opacity-30"),style:{flexGrow:o,flexBasis:0}})]}),e.jsxs("div",{className:"flex flex-wrap items-stretch gap-2",children:[e.jsxs(Os,{variant:"outline","data-scope":_e,pressed:t===_e,onPressedChange:()=>s(_e),className:"h-auto min-h-11 flex-col items-start gap-0.5 px-3 py-1.5 data-[state=on]:border-primary data-[state=on]:bg-card",children:[e.jsx("span",{className:"text-xs font-semibold text-foreground",children:m}),e.jsx("span",{className:"text-[11px] font-normal text-muted-foreground tabular-nums",children:c(l)})]}),r.map((b,i)=>e.jsxs(Os,{variant:"outline","data-scope":b.key,title:b.title,pressed:t===b.key,onPressedCh
7ange:()=>s(b.key),className:"h-auto min-h-11 items-center gap-2 px-3 py-1.5 data-[state=on]:border-primary data-[state=on]:bg-card",children:[e.jsx("i",{"aria-hidden":"true",className:"h-2.5 w-2.5 shrink-0 rounded-sm",style:{backgroundColor:Dt[i%Dt.length]}}),e.jsxs("span",{className:"flex flex-col items-start gap-0.5",children:[e.jsx("span",{className:"text-xs font-semibold text-foreground",children:b.stem}),e.jsxs("span",{className:"text-[11px] font-normal text-muted-foreground tabular-nums",children:[p(a(b.valueEur))," · ",c(b.valueEur)]})]})]},b.key)),o>0&&e.jsxs("span",{className:"flex items-center gap-2 px-1 text-[11px] text-muted-foreground tabular-nums",children:[e.jsx("i",{"aria-hidden":"true",className:"h-2.5 w-2.5 shrink-0 rounded-sm bg-muted"}),h("Ohne Aufschlüsselung","Not broken down")," ",p(a(o))]})]})]})},ui=({result:t,loading:s,error:r,unresolvedFunds:l,fundCount:o,fundCandidateCount:m,positions:n,funds:h,direct:p,computeForTickers:c,t:a,headerAction:b})=>{var Re;const i=a("de","en")==="de"?"de":"en",x=js(i),N=ks(),S=j=>sr(x(j)),P=j=>x(jn(j)),v=j=>sr(P(j)),[y,E]=g.useState(_e),[Q,$]=g.useState(!1),[O,V]=g.useState(!1);g.useEffect(()=>{$(!1),V(!1)},[y]);const D=g.useMemo(()=>{var le;const j=new Map;for(const ge of n){const f=(le=ge.ticker)==null?void 0:le.trim();if(!f||!(ge.valueEur>0)||!h.get(f))continue;const H=j.get(f)??{key:f,ticker:f,stem:qt(f),title:ge.name||f,valueEur:0};H.valueEur+=ge.valueEur,j.set(f,H)}return[...j.values()].sort((ge,f)=>f.valueEur-ge.valueEur)},[n,h]),F=D.length>0,w=g.useMemo(()=>{const j=new Set(h.keys());for(const le of l)j.add(le.ticker);return j},[h,l]),M=g.useMemo(()=>c(null),[c]),I=(M==null?void 0:M.totalValueEur)??0,T=I>0,Y=g.useMemo(()=>w.size>0?c([...w]):null,[c,w]),ae=(Y==null?void 0:Y.totalValueEur)??0,J=g.useMemo(()=>y===_e?t:y===He?M:c([y]),[y,t,c,M]),W=J?y:_e,A=W===_e?t:J;g.useEffect(()=>{if(y!==_e){if(y===He){T||E(_e);return}D.some(j=>j.key===y)||E(_e)}},[y,D,T]);const z=g.useMemo(()=>Math.max(...((A==null?void 0:A.regions.filter(j=>j.pct>=.05))??[]).map(j=>j.pct),0),[A]),Z=g.useMemo(()=>O?(A==null?void 0:A.sectors)??[]:((A==null?void 0:A.sectors)??[]).slice(0,6),[A,O]),re=g.useMemo(()=>((A==null?void 0:A.sectors)??[]).slice(6),[A]),pe=g.useMemo(()=>Math.max(...((A==null?void 0:A.sectors)??[]).map(j=>j.pct),0),[A]);if(s&&!t)return m&&m>0?e.jsx(Ye,{className:"p-5",children:e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:a("Durchschau lädt â¦","Resolving look-through â¦")}),b&&e.jsx("div",{className:"shrink-0",children:b})]})}):null;if(r)return m&&m>0?e.jsxs(Ye,{className:"p-5 space-y-1",children:[e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsx("h3",{className:"font-serif italic font-normal text-lg",children:a("Durchschau","Look-through")}),b&&e.jsx("div",{className:"shrink-0",children:b})]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[a("Die Fondsdaten konnten nicht geladen werden.","Fund composition could not be loaded.")," ",r]})]}):null;if(!F||!t||t.totalValueEur<=0||!A)return null;const C=A.regions.filter(j=>j.pct>=.05),k=W===_e,q=A.names.slice(0,Q?30:10),se=A.names[0],be=((Re=q[0])==null?void 0:Re.pct)??1,ie=D.find(j=>j.key===W),R=t.totalValueEur>0?A.totalValueEur/t.totalValueEur*100:0,u=W===_e?D:W===He?[]:D.filter(j=>j.key===W),B=u.map(j=>{const le=h.get(j.key),ge=le?_n(le.holdings):0;return{key:j.key,stem:j.stem,pct:ge}}),oe=u.reduce((j,le)=>{var f;const ge=(f=h.get(le.key))==null?void 0:f.refreshedAt;return ge?j?new Date(ge).getTime()<new Date(j).getTime()?ge:j:ge:j},null),X=oe?a(`Stand der Zusammensetzung: ${tr(oe,"de")}`,`Composition as of ${tr(oe,"en")}`):null,ke=u.filter(j=>{var le;return((le=h.get(j.key))==null?void 0:le.stale)===!0}).map(j=>j.stem),ve=ke.length>0?a(`Zusammensetzung älter als 35 Tage oder ohne Datum: ${ke.join(", ")}`,`Composition older than 35 days or undated: ${ke.join(", ")}`):null,ze=T?a("Gesamtes Depot","Whole depot"):a("Alle Fonds","All funds"),Ke=W===_e?a(`${o} Fonds aufgelöst in die Unternehmen, Sektoren und Regionen dahinter.`,`${o} funds dissolved into the companies, sectors and regions behind them.`):W===He?a(`Direktpositionen: ${N(A.totalValueEur)}, ${x(R)} des Depots.`,`Direct positions: ${N(A.totalValueEur)}, ${x(R)} of the depot.`):a(`${(ie==null?void 0:ie.title)??W} (${ie?qt(ie.key):""}): ${N(A.totalValueEur)}, ${x(R)} des Depots.`,`${(ie==null?void 0:ie.title)??W} (${ie?qt(ie.key):""}): ${N(A.totalValueEur)}, ${x(R)} of the depot.`),Ce=W===_e?a("Depotwert","Depot value"):W===He?a("Wert der Direktpositionen","Direct positions value"):a("Fondswert","Fund value"),ye=h.size+l.length,We=t.totalValueEur>0?ae/t.totalValueEur*100:0,Xe=W===_e?a("Fonds aufgelöst","Funds dissolved"):a("Anteil am Depot","Share of the depot"),Se=W===_e?`${h.size} ${a("von","of")} ${ye}`:x(R),Ie=W===_e?a(`${x(We)} des Depots liegt in Fonds`,`${x(We)} of the depot sits in funds`):W===He?a("Direktpositionen","Direct positions"):(ie==null?void 0:ie.title)??"",Ne=W===_e?a("Anteil am gesamten Depot","Share of the whole depot"):W===He?a("Anteil an diesen Positionen","Share of these positions"):a("Anteil an diesem Fonds","Share of this fund"),me=k&&t.overlaps.length>0?a(` · ${t.overlaps.length} über mehrere Positionen gehalten`,` · ${t.overlaps.length} held through several positions`):"",tt="grid-cols-[1.5rem_minmax(0,1fr)_3.5rem_5.5rem]",Ge=k?"md:grid-cols-[1.5rem_minmax(0,1fr)_10rem_8rem_3.5rem_5.5rem]":"md:grid-cols-[1.5rem_minmax(0,1fr)_8rem_3.5rem_5.5rem]",Je=T?[...D,{key:He,ticker:null,stem:a("Direkt","Direct"),title:a("Direktpositionen","Direct positions"),valueEur:I}]:D,qe=1+Je.length<=ni,st=Math.max(0,t.totalValueEur-Je.reduce((j,le)=>j+le.valueEur,0)),ht=t.totalValueEur>0&&st/t.totalValueEur>=5e-4?st:0,nt=new Map;for(const j of n)j.ticker&&j.name&&nt.set(j.ticker,j.name);const at=new Set(l.map(j=>j.ticker)),Pe=t.unresolved.filter(j=>!(j.ticker&&at.has(j.ticker))),Me=t.totalValueEur>0?Pe.reduce((j,le)=>j+le.valueEur,0)/t.totalValueEur*100:0,$e=Pe.map(j=>{var le,ge;return((le=j.name)==null?void 0:le.trim())||((ge=j.ticker)==null?void 0:ge.trim())||""}
7).filter(Boolean).slice(0,3);return e.jsxs(Ye,{className:"p-5 space-y-5",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("h3",{className:"font-serif italic font-normal text-lg flex items-center gap-2",children:[e.jsx(jr,{className:"h-4 w-4 text-primary shrink-0"}),a("Durchschau: was wirklich drin liegt","Look-through: what you actually hold")]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:Ke}),(X||ve)&&e.jsxs("div",{className:"flex flex-wrap items-center gap-x-2 gap-y-1",children:[X&&e.jsx("p",{className:"text-xs text-muted-foreground tabular-nums",children:X}),ve&&e.jsx(To,{variant:"outline","data-lt-stale":!0,title:ve,children:a("Veraltet","Outdated")})]})]}),e.jsxs("div",{className:"shrink-0 flex flex-col items-end gap-2",children:[b,e.jsxs("div",{className:"flex flex-col items-end gap-0.5",children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-wide text-muted-foreground/80",children:Ce}),e.jsx("span",{"data-lt-value":!0,className:"text-lg font-semibold tabular-nums text-foreground",children:N(A.totalValueEur)})]})]})]}),qe&&e.jsx("div",{className:"hidden md:flex w-full",children:e.jsx(di,{scope:W,onSelect:E,segments:Je,totalValueEur:t.totalValueEur,unassignedValueEur:ht,allLabel:ze,lang:i,t:a})}),e.jsx(Dn,{label:a("Anzeigen","Show"),"aria-label":a("Nach Fonds filtern","Filter by fund"),value:W,onChange:E,className:Nt("max-w-sm",qe&&"md:hidden"),options:[{value:_e,label:`${ze} · ${N(t.totalValueEur)}`},...D.map(j=>({value:j.key,label:`${j.stem} · ${j.title} · ${x(t.totalValueEur>0?j.valueEur/t.totalValueEur*100:0)}`})),...T?[{value:He,label:`${a("Direktpositionen","Direct positions")} · ${x(t.totalValueEur>0?I/t.totalValueEur*100:0)}`}]:[]]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 divide-y divide-border md:divide-y-0 md:divide-x border-y border-border",children:[e.jsxs("div",{className:"py-3 md:py-3.5 md:px-5 md:first:pl-0 space-y-1",children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-wide text-muted-foreground/80",children:Xe}),e.jsx("p",{className:"text-xl font-semibold tabular-nums text-foreground",children:Se}),e.jsx("p",{className:"text-xs text-muted-foreground",children:Ie})]}),e.jsxs("div",{className:"py-3 md:py-3.5 md:px-5 space-y-1",children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-wide text-muted-foreground/80",children:a("Namentliche Abdeckung","Named coverage")}),e.jsx("p",{className:"text-xl font-semibold tabular-nums text-foreground",children:P(A.namedCoveragePct)}),e.jsx("p",{className:"text-xs text-muted-foreground",children:a("Ein Mindestwert: unser Datenanbieter liefert je Fonds nur die gröÃten Positionen.","A lower bound: our data provider only supplies each fund's largest positions.")})]}),e.jsxs("div",{className:"py-3 md:py-3.5 md:px-5 space-y-1",children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-wide text-muted-foreground/80",children:a("GröÃtes Einzelunternehmen","Largest single company")}),e.jsx("p",{"data-lt-kpi-top-company":!0,className:"text-xl font-semibold tabular-nums text-foreground line-clamp-2",children:se?`${ci(se.name)} ${x(se.pct)}`:"-"}),e.jsx("p",{className:"text-xs text-muted-foreground tabular-nums",children:se?a(`etwa ${N(se.valueEur)}`,`about ${N(se.valueEur)}`):""})]})]}),e.jsxs("div",{className:"grid gap-6 md:grid-cols-2",children:[e.jsxs("section",{children:[e.jsx("h4",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground mb-3",children:a("Regionen","Regions")}),e.jsx(rr,{slices:C,max:z,lang:i})]}),e.jsxs("section",{children:[e.jsx("h4",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground mb-3",children:a("Sektoren","Sectors")}),e.jsx(rr,{slices:Z,max:pe,lang:i}),re.length>0&&e.jsx(ue,{type:"button",variant:"ghost",size:"sm",className:"mt-2 h-auto px-2 py-1 text-xs font-semibold text-muted-foreground hover:text-foreground",onClick:()=>V(j=>!j),children:O?a("Weniger Sektoren zeigen","Show fewer sectors"):a(`${re.length} weitere Sektoren zeigen (${x(re.reduce((j,le)=>j+le.pct,0))})`,`Show ${re.length} more sectors (${x(re.reduce((j,le)=>j+le.pct,0))})`)})]})]}),e.jsxs("section",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-baseline justify-between gap-3",children:[e.jsx("h4",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:a("GröÃte Einzeltitel","Largest underlying companies")}),e.jsxs("span",{className:"text-xs text-muted-foreground text-right",children:[Ne,me]})]}),e.jsxs("div",{className:"flex flex-col",children:[e.jsxs("div",{className:Nt("grid items-center gap-3 py-1.5 border-b border-border text-[11px] font-semibold text-muted-foreground",tt,Ge),children:[e.jsx("span",{children:"#"}),e.jsx("span",{children:a("Unternehmen","Company")}),k&&e.jsx("span",{className:"hidden md:block",children:a("Ãber","Through")}),e.jsx("span",{className:"hidden md:block"}),e.jsx("span",{className:"text-right",children:a("Anteil","Share")}),e.jsx("span",{className:"text-right",children:a("Wert","Value")})]}),q.map((j,le)=>{const ge=kn(j,ts[i]).join(" · ");return e.jsxs("div",{className:Nt("grid items-center gap-3 py-2 border-b border-border/60 text-xs",tt,Ge),children:[e.jsx("span",{className:"text-muted-foreground tabular-nums",children:le+1}),e.jsx("span",{className:"truncate",children:j.name}),k&&e.jsx("span",{className:"hidden md:block truncate text-[11px] text-muted-foreground",title:ge,children:ge}),e.jsx("div",{className:"hidden md:block h-1 rounded-sm bg-muted/40",children:e.jsx("div",{className:"h-1 rounded-sm bg-primary/80",style:{width:`${be>0?Math.max(j.pct/be*100,1):0}%`}})}),e.jsx("span",{className:"text-right tabular-nums text-foreground",children:x(j.pct)}),e.jsx("span",{className:"text-right tabular-nums text-muted-foreground truncate",children:N(j.valueEur)})]},j.ticker)})]}),A.names.length>10&&e.jsx(ue,{type:"button",variant:"outline",size:"sm",className:"mt-1",onClick:()=>$(j=>!j),children:Q?a("Top 10 zeigen","Show top 10"):a(`Alle ${Math.min(30,A.names.length)} Unternehmen zeigen`,`Show all ${Math.min(30,A.names.length)} companies`)}
7)]}),e.jsx("p",{className:"text-xs text-muted-foreground border-t border-border pt-3",children:W===He?a("Quelle: die Direktpositionen dieses Depots, nicht die Zusammensetzung eines Fonds.","Source: this depot's own direct positions, not a fund's composition."):W===_e?a(`Quelle: die veröffentlichten Zusammensetzungen der Fonds${T?" sowie die direkt gehaltenen Positionen":""}. Namentlich genannte Unternehmen decken ${v(A.namedCoveragePct)} des Depots ab, ein Mindestwert: unser Datenanbieter liefert je Fonds nur die gröÃten Positionen.`,`Source: the funds' published compositions${T?", and the directly held positions":""}. Named companies cover ${v(A.namedCoveragePct)} of the depot, a lower bound: our data provider only supplies each fund's largest positions.`):a(`Quelle: die veröffentlichte Zusammensetzung von ${(ie==null?void 0:ie.title)??W}. Namentlich genannte Unternehmen decken ${v(A.namedCoveragePct)} des Fonds ab, ein Mindestwert: unser Datenanbieter liefert je Fonds nur die gröÃten Positionen.`,`Source: the published composition of ${(ie==null?void 0:ie.title)??W}. Named companies cover ${v(A.namedCoveragePct)} of the fund, a lower bound: our data provider only supplies each fund's largest positions.`)}),B.length>0&&e.jsx("p",{className:"text-xs text-muted-foreground",children:B.map(j=>a(`${j.stem}: ${v(j.pct)} der Fondsgewichte namentlich erfasst`,`${j.stem}: ${v(j.pct)} of fund weight named`)).join(" · ")}),e.jsx("p",{className:"text-xs text-muted-foreground border-t border-border/50 pt-3",children:a(`Abdeckung dieses Ausschnitts: Regionen ${S(A.regionsResolvedPct)}, Sektoren ${S(A.sectorsResolvedPct)}. Der jeweilige Rest bleibt unklassifiziert.`,`Coverage of this scope: regions ${S(A.regionsResolvedPct)}, sectors ${S(A.sectorsResolvedPct)}. Each layer's remainder stays unclassified.`)}),(l.length>0||Pe.length>0)&&e.jsxs("div",{className:"text-xs text-muted-foreground border-t border-border/50 pt-3 space-y-1",children:[l.length>0&&e.jsxs("p",{children:[a("Keine Fondsdaten für: ","No fund breakdown for: "),l.map(j=>nt.get(j.ticker)??j.ticker).join(", ")]}),Pe.length>0&&e.jsxs("p",{children:[a(`${Pe.length} Positionen ohne Regions- oder Sektordaten (${S(Me)} des Depots)`,`${Pe.length} positions without region or sector data (${S(Me)} of the depot)`),$e.length>0&&`: ${$e.join(", ")}`,Pe.length>$e.length&&$e.length>0&&a(` und ${Pe.length-$e.length} weitere`,` and ${Pe.length-$e.length} more`),"."]})]})]})},ro=({checked:t,onCheckedChange:s,t:r})=>{const l=g.useId();return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx($n,{htmlFor:l,className:"text-xs font-normal text-muted-foreground cursor-pointer",children:r("Anzeigen","Show")}),e.jsx(Nr,{id:l,"data-testid":"lookthrough-visibility-switch","aria-label":r("Durchschau anzeigen","Show look-through"),checked:t,onCheckedChange:s})]})},mi=t=>e.jsx(Ye,{className:"p-5","data-testid":"lookthrough-collapsed",children:e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsxs("h3",{className:"font-serif italic font-normal text-lg flex items-center gap-2 min-w-0",children:[e.jsx(jr,{className:"h-4 w-4 text-primary shrink-0"}),t.t("Durchschau: was wirklich drin liegt","Look-through: what you actually hold")]}),e.jsx("div",{className:"shrink-0",children:e.jsx(ro,{...t})})]})}),oo="desk:lookThroughVisible";function fi(){try{return localStorage.getItem(oo)==="1"}catch{return!1}}function hi(){const[t,s]=g.useState(fi),r=g.useCallback(l=>{s(l);try{localStorage.setItem(oo,l?"1":"0")}catch{}},[]);return{visible:t,setVisible:r}}const pi=({portfolio:t,assets:s,portfolioValue:r,isExpanded:l,onToggle:o,onStockClick:m,language:n,isArchived:h,holdingsWithCriteria:p=[],onUnarchive:c,onDelete:a,subscribedBriefing:b})=>{const[i,x]=g.useState("sector"),[N,S]=g.useState(!1),{rates:P}=Bt(),v=ft[n]??ft.de,y=et(),E=Ct(),Q=ys(r,E.currency,E.rates),$=g.useMemo(()=>{const O=v.unknown,V=s.map(F=>({value:Oe(F,P)??0,groupKey:Ir(F,i,O,n),shares:F.shares})),D=V.some(F=>F.value>0);return gn(V,D)},[s,i,v.unknown,P,n]);return e.jsxs("div",{className:`rounded-xl border transition-all ${h?"border-border/30 bg-foreground
7/[0.005] opacity-70":"border-border/50 bg-background hover:border-primary/20"}`,children:[e.jsxs("div",{className:"flex items-center",children:[e.jsxs("button",{onClick:o,className:"flex-1 min-w-0 flex items-center gap-4 px-5 py-4 text-left group",children:[e.jsx("div",{className:`w-9 h-9 rounded-lg flex items-center justify-center shrink-0 ${h?"bg-muted/30":"bg-primary/8 border border-primary/15"}`,children:e.jsx(rs,{size:16,className:h?"text-muted-foreground/50":"text-primary"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("h3",{className:"text-sm font-semibold text-foreground tracking-wide uppercase tabular-nums truncate",children:[t.portfolio_name,e.jsx("span",{className:"ml-2 text-2xs font-normal text-primary/70 bg-primary/8 px-1.5 py-0.5 rounded",children:s.length}),b!==void 0&&!h&&e.jsx(zr,{subscribed:b,className:"ml-2 normal-case tracking-normal"})]}),e.jsxs("p",{className:"text-xs text-muted-foreground/60 tabular-nums mt-0.5",children:[Ve(Or(Q.value,Q.currency),y),e.jsx("span",{className:"mx-1.5 text-muted-foreground/30",children:"·"}),t.portfolio_id]})]}),l?e.jsx(wr,{size:16,className:"text-muted-foreground/40 shrink-0"}):e.jsx(Kr,{size:16,className:"text-muted-foreground/40 group-hover:text-primary/60 transition-colors shrink-0"})]}),h&&(c||a)&&e.jsxs("div",{className:"flex items-center gap-1 pr-4 shrink-0",children:[c&&e.jsxs("button",{onClick:c,className:"inline-flex items-center gap-1.5 text-xs tabular-nums font-semibold px-2.5 py-1.5 rounded-lg border border-primary/25 text-primary hover:bg-primary/10 transition-colors",title:v.activate,children:[e.jsx(Cr,{size:12}),e.jsx("span",{className:"hidden sm:inline",children:v.activate})]}),a&&e.jsx("button",{onClick:()=>S(!0),className:"inline-flex items-center justify-center w-8 h-8 rounded-lg border border-border/50 text-muted-foreground hover:text-destructive hover:border-destructive/40 transition-colors",title:v.deleteLabel,children:e.jsx(_s,{size:13})})]})]}),a&&e.jsx(fs,{open:N,onOpenChange:S,children:e.jsxs(hs,{children:[e.jsxs(ps,{children:[e.jsx(gs,{children:n==="de"?"Portfolio löschen?":"Delete portfolio?"}),e.jsx(xs,{children:n==="de"?`â${t.portfolio_name||"Portfolio"}" und alle ${s.length} Position(en) werden dauerhaft gelöscht. Das kann nicht rückgängig gemacht werden.`:`"${t.portfolio_name||"Portfolio"}" and all ${s.length} position(s) will be permanently deleted. This cannot be undone.`})]}),e.jsxs(bs,{children:[e.jsx(Er,{children:n==="de"?"Abbrechen":"Cancel"}),e.jsx(vs,{onClick:()=>a(),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:n==="de"?"Endgültig löschen":"Delete permanently"})]})]})}),l&&e.jsx("div",{className:"px-5 pb-5 animate-fade-in",children:e.jsx("div",{className:"border-t border-border/30 pt-4",children:s.length===0?e.jsx("p",{className:"text-xs text-muted-foreground/50 py-4 text-center",children:v.noPositions}):e.jsxs(e.Fragment,{children:[e.jsxs(Ye,{className:"rounded-xl border-foreground
7/5 overflow-hidden mb-4",children:[e.jsx(Dr,{activeTab:i,setActiveTab:x,lang:n}),e.jsx("div",{className:"p-5",children:e.jsx(Mr,{chartData:$,centerLabel:v.valueLabel,centerValue:r>0?Ve(ut(r,E).text,y):`${s.length}`,noDataText:v.noData,totalValue:r,lang:n})})]}),e.jsxs("div",{className:"rounded-xl border border-border/30 overflow-hidden",children:[e.jsx("div",{className:"px-4 py-2.5 border-b border-border/20 bg-foreground/[0.01]",children:e.jsx("p",{className:"text-2xs tabular-nums text-muted-foreground/50 uppercase tracking-wider",children:v.positionsLabel})}),e.jsx("div",{className:"divide-y divide-border/15",children:s.map(O=>e.jsx(gi,{asset:O,language:n,onClick:()=>O.ticker_eod&&m(O.ticker_eod),holdingCriteria:p.find(V=>V.ticker_eod===O.ticker_eod)},O.id))})]})]})})})]})},gi=({asset:t,language:s,onClick:r,holdingCriteria:l})=>{var Q;const{rates:o}=Bt(),m=ft[s]??ft.de,n=et(),h=Ct(),p=s==="en"?"en":"de",c=((Q=t.ticker_eod)==null?void 0:Q.split(".")[0])??null,a=c==null?Yn(t,p):null,b=Br(t.category,p),i=Vr(t.ticker_eod),x=i?Wr(t.ticker_eod,s):null,N=t.current_price!=null,S=Oe(t,o),P=N&&S==null,v=t.current_price!=null?qn(t.current_price,t.currency,o):null,y=t.avg_cost&&v!=null?(v-t.avg_cost)/t.avg_cost*100:null,E=$=>{const O=ys($,h.currency,h.rates);return Ve(Or(O.value,O.currency),n)};return e.jsxs("div",{onClick:r,className:"flex items-center gap-3 px-4 py-2.5 hover:bg-foreground
7/[0.02] cursor-pointer transition-colors group",children:[e.jsx("div",{className:`w-1.5 h-1.5 rounded-full shrink-0 ${t.decision_status==="sell"?"bg-red-400":t.decision_status==="buy"||t.decision_status==="scale"?"bg-emerald-400":t.decision_status==="active_review"?"bg-amber-400":"bg-primary/30"}`}),c!=null?e.jsx(sa,{ticker:c,name:x??ot(t),title:i?ss[i].etcName:void 0,tickerClassName:"min-w-[48px]",className:"flex-1 min-w-0"}):e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"flex-1 truncate font-sans text-sm font-semibold text-foreground",title:i?ss[i].etcName:void 0,children:x??ot(t)}),e.jsx("span",{className:"shrink-0 min-w-[52px] max-w-[130px] truncate rounded bg-foreground/[0.04] px-1.5 py-0.5 text-center font-sans text-2xs font-medium text-muted-foreground",title:a??void 0,children:a})]}),b&&b!==a&&e.jsx("span",{className:"hidden lg:inline shrink-0 max-w-[150px] truncate font-sans text-2xs text-muted-foreground/70",title:b,children:b}),l&&l.monitoring_criteria.length>0&&e.jsxs("div",{className:"flex items-center gap-1 shrink-0",title:s==="de"?`${l.monitoring_criteria.length} Watchtower-Kriterien`:`${l.monitoring_criteria.length} Watchtower criteria`,children:[e.jsx(Ao,{size:10,className:"text-primary/50"}),l.monitoring_criteria.map($=>e.jsx("div",{className:`w-1.5 h-1.5 rounded-full ${$.status==="met"?"bg-emerald-500":$.status==="violated"?"bg-destructive":$.status==="challenged"?"bg-amber-500":"bg-muted-foreground/30"}`,title:`${$.criterion} â ${$.status}`},$.id))]}),e.jsx("span",{className:"text-2xs tabular-nums text-muted-foreground/50 hidden sm:block min-w-[40px] text-right",children:i?t.shares?De(Hr(Ur(i,t.shares)),n):"â":t.shares?De(`${t.shares} ${m.unitShares}`,n):"â"}),e.jsx("span",{className:"text-xs tabular-nums text-foreground/60 min-w-[60px] text-right hidden md:block",children:t.ticker_eod!=null?N?P?e.jsxs("span",{className:"inline-flex items-center gap-1 text-amber-500/80",title:m.noFx.replace("{currency}",t.currency??""),children:[e.jsx(mt,{size:10}),m.noFxLabel]}):S&&S>0?E(S):"â":e.jsxs("span",{className:"inline-flex items-center gap-1 text-amber-500/80",title:m.noLivePrice,children:[e.jsx(mt,{size:10}),m.noLivePriceLabel]}):S==null?e.jsxs("span",{className:"inline-flex items-center gap-1 text-amber-500/80",title:m.notValued,children:[e.jsx(mt,{size:10}),m.notValuedLabel]}):E(S)}),e.jsx("span",{className:`text-2xs tabular-nums min-w-[48px] text-right hidden lg:flex items-center justify-end gap-0.5 ${y===null?"text-muted-foreground/40":y>0?"text-emerald-500":y<0?"text-red-400":"text-muted-foreground/50"}`,children:y===null?"â":e.jsxs(e.Fragment,{children:[y>0?e.jsx(da,{size:10}):y<0?e.jsx(ua,{size:10}):e.jsx(ma,{size:10}),Math.abs(y).toFixed(1),"%"]})})]})};function no(t){var o;const s=t??{},r=s.message;if(s.code==="PGRST202"||s.code==="42883"||/function .*(merge_portfolios|split_position|move_portfolio_asset)/i.test(r??""))return{reason:"not_deployed",message:r};if(s.details)try{const m=JSON.parse(s.details),n=m==null?void 0:m.code;if(typeof n=="string"&&or(n))return{reason:n,detail:m,message:r}}catch{}const l=(o=/(?:merge_portfolios|split_position|move_portfolio_asset):\s*([a-z_]+)/.exec(r??""))==null?void 0:o[1];return l&&or(l)?{reason:l,message:r}:s.code==="42501"||s.code==="PGRST301"?{reason:"denied",message:r}:{reason:"failed",message:r}}const xi=new Set(["not_found","target_not_found","noop","conflict","denied","cross_company_unsupported","same_portfolio","system_portfolio","source_archived","target_archived","position_limit_exceeded","invalid_profile_source","invali
7d_share_count","moves_all_shares","parented_position","manual_valued_position","not_deployed","failed"]);function or(t){return xi.has(t)}async function ao(t,{sourcePortfolioId:s,targetPortfolioId:r,profileSource:l="target",unitSanityFactor:o},m){if(s===r)return{ok:!1,reason:"same_portfolio"};const n={p_source_portfolio_id:s,p_target_portfolio_id:r,p_profile_source:l,p_confirmed:m};o!=null&&(n.p_unit_sanity_factor=o);let h,p;try{({data:h,error:p}=await t.rpc("merge_portfolios",n))}catch(a){return console.error("[mergeSplitCore] merge_portfolios threw:",a),{ok:!1,reason:"failed",message:a==null?void 0:a.message}}if(p){const a=no(p);return console.error("[mergeSplitCore] merge_portfolios failed:",a.reason,p),{ok:!1,...a}}const c=h??null;if(!c)return{ok:!1,reason:"failed",message:"merge_portfolios returned no payload"};switch(c.status){case"not_found":case"target_not_found":return{ok:!1,reason:c.status,payload:c};case"blocked":return{ok:!1,reason:"position_limit_exceeded",payload:c};default:return{ok:!0,payload:c}}}function bi(t,s){return ao(t,s,!1)}function vi(t,s){return ao(t,s,!0)}async function io(t,{assetId:s,sharesToMove:r,targetPortfolioId:l},o){if(!(r>0))return{ok:!1,reason:"invalid_share_count"};let m,n;try{({data:m,error:n}=await t.rpc("split_position",{p_asset_id:s,p_shares_to_move:r,p_target_portfolio_id:l,p_confirmed:o}))}catch(p){return console.error("[mergeSplitCore] split_position threw:",p),{ok:!1,reason:"failed",message:p==null?void 0:p.message}}if(n){const p=no(n);return console.error("[mergeSplitCore] split_position failed:",p.reason,n),{ok:!1,...p}}const h=m??null;if(!h)return{ok:!1,reason:"failed",message:"split_position returned no payload"};switch(h.status){case"not_found":case"target_not_found":case"noop":return{ok:!1,reason:h.status,payload:h};case"conflict":return{ok:!1,reason:"conflict",payload:h};case"blocked":return{ok:!1,reason:"position_limit_exceeded",payload:h};default:return{ok:!0,payload:h}}}function yi(t,s){return io(t,s,!1)}function _i(t,s){return io(t,s,!0)}function ki(t,s){var m;const r=[],l=[];for(const n of t){const h=n.is_self?s:((m=n.customer_name)==null?void 0:m.trim())||`#${n.company_id}`,p=n.portfolios.filter(c=>!Qe(c.portfolio_id));if(p.length!==0){r.push({companyId:n.company_id,label:h,isSelf:n.is_self});for(const c of p)l.push({portfolio_id:c.portfolio_id,portfolio_name:c.portfolio_name,companyId:n.company_id,accountLabel:h,isSelf:n.is_self,archived:c.product_status==="archived",subscribedBriefing:c.subscribed_portfolio_briefing===!0})}}r.sort((n,h)=>n.isSelf!==h.isSelf?n.isSelf?-1:1:n.label.localeCompare(h.label,"de"));const o=new Map(r.map((n,h)=>[n.companyId,h]));return l.sort((n,h)=>{const p=o.get(n.companyId)??Number.MAX_SAFE_INTEGER,c=o.get(h.companyId)??Number.MAX_SAFE_INTEGER;return p!==c?p-c:n.portfolio_id.localeCompare(h.portfolio_id)}),{accounts:r,options:l}}function nr(t,s){return s===null?t.options:t.options.filter(r=>r.companyId===s)}function dt(t,s){return s?t.options.find(r=>r.portfolio_id===s)??null:null}function lo(t,s){return t.options.filter(r=>r.portfolio_id!==s&&!r.archived)}function co(t,s){return!t||!s?!1:t.companyId!==s.companyId}function uo(t,s){return!t||!s?!1:t.isSelf&&s.isSelf}const ji={de:{planTitle:"Das passiert",moves:"Positionen ziehen um",folds:"Positionen werden zusammengefasst",stays:"Positionen bleiben stehen",countAfter:"Positionen im Zielportfolio danach",ofLimit:"von 20",foldsTitle:"Zusammengefasste Positionen",foldsWarning:"Das ist deine einzige Gelegenheit, diese Zahlen zu sehen. Nach dem Zusammenfuehren lässt sich die urspruengliche Aufteilung nicht mehr rekonstruieren.",foldTarget:"Ziel",foldSource:"Quelle",foldAfter:"Danach",conflictsTitle:"Bleibt stehen, bitte manuell klaeren",conflictsHint:"Diese Positionen bleiben unveraendert in ihrem jetzigen Portfolio. Der Rest wird trotzdem zusammengefuehrt.",warningsTitle:"Hinweise",consequencesTitle:"Folgen",consWatchtower:"Ãberwacht beides denselben Titel, bleibt die Watchtower-Einstellung des Zielportfolios stehen.",consBriefingTarget:"Das Portfolio Briefing des Zielportfolios bleibt wie es ist.",consBriefingTransfer:"Das Portfolio Briefing zieht vom Quellportfolio ins Ziel um.",consBriefingNone:"Kein Portfolio Briefing betroffen.",consArchive:"Das Quellportfolio wird archiviert, nicht gelöscht: du kannst es jederzeit wieder aktivieren. Zusammengefasste Positionen lassen sich dadurch aber nicht wiederherstellen.",blockedTitle:"Zu viele Positionen",blockedText:"Das Zielportfolio haette danach {after} boersennotierte Positionen, erlaubt sind {max}. Archiviere oder verschiebe zuerst einzelne Positionen.",shares:"Stück",cost:"Einstand"},en:{planTitle:"What happens",moves:"positions move",folds:"positions are combined",stays:"positions stay behind",countAfter:"Positions in the target portfolio afterwards",ofLimit:"of 20",foldsTitle:"Combined positions",foldsWarning:"This is your only chance to see these numbers. After the merge the original split cannot be reconstructed.",foldTarget:"Target",foldSource:"Source",foldAfter:"After",conflictsTitle:"Stays where it is, resolve manually",conflictsHint:"The
7se positions are left untouched in their current portfolio. Everything else still merges.",warningsTitle:"Notes",consequencesTitle:"Consequences",consWatchtower:"Where both monitor the same security, the target portfolio keeps its Watchtower tuning.",consBriefingTarget:"The target portfolio keeps its Portfolio Briefing as it is.",consBriefingTransfer:"The Portfolio Briefing moves from the source portfolio to the target.",consBriefingNone:"No Portfolio Briefing is affected.",consArchive:"The source portfolio is archived, not deleted: you can reactivate it at any time. That does not bring back combined positions, though.",blockedTitle:"Too many positions",blockedText:"The target portfolio would hold {after} listed positions, the limit is {max}. Archive or move individual positions first.",shares:"sh.",cost:"cost"}},Ni=({payload:t,blocked:s,lang:r,fmtCost:l})=>{var b;const o=ji[r],m=et(),n=t.counts,h=t.merges??[],p=t.conflicts??[],c=t.warnings??[],a=t.briefing==="transferred_from_source"?o.consBriefingTransfer:t.briefing==="none"?o.consBriefingNone:o.consBriefingTarget;return e.jsxs("div",{className:"space-y-4",children:[s&&n&&e.jsxs("div",{className:"rounded-xl border border-destructive/40 bg-destructive/[0.06] p-4",children:[e.jsxs("p",{className:"flex items-center gap-2 text-sm font-semibold text-destructive",children:[e.jsx(Fe,{size:15,className:"shrink-0"})," ",o.blockedTitle]}),e.jsx("p",{className:"text-sm text-foreground/80 mt-1.5",children:o.blockedText.replace("{after}",String(n.listed_after)).replace("{max}",String(n.max_listed))}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-2 tabular-nums",children:[n.target_listed_before," + ",n.source_listed," = ",n.listed_after]})]}),e.jsxs("div",{className:"rounded-xl border border-border/50 bg-foreground
7/[0.02] p-4 space-y-1.5",children:[e.jsx("p",{className:"text-xs font-bold uppercase tracking-wider text-muted-foreground",children:o.planTitle}),e.jsxs("p",{className:"text-sm text-foreground/80",children:[e.jsx("span",{className:"tabular-nums font-semibold",children:t.moved_count??((b=t.moves)==null?void 0:b.length)??0})," ",o.moves,e.jsx("span",{className:"mx-1.5 text-muted-foreground/40",children:"·"}),e.jsx("span",{className:"tabular-nums font-semibold",children:t.merged_count??h.length})," ",o.folds,e.jsx("span",{className:"mx-1.5 text-muted-foreground/40",children:"·"}),e.jsx("span",{className:"tabular-nums font-semibold",children:p.length})," ",o.stays]}),n&&e.jsxs("p",{className:"text-sm text-foreground/80",children:[o.countAfter,": ",e.jsx("span",{className:"tabular-nums font-semibold",children:n.listed_after})," ",e.jsx("span",{className:"text-muted-foreground",children:o.ofLimit})]})]}),h.length>0&&e.jsxs("div",{className:"rounded-xl border border-amber-500/30 bg-amber-500/[0.05] p-4",children:[e.jsx("p",{className:"text-xs font-bold uppercase tracking-wider text-amber-600 dark:text-amber-400",children:o.foldsTitle}),e.jsx("p",{className:"text-xs text-amber-700/90 dark:text-amber-300/90 mt-1.5",children:o.foldsWarning}),e.jsx("div",{className:"mt-3 space-y-2.5",children:h.map(i=>e.jsxs("div",{className:"rounded-lg border border-border/40 bg-background/60 p-3",children:[e.jsx("p",{className:"tabular-nums text-xs font-semibold text-primary",children:i.ticker_eod}),e.jsxs("div",{className:"mt-1.5 grid grid-cols-1 sm:grid-cols-3 gap-2 text-xs",children:[e.jsxs("div",{children:[e.jsx("span",{className:"block text-muted-foreground",children:o.foldTarget}),e.jsxs("span",{className:"tabular-nums",children:[De(Ue(i.before.target.shares),m)," ",o.shares]}),e.jsxs("span",{className:"block tabular-nums text-muted-foreground/80",children:[o.cost," ",l(i.before.target.avg_cost)]})]}),e.jsxs("div",{children:[e.jsx("span",{className:"block text-muted-foreground",children:o.foldSource}),e.jsxs("span",{className:"tabular-nums",children:[De(Ue(i.before.source.shares),m)," ",o.shares]}),e.jsxs("span",{className:"block tabular-nums text-muted-foreground/80",children:[o.cost," ",l(i.before.source.avg_cost)]})]}),e.jsxs("div",{children:[e.jsx("span",{className:"block text-muted-foreground",children:o.foldAfter}),e.jsxs("span",{className:"tabular-nums font-semibold",children:[De(Ue(i.after.shares),m)," ",o.shares]}),e.jsxs("span",{className:"block tabular-nums font-semibold text-muted-foreground/80",children:[o.cost," ",l(i.after.avg_cost)]})]})]})]},i.source_asset_id))})]}),p.length>0&&e.jsxs("div",{className:"rounded-xl border border-border/50 bg-foreground
7/[0.02] p-4",children:[e.jsx("p",{className:"text-xs font-bold uppercase tracking-wider text-muted-foreground",children:o.conflictsTitle}),e.jsx("p",{className:"text-xs text-muted-foreground/80 mt-1.5",children:o.conflictsHint}),e.jsx("ul",{className:"mt-3 space-y-2",children:p.map(i=>e.jsxs("li",{className:"text-xs",children:[e.jsx("span",{className:"tabular-nums font-semibold text-foreground/80",children:i.ticker_eod??i.source_asset_id.slice(0,8)}),e.jsxs("span",{className:"text-muted-foreground",children:[" - ",va(i.reason,r)]}),i.reason==="avg_cost_unit_mismatch"&&e.jsxs("span",{className:"block tabular-nums text-2xs text-muted-foreground/70 mt-0.5",children:[l(i.source_avg_cost)," vs ",l(i.target_avg_cost),i.ratio!=null&&` (${i.ratio.toLocaleString("de-DE",{maximumFractionDigits:1})}x)`]})]},`${i.source_asset_id}-${i.reason}`))})]}),c.length>0&&e.jsxs("div",{className:"rounded-xl border border-border/50 p-4",children:[e.jsx("p",{className:"text-xs font-bold uppercase tracking-wider text-muted-foreground",children:o.warningsTitle}),e.jsx("ul",{className:"mt-2 space-y-1.5",children:c.map((i,x)=>e.jsxs("li",{className:"flex items-start gap-2 text-xs text-muted-foreground",children:[e.jsx(wt,{size:12,className:"shrink-0 mt-0.5 text-primary/60"}),e.jsxs("span",{children:[ya(i.code,r),i.ticker_eod?e.jsxs("span",{className:"tabular-nums",children:[" (",i.ticker_eod,")"]}):null]})]},`${i.code}-${i.ticker_eod??x}`))})]}),e.jsxs("div",{className:"rounded-xl border border-border/50 p-4",children:[e.jsx("p",{className:"text-xs font-bold uppercase tracking-wider text-muted-foreground",children:o.consequencesTitle}),e.jsxs("ul",{className:"mt-2 space-y-1.5 text-xs text-muted-foreground list-disc pl-4",children:[e.jsx("li",{children:o.consWatchtower}),e.jsx("li",{children:a}),e.jsx("li",{children:o.consArchive})]})]})]})},wi={de:{titleMerge:"Portfolios zusammenfuehren",titleSplit:"Portfolio aufteilen",descMerge:"Positionen aus diesem Portfolio in ein anderes übernehmen.",descSplit:"Positionen aus diesem Portfolio in ein anderes verschieben, ganz oder teilweise.",sourceLabel:"Quellportfolio",sourceHint:"Aus welchem Portfolio sollen die Positionen heraus?",noSources:"Es gibt kein aktives Portfolio.",noPositions:"Dieses Portfolio hat keine Positionen zum Verschieben.",positionsLabel:"Positionen",positionsHint:"Ohne Eingabe zieht die ganze Position um. Eine kleinere Stückzahl teilt sie auf.",selectAll:"Alle",selectNone:"Keine",sharesPlaceholder:"Stück",ofShares:"von",targetLabel:"Ziel",newPortfolio:"Neues Portfolio",newPortfolioName:"Name des neuen Portfolios",newPortfolioHint:"Wird beim Bestaetigen angelegt. Vorab prüfen lässt sich dagegen nichts, weil das Ziel noch nicht existiert.",modeMerge:"Das Quellportfolio geht vollstaendig ins Ziel über und wird archiviert (reversibel, ausser bei zusammengefuehrten Positionen).",modeTransfer:"Positionen werden verschoben, Quelle bleibt bestehen.",profileLabel:"Investoren-Profil",profileTarget:"Profil des Zielportfolios behalten",profileTargetHint:"Buy-Box-Trigger, Skalen und Rauschfilter des Ziels bleiben unveraendert.",profileSource:"Profil des Quellportfolios übernehmen",profileSourceHint:"Ãberschreibt die Einstellungen des Zielportfolios.",preview:"Vorschau berechnen",previewing:"Wird geprüft...",back:"Zurück",cancel:"Abbrechen",close:"SchlieÃen",confirmMerge:"Zusammenfuehren",confirmMove:"Verschieben",running:"Wird ausgefuehrt...",reasonHasParent:"Unterposition, nur zusammen mit ihrer Oberposition zu verschieben",reasonHasChildren:"hat Unterpositionen, nur als Ganzes zu verschieben",noteManualValued:"Sachwert, nur als Ganzes verschiebbar",planTitle:"Das passiert",planMove:"ganze Position",planSplit:"Teilverschiebung",planCheckedLater:"wird beim Verschieben geprüft",planBlocked:"nicht möglich",capacityLabel:"Positionen im Ziel danach",ofLimit:"von",blockedCapacity:"Das Ziel haette danach {after} boersennotierte Positionen, erlaubt sind {max}.",blockedCollision:'Das Ziel haelt diesen Titel bereits. Nutze stattdessen "Portfolios zusammenfuehren", um beide Portfolios zusammenzulegen.',nothingSelected:"Wähle mindestens eine Position aus.",noTarget:"Wähle ein Ziel aus.",nameRequired:"Bitte einen Namen für das neue Portfolio eingeben.",splitBefore:"vorher",splitStays:"bleibt",splitMoves:"zieht um",cost:"Einstand",shares:"Stück",resultAllOk:"Alle Positionen wurden verschoben.",resultPartial:"Nicht alle Positionen konnten verschoben werden. Was gelaufen ist, ist gelaufen und wurde nicht zurückgenommen.",resultMoved:"verschoben",resultSplit:"aufgeteilt",resultFailed:"nicht verschoben",mergeSuccess:"Portfolios zusammengefuehrt",createFailed:"Das neue Portfolio konnte nicht angelegt werden.",portfolioLimit:"Alle Portfolio-Kennungen (A-J) sind vergeben. Archiviere zuerst ein Portfolio.",crossAccountWholeOnly:"Nur innerhalb eines Kontos teilbar. Verschiebe die ganze Position zuerst, um sie dort aufzuteilen."},en:{titleMerge:"Merge portfolios",titleSplit:"Split portfolio",descMerge:"Take positions from this portfolio into another one.",descSplit:"Move positions from this portfolio into another one, whole or in part.",sourceLabel:"Source portfolio",sourceHint:"Which portfolio should the positions leave?",noSources:"There is no active portfolio.",noPositions:"This portfolio has no positions to move.",positionsLabel:"Positions",positionsHint:"Left as is, the whole position moves. A smaller share count splits it.",selectAll:"All",selectNone:"None",sharesPlaceholder:"shares",ofShares:"of",targetLabel:"Target",newPortfolio:"New portfolio",newPortfolioName:"Name of the new portfolio",newPortfolioHint:"Created on confirm. Nothing can be checked up front, because the target does not exist yet.",modeMerge:"The source portfolio folds entirely into the target and is archived (reversible, except for folded positions).",modeTransfer:"The positions move, the source portfolio stays.",profileLabel:"Investor profile",profileTarget:"Keep the target portfolio profile",profileTargetHint:"The target buy-box triggers, scales and noise filter stay untouched.",profileSource:"C
7opy the source portfolio profile over",profileSourceHint:"Overwrites the target portfolio settings.",preview:"Show preview",previewing:"Checking...",back:"Back",cancel:"Cancel",close:"Close",confirmMerge:"Merge",confirmMove:"Move",running:"Working...",reasonHasParent:"sub-position, move it together with its parent",reasonHasChildren:"has sub-positions, move it as a whole",noteManualValued:"non-listed asset, moves whole only",planTitle:"What happens",planMove:"whole position",planSplit:"partial move",planCheckedLater:"checked when moving",planBlocked:"not possible",capacityLabel:"Positions in the target afterwards",ofLimit:"of",blockedCapacity:"The target would hold {after} listed positions, the limit is {max}.",blockedCollision:'The target already holds this security. Use "Merge portfolios" instead to combine the two portfolios.',nothingSelected:"Select at least one position.",noTarget:"Pick a target.",nameRequired:"Please enter a name for the new portfolio.",splitBefore:"before",splitStays:"stays",splitMoves:"moves",cost:"cost",shares:"sh.",resultAllOk:"Every position was moved.",resultPartial:"Not every position could be moved. What already ran stands and was not rolled back.",resultMoved:"moved",resultSplit:"split",resultFailed:"not moved",mergeSuccess:"Portfolios merged",createFailed:"The new portfolio could not be created.",portfolioLimit:"All portfolio ids (A-J) are taken. Archive a portfolio first.",crossAccountWholeOnly:"Only possible inside one account. Move the whole position first, then split it there."}},ar="__new__",kt=t=>{var s;return((s=t.portfolio_name)==null?void 0:s.trim())||t.portfolio_id},Ci=t=>{const s=t!=null&&t.trim()?Number(t):NaN;return Number.isFinite(s)?s:null};async function Si(t,s){const r=Ee,{data:l}=await r.from("kasona_investor_profiles").select("portfolio_id").eq("company_id",t),o=new Set((l??[]).map(a=>String(a.portfolio_id).split("-").pop()).filter(Boolean)),m=fa.find(a=>!o.has(a));if(!m)throw new qr(t);const n=`${t}-${m}`,{data:h}=await r.from("kasona_customer_basic_info").select("contact_person_name, company_name").eq("company_id",t).maybeSingle(),{data:p}=await r.from("kasona_investor_profiles").select("recipient_email, delivery_channel").eq("portfolio_id",`${t}-A`).maybeSingle(),{error:c}=await r.from("kasona_investor_profiles").insert({company_id:t,portfolio_id:n,portfolio_name:s.trim()||`Portfolio ${m}`,customer_name:(h==null?void 0:h.contact_person_name)||(h==null?void 0:h.company_name)||"",subscribed_quartals:!0,subscribed_portfolio_briefing:!1,product_status:"to create",language:"de",voice_config:"helmut",recipient_email:(p==null?void 0:p.recipient_email)??null,delivery_channel:(p==null?void 0:p.delivery_channel)||"email"});if(c)throw c;return{portfolio_id:n,portfolio_name:s.trim()||`Portfolio ${m}`}}const Pi=({open:t,onOpenChange:s,mode:r,initialSourceId:l,portfolios:o,assets:m,companyId:n,language:h,onDone:p,scope:c=null,initialSourceCompanyId:a=null})=>{const b=St(h),i=wi[b],x=Qr[b],N=et(),S=Ct(),[P,v]=g.useState(l),[y,E]=g.useState(new Set),[Q,$]=g.useState({}),[O,V]=g.useState(""),[D,F]=g.useState(null),[w,M]=g.useState(null),[I,T]=g.useState(""),[Y,ae]=g.useState("target"),[J,W]=g.useState(null),[A,z]=g.useState(null),[Z,re]=g.useState(!1),[pe,C]=g.useState(null),[k,q]=g.useState(null),se=c?dt(c,P):null,be=c?dt(c,O):null,ie=c?se:o.find(f=>f.portfolio_id===P)??null,R=g.useMemo(()=>P?m.filter(f=>f.portfolio_id===P):[],[m,P]),u=g.useMemo(()=>{const f=new Set;for(const ee of m)ee.parent_asset_id&&f.add(ee.parent_asset_id);return f},[m]),B=Eo.useCallback(f=>f.parent_asset_id!=null?"has_parent":u.has(f.id)?"has_children":null,[u]),oe=f=>f==="has_parent"?i.reasonHasParent:i.reasonHasChildren,X=g.useMemo(()=>R.filter(f=>B(f)==null),[R,B]);g.useEffect(()=>{if(!t)return;const f=c&&l?dt(c,l):null,ee=c&&c.accounts.length===1?c.accounts[0].companyId:null,H=a??(f==null?void 0:f.companyId)??ee??null;F(H),M(ee);let de=l??null;if(de==null)if(c){if(H!=null){const L=nr(c,H).filter(fe=>!fe.archived);de=L.length===1?L[0].portfolio_id:null}}else de=o.length===1?o[0].portfolio_id:null;v(de),V(""),T(""),$({}),ae("target"),W(null),z(null),re(!1),C(null),q(null),E(new Set)},[t,l,a,o,c]),g.useEffect(()=>{if(!(!t||!P)&&(E(new Set),$({}),W(null),z(null),re(!1),c)){const f=dt(c,P);f&&F(f.companyId)}},[t,P,r,c]);const ke=f=>{if(f==null||!Number.isFinite(f))return"-";const ee=ys(f,S.currency,S.rates);return Ve(Pr(ee.value,"de",{currency:ee.currency,decimals:2,locale:"de-DE"}),N)},ve=()=>{W(null),z(null),re(!1)},ze=f=>{ve(),E(ee=>{const H=new Set(ee);return H.has(f)?H.delete(f):H.add(f),H})},Ke=f=>{var L;const ee=f.shares;if(ee==null||!(ee>0)||f.manual_value!=null||c&&Ne)return null;const H=(L=Q[f.id])==null?void 0:L.trim();if(!H)return null;const de=Number(H.replace(",","."));return!Number.isFinite(de)||de<=0||de>=ee?null:de},Ce=c?be:o.find(f=>f.portfolio_id===O)??null,ye=O===ar,We=c?lo(c,P):null,Xe=We?We.filter(f=>w==null||f.companyId===w):o.filter(f=>f.portfolio_id!==P),Se=r==="merge",Ie=!c||(ye?(se==null?void 0:se.isSelf)??!0:uo(se,be)),Ne=!ye&&!!c&&co(se,be),me=c?c.accounts.find(f=>f.companyId===w)??null:null,tt=!c||((me==null?void 0:me.isSelf)??!1),Ge=c?D!=null?nr(c,D).filter(f=>!f.archived):[]:o,Je=g.useMemo(()=>Ce?m.filter(f=>f.portfolio_id===Ce.portfolio_id):[],[m,Ce]),qe=ye?y.size:Je.filter(f=>(f.asset_kind??"listed")==="listed").length+R.filter(f=>y.has(f.id)&&(f.asset_kind??"listed")==="listed").length,st=!ye&&qe>It,ht=async()=>
7{if(!(k||!P)){if(!Se&&y.size===0){te.warning(i.nothingSelected);return}if(!O){te.warning(i.noTarget);return}if(ye&&!I.trim()){te.warning(i.nameRequired);return}q("preview");try{if(Se){if(Ie){const ne=await bi(Ee,{sourcePortfolioId:P,targetPortfolioId:O,profileSource:Y});if(ne.ok){z(ne.payload??null),re(!1);return}if(ne.reason==="position_limit_exceeded"&&ne.payload){z(ne.payload),re(!0);return}te.error(yt(ne.reason,b));return}const L=await ha({source_portfolio_id:P,target_portfolio_id:O,profile_source:Y});if(L.ok===!1){te.error(Be(L.code,b));return}const fe=L.data.payload;if(!fe){te.error(Be("unknown",b));return}z(fe),re(fe.status==="blocked");return}const f=R.filter(L=>y.has(L.id)),ee=Ie&&!ye&&qe>It,H=new Set(Je.map(L=>Us(L.ticker_eod)).filter(Boolean)),de=[];for(const L of f){const fe=ot(L)??L.ticker_eod??L.id,ne=L.ticker_eod,xe=Ke(L),ce=Us(ne);if(ee){de.push({assetId:L.id,label:fe,ticker:ne,kind:xe==null?"move":"split",sharesToMove:xe??void 0,blocked:i.blockedCapacity.replace("{after}",String(qe)).replace("{max}",String(It))});continue}if(ce&&H.has(ce)){de.push({assetId:L.id,label:fe,ticker:ne,kind:xe==null?"move":"split",sharesToMove:xe??void 0,blocked:i.blockedCollision});continue}if(xe==null){de.push({assetId:L.id,label:fe,ticker:ne,kind:"move"});continue}if(ye){de.push({assetId:L.id,label:fe,ticker:ne,kind:"split",sharesToMove:xe});continue}if(Ie){const he=await yi(Ee,{assetId:L.id,sharesToMove:xe,targetPortfolioId:O});de.push({assetId:L.id,label:fe,ticker:ne,kind:"split",sharesToMove:xe,preview:he.payload,blocked:he.ok?void 0:yt(he.reason,b)});continue}const pt=await Zr({source_portfolio_id:P,target_portfolio_id:O,asset_id:L.id,shares_to_move:xe});pt.ok===!1?de.push({assetId:L.id,label:fe,ticker:ne,kind:"split",sharesToMove:xe,blocked:Be(pt.code,b)}):de.push({assetId:L.id,label:fe,ticker:ne,kind:"split",sharesToMove:xe,preview:pt.data.payload})}W(de)}finally{q(null)}}},nt=async()=>{var f;if(!(!P||k||Z)){q("run");try{if(Ie){const H=await vi(Ee,{sourcePortfolioId:P,targetPortfolioId:O,profileSource:Y});if(!H.ok){if(H.reason==="position_limit_exceeded"&&H.payload){z(H.payload),re(!0);return}te.error(yt(H.reason,b));return}te.success(i.mergeSuccess),s(!1),await p();return}const ee=await pa({source_portfolio_id:P,target_portfolio_id:O,profile_source:Y});if(ee.ok===!1){const H=(f=ee.response)==null?void 0:f.payload;if((H==null?void 0:H.status)==="blocked"){z(H),re(!0);return}te.error(Be(ee.code,b));return}te.success(i.mergeSuccess),s(!1),await p()}finally{q(null)}}},at=async()=>{if(!(k||!J||!P)){q("run");try{let f=Ce;if(ye)try{f=await Si(n,I)}catch(L){L instanceof qr?te.error(i.portfolioLimit,{description:L.message}):te.error(i.createFailed,{description:L instanceof Error?L.message:String(L)});return}if(!f)return;const ee=J.filter(L=>!L.blocked),H=J.filter(L=>L.blocked).map(L=>({assetId:L.assetId,label:L.label,outcome:"failed",message:L.blocked}));let de=!1;for(const L of ee){if(Ie){if(L.kind==="split"&&L.sharesToMove!=null){const ce=await _i(Ee,{assetId:L.assetId,sharesToMove:L.sharesToMove,targetPortfolioId:f.portfolio_id});H.push(ce.ok?{assetId:L.assetId,label:L.label,outcome:"split"}:{assetId:L.assetId,label:L.label,outcome:"failed",message:yt(ce.reason,b)});continue}const ne=R.find(ce=>ce.id===L.assetId),xe=await Gr(Ee,{assetId:L.assetId,sourcePortfolioId:P,targetPortfolioId:f.portfolio_id,tickerEod:L.ticker??"",stockName:(ne==null?void 0:ne.stock_name)??null,isOwned:((ne==null?void 0:ne.shares)??0)>0});H.push(xe.ok?{assetId:L.assetId,label:L.label,outcome:"moved"}:{assetId:L.assetId,label:L.label,outcome:"failed",message:yt(xe.reason==="conflict"?"conflict":xe.reason==="denied"?"denied":"failed",b)});continue}if(de){H.push({assetId:L.assetId,label:L.label,outcome:"failed",message:Be("op_not_enabled",b)});continue}const fe=await os({source_portfolio_id:P,target_portfolio_id:f.portfolio_id,asset_id:L.assetId,...L.sharesToMove!=null?{shares_to_move:L.sharesToMove}:{}});if(fe.ok===!0){H.push({assetId:L.assetId,label:L.label,outcome:L.sharesToMove!=null?"split":"moved"});continue}fe.code==="op_not_enabled"&&(de=!0),H.push({assetId:L.assetId,label:L.label,outcome:"failed",message:Be(fe.code,b)})}C(H),H.some(L=>L.outcome!=="failed")&&await p()}finally{q(null)}}},Pe=(pe==null?void 0:pe.some(f=>f.outcome==="failed"))??!1,Me=J!=null||A!=null,$e=Se?i.modeMerge:i.modeTransfer,Re=c?c.accounts.length>1&&a==null||Ge.length>1:o.length>1,j=Me?"clear-preview":P!=null?l==null&&Re?"to-source-portfolio-step":"close":c&&D!=null&&a==null&&c.accounts.length>1?"to-source-account-step":"close",le=j==="close"?i.cancel:i.back,ge=()=>{switch(j){case"clear-preview":ve();return;case"to-source-portfolio-step":v(null);return;case"to-source-account-step":F(null);return;
7case"close":s(!1);return}};return e.jsx(as,{open:t,onOpenChange:s,children:e.jsxs(is,{className:"max-w-2xl max-h-[85vh] overflow-y-auto",children:[e.jsxs(ls,{children:[e.jsx(cs,{children:r==="merge"?i.titleMerge:i.titleSplit}),e.jsxs(ds,{children:[ie&&e.jsx("span",{className:"block font-semibold text-foreground mb-1",children:kt(ie)}),r==="merge"?i.descMerge:i.descSplit]})]}),pe?e.jsxs("div",{className:"space-y-3",children:[e.jsx("p",{className:`text-sm ${Pe?"text-amber-600 dark:text-amber-400":"text-foreground/80"}`,children:Pe?i.resultPartial:i.resultAllOk}),e.jsx("ul",{className:"space-y-1.5",children:pe.map(f=>e.jsxs("li",{className:"flex items-start gap-2 text-xs",children:[f.outcome==="failed"?e.jsx(Sr,{size:13,className:"shrink-0 mt-0.5 text-destructive"}):e.jsx(us,{size:13,className:"shrink-0 mt-0.5 text-emerald-500"}),e.jsxs("span",{className:"min-w-0",children:[e.jsx("span",{className:"font-medium text-foreground/80",children:f.label}),e.jsxs("span",{className:"text-muted-foreground",children:[" - ",f.outcome==="moved"?i.resultMoved:f.outcome==="split"?i.resultSplit:i.resultFailed,f.message?`: ${f.message}`:""]})]})]},f.assetId))})]}):P?R.length===0?e.jsx("p",{className:"text-sm text-muted-foreground py-4",children:i.noPositions}):Me?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"rounded-xl border border-border/50 bg-foreground
7/[0.02] p-4 space-y-1",children:[e.jsxs("p",{className:"flex items-center gap-2 text-xs font-bold uppercase tracking-wider text-muted-foreground",children:[i.planTitle,Ne&&e.jsx("span",{className:"rounded-full bg-amber-500/15 px-2 py-0.5 text-2xs font-semibold normal-case tracking-normal text-amber-700 dark:text-amber-400",children:x.crossBadge})]}),e.jsxs("p",{className:"flex items-center gap-2 text-sm text-foreground/80",children:[e.jsx("span",{className:"font-medium",children:kt(ie)}),e.jsx(lt,{size:13,className:"text-primary shrink-0"}),e.jsx("span",{className:"font-medium",children:ye?I.trim()||i.newPortfolio:kt(Ce)})]}),c&&e.jsxs("p",{className:"flex flex-wrap items-center gap-x-1.5 gap-y-0.5 text-2xs text-muted-foreground",children:[e.jsxs("span",{children:[x.fromAccount,": ",e.jsx("span",{className:"font-medium text-foreground/70",children:(se==null?void 0:se.accountLabel)??"?"})]}),e.jsx(lt,{size:11,className:"text-muted-foreground/50 shrink-0"}),e.jsxs("span",{children:[x.toAccount,": ",e.jsx("span",{className:"font-medium text-foreground/70",children:ye?x.accountLabel:(be==null?void 0:be.accountLabel)??"?"})]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:$e})]}),Ne&&e.jsxs("div",{className:"rounded-lg border border-amber-500/30 bg-amber-500/[0.05] p-3 space-y-1.5",children:[e.jsxs("p",{className:"flex items-start gap-1.5 text-xs text-amber-700 dark:text-amber-400",children:[e.jsx(Fe,{size:12,className:"shrink-0 mt-0.5"})," ",x.alertRetuneNotice]}),e.jsxs("p",{className:"flex items-start gap-1.5 text-xs text-amber-700 dark:text-amber-400",children:[e.jsx(Fe,{size:12,className:"shrink-0 mt-0.5"})," ",x.auditNotice]}),Se&&e.jsxs("p",{className:"flex items-start gap-1.5 text-xs text-amber-700 dark:text-amber-400",children:[e.jsx(Fe,{size:12,className:"shrink-0 mt-0.5"})," ",x.briefingNotTransferred]})]}),A?e.jsx(Ni,{payload:A,blocked:Z,lang:b,fmtCost:ke}):e.jsxs(e.Fragment,{children:[!ye&&e.jsxs("p",{className:"text-sm text-foreground/80",children:[i.capacityLabel,": ",e.jsx("span",{className:"tabular-nums font-semibold",children:qe})," ",e.jsxs("span",{className:"text-muted-foreground",children:[i.ofLimit," ",It]})]}),!Ie&&st&&e.jsxs("p",{className:"flex items-start gap-1.5 text-xs text-amber-600 dark:text-amber-400",children:[e.jsx(Fe,{size:12,className:"shrink-0 mt-0.5"})," ",x.limitWarnCrossing20]}),e.jsx("ul",{className:"space-y-2",children:(J??[]).map(f=>{var ee,H,de,L;return e.jsxs("li",{className:`rounded-lg border p-3 ${f.blocked?"border-destructive/40 bg-destructive/[0.05]":"border-border/40"}`,children:[e.jsxs("p",{className:"flex items-center gap-2 text-sm",children:[e.jsx("span",{className:"font-medium text-foreground/85 truncate",children:f.label}),f.ticker&&e.jsx("span",{className:"tabular-nums text-2xs text-primary/70 shrink-0",children:f.ticker}),e.jsx("span",{className:"ml-auto shrink-0 text-2xs tabular-nums uppercase tracking-wider text-muted-foreground",children:f.blocked?i.planBlocked:f.kind==="move"?i.planMove:i.planSplit})]}),f.blocked?e.jsxs("p",{className:"flex items-start gap-1.5 text-xs text-destructive mt-1.5",children:[e.jsx(Fe,{size:12,className:"shrink-0 mt-0.5"})," ",f.blocked]}):(ee=f.preview)!=null&&ee.before?e.jsxs("p",{className:"text-2xs tabular-nums text-muted-foreground mt-1.5",children:[i.splitBefore," ",De(Ue(f.preview.before.shares),N)," ",i.shares," -> ",i.splitStays," ",De(Ue((H=f.preview.after)==null?void 0:H.source_shares),N)," ",i.shares," · ",i.splitMoves," ",De(Ue((de=f.preview.after)==null?void 0:de.target_shares),N)," ",i.shares," · ",i.cost," ",ke(((L=f.preview.after)==null?void 0:L.avg_cost)??f.preview.before.avg_cost)]}):e.jsxs("p",{className:"flex items-start gap-1.5 text-2xs text-muted-foreground mt-1.5",children:[e.jsx(wt,{size:11,className:"shrink-0 mt-0.5 text-primary/60"}),f.kind==="split"&&f.sharesToMove!=null?`${De(Ue(f.sharesToMove),N)} ${i.shares} - ${i.planCheckedLater}`:i.planCheckedLater]})]},f.assetId)})})]})]}):e.jsxs("div",{className:"space-y-5",children:[Se?e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-xs font-bold uppercase tracking-wider text-muted-foreground",children:i.positionsLabel}),e.jsx("div",{className:"space-y-1.5",children:R.map(f=>{const ee=B(f),H=f.shares;return e.jsx("div",{className:"flex flex-wrap items-center gap-3 rounded-lg border border-border/50 px-3 py-2.5",children:e.jsxs("span",{className:"flex-1 min-w-0",children:[e.jsx("span",{className:"block text-sm font-medium truncate",children:ot(f)??f.ticker_eod??f.id}),e.jsxs("span",{className:"block text-2xs text-muted-foreground tabular-nums",children:[f.ticker_eod??f.asset_kind,H!=null&&H>0?` · ${De(Ue(H),N)} ${i.shares}`:"",ee?` · ${oe(ee)}`:f.manual_value!=null?` · ${i.noteManualValued}`:""]})]})},f.id)})})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("p",{className:"text-xs font-bold uppercase tracking-wider text-muted-foreground",children:i.positionsLabel}),e.jsxs("span",{className:"flex items-center gap-2 text-2xs",children:[e.jsx("button",{type:"button",onClick:()=>{ve(),E(new Set(X.map(f=>f.id)))},className:"text-muted-foreground hover:text-primary transition-colors",children:i.selectAll}
7),e.jsx("span",{className:"text-muted-foreground/30",children:"·"}),e.jsx("button",{type:"button",onClick:()=>{ve(),E(new Set)},className:"text-muted-foreground hover:text-primary transition-colors",children:i.selectNone})]})]}),e.jsx("p",{className:"text-xs text-muted-foreground/80",children:i.positionsHint}),e.jsx("div",{className:"space-y-1.5",children:R.map(f=>{const ee=B(f),H=f.shares,de=ee==null&&f.manual_value==null&&H!=null&&H>1,L=!!c&&Ne,fe=de&&!L;return e.jsxs("div",{className:`flex flex-wrap items-center gap-3 rounded-lg border px-3 py-2.5 ${ee?"border-border/30 bg-foreground/[0.01] opacity-60":"border-border/50"}`,children:[e.jsx("input",{type:"checkbox",className:"accent-primary",disabled:ee!=null,checked:y.has(f.id),onChange:()=>ze(f.id)}),e.jsxs("span",{className:"flex-1 min-w-0",children:[e.jsx("span",{className:"block text-sm font-medium truncate",children:ot(f)??f.ticker_eod??f.id}),e.jsxs("span",{className:"block text-2xs text-muted-foreground tabular-nums",children:[f.ticker_eod??f.asset_kind,H!=null&&H>0?` · ${De(Ue(H),N)} ${i.shares}`:"",ee?` · ${oe(ee)}`:f.manual_value!=null?` · ${i.noteManualValued}`:""]})]}),y.has(f.id)&&de&&L&&e.jsx("span",{className:"text-2xs text-amber-600 dark:text-amber-400 shrink-0",children:i.crossAccountWholeOnly}),fe&&y.has(f.id)&&e.jsxs("span",{className:"flex items-center gap-1.5 shrink-0",children:[e.jsx(Io,{lang:b,min:0,max:H??void 0,decimals:8,value:Ci(Q[f.id]),onChange:ne=>{ve(),$(xe=>({...xe,[f.id]:ne==null?"":String(ne)}))},placeholder:i.sharesPlaceholder,className:"h-8 w-24 bg-card border-border/50 tabular-nums text-xs"}),e.jsxs("span",{className:"text-2xs text-muted-foreground tabular-nums whitespace-nowrap",children:[i.ofShares," ",De(Ue(H),N)]})]})]},f.id)})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-xs font-bold uppercase tracking-wider text-muted-foreground",children:i.targetLabel}),c&&c.accounts.length>1&&e.jsxs("div",{className:"space-y-1.5 pb-1",children:[e.jsx("p",{className:"text-2xs font-semibold uppercase tracking-wider text-muted-foreground/80",children:x.toAccount}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:c.accounts.map(f=>e.jsx("button",{type:"button",onClick:()=>{M(f.companyId),V(""),ve()},className:`rounded-full border px-2.5 py-1 text-2xs font-medium transition-colors ${w===f.companyId?"border-primary/60 bg-primary/10 text-foreground":"border-border/50 text-muted-foreground hover:border-border"}`,children:f.label},f.companyId))})]}),Xe.map(f=>e.jsxs("label",{className:`flex items-center gap-3 rounded-lg border px-3 py-2.5 cursor-pointer transition-colors ${O===f.portfolio_id?"border-primary/50 bg-primary/5":"border-border/50 hover:border-border"}`,children:[e.jsx("input",{type:"radio",name:"transfer-target",className:"accent-primary",checked:O===f.portfolio_id,onChange:()=>{V(f.portfolio_id),"companyId"in f&&M(f.companyId),ve()}}),e.jsx("span",{className:"flex-1 min-w-0 truncate text-sm font-medium",children:kt(f)}),c&&c.accounts.length>1&&"accountLabel"in f&&e.jsx("span",{className:"text-2xs text-muted-foreground/70 shrink-0",children:f.accountLabel}),e.jsx("span",{className:"tabular-nums text-2xs text-muted-foreground/60 shrink-0",children:f.portfolio_id})]},f.portfolio_id)),r==="split"&&tt&&e.jsxs(e.Fragment,{children:[e.jsxs("label",{className:`flex items-center gap-3 rounded-lg border px-3 py-2.5 cursor-pointer transition-colors ${ye?"border-primary/50 bg-primary/5":"border-border/50 hover:border-border"}`,children:[e.jsx("input",{type:"radio",name:"transfer-target",className:"accent-primary",checked:ye,onChange:()=>{V(ar),ve()}}),e.jsx("span",{className:"text-sm font-medium",children:i.newPortfolio})]}),ye&&e.jsxs("div",{className:"pl-8 space-y-1.5",children:[e.jsx(ct,{value:I,onChange:f=>T(f.target.value),placeholder:i.newPortfolioName,className:"bg-card border-border/50"}),e.jsx("p",{className:"text-2xs text-muted-foreground",children:i.newPortfolioHint})]})]})]}),Se&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-xs font-bold uppercase tracking-wider text-muted-foreground",children:i.profileLabel}),["target","source"].map(f=>e.jsxs("label",{className:`flex items-start gap-3 rounded-lg border px-3 py-2.5 cursor-pointer transition-colors ${Y===f?"border-primary/50 bg-primary/5":"border-border/50 hover:border-border"}`,children:[e.jsx("input",{type:"radio",name:"transfer-profile-source",className:"accent-primary mt-0.5",checked:Y===f,onChange:()=>{ae(f),ve()}}),e.jsxs("span",{className:"min-w-0",children:[e.jsx("span",{className:"block text-sm font-medium",children:f==="target"?i.profileTarget:i.profileSource}),e.jsx("span",{className:"block text-xs text-muted-foreground mt-0.5",children:f==="target"?i.profileTargetHint:i.profileSourceHint})]})]},f))]}),e.jsxs("p",{className:`flex items-start gap-2 rounded-lg border px-3 py-2.5 text-xs ${Se?"border-amber-500/30 bg-amber-500/[0.05] text-amber-700 dark:text-amber-400":"border-border/50 text-muted-foreground"}`,children:[e.jsx(wt,{size:13,className:"shrink-0 mt-0.5"})," ",$e]}
7)]}):e.jsxs("div",{className:"space-y-4",children:[c&&c.accounts.length>1&&D==null&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-xs font-bold uppercase tracking-wider text-muted-foreground",children:x.fromAccount}),c.accounts.map(f=>e.jsxs("button",{type:"button",onClick:()=>F(f.companyId),className:"w-full flex items-center gap-3 rounded-lg border border-border/50 hover:border-primary/50 hover:bg-primary/5 px-3 py-2.5 text-left transition-colors",children:[e.jsx("span",{className:"flex-1 min-w-0 truncate text-sm font-medium",children:f.label}),e.jsx(lt,{size:13,className:"text-primary shrink-0"})]},f.companyId))]}),(!c||c.accounts.length<=1||D!=null)&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-xs font-bold uppercase tracking-wider text-muted-foreground",children:i.sourceLabel}),e.jsx("p",{className:"text-xs text-muted-foreground/80",children:i.sourceHint}),Ge.length===0?e.jsx("p",{className:"text-sm text-muted-foreground py-2",children:i.noSources}):Ge.map(f=>e.jsxs("button",{type:"button",onClick:()=>v(f.portfolio_id),className:"w-full flex items-center gap-3 rounded-lg border border-border/50 hover:border-primary/50 hover:bg-primary/5 px-3 py-2.5 text-left transition-colors",children:[e.jsx("span",{className:"flex-1 min-w-0 truncate text-sm font-medium",children:kt(f)}),c&&c.accounts.length>1&&"accountLabel"in f&&e.jsx("span",{className:"text-2xs text-muted-foreground/70 shrink-0",children:f.accountLabel}),e.jsx("span",{className:"tabular-nums text-2xs text-muted-foreground/60 shrink-0",children:f.portfolio_id}),e.jsx(lt,{size:13,className:"text-primary shrink-0"})]},f.portfolio_id))]})]}),e.jsx(ms,{className:"gap-2 sm:gap-2",children:pe?e.jsx(ue,{onClick:()=>s(!1),children:i.close}):e.jsxs(e.Fragment,{children:[e.jsx(ue,{variant:"ghost",onClick:ge,disabled:k==="run",children:le}),P&&!Me&&R.length>0&&e.jsx(ue,{onClick:ht,disabled:k!=null||!O||!Se&&y.size===0,children:k==="preview"?e.jsxs(e.Fragment,{children:[e.jsx(rt,{withMargin:!0})," ",i.previewing]}):i.preview}),Me&&(A?!Z&&e.jsx(ue,{onClick:nt,disabled:k!=null,children:k==="run"?e.jsxs(e.Fragment,{children:[e.jsx(rt,{withMargin:!0})," ",i.running]}):i.confirmMerge}):e.jsx(ue,{onClick:at,disabled:k!=null||(J??[]).every(f=>!!f.blocked),children:k==="run"?e.jsxs(e.Fragment,{children:[e.jsx(rt,{withMargin:!0})," ",i.running]}):i.confirmMove}))]})})]})})},Ti={de:{title:"In anderes Portfolio verschieben",desc:"Die Position zieht komplett um. Ihre Watchtower-Einstellungen, offene Wiedervorlagen und das Dividenden-Log ziehen mit.",noCandidates:"Es gibt kein zweites aktives Portfolio, in das diese Position ziehen könnte.",targetLabel:"Zielportfolio",cancel:"Abbrechen",close:"SchlieÃen",confirm:"Verschieben",moving:"Wird verschoben...",success:"Position verschoben",preview:"Vorschau",previewing:"Wird geprüft...",confirmCross:"Bestätigen und verschieben",previewReviews:"Offene Wiedervorlagen",previewDividends:"Dividenden-Log-Einträge",previewWatchtower:"Watchtower-Einstellungen",errConflict:'Das Zielportfolio hält diesen Titel bereits. Zwei Positionen zusammenzurechnen ist ein Zusammenführen, nicht ein Verschieben: nutze dafür "Zusammenführen" auf dem Portfolio.',errNoop:"Die Position liegt bereits in diesem Portfolio.",errDenied:"Dafür fehlen dir die Rechte.",errTargetNotFound:"Das Zielportfolio wurde nicht gefunden.",errNotDeployed:"Diese Funktion ist noch nicht verfügbar.",errFailed:"Das hat nicht geklappt. Bitte versuche es später erneut."},en:{title:"Move to another portfolio",desc:"The whole position moves. Its Watchtower tuning, pending review reminders and dividend log travel with it.",noCandidates:"There is no second active portfolio for this position to move into.",targetLabel:"Target portfolio",cancel:"Cancel",close:"Close",confirm:"Move",moving:"Moving...",success:"Position moved",preview:"Preview",previewing:"Checking...",confirmCross:"Confirm and move",previewReviews:"Pending review reminders",previewDividends:"Dividend log entries",previewWatchtower:"Watchtower settings",errConflict:'The target portfolio already holds this security. Combining two positions is a merge, not a move: use "Merge" on the portfolio instead.',errNoop:"The position is already in that portfolio.",errDenied:"You do not have permission for this.",errTargetNotFound:"Target portfolio not found.",errNotDeployed:"This feature is not available yet.",errFailed:"That did not work. Please try again later."}},Li=t=>{var s;return((s=t.portfolio_name)==null?void 0:s.trim())||t.portfolio_id},Ai=t=>{var s;return((s=t.portfolio_name)==null?void 0:s.trim())||t.portfolio_id};function Ei(t){if(t.reason==="conflict")return"conflict";if(t.reason==="noop")return"noop";if(t.reason==="denied")return"denied";const s=t.message??"";return/function .*move_portfolio_asset|PGRST202|does not exist/i.test(s)?"not_deployed":/target_not_found
7/i.test(s)?"target_not_found":"failed"}function Ii(t){const s=t??{},r=s.payload??{},l=r.child_rows??r.counts??{},o=l.review_reminders??l.reviews,m=l.dividend_log??l.dividends,n=r.config??r.config_decision,h=r.warnings??s.warnings,c=(Array.isArray(h)?h:[]).some(a=>{const b=typeof a=="string"?a:a==null?void 0:a.code;return typeof b=="string"&&/position_limit|(?:^|\D)20(?:\D|$)/i.test(b)});return{reviewCount:typeof o=="number"?o:null,dividendCount:typeof m=="number"?m:null,configDecision:typeof n=="string"?n:null,hasLimitWarning:c}}const Di=({open:t,onOpenChange:s,position:r,candidates:l,language:o,onMoved:m,scope:n})=>{const h=St(o),p=Ti[h],c=Qr[h],[a,b]=g.useState(""),[i,x]=g.useState(!1),[N,S]=g.useState(null),[P,v]=g.useState(null),[y,E]=g.useState(!1),[Q,$]=g.useState(null);g.useEffect(()=>{t&&(b(n?"":l.length===1?l[0].portfolio_id:""),x(!1),S(null),v(null),E(!1),$(null))},[t,l,n]);const O=k=>k==="conflict"?p.errConflict:k==="noop"?p.errNoop:k==="denied"?p.errDenied:k==="target_not_found"?p.errTargetNotFound:k==="not_deployed"?p.errNotDeployed:p.errFailed,V=k=>{b(k),S(null),v(null),$(null)},D=n?dt(n,(r==null?void 0:r.sourcePortfolioId)??null):null,F=n?dt(n,a||null):null,w=!n||uo(D,F),M=!!n&&co(D,F),I=n?lo(n,(r==null?void 0:r.sourcePortfolioId)??null):[],T=n?[...n.accounts].filter(k=>I.some(q=>q.companyId===k.companyId)).sort((k,q)=>Number(q.isSelf)-Number(k.isSelf)):[],Y=T.length>1,ae=n?I.length===0:l.length===0,J=!!D&&!!F&&D.companyId!==F.companyId,W=async()=>{if(!(!r||!a||i)){x(!0),S(null);try{const k=await Gr(Ee,{assetId:r.assetId,sourcePortfolioId:r.sourcePortfolioId,targetPortfolioId:a,tickerEod:r.tickerEod??"",stockName:r.stockName,isOwned:(r.shares??0)>0});if(!k.ok){S(Ei(k));return}te.success(p.success),s(!1),await m()}finally{x(!1)}}},A=async()=>{if(!(!r||!a||i)){x(!0),v(null);try{const k=await os({source_portfolio_id:r.sourcePortfolioId,target_portfolio_id:a,asset_id:r.assetId});if(k.ok===!1){v({code:k.code,message:k.message});return}te.success(p.success),s(!1),await m()}finally{x(!1)}}},z=async()=>{if(!(!r||!a||y)){E(!0),v(null),$(null);try{const k=await Zr({source_portfolio_id:r.sourcePortfolioId,target_portfolio_id:a,asset_id:r.assetId});if(k.ok===!1){v({code:k.code,message:k.message});return}$(k.data)}finally{E(!1)}}},Z=async()=>{if(!(!r||!a||i)){x(!0),v(null);try{const k=await os({source_portfolio_id:r.sourcePortfolioId,target_portfolio_id:a,asset_id:r.assetId});if(k.ok===!1){v({code:k.code,message:k.message});return}te.success(p.success),s(!1),await m()}finally{x(!1)}}},re=(P==null?void 0:P.code)==="op_not_enabled",pe=P?Be(P.code,h):N?O(N):null,C=Ii(Q);return e.jsx(as,{open:t,onOpenChange:s,children:e.jsxs(is,{className:"max-w-md",children:[e.jsxs(ls,{children:[e.jsx(cs,{children:p.title}),e.jsxs(ds,{children:[r&&e.jsxs("span",{className:"block font-medium text-foreground mb-1",children:[r.label,r.tickerEod?e.jsx("span",{className:"tabular-nums text-xs text-primary/70 ml-2",children:r.tickerEod}):null]}),M?e.jsxs("span",{className:"block space-y-1 mt-1",children:[e.jsx("span",{className:"block",children:c.alertRetuneNotice}),e.jsx("span",{className:"block text-xs text-muted-foreground/80",children:c.auditNotice}),e.jsx("span",{className:"block text-xs text-muted-foreground/80",children:c.briefingNotTransferred})]}):p.desc]})]}),ae?e.jsx("p",{className:"text-sm text-muted-foreground py-2",children:p.noCandidates}):n?e.jsxs("div",{className:"space-y-3",children:[e.jsx("p",{className:"text-xs font-bold uppercase tracking-wider text-muted-foreground",children:Y?c.accountLabel:c.portfolioLabel}),T.map(k=>e.jsxs("div",{className:"space-y-1.5",children:[Y&&e.jsx("p",{className:"text-xs font-semibold text-primary/80 pl-1",children:k.label}),I.filter(q=>q.companyId===k.companyId).map(q=>e.jsxs("label",{className:`flex items-center gap-3 rounded-lg border px-3 py-2.5 cursor-pointer transition-colors ${a===q.portfolio_id?"border-primary/50 bg-primary/5":"border-border/50 hover:border-border"}`,children:[e.jsx("input",{type:"radio",name:"move-position-target",className:"accent-primary",checked:a===q.portfolio_id,onChange:()=>V(q.portfolio_id)}),e.jsx("span",{className:"flex-1 min-w-0 truncate text-sm font-medium",children:Ai(q)}),e.jsx("span",{className:"tabular-nums text-xs text-muted-foreground
7/60 shrink-0",children:q.portfolio_id})]},q.portfolio_id))]},k.companyId)),r&&a&&e.jsxs("div",{className:"text-xs text-muted-foreground pt-1 space-y-1",children:[J&&D&&F&&e.jsxs("p",{className:"text-2xs text-muted-foreground/60",children:[c.fromAccount,": ",D.accountLabel,"  â ",c.toAccount,": ",F.accountLabel]}),e.jsxs("p",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"tabular-nums",children:r.sourcePortfolioId}),e.jsx(lt,{size:13,className:"text-primary shrink-0"}),e.jsx("span",{className:"tabular-nums",children:a})]})]}),M&&Q&&e.jsxs("div",{className:"rounded-lg border border-primary/30 bg-primary/[0.04] p-3 space-y-1.5 text-xs",children:[e.jsx("span",{className:"inline-block rounded-full bg-primary/15 text-primary px-2 py-0.5 text-2xs font-bold uppercase tracking-wide",children:c.crossBadge}),C.reviewCount!=null&&e.jsxs("p",{className:"text-muted-foreground",children:[p.previewReviews,": ",e.jsx("span",{className:"font-medium text-foreground",children:C.reviewCount})]}),C.dividendCount!=null&&e.jsxs("p",{className:"text-muted-foreground",children:[p.previewDividends,": ",e.jsx("span",{className:"font-medium text-foreground",children:C.dividendCount})]}),C.configDecision&&e.jsxs("p",{className:"text-muted-foreground",children:[p.previewWatchtower,": ",e.jsx("span",{className:"font-medium text-foreground",children:C.configDecision})]}),C.hasLimitWarning&&e.jsxs("p",{className:"flex items-start gap-2 text-amber-600 dark:text-amber-400",children:[e.jsx(Fe,{size:12,className:"shrink-0 mt-0.5"}),e.jsx("span",{children:c.limitWarnCrossing20})]})]}),pe&&e.jsxs("p",{className:`flex items-start gap-2 rounded-lg border p-3 text-xs mt-2 ${re?"border-muted-foreground/30 bg-muted/40 text-muted-foreground":"border-destructive/40 bg-destructive/[0.06] text-destructive"}`,children:[re?e.jsx(wt,{size:13,className:"shrink-0 mt-0.5"}):e.jsx(Fe,{size:13,className:"shrink-0 mt-0.5"}),e.jsx("span",{children:pe})]})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-xs font-bold uppercase tracking-wider text-muted-foreground",children:p.targetLabel}),l.map(k=>e.jsxs("label",{className:`flex items-center gap-3 rounded-lg border px-3 py-2.5 cursor-pointer transition-colors ${a===k.portfolio_id?"border-primary/50 bg-primary/5":"border-border/50 hover:border-border"}`,children:[e.jsx("input",{type:"radio",name:"move-position-target",className:"accent-primary",checked:a===k.portfolio_id,onChange:()=>{b(k.portfolio_id),S(null)}}),e.jsx("span",{className:"flex-1 min-w-0 truncate text-sm font-medium",children:Li(k)}),e.jsx("span",{className:"tabular-nums text-xs text-muted-foreground/60 shrink-0",children:k.portfolio_id})]},k.portfolio_id)),r&&a&&e.jsxs("p",{className:"flex items-center gap-2 text-xs text-muted-foreground pt-1",children:[e.jsx("span",{className:"tabular-nums",children:r.sourcePortfolioId}),e.jsx(lt,{size:13,className:"text-primary shrink-0"}),e.jsx("span",{className:"tabular-nums",children:a})]}),pe&&e.jsxs("p",{className:"flex items-start gap-2 rounded-lg border border-destructive/40 bg-destructive/[0.06] p-3 text-xs text-destructive mt-2",children:[e.jsx(Fe,{size:13,className:"shrink-0 mt-0.5"}),e.jsx("span",{children:pe})]})]}),e.jsxs(ms,{className:"gap-2 sm:gap-2",children:[e.jsx(ue,{variant:"ghost",onClick:()=>s(!1),disabled:i||y,children:ae?p.close:p.cancel}),!ae&&(w?e.jsx(ue,{onClick:W,disabled:!a||i,children:i?e.jsxs(e.Fragment,{children:[e.jsx(rt,{withMargin:!0})," ",p.moving]}):p.confirm}):M?Q?e.jsx(ue,{onClick:Z,disabled:i,children:i?e.jsxs(e.Fragment,{children:[e.jsx(rt,{withMargin:!0})," ",p.moving]}):p.confirmCross}):e.jsx(ue,{onClick:z,disabled:!a||y,children:y?e.jsxs(e.Fragment,{children:[e.jsx(rt,{withMargin:!0})," ",p.previewing]}):p.preview}):e.jsx(ue,{onClick:A,disabled:!a||i,children:i?e.jsxs(e.Fragment,{children:[e.jsx(rt,{withMargin:!0})," ",p.moving]}):p.confirm}))]})]})})},Mi={de:{title:"Portfolio hinzufügen",desc:"Für wen soll das Portfolio angelegt werden?",own:"Mein Portfolio",ownHint:"Ãffnet den Assistenten für dein eigenes Konto.",clients:"Für einen Mandanten",clientsHint:"Ãffnet denselben Assistenten, legt das Portfolio aber im Konto des Mandanten an.",noClients:"Es sind keine Mandanten hinterlegt.",pickClient:"Wähle einen Mandanten aus.",cancel:"Abbrechen",next:"Weiter"},en:{title:"Add portfolio",desc:"Who is this portfolio for?",own:"My portfolio",ownHint:"Opens the wizard for your own account.",clients:"For a client",clientsHint:"Opens the same wizard, but creates the portfolio in the client account.",noClients:"No clients on file.",pickClient:"Select a client.",cancel:"Cancel",next:"Continue"}},$i=({open:t,onOpenChange:s,clients:r,language:l,onGoToWizard:o})=>{const m=St(l),n=Mi[m],[h,p]=g.useState("own"),[c,a]=g.useState(null),[b,i]=g.useState(null);g.useEffect(()=>{t&&(p("own"),a(r.length===1?r[0].companyId:null),i(null))},[t,r]);const x=()=>
7{if(h==="own"){s(!1),o(null);return}if(c==null){i(n.pickClient);return}s(!1),o(c)};return e.jsx(as,{open:t,onOpenChange:s,children:e.jsxs(is,{className:"max-w-lg max-h-[85vh] overflow-y-auto",children:[e.jsxs(ls,{children:[e.jsx(cs,{children:n.title}),e.jsx(ds,{children:n.desc})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("label",{className:`flex items-start gap-3 rounded-lg border px-3 py-2.5 cursor-pointer transition-colors ${h==="own"?"border-primary/50 bg-primary/5":"border-border/50 hover:border-border"}`,children:[e.jsx("input",{type:"radio",name:"add-portfolio-for-whom",className:"accent-primary mt-1",checked:h==="own",onChange:()=>{p("own"),i(null)}}),e.jsx(Yr,{size:15,className:"mt-0.5 shrink-0 text-primary"}),e.jsxs("span",{className:"min-w-0",children:[e.jsx("span",{className:"block text-sm font-medium",children:n.own}),e.jsx("span",{className:"block text-xs text-muted-foreground mt-0.5",children:n.ownHint})]})]}),e.jsxs("label",{className:`flex items-start gap-3 rounded-lg border px-3 py-2.5 transition-colors ${r.length===0?"border-border/30 opacity-60":h==="client"?"border-primary/50 bg-primary/5 curs
7or-pointer":"border-border/50 hover:border-border cursor-pointer"}`,children:[e.jsx("input",{type:"radio",name:"add-portfolio-for-whom",className:"accent-primary mt-1",disabled:r.length===0,checked:h==="client",onChange:()=>{p("client"),i(null)}}),e.jsx(Xr,{size:15,className:"mt-0.5 shrink-0 text-primary"}),e.jsxs("span",{className:"min-w-0",children:[e.jsx("span",{className:"block text-sm font-medium",children:n.clients}),e.jsx("span",{className:"block text-xs text-muted-foreground mt-0.5",children:r.length===0?n.noClients:n.clientsHint})]})]}),h==="client"&&r.length>0&&e.jsx("div",{className:"space-y-2 pl-3 border-l-2 border-primary/20",children:r.map(N=>e.jsxs("label",{className:"flex items-center gap-3 text-sm cursor-pointer",children:[e.jsx("input",{type:"radio",name:"add-portfolio-client",className:"accent-primary",checked:c===N.companyId,onChange:()=>{a(N.companyId),i(null)}}),e.jsx("span",{className:"truncate",children:N.label})]},N.companyId))}),b&&e.jsxs("p",{className:"flex items-start gap-1.5 text-xs text-amber-600 dark:text-amber-400",children:[e.jsx(wt,{size:12,className:"shrink-0 mt-0.5"})," ",b]})]}),e.jsxs(ms,{className:"gap-2 sm:gap-2",children:[e.jsx(ue,{variant:"ghost",onClick:()=>s(!1),children:n.cancel}),e.jsx(ue,{onClick:x,children:n.next})]})]})})},ir={de:{title:"Anlagestrategie",readOnly:"nur Lesen",philosophy:"Anlagephilosophie",buyBox:"Buy Box Trigger",noiseFilter:"Rauschfilter",empty:"Nicht hinterlegt",none:"Für dieses Portfolio ist noch keine Anlagestrategie hinterlegt.",edit:"Bearbeiten",save:"Speichern",cancel:"Abbrechen",saved:"Anlagestrategie gespeichert",saveError:"Anlagestrategie konnte nicht gespeichert werden",philosophyPlaceholder:"Wie investiert diese Person?",triggerPlaceholder:"Was muss zutreffen, damit gekauft wird?",noisePlaceholder:"Was soll ausgeblendet werden?",notSetScale:"nicht gesetzt",scales:{data_granularity:["Detailtiefe","Nur das Wichtigste","Alle Details"],action_frequency:["Handlungsfrequenz","Selten handeln","Oft handeln"],decision_logic:["Entscheidungslogik","Bauchgefühl","Streng datenbasiert"],risk_appetite:["Risikobereitschaft","Vorsichtig","Risikofreudig"]}},en:{title:"Investment strategy",readOnly:"read-only",philosophy:"Investment philosophy",buyBox:"Buy Box Triggers",noiseFilter:"Noise filter",empty:"Not set",none:"No investment strategy has been recorded for this portfolio yet.",edit:"Edit",save:"Save",cancel:"Cancel",saved:"Investment strategy saved",saveError:"Could not save the investment strategy",philosophyPlaceholder:"How does this person invest?",triggerPlaceholder:"What has to be true before buying?",noisePlaceholder:"What should be filtered out?",notSetScale:"not set",scales:{data_granularity:["Data granularity","Just the essentials","Every detail"],action_frequency:["Action frequency","Act rarely","Act often"],decision_logic:["Decision logic","Gut feel","Strictly data-driven"],risk_appetite:["Risk appetite","Cautious","Risk-seeking"]}}},Zt=["data_granularity","action_frequency","decision_logic","risk_appetite"],lr=({label:t,value:s,emptyLabel:r,muted:l})=>e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-base font-semibold text-foreground flex items-center gap-2",children:t}),s!=null&&s.trim()?e.jsx("p",{className:`text-sm leading-relaxed ${l?"text-muted-foreground":"text-foreground"}`,children:s}):e.jsx("p",{className:"text-sm text-muted-foreground/30 italic",children:r})]}),Fi=({title:t,low:s,high:r,value:l})=>e.jsxs("div",{className:"p-3 rounded-xl border border-border/50 bg-card",children:[e.jsxs("div",{className:"flex items-center justify-between mb-1.5",children:[e.jsx("span",{className:"text-sm text-foreground",children:t}),e.jsxs("span",{className:"text-xs tabular-nums text-primary",children:[l??"â",l!=null?" / 5":""]})]}),e.jsx("div",{className:"flex items-center gap-1",children:[1,2,3,4,5].map(o=>e.jsx("div",{className:`h-1.5 flex-1 rounded-full ${l!=null&&o<=l?"bg-primary":"bg-foreground
7/10"}`},o))}),e.jsxs("div",{className:"flex items-center justify-between mt-1",children:[e.jsx("span",{className:"text-2xs text-muted-foreground/60",children:s}),e.jsx("span",{className:"text-2xs text-muted-foreground/60",children:r})]})]}),cr=t=>({investment_philosophy:t.investment_philosophy??"",buy_box_trigger_1:t.buy_box_trigger_1??"",buy_box_trigger_2:t.buy_box_trigger_2??"",buy_box_trigger_3:t.buy_box_trigger_3??"",noise_filter:t.noise_filter??"",data_granularity:t.data_granularity??null,action_frequency:t.action_frequency??null,decision_logic:t.decision_logic??null,risk_appetite:t.risk_appetite??null}),zi=({title:t,low:s,high:r,notSet:l,value:o,onChange:m})=>e.jsxs("div",{className:"p-3 rounded-xl border border-border/50 bg-card",children:[e.jsxs("div",{className:"flex items-center justify-between mb-1.5",children:[e.jsx("span",{className:"text-sm text-foreground",children:t}),e.jsxs("span",{className:"text-xs tabular-nums text-primary",children:[o??l,o!=null?" / 5":""]})]}),e.jsx("div",{className:"flex items-center gap-1",children:[1,2,3,4,5].map(n=>e.jsx("button",{type:"button","aria-label":`${t}: ${n}`,onClick:()=>m(o===n?null:n),className:`h-3 flex-1 rounded-full transition-colors ${o!=null&&n<=o?"bg-primary":"bg-foreground
7/10 hover:bg-foreground/25"}`},n))}),e.jsxs("div",{className:"flex items-center justify-between mt-1",children:[e.jsx("span",{className:"text-2xs text-muted-foreground/60",children:s}),e.jsx("span",{className:"text-2xs text-muted-foreground/60",children:r})]})]}),mo=({portfolio:t,language:s,onSave:r})=>{var S,P;const l=ir[s]??ir.de,[o,m]=g.useState(!1),[n,h]=g.useState(!1),[p,c]=g.useState(()=>cr(t)),a=()=>{c(cr(t)),m(!0)},b=(v,y)=>c(E=>({...E,[v]:y})),i=async()=>{if(r){h(!0);try{await r(p)&&m(!1)}finally{h(!1)}}},x=[t.buy_box_trigger_1,t.buy_box_trigger_2,t.buy_box_trigger_3].filter(v=>!!(v!=null&&v.trim())),N=!!((S=t.investment_philosophy)!=null&&S.trim())||!!((P=t.noise_filter)!=null&&P.trim())||x.length>0||Zt.some(v=>t[v]!=null);return o?e.jsxs("div",{className:"mt-6 pt-6 border-t border-border/30",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2 mb-4",children:[e.jsx("h3",{className:"text-lg font-semibold text-foreground",children:l.title}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ue,{size:"sm",variant:"ghost",disabled:n,onClick:()=>m(!1),children:l.cancel}),e.jsxs(ue,{size:"sm",disabled:n,onClick:()=>void i(),children:[n?e.jsx(zt,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}):e.jsx(us,{className:"h-3.5 w-3.5 mr-1.5"}),l.save]})]})]}),e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-base font-semibold text-foreground",children:l.philosophy}),e.jsx(qs,{value:p.investment_philosophy,onChange:v=>b("investment_philosophy",v.target.value),placeholder:l.philosophyPlaceholder,maxLength:4e3,rows:3,className:"text-sm"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-base font-semibold text-foreground",children:l.buyBox}),[1,2,3].map(v=>e.jsx(ct,{value:p[`buy_box_trigger_${v}`],onChange:y=>b(`buy_box_trigger_${v}`,y.target.value),placeholder:`${l.triggerPlaceholder} (${v})`,maxLength:1e3,className:"h-9 text-sm"},v))]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-base font-semibold text-foreground",children:l.noiseFilter}),e.jsx(qs,{value:p.noise_filter,onChange:v=>b("noise_filter",v.target.value),placeholder:l.noisePlaceholder,maxLength:4e3,rows:2,className:"text-sm"})]}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:Zt.map(v=>{const[y,E,Q]=l.scales[v];return e.jsx(zi,{title:y,low:E,high:Q,notSet:l.notSetScale,value:p[v],onChange:$=>b(v,$)},v)})})]})]}):e.jsxs("div",{className:"mt-6 pt-6 border-t border-border/30",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[e.jsx("h3",{className:"text-lg font-semibold text-foreground flex items-center gap-2",children:l.title}),r?e.jsxs(ue,{size:"sm",variant:"ghost",className:"ml-auto h-7 px-2 text-xs",onClick:a,children:[e.jsx(Jr,{className:"h-3 w-3 mr-1.5"})," ",l.edit]}):e.jsxs("span",{className:"inline-flex items-center gap-1 text-2xs tabular-nums uppercase tracking-wider text-muted-foreground/60 border border-border/50 rounded px-1.5 py-0.5",children:[e.jsx(Do,{size:9})," ",l.readOnly]})]}),N?e.jsxs("div",{className:"space-y-5",children:[e.jsx(lr,{label:l.philosophy,value:t.investment_philosophy,emptyLabel:l.empty}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-base font-semibold text-foreground flex items-center gap-2",children:l.buyBox}),x.length>0?e.jsx("ul",{className:"space-y-1.5",children:x.map((v,y)=>e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"mt-2 w-1.5 h-1.5 rounded-full bg-primary shrink-0"}),e.jsx("p",{className:"text-sm text-foreground leading-relaxed flex-1",children:v})]},y))}):e.jsx("p",{className:"text-sm text-muted-foreground/30 italic",children:l.empty})]}),e.jsx(lr,{label:l.noiseFilter,value:t.noise_filter,emptyLabel:l.empty,muted:!0}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:Zt.map(v=>{const[y,E,Q]=l.scales[v];return e.jsx(Fi,{title:y,low:E,high:Q,value:t[v]},v)})})]}):e.jsx("p",{className:"text-sm text-muted-foreground/50 italic",children:l.none})]})},dr={de:{shares:"Stückzahl",sharesOz:"Unzen (oz)",avgCost:"à K
7aufkurs",thesis:"These",save:"Speichern",remove:"Position entfernen",invalid:"Ungueltige Zahl",readAs:"Gelesen als",sharesUnit:"Stück"},en:{shares:"Shares",sharesOz:"Ounces (oz)",avgCost:"Avg. cost",thesis:"Thesis",save:"Save",remove:"Remove position",invalid:"Invalid number",readAs:"Read as",sharesUnit:"shares"}},Mt=(t,s)=>{if(t.trim()==="")return null;const r=eo(t,s);return r!==null&&r>=0?r:void 0},Ri=({asset:t,language:s,saving:r,onSave:l,onRemove:o})=>{const m=dr[s]??dr.de,n=s==="en"?"en":"de",h=g.useId(),p=g.useId(),c=ra(t.ticker_eod),a=(t.asset_kind??"listed")==="listed",[b,i]=g.useState(()=>Zs(oa(t.ticker_eod,t.shares),n)),[x,N]=g.useState(()=>Zs(na(t.ticker_eod,t.avg_cost),n)),[S,P]=g.useState(t.owner_comment??""),[v,y]=g.useState(null);Ca(n,(D,F)=>{i(w=>Qs(w,D,F)),N(w=>Qs(w,D,F))});const E=async()=>{if(!a){await l({shares:t.shares,avg_cost:t.avg_cost,avg_cost_currency:null,owner_comment:S.trim()||null});return}const D=Mt(b,n),F=Mt(x,n);if(D===void 0||F===void 0){y(m.invalid);return}y(null),await l({shares:ia(t.ticker_eod,D),avg_cost:la(t.ticker_eod,F),avg_cost_currency:"EUR",owner_comment:S.trim()||null})},Q=Ys(b)?Mt(b,n):null,$=Ys(x)?Mt(x,n):null,O=Q!=null?`${m.readAs} ${Xs(Q,n,{unit:c?"oz":m.sharesUnit})}`:null,V=$!=null?`${m.readAs} ${Xs($,n,{currency:"EUR",unit:c?"oz":void 0})}`:null;return e.jsxs("div",{className:"mt-2 pt-3 border-t border-border/10 space-y-2",children:[a?e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-2",children:[e.jsxs("div",{children:[e.jsx(ct,{type:"text",value:b,onChange:D=>i(D.target.value),placeholder:c?m.sharesOz:m.shares,inputMode:"decimal","aria-describedby":O?h:void 0,className:"h-9 text-sm tabular-nums"}),O&&e.jsx("p",{id:h,className:"mt-1 text-xs text-muted-foreground tabular-nums",children:O})]}),e.jsxs("div",{children:[e.jsx(ct,{type:"text",value:x,onChange:D=>N(D.target.value),placeholder:`${m.avgCost} (${aa(t.ticker_eod)})`,inputMode:"decimal","aria-describedby":V?p:void 0,className:"h-9 text-sm tabular-nums"}),V&&e.jsx("p",{id:p,className:"mt-1 text-xs text-muted-foreground tabular-nums",children:V})]}),e.jsx(ct,{value:S,onChange:D=>P(D.target.value),placeholder:m.thesis,maxLength:500,className:"h-9 text-sm"})]}):e.jsx(ct,{value:S,onChange:D=>P(D.target.value),placeholder:m.thesis,maxLength:500,className:"h-9 text-sm"}),v&&e.jsx("p",{className:"text-xs text-destructive",children:v}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ue,{size:"sm",onClick:E,disabled:r,children:r?e.jsxs(e.Fragment,{children:[e.jsx(zt,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"})," ",m.save]}):e.jsxs(e.Fragment,{children:[e.jsx(us,{className:"h-3.5 w-3.5 mr-1.5"})," ",m.save]})}),e.jsxs(ue,{size:"sm",variant:"ghost",onClick:o,disabled:r,className:"text-muted-foreground hover:text-destructive",children:[e.jsx(_s,{className:"h-3.5 w-3.5 mr-1.5"})," ",m.remove]})]})]})};function Oi(t,s){return Number.isFinite(t)?Math.abs(t)>=1?Pr(t,s,{decimals:2,symbol:"none"}):t.toLocaleString(Mo(s),{maximumSignificantDigits:6}):"-"}const ns={de:{position:"Position",positions:"Positionen",totalValue:"Gesamtwert",stock:"Wertpapier",priceValue:"Kurs / Wert",vsQuarter:"Î Vorquartal",vsYear:"Î Vorjahr",value:"Wert",thesis:"These",noThesis:"Keine These hinterlegt",noLivePrice:"Kein Live-Kurs verfügbar",noLivePriceLabel:"kein Kurs",noPositions:"Keine Positionen",addedByManager:"von dir hinzugefügt",edit:"Bearbeiten",cancel:"Abbrechen",options:"Optionen",merge:"Zusammenführen",split:"Aufteilen",archive:"Archivieren",unarchive:"Aktivieren",delete:"Löschen",deleteTitle:"Portfolio von {name} löschen?",deleteBody:'â{portfolio}" von {name} und alle {n} Position(en) werden dauerhaft gelöscht. Das kann nicht rueckgaengig gemacht werden. Zum Aufheben stattdessen archivieren.',deleteConfirm:"Endgueltig löschen",archived:"Archiviert",notValued:"Sachwert ohne hinterlegte Bewertung",notValuedLabel:"nicht bewertet",valuedOn:"Bewertet am",priceAsOf:"Kurs vom",priceOld:`Kurs älter als ${Bs} Tage`,briefingFullHint:"Alle Briefing-Plätze belegt",briefingUpgrade:"Paket erweitern",briefingGenericError:"Ãnderung konnte nicht gespeichert werden",enrichData:"Daten anreichern",enrichUnavailable:"Für Mandanten noch nicht verfügbar",enriching:"Kurse werden geladen...",move:"Verschieben",moveTitle:"In anderes Portfolio verschieben"},en:{position:"position",positions:"positions",totalValue:"Total value",stock:"Stock",priceValue:"Price / Value",vsQuarter:"Î last quarter",vsYear:"Î last year",value:"Value",thesis:"Thesis",noThesis:"No thesis recorded",noLivePrice:"No live price available",noLivePriceLabel:"no price",noPositions:"No positions",addedByManager:"added by you",edit:"Edit",cancel:"Cancel",options:"Options",merge:"Merge",split:"Split",archive:"Archive",unarchive:"Activate",delete:"Delete",deleteTitle:"Delete {name}'s portfolio?",deleteBody:'"{portfolio}" belonging to {name} and all {n} position(s) will be permanently deleted. This cannot be undone. Archive instead if it may be wanted back.',deleteConfirm:"Delete permanently",archived:"Archived",notValued:"Non-listed asset without a valuation on file",notValuedLabel:"not valued",valuedOn:"Valued on",priceAsOf:"Price as of",priceOld:`Price older than ${Bs} days`,briefingFullHint:"All briefing slots in use",briefingUpgrade:"Upgrade plan",briefingGenericError:"Could not save the change",enrichData:"Enrich data",enrichUnavailable:"Not available for client portfolios yet",enriching:"Loading prices...",move:"Move",moveTitle:"Move to another portfolio"}},ur=({delta:t})=>t?e.jsx("span",{className:t.isPositive?"data-delta-positive":t.isNegative?"data-delta-negative":"text-muted-foreground tabular-nums text-sm",children:t.formatted}
7):e.jsx("span",{className:"text-muted-foreground/40 tabular-nums text-sm",children:"â"}),Bi=({portfolio:t,assets:s,rates:r,language:l,actionSlot:o,memberName:m,isEditing:n,onToggleEdit:h,onArchive:p,onUnarchive:c,onDelete:a,onMerge:b,onSplit:i,busy:x,edit:N,isSelf:S,briefingUsed:P,briefingQuota:v,onBriefingChanged:y,positions:E,onEnrich:Q,enriching:$,onSaveStrategy:O})=>{const[V,D]=g.useState(!1),F=t.portfolio_id,w=t.portfolio_name,[M,I]=g.useState(!1),T=ns[l]??ns.de,Y=et(),ae=Ct(),J=F.split("-")[1]||"A",W=t.product_status==="archived",A=C=>C.split("{name}").join(m??"").split("{portfolio}").join(w||"Portfolio").split("{n}").join(String(s.length)),{totalEur:z,excludedCount:Z}=g.useMemo(()=>Zn(s.map(C=>Oe(C,r))),[s,r]),re=g.useMemo(()=>Xn(s),[s]),pe=g.useMemo(()=>s.map(C=>{var k;return{id:C.id,ticker_eod:C.ticker_eod,ticker:((k=C.ticker_eod)==null?void 0:k.split(".")[0])??null,stock_name:C.stock_name||C.ticker_eod||"",shares:C.shares,avg_cost:C.avg_cost,current_price:C.current_price,sector:C.sector,industry:C.industry,country_name:C.country_name,currency:C.currency,logo_url:C.logo_url}}),[s]);return e.jsxs(Na,{open:M,onOpenChange:I,className:"mb-6 last:mb-0",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4 pb-4 border-b border-border/50",children:[e.jsxs("div",{className:"flex items-center gap-3 group text-left flex-1 min-w-0
7w-full sm:w-auto",children:[e.jsx(Gs,{asChild:!0,children:e.jsx("button",{className:"flex items-center gap-3 shrink-0",children:e.jsx("div",{className:"w-8 h-8 rounded-lg bg-primary/10 flex items-center justify-center shrink-0 group-hover:bg-primary/20 transition-colors font-serif italic text-primary font-semibold",children:J})})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx(Gs,{asChild:!0,children:e.jsx("button",{className:"text-left w-full",children:e.jsx("h3",{className:"text-xl font-semibold truncate hover:text-primary transition-colors",children:w||"Portfolio"})})}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5 flex items-center flex-wrap gap-x-3 gap-y-1",children:[e.jsxs("span",{children:[s.length," ",s.length===1?T.position:T.positions]}),z>0&&e.jsxs("span",{className:"tabular-nums bg-primary/10 text-primary px-1.5 py-0.5 rounded",children:[T.totalValue,": ",Ve(ut(z,ae).text,Y)]}),re&&e.jsxs("span",{className:`tabular-nums ${re.isPositive?"text-emerald-500":re.isNegative?"text-rose-500":""}`,children:["Ã ",re.formatted]}),Z>0&&e.jsxs("span",{className:"flex items-center gap-1 text-amber-600 dark:text-amber-400",children:[e.jsx(mt,{size:11,className:"shrink-0"}),Jn(Z,l==="en"?"en":"de")]})]})]})]}),(h||p||c||a||b||i||!W&&!Qe(F))&&e.jsxs("div",{className:"flex items-center gap-2 shrink-0 self-start sm:self-auto w-full sm:w-auto justify-end",children:[!W&&!Qe(F)&&e.jsx(zr,{subscribed:!!t.subscribed_portfolio_briefing}),!W&&!Qe(F)&&y&&e.jsx(Vi,{portfolioId:F,subscribed:!!t.subscribed_portfolio_briefing,isSelf:!!S,used:P??0,quota:v??null,language:l,onChanged:C=>y(F,C)}),!W&&!n&&s.length>0&&(Q?e.jsx(ue,{variant:"outline",size:"xs",disabled:$,onClick:()=>{M||I(!0),Q()},children:$?e.jsxs(e.Fragment,{children:[e.jsx(zt,{className:"h-3 w-3 mr-1.5 animate-spin"})," ",T.enriching]}):e.jsxs(e.Fragment,{children:[e.jsx(Jt,{className:"h-3 w-3 mr-1.5"})," ",T.enrichData]})}):e.jsxs(ue,{variant:"outline",size:"xs",disabled:!0,title:T.enrichUnavailable,className:"opacity-60 cursor-not-allowed",children:[e.jsx(Jt,{className:"h-3 w-3 mr-1.5"})," ",T.enrichData]})),h&&!W&&e.jsx(ue,{variant:n?"outline":"default",size:"sm",disabled:x,onClick:()=>{M||I(!0),h()},className:n?"":"shadow-glow hover:shadow-glow-lg transition-all",children:n?T.cancel:e.jsxs(e.Fragment,{children:[e.jsx(Jr,{className:"h-3.5 w-3.5 mr-1.5"})," ",T.edit]})}),(p||c||a||b||i)&&!n&&e.jsxs(_a,{children:[e.jsx(ka,{asChild:!0,children:e.jsx(ue,{variant:"ghost",size:"icon",disabled:x,className:"h-9 w-9 shrink-0 text-muted-foreground hover:text-foreground",title:T.options,children:x?e.jsx(zt,{className:"h-4 w-4 animate-spin"}):e.jsx(Fn,{className:"h-4 w-4"})})}),e.jsxs(ja,{align:"end",className:"w-44",children:[b&&e.jsxs(_t,{onClick:b,children:[e.jsx(zn,{className:"h-4 w-4 mr-2"})," ",T.merge]}),i&&e.jsxs(_t,{onClick:i,children:[e.jsx(Rn,{className:"h-4 w-4 mr-2"})," ",T.split]}),(b||i)&&(p||c||a)&&e.jsx(Ks,{}),W&&c&&e.jsxs(_t,{onClick:c,children:[e.jsx(Cr,{className:"h-4 w-4 mr-2"})," ",T.unarchive]}),!W&&p&&e.jsxs(_t,{onClick:p,children:[e.jsx(Rr,{className:"h-4 w-4 mr-2"})," ",T.archive]}),(p||c)&&a&&e.jsx(Ks,{}),a&&e.jsxs(_t,{onClick:()=>D(!0),className:"text-destructive focus:text-destructive",children:[e.jsx(_s,{className:"h-4 w-4 mr-2"})," ",T.delete]})]})]})]})]}),a&&e.jsx(fs,{open:V,onOpenChange:D,children:e.jsxs(hs,{children:[e.jsxs(ps,{children:[e.jsx(gs,{children:A(T.deleteTitle)}),e.jsx(xs,{children:A(T.deleteBody)})]}),e.jsxs(bs,{children:[e.jsx(Er,{children:T.cancel}),e.jsx(vs,{onClick:()=>a(),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:T.deleteConfirm})]})]})}),e.jsx(wa,{children:e.jsxs("div",{className:"pt-6 space-y-6",children:[s.length===0?e.jsx("p",{className:"text-sm text-muted-foreground/50 py-4 text-center",children:T.noPositions}):e.jsxs(e.Fragment,{children:[e.jsx(xn,{portfolioId:F,lang:l,assets:pe}),e.jsxs("div",{className:"hidden lg:grid lg:grid-cols-4 gap-4 px-4 pb-2 eyebrow-sans border-b border-border/30",children:[e.jsx("div",{children:T.stock}),e.jsx("div",{className:"text-right",children:T.priceValue}),e.jsx("div",{className:"text-right",children:T.vsQuarter}),e.jsx("div",{className:"text-right",children:T.vsYear})]}),e.jsx("div",{className:"space-y-4",children:s.map((C,k)=>{var R;const q=Oe(C,r),se=Vr(C.ticker_eod),be=l==="en"?"en":"de",ie=(C.asset_kind??"listed")==="listed";return e.jsxs("div",{className:"flex flex-col gap-3 p-4 rounded-xl border border-border/30 bg-white dark:bg-card shadow-sm hover:shadow-md transition-shadow",children:[ie?e.jsxs("div",{className:"grid grid-cols-2 lg:grid-cols-4 gap-4 items-center",children:[e.jsxs("div",{className:"tabular-nums text-lg font-semibold text-foreground flex items-center gap-2.5 col-span-2 lg:col-span-1",children:[e.jsx("div",{className:"w-6 h-6 rounded-full bg-primary/10 flex items-center justify-center text-2xs text-primary shrink-0 font-sans font-bold",children:k+1}),e.jsx("span",{className:"truncate font-semibold",title:se?ss[se].etcName:void 0,children:Wr(C.ticker_eod,l)??C.stock_name}),C.added_by_company_id!=null&&e.jsx("span",{className:"shrink-0 text-2xs tabular-nums uppercase tracking-wider text-primary/70 bg-primary/10 px-1.5 py-0.5 rounded",children:T.addedByManager})]}),e.jsxs("div",{className:"lg:text-right tabular-nums text-lg font-semibold text-foreground flex flex-col lg:block",children:[e.jsx("span",{className:"lg:hidden text-xs text-muted-foreground mb-0.5 font-sans font-normal",children:T.priceValue}),C.current_price!=null?e.jsxs("div",{className:"flex flex-col",children:[e.jsxs("span",{children:[Oi(C.current_price,l)," ",C.currency]}),(()=>{const u=C.price_updated_at?On(C.price_updated_at,be):"";if(!u)return null;const B=Bn(C.price_updated_at);return e.jsxs("span",{"data-price-date":B?"old":"fresh",title:B?T.priceOld:void 0,className:`text-xs mt-0.5 font-sans font-normal tabular-nums ${B?"text-amber-500/80":"text-muted-foreground opacity-80"}`,children:[T.priceAsOf," ",u]})})(),q!=null&&q>0&&e.jsxs("span",{className:"text-xs text-muted-foreground mt-0.5 font-sans opacity-80",children:[T.value,": ",Ve(ut(q,ae).text,Y)]}),se&&C.shares!=null&&e.jsx("span",{className:"text-xs text-muted-foreground mt-0.5 font-sans opacity-80",children:De(Hr(Ur(se,C.shares)),Y)})]}):e.jsxs("span",{className:"inline-flex items-center gap-1 text-amber-500/80",title:T.noLivePrice,children:[e.jsx(mt,{className:"h-3 w-3"}),T.noLivePriceLabel]})]}),e.jsxs("div",{className:"lg:text-right tabular-nums text-lg font-semibold text-foreground flex flex-col lg:block",children:[e.jsx("span",{className:"lg:hidden text-xs text-muted-foreground mb-0.5 font-sans font-normal",children:"Î QoQ:"}),e.jsx(ur,{delta:Hs(C.current_price,C.prev_quarter_price)})]}),e.jsxs("div",{className:"lg:text-right tabular-nums text-lg font-semibold text-foreground flex flex-col lg:block",children:[e.jsx("span",{className:"lg:hidden text-xs text-muted-foreground mb-0.5 font-sans font-normal",children:"Î YoY:"}),e.jsx(ur,{delta:Hs(C.current_price,C.yoy_price)})]})]}):e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4 items-start",children:[e.jsxs("div",{className:"tabular-nums text-lg font-semibold text-foreground flex items-start gap-2.5",children:[e.jsx("div",{className:"w-6 h-6 rounded-full bg-primary/10 flex items-center justify-center text-2xs text-primary shrink-0 font-sans font-bold mt-0.5",children:k+1}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"truncate font-semibold",children:ot(C)??C.ticker_eod??C.id}),C.added_by_company_id!=null&&e.jsx("span",{className:"shrink-0 text-2xs tabular-nums uppercase tracking-wider text-primary/70 bg-primary/10 px-1.5 py-0.5 rounded",children:T.addedByManager})]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:ln(C.asset_kind,C.category,be)})]})]}),e.jsxs("div",{className:"sm:text-right tabular-nums text-lg font-semibold text-foreground flex flex-col sm:items-end",children:[q!=null?e.jsx("span",{className:q<0?"text-rose-500":void 0,children:Ve(ut(q,ae).text,Y)}):e.jsxs("span",{className:"inline-flex items-center gap-1 text-amber-500/80",title:T.notValued,children:[e.jsx(mt,{className:"h-3 w-3"}),T.notValuedLabel]}),C.valuation_date&&e.jsxs("span",{className:"text-2xs text-muted-foreground
7/50 mt-0.5",children:[T.valuedOn,": ",C.valuation_date]})]})]}),n&&N?e.jsx(Ri,{asset:C,language:l,saving:N.savingAssetId===C.id,onSave:u=>N.onSavePosition(C.id,u),onRemove:()=>N.onRemovePosition(C.id)}):e.jsxs("div",{className:"mt-2 pt-3 border-t border-border/10 text-sm font-sans",children:[e.jsx("span",{className:"text-xs text-muted-foreground block mb-1",children:T.thesis}),C.owner_comment?e.jsx("span",{className:"text-muted-foreground italic font-serif text-base opacity-80",children:C.owner_comment}):e.jsx("span",{className:"text-muted-foreground/30 italic",children:T.noThesis})]}),C.id&&!W&&E&&(E.categoryOf||E.onMovePosition)&&e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 mt-2",children:[E.categoryOf&&E.onAssignCategory?e.jsx(Nn,{lang:l==="en"?"en":"de",category:E.categoryOf(C.id),existingCategories:E.existingCategories??[],onSave:u=>E.onAssignCategory(C.id,u),listId:`family-cat-${C.id}`,saving:(R=E.savingCategoryIds)==null?void 0:R.has(C.id),size:"sm"}):e.jsx("span",{}),E.onMovePosition&&e.jsxs("button",{type:"button",onClick:()=>E.onMovePosition(C.id),className:"inline-flex items-center gap-1.5 text-xs text-muted-foreground hover:text-primary transition-colors",title:T.moveTitle,children:[e.jsx(Sa,{size:12}),T.move]})]})]},C.id||k)})})]}),o,e.jsx(mo,{portfolio:t,language:l,onSave:O})]})})]})},Vi=({portfolioId:t,subscribed:s,isSelf:r,used:l,quota:o,language:m,onChanged:n})=>{const h=St(m),p=ns[h],[c,a]=g.useState(!1),b=!s&&o!=null&&l>=o,i=async N=>{a(!0);try{if(r){const P=await Vn(t,N);if(P.ok===!1){P.reason==="quota_full"?te.error(p.briefingFullHint,{description:e.jsx(Ot,{to:"/upgrade",className:"underline underline-offset-2",children:p.briefingUpgrade})}):te.error(p.briefingGenericError);return}n({subscribed:P.subscribed,used:P.used,quota:Number.isFinite(P.quota)?P.quota:null});return}const S=await ga({portfolio_id:t,subscribed:N});if(S.ok===!1){te.error(Be(S.code,h));return}n({subscribed:!!S.data.subscribed,used:typeof S.data.used=="number"?S.data.used:l,quota:S.data.quota??null})}finally{a(!1)}}
7,x=s?h==="en"?"Briefing active":"Briefing aktiv":h==="en"?"no briefing":"ohne Briefing";return e.jsx(Nr,{checked:s,disabled:c||b,onCheckedChange:i,"aria-label":x,title:b?p.briefingFullHint:void 0})},Rt=t=>{if(t==null||t==="")return null;const s=Number(String(t).replace(",","."));return Number.isFinite(s)?s:null},mr=t=>{var s;return((s=t.owner_comment)==null?void 0:s.trim())??""},fr=t=>{var s;return{shares:Rt(t.shares),avg_cost:Rt(t.avg_cost),owner_comment:((s=t.owner_comment)==null?void 0:s.trim())||null}},Wi=(t,s)=>t.shares===s.shares&&t.avg_cost===s.avg_cost&&t.owner_comment===s.owner_comment;function Hi(t){return t.some(s=>s.asset_kind==="cash")}const hr=t=>{const s=Wn(t);return s>0?s:null};function Ui(t,s){var n,h;const r=t.kind==="decrease"?t.before:t.after??t.before,l=r.currency||"EUR";let o=hr(r.current_price),m=o!=null?"current":void 0;if(t.kind==="new"){const p=hr((n=t.after)==null?void 0:n.avg_cost),c=p!=null?l==="EUR"?p:Qn(p,l,s.rates):null;c!=null&&c>0&&(o=c,m="avg_cost")}return{key:t.tickerKey,name:r.stock_name||r.ticker,ticker:r.ticker,tickerEod:t.before?t.before.ticker:(((h=t.after)==null?void 0:h.ticker)??"").trim(),kind:t.kind,sharesBefore:t.sharesBefore,sharesAfter:t.sharesAfter,listingCurrency:l,pricePrefill:o,priceLabel:m,datePrefill:s.today,cashAvailable:t.kind==="decrease"&&s.cashAvailable}}function Ki(t,s,r){const l=t.kind==="decrease"?"sell":"buy";return{op:"record_trade",company_id:r.companyId,portfolio_id:r.portfolioId,ticker_eod:t.tickerEod,action:l,shares:Math.abs(t.sharesAfter-t.sharesBefore),fill_price:s.price,created_at:r.attempt.createdAt,expected_holding_shares:t.sharesBefore,...l==="sell"&&s.addProceedsToCash===!0?{add_proceeds_to_cash:!0}:{},idempotency_key:r.attempt.idempotencyKey}}function Gi(t,s,r){const l=Number(r.holding_shares??s.sharesAfter),o=r.holding_removed===!0||r.asset_id==null||!(l>0),m=r.holding_avg_cost_eur,n=[];let h=!1;for(const p of t){if($t(p.ticker)!==s.tickerKey){n.push(p);continue}h||(h=!0,!o&&n.push({...p,id:r.asset_id,shares:String(l),avg_cost:m!=null?String(m):p.avg_cost}))}if(!h&&!o){const p=s.after??s.before;n.push({...p,id:r.asset_id,shares:String(l),avg_cost:m!=null?String(m):"",owner_comment:""})}return n}function qi(t,s,r,l){var c;const o=new Map(s.filter(a=>a.id).map(a=>[a.id,a])),m=new Set(r.filter(a=>a.id).map(a=>a.id)),n=[],h=[],p=[];for(const a of r){if(!a.id)continue;const b=o.get(a.id);if(!b)continue;if(l.has($t(b.ticker))){const x=mr(a);if(x===mr(b))continue;n.push({kind:"update",commentOnly:!0,row:a,before:b,input:{op:"update",portfolio_id:t,asset_id:a.id,owner_comment:x}});continue}const i=fr(a);Wi(i,fr(b))||n.push({kind:"update",commentOnly:!1,row:a,before:b,input:{op:"update",portfolio_id:t,asset_id:a.id,shares:i.shares,avg_cost:i.avg_cost,avg_cost_currency:"EUR",owner_comment:i.owner_comment}})}for(const a of r){if(a.id)continue;const b=a.ticker.trim();!b||l.has($t(b))||h.push({kind:"add",row:a,input:{op:"add",portfolio_id:t,ticker_eod:b,shares:Rt(a.shares),avg_cost:Rt(a.avg_cost),avg_cost_currency:a.currency.trim()||null,owner_comment:((c=a.owner_comment)==null?void 0:c.trim())||null}})}for(const a of s)!a.id||m.has(a.id)||l.has($t(a.ticker))||p.push({kind:"remove",before:a,input:{op:"remove",portfolio_id:t,asset_id:a.id}});return[...n,...h,...p]}function Zi(t,s,r){if(s.kind==="remove")return t.filter(o=>o.id!==s.before.id);if(s.kind==="update")return t.map(o=>o.id!==s.before.id?o:s.commentOnly?{...o,owner_comment:s.input.owner_comment??""}:{...o,shares:s.row.shares,avg_cost:s.row.avg_cost,owner_comment:s.row.owner_comment});const l=r==null?void 0:r.asset_id;return l?[...t,{...s.row,id:String(l)}]:t}function Qi(t,s){const r=xa(t);return r?Ia(r,s):Be(t==null?void 0:t.code,s)}const Yi={de:{tradesRecorded:t=>t===1?"1 Trade im Trade-Log erfasst":`${t} Trades im Trade-Log erfasst`,tradesStand:"Die Trades sind im Trade-Log erfasst und bleiben bestehen. Die übrigen Ãnderungen wurden nicht vollständig gespeichert. Bitte erneut speichern.",unresolved:t=>`Nicht zugeordnet und daher nicht angelegt: ${t}`,saved:(t,s,r)=>`Gespeichert: ${t} geändert, ${s} hinzugefügt, ${r} entfernt`},en:{tradesRecorded:t=>t===1?"1 trade recorded in the Trade Log":`${t} trades recorded in the Trade Log`,tradesStand:"The trades are recorded in the Trade Log and stay there. The other changes were not all saved. Please save again.",unresolved:t=>`Not matched to a security, so not added: ${t}`,saved:(t,s,r)=>`Saved: ${t} changed, ${s} added, ${r} removed`}};function Xi(t){const{portfolioId:s,companyId:r,language:l,cashAvailable:o,listedAssets:m,mutateAsync:n}=t,{rates:h}=Bt(),p=Yi[l],c=g.useRef({attempts:new Map,tradeKeys:new Set,baseline:null}),[a,b]=g.useState(null),[i,x]=g.useState({}),[N,S]=g.useState(!1),P=g.useCallback(()=>{c.current={attempts:new Map,tradeKeys:new Set,baseline:null}},[]),v=g.useMemo(()=>a?a.changes.map(D=>Ui(D,{cashAvailable:o,rates:h,today:Da(new Date,"yyyy-MM-dd")})):[],[a,o,h]),y=async(D,F,w)=>{const M=c.current,I=qi(s,M.baseline??[],D,F);let T=0,Y=0,ae=0,J=!1;for(const A of I)try{const z=await n(A.input);
7M.baseline=Zi(M.baseline??[],A,z),A.kind==="update"?T+=1:A.kind==="add"?Y+=1:ae+=1}catch(z){J=!0,te.error(Be(z==null?void 0:z.code,l))}w.length>0&&te.warning(p.unresolved(w.join(", "))),J?M.tradeKeys.size>0&&te.error(p.tradesStand,{duration:12e3}):te.success(p.saved(T,Y,ae));const W=!J&&w.length===0;return W&&P(),W},E=async(D,F)=>{if(a)return!1;const w=c.current,M=w.baseline??F??m;w.baseline=M;const I=Z=>!Z.stock_name.trim()&&!Z.ticker.trim(),T=Z=>Z.stock_name.trim()||Z.ticker.trim(),Y=D.filter(Z=>!Z.id&&!I(Z)&&!Z.ticker.trim()),ae=Y.length>0?await to(Y.map(Z=>({name:T(Z),isin:null,ticker:null})),Ee):{},J=[],W=[];for(const Z of D){if(Z.id){W.push(Z);continue}if(I(Z))continue;const re=Z.ticker.trim()||ae[T(Z).toLowerCase()]||null;if(!re){J.push(T(Z));continue}W.push({...Z,ticker:re})}const A=Vs(M,W),z=r!=null?Hn(M,A):[];return z.length===0?y(A,w.tradeKeys,J):(x({}),new Promise(Z=>{b({changes:z,assets:A,unresolved:J,resolve:Z})}))},Q=()=>{b(null),x({}),S(!1)},$=()=>{N||!a||(a.resolve(!1),Q())},O=async D=>{var A;if(!a||N||r==null)return;S(!0);const F=c.current,w=new Map(D.map(z=>[z.key,z]));let M=!1,I=0;for(const z of v){const Z=w.get(z.key);if(!Z||Z.choice!=="trade"||((A=i[z.key])==null?void 0:A.status)==="done")continue;const re=a.changes.find(se=>se.tickerKey===z.key);if(!re)continue;const pe=z.kind==="decrease"?"sell":"buy",C=Z.date??z.datePrefill,k=Ea(F.attempts,`${z.key}|${pe}|${z.sharesBefore}|${z.sharesAfter}`,C);x(se=>({...se,[z.key]:{status:"busy"}}));let q=null;try{q=await n(Ki(z,Z,{companyId:r,portfolioId:s,attempt:k}))}catch(se){if(q=ba(se),q)console.warn("[family-holding-review] trade recorded, audit completion failed",se);else{x(be=>({...be,[z.key]:{status:"error",error:Qi(se,l)}})),M=!0;continue}}F.baseline=Gi(F.baseline??[],re,q),F.tradeKeys.add(z.key),I+=1,x(se=>({...se,[z.key]:{status:"done"}}))}if(I>0&&te.success(p.tradesRecorded(I)),M){S(!1);return}const T=new Set([...F.tradeKeys].filter(z=>{var Z;return((Z=w.get(z))==null?void 0:Z.choice)!=="correction"})),Y=Vs(F.baseline??[],a.assets),{resolve:ae,unresolved:J}=a,W=await y(Y,T,J);Q(),ae(W)};return{dialog:a==null?null:e.jsx(Aa,{open:!0,rows:v,rowState:i,submitting:N,language:l,onCancel:$,onSubmit:O}),save:E,reset:P}}function Qt(t){return t&&typeof t=="object"&&"message"in t?String(t.message):String(t)}function Ji(t={}){const{onWrote:s}=t,r=Vt(),l=g.useCallback(async(m,n)=>{try{const h=await to(m.map(c=>({name:c.name,isin:c.isin??null,ticker:c.ticker??null})),Ee),p=m.map(c=>({name:c.name,isin:c.isin??null,ticker:c.ticker??null,shares:c.shares??null,average_cost:c.average_cost??null,currency:c.currency??null,ticker_eod:h[c.name.toLowerCase()]??null}));return Ma({statement:p,holdings:n})}catch(h){return console.error("prepareFamilyStatementReconcile error:",h),null}},[]),o=g.useCallback(async(m,n,h,p)=>{var v;const c={ok:!1,unresolved:[],failed:[],updatedCount:0,addedCount:0,removedCount:0},a=new Set(p.map(y=>y.id)),b=new Set([...n.matched.map(y=>y.holding.id),...n.unchanged.map(y=>y.holding.id),...n.missing.map(y=>y.id)]);if(!(a.size===b.size&&[...b].every(y=>a.has(y))))return console.error("applyFamilyStatementReconcile: holdings changed since review, aborting without writing"),{...c,stale:!0};const x=$a(n,h);x.rename&&(c.skippedRename=x.rename);const{safe:N,destructive:S}=Fa(x);let P=!1;for(const y of N.updates)try{await r.mutateAsync({op:"update",portfolio_id:m,asset_id:y.id,...y.shares!==void 0?{shares:y.shares}:{},...y.average_cost!==void 0?{avg_cost:y.average_cost}:{},...y.currency!==void 0?{avg_cost_currency:y.currency}:{}}),c.updatedCount+=1,P=!0}catch(E){c.failed.push({label:y.id,reason:Qt(E)})}for(const y of N.add){const E=y.ticker_eod??((v=N.resolved)==null?void 0:v[y.name.toLowerCase()])??null;if(!E){c.unresolved.push(y.name);continue}try{await r.mutateAsync({op:"add",portfolio_id:m,ticker_eod:E,shares:y.shares??null,avg_cost:y.average_cost??null,avg_cost_currency:y.currency??null,owner_comment:null}),c.addedCount+=1,P=!0}catch(Q){c.failed.push({label:y.name,reason:Qt(Q)})}}for(const y of S.removeIds)try{await r.mutateAsync({op:"remove",portfolio_id:m,asset_id:y}),c.removedCount+=1,P=!0}catch(E){c.failed.push({label:y,reason:Qt(E)})}return P&&await(s==null?void 0:s()),c.ok=c.failed.length===0,c},[r,s]);return{prepareFamilyStatementReconcile:l,applyFamilyStatementReconcile:o}}const Yt=t=>t==null?"":String(t),Xt=t=>(t.asset_kind??"listed")==="listed",el=({portfolio:t,companyId:s,assets:r,language:l,memberName:o,defaultOpen:m,onArchive:n,onDelete:h,onMerge:p,onSplit:c,categoryOf:a,existingCategories:b,onAssignCategory:i,savingCategoryIds:x,onMovePosition:N,isReadOnly:S,briefingSlotState:P,hasBriefingSubscription:v,onBriefingChanged:y})=>{var R;const E=t.portfolio_id,Q=St(l),$=l!=="en",O=Vt(),[V,D]=g.useState(!1),[F,w]=g.useState(!1),M=g.useMemo(()=>r.filter(Xt).map(u=>({id:u.id,stock_name:u.stock_name??u.ticker_eod??"",ticker:u.ticker_eod??"",owner_comment:u.owner_comment??"",currency:u.currency??"",current_price:Yt(u.current_price),prev_quarter_price:Yt(u.prev_quarter_price),yoy_price:Yt(u.yoy_price),qoq_price:"",shares:u.shares??"",avg_cost:u.avg_cost??"",logo_url:u.logo_url??null,asset_class:u.asset_class??null,price_updated_at:u.price_updated_at??null})),[r]),I=g.useMemo(()=>r.filter(u=>!Xt(u)).map(u=>({id:u.id,asset_kind:u.asset_kind??"property",display_name:u.dis
7play_name??u.stock_name??"",note:null,category:u.category??null,manual_value:u.manual_value??null,manual_value_currency:u.manual_value_currency??null,purchase_price:u.purchase_price??null,purchase_price_currency:u.purchase_price_currency??null,valuation_date:u.valuation_date??null,parent_asset_id:u.parent_asset_id??null})),[r]),[T,Y]=g.useState(M),ae=s??((R=r.find(u=>u.company_id!=null))==null?void 0:R.company_id)??null,J=Xi({portfolioId:E,companyId:ae,language:Q,cashAvailable:Hi(r),listedAssets:M,mutateAsync:O.mutateAsync}),W=u=>{u&&S||(u&&(Y(M),J.reset()),D(u))},A=g.useMemo(()=>r.map(u=>{var B;return{id:u.id,ticker_eod:u.ticker_eod,ticker:((B=u.ticker_eod)==null?void 0:B.split(".")[0])??null,stock_name:u.stock_name||u.ticker_eod||"",shares:u.shares,avg_cost:u.avg_cost,current_price:u.current_price,currency:u.currency,sector:u.sector??null,industry:u.industry??null,country_name:u.country_name??null,asset_class:u.asset_class??null,asset_kind:u.asset_kind??null,manual_value:u.manual_value??null,manual_value_currency:u.manual_value_currency??null}}),[r]),z=u=>{const B=u;te.error(Be(B==null?void 0:B.code,Q))},Z=async u=>{w(!0);try{return await J.save(T,u)}finally{w(!1)}},re=async u=>{try{await O.mutateAsync({op:"add",portfolio_id:E,ticker_eod:u.tickerEod,shares:u.shares,avg_cost:u.avgCostPerShare,avg_cost_currency:"EUR",owner_comment:null}),te.success($?"Position hinzugefügt":"Position added")}catch(B){z(B)}},pe=async u=>{var ze,Ke,Ce,ye,We,Xe,Se,Ie;const B=(u.displayName??"").trim();if(!B)return{ok:!1,code:"value_invalid",message:"display_name required"};const oe=Ta(u.assetKind,u.valueText,u.lang);if(oe==null||!Number.isFinite(oe))return{ok:!1,code:"value_invalid",message:"manual_value must be a finite number"};const X=(u.purchasePriceText??"").trim().replace(",","."),ke=u.lang?eo(u.purchasePriceText??"",u.lang)??NaN:X?Number(X):NaN,ve=Number.isFinite(ke)&&ke>=0?ke:null;try{const Ne=await O.mutateAsync({op:"add",portfolio_id:E,asset_kind:u.assetKind,display_name:B,category:u.category??null,manual_value:oe,manual_value_currency:(u.manualValueCurrency??"EUR").trim().toUpperCase(),valuation_date:u.valuationDate??null,valuation_source:u.valuationSource??null,parent_asset_id:u.parentAssetId??null,purchase_price:ve,purchase_price_currency:ve!=null?u.purchasePriceCurrency??null:null,monthly_net_cashflow:((ze=u.terms)==null?void 0:ze.monthlyNetCashflow)??null,monthly_net_cashflow_currency:((Ke=u.terms)==null?void 0:Ke.monthlyNetCashflowCurrency)??null,interest_rate_pct:((Ce=u.terms)==null?void 0:Ce.interestRatePct)??null,term_start_date:((ye=u.terms)==null?void 0:ye.termStartDate)??null,term_end_date:((We=u.terms)==null?void 0:We.termEndDate)??null,provision_due_date:((Xe=u.terms)==null?void 0:Xe.provisionDueDate)??null,credit_type:((Se=u.terms)==null?void 0:Se.creditType)??null,collateral_asset_ids:((Ie=u.terms)==null?void 0:Ie.collateralAssetIds)??null});return{ok:!0,assetId:String((Ne==null?void 0:Ne.asset_id)??"")}}catch(Ne){const me=Ne;return{ok:!1,code:(me==null?void 0:me.code)==="not_authorized"?"denied":(me==null?void 0:me.code)==="already_held"||(me==null?void 0:me.code)==="unknown_ticker"||(me==null?void 0:me.code)==="value_invalid"?me.code:"failed",message:String((me==null?void 0:me.message)??Ne)}}},C=async u=>{const B=oe=>oe.trim()?oe.trim():null;try{return await O.mutateAsync({op:"save_investor_profile",portfolio_id:E,investment_philosophy:B(u.investment_philosophy),buy_box_trigger_1:B(u.buy_box_trigger_1),buy_box_trigger_2:B(u.buy_box_trigger_2),buy_box_trigger_3:B(u.buy_box_trigger_3),noise_filter:B(u.noise_filter),data_granularity:u.data_granularity,action_frequency:u.action_frequency,decision_logic:u.decision_logic,risk_appetite:u.risk_appetite}),te.success($?"Anlagestrategie gespeichert":"Investment strategy saved"),!0}catch(oe){return z(oe),!1}},k=async u=>{try{return await O.mutateAsync({op:"remove",portfolio_id:E,asset_id:u}),!0}catch(B){return z(B),!1}},q=g.useMemo(()=>r.filter(Xt).map(u=>({id:u.id,ticker_eod:u.ticker_eod??null,stock_name:u.stock_name??null,shares:u.shares??null,avg_cost:u.avg_cost??null,owner_comment:u.owner_comment??null})),[r]),{prepareFamilyStatementReconcile:se,applyFamilyStatementReconcile:be}
7=Ji(),ie=g.useMemo(()=>({prepare:(u,B)=>se(B,q),apply:async(u,B,oe)=>{const X=await be(u,B,oe,q),ke=X.updatedCount+X.addedCount+X.removedCount;return{ok:X.ok,stale:X.stale,updatedCount:X.updatedCount,addedCount:X.addedCount,removedCount:X.removedCount,unresolved:X.unresolved,partial:!X.ok&&!X.stale&&ke>0?{updatedCount:X.updatedCount,addedCount:X.addedCount,removedCount:X.removedCount}:void 0}}}),[se,be,q]);return e.jsxs(e.Fragment,{children:[e.jsx(Un,{portfolioName:t.portfolio_name||"Portfolio",assets:V?T:M,isEditing:V,setIsEditing:W,onSetPortfolioName:()=>{te.message($?"Umbenennen ist für Mandantenportfolios noch nicht verfügbar.":"Renaming is not available for client portfolios yet.")},onAddAsset:()=>Y(u=>[...u,{stock_name:"",ticker:"",owner_comment:"",currency:"",current_price:"",prev_quarter_price:"",yoy_price:"",qoq_price:"",shares:"",avg_cost:""}]),onAddAssets:u=>Y(B=>[...B,...u.map(oe=>({stock_name:"",ticker:"",owner_comment:"",currency:"",current_price:"",prev_quarter_price:"",yoy_price:"",qoq_price:"",shares:"",avg_cost:"",...oe}))]),onDiscardEdits:u=>{J.reset(),Y(u)},sachwertUpdater:Pa(E),briefingSubscribed:!!t.subscribed_portfolio_briefing,slotState:P,hasBriefingSubscription:v,briefingWriter:Kn,onBriefingSlotChanged:u=>y==null?void 0:y(u.subscribed),onAddMetalAsset:u=>void re(u),onRemoveAsset:u=>Y(B=>B.filter((oe,X)=>X!==u)),onUpdateAsset:(u,B,oe)=>Y(X=>X.map((ke,ve)=>ve===u?{...ke,[B]:oe}:ke)),onSave:Z,saving:F,companyId:null,portfolioId:E,language:l,defaultOpen:m,onArchive:S?void 0:n,onDelete:S?void 0:h,onMerge:S?void 0:p,onSplit:S?void 0:c,categoryOf:a,existingCategories:b,onAssignCategory:S?void 0:i,savingCategoryIds:x,onMovePosition:S?void 0:N,isReadOnly:S,sachwerte:I,onRemoveSachwert:k,overviewAssets:A,statementEngine:ie,sachwertWriter:pe,strategySlot:e.jsx(mo,{portfolio:t,language:l,onSave:S?void 0:C})}),J.dialog]})},tl={de:{used:(t,s)=>`${t} von ${s} Briefing-Plätzen belegt`,usedUnknownQuota:t=>`${t} Briefing-Plätze belegt`,more:"Mehr Plätze"},en:{used:(t,s)=>`${t} of ${s} briefing slots in use`,usedUnknownQuota:t=>`${t} briefing slots in use`,more:"More slots"}},sl=({used:t,quota:s,language:r,isSelf:l=!1,className:o})=>{const m=tl[r==="en"?"en":"de"];if(t===0&&s==null)return null;const n=s!=null&&t>=s;return e.jsxs("span",{className:`inline-flex items-center gap-2 rounded-full border px-2.5 py-0.5 text-xs font-medium ${n?"bg-amber-500/10 border-amber-500/20 text-amber-700 dark:text-amber-400":"bg-muted/40 border-border text-muted-foreground"} ${o??""}`,children:[s!=null?m.used(t,s):m.usedUnknownQuota(t),n&&l&&e.jsx(Ot,{to:"/upgrade",className:"underline underline-offset-2 hover:no-underline font-semibold",children:m.more})]})};function rl(t,s,r){const l=s!=="en";switch(t==null?void 0:t.code){case"not_authorized":return l?"Keine Schreibberechtigung für dieses Portfolio.":"No write access to this portfolio.";case"inactive_customer":return l?`${r} ist kein aktiver Kunde mehr.`:`${r} is no longer an active customer.`;case"not_found":return l?"Nicht gefunden. Seite neu laden.":"Not found. Reload the page.";case"audit_unavailable":return l?"Nicht gelöscht: der Aenderungsverlauf konnte nicht geschrieben werden. Es wurde nichts veraendert.":"Not deleted: the change log could not be written, so nothing was changed.";default:return l?"Aktion fehlgeschlagen.":"Action failed."}}const ol=({member:t,assets:s,portfolios:r,archivedPortfolios:l,value:o,share:m,rates:n,language:h,strings:p,renderSelfBody:c,headerActions:a,onSelfUnarchive:b,onSelfDelete:i,onMergeClientPortfolio:x,onSplitClientPortfolio:N,clientHeaderActions:S,briefingQuota:P=null,positions:v})=>{var ie,R;const[y,E]=g.useState(!1);g.useState(null),g.useState(null);const[Q,$]=g.useState(null);g.useState(null);const O=Vt(),{writeLocked:V,isReadOnlyRole:D,isClient:F,loading:w}=$o(),M=w||(V??D)||F,I=et(),T=Ct(),[Y,ae]=g.useState({}),[J,W]=g.useState(null),A=g.useMemo(()=>r.map(u=>({...u,subscribed_portfolio_briefing:Y[u.portfolio_id]??u.subscribed_portfolio_briefing})),[r,Y]),z=(J==null?void 0:J.used)??Fo(r),Z=g.useMemo(()=>t.plan==null?void 0:Tr(A,t.plan),[A,t.plan]),re=J?J.quota:P,pe=(u,B)=>{ae(oe=>({...oe,[u]:B.subscribed})),W({used:B.used,quota:B.quota})},C=((ie=t.customer_name)==null?void 0:ie.trim())||`#${t.company_id}`,k=h!=="en",q=async(u,B)=>{try{return await O.mutateAsync(u),te.success(B),!0}catch(oe){return te.error(rl(oe,h,C)),!1}},se=t.is_self?p.selfLabel:((R=t.customer_name)==null?void 0:R.trim())||`#${t.company_id}`,be=g.useMemo(()=>{const u=new Map;for(const B of s){const oe=u.get(B.portfolio_id);oe?oe.push(B):u.set(B.portfolio_id,[B])}return u},[s]);return e.jsxs(Ye,{children:[a&&e.jsx("div",{className:"flex justify-end px-5 pt-4",children:a}),e.jsxs("div",{className:"flex items-center",children:[e.jsxs("button",{onClick:()=>E(u=>!u),className:"flex-1 min-w-0 flex items-center gap-4 pl-5 py-4 text-left",children:[t.is_self?e.jsx(Yr,{className:"h-6 w-6 text-primary shrink-0"}):e.jsx(Xr,{className:"h-6 w-6 text-primary shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h3",{className:"font-serif font-semibold text-2xl text-foreground truncate",children:se}),e.jsxs("p",{className:"text-sm text-muted-foreground mt-1",children:[r.length," ",p.portfolios,e.jsx("span",{className:"mx-1.5 text-muted-foreground
7/30",children:"·"}),s.length," ",p.positions]})]})]}),(S||z>0||re!=null)&&e.jsxs("div",{className:"flex items-center gap-2 shrink-0 pl-4",children:[e.jsx(sl,{used:z,quota:re,language:h,isSelf:t.is_self}),S]}),e.jsxs("button",{onClick:()=>E(u=>!u),className:"flex items-center gap-4 shrink-0 pl-4 pr-5 py-4 group",children:[e.jsxs("div",{className:"text-right shrink-0",children:[e.jsx("p",{className:"font-sans tabular-nums text-base font-semibold text-foreground",children:Ve(ut(o,T).text,I)}),e.jsxs("p",{className:"text-xs font-sans tabular-nums text-muted-foreground/60 mt-0.5",children:[(m*100).toFixed(1),"%"]})]}),y?e.jsx(wr,{size:16,className:"text-muted-foreground/40 shrink-0"}):e.jsx(Kr,{size:16,className:"text-muted-foreground/40 group-hover:text-primary/60 transition-colors shrink-0"})]})]}),y&&e.jsx("div",{className:"px-5 pb-5 animate-fade-in",children:e.jsxs("div",{className:"border-t border-border/30 pt-4 space-y-3",children:[t.is_self&&c?c():r.length===0?e.jsx("p",{className:"text-xs text-muted-foreground/50 py-4 text-center",children:p.noPortfolios}):A.map(u=>e.jsx(el,{portfolio:u,companyId:t.company_id,assets:be.get(u.portfolio_id)??[],language:h,memberName:C,isReadOnly:M,briefingSlotState:M?void 0:Z,hasBriefingSubscription:t.plan!=null,onBriefingChanged:B=>pe(u.portfolio_id,{subscribed:B,used:B?z+1:Math.max(0,z-1),quota:re}),onArchive:M||u.product_status==="archived"?void 0:async()=>{$(u.portfolio_id),await q({op:"archive",portfolio_id:u.portfolio_id},k?"Portfolio archiviert":"Portfolio archived"),$(null)},onDelete:M?void 0:async()=>{$(u.portfolio_id),await q({op:"delete_portfolio",portfolio_id:u.portfolio_id},k?"Portfolio gelöscht":"Portfolio deleted"),$(null)},onMerge:!M&&x?()=>x(u.portfolio_id):void 0,onSplit:!M&&N?()=>N(u.portfolio_id):void 0,categoryOf:v==null?void 0:v.categoryOf,existingCategories:v==null?void 0:v.existingCategories,onAssignCategory:M||v==null?void 0:v.onAssignCategory,savingCategoryIds:v==null?void 0:v.savingCategoryIds,onMovePosition:M||v==null?void 0:v.onMovePosition},u.portfolio_id)),l.length>0&&e.jsxs("div",{className:"pt-2 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-px flex-1 bg-border/50"}),e.jsx("span",{className:"text-2xs font-sans text-muted-foreground/50 uppercase tracking-widest",children:p.archived}),e.jsx("div",{className:"h-px flex-1 bg-border/50"})]}),l.map(u=>e.jsx("div",{className:"opacity-70",children:e.jsx(Bi,{portfolio:u,assets:be.get(u.portfolio_id)??[],rates:n,language:h,memberName:C,busy:Q===u.portfolio_id,onUnarchive:M?void 0:t.is_self?b?async()=>{$(u.portfolio_id);try{await b(u.portfolio_id)}finally{$(null)}}:void 0:async()=>{$(u.portfolio_id),await q({op:"unarchive",portfolio_id:u.portfolio_id},k?"Portfolio aktiviert":"Portfolio activated"),$(null)},onDelete:M?void 0:t.is_self?i?async()=>{$(u.portfolio_id);try{await i(u.portfolio_id)}finally{$(null)}}:void 0:async()=>{$(u.portfolio_id),await q({op:"delete_portfolio",portfolio_id:u.portfolio_id},k?"Portfolio gelöscht":"Portfolio deleted"),$(null)}})},u.portfolio_id))]})]})})]})},pr={de:{loading:"Geldfluss wird geladen ...",empty:"Noch kein Geldfluss: Einnahmen, Ausgaben oder Sparpläne im Cashflow-Planer erfassen.",cta:"Zum Cashflow-Planer",title:"Geldfluss",period:"Monatsdurchschnitt",scopeLabel:"Analyseumfang",scopeOverall:"Gesamt",scopeByClass:"Nach Anlageklasse",scopeByClassDisabledHint:"Erfordert mindestens einen aktiven Sparplan.",incomplete:"Einige Bruttoeinnahmen sind ausgeschlossen, bis ihre Steuerangaben hinterlegt sind.",incompleteCta:"Im Cashflow-Planer ergänzen",loadError:"Cashflow konnte nicht geladen werden"},en:{loading:"Loading money flow ...",empty:"No money flow yet: record income, expenses or savings plans in the Cashflow Planner.",cta:"Open Cashflow Planner",title:"Money Flow",period:"Monthly average",scopeLabel:"Explorer scope",scopeOverall:"Overall",scopeByClass:"By asset class",scopeByClassDisabledHint:"Requires at least one active savings plan.",incomplete:"Some gross income is excluded until its tax details are configured.",incompleteCta:"Complete in Cashflow Planner",loadError:"Unable to load cashflow"}},nl=({lang:t})=>{const s=t==="en"?pr.en:pr.de,r=et(),{totals:l,settings:o,settingsLoading:m,portfolioLoading:n,portfolioAssets:h,plans:p,sparplanTrades:c,items:a=[],cashflowLoadError:b,listsLoading:i=!1}=Ra(),[x,N]=g.useState("overall"),S=(o==null?void 0:o.base_currency)||"EUR",P=o==null?void 0:o.default_income_tax_rate,v=a.some(F=>Va(F,P).taxRateSource==="missing"),{classOf:y,loading:E}=Oa(h,p,c,x==="by_class"),Q=g.useMemo(()=>Wa(p,c,y),[p,c,y]),$=x==="by_class"&&E?"overall":x,O=g.useMemo(()=>{try{return Ba(l,{...$==="by_class"&&p.length>0?{savingsByClass:Q}:{},currency:S})}catch(F){return console.warn("buildPersonalCashflowGraph: graph does not balance, showing empty state",F),null}},[l,$,p.length,Q,S]),V=e.jsx(es,{variant:"page",as:"h2",title:s.title,subtitle:`${s.period} · ${S}`,right:e.jsx(zo,{value:x,onChange:N,variant:"track",ariaLabel:s.scopeLabel,options:[{value:"overall",label:s.scopeOverall},{value:"by_class",label:s.scopeByClass,disabled:p.length===0,title:p.length===0?s.scopeByClassDisabledHint:void 0}]})}),D=v?e.jsxs("p",{className:"mt-3 text-xs font-medium text-amber-600 dar
7k:text-amber-400",children:[s.incomplete," ",e.jsx(Ot,{to:"/desk/cashflow",className:"underline underline-offset-2 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",children:s.incompleteCta})]}):null;return m||i||n?e.jsxs(e.Fragment,{children:[V,e.jsx("p",{className:"mt-4 text-sm text-muted-foreground",children:s.loading})]}):b?e.jsxs(e.Fragment,{children:[V,e.jsx(Lr,{variant:"destructive",className:"mt-4",children:e.jsx(Ar,{children:s.loadError})})]}):!O||O.nodes.length===0?e.jsxs(e.Fragment,{children:[V,D,e.jsx("div",{className:"mt-4",children:e.jsx(Ua,{reason:s.empty,cta:{label:s.cta,to:"/desk/cashflow?tab=settings"}})})]}):e.jsxs(e.Fragment,{children:[V,D,e.jsx("div",{className:"mt-4",children:e.jsx(Ha,{graph:O,lang:t==="en"?"en":"de",maskValues:r})})]})};function gr(t){var s,r,l;return((s=t.display_name)==null?void 0:s.trim())||((r=t.stock_name)==null?void 0:r.trim())||((l=t.ticker_eod)==null?void 0:l.trim())||t.id}function al(t,s,r={}){const l=r.asOf??new Date,o=r.unassignedCategoryLabel??"Nicht zugeordnet",m=new Map(t.map(n=>[n.id,n]));return t.map(n=>{var b,i,x;const h=Ka(n,s,l);let p=null,c=n.manual_value_currency||n.currency||"EUR";h.isUnvalued||(n.manual_value!=null?(p=n.manual_value,c=n.manual_value_currency||"EUR"):(p=(n.shares??0)*n.current_price,c=n.currency||"EUR"));const a=n.parent_asset_id?m.get(n.parent_asset_id):void 0;return{name:gr(n),category:((b=n.category)==null?void 0:b.trim())||o,assetKind:h.kind,value:p,currency:c,valuationDate:n.valuation_date||"",valuationSource:n.valuation_source||"",parentPosition:a?gr(a):"",portfolio:((x=(i=r.portfolioNames)==null?void 0:i.get(n.portfolio_id))==null?void 0:x.trim())||n.portfolio_id}})}const xr=[{key:"name",header:"Name"},{key:"category",header:"Kategorie"},{key:"assetKind",header:"Anlageart"},{key:"value",header:"Wert"},{key:"currency",header:"Währung"},{key:"valuationDate",header:"Bewertungsdatum"},{key:"valuationSource",header:"Quelle"},{key:"parentPosition",header:"Ãbergeordnete Position"},{key:"portfolio",header:"Portfolio"}];function Ae(t){if(t==null)return"";const s=typeof t=="number"?String(t):t;return/[",\n\r]/.test(s)?`"${s.replace(/"/g,'""')}"`:s}function il(t,s={}){const r=",",l="\uFEFF",o=xr.map(n=>Ae(n.header)).join(r),m=t.map(n=>xr.map(h=>Ae(n[h.key])).join(r));return l+[o,...m].join(`\r 8`)+`\r 9`}function ll(t){if(!t)return[];const s=[];for(const r of t.regions)s.push({bucket:"Region",name:r.name,weightPct:r.pct,valueEur:r.valueEur,coveragePct:null});for(const r of t.sectors)s.push({bucket:"Sector",name:r.name,weightPct:r.pct,valueEur:r.valueEur,coveragePct:null});for(const r of t.names)s.push({bucket:"Holding",name:r.name,weightPct:r.pct,valueEur:r.valueEur,coveragePct:t.namedCoveragePct});return s}const cl=[{key:"bucket",header:"Kategorie"},{key:"name",header:"Name"},{key:"weightPct",header:"Anteil %"},{key:"valueEur",header:"Wert EUR"},{key:"coveragePct",header:"Namentliche Abdeckung %"}],dl={Region:"Region",Sector:"Sektor",Holding:"Position"};function fo(t){if(typeof t=="string"){const o=/^(\d{4})-(\d{2})-(\d{2})$/.exec(t);if(o)return`${o[3]}.${o[2]}.${o[1]}`}const s=t instanceof Date?t:new Date(t);if(Number.isNaN(s.getTime()))return String(t);const r=String(s.getDate()).padStart(2,"0"),l=String(s.getMonth()+1).padStart(2,"0");return`${r}.${l}.${s.getFullYear()}`}const ul="Ein Mindestwert: unser Datenanbieter liefert je Fonds nur die gröÃten Positionen.",ml="Quelle: Fondszusammensetzung unseres Datenanbieters, Berechnung Kasona";function fl(t,s=0,r,l="Durchschau"){if(t.length===0)return"";const o=s>0,m=",",n=[];o&&r&&(n.push(Ae(r.subjectName)),n.push(Ae(`Stichtag: ${r.asOf}`)),r.oldestRefreshedAt&&n.push(Ae(`Stand der Zusammensetzung: ${fo(r.oldestRefreshedAt)}`)),n.push(Ae(ul)),n.push(Ae(ml)),n.push(Ae(Za.de)));const h=cl.map(c=>Ae(c.header)).join(m),p=t.map(c=>{const a=o?dl[c.bucket]:c.bucket,b=o&&c.bucket!=="Holding"?Fr(c.name,"de"):c.name;return[Ae(a),Ae(b),Ae(c.weightPct),Ae(c.valueEur),Ae(c.coveragePct)].join(m)});return[...n,Ae(l),h,...p].join(`\r 10`)}function hl(t,s){const r=new Blob([t],{type:"text/csv;charset=utf-8"}),l=URL.createObjectURL(r),o=document.createElement("a");o.href=l,o.download=s,document.body.appendChild(o),o.click(),document.body.removeChild(o),URL.revokeObjectURL(l)}
10const br={de:{exportPdf:"PDF exportieren",exportCsv:"CSV exportieren",reportTitle:"Netto-Vermögen: Organigramm",asOfLabel:"Stand:",pageOfTemplate:"Seite {n} von {m}",unvaluedLabel:"unbewertet",noDataLabel:"Keine Daten",staleLabel:"Bewertung älter als zwölf Monate.",continuedTemplate:"{parent} (Forts.)",overviewHeading:"Ãbersicht",netWorthLabel:"Netto-Vermögen",assetsLabel:"Vermögen",liabilitiesLabel:"Schulden",investedLabel:"Eingesetzt",priceGainLabel:"Kursgewinn",assetClassesLabel:"Assetklassen",positionsLabel:"Positionen",portfoliosLabel:"Portfolios",currencyLabel:"Währung",expectedDividendsPaLabel:"Dividenden erwartet p.a.",hasUnvaluedNote:"Enthält unbewertete Positionen, nicht in der Summe berücksichtigt.",categorySplitHeading:"Aufteilung nach Kategorie",clusterHeading:"Gesamtübersicht",orgPositionsCountTemplate:"{n} Positionen",orgChartDetailNote:"Detail je Kategorie auf den folgenden Seiten.",morePositionsTemplate:"weitere {n} Positionen",subUnitsInStatementNote:"Untereinheiten siehe Positionsliste.",omittedInStatementNote:"Vollständige Aufstellung in der Positionsliste.",positionsHeading:"Positionen",positionColumnLabel:"Position",shareColumnLabel:"Anteil",valueColumnLabel:"Wert",totalLabel:"Netto-Vermögen gesamt",lookThroughHeading:"Durchschau: Fonds aufgelöst",lookThroughRegionsLabel:"Regionen",lookThroughSectorsLabel:"Sektoren",lookThroughTopPositionsLabel:"GröÃte Positionen",lookThroughNameColumnLabel:"Name",lookThroughShareColumnLabel:"Anteil am Depot",lookThroughViaFundsColumnLabel:"Ãber Fonds",lookThroughAtLeastTemplate:"mind. {pct}",lookThroughDirectLabel:ts.de,lookThroughNFundsTemplate:"{n} Fonds",lookThroughOneFundLabel:"1 Fonds",lookThroughCoverageCaveat:"Ein Mindestwert: unser Datenanbieter liefert je Fonds nur die gröÃten Positionen.",lookThroughFundCoverageTemplate:"{ticker}: {pct} der Fondsgewichte namentlich erfasst",lookThroughCompositionAsOfTemplate:"Stand der Zusammensetzung: {date}",cashLabel:"Cash",cashUnavailableNote:"Cash-Bestand nicht verfügbar, daher kein Gesamtwert."},en:{exportPdf:"Export PDF",exportCsv:"Export CSV",reportTitle:"Net Worth: Organisation Chart",asOfLabel:"As of:",pageOfTemplate:"Page {n} of {m}",unvaluedLabel:"unvalued",noDataLabel:"No data",staleLabel:"Valuation older than twelve months.",continuedTemplate:"{parent} (cont'd)",overviewHeading:"Overview",netWorthLabel:"Net Worth",assetsLabel:"Assets",liabilitiesLabel:"Liabilities",investedLabel:"Invested",priceGainLabel:"Price Gain",assetClassesLabel:"Asset Classes",positionsLabel:"Positions",portfoliosLabel:"Portfolios",currencyLabel:"Currency",expectedDividendsPaLabel:"Dividends expected p.a.",hasUnvaluedNote:"Includes unvalued positions, not counted in the totals.",categorySplitHeading:"Split by category",clusterHeading:"Overview chart",orgPositionsCountTemplate:"{n} positions",orgChartDetailNote:"Detail per category on the following pages.",morePositionsTemplate:"{n} more positions",subUnitsInStatementNote:"Sub-units: see the positions list.",omittedInStatementNote:"Full detail in the positions list.",positionsHeading:"Positions",positionColumnLabel:"Position",shareColumnLabel:"Share",valueColumnLabel:"Value",totalLabel:"Total net worth",lookThroughHeading:"Look-through: funds dissolved",lookThroughRegionsLabel:"Regions",lookThroughSectorsLabel:"Sectors",lookThroughTopPositionsLabel:"Largest positions",lookThroughNameColumnLabel:"Name",lookThroughShareColumnLabel:"Share of portfolio",lookThroughViaFundsColumnLabel:"Via funds",lookThroughAtLeastTemplate:"at least {pct}",lookThroughDirectLabel:ts.en,lookThroughNFundsTemplate:"{n} funds",lookThroughOneFundLabel:"1 fund",lookThroughCoverageCaveat:"A lower bound: our data provider only supplies each fund's largest positions.",lookThroughFundCoverageTemplate:"{ticker}: {pct} of fund weight named",lookThroughCompositionAsOfTemplate:"Composition as of {date}",cashLabel:"Cash",cashUnavailableNote:"Cash balance unavailable, so no total is shown."}},pl=({root:t,assets:s,rates:r,lang:l,subjectName:o,portfolioNames:m,lookThroughResult:n,fundCount:h,funds:p,locale:c,className:a,settingsCurrentCash:b,cashUnavailable:i=!1})=>{const x=br[l]??br.de,[N,S]=g.useState(null),P=c??(l==="en"?"en-US":"de-DE"),v=new Date().toLocaleDateString(P),y=fo(new Date),E={reportTitle:x.reportTitle,asOfLabel:x.asOfLabel,pageOfTemplate:x.pageOfTemplate,unvaluedLabel:x.unvaluedLabel,staleLabel:x.staleLabel,noDataLabel:x.noDataLabel,continuedTemplate:x.continuedTemplate,overviewHeading:x.overviewHeading,netWorthLabel:x.netWorthLabel,assetsLabel:x.assetsLabel,liabilitiesLabel:x.liabilitiesLabel,investedLabel:x.investedLabel,priceGainLabel:x.priceGainLabel,assetClassesLabel:x.assetClassesLabel,positionsLabel:x.positionsLabel,portfoliosLabel:x.portfoliosLabel,currencyLabel:x.currencyLabel,expectedDividendsPaLabel:x.expectedDividendsPaLabel,hasUnvaluedNote:x.hasUnvaluedNote,categorySplitHeading:x.categorySplitHeading,clusterHeading:x.clusterHeading,orgPositionsCountTemplate:x.orgPositionsCountTemplate,orgChartDetailNote:x.orgChartDetailNote,morePositionsTemplate:x.morePositionsTemplate,subUnits
10InStatementNote:x.subUnitsInStatementNote,omittedInStatementNote:x.omittedInStatementNote,positionsHeading:x.positionsHeading,positionColumnLabel:x.positionColumnLabel,shareColumnLabel:x.shareColumnLabel,valueColumnLabel:x.valueColumnLabel,totalLabel:x.totalLabel,lookThroughHeading:x.lookThroughHeading,lookThroughRegionsLabel:x.lookThroughRegionsLabel,lookThroughSectorsLabel:x.lookThroughSectorsLabel,lookThroughTopPositionsLabel:x.lookThroughTopPositionsLabel,lookThroughNameColumnLabel:x.lookThroughNameColumnLabel,lookThroughShareColumnLabel:x.lookThroughShareColumnLabel,lookThroughViaFundsColumnLabel:x.lookThroughViaFundsColumnLabel,lookThroughAtLeastTemplate:x.lookThroughAtLeastTemplate,lookThroughDirectLabel:x.lookThroughDirectLabel,lookThroughNFundsTemplate:x.lookThroughNFundsTemplate,lookThroughOneFundLabel:x.lookThroughOneFundLabel,lookThroughCoverageCaveat:x.lookThroughCoverageCaveat,lookThroughFundCoverageTemplate:x.lookThroughFundCoverageTemplate,lookThroughCompositionAsOfTemplate:x.lookThroughCompositionAsOfTemplate,cashLabel:x.cashLabel,cashUnavailableNote:x.cashUnavailableNote},Q=(m==null?void 0:m.size)??new Set(s.map(w=>w.portfolio_id)).size,$=h??(p==null?void 0:p.size)??0,O=g.useMemo(()=>{if(!p)return null;let w=null;for(const M of p.values())M.refreshedAt&&(w===null||M.refreshedAt<w)&&(w=M.refreshedAt);return w},[p]),V=g.useMemo(()=>{var M;const w=new Map;if(!m)return w;for(const I of s){const T=(M=m.get(I.portfolio_id))==null?void 0:M.trim();T&&T!==I.portfolio_id&&w.set(I.id,T)}return w},[s,m]),D=async()=>{S("pdf");try{const[{generateNetworthPdf:w},M]=await Promise.all([Ro(()=>import("./networthPdf-D9umwphS.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38])),Qa()]),I=so(s,r,Q,new Date,b),T=I.cash.source!=="positions",Y={netWorthEur:I.netWorthEur,assetsEur:I.assetsEur,liabilitiesEur:I.liabilitiesEur,investedListedEur:I.investedListedEur,priceGainAbsEur:I.priceGainAbsEur,priceGainPct:I.priceGainPct,assetClassCount:I.assetClassCount,positionCount:I.positionCount,portfolioCount:I.portfolioCount,expectedDividendsPaEur:I.expectedDividendsPaEur,hasUnvalued:I.hasUnvalued,...T&&I.cash.amountEur!==0?{manualCashEur:I.cash.amountEur}:{},...i&&T?{cashUnavailable:!0}:{}};w({root:t,overview:Y,locale:P,asOf:v,subjectName:o,strings:E,portfolioNameByNodeId:V,logo:M,lookThroughResult:n,lookThroughFundCount:$,lookThroughFunds:p}),Js({kind:"networth_pdf",scope:"total_wealth"})}catch(w){throw Js({kind:"networth_pdf",scope:"total_wealth",success:!1,error:w}),w}finally{S(null)}},F=()=>{S("csv");try{const w=al(s,r,{portfolioNames:m});let M=il(w,{fundCount:$});const I=fl(ll(n),$,{subjectName:o,asOf:y,oldestRefreshedAt:O});I&&(M=`${M}\r 11${I}\r 12`),hl(M,`kasona-networth-positionen-${v.replace(/[^0-9A-Za-z]+/g,"-")}.csv`)}finally{S(null)}};return e.jsxs("div",{className:`flex items-center gap-2 ${a??""}`,children:[e.jsxs("button",{type:"button",onClick:D,disabled:N!==null,className:"inline-flex items-center gap-1.5 rounded-2xl border border-border bg-card px-3 py-2 font-sans text-xs text-foreground transition-colors hover:text-primary disabled:opacity-50 whitespace-nowrap",children:[e.jsx(Ya,{size:13})," ",x.exportPdf]}),e.jsxs("button",{type:"button",onClick:F,disabled:N!==null,className:"inline-flex items-center gap-1.5 rounded-2xl border border-border bg-card px-3 py-2 font-sans text-xs text-foreground transition-colors hover:text-primary disabled:opacity-50 whitespace-nowrap",children:[e.jsx(Xa,{size:13})," ",x.exportCsv]})]})},vr="min(170px, 78%)",gl="min(85px, 39%)",yr=.6,xl=({investedEur:t,priceGainEur:s,expectedDividendsPaEur:r,labels:l,formatMoney:o,footnote:m,note:n,className:h})=>{const p=t+s+r,c=Math.max(t,t+s,p,0),a=[{key:"invested",label:l.invested,valueEur:t,from:0,to:t},{key:"priceGain",label:l.priceGain,valueEur:s,from:t,to:t+s},{key:"dividends",label:l.dividends,valueEur:r,from:t+s,to:p},{key:"net",label:l.net,valueEur:p,from:0,to:p}],b=a.map((i,x)=>{const N=i.key==="priceGain";return{...i,color:i.key==="invested"?"hsl(var(--muted-foreground))":i.key==="priceGain"?s>=0?"#16a34a":"hsl(var(--destructive))":i.key==="dividends"?"#95ddfa":"hsl(var(--primary))",hasConnector:x<a.length-1,signPrefix:i.key==="dividends"||N}});return c<=0?e.jsx("div",{className:h,children:e.jsx("p",{className:"text-2xs text-muted-foreground
12/70 mt-3.5",children:m})}):e.jsxs("div",{className:h,children:[n&&e.jsx("p",{className:"text-2xs text-muted-foreground/70",children:n}),e.jsx("div",{className:"flex border-b border-border mt-6",style:{height:220},children:b.map(i=>{const x=Math.min(i.from,i.to),N=Math.max(i.from,i.to),S=(N-x)/c*100,P=S>0&&S<yr?yr:S,v=x/c*100,y=`calc(${N/c*100}% + 4px)`,E=`${i.to/c*100}%`,$=`${i.signPrefix&&i.valueEur>=0?"+":""}${o(i.valueEur)}`;return e.jsxs("div",{style:{position:"relative",height:"100%",flex:1},children:[e.jsx("div",{className:"font-sans tabular-nums text-foreground",style:{position:"absolute",bottom:y,left:0,width:"100%",textAlign:"center",fontSize:"12px",fontWeight:700},children:$}),e.jsx("div",{style:{position:"absolute",bottom:`${v}%`,height:`${P}%`,left:"50%",transform:"translateX(-50%)",width:vr,borderRadius:6,background:i.color}}),i.hasConnector&&e.jsx("div",{className:"pointer-events-none border-foreground/25",style:{position:"absolute",bottom:E,left:`calc(50% + ${gl})`,width:`calc(100% - ${vr})`,borderTopWidth:1.5,borderTopStyle:"dashed"}})]},i.key)})}),e.jsx("div",{className:"flex",style:{marginTop:8},children:b.map(i=>e.jsx("div",{className:"px-1 leading-tight break-words text-muted-foreground font-sans",style:{flex:1,textAlign:"center",fontSize:"11px",fontWeight:600},children:i.label},i.key))}),e.jsx("p",{className:"text-2xs text-muted-foreground/70 mt-3.5",children:m})]})};function jt(t,s){return Object.entries(s).reduce((r,[l,o])=>r.split(`{${l}}`).join(String(o)),t)}const bl=({lang:t,positions:s,existingCategories:r,onApply:l,onClose:o})=>{const m=Le(t).categoryAssign,[n,h]=g.useState(()=>new Set),[p,c]=g.useState(""),[a,b]=g.useState(!1),[i,x]=g.useState(null),[N,S]=g.useState(null),[P,v]=g.useState(!1),y=n.size>0&&n.size===s.length,E=()=>{v(!1),h(y?new Set:new Set(s.map(w=>w.assetId)))},Q=w=>{v(!1),h(M=>{const I=new Set(M);return I.has(w)?I.delete(w):I.add(w),I})},$=w=>{v(!1),c(w)},O=s.filter(w=>n.has(w.assetId)),V=new Set(O.map(w=>w.portfolioId)).size,D=new Set(O.filter(w=>w.isFamily).map(w=>w.memberName??w.portfolioId)).size,F=async()=>{if(n.size===0){S(m.bulkSelectionRequired);return}const w=p.trim();if(!w){S(m.bulkCategoryRequired);return}if(S(null),!P){v(!0);return}v(!1),b(!0);const M=s.filter(I=>n.has(I.assetId)).map(I=>({assetId:I.assetId,portfolioId:I.portfolioId,isFamily:I.isFamily}));try{const I=await l(M,w),T=I.filter(ae=>ae.ok).length,Y=I.length-T;x({ok:T,failed:Y}),h(new Set(I.filter(ae=>!ae.ok).map(ae=>ae.target.assetId)))}finally{b(!1)}};return e.jsxs("div",{className:"rounded-xl border border-primary/25 bg-primary/[0.03] p-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[e.jsxs("h4",{className:"flex items-center gap-1.5 text-sm font-semibold text-foreground",children:[e.jsx($r,{size:14,className:"text-primary"})," ",m.bulkTitle]}),e.jsx("button",{onClick:o,className:"shrink-0 inline-flex items-center justify-center w-7 h-7 rounded-lg border border-border/50 text-muted-foreground hover:text-foreground transition-colors",children:e.jsx(Sr,{size:13})})]}),e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsxs("label",{className:"flex items-center gap-2 text-xs text-muted-foreground cursor-pointer select-none",children:[e.jsx("input",{type:"checkbox",checked:y,onChange:E,className:"rounded border-border"}),m.bulkSelectAll]}),e.jsx("span",{className:"text-xs font-sans text-muted-foreground/70",children:jt(m.bulkSelectedCount,{n:n.size,total:s.length})})]}),e.jsx("div",{className:"max-h-64 overflow-y-auto rounded-lg border border-border/30 divide-y divide-border/15 mb-3",children:s.length===0?e.jsx("p",{className:"text-xs text-muted-foreground/60 py-4 text-center",children:"â"}):s.map(w=>e.jsxs("label",{className:"flex items-center gap-2.5 px-3 py-2 text-xs text-foreground/80 hover:bg-foreground
12/[0.02] cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:n.has(w.assetId),onChange:()=>Q(w.assetId),className:"rounded border-border shrink-0"}),e.jsx("span",{className:"flex-1 min-w-0 truncate",title:w.label,children:w.label}),w.memberName&&e.jsx("span",{className:"shrink-0 text-2xs font-sans uppercase tracking-wide text-muted-foreground/50 bg-foreground/[0.04] rounded px-1.5 py-0.5",children:w.memberName})]},w.assetId))}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"flex-1 min-w-0",children:e.jsx(La,{value:p,onChange:$,existingCategories:r,listId:"category-bulk-assign-combobox",placeholder:m.placeholder,lang:t,disabled:a})}),e.jsx(ue,{type:"button",onClick:F,disabled:a||s.length===0,size:"sm",className:`shrink-0 gap-1.5 ${P?"bg-amber-500 text-primary-foreground hover:bg-amber-500/90":""}`,children:a?m.bulkApplying:P?m.bulkConfirmYes:m.bulkApply})]}),P&&!a&&e.jsxs("div",{className:"mt-2 rounded-lg border border-amber-500/30 bg-amber-500/[0.06] px-3 py-2",children:[e.jsx("p",{className:"text-xs text-amber-600 dark:text-amber-400",children:jt(m.bulkConfirmPrompt,{n:n.size,p:V,category:p.trim()})}),D>0&&e.jsx("p",{className:"mt-1 text-xs font-medium text-amber-600 dark:text-amber-400",children:jt(m.bulkConfirmClients,{c:D})})]}),N&&e.jsx("p",{className:"mt-2 text-xs text-amber-500/90",children:N}),i&&e.jsx("p",{className:`mt-2 text-xs ${i.failed>0?"text-amber-500/90":"text-emerald-500/90"}`,children:i.failed>0?jt(m.bulkPartial,{ok:i.ok,total:i.ok+i.failed,failed:i.failed}):jt(m.bulkSuccess,{n:i.ok,category:p.trim()})})]})};function ho(t){const s=t==null?void 0:t.trim();return s||null}async function vl(t,s){const r=ho(s.category),{error:l}=await t.from("kasona_portfolio_assets").update({category:r}).eq("id",s.assetId).eq("portfolio_id",s.portfolioId);if(l)throw l}async function yl(t,s,r){const l=ho(s);return(await Promise.allSettled(t.map(m=>{const n={portfolioId:m.portfolioId,assetId:m.assetId,category:l};return(m.isFamily?r.familyScope:r.ownScope)(n)}))).map((m,n)=>({target:t[n],ok:m.status==="fulfilled",error:m.status==="rejected"?m.reason instanceof Error?m.reason.message:String(m.reason):void 0}))}const Ft="desk:hidePortfolioValues";function _l(){try{return localStorage.getItem(Ft)==="true"}catch{return!1}}function kl(){const[t,s]=g.useState(_l),r=g.useCallback(o=>{s(o);try{localStorage.setItem(Ft,String(o))}catch{}},[]),l=g.useCallback(()=>s(o=>{const m=!o;try{localStorage.setItem(Ft,String(m))}catch{}return m}),[]);return g.useEffect(()=>{const o=m=>{m.key===Ft&&s(m.newValue==="true")};return window.addEventListener("storage",o),()=>window.removeEventListener("storage",o)},[]),{hidden:t,setHidden:r,toggle:l}}const jl="EUR";function Nl(){const[t,s]=g.useState(jl),[r,l]=g.useState(!1);return g.useEffect(()=>{let m=!1;return(async()=>{var n;try{const{data:h}=await Ee.auth.getUser(),p=(n=h.user)==null?void 0:n.id;if(!p)return;const{data:c,error:a}=await Ee.from("profiles").select("display_currency").eq("id",p).single();if(m||a)return;const b=c==null?void 0:c.display_currency;b&&s(b)}catch{}finally{m||l(!0)}})(),()=>{m=!0}},[]),{currency:t,loaded:r,setCurrency:m=>{s(m),(async()=>{var n;try{const{data:h}=await Ee.auth.getUser(),p=(n=h.user)==null?void 0:n.id;if(!p)return;await Ee.from("profiles").update({display_currency:m}).eq("id",p)}catch{}})()}}}const _r={de:{...ft.de,family:{...zs.de,totalValueFamily:"Gesamtwert alle Portfolios (Marktwert)",investedFamily:"Eingesetzt (alle Portfolios)"},emptyPortfolioTitle:"Noch kein Portfolio",emptyPortfolioText:"Lege dein erstes Portfolio an, um loszulegen.",cashUnavailable:"Der Cash-Bestand konnte nicht geladen werden. Das Netto-Vermögen enthält deshalb keinen manuell erfassten Cash-Bestand."},en:{...ft.en,family:{...zs.en,totalValueFamily:"Total Value, All Portfolios (Market)",investedFamily:"Invested (all portfolios)"},emptyPortfolioTitle:"No portfolio yet",emptyPortfolioText:"Create your first portfolio to get started.",cashUnavailable:"Cash balance could not be loaded, so net worth excludes your manually entered cash."}},wl=["category","assetKind","portfolio"],Cl=["category","assetKind","portfolio","member"],po="desk:netWorthView";function Sl(t){return t==="pie"||t==="split"||t==="capital"||t==="flow"}function Pl(){try{const t=localStorage.getItem(po);return Sl(t)?t:"split"}catch{return"split"}}const Tl=new Map;function Ll(t){const s=Jo(t);return Number.isFinite(s)?s:null}const mu=()=>{const t=Oo(),s=Bo(),r=d=>rn({from:s.pathname+s.search,add:!0,forCompanyId:d}),l=new URLSearchParams(s.search).get("portfolio"),{language:o}=kr();Vo();const{access:m,loading:n}=Wo(),h=_r[o]??_r.de,p=o==="en"?"en":"de",{portfolios:c,activePortfolios:a,archivedPortfolios:b,portfolioAssets:i,loading:x,companyId:N,contactName:S,refetchPortfolios:P,toggleArchiveStatus:v,deletePortfolio:y,patchAssetCategory:E,error:Q}=Ho(),$=Vt(),{holdingsWithCriteria:O}=on(),{rates:V,ratesUpdatedAt:D}=Bt(),{hasPortfolioBriefing:F,loading:w,subscriptions:M}=Uo(),{hidden:I,toggle:T}=kl(),{visible:Y,setVisible:ae}=hi(),{currency:J,setCurrency:W}=Nl(),A=g.useMemo(()=>({currency:J,rates:V}),[J,V]),[z,Z]=g.useState(Pl),re=d=>{Z(d);try{localStorage.setItem(po,d)}catch{}},[pe,C]=g.useState(new Set),k=nn(),{value:q,setValue:se,orgClients:be,label:ie}=an(),R=q==="all",u=typeof q=="number",B=Ko(),oe=()=>{R&&B.invalidateQueries({queryKey:["familyOverview"]})},[X,ke]=g.useState(null),[ve,ze]=g.useState(!1);g.useEffect(()=>{if(ze(!1),!N||R){ke(null);return}let d=!1;return(async()=>{try{const{data:_,error:U}=await Ee.from("kasona_cashflow_settings").select("current_cash").eq("company_id",N).maybeSingle();if(d)return;if(U){ke(null),ze(!0);return}ke(_??{current_cash:0})}catch{if(d)return;ke(null),ze(!0)}})(),()=>{d=!0}},[N,R]),Gn("portfolio",!x&&!R);const[Ke,Ce]=g.useState(0),ye=!w&&!F&&a.some(d=>!d.subscribed_portfolio_briefing),We=Go(M),Xe=Tr(a,We),[Se,Ie]=g.useState(!1),Ne=g.useRef(null),me=d=>{if(F&&!w&&Xe.full){Ne.current=d,Ie(!0);return}d()},{tier:tt,limits:Ge,loading:Je}=qo(),qe=c.filter(d=>!Qe(d.portfolio_id)).length,st=d=>{const _=o==="de"?"de":"en";if(hn({level:m.level,loading:Je||n||x,count:qe,limit:Ge.portfolios})){const U=pn({lang:_,limit:Ge.portfolios,tier:tt});te.warning(U.text,U.cta?{action:{label:U.cta.label,onClick:()=>t(U.cta.to)}}:void 0);return}d()};Zo(ye&&!n?`portfolio_premium_promo:${m.level}`:null,()=>en({surface:"portfolio_premium_promo",access_level:m.level}));const ht=()=>{tn({surface:"portfolio_premium_promo",access_level:m.level,cta_target:"checkout",plan:"premium_monthly"}
12),t(sn("/checkout?plan=premium_monthly"))},nt=d=>{C(_=>{const U=new Set(_);return U.has(d)?U.delete(d):U.add(d),U})},at=async d=>{try{await v(d,!0),Ce(_=>_+1),oe(),te.success(o==="de"?"Portfolio archiviert":"Portfolio archived")}catch{te.error(o==="de"?"Fehler beim Archivieren":"Error archiving")}},Pe=async d=>{try{await v(d,!1),Ce(_=>_+1),oe(),te.success(o==="de"?"Portfolio aktiviert":"Portfolio activated")}catch{te.error(o==="de"?"Fehler beim Aktivieren":"Error activating")}},[Me,$e]=g.useState(null),Re=(d,_,U=null)=>$e({mode:d,sourceId:_,sourceCompanyId:U}),[j,le]=g.useState(null),[ge,f]=g.useState(!1),ee=g.useMemo(()=>a.filter(d=>!Qe(d.portfolio_id)),[a]),H=g.useMemo(()=>R?ki(k.members,h.family.selfLabel):null,[R,k.members,h.family.selfLabel]),de=R?k.assets:i,L=async()=>{await P(),Ce(d=>d+1),oe()},fe=async d=>{try{await y(d),Ce(_=>_+1),oe(),te.success(o==="de"?"Portfolio gelöscht":"Portfolio deleted")}catch(_){const U=_ instanceof Error?_.message:String(_);te.error(o==="de"?"Fehler beim Löschen":"Error deleting",{description:U})}},ne=g.useMemo(()=>{const d=new Set;for(const _ of k.members)for(const U of _.portfolios)(U.product_status==="archived"||Qe(U.portfolio_id))&&d.add(U.portfolio_id);return d},[k.members]),xe=g.useMemo(()=>R?k.assets.filter(d=>!ne.has(d.portfolio_id)):[],[R,k.assets,ne]),ce=g.useMemo(()=>{const d=je=>je.shares!=null&&je.shares>0||je.watchtower!==!0,_=(R?xe:i.filter(je=>a.some(Ze=>Ze.portfolio_id===je.portfolio_id))).filter(d),U=new Map(_.map(je=>[je.id,je])),K=je=>{const Ze=je.parent_asset_id;if(Ze==null||Ze===je.id)return!0;const Fs=U.get(Ze);return Fs?Oe(Fs,V)==null:!0},G=_.filter(K),Te=G.reduce((je,Ze)=>je+(Oe(Ze,V)??0),0),Gt=G.reduce((je,Ze)=>je+ea(Ze),0),wo=_.filter(je=>Oe(je,V)==null).length,Co=_.filter(je=>je.ticker_eod!=null&&!(Number(je.shares)>0)).length;return{totalInvested:Te,totalCost:Gt,totalPositions:_.length,unpricedCount:wo,noQuantityCount:Co,activeAssets:_,valueBearingAssets:G}},[R,xe,i,a,V]),pt=g.useMemo(()=>ce.activeAssets.map(d=>({ticker:d.ticker_eod,name:d.stock_name??d.display_name??null,valueEur:Oe(d,V)??0})),[ce.activeAssets,V]),he=wn(pt),Ns=g.useMemo(()=>{if(!R)return[];const d=new Map;for(const K of xe){const G=d.get(K.company_id);G?G.push(K):d.set(K.company_id,[K])}const _=k.members.map(K=>{const G=d.get(K.company_id)??[];return{member:K,assets:G,portfolios:K.portfolios.filter(Te=>!ne.has(Te.portfolio_id)),archivedPortfolios:K.portfolios.filter(Te=>ne.has(Te.portfolio_id)&&!Qe(Te.portfolio_id)),value:G.reduce((Te,Gt)=>Te+(Oe(Gt,V)??0),0)}}),U=_.reduce((K,G)=>K+G.value,0);return _.map(K=>({...K,share:U>0?K.value/U:0})).sort((K,G)=>K.member.is_self!==G.member.is_self?K.member.is_self?-1:1:G.value-K.value)},[R,xe,k.members,ne,V]),[ws,go]=g.useState("category"),Cs=R?Cl:wl,Wt=Cs.includes(ws)?ws:"category",[gt,Ss]=g.useState("sector"),Ps=g.useRef(!1),xo=d=>{Ps.current=!0,Ss(d)},we=R?xe:ce.activeAssets,it=g.useMemo(()=>R?k.members.flatMap(d=>d.portfolios).filter(d=>!ne.has(d.portfolio_id)).map(d=>({portfolio_id:d.portfolio_id,portfolio_name:d.portfolio_name})):a,[R,k.members,ne,a]),Ts=g.useMemo(()=>Ga(we,{groupBy:Wt,rates:V,portfolios:it,rootLabel:Le(o).rootLabel,unassignedLabel:Le(o).unassignedCategory,categoryFallbackLabels:Le(o).categoryFallbackByKind,assetKindLabels:Le(o).assetKind,lang:o==="en"?"en":"de"}),[we,it,Wt,V,o]),Pt=g.useMemo(()=>ce.valueBearingAssets.filter(d=>!bn(d)&&!vn(d)).map(d=>({asset:d,value:Oe(d,V)??0})),[ce.valueBearingAssets,V]),{enabled:Ls,setEnabled:bo}=Cn(),Tt=he.funds??Tl,As=g.useMemo(()=>!he.loading&&Sn(Pt,Tt),[he.loading,Pt,Tt]),Es=Ls&&As,Ht=In(o),vo=g.useMemo(()=>{const d=h.unknown,_=Le(o).unassignedCategory,U=Le(o).categoryFallbackByKind,K=Pt.map(({asset:G,value:Te})=>({asset:G,value:Te,groupKey:gt==="category"&&!G.category?U[qa(G.asset_kind)]??_:Ir(G,gt,d,o,_),shares:G.shares}));return Pn(K,{tab:gt,lang:o,unknownLabel:d,funds:Es?Tt:null}).slices},[Pt,gt,h.unknown,o,Es,Tt]);g.useEffect(()=>{Ps.current||x||yn(ce.activeAssets)&&Ss("category")},[x,ce.activeAssets]);const Lt=g.useMemo(()=>so(we,V,it.length,new Date,X==null?void 0:X.current_cash),[we,V,it.length,X==null?void 0:X.current_cash]),yo=ve&&Lt.cash.source!=="positions",xt=g.useMemo(()=>{const d=new Map;for(const _ of we){const U=R&&!_.is_self;d.set(_.id,{portfolioId:_.portfolio_id,isFamily:U})}return d},[we,R]),bt=g.useMemo(()=>{var _;const d=new Map;for(const U of we){const K=(_=U.category)==null?void 0:_.trim();if(!K)continue;const G=Br(K,o)??K,Te=ta(G);d.has(Te)||d.set(Te,G)}return Array.from(d.values()).sort((U,K)=>U.localeCompare(K))},[we,o]),_o=d=>{var _,U,K;return((_=d.display_name)==null?void 0:_.trim())||((U=d.stock_name)==null?void 0:U.trim())||((K=d.ticker_eod)==null?void 0:K.trim())||d.id},[At,Is]=g.useState(new Set),[ko,Ds]=g.useState(!1),Ut=g.useMemo(()=>we.filter(d=>{var _;return!((_=d.category)!=null&&_.trim())}).map(d=>{const _=xt.get(d.id);return{assetId:d.id,portfolioId:_.portfolioId,isFamily:_.isFamily,label:_o(d),memberName:R?d.member_name:null}}),[we,xt,R]),Et=async(d,_)=>{Is(U=>new Set([...U,...d.map(K=>K.assetId)]));try{const U=await yl(d,_,{ownScope:G=>vl(Ee,G),familyScope:G=>$.mutateAsync({op:"update",portfolio_id:G.portfolioId,asset_id:G.assetId,category:G.category}).then(()=>{})}),K=(_==null?void 0:_.trim())||null;for(const G of U)G.ok&&!G.target.isFamily&&E(G.target.assetId,K);return U}finally{Is(U=>{const K=new Set(U);for(const G of d)K.delete(G.assetId);return K})}},jo={lang:o==="en"?"en":"de",existingCategories:bt,getTarget:d=>xt.get(d)??null,onAssign:(d,_)=>{const U=xt.get(d);U&&Et([{assetId:d,portfolioId:U.portfolioId,isFamily:U.isFamily}],_).then(K=>{const[G]=K;G!=null&&G.ok||te.error(o==="de"?"Kategorie konnte nicht gespeichert werden":"Could not save category")})},savingIds:At},vt=g.useMemo(()=>R?k.assets.filter(d=>d.is_self):i,[R,k.assets,i]),Ms=g.useMemo(()=>{const d=new Map;for(const _ of vt)d.set(_.id,_.category??null);return d},[vt]),No=g.useMemo(()=>{const d=new Map;for(const _ of we)d.set(_.id,_.category??null);return d},[we]),$s=(d,_)=>{const U=vt.find(K=>K.id===d);U&&Et([{assetId:d,portfolioId:U.portfolio_id,isFamily:!1}],_).then(([K])=>{K!=null&&K.ok||te.error(o==="de"?"Kategorie konnte nicht gespeichert werden":"Could not save category")})},Kt=g.useMemo(()=>
12{const d=vt.find(_=>_.id===j)??we.find(_=>_.id===j);return d?{assetId:d.id,label:ot(d)??d.ticker_eod??d.id,tickerEod:d.ticker_eod,stockName:d.stock_name,shares:d.shares,sourcePortfolioId:d.portfolio_id}:null},[vt,we,j]);return x?e.jsx(Qo,{}):Q&&N==null?e.jsxs("div",{className:"space-y-4 animate-fade-in",children:[e.jsx(es,{icon:e.jsx(rs,{size:28,className:"text-primary"}),title:"Portfolios"}),e.jsx(dn,{onRetry:P})]}):e.jsx(Mn.Provider,{value:I,children:e.jsx(ca.Provider,{value:A,children:e.jsxs("div",{className:"space-y-8 animate-fade-in",children:[e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between sm:gap-6",children:[e.jsxs("div",{"data-tour":"portfolio-header",className:"min-w-0",children:[e.jsx(es,{icon:e.jsx(rs,{size:28,className:"text-primary"}),title:"Portfolios",subtitle:R?`${ce.totalPositions} ${h.positions} · ${Ns.reduce((d,_)=>d+_.portfolios.length,0)} ${h.activePortfolios} · ${k.counts.members} ${h.family.members}`:`${ce.totalPositions} ${h.positions} · ${a.length} ${h.activePortfolios}`}),e.jsxs("div",{className:"mt-2 space-y-1",children:[ce.unpricedCount>0&&e.jsxs("p",{className:"flex items-center gap-1.5 text-xs text-amber-600 dark:text-amber-400",children:[e.jsx(Fe,{size:11,className:"shrink-0"}),ce.unpricedCount," ",h.unpricedWarning.replace("{plural}",ce.unpricedCount===1?"":o==="en"?"s":"en")]}),ce.noQuantityCount>0&&e.jsxs("p",{className:"flex items-center gap-1.5 text-xs text-amber-600 dark:text-amber-400",children:[e.jsx(Fe,{size:11,className:"shrink-0"}),ce.noQuantityCount," ",h.noQuantityWarning.replace("{plural}",ce.noQuantityCount===1?"":o==="en"?"s":"en")]})]})]}),e.jsxs("div",{className:"flex flex-wrap items-end gap-3 min-w-0",children:[e.jsx(cn,{family:k,orgClients:be,value:q,onChange:se,language:o,className:"w-full sm:w-auto shrink-0"}),e.jsxs(ue,{onClick:()=>t("/desk/decision-room"),size:"sm",className:"gap-1.5 shrink-0",children:[e.jsx(Ja,{size:15})," ",h.startReviewLabel]}),!R&&e.jsx(mn,{target:{kind:"prompt",prompt:fn(ee.map(d=>d.portfolio_name),p)},lang:p,analysisKind:"portfolio_review",analysisSurface:"portfolio"}),!R&&e.jsx(un,{language:o,companyId:N,portfolioAssets:i})]})]}),R&&e.jsx(Rs,{language:o,detail:`${k.counts.members} ${h.family.members} · ${k.counts.portfolios} ${h.family.portfolios} · ${k.counts.assets} ${h.family.positions}`}),u&&e.jsx(Rs,{language:o,subject:ie??void 0,detail:`${i.length} ${h.family.positions}`}),e.jsxs("section",{children:[e.jsx(za,{assets:we,rates:V,portfolioCount:it.length,lang:o,settingsCurrentCash:X==null?void 0:X.current_cash,cashUnavailable:ve,onToggleHidden:T,currency:J,onCurrencyChange:W,ratesUpdatedAt:D,headerActions:e.jsx(pl,{root:Ts,assets:we,rates:V,lang:o==="en"?"en":"de",subjectName:S??"",settingsCurrentCash:X==null?void 0:X.current_cash,cashUnavailable:ve,portfolioNames:new Map(it.map(d=>[d.portfolio_id,d.portfolio_name??d.portfolio_id])),lookThroughResult:he.loading?void 0:he.result,fundCount:he.loading?0:he.fundCount,funds:he.loading?void 0:he.funds})}),yo&&e.jsxs(Lr,{className:"mt-4",children:[e.jsx(Fe,{className:"h-4 w-4"}),e.jsx(Ar,{children:h.cashUnavailable})]}),e.jsxs(Ye,{className:"mt-5 overflow-hidden",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 border-b border-border px-5 py-3.5",children:[e.jsx(Tn,{value:z,onChange:re,lang:o}),z==="split"&&e.jsx(Ln,{value:Wt,options:Cs,onChange:go,lang:o})]}),z==="pie"&&e.jsxs("div",{"data-tour":"portfolio-allocation",children:[e.jsx(Dr,{activeTab:gt,setActiveTab:xo,lang:o}),As&&e.jsx("div",{className:"flex justify-end px-6 pt-4","data-testid":"donut-lookthrough-control",children:e.jsx(Yo,{layout:"pill",checked:Ls,onCheckedChange:bo,label:Ht.label,"aria-label":Ht.ariaLabel,title:Ht.title})}),e.jsx("div",{className:"p-6",children:e.jsx(Mr,{chartData:vo,centerLabel:ce.totalInvested>0?h.valueLabel:h.positionsLabel,centerValue:ce.totalInvested>0?Ve(ut(ce.totalInvested,A).text,I):`${ce.totalPositions}`,noDataText:h.noData,totalValue:ce.totalInvested,lang:o})})]}),z==="split"&&e.jsxs("div",{className:"p-5",children:[Ut.length>0&&e.jsx("div",{className:"mb-4",children:ko?e.jsx(bl,{lang:o==="en"?"en":"de",positions:Ut,existingCategories:bt,onApply:Et,onClose:()=>Ds(!1)}):e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 rounded-xl border border-amber-500/25 bg-amber-500/[0.04] px-4 py-3",children:[e.jsxs("p",{className:"flex items-center gap-2 text-xs text-amber-600 dar
12k:text-amber-400",children:[e.jsx($r,{size:14,className:"shrink-0"}),Le(o).categoryAssign.unassignedCallout.replace("{n}",String(Ut.length))]}),e.jsx("button",{type:"button",onClick:()=>Ds(!0),className:"shrink-0 inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-semibold bg-amber-500/15 text-amber-700 dark:text-amber-400 hover:bg-amber-500/25 transition-colors",children:Le(o).categoryAssign.unassignedCalloutCta})]})}),e.jsx(An,{root:Ts,lang:o,categoryAssignment:jo})]}),z==="capital"&&e.jsx("div",{className:"p-5",children:e.jsx(xl,{investedEur:Lt.investedListedEur,priceGainEur:Lt.priceGainAbsEur,expectedDividendsPaEur:Lt.expectedDividendsPaEur,labels:{invested:Le(o).invested,priceGain:Le(o).priceGain,dividends:Le(o).expectedDividendsPa,net:Le(o).overview.capitalNet},formatMoney:d=>Ve(En(d,o),I),footnote:Le(o).overview.capitalFootnote,note:J!=="EUR"?Le(o).overview.capitalEurNote:void 0})}),z==="flow"&&e.jsx("div",{className:"p-5",children:e.jsx(nl,{lang:o})})]})]}),!R&&ce.activeAssets.length>0&&!Y&&he.fundCount>0&&e.jsx(mi,{checked:!1,onCheckedChange:ae,t:(d,_)=>o==="de"?d:_}),!R&&ce.activeAssets.length>0&&Y&&e.jsx(ui,{result:he.result,loading:he.loading,error:he.error,unresolvedFunds:he.unresolvedFunds,fundCount:he.fundCount,fundCandidateCount:he.fundCandidateCount,positions:he.positions,funds:he.funds,direct:he.direct,computeForTickers:he.computeForTickers,t:(d,_)=>o==="de"?d:_,headerAction:e.jsx(ro,{checked:!0,onCheckedChange:ae,t:(d,_)=>o==="de"?d:_})},N),!R&&N!=null&&a.length>0&&e.jsxs("div",{className:"space-y-8",children:[e.jsx("div",{"data-tour":"portfolio-manage",children:e.jsx(Ws,{hideGuide:!0,hideCombinedOverview:!0,focusPortfolioId:l,onAddPortfolio:()=>st(()=>me(()=>t(r()))),addPortfolioLabel:h.addPortfolio,onArchivePortfolio:at,onDeletePortfolio:fe,onMergePortfolio:d=>Re("merge",d),onSplitPortfolio:d=>Re("split",d),categoryOf:d=>Ms.get(d)??null,existingCategories:bt,onAssignCategory:$s,savingCategoryIds:At,onMovePosition:le},Ke)}),ye&&e.jsxs(Ye,{className:"relative overflow-hidden border-primary/20 p-6",children:[e.jsx("div",{className:"absolute top-0 right-0 w-[280px] h-[280px] bg-primary/[0.06] rounded-full blur-[90px] pointer-events-none"}),e.jsxs("div",{className:"relative z-10 flex flex-col gap-5 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-1.5 eyebrow-sans text-primary/80 mb-2",children:[e.jsx(Jt,{size:12})," ",h.briefingPromoKicker]}),e.jsx("h3",{className:"text-base font-semibold text-foreground",children:h.briefingPromoTitle}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1.5 max-w-xl",children:h.briefingPromoText})]}),e.jsxs(ue,{onClick:ht,className:"gap-1.5 shrink-0",children:[e.jsx(ei,{size:15})," ",h.briefingPromoCta]})]})]})]}),!R&&N!=null&&a.length===0&&e.jsxs(Ye,{className:"p-10 text-center",children:[e.jsx(er,{size:28,className:"text-primary/60 mx-auto mb-4"}),e.jsx("h3",{className:"text-base font-semibold text-foreground",children:h.emptyPortfolioTitle}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1.5 max-w-sm mx-auto",children:h.emptyPortfolioText}),e.jsxs(ue,{onClick:()=>st(()=>me(()=>t(r()))),className:"mt-5 gap-1.5",children:[e.jsx(er,{size:15})," ",h.addPortfolio]})]}),R&&e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"flex justify-end",children:e.jsxs(ue,{variant:"outline",size:"sm",onClick:()=>f(!0),className:"gap-1.5 hover:text-primary transition-colors",children:[e.jsx(ti,{className:"h-3.5 w-3.5"})," ",h.addPortfolio]})}),Ns.map(d=>e.jsx(ol,{member:d.member,assets:[...d.assets,...k.assets.filter(_=>_.company_id===d.member.company_id&&ne.has(_.portfolio_id)&&!Qe(_.portfolio_id))],portfolios:d.portfolios,archivedPortfolios:d.archivedPortfolios,onSelfUnarchive:Pe,onSelfDelete:fe,value:d.value,share:d.share,rates:V,language:o,strings:{selfLabel:h.family.selfLabel,portfolios:h.family.portfolios,positions:h.family.positions,noPortfolios:h.family.noPortfolios,archived:h.archived},briefingQuota:Ll(d.member.plan),renderSelfBody:d.member.is_self&&N!=null?()=>e.jsx(Ws,{embedded:!0,ownScopeOnly:!0,hideGuide:!0,hideCombinedOverview:!0,onArchivePortfolio:at,onDeletePortfolio:fe,onMergePortfolio:_=>Re("merge",_),onSplitPortfolio:_=>Re("split",_),categoryOf:_=>Ms.get(_)??null,existingCategories:bt,onAssignCategory:$s,savingCategoryIds:At,onMovePosition:le},Ke):void 0,onMergeClientPortfolio:_=>Re("merge",_,d.member.company_id),onSplitClientPortfolio:_=>Re("split",_,d.member.company_id),positions:{categoryOf:_=>No.get(_)??null,existingCategories:bt,onAssignCategory:(_,U)=>{const K=xt.get(_);K&&Et([{assetId:_,portfolioId:K.portfolioId,isFamily:K.isFamily}],U).then(([G])=>{G!=null&&G.ok||te.error(o==="de"?"Kategorie konnte nicht gespeichert werden":"Could not save category")})},savingCategoryIds:At,onMovePosition:le}},d.member.company_id))]}),!R&&b.length>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-3 px-1",children:[e.jsx("div",{className:"h-px flex-1 bg-border/50"}
12),e.jsxs("span",{className:"eyebrow-sans text-muted-foreground/50 flex items-center gap-1.5",children:[e.jsx(Rr,{size:12}),h.archived]}),e.jsx("div",{className:"h-px flex-1 bg-border/50"})]}),b.map(d=>{const _=i.filter(G=>G.portfolio_id===d.portfolio_id),U=pe.has(d.portfolio_id),K=_.reduce((G,Te)=>G+(Oe(Te,V)??0),0);return e.jsx(pi,{portfolio:d,assets:_,portfolioValue:K,isExpanded:U,onToggle:()=>nt(d.portfolio_id),onStockClick:G=>t(Xo(G,!0)),language:o,isArchived:!0,holdingsWithCriteria:O,onUnarchive:()=>Pe(d.portfolio_id),onDelete:()=>fe(d.portfolio_id),subscribedBriefing:d.subscribed_portfolio_briefing},d.portfolio_id)})]}),Me&&N!=null&&e.jsx(Pi,{open:!0,onOpenChange:d=>{d||$e(null)},mode:Me.mode,initialSourceId:Me.sourceId,portfolios:ee,assets:de,companyId:N,language:o,scope:H,initialSourceCompanyId:Me.sourceCompanyId,onDone:L}),ge&&e.jsx($i,{open:!0,onOpenChange:f,clients:k.members.filter(d=>!d.is_self).map(d=>{var _;return{companyId:d.company_id,label:((_=d.customer_name)==null?void 0:_.trim())||`#${d.company_id}`}}),language:o,onGoToWizard:d=>t(d==null?r():r(d))}),Kt&&e.jsx(Di,{open:!0,onOpenChange:d=>{d||le(null)},position:Kt,candidates:ee.filter(d=>d.portfolio_id!==Kt.sourcePortfolioId),language:o,scope:H,onMoved:L}),e.jsx(ri,{open:Se,onOpenChange:Ie,onContinue:()=>{const d=Ne.current;Ne.current=null,d==null||d()}})]})})})};export{mu 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.