1import{j as t}from"./vendor-radix-6dBKxLfn.js";import{o as I,_ as Re,c as fe,e as He,y as wt,ac as Tt,$ as Ye,O as Rt,cf as We,b1 as Qe,B as C,I as ge,C as V,cl as St,ao as At,V as Xe,t as k,X as It,b2 as Pt,c5 as Lt,a5 as kt,aD as zt,u as Dt,aJ as Ot,aa as Bt,N as Ft,a3 as Mt,a4 as Se,g as Ut,ak as Ae}from"./index-CZxwBdsI.js";import{_ as N}from"./vendor-datadog-D3gwQpHA.js";import{a as U,u as h}from"./vendor-i18n-B-AdlurK.js";import{u as re,i as F,j as M,r as p,o as Vt}from"./vendor-query-jnzAvHUk.js";import{P as Je}from"./page-title-X2FduTCy.js";import{N as Kt}from"./nav-tabs-CsctvXIp.js";import"./vendor-date-CemE0fj8.js";import{a as $t}from"./filter-date-range-D233jDPB.js";import{c as je}from"./card-BB-EzJ8z.js";import{D as de}from"./data-table-NVPW0QOM.js";import{F as Gt}from"./filter-dropdown-B97NKVrR.js";import{L as qt}from"./list-page-layout-BKBF2jCg.js";import{E as Ie}from"./empty-CkTzGOSe.js";import{E as Ht}from"./empty-icon-C4IyT05g.js";import{D as Yt,a as Wt,b as Qt,g as Xt}from"./dropdown-menu-DVG6nqLs.js";import{C as ne}from"./confirmation-dialog-CUuzcOYm.js";import{c as Ze}from"./currency-CXpkR5tp.js";import{F as $}from"./field-CiM0_sXs.js";import{S as K}from"./select-CGLiJPH5.js";import{S as et}from"./search-select-DWvJp3KS.js";import{D as Jt}from"./date-picker-CTwZ8HMm.js";import{A as Zt}from"./alert-_d8iBvLa.js";import{R as es}from"./radio-group-D7nhu0F6.js";import{S as ts}from"./stepper-Cv6TBT6x.js";import{D as ss}from"./detail-page-layout-BG61x2vK.js";import{D as Pe}from"./detail-section-B7igv8yZ.js";import{D as os}from"./detail-page-header-BTSENFvt.js";import{u as ns}from"./use-verify-permission.hook-DJsx5DnT.js";import{A as rs}from"./access-denied-alert-i46RS9pO.js";
1import"./vendor-shared-D7qeTqf-.js";import"./vendor-charts-CmjbgAhh.js";import"./nav-link-BD2hPQEd.js";import"./time-picker-CoB_OqYH.js";import"./field-DrQNaCOk.js";import"./vendor-table-szJPgfvF.js";import"./list-page-header-DT1dW2p8.js";import"./list-filter-toolbar-UBT54uAc.js";import"./intl-DBWlphZd.js";import"./textarea-DaVSFYgM.js";import"./field-label-row-BxLZOzy4.js";import"./combobox-yC6-o-UZ.js";import"./command-DmRDzTZm.js";import"./data-item-DcZRDrLc.js";function is(e={},s=!0){return re({queryKey:["GET/costs/kpis",e],queryFn:()=>I.getInstance().getCostKpis(e).then(n=>n?.data),enabled:s,useErrorBoundary:!1})}function as(e=!0){return re({queryKey:["GET/costs/config/profiles"],queryFn:()=>I.getInstance().getCostProfiles().then(o=>o?.data),enabled:e,useErrorBoundary:!1})}function ls(e,s=!0){return re({queryKey:["GET/costs/config/profiles",e],queryFn:()=>I.getInstance().getCostProfile(e).then(n=>n?.data),enabled:s&&!!e,useErrorBoundary:!1})}function cs(e,s=!0){return re({queryKey:["GET/costs/config/profiles/components",e],queryFn:()=>I.getInstance().getCostProfileComponents(e).then(n=>n?.data),enabled:s&&!!e,useErrorBoundary:!1})}function ds(e={},s=!0){return re({queryKey:["GET/costs/breakdown",e],queryFn:()=>I.getInstance().getCostBreakdown(e).then(n=>n?.data),enabled:s,useErrorBoundary:!1})}function us(){const e=F();return M(["create-cost-profile"],s=>I.getInstance().createCostProfile(s).then(n=>n?.data),{useErrorBoundary:!1,onSuccess:()=>{e.invalidateQueries({queryKey:["GET/costs/config/profiles"]})}})}function ps(){const e=F();return M(["update-cost-profile"],({profileKey:s,payload:o})=>I.getInstance().updateCostProfile(s,o).then(r=>r?.data),{useErrorBoundary:!1,onSuccess:(s,{profileKey:o})=>{e.invalidateQueries({queryKey:["GET/costs/config/profiles"]}),e.invalidateQueries({queryKey:["GET/costs/config/profiles",o]})}})}function tt(){const e=F();return M(["delete-cost-profile"],s=>I.getInstance().deleteCostProfile(s).then(n=>n?.data),{useErrorBoundary:!1,onSuccess:()=>{e.invalidateQueries({queryKey:["GET/costs/config/profiles"]})}})}function st(){const e=F();return M(["create-cost-profile-component"],({profileKey:s,payload:o})=>I.getInstance().createCostProfileComponent(s,o).then(r=>r?.data),{useErrorBoundary:!1,onSuccess:(s,{profileKey:o})=>{e.invalidateQueries({queryKey:["GET/costs/config/profiles/components",o]})}})}function ms(){const e=F();return M(["delete-cost-profile-component"],({profileKey:s,componentId:o})=>I.getInstance().deleteCostProfileComponent(s,o).then(r=>r?.data),{useErrorBoundary:!1,onSuccess:(s,{profileKey:o})=>{e.invalidateQueries({queryKey:["GET/costs/config/profiles/components",o]})}})}function fs(){const e=F();return M(["bind-cost-profile-connection"],({profileKey:s,payload:o})=>I.getInstance().bindCostProfileConnection(s,o).then(r=>r?.data),{useErrorBoundary:!1,onSuccess:(s,{profileKey:o})=>{e.invalidateQueries({queryKey:["GET/costs/config/profiles"]}),e.invalidateQueries({queryKey:["GET/costs/config/profiles",o]})}})}function gs(){const e=F();return M(["unbind-cost-profile-connection"],({profileKey:s,connectionId:o})=>I.getInstance().unbindCostProfileConnection(s,o).then(r=>r?.data),{useErrorBoundary:!1,onSuccess:(s,{profileKey:o})=>{e.invalidateQueries({queryKey:["GET/costs/config/profiles"]}),e.invalidateQueries({queryKey:["GET/costs/config/profiles",o]})}})}function xs(){const e=F();return M(["update-cost-profile-component"],({profileKey:s,componentId:o,payload:n})=>I.getInstance().updateCostProfileComponent(s,o,n).then(i=>i?.data),{useErrorBoundary:!1,onSuccess:(s,{profileKey:o})=>{e.invalidateQueries({queryKey:["GET/costs/config/profiles/components",o]})}})}const Le="en",ke=["en","es","pt","fr","ja","tr","zh","ru","ar","de"];function ze(e){const s=(e??"").trim();if(!s)return Le;if(ke.includes(s))return s;const o=s.split("-")[0];return o&&ke.includes(o)?o:Le}function hs({children:e}){const[s,o]=p.useState(!1);return p.useEffect(()=>{const n=ze(U.language||localStorage.getItem("lang"));Re(Object.assign({
1"./lang/ar.json":()=>N(()=>import("./ar-BZ9S2Fdc.js"),[]),
1"./lang/de.json":()=>N(()=>import("./de-DBv8ifUq.js"),[]),
1"./lang/en.json":()=>N(()=>import("./en-DKBSdImK.js"),[]),
1"./lang/es.json":()=>N(()=>import("./es-Bbgnnhmw.js"),[]),
1"./lang/fr.json":()=>N(()=>import("./fr-DQUKQlOb.js"),[]),
1"./lang/ja.json":()=>N(()=>import("./ja-DJ1u2UL6.js"),[]),
1"./lang/pt.json":()=>N(()=>import("./pt-D9pR19Lr.js"),[]),
1"./lang/ru.json":()=>N(()=>import("./ru-BPdBBU-o.js"),[]),
1"./lang/tr.json":()=>N(()=>import("./tr-BPgcWG7U.js"),[]),
1"./lang/zh.json":()=>N(()=>import("./zh-BXVZtkQG.js"),[])}),`./lang/${n}.json`,3).then(r=>{U.addResourceBundle(n,"translation",r.default??r,!0,!0),o(!0)}).catch(()=>{N(()=>import("./en-DKBSdImK.js"),[]).then(r=>{U.addResourceBundle("en","translation",r.default??r,!0,!0),o(!0)})})},[]),p.useEffect(()=>{const n=()=>{const r=ze(U.language);Re(Object.assign({
1"./lang/ar.json":()=>N(()=>import("./ar-BZ9S2Fdc.js"),[]),
1"./lang/de.json":()=>N(()=>import("./de-DBv8ifUq.js"),[]),
1"./lang/en.json":()=>N(()=>import("./en-DKBSdImK.js"),[]),
1"./lang/es.json":()=>N(()=>import("./es-Bbgnnhmw.js"),[]),
1"./lang/fr.json":()=>N(()=>import("./fr-DQUKQlOb.js"),[]),
1"./lang/ja.json":()=>N(()=>import("./ja-DJ1u2UL6.js"),[]),
1"./lang/pt.json":()=>N(()=>import("./pt-D9pR19Lr.js"),[]),
1"./lang/ru.json":()=>N(()=>import("./ru-BPdBBU-o.js"),[]),
1"./lang/tr.json":()=>N(()=>import("./tr-BPgcWG7U.js"),[]),
1"./lang/zh.json":()=>N(()=>import("./zh-BXVZtkQG.js"),[])
1}),`./lang/${r}.json`,3).then(i=>{U.addResourceBundle(r,"translation",i.default??i,!0,!0)}).catch(()=>{})};return U.on("languageChanged",n),()=>{U.off("languageChanged",n)}},[]),s?t.jsx(t.Fragment,{children:e}):null}const ce=[{id:"insights",path:"insights",labelKey:"costs.insightsTab",labelDefault:"Cost Insights"},{id:"profiles",path:"profiles",labelKey:"costs.profilesTab",labelDefault:"Fee Profiles"}],ys="/costs/insights",bs=()=>{const{t:e}=h(),s=fe(),{pathname:o}=He(),n=ce.findIndex(l=>{const d=`/costs/${l.path}`;return o===d||o.startsWith(`${d}/`)}),r=n===-1?0:n,i=ce[r].id;return{tabs:p.useMemo(()=>ce.map(l=>({id:`costs-tab-${l.id}`,label:e(l.labelKey,l.labelDefault),content:null})),[e]),defaultTab:r,handleClickTab:l=>{const d=ce[l];d&&(wt("tab.selected",{section:Tt(),tab:d.id}),s(`/costs/${d.path}`))},currentTab:i}};function _s(){const{t:e}=h(),{isTesting:s}=Ye(),{tabs:o,defaultTab:n,handleClickTab:r,currentTab:i}=bs();return t.jsxs(t.Fragment,{children:[t.jsx(Je,{className:"mb-5",children:e("costs.title","Costs")}),t.jsx("div",{className:"sticky z-20 bg-surface pt-5",style:{top:s?"99px":"55px"},children:t.jsx(Kt,{tabs:o,defaultTab:n,onChange:r,contentClassName:"hidden"},i)}),t.jsx("div",{className:"flex flex-1 flex-col pb-6 pt-6",children:t.jsx(Rt,{})})]})}const js=/^\d{4}-\d{2}$/,ve=e=>typeof e=="string"&&js.test(e),vs=(e,s)=>`${e}-${String(s+1).padStart(2,"0")}`,ot=(e,s)=>{if(!ve(e))return e;const[o,n]=e.split("-").map(Number),r=new Date(Date.UTC(o,n-1,1,12));return new Intl.DateTimeFormat(s,{month:"long",year:"numeric",timeZone:"UTC"}).format(r)},Cs=12,Es=(e,s,o)=>{const n=[],r=new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),1,12));r.setUTCMonth(r.getUTCMonth()-1);for(let i=0;i<Cs;i+=1)n.push(vs(r.getUTCFullYear(),r.getUTCMonth())),r.setUTCMonth(r.getUTCMonth()-1);return ve(o)&&!n.includes(o)&&(n.push(o),n.sort((i,a)=>a.localeCompare(i))),n.map(i=>({value:i,label:ot(i,s)}))},nt=()=>{const{i18n:e}=h();return e?.language||"en"},Ns=e=>{const s=nt(),o=new Date,n=`${o.getFullYear()}-${o.getMonth()}`;return p.useMemo(()=>Es(new Date,s,e),[s,e,n])},ws=(e,s)=>{const{t:o,i18n:n}=h(),r=nt(),{setFilter:i}=We(),a=Ns(e||void 0),u=o("costs.insights.period","Period"),l=p.useMemo(()=>[{id:"period",icon:"Calendar",label:u,type:"radio",items:a,selectedValue:e,onValueChange:m=>{s?.(m),i("period",m)},clearable:!1}],[u,a,e,i,s]),d=e?[{id:"period",label:ot(e,r)}]:[],c=()=>{s?.(""),i("period","")};return{filterConfigs:l,appliedFilters:d,handleRemoveFilter:c,handleClearAll:c,filterLang:$t(n?.language||"en")}},Ts="costs-insights-filters",Rs="/costs/insights";function O(e,s){const o=s?.trim();if(o)try{return new Intl.NumberFormat("pt-BR",{style:"currency",currency:o}).format(e/100)}catch{}return new Intl.NumberFormat("pt-BR",{minimumFractionDigits:2,maximumFractionDigits:2}).format(e/100)}function Ss(e,s){const o=O(Math.abs(e),s);return e>0?`+${o}`:e<0?`-${o}`:o}function De(e){return new Intl.NumberFormat("pt-BR").format(e)}function Oe(e){return new Intl.NumberFormat("pt-BR",{style:"percent",minimumFractionDigits:2,maximumFractionDigits:2}).format(e)}function As(e){const s=new Intl.NumberFormat("pt-BR",{style:"percent",minimumFractionDigits:1,maximumFractionDigits:1}).format(Math.abs(e));return e>0?`+${s} â`:e<0?`â${s} â`:s}function Is(e,s=""){return e>0?"text-destructive":e<0?"text-emerald-600":s}const T={profile:"profile",component:"component",segment:"segment",empty:"empty"};function Ps(e){return e.components.length>0||e.segments.length>0}function Ls(e){return e.components.map((s,o)=>({kind:T.component,id:`breakdown-l1-${e.profile_key}-${o}-${s.cost_type}`,component:s,first:o===0}))}function ks(e){return e.segments.map((s,o)=>({kind:T.segment,id:`breakdown-l2-${e.profile_key}-${o}-${s.card_brand}-${s.card_type}`,segment:s,first:o===0}))}function zs(e){return Ps(e)?[...Ls(e),...ks(e)]:[{kind:T.empty,id:`breakdown-empty-${e.profile_key}`}]}function Ds(e,s){return e.flatMap(o=>{const n=s.has(o.profile_key),r={kind:T.profile,id:`breakdown-l0-${o.profile_key}`,node:o,expanded:n};return n?[r,...zs(o)]:[r]})}const Os=1e4;function Bs(e){const[s,o]=p.useState(!1),[n,r]=p.useState(()=>new Set),i={};e&&(i.period=e),s&&(i.deviation_min_minor=Os);const{data:a,isLoading:u,isError:l}=ds(i),d=p.useCallback(f=>{r(x=>{const b=new Set(x);return b.has(f)?b.delete(f):b.add(f),b})},[]),c=a?.profiles;return{rows:p.useMemo(()=>Ds(c??[],n),[c,n]),isLoading:u,isError:l,highestOnly:s,setHighestOnly:o,toggleProfile:d}}const Fs=e=>e>0?"bg-destructive/10 text-destructive":e<0?"bg-emerald-50 text-emerald-700 dark:bg-emerald-900/20 dark:text-emerald-400":"bg-muted text-muted-foreground",be={AVAILABLE:"",UNAVAILABLE_NO_PROFILE:"costs.insights.unavailable.noProfile",UNAVAILABLE_NO_SETTLEMENT:"costs.insights.unavailable.noSettlement",AWAITING_SETTLEMENT:"costs.insights.unavailable.awaitingSettlement",PROVISIONAL:"costs.insights.unavailable.provisional",NOT_COMPARABLE:"costs.insights.unavailable.notComparable"},Ce="â",Ms=320,Y={txns:96,volume:132,rate:136,expected:132,actual:200,deviation:200},Us=44;function W({children:e}){return t.jsx("div",{className:"text-right tabular-nums",children:e})}function B(){return t.jsx("span",{className:"text-muted-foreground",children:Ce})}function Be({deviationMinor:e,deviationState:s,currency:o}){const{t:n}=h();if(s==="NOT_COMPARABLE")return t.jsx("span",{className:"text-xs text-muted-foreground","data-testid":"deviation-not-comparable",children:n("costs.insights.breakdown.notComparable")});if(e==null){const r=s&&s in be?be[s]:"costs.insights.unavailable.awaitingSettlement";return t.jsxs("span",{className:"whitespace-nowrap text-xs text-muted-foreground",children:[t.jsx("span",{className:"text-base font-semibold",children:Ce}),t.jsx("span",{className:"ml-2",children:r?n(r):""})]})}return t.jsx("span",{className:"rounded-full px-2 py-0.5 text-xs font-semibold "+Fs(e),"data-testid":"deviation-number",children:Ss(e,o)})}function Vs({actualMinor:e,availability:s,currency:o}){const{t:n}=h();if(e!=null)return t.jsx(t.Fragment,{children:O(e,o)});const r=be[s];return r?t.jsxs("span",{className:"whitespace-nowrap text-xs text-muted-foreground","data-testid":"actual-unavailable",children:[t.jsx("span",{className:"text-base",children:Ce})," ",n(r)]}):t.jsx(B,{})}function Ks({row:e,onToggle:s}){const{t:o}=h(),{node:n}=e,r=e.expanded?o("costs.insights.breakdown.collapseProfile",{name:n.name}):o("costs.insights.breakdown.expandProfile",{name:n.name});return t.jsxs("div",{className:"flex items-center gap-2 whitespace-nowrap","data-testid":e.id,"data-row-level":"0",children:[t.jsx(C,{variant:"ghost",size:"icon",className:"size-6 shrink-0","aria-label":r,"aria-expanded":e.expanded,onClick:()=>s(n.profile_key),children:t.jsx(ge,{name:e.expanded?"CaretDown":"CaretRight",size:"sm"})}),t.jsx("span",{className:"shrink-0 font-medium",children:n.name}),t.jsx(V,{variant:"outline",className:"shrink-0",children:n.pricing_model}),t.jsx(V,{variant:"secondary",className:"shrink-0",children:o("costs.insights.breakdown.connectionsCoverage",{covered:n.connections.covered,total:n.connections.total})}),t.jsx(V,{variant:"secondary",className:"shrink-0",children:o("costs.insights.breakdown.settledCoverage",{covered:n.settled.covered,total:n.settled.total})}),n.provisional&&t.jsx(V,{variant:"secondary",className:"shrink-0","data-testid":`breakdown-provisional-${n.profile_key}`,children:o("costs.insights.unavailable.provisional")})]})}function rt({labelKey:e}){const{t:s}=h();return t.jsx("span",{className:"shrink-0 text-xs font-medium uppercase text-muted-foreground",children:s(e)})}function $s({row:e}){const{t:s}=h();return t.jsxs("div",{className:"flex items-center gap-2 whitespace-nowrap pl-8","data-testid":e.id,"data-row-level":"1",children:[e.first&&t.jsx(rt,{labelKey:"costs.insights.breakdown.componentsGroup"}),t.jsx("span",{children:e.component.cost_type}),!e.component.priced&&t.jsx(V,{variant:"secondary",className:"shrink-0",children:s("costs.insights.breakdown.referencePassThrough")})]})}function Gs({row:e}){return t.jsxs("div",{className:"flex items-center gap-2 whitespace-nowrap pl-8","data-testid":e.id,"data-row-level":"2",children:[e.first&&t.jsx(rt,{labelKey:"costs.insights.breakdown.segmentsGroup"}),t.jsxs("span",{children:[e.segment.card_brand," · ",e.segment.card_type]})]})}function qs({row:e,onToggle:s}){const{t:o}=h();return e.kind===T.profile?t.jsx(Ks,{row:e,onToggle:s}):e.kind===T.component?t.jsx($s,{row:e}):e.kind===T.segment?t.jsx(Gs,{row:e}):t.jsx("p",{className:"pl-8 text-sm text-muted-foreground","data-testid":e.id,"data-row-level":"1",children:o("costs.insights.breakdown.noCostFacts")})}function Hs({row:e}){return e.kind===T.profile?t.jsx(t.Fragment,{children:De(e.node.txns)}):e.kind===T.segment?t.jsx(t.Fragment,{children:De(e.segment.txns)}):t.jsx(B,{})}function Ys({row:e,currency:s}){return e.kind===T.profile?t.jsx(t.Fragment,{children:O(e.node.gross_minor,s)}):e.kind===T.segment?t.jsx(t.Fragment,{children:O(e.segment.volume_minor,s)}):t.jsx(B,{})}function Ws({row:e}){if(e.kind!==T.segment)return t.jsx(B,{});const{expected_rate:s,actual_rate:o}=e.segment;return t.jsxs("span",{className:"whitespace-nowrap",children:[Oe
1(s),o!=null&&t.jsxs(t.Fragment,{children:[" â ",Oe(o)]})]})}function Qs({row:e,currency:s}){return e.kind===T.profile?t.jsx(t.Fragment,{children:O(e.node.expected_minor,s)}):e.kind===T.component&&e.component.priced?t.jsx(t.Fragment,{children:O(e.component.expected_minor,s)}):t.jsx(B,{})}function Xs({row:e,currency:s}){return e.kind===T.profile?t.jsx(Vs,{actualMinor:e.node.actual_minor,availability:e.node.availability,currency:s}):e.kind===T.component&&e.component.priced?e.component.actual_minor==null?t.jsx(B,{}):t.jsx(t.Fragment,{children:O(e.component.actual_minor,s)}):t.jsx(B,{})}function Js({row:e,currency:s}){return e.kind===T.profile?t.jsx(Be,{deviationMinor:e.node.deviation_minor,deviationState:e.node.deviation_state,currency:s}):e.kind===T.segment?t.jsx(Be,{deviationMinor:e.segment.deviation_minor,deviationState:e.segment.deviation_state,currency:s}):t.jsx(B,{})}function Zs(e,s){const{t:o}=h();return p.useMemo(()=>[{id:"entity",header:o("costs.insights.breakdown.column.entity"),flex:!0,size:Ms,cell:({row:n})=>t.jsx(qs,{row:n.original,onToggle:s})},{id:"txns",header:{title:o("costs.insights.breakdown.column.txns"),className:"justify-end"},size:Y.txns,cell:({row:n})=>t.jsx(W,{children:t.jsx(Hs,{row:n.original})})},{id:"volume",header:{title:o("costs.insights.breakdown.column.volume"),className:"justify-end"},size:Y.volume,cell:({row:n})=>t.jsx(W,{children:t.jsx(Ys,{row:n.original,currency:e})})},{id:"rate",header:{title:o("costs.insights.breakdown.column.rate"),className:"justify-end"},size:Y.rate,cell:({row:n})=>t.jsx(W,{children:t.jsx(Ws,{row:n.original})})},{id:"expected",header:{title:o("costs.insights.breakdown.column.expected"),className:"justify-end"},size:Y.expected,cell:({row:n})=>t.jsx(W,{children:t.jsx(Qs,{row:n.original,currency:e})})},{id:"actual",header:{title:o("costs.insights.breakdown.column.actual"),className:"justify-end"},size:Y.actual,cell:({row:n})=>t.jsx(W,{children:t.jsx(Xs,{row:n.original,currency:e})})},{id:"deviation",header:{title:o("costs.insights.breakdown.column.deviation"),className:"justify-end"},size:Y.deviation,cell:({row:n})=>t.jsx(W,{children:t.jsx(Js,{row:n.original,currency:e})})}],[o,e,s])}function eo({period:e,currency:s}){const{t:o}=h(),{rows:n,isLoading:r,isError:i,highestOnly:a,setHighestOnly:u,toggleProfile:l}=Bs(e),d=Zs(s,l);return t.jsxs(je,{className:"bg-card p-4",role:"region","data-testid":"breakdown-panel","aria-labelledby":"breakdown-heading",children:[t.jsxs("header",{className:"mb-3 flex flex-wrap items-center justify-between gap-2",children:[t.jsxs("div",{children:[t.jsx("h3",{id:"breakdown-heading",className:"text-lg font-semibold",children:o("costs.insights.breakdown.heading")}),t.jsx("p",{className:"text-xs text-muted-foreground",children:o("costs.insights.breakdown.description")})]}),t.jsx(Qe,{label:o("costs.insights.breakdown.highestDeviation"),checked:a,onChange:c=>u(c.target.checked),"data-testid":"breakdown-highest-deviation"})]}),i&&t.jsx("p",{role:"alert",className:"text-sm",children:o("costs.insights.breakdown.error")}),!i&&t.jsx(de,{columns:d,data:n,isLoading:r,rowHeight:Us,empty:{title:o("costs.insights.breakdown.empty")}})]})}const to={AVAILABLE:"",UNAVAILABLE_NO_PROFILE:"costs.insights.unavailable.noProfile",UNAVAILABLE_NO_SETTLEMENT:"costs.insights.unavailable.noSettlement",AWAITING_SETTLEMENT:"costs.insights.unavailable.awaitingSettlement",PROVISIONAL:"costs.insights.unavailable.provisional",NOT_COMPARABLE:"costs.insights.unavailable.notComparable"};function so({slug:e,title:s,metric:o,loading:n}){const{t:r}=h(),i=o&&o.value_minor!=null&&(o.availability==="AVAILABLE"||o.availability==="PROVISIONAL");return t.jsxs(je,{role:"article","data-testid":`scorecard-${e}`,className:"bg-card p-4",children:[t.jsx("h2",{className:"text-sm text-muted-foreground",children:s}),n&&t.jsx("p",{"aria-busy":"true",children:"â¦"}),!n&&i&&t.jsxs("p",{className:"text-2xl font-semibold",children:[O(o.value_minor,o.currency),o.pct!=null&&t.jsx("span",{"data-testid":"scorecard-pct",className:"ml-2 align-middle text-sm font-medium "+Is(o.pct,"text-muted-foreground"),children:As(o.pct)}),o.availability==="PROVISIONAL"&&t.jsx("span",{className:"ml-2 align-middle text-xs font-normal",children:r("costs.insights.provisional")})]}),!n&&o&&!i&&t.jsxs("p",{"data-testid":"scorecard-unavailable",children:[t.jsx("span",{className:"text-2xl font-semibold",children:"â"}),t.jsx("span",{className:"ml-2 text-xs",children:o.sub||r(to[o.availability])})]}),!n&&o&&o.covered<o.total&&t.jsx("p",{className:"text-xs text-muted-foreground",children:r("costs.insights.coverage",{covered:o.covered,total:o.total})})]})}const oo=[{key:"monthly_volume",slug:"monthly-volume",titleKey:"costs.insights.tiles.monthlyVolume"},{key:"expected_costs",slug:"expected-costs",titleKey:"costs.insights.tiles.expectedCosts"},{key:"actual_costs",slug:"actual-costs",titleKey:"costs.insights.tiles.actualCosts"},{key:"deviation",slug:"deviation",titleKey:"costs.insights.tiles.deviation"},{key:"potential_routing_savings",slug:"potential-routing-savings",titleKey:"costs.insights.tiles.potentialRoutingSavings"}];function no(e){if(e?.period?.start)return e.period.start.slice(0,7)}function ro(e){if(!e)return null;const s=e.expected_costs.availability,o=e.actual_costs.availability;return s==="UNAVAILABLE_NO_PROFILE"?{message:"Add a fee profile to see your expected costs.",href:"/costs/profiles/new"}:o==="UNAVAILABLE_NO_SETTLEMENT"?{message:"Connect settlement to see actual costs."}:null}function io(){const{t:e}=h(),{filters:s,setFilter:o,isReady:n}=We(),r=p.useRef(null),i=p.useRef(!1),a=p.useCallback(g=>{i.current=!!g},[]),u=ve(s.period)&&(i.current||s.period!==r.current)?s.period:void 0,{data:l,isLoading:d,isError:c}=is(u?{period:u}:{},n),m=no(l),f=ro(l);p.useEffect(()=>{!n||s.period||!m||(r.current=m,o("period",m))},[n,s.period,m,o]);const x=u??m??"",{filterConfigs:b,appliedFilters:w,handleRemoveFilter:P,handleClearAll:_,f
1ilterLang:E}=ws(x,a);return t.jsxs("section",{"data-testid":"cost-insights-page",className:"flex flex-col gap-6",children:[t.jsx("header",{children:t.jsx("div",{className:"w-fit","data-testid":"cost-period-picker",children:t.jsx(Gt,{filters:b,appliedFilters:w,onRemoveFilter:P,onClearAllFilters:_,lang:E})})}),c&&t.jsx("p",{role:"alert",className:"text-sm",children:e("costs.insights.error")}),t.jsx("div",{className:"grid grid-cols-1 gap-4 sm:grid-cols-2 xl:grid-cols-5",children:oo.map(({key:g,slug:v,titleKey:L})=>t.jsx(so,{slug:v,title:e(L),metric:l?.[g],loading:d},g))}),f&&t.jsxs("div",{className:"rounded-md border border-amber-500/40 bg-amber-50 p-3 text-sm text-amber-900 dark:bg-amber-900/20 dark:text-amber-200",role:"status","data-testid":"cost-config-nudge",children:[f.message," ",f.href&&t.jsx(At,{to:f.href,className:"font-medium underline","data-testid":"cost-config-nudge-link",children:"Get started"})]}),t.jsx(eo,{period:m,currency:l?.monthly_volume?.currency})]})}const ao={period:""};function lo(){return t.jsx(St,{initial:ao,storageKey:Ts,routePath:Rs,children:t.jsx(io,{})})}function ie(e=new Date,s){return new Intl.DateTimeFormat("en-CA",{year:"numeric",month:"2-digit",day:"2-digit",...s?{timeZone:s}:{}}).format(e)}const co=/^\d{4}-\d{2}-\d{2}$/;function uo(e){if(!e||!co.test(e))return;const s=new Date(`${e}T00:00:00`);return Number.isNaN(s.getTime())?void 0:s}function po(e,s){return!e||Number.isNaN(e.getTime())?"":ie(e,s)}const mo=ie;function fo(e){if(e.role!=="RATE"||e.locus!=="CARD")return!1;const s=e.scope_json||{};return!s.card_brand&&!s.card_type}function go(e){return e.role==="RATE"&&e.locus==="CARD"}function xo(e,s){const o=(s??[]).filter(go),n=o.some(fo),r=mo(),i=o.length>0&&o.every(a=>a.valid_from>r);return o.length>0&&!n?"NO_FALLBACK":i?"SCHEDULED":e.status==="ACTIVE"&&e.connection_ids.length>0&&n?"ACTIVE":"INACTIVE"}function ho(e){const s=Vt({queries:e.map(n=>({queryKey:["GET/costs/config/profiles/components",n],queryFn:()=>I.getInstance().getCostProfileComponents(n).then(i=>i?.data),useErrorBoundary:!1}))}),o=s.map((n,r)=>`${e[r]}:${n.isLoading?1:0}:${n.isError?1:0}:${n.dataUpdatedAt}`).join("|");return p.useMemo(()=>{const n={},r={},i={};return s.forEach((a,u)=>{const l=e[u];n[l]=a.data?.rows,r[l]=a.isLoading&&!a.isError,i[l]=a.isError}),{componentsByProfile:n,pendingByProfile:r,errorByProfile:i}},[o])}const yo={ACTIVE:"success",SCHEDULED:"info",NO_FALLBACK:"warning",INACTIVE:"outline",UNKNOWN:"secondary"},bo={ACTIVE:"costs.profiles.status.active",SCHEDULED:"costs.profiles.status.scheduled",NO_FALLBACK:"costs.profiles.status.noFallback",INACTIVE:"costs.profiles.status.inactive",UNKNOWN:"costs.profiles.status.unknown"};function _o({status:e}){const{t:s}=h(),o=yo[e],n=s(bo[e]);return t.jsx(V,{variant:o,"data-testid":`profile-status-${e.toLowerCase()}`,children:e==="NO_FALLBACK"?`â ${n}`:n})}const jo={ICPP:"costs.profiles.pricingModel.icpp",BLENDED:"costs.profiles.pricingModel.blended"},vo="costs.profiles.pricingModel.unmapped";function Co(e){return jo[e]??vo}function Eo(e,s){return(s??[]).filter(n=>n.role==="RATE"&&n.locus==="CARD").map(n=>n.valid_from.slice(0,10)).sort((n,r)=>n.localeCompare(r))[0]??e.created_at.slice(0,10)}function No(e,s){const o=new Date(`${e.slice(0,10)}T00:00:00`);return Number.isNaN(o.getTime())?e.slice(0,10):new Intl.DateTimeFormat(s||"en",{dateStyle:"medium"}).format(o)}const wo="â",Fe=()=>t.jsx(Xe,{"data-testid":"profile-cell-pending",className:"h-4 w-24"}),To=({componentsByProfile:e,pendingByProfile:s,errorByProfile:o})=>{const{t:n,i18n:r}=h(),i=r?.language??"en";return p.useMemo(()=>[{accessorKey:"name",header:n("costs.profiles.column.profile"),cell:({row:a})=>t.jsx("span",{className:"font-medium",children:a.original.name})},{accessorKey:"provider_code",header:n("costs.profiles.column.provider"),cell:({row:a})=>t.jsx("span",{"data-testid":`profile-provider-${a.original.profile_key}`,children:a.original.provider_code})},{accessorKey:"pricing_model",header:n("costs.profiles.column.pricingModel"),cell:({row:a})=>n(Co(a.original.pricing_model))},{id:"connections",header:n("costs.profiles.column.connections"),cell:({row:a})=>a.original.connection_ids.length},{id:"validity",header:n("costs.profiles.column.validity"),cell:({row:a})=>{if(s[a.original.profile_key])return t.jsx(Fe,{});if(o[a.original.profile_key])return t.jsx("span",{"data-testid":`profile-validity-unknown-${a.original.profile_key}`,children:wo});const u=Eo(a.original,e[a.original.profile_key]);return n("costs.profiles.validity.ongoing",{date:No(u,i)})}},{id:"status",header:n("costs.profiles.column.status"),cell:({row:a})=>{if(s[a.original.profile_key])return t.jsx(Fe,{});const u=o[a.original.profile_key]?"UNKNOWN":a.original.status;return t.jsx(_o,{status:u})}}],[n,i,e,s,o])};function Ro(){const{t:e}=h(),s=fe(),{data:o,isLoading:n,isError:r,refetch:i}=as(),a=o?.rows??[],u=p.useMemo(()=>a.map(g=>g.profile_key),[a]),{componentsByProfile:l,pendingByProfile:d,errorByProfile:c}=ho(u),m=p.useMemo(()=>a.map(g=>{const{status:v,...L}=g;return{...L,serverStatus:v,status:xo(g,l[g.profile_key])}}),[a,l]),{mutateAsync:f,isPending:x}=tt(),[b,w]=p.useState(null),P=async()=>
1{if(b)try{await f(b.profile_key),w(null),i()}catch{k.error(e("costs.profiles.delete.error"))}},_=To({componentsByProfile:l,pendingByProfile:d,errorByProfile:c}),E=t.jsx(C,{size:"sm",startIcon:"Plus",onClick:()=>s("/costs/profiles/new"),children:e("costs.profiles.newButton")});return t.jsxs(qt,{title:t.jsx("span",{className:"sr-only",children:e("costs.profiles.listTitle")}),description:e("costs.profiles.pageDescription"),actions:E,loading:n,loadingFallback:t.jsx(de,{columns:_,data:[],isLoading:!0}),empty:!n&&m.length===0&&!r,emptyState:t.jsx(Ie,{title:e("costs.profiles.empty.title"),description:e("costs.profiles.empty.description"),actions:E}),children:[r&&t.jsx("div",{role:"alert",children:t.jsx(Ie,{media:t.jsx(Ht,{name:"WarningCircle",size:"xl",className:"text-neutral-400"}),title:e("costs.profiles.error.title"),description:e("costs.profiles.error.description"),actions:t.jsx(C,{size:"sm",variant:"outline",startIcon:"ArrowsClockwise",onClick:()=>i(),children:e("costs.profiles.error.retry")})})}),!r&&t.jsx(de,{columns:_,data:m,enableSorting:!0,onRowClick:g=>s(`/costs/profiles/${g.profile_key}`),actions:{render:g=>t.jsxs(Yt,{children:[t.jsx(Wt,{asChild:!0,children:t.jsx(C,{variant:"ghost",size:"icon",className:"size-8","aria-label":e("costs.profiles.actions.rowActions"),startIcon:"DotsThreeCircleVertical",onClick:v=>v.stopPropagation()})}),t.jsx(Qt,{align:"end",className:"z-[100]",children:t.jsxs(Xt,{onClick:v=>{v.stopPropagation(),w(g)},children:[t.jsx(ge,{name:"Trash",size:"sm"}),t.jsx("span",{className:"ml-2",children:e("costs.profiles.actions.delete")})]})})]})}}),t.jsx(ne,{open:b!==null,onClose:()=>w(null),onConfirm:P,title:e("costs.profiles.delete.title"),description:b?e("costs.profiles.delete.description",{name:b.name,count:b.connection_ids.length}):"",confirmLabel:e("costs.profiles.delete.confirm"),cancelLabel:e("costs.profiles.delete.cancel"),variant:"destructive",isLoading:x})]})}const A="ANY",So=["INSTALLMENT_COUNT","TXN_AMOUNT","MONTHLY_TXN_COUNT","MONTHLY_TXN_VOLUME"],Ee=[{id:"CHARGEBACK",label:"Chargeback fee",costType:"CHARGEBACK",calcType:"FIXED_PER_EVENT",unit:"per dispute",typicalAmount:2,trigger:{type:["CHARGEBACK"]}},{id:"REFUND",label:"Refund fee",costType:"REFUND",calcType:"FIXED_PER_EVENT",unit:"per refund",typicalAmount:0,trigger:{type:["REFUND"],succeeded:!0}},{id:"THREE_DS",label:"3D Secure authentication",costType:"THREE_DS",calcType:"FIXED_PER_EVENT",unit:"per check",typicalAmount:.05,isNew:!0,trigger:{type:["THREE_D_SECURE"]}},{id:"MONTHLY",label:"Monthly fee",costType:"MONTHLY",calcType:"FIXED_PER_EVENT",unit:"per month",typicalAmount:0,trigger:void 0},{id:"TOKENIZATION",label:"Network token usage",costType:"TOKENIZATION",calcType:"FIXED_PER_EVENT",unit:"per transaction",typicalAmount:.02,isNew:!0,trigger:{type:["PURCHASE","CAPTURE"],succeeded:!0,network_token:!0}},{id:"PROCESSING",label:"Processing fee",costType:"PROCESSING",calcType:"TIERED",unit:"tiered by MTD transaction count",typicalAmount:.054,trigger:{type:["PURCHASE","CAPTURE"],succeeded:!0}}],it={type:["PURCHASE","CAPTURE"],succeeded:!0};function at(){return Object.fromEntries(Ee.map(e=>[e.id,{on:!1,amount:e.typicalAmount}]))}function Ne(){return{id:`rr_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,6)}`,cardBrand:A,cardType:A,mode:"FLAT",ratePct:null,fixedMinor:0}}function Ao(e){return{name:"",providerCode:"",pricingModel:"BLENDED",settlementCurrency:"BRL",validFrom:e,cardRates:[{...
1Ne()}],platformCosts:at(),connectionIds:[]}}const lt=6;function ct(e){if(e==null||!Number.isFinite(e))return null;const s=e/100,o=10**lt;return Math.round(s*o)/o}function Io(e){if(e==null||!Number.isFinite(e))return null;const s=e*100,o=10**(lt-2);return Math.round(s*o)/o}let Me=null;function Po(e){Me??(Me=new Map(Ze().map(o=>[o.code,o.digits])));const s=Me.get(e?.trim().toUpperCase());return 10**(typeof s=="number"?s:2)}function Lo(e,s){return Math.round(e*Po(s))}function ko(e){const s={};return e.cardBrand!==A&&(s.card_brand=e.cardBrand),e.cardType!==A&&(s.card_type=e.cardType),s}function zo(e){if(!(e.mode!=="TIERED"||!e.bands))return e.bands.map((s,o)=>{const n={seq:o+1,lower:s.lower,rate_fraction:ct(s.ratePct),fixed_minor:s.fixedMinor};return s.upper!=null&&(n.upper=s.upper),n})}function dt(e,s){const o=s.mode==="TIERED",n={cost_type:"CARD_RATE",calc_type:o?"TIERED":"PCT_VOLUME",role:"RATE",locus:"CARD",currency:e.settlementCurrency,trigger_json:{...it},scope_json:ko(s),valid_from:e.validFrom};return o?(n.tier_basis=s.tierBasis,n.tiers=zo(s)):(n.rate_fraction=ct(s.ratePct),n.fixed_minor=s.fixedMinor),s.minFeeMinor!=null&&(n.min_fee_minor=s.minFeeMinor),s.maxFeeMinor!=null&&(n.max_fee_minor=s.maxFeeMinor),n}function Do(e){const s=[];for(const o of Ee){const n=e.platformCosts[o.id];if(!n?.on)continue;const r={cost_type:o.costType,calc_type:o.calcType,role:"COST",locus:"PLATFORM",currency:e.settlementCurrency,scope_json:{},fixed_minor:Lo(n.amount,e.settlementCurrency),valid_from:e.validFrom};o.trigger&&(r.trigger_json={...o.trigger}),s.push(r)}return s}function Oo(e){return[...e.cardRates.map(s=>dt(e,s)),...Do(e)]}function Bo(e){return{name:e.name.trim(),provider_code:e.providerCode,pricing_model:e.pricingModel,settlement_currency:e.settlementCurrency,connection_ids:e.connectionIds,account_ids:[]}}function Fo(e,s){if(e.ratePct==null||Number.isNaN(e.ratePct))return"unpriced";if(!s&&e.upper==null||e.upper!=null&&e.upper<=e.lower)return"bad_upper"}function Mo(e,s){if(e.upper==null)return"bad_upper";if(s.lower>e.upper)return"gap";if(s.lower<e.upper)return"overlap"}function Uo(e){if(!e||e.length<2)return{ok:!1,reason:"need_two_bands"};for(let s=0;s<e.length;s++){const o=Fo(e[s],s===e.length-1)??(s>0?Mo(e[s-1],e[s]):void 0);if(o)return{ok:!1,reason:o}}return{ok:!0}}function Vo(e){const s=new Set,o=new Set;for(const n of e){const r=JSON.stringify([n.cardBrand,n.cardType]);s.has(r)?o.add(n.id):s.add(r)}return o}function we(e){const s={},o=Vo(e);for(const n of e)if(o.has(n.id))s[n.id]="duplicate_scope";else if(n.mode==="TIERED"){const r=Uo(n.bands);r.ok||(s[n.id]=r.reason??"invalid")}else n.ratePct==null&&(s[n.id]="rate_required");return{ok:Object.keys(s).length===0,errorsById:s}}function _e(e){const s=new Set;for(const o of e??[]){const n=o?.trim();n&&s.add(n)}return[...s].sort()}function Ko(e){return _e(e).map(s=>({value:s,label:s}))}function ut(){const{data:e,isLoading:s,isError:o}=It(),n=p.useMemo(()=>Ko(e?.providers),[e?.providers]),r=p.useMemo(()=>_e(e?.card_brand),[e?.card_brand]),i=p.useMemo(()=>_e(e?.card_types),[e?.card_types]);return{providers:n,brands:r,types:i,isLoading:s,isError:o,hasScopeData:r.length>0||i.length>0}}function pt(e,s,o){return(e||s)&&!o}const $o=[...new Set(Ze().map(e=>e.code))].map(e=>({value:e,label:e}));function Go({draft:e,onChange:s,providers:o,providersLoading:n,providersError:r,currencies:i}){const{t:a}=h(),u=[{value:"BLENDED",label:a("costs.profiles.wizard.stepProfile.blendedLabel")},{value:"ICPP",label:a("costs.profiles.wizard.stepProfile.icppLabel")}];return t.jsxs("section",{"aria-label":a("costs.profiles.wizard.step.profile"),className:"flex flex-col gap-4",children:[t.jsxs("div",{className:"grid grid-cols-1 items-start gap-x-6 gap-y-4 md:grid-cols-2",children:[t.jsx($,{label:a("costs.profiles.wizard.stepProfile.name"),value:e.name,requiredIndicator:a("costs.profiles.wizard.requiredIndicator"),onChange:l=>s({name:l.target.value}),placeholder:a("costs.profiles.wizard.stepProfile.namePlaceholder")}),t.jsx(qo,{value:e.providerCode,onChange:l=>s({providerCode:l}),options:o,isLoading:n,isError:r}),t.jsx(K,{id:"wiz-pricing-model","aria-label":a("costs.profiles.wizard.stepProfile.pricingModel"),label:a("costs.profiles.wizard.stepProfile.pricingModel"),value:e.pricingModel,onChange:l=>s({pricingModel:l}),options:u,placeholder:a("costs.profiles.wizard.stepProfile.pricingModelPlaceholder")}),t.jsx(et,{id:"wiz-settlement-currency",label:a("costs.profiles.wizard.stepProfile.settlementCurrency"),value:e.settlementCurrency,onChange:l=>s({settlementCurrency:l}),options:i,searchPlaceholder:a("costs.profiles.wizard.stepProfile.settlementCurrencySearchPlaceholder")}),t.jsx(Jt,{label:a("costs.profiles.wizard.stepProfile.validFrom"),date:uo(e.validFrom),onChange:l=>{l&&s({validFrom:po(l)})}})]}),t.jsx(Zt,{icon:"Info",description:a("costs.profiles.wizard.stepProfile.providerDescription")})]})}
1function qo({value:e,onChange:s,options:o,isLoading:n,isError:r}){const{t:i}=h(),a=p.useMemo(()=>{const u=e.trim();return!u||o.some(l=>l.value===u)?o:[...o,{value:u,label:u}]},[o,e]);return t.jsxs("div",{className:"flex flex-col gap-1",children:[t.jsx(et,{id:"wiz-provider",label:i("costs.profiles.wizard.stepProfile.provider"),value:e,onChange:s,options:a,disabled:n,placeholder:i("costs.profiles.wizard.stepProfile.providerPlaceholder"),searchPlaceholder:i("costs.profiles.wizard.stepProfile.providerSearchPlaceholder"),requiredIndicator:i("costs.profiles.wizard.requiredIndicator")}),r&&t.jsx("p",{role:"alert",className:"text-sm text-destructive",children:i("costs.profiles.wizard.stepProfile.providerLoadError")})]})}function Ho(e){if(e.length===0)return[{lower:1,upper:null,ratePct:null,fixedMinor:0}];const s=e[e.length-1],o=s.upper??s.lower+1;return[...e.map((r,i)=>i===e.length-1&&r.upper==null?{...r,upper:o}:r),{lower:o,upper:null,ratePct:null,fixedMinor:0}]}function Yo(e,s){if(e.length<=1||s<0||s>=e.length)return[...e];const o=e[s],n=e.filter((r,i)=>i!==s);return s<e.length-1?n[s]={...n[s],lower:o.lower}:n[n.length-1]={...n[n.length-1],upper:null},n}function mt(e){const s=e.trim();if(s==="")return null;const o=Number(s);return Number.isFinite(o)?o:null}const ue=Symbol("keep");function ft(e,s,o){const[n,r]=p.useState(null),i=e===null?"":String(e);return{value:n&&n.value===e?n.text:i,onChange:a=>{const u=a.target.value,l=o(u,a.target.validity?.badInput??!1),d=l===ue?e:l;r({text:u,value:d}),d!==e&&s(d)},onBlur:()=>r(null)}}function gt(e,s){return ft(e,s,o=>mt(o)??ue)}function Wo(e,s){return ft(e,s,(o,n)=>n?ue:o.trim()===""?null:mt(o)??ue)}function pe({value:e,onCommit:s,...o}){const n=gt(e,s);return t.jsx($,{type:"number",...o,value:n.value,onChange:n.onChange,onBlur:n.onBlur})}function me({value:e,onCommit:s,...o}){const n=Wo(e,s);return t.jsx($,{type:"number",...o,value:n.value,onChange:n.onChange,onBlur:n.onBlur})}function Qo({draft:e,onChange:s,brandOptions:o,cardTypeOptions:n,tierBasisOptions:r,onEditorOpenChange:i,catalogLoading:a=!1,catalogError:u=!1,catalogHasData:l=!1}){const{t:d}=h();return t.jsxs("section",{"aria-label":d("costs.profiles.wizard.step.components"),className:"flex flex-col gap-6",children:[t.jsx(en,{draft:e,onChange:s,brandOptions:o,cardTypeOptions:n,tierBasisOptions:r,onEditorOpenChange:i,catalogLoading:a,catalogError:u,catalogHasData:l}),t.jsxs("section",{"aria-labelledby":"wiz-platform",className:"flex flex-col gap-2",children:[t.jsx("h3",{id:"wiz-platform",className:"text-sm font-semibold",children:d("costs.profiles.wizard.stepComponents.platformHeading")}),t.jsx("p",{className:"text-sm text-muted-foreground",children:d("costs.profiles.wizard.stepComponents.platformDescription")}),t.jsx("div",{className:"divide-y rounded-md border",children:Ee.map(c=>t.jsx(Jo,{entry:c,state:e.platformCosts[c.id],currency:e.settlementCurrency,onPatch:m=>s({platformCosts:{...e.platformCosts,[c.id]:{...e.platformCosts[c.id],...m}}})},c.id))})]}),e.pricingModel==="ICPP"&&t.jsxs("aside",{className:"rounded-md border bg-muted p-3 text-sm",children:[t.jsx("strong",{children:d("costs.profiles.wizard.stepComponents.icppNoteBold")})," ",d("costs.profiles.wizard.stepComponents.icppNoteBody")]})]})}function Xo({testId:e,title:s,description:o,badge:n,unit:r,currency:i,amountAria:a,state:u,offSlot:l,onPatch:d}){const c=gt(u.amount,m=>d({amount:m}));return t.jsxs("div",{className:"flex items-center gap-3 px-4 py-3","data-testid":e,children:[t.jsx(Pt,{label:"","aria-label":s,checked:u.on,onChange:m=>d({on:m.target.checked})}),t.jsxs("div",{className:"flex flex-col",children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("span",{className:"text-sm font-medium",children:s}),n]}),t.jsx("span",{className:"text-xs text-muted-foreground",children:o})]}),t.jsx("div",{className:"flex-1"}),u.on?t.jsxs("div",{className:"flex w-56 items-center gap-2 rounded-md border px-3 py-1.5",children:[t.jsx("span",{className:"text-xs text-muted-foreground",children:i}),t.jsx("input",{type:"number","aria-label":a,className:"w-full min-w-0 bg-transparent text-sm outline-none",value:c.value,onChange:c.onChange,onBlur:c.onBlur}),t.jsx("span",{className:"whitespace-nowrap text-xs text-muted-foreground",children:r})]}):l]})}function Jo({entry:e,state:s,currency:o,onPatch:n}
1){const{t:r}=h(),i=r(`costs.profiles.wizard.platformCost.${e.id}.label`);return t.jsx(Xo,{testId:`platform-cost-${e.id}`,title:i,description:r(`costs.profiles.wizard.platformCost.${e.id}.description`),badge:e.isNew?t.jsx(V,{variant:"default",children:r("costs.profiles.wizard.stepComponents.newBadge")}):void 0,unit:r(`costs.profiles.wizard.platformCost.${e.id}.unit`),currency:o,amountAria:r("costs.profiles.wizard.stepComponents.amountAria",{fee:i}),state:s,offSlot:t.jsx("p",{className:"text-xs text-muted-foreground",children:r("costs.profiles.wizard.stepComponents.typicalAmount",{currency:o,amount:e.typicalAmount})}),onPatch:n})}function Zo(e){return e.cardBrand===A&&e.cardType===A}function en({draft:e,onChange:s,brandOptions:o,cardTypeOptions:n,tierBasisOptions:r,onEditorOpenChange:i,catalogLoading:a=!1,catalogError:u=!1,catalogHasData:l=!1}){const{t:d}=h(),[c,m]=p.useState(null),{errorsById:f}=we(e.cardRates),x=g=>{m(g),i?.(g!==null)},b=e.cardRates.find(Zo)?.id??null,w=e.cardRates.filter(g=>f[g.id]&&f[g.id]!=="duplicate_scope").length,P=()=>{c&&(s({cardRates:c.mode==="new"?[...e.cardRates,c.row]:e.cardRates.map(g=>g.id===c.row.id?c.row:g)}),x(null))},_=pt(a,u,l),E=g=>{c?.row.id===g&&x(null),s({cardRates:e.cardRates.filter(v=>v.id!==g)})};return t.jsxs("section",{"aria-labelledby":"wiz-card-rates",className:"flex flex-col gap-3",children:[t.jsx("h3",{id:"wiz-card-rates",className:"text-sm font-semibold",children:d("costs.profiles.wizard.stepComponents.cardHeading")}),t.jsx("p",{className:"text-sm text-muted-foreground",children:d("costs.profiles.wizard.stepComponents.cardDescription")}),u&&t.jsx("p",{role:"alert",className:"text-sm text-destructive",children:d("costs.profiles.wizard.stepComponents.catalogLoadError")}),t.jsx("div",{className:"divide-y rounded-md border",children:e.cardRates.map((g,v)=>t.jsx(sn,{row:g,index:v+1,isFallback:g.id===b,error:f[g.id],editDisabled:c!==null||_,removeDisabled:c!==null,onEdit:()=>x({mode:"edit",row:{...g}}),onRemove:()=>E(g.id)},g.id))}),c&&t.jsx(nn,{state:c,siblings:e.cardRates.filter(g=>g.id!==c.row.id),lockScope:c.row.id===b,brandOptions:o,cardTypeOptions:n,tierBasisOptions:r,onPatch:g=>m(v=>v&&{...v,row:{...v.row,...g}}),onCancel:()=>x(null),onSave:P}),t.jsxs("div",{className:"flex items-center gap-3",children:[t.jsx(C,{variant:"outline",startIcon:"Plus",disabled:c!==null||_,onClick:()=>x({mode:"new",row:Ne()}),children:d("costs.profiles.wizard.stepComponents.addRateRow")}),w>0&&t.jsx("p",{className:"text-xs text-warning",children:d("costs.profiles.wizard.stepComponents.ratesNeedPrice",{count:w})})]})]})}function tn(e,s){switch(s){case void 0:return null;case"rate_required":return e("costs.profiles.wizard.rateRow.errorRateRequired");case"unpriced":return e("costs.profiles.wizard.rateRow.errorUnpriced");case"need_two_bands":return e("costs.profiles.wizard.rateRow.errorNeedTwoBands");case"gap":return e("costs.profiles.wizard.rateRow.errorGap");case"overlap":return e("costs.profiles.wizard.rateRow.errorOverlap");case"duplicate_scope":return e("costs.profiles.wizard.rateRow.errorDuplicateScope");default:return e("costs.profiles.wizard.rateRow.errorBounds")}}function sn({row:e,index:s,isFallback:o,error:n,editDisabled:r,removeDisabled:i,onEdit:a,onRemove:u}){const{t:l}=h(),d=e.cardBrand===A?l("costs.profiles.wizard.rateRow.anyNetwork"):e.cardBrand,c=e.cardType===A?l("costs.profiles.wizard.rateRow.anyMethod"):e.cardType,m=`${d} · ${c}`,f=()=>o?l("costs.profiles.wizard.rateRow.fallbackDescription"):e.mode==="TIERED"?l("costs.profiles.wizard.rateRow.ladder"):l("costs.profiles.wizard.rateRow.flatRate"),x="rounded-full border px-2 py-0.5 text-xs";return t.jsxs("div",{className:"flex items-center gap-3 px-4 py-3","data-testid":`rate-row-${e.id}`,children:[t.jsxs("div",{className:"flex flex-col gap-1",children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("span",{className:e.cardBrand===A?`${x} border-dashed`:`${x}`,children:d}),t.jsx("span",{className:e.cardType===A?`${x} border-dashed`:x,children:c})]}),t.jsx("span",{className:"text-xs text-muted-foreground",children:f()})]}),t.jsx("div",{className:"flex-1"}),t.jsx(on,{row:e,error:n}),t.jsx(C,{variant:"outline",size:"icon",startIcon:"Pencil","aria-label":l("costs.profiles.wizard.rateRow.edit",{scope:m,index:s}),disabled:r,onClick:a}),!o&&t.jsx(C,{variant:"outline",size:"icon",startIcon:"Trash","aria-label":l("costs.profiles.wizard.rateRow.remove",{scope:m,index:s}),disabled:i,onClick:u})]})}function on({row:e,error:s}){const{t:o}=h();return s?t.jsx("span",{className:"text-xs text-warning",children:o(s==="duplicate_scope"?"costs.profiles.wizard.rateRow.duplicateScopeShort":"costs.profiles.wizard.rateRow.rateNeeded")}):e.mode==="TIERED"?t.jsx("span",{className:"text-sm font-semibold",children:o("costs.profiles.wizard.rateRow.ladder
1Summary",{count:e.bands?.length??0})}):t.jsxs("div",{className:"flex flex-col items-end",children:[t.jsx("span",{className:"text-sm font-semibold",children:`${e.ratePct}%`}),t.jsx("span",{className:"text-xs text-muted-foreground",children:o("costs.profiles.wizard.rateRow.flatSummarySuffix")})]})}function ye({index:e,title:s,description:o,children:n}){return t.jsxs("div",{className:"flex flex-col gap-2",children:[t.jsxs("div",{className:"flex items-start gap-2",children:[t.jsx("span",{"aria-hidden":"true",className:"flex size-5 shrink-0 items-center justify-center rounded-full bg-primary text-xs text-primary-foreground",children:e}),t.jsxs("div",{className:"flex flex-col",children:[t.jsx("span",{className:"text-sm font-semibold",children:s}),t.jsx("span",{className:"text-xs text-muted-foreground",children:o})]})]}),t.jsx("div",{className:"flex flex-col gap-2 pl-7",children:n})]})}function Ue(){const{t:e}=h();return t.jsx("p",{className:"text-xs text-muted-foreground",children:e("costs.profiles.wizard.rateEditor.fallbackScopeLocked")})}function nn({state:e,siblings:s,lockScope:o,brandOptions:n,cardTypeOptions:r,tierBasisOptions:i,onPatch:a,onCancel:u,onSave:l}){const{t:d}=h(),c=e.row,{errorsById:m}=we(o?[c,...s]:[...s,c]),f=tn(d,m[c.id]);
1return t.jsxs("div",{className:"flex flex-col gap-4 rounded-md border p-4","data-testid":"rate-editor",children:[t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsx("h4",{className:"text-sm font-semibold",children:e.mode==="new"?d("costs.profiles.wizard.rateEditor.titleNew"):d("costs.profiles.wizard.rateEditor.titleEdit")}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(C,{variant:"outline",onClick:u,children:d("costs.profiles.wizard.rateEditor.cancel")}),t.jsx(C,{onClick:l,children:d("costs.profiles.wizard.rateEditor.save")})]})]}),t.jsxs(ye,{index:1,title:d("costs.profiles.wizard.rateEditor.networkTitle"),description:d("costs.profiles.wizard.rateEditor.networkDescription"),children:[t.jsx(K,{id:"wiz-rate-brand",label:d("costs.profiles.wizard.rateRow.cardBrand"),value:c.cardBrand,disabled:o,onChange:x=>a({cardBrand:x}),options:n}),o&&t.jsx(Ue,{})]}),t.jsxs(ye,{index:2,title:d("costs.profiles.wizard.rateEditor.methodTitle"),description:d("costs.profiles.wizard.rateEditor.methodDescription"),children:[t.jsx(K,{id:"wiz-rate-type",label:d("costs.profiles.wizard.rateRow.cardType"),value:c.cardType,disabled:o,onChange:x=>a({cardType:x}),options:r}),o&&t.jsx(Ue,{})]}),t.jsxs(ye,{index:3,title:d("costs.profiles.wizard.rateEditor.rateTitle"),description:d("costs.profiles.wizard.rateEditor.rateDescription"),children:[t.jsx(K,{id:"wiz-rate-structure",label:d("costs.profiles.wizard.rateEditor.pricingStructure"),value:c.mode,onChange:x=>{const b=x;b==="TIERED"&&!c.bands?a({mode:b,tierBasis:"INSTALLMENT_COUNT",bands:[{lower:1,upper:6,ratePct:null,fixedMinor:0},{lower:6,upper:null,ratePct:null,fixedMinor:0}]}):a({mode:b})},options:[{value:"FLAT",label:d("costs.profiles.wizard.rateRow.flatRate")},{value:"TIERED",label:d("costs.profiles.wizard.rateRow.ladder")}]}),c.mode==="FLAT"&&t.jsxs("div",{className:"flex items-end gap-3",children:[t.jsx(me,{label:d("costs.profiles.wizard.rateRow.rate"),value:c.ratePct,onCommit:x=>a({ratePct:x}),placeholder:d("costs.profiles.wizard.rateRow.ratePlaceholder")}),t.jsx(pe,{label:d("costs.profiles.wizard.rateRow.fixed"),value:c.fixedMinor,onCommit:x=>a({fixedMinor:x})})]}),c.mode==="TIERED"&&t.jsxs("div",{className:"flex flex-col gap-2",children:[t.jsx(K,{id:"wiz-rate-tier-basis",label:d("costs.profiles.wizard.rateRow.tierBasis"),value:c.tierBasis??"INSTALLMENT_COUNT",onChange:x=>a({tierBasis:x}),options:i}),t.jsx(rn,{bands:c.bands??[],onChange:x=>a({bands:x})})]})]}),f&&t.jsx("p",{role:"alert",className:"text-xs text-destructive",children:f})]})}function rn({bands:e,onChange:s}){const{t:o}=h(),n=e??[],r=(u,l)=>{const d=n.map((c,m)=>m===u?{...c,...l}:c);l.upper!=null&&u<d.length-1&&(d[u+1]={...d[u+1],lower:l.upper}),s(d)},i=()=>{s(Ho(n))},a=n.map((u,l)=>({band:u,i:l,key:`band-${l}`}));return t.jsxs("div",{className:"flex flex-col gap-2",children:[a.map(({band:u,i:l,key:d})=>t.jsxs("div",{className:"grid grid-cols-[repeat(4,minmax(0,1fr))_auto] items-end gap-2","data-testid":`rate-band-${l}`,children:[t.jsx(pe,{label:o(l===0?"costs.profiles.wizard.bands.from":"costs.profiles.wizard.bands.fromAuto"),value:u.lower,disabled:l>0,onCommit:c=>r(l,{lower:c})}),t.jsx(me,{label:o("costs.profiles.wizard.bands.to"),value:u.upper,placeholder:l===n.length-1?o("costs.profiles.wizard.bands.toInfinity"):"",onCommit:c=>r(l,{upper:c})}),t.jsx(me,{label:o("costs.profiles.wizard.bands.rate"),value:u.ratePct,onCommit:c=>r(l,{ratePct:c})}),t.jsx(pe,{label:o("costs.profiles.wizard.bands.fixed"),value:u.fixedMinor,onCommit:c=>r(l,{fixedMinor:c})}),t.jsx(C,{variant:"outline",size:"icon",startIcon:"Trash",disabled:n.length<=1,"aria-label":o("costs.profiles.wizard.bands.removeBand",{index:l+1}),onClick:()=>s(Yo(n,l))})]},d)),t.jsx(C,{variant:"outline",onClick:i,startIcon:"Plus",children:o("costs.profiles.wizard.bands.addBand")})]})}function an(e,s){const o=Array.isArray(e)?e:[],n=s.trim().toLowerCase();return n?o.filter(r=>[r?.name,r?.code,r?.account_code_live].filter(Boolean).some(i=>String(i).toLowerCase().includes(n))):o}function ln(e,s){const o=s.trim().toLowerCase();return o?[e?.provider?.name,e?.provider?.provider_id,e?.provider_id].filter(
1Boolean).some(n=>String(n).trim().toLowerCase()===o):!0}function cn(e,s){return(Array.isArray(e)?e:[]).filter(n=>ln(n,s))}function Ve(e,s,o){return o?e.includes(s)?e:[...e,s]:e.filter(n=>n!==s)}function dn(e,s){const o=[...e];for(const n of s)o.includes(n)||o.push(n);return o}function xt(e){return e?.name?.trim()||e?.code||""}function un(e){const{isTesting:s}=Ye(),{data:o,isLoading:n,isError:r}=Lt(),i=p.useMemo(()=>Array.isArray(o)?o:[],[o]),[a,u]=p.useState(""),[l,d]=p.useState(""),c=i.find(E=>E?.code===l),m=c?kt(c,s):"",{data:f,isLoading:x,isError:b}=zt({accountCode:m,organizationCode:""}),w=p.useMemo(()=>cn(f,e),[f,e]),[P,_]=p.useState({});return p.useEffect(()=>{!Array.isArray(f)||!c||_(E=>{const g={...E};for(const v of f)v?.code&&(g[v.code]={name:xt(v)});return g})},[f,c]),{accounts:i,accountsLoading:n,accountsError:r,search:a,setSearch:u,selectedAccountCode:l,selectAccount:d,connections:w,connectionsLoading:!!m&&x,connectionsError:!!m&&b,labels:P}}function pn({draft:e,onChange:s}){const{t:o}=h(),n=un(e.providerCode),r=an(n.accounts,n.search);return t.jsxs("section",{"aria-label":o("costs.profiles.wizard.step.scope"),className:"flex flex-col gap-6",children:[t.jsx("p",{className:"text-sm text-muted-foreground",children:o("costs.profiles.wizard.stepScope.description")}),t.jsx(mn,{accounts:r,isLoading:n.accountsLoading,isError:n.accountsError,search:n.search,onSearch:n.setSearch,selectedAccountCode:n.selectedAccountCode,onSelect:n.selectAccount}),t.jsx(fn,{hasAccount:!!n.selectedAccountCode,connections:n.connections,isLoading:n.connectionsLoading,isError:n.connectionsError,hasProvider:e.providerCode.trim().length>0,selectedIds:e.connectionIds,onToggle:(i,a)=>s({connectionIds:Ve(e.connectionIds,i,a)}),onSelectAll:i=>s({connectionIds:dn(e.connectionIds,i)})}),t.jsx(xn,{selectedIds:e.connectionIds,labels:n.labels,onRemove:i=>s({connectionIds:Ve(e.connectionIds,i,!1)})})]})}function mn({accounts:e,isLoading:s,isError:o,search:n,onSearch:r,selectedAccountCode:i,onSelect:a}){const{t:u}=h();return t.jsxs("section",{"aria-labelledby":"wiz-scope-accounts",className:"flex flex-col gap-3",children:[t.jsx("h3",{id:"wiz-scope-accounts",className:"text-sm font-semibold",children:u("costs.profiles.wizard.stepScope.accountsHeading")}),t.jsx("p",{className:"text-sm text-muted-foreground",children:u("costs.profiles.wizard.stepScope.accountsDescription")}),t.jsx($,{label:u("costs.profiles.wizard.stepScope.accountSearchLabel"),placeholder:u("costs.profiles.wizard.stepScope.accountSearchPlaceholder"),value:n,onChange:l=>r(l.target.value)}),s&&t.jsx(ht,{rows:4}),!s&&o&&t.jsx("p",{role:"alert",className:"text-sm text-destructive",children:u("costs.profiles.wizard.stepScope.accountsError")}),!s&&!o&&e.length===0&&t.jsx("p",{className:"text-sm text-muted-foreground",children:u("costs.profiles.wizard.stepScope.accountsEmpty")}),!s&&!o&&e.length>0&&t.jsx(es,{name:"wiz-scope-account","aria-label":u("costs.profiles.wizard.stepScope.accountsHeading"),className:"grid grid-cols-2 gap-3 md:grid-cols-3 lg:grid-cols-4",value:i,onChange:a,options:e.map(l=>({value:l.code,label:l.name||l.code}))})]})}function fn({hasAccount:e,connections:s,isLoading:o,isError:n,hasProvider:r,selectedIds:i,onToggle:a,onSelectAll:u}){const{t:l}=h(),d=s.filter(f=>!!f?.code),c=d.map(f=>f.code),m=c.length>0&&c.every(f=>i.includes(f));return t.jsxs("section",{"aria-labelledby":"wiz-scope-connections",className:"flex flex-col gap-3",children:[t.jsxs("div",{className:"flex items-center gap-3",children:[t.jsx("h3",{id:"wiz-scope-connections",className:"text-sm font-semibold",children:l("costs.profiles.wizard.stepScope.connectionsHeading")}),t.jsx("div",{className:"flex-1"}),c.length>0&&t.jsx(C,{variant:"outline",disabled:m,onClick:()=>u(c),children:l("costs.profiles.wizard.stepScope.selectAll")})]}),!e&&t.jsx("p",{className:"text-sm text-muted-foreground",children:l("costs.profiles.wizard.stepScope.selectAccountPrompt")}),e&&o&&t.jsx(ht,{rows:3}),e&&!o&&n&&t.jsx("p",{role:"alert",className:"text-sm text-destructive",children:l("costs.profiles.wizard.stepScope.connectionsError")}),e&&!o&&!n&&d.length===0&&t.jsx("p",{className:"text-sm text-muted-foreground",children:l(r?"costs.profiles.wizard.stepScope.connectionsEmptyForProvider":"costs.profiles.wizard.stepScope.connectionsEmpty")}),e&&!o&&!n&&d.length>0&&t.jsx("div",{className:"divide-y rounded-md border",children:d.map(f=>t.jsx(gn,{connection:f,checked:i.includes(f.code),onToggle:x=>a(f.code,x)},f.code))})]})}function gn({connection:e,checked:s,onToggle:o}){const{t:n}=h(),r=xt(e),i=e.provider?.name??e.provider_id??"";return t.jsxs("div",{className:"flex items-center gap-3 px-4 py-3","data-testid":`scope-connection-${e.code}`,children:[t.jsx(Qe,{checked:s,"aria-label":n("costs.profiles.wizard.stepScope.connectionToggle",{name:r}),onChange:a=>o(a.target.checked)}),t.jsxs("div",{className:"flex flex-col",children:[t.jsx("span",{className:"text-sm font-medium",children:r}),t.jsx("span",{className:"text-xs text-muted-foreground",children:i})]}),t.jsx("div",{className:"flex-1"}),e.status&&t.jsx("span",{className:"text-xs text-muted-foreground",children:e.status})]})}function xn({selectedIds:e,labels:s,onRemove:o}){const{t:n}=h();return t.jsxs("section",{"aria-labelledby":"wiz-scope-selected",className:"flex flex-col gap-2",children:[t.jsx("h3",{id:"wiz-scope-selected",className:"text-sm font-semibold",children:n("costs.profiles.wizard.stepScope.selectedHeading",{count:e.length})}),e.length===0?t.jsx("p",{className:"text-sm text-muted-foreground",children:n("costs.profiles.wizard.stepScope.selectedEmpty")}):t.jsx("ul",{className:"flex flex-wrap gap-2",children:e.map(r=>{const i=s[r]?.name||r;return t.jsxs("li",{className:"flex items-center gap-2 rounded-full border px-3 py-1 text-xs",children:[t.jsx("span",{children:i}),t.jsx(C,{variant:"ghost",size:"icon",startIcon:"X","aria-label":n("costs.profiles.wizard.stepScope.removeConnection",{name:i}),onClick:()=>o(r)})]},r)})})]})}function ht({rows:e}){const s=Array.from({length:e},(o,n)=>`sk-${n}`);return t.jsx("div",{"aria-hidden":"true",className:"flex flex-col gap-2",children:s.map(o=>t.jsx(Xe,{className:"h-10 w-full"},o))})}const hn={INSTALLMENT_COUNT:"costs.profiles.wizard.tierBasis.installmentCount",TXN_AMOUNT:"costs.profiles.wizard.tierBasis.transactionAmount",MONTHLY_TXN_COUNT:"costs.profiles.wizard.tierBasis.monthlyTxnCount",MONTHLY_TXN_VOLUME:"costs.profiles.wizard.tierBasis.monthlyTxnVolume"},yn=[{key:"profile",labelKey:"costs.profiles.wizard.step.profile"},{key:"components",labelKey:"costs.profiles.wizard.step.components"},{key:"scope",labelKey:"costs.profiles.wizard.step.scope"}],bn=ie;function _n(){const{t:e}=h(),[s,o]=Dt(),n=fe();Ot([{label:e("costs.profilesTab"),to:"/costs/profiles"},{label:e("costs.profiles.wizard.titleNew")}]);const r=Math.max(0,Math.min(2,Number(s.get("step")??"0"))),[i,a]=p.useState(Number.isFinite(r)?r:0),[u,l]=p.useState(()=>
1Ao(bn())),[d,c]=p.useState(null),[m,f]=p.useState(!1),{mutateAsync:x,isPending:b}=us(),{mutateAsync:w,isPending:P}=st(),{mutateAsync:_}=tt(),{providers:E,brands:g,types:v,isLoading:L,isError:Q,hasScopeData:ae}=ut(),X=p.useMemo(()=>So.map(j=>({value:j,label:e(hn[j])})),[e]),J=p.useMemo(()=>{const j=[{value:A,label:e("costs.profiles.wizard.scopeOption.anyBrand")}];for(const R of g)j.push({value:R,label:R});return j},[g,e]),Z=p.useMemo(()=>{const j=[{value:A,label:e("costs.profiles.wizard.scopeOption.anyType")}];for(const R of v)j.push({value:R,label:R});return j},[v,e]),z=j=>{a(j),o({step:String(j)})},G=j=>l(R=>({...R,...j})),ee=j=>l(R=>{const S={...R,...j},D=j.providerCode?.trim()??"",oe=R.providerCode.trim();return D&&D!==oe&&(S.connectionIds=[]),S}),te=u.providerCode.trim().length>0,q=p.useRef(!1),xe=async()=>{if(!q.current){q.current=!0;try{await H()}finally{q.current=!1}}},H=async()=>{if(c(null),!te){c(e("costs.profiles.wizard.submitError.providerRequired")),z(0);return}if(!u.validFrom.trim()){c(e("costs.profiles.wizard.submitError.validFromRequired")),z(0);return}const{ok:j}=we(u.cardRates);if(!j){c(e("costs.profiles.wizard.submitError.invalidRates")),z(1);return}let R;try{R=await x(Bo(u))}catch(S){const D=S?.response?.status??S?.status;c(e(D===409?"costs.profiles.wizard.submitError.connectionBound":"costs.profiles.wizard.submitError.generic"));return}try{for(const S of Oo(u))await w({profileKey:R.profile_key,payload:S});k.success(e("costs.profiles.wizard.toast.created")),n("/costs/profiles")}catch(S){try{await _(R.profile_key)}catch{}const D=S?.response?.status??S?.status,oe=S?.response?.data?.error?.code;c(e(D===409?oe==="SCOPE_CLASH"?"costs.profiles.wizard.submitError.scopeClash":"costs.profiles.wizard.submitError.connectionBound":"costs.profiles.wizard.submitError.generic"))}},se=b||P;return t.jsxs("section",{"data-testid":"profile-wizard-page",className:"flex flex-col gap-6",children:[t.jsx("header",{className:"flex flex-col gap-2",children:t.jsx("h1",{className:"text-2xl font-semibold",children:e("costs.profiles.wizard.titleNew")})}),t.jsxs(je,{className:"flex flex-col gap-6 bg-card p-6",children:[t.jsx("div",{className:"flex justify-center",children:t.jsx(ts,{activeStep:i,steps:yn.map(j=>({key:j.key,label:e(j.labelKey)})),onStepClick:m?void 0:j=>z(j)})}),i===0&&t.jsx(Go,{draft:u,onChange:ee,providers:E,providersLoading:L,providersError:Q,currencies:$o}),i===1&&t.jsx(Qo,{draft:u,onChange:G,brandOptions:J,cardTypeOptions:Z,tierBasisOptions:X,onEditorOpenChange:f,catalogLoading:L,catalogError:Q,c
1atalogHasData:ae}),i===2&&t.jsx(pn,{draft:u,onChange:G}),d&&t.jsx("p",{role:"alert",className:"text-sm text-destructive",children:d}),t.jsxs("footer",{className:"flex items-center justify-between border-t pt-6",children:[t.jsx(C,{variant:"outline",onClick:()=>i===0?n("/costs/profiles"):z(i-1),disabled:se||m,children:e(i===0?"costs.profiles.wizard.cancel":"costs.profiles.wizard.back")}),i<2?t.jsx(C,{onClick:()=>z(i+1),disabled:i===0&&!te||m,children:e("costs.profiles.wizard.next")}):t.jsx(C,{onClick:xe,loading:se,children:e("costs.profiles.wizard.createButton")})]})]})]})}const Ke=ie;function jn({open:e,onClose:s,profileKey:o,component:n,nextPayload:r,onSuccess:i}){const{t:a}=h(),[u,l]=p.useState(Ke()),{mutateAsync:d,isPending:c}=xs(),m=u<Ke(),f=async()=>{const x=await d({profileKey:o,componentId:n.component_id,payload:{...r,effective_from:u}});i?.(x),s()};return t.jsxs(ne,{open:e,onClose:s,onConfirm:f,title:"Update effective date",description:"A price change mints a new version of the component. Days on or after the effective date get the new rate.",confirmLabel:"Ap
1ply",cancelLabel:"Cancel",isLoading:c,children:[t.jsx($,{type:"date",label:a("costs.profiles.reprice.prompt"),value:u,onChange:x=>l(x.target.value)}),m&&t.jsx("p",{role:"alert","data-testid":"reprice-backdated-warning",className:"text-sm text-yellow-600",children:a("costs.profiles.reprice.backdatedWarning")})]})}const vn=ie;function $e(e){const s=e;return s?.response?.status??s?.status}function Ge(e){return e?.response?.data?.error?.code}function Cn(){const{t:e}=h();return s=>{const o=s.card_brand??e("costs.profiles.edit.scope.anyBrand"),n=s.card_type??e("costs.profiles.edit.scope.anyType");return`${o} · ${n}`}}function En(){const{t:e}=h();return s=>{if(s.calc_type==="TIERED"){const i=s.tiers?.length??0;return e("costs.profiles.edit.rateSummary.tiers",{count:i})}const o=Io(s.rate_fraction),n=s.fixed_minor??0,r=[];return o!=null&&r.push(`${o}%`),n>0&&r.push(e("costs.profiles.edit.rateSummary.fixed",{amount:n})),r.length>0?r.join(" "):e("costs.profiles.edit.rateSummary.empty")}}const Nn=(e,s)=>{const{t:o}=h(),n=Cn(),r=En();return[{accessorKey:"cost_type",header:o("costs.profiles.edit.columns.costType"),cell:({row:a})=>a.original.cost_type},{accessorKey:"calc_type",header:o("costs.profiles.edit.columns.calc"),cell:({row:a})=>a.original.calc_type},{id:"scope",header:o("costs.profiles.edit.columns.scope"),cell:({row:a})=>n(a.original.scope_json??{})},{id:"rate",header:o("costs.profiles.edit.columns.rate"),cell:({row:a})=>r(a.original)},{accessorKey:"valid_from",header:o("costs.profiles.edit.columns.validFrom")},{id:"row-actions",header:"",cell:({row:a})=>t.jsxs("div",{className:"flex justify-end gap-2",children:[t.jsx(C,{variant:"ghost",size:"sm",onClick:()=>e(a.original),"data-testid":`reprice-${a.original.component_id}`,children:o("costs.profiles.edit.row.reprice")}),t.jsx(C,{variant:"ghost",size:"sm",onClick:()=>s(a.original),"data-testid":`delete-${a.original.component_id}`,"aria-label":o("costs.profiles.edit.row.deleteAria",{costType:a.original.cost_type}),children:t.jsx(ge,{name:"Trash",size:"sm"})})]})}]};function wn(){const{t:e}=h(),{profileKey:s}=Bt(),o=fe(),{data:n,isLoading:r}=ls(s),{data:i,isLoading:a}=cs(s),{brands:u,types:l,isLoading:d,isError:c}=ut(),m=i?.rows??[],f=p.useMemo(()=>m.filter(y=>y.role==="RATE"&&y.locus==="CARD"),[m]),{mutateAsync:x,isPending:b}=ps(),{mutateAsync:w}=ms(),{mutateAsync:P}=st(),{mutateAsync:_,isPending:E}=fs(),{mutateAsync:g}=gs(),[v,L]=p.useState(!1),[Q,ae]=p.useState(""),[X,J]=p.useState(null),[Z,z]=p.useState(null),[G,ee]=p.useState(null),[te,q]=p.useState(""),[xe,H]=p.useState(null),[se,j]=p.useState(!1),[R,S]=p.useState(null),D=r||a,oe=()=>{ae(n?.name??""),L(!0)},yt=async()=>{if(!s)return;const y=Q.trim();if(!y||y===n?.name){L(!1);return}try{await x({profileKey:s,payload:{name:y}}),k.success(e("costs.profiles.edit.toast.renamed")),L(!1)}catch{k.error(e("costs.profiles.edit.toast.renameError"))}},bt=async()=>{if(!(!s||!X))try{await w({profileKey:s,componentId:X.component_id}),k.success(e("costs.profiles.edit.toast.rowRemoved"))}catch{k.error(e("costs.profiles.edit.toast.rowRemoveError"))}finally{J(null)}},_t=async()=>{if(!(!s||!G))try{await g({profileKey:s,connectionId:G}),k.success(e("costs.profiles.edit.toast.connectionUnbound"))}catch{k.error(e("costs.profiles.edit.toast.connectionUnbindError"))}finally{ee(null)}},jt=async()=>{if(!s)return;const y=te.trim();if(!y){H(e("costs.profiles.edit.connections.bindErrorEmpty"));return}H(null);try{await _({profileKey:s,payload:{connection_id:y}}),k.success(e("costs.profiles.edit.toast.connectionBound")),q("")}catch(le){const he=Ge(le);$e(le)===409?H(e(he==="CONNECTION_ALREADY_BOUND"?"costs.profiles.edit.connections.bindErrorAlreadyBound":"costs.profiles.edit.connections.bindErrorConflict")):H(e("costs.profiles.edit.connections.bindErrorGeneric"))}},vt=async y=>{if(!n||!s)return;const le={name:n.name,providerCode:n.provider_code,pricingModel:n.pricing_model,settlementCurrency:n.settlement_currency,validFrom:vn(),platformCosts:at()},he=dt(le,y);S(null);try{await P({profileKey:s,payload:he}),k.success(e("costs.profiles.edit.toast.rowAdded")),j(!1)}catch(Te){const Nt=Ge(Te);$e(Te)===409?S(e(Nt==="SCOPE_CLASH"?"costs.profiles.edit.addRow.errorScopeClash":"costs.profiles.edit.addRow.errorConflict")):S(e("costs.profiles.edit.addRow.errorGeneric"))}},Ct=y=>({cost_type:y.cost_type,calc_type:y.calc_type,role:y.role,locus:y.locus,currency:y.currency,scope_json:y.scope_json,valid_from:y.valid_from,valid_to:y.valid_to,rate_fraction:y.rate_fraction,fixed_minor:y.fixed_minor,trigger_json:y.trigger_json,tier_basis:y.tier_basis,tiers:y.tiers,min_fee_minor:y.min_fee_minor,max_fee_minor:y.max_fee_minor,component_key:y.component_key}),Et=Nn(z,J);return t.jsxs("section",{"data-testid":"profile-edit-page",className:"flex flex-col gap-6",children:[t.jsx("div",{className:"flex items-center gap-3",children:t.jsxs(C,{variant:"ghost",size:"sm",onClick:()=>o("/costs/profiles"),"aria-label":e("costs.profiles.edit.backAria"),children:[t.jsx(ge,{name:"ArrowLeft",size:"sm"}),e("costs.profiles.edit.back")]})}),t.jsxs(ss,{loading:D,header:n?t.jsx(os,{title:v?t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx($,{"aria-label":e("costs.profiles.edit.nameLabel"),value:Q,onChange:y=>ae(y.target.value)}),t.jsx(C,{onClick:yt,loading:b,"data-testid":"profile-name-save",children:e("costs.profiles.edit.nameSave")}),t.jsx(C,{variant:"ghost",onClick:()=>L(!1),children:e("costs.profiles.edit.nameCancel")})]}):t.jsx("span",{"data-testid":"profile-name",children:n.name}),actions:!v&&t.jsx(C,{variant:"outline",onClick:oe,"data-testid":"profile-name-edit",children:e("costs.profiles.edit.nameEdit")}),items:[{label:e("costs.profiles.edit.header.provider"),value:n.provider_code},{label:e("costs.profiles.edit.header.pricingModel"),value:n.pricing_model},{label:e("costs.profiles.edit.header.settlementCurrency"),value:n.settlement_currency},{label:e("costs.profiles.edit.header.status"),value:n.status}]}):null,children:[t.jsx(Pe,{id:"rate-card",title:e("costs.profiles.edit.rateCard.title"),description:e("costs.profiles.edit.rateCard.description"),actions:t.jsx(C,{variant:"outline",onClick:()=>j(!0),startIcon:"Plus","data-testid":"add-rate-row",children:e("costs.profiles.edit.rateCard.addRow")}),children:t.jsx(de,{columns:Et,data:f,isLoading:a})}),t.jsxs(Pe,{id:"connections",title:e("costs.profiles.edit.connections.title"),description:e("costs.profiles.edit.connections.description"),children:[(n?.connection_ids??[]).length===0?t.jsx("p",{className:"text-sm text-muted-foreground",children:e("costs.profiles.edit.connections.empty")}):t.jsx("ul",{className:"flex flex-col gap-2","data-testid":"connection-list",children:(n?.connection_ids??[]).map(y=>t.jsxs("li",{className:"flex items-center justify-between gap-3 rounded-md border p-3","data-testid":`connection-row-${y}`,children:[t.jsx("code",{className:"text-sm",children:y}),t.jsx(C,{variant:"ghost",size:"sm",onClick:()=>ee(y),"data-testid":`unbind-${y}`,children:e("costs.profiles.edit.connections.unbind")})]},y))}),t.jsxs("div",{className:"mt-4 flex items-end gap-3",children:[t.jsx($,{label:e("costs.profiles.edit.connections.bindLabel"),value:te,onChange:y=>q(y.target.value),placeholder:e("costs.profiles.edit.connections.bindPlaceholder"),"aria-label":e("costs.profiles.edit.connections.bindAria"),error:xe??void 0,"data-testid":"bind-input"}),t.jsx(C,{onClick:jt,loading:E,"data-testid":"bind-submit",children:e("costs.profiles.edit.connections.bindSubmit")})]})]})]}),t.jsx(ne,{open:X!==null,onClose:()=>J(null),onConfirm:bt,title:e("costs.profiles.edit.deleteRow.title"),description:e("costs.profiles.edit.deleteRow.description"),confirmLabel:e("costs.profiles.edit.deleteRow.confirm"),cancelLabel:e("costs.profiles.edit.deleteRow.cancel"),variant:"destructive"}),t.jsx(ne,{open:G!==null,onClose:()=>ee(null),onConfirm:_t,title:e("costs.profiles.edit.unbindDialog.title"),description:e("costs.profiles.edit.unbindDialog.description"),confirmLabel:e("costs.profiles.edit.unbindDialog.confirm"),cancelLabel:e("costs.profiles.edit.unbindDialog.cancel"),variant:"destructive"}),Z&&s&&t.jsx(jn,{open:!0,onClose:()=>z(null),profileKey:s,component:Z,nextPayload:Ct(Z),onSuccess:()=>{k.success(e("costs.profiles.edit.toast.rateUpdated")),z(null)}}),se&&t.jsx(Tn,{open:se,onClose:()=>{j(!1),S(null)},onSubmit:vt,error:R,brands:u,types:l,catalogLoading:d,catalogError:c})]})}function Tn({open:e,onClose:s,onSubmit:o,error:n,brands:r,types:i,catalogLoading:a,catalogError:u}){const{t:l}=h(),[d,c]=p.useState(()=>Ne()),[m,f]=p.useState(!1),x=[{value:A,label:l("costs.profiles.edit.scope.anyBrand")},...r.map(_=>({value:_,label:_}))],b=[{value:A,label:l("costs.profiles.edit.scope.anyType")},...i.map(_=>({value:_,label:_}))],w=pt(a,u,r.length>0||i.length>0),P=async()=>{f(!0);try{await o(d)}finally{f(!1)}};return t.jsx(ne,{open:e,onClose:s,onConfirm:P,title:l("costs.profiles.edit.addRow.title"),description:l("costs.profiles.edit.addRow.description"),confirmLabel:l("costs.profiles.edit.addRow.confirm"),cancelLabel:l("costs.profiles.edit.addRow.cancel"),isLoading:m,confirmDisabled:w,children:t.jsxs("div",{className:"flex flex-col gap-3",children:[u&&t.jsx("p",{role:"alert",className:"text-sm text-destructive",children:l("costs.profiles.edit.addRow.catalogLoadError")}),t.jsx(K,{label:l("costs.profiles.edit.addRow.cardBrand"),value:d.cardBrand,onChange:_=>c(E=>({...E,cardBrand:_||A})),options:x,disabled:w}),t.jsx(K,{label:l("costs.profiles.edit.addRow.cardType"),value:d.cardType,onCh
1ange:_=>c(E=>({...E,cardType:_||A})),options:b,disabled:w}),t.jsx(me,{label:l("costs.profiles.edit.addRow.rate"),value:d.ratePct,onCommit:_=>c(E=>({...E,ratePct:_})),placeholder:l("costs.profiles.edit.addRow.ratePlaceholder")}),t.jsx(pe,{label:l("costs.profiles.edit.addRow.fixed"),value:d.fixedMinor,onCommit:_=>c(E=>({...E,fixedMinor:_}))}),t.jsx("input",{type:"hidden","data-testid":"rate-trigger",value:JSON.stringify(it)}),n&&t.jsx("p",{role:"alert",className:"text-sm text-destructive",children:n})]})})}function qe(){const{search:e}=He();return t.jsx(Ft,{to:{pathname:ys,search:e},replace:!0})}function Rn(){return[{element:t.jsx(_s,{}),children:[{index:!0,element:t.jsx(qe,{})},{path:"insights",element:t.jsx(lo,{})},{path:"profiles",element:t.jsx(Ro,{})}]},{path:"profiles/new",element:t.jsx(_n,{})},{path:"profiles/:profileKey",element:t.jsx(wn,{})},{path:"*",element:t.jsx(qe,{})}]}function Sn(){return Rn()}const An="view_settlement_reports",In=()=>{const{t:e}=h(),s=Mt({name:Se.COSTS_SECTION}),{statusPermission:o}=ns([An]),n=Sn(),r=Ut(n);return s?.data?.[Se.COSTS_SECTION]!==!0||o===Ae.LOADING?null:o===Ae.DENIED?t.jsxs(t.Fragment,{children:[t.jsx(Je,{className:"mb-5",children:e("costs.title","Costs")}),t.jsx(rs,{})]}):r};function vr(){return t.jsx(hs,{children:t.jsx(In,{})})}export{vr 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.