UNPKG

datajunction-ui

Version:
3 lines (2 loc) 46.7 kB
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("react/jsx-runtime"),a=require("react"),vt=require("react-router-dom"),_e=require("./index-h1A5IisM.cjs"),pt=require("./PreAggDetailsPanel-DbHqhxEA.cjs"),de=require("./BarChart-GlY5o0Rr.cjs"),yt=require("./LineChart-DiBufR9L.cjs"),Mt=[{value:null,label:"Auto"},{value:"druid",label:"Druid"},{value:"trino",label:"Trino"}],ft="application/x-dj-dimension",Ct=(o,u)=>(o.trim()?o.trimEnd()+" AND ":"")+u;function kt({text:o}){return e.jsx("span",{className:"chip-label chip-label-clip",title:o,children:e.jsx("bdi",{className:"chip-label-inner",children:o})})}function Lt({metrics:o,selectedMetrics:u,onMetricsChange:w,dimensions:D,selectedDimensions:b,onDimensionsChange:_,loading:y,cubes:x=[],onLoadCubePreset:v,loadedCubeName:g=null,onClearSelection:F,filters:h=[],onFiltersChange:W,selectedEngine:P=null,onEngineChange:M,onRunQuery:L,canRunQuery:A=!1,queryLoading:$=!1,compatibleMetrics:U=null}){const[B,le]=a.useState(""),[C,be]=a.useState(""),[T,me]=a.useState(new Set),[$e,V]=a.useState(new Set),[G,ne]=a.useState(new Set),[xe,je]=a.useState(!1),[I,Ce]=a.useState(""),[ke,Ne]=a.useState(!1),[X,N]=a.useState(!1),[k,z]=a.useState(""),[H,J]=a.useState(!1),[he,Fe]=a.useState(35),[we,Me]=a.useState(65),[Z,Le]=a.useState(85),pe=a.useRef(""),Ae=a.useRef(null),Te=a.useRef(null),Se=a.useRef(null),R=a.useRef(null),oe=a.useRef(null),ie=a.useRef(null),De=a.useRef({split1:35,split2:65,split3:85});a.useEffect(()=>{De.current={split1:he,split2:we,split3:Z}},[he,we,Z]);const fe=8,ve=a.useMemo(()=>g?x.find(t=>t.name===g)||{name:g}:null,[g,x]);a.useEffect(()=>{const t=l=>{Ae.current&&!Ae.current.contains(l.target)&&je(!1)};return document.addEventListener("mousedown",t),()=>document.removeEventListener("mousedown",t)},[]);const Ee=a.useMemo(()=>{const t=I.toLowerCase().trim();return t?x.filter(l=>{const m=l.name||"",f=l.display_name||"";return m.toLowerCase().includes(t)||f.toLowerCase().includes(t)}):x},[x,I]),Pe=t=>{const l=t.split(".");return l[l.length-1]},Ge=t=>{const l=t.split(".");return l.length>1?l.slice(0,-1).join("."):"default"},ye=a.useMemo(()=>{const t={};return o.forEach(l=>{const m=Ge(l);t[m]||(t[m]=[]),t[m].push(l)}),t},[o]),{filteredGroups:ge,sortedNamespaces:Re}=a.useMemo(()=>{const t=B.trim().toLowerCase();if(!t){const f=Object.keys(ye).sort();return{filteredGroups:ye,sortedNamespaces:f}}const l={};Object.entries(ye).forEach(([f,p])=>{const r=p.filter(s=>s.toLowerCase().includes(t));r.length>0&&(r.sort((s,n)=>{const i=Pe(s).toLowerCase(),c=Pe(n).toLowerCase(),d=i.startsWith(t),E=c.startsWith(t);return d&&!E?-1:!d&&E?1:i.localeCompare(c)}),l[f]=r)});const m=Object.keys(l).sort((f,p)=>{const r=f.toLowerCase(),s=p.toLowerCase(),n=r.startsWith(t),i=s.startsWith(t);if(n&&!i)return-1;if(!n&&i)return 1;const c=r.includes(t),d=s.includes(t);if(c&&!d)return-1;if(!c&&d)return 1;const E=l[f].length,q=l[p].length;return E!==q?q-E:r.localeCompare(s)});return{filteredGroups:l,sortedNamespaces:m}},[ye,B]);a.useEffect(()=>{const t=B.trim(),l=pe.current;t&&t!==l&&me(new Set(Re)),pe.current=t},[B,Re]);const j=a.useMemo(()=>{const t=new Map;return D.forEach(l=>{var f,p;if(!l.name)return;const m=t.get(l.name);(!m||(((f=l.path)==null?void 0:f.length)||0)<(((p=m.path)==null?void 0:p.length)||1/0))&&t.set(l.name,l)}),Array.from(t.values())},[D]),He=t=>{const l=t.match(/\[([^\]]+)\]$/);return l?l[1]:null},Q=t=>t?"via "+t.replace(/->/g," → "):"direct",ce=t=>t?t.split("->").length:0,K=a.useMemo(()=>{const t=C.trim().toLowerCase(),l=new Map;j.forEach(f=>{var i;if(!f.name)return;const p=((i=f.path)==null?void 0:i.length)>0?f.path[f.path.length-1]:f.name.split(".").slice(0,-1).join("."),r=Math.max(0,f.path?f.path.length-1:0),s=He(f.name);l.has(p)||l.set(p,{nodeKey:p,minDistance:r,rolePathMap:new Map});const n=l.get(p);n.minDistance=Math.min(n.minDistance,r),n.rolePathMap.has(s)||n.rolePathMap.set(s,{roleKey:s,dimensions:[]}),n.rolePathMap.get(s).dimensions.push(f)});let m=Array.from(l.values()).map(f=>{const p=Array.from(f.rolePathMap.values()).sort((r,s)=>ce(r.roleKey)-ce(s.roleKey)||(r.roleKey||"").localeCompare(s.roleKey||""));return p.forEach(r=>{r.dimensions.sort((s,n)=>s.name.localeCompare(n.name))}),{nodeKey:f.nodeKey,minDistance:f.minDistance,rolePaths:p,totalCount:p.reduce((r,s)=>r+s.dimensions.length,0)}});return t&&(m=m.map(f=>({...f,rolePaths:f.rolePaths.map(p=>({...p,dimensions:p.dimensions.filter(r=>r.name.toLowerCase().includes(t)||r.name.split(".").pop().toLowerCase().includes(t))})).filter(p=>p.dimensions.length>0||(p.roleKey||"").toLowerCase().includes(t))})).filter(f=>f.rolePaths.length>0||f.nodeKey.toLowerCase().includes(t)).map(f=>({...f,totalCount:f.rolePaths.reduce((p,r)=>p+r.dimensions.length,0)}))),m.sort((f,p)=>f.minDistance-p.minDistance||f.nodeKey.localeCompare(p.nodeKey)),m},[j,C]);a.useEffect(()=>{K.length!==0&&(C.trim()?(V(new Set(K.map(t=>t.nodeKey))),ne(new Set(K.flatMap(t=>t.rolePaths.map(l=>`${t.nodeKey}::${l.roleKey}`))))):(V(t=>t.size>0?t:new Set(K.filter(l=>l.minDistance===0).map(l=>l.nodeKey))),ne(t=>t.size>0?t:new Set(K.filter(l=>l.minDistance===0).map(l=>`${l.nodeKey}::null`)))))},[K,C]);const ee=t=>(t||"").split(".").slice(-2).join("."),Qe=t=>{me(l=>{const m=new Set(l);return m.has(t)?m.delete(t):m.add(t),m})},Ye=t=>{V(l=>{const m=new Set(l);return m.has(t)?m.delete(t):m.add(t),m})},Xe=(t,l)=>{const m=`${t}::${l}`;ne(f=>{const p=new Set(f);return p.has(m)?p.delete(m):p.add(m),p})},Je=t=>t.split(".").pop(),We=a.useCallback((t,l)=>{t.preventDefault();const m=l===1?De.current.split1:l===2?De.current.split2:De.current.split3;ie.current={divider:l,startY:t.clientY,startSplit:m}},[]);a.useEffect(()=>{const t=m=>{if(!ie.current||!oe.current)return;const f=oe.current.getBoundingClientRect().height,p=(m.clientY-ie.current.startY)/f*100,{divider:r,startSplit:s}=ie.current,{split1:n,split2:i,split3:c}=De.current;r===1?Fe(Math.max(10,Math.min(i-15,s+p))):r===2?Me(Math.max(n+15,Math.min(c-10,s+p))):Le(Math.max(i+10,Math.min(95,s+p)))},l=()=>{ie.current=null};return window.addEventListener("mousemove",t),window.addEventListener("mouseup",l),()=>{window.removeEventListener("mousemove",t),window.removeEventListener("mouseup",l)}},[]);const Ke=t=>{u.includes(t)?w(u.filter(l=>l!==t)):w([...u,t])},Ze=t=>{w(u.filter(l=>l!==t))},et=t=>{b.includes(t)?_(b.filter(l=>l!==t)):_([...b,t])},tt=t=>{_(b.filter(l=>l!==t))},st=(t,l)=>{const m=[...new Set([...u,...l])];w(m)},nt=(t,l)=>{w(u.filter(m=>!l.includes(m)))},at=t=>{v&&v(t.name),je(!1),Ce("")},rt=()=>{F?F():(w([]),_([]))},Be=()=>{const t=k.trim();t&&!h.includes(t)&&W&&(W([...h,t]),z(""))},lt=t=>{t.key==="Enter"&&(t.preventDefault(),Be())},ot=t=>{W&&W(h.filter(l=>l!==t))},it=t=>{var l;z(m=>Ct(m,t)),W&&W(h.filter(m=>m!==t)),(l=R.current)==null||l.focus()},Ue=t=>{var l;z(m=>Ct(m,t+" ")),(l=R.current)==null||l.focus()},ct=(t,l)=>{t.preventDefault(),t.stopPropagation(),Ue(l)},Ie=(t,l)=>{t.dataTransfer.setData(ft,l),t.dataTransfer.setData("text/plain",l),t.dataTransfer.effectAllowed="copy"},ut=t=>{t.dataTransfer.types.includes(ft)&&(t.preventDefault(),t.dataTransfer.dropEffect="copy",H||J(!0))},dt=t=>{t.currentTarget.contains(t.relatedTarget)||J(!1)},mt=t=>{const l=t.dataTransfer.getData(ft);l&&(t.preventDefault(),Ue(l)),J(!1)};return e.jsxs("div",{className:"selection-panel",children:[x.length>0&&e.jsxs("div",{className:"cube-preset-section",ref:Ae,children:[e.jsxs("div",{className:"preset-row",children:[e.jsxs("button",{className:`preset-button ${ve?"has-preset":""}`,onClick:()=>je(!xe),children:[e.jsx("span",{className:"preset-icon",children:ve?"📦":"📂"}),e.jsx("span",{className:"preset-label",children:ve?ve.display_name||(ve.name?ve.name.split(".").pop():"Cube"):"Load from Cube"}),e.jsx("span",{className:"dropdown-arrow",children:xe?"▲":"▼"})]}),(u.length>0||b.length>0)&&e.jsx("button",{className:"clear-all-btn",onClick:rt,children:"Clear"})]}),xe&&e.jsxs("div",{className:"cube-dropdown",children:[e.jsx("input",{type:"text",className:"cube-search",placeholder:"Search cubes...",value:I,onChange:t=>Ce(t.target.value),autoFocus:!0}),e.jsx("div",{className:"cube-list",children:Ee.length===0?e.jsx("div",{className:"cube-empty",children:I?"No cubes match your search":"No cubes available"}):Ee.map(t=>e.jsxs("button",{className:`cube-option ${g===t.name?"selected":""}`,onClick:()=>at(t),children:[e.jsx("span",{className:"cube-name",children:t.display_name||(t.name?t.name.split(".").pop():"Unknown")}),e.jsx("span",{className:"cube-info",children:t.name}),g===t.name&&e.jsx("span",{className:"cube-selected-icon",children:"✓"})]},t.name))})]})]}),e.jsxs("div",{className:"resizable-sections",ref:oe,children:[e.jsxs("div",{className:"selection-section",style:{flex:he},children:[e.jsxs("div",{className:"section-header",children:[e.jsx("h3",{children:"Metrics"}),e.jsxs("span",{className:"selection-count",children:[u.length," selected"]})]}),e.jsxs("div",{className:"combobox-input",onClick:()=>{var t;return(t=Te.current)==null?void 0:t.focus()},children:[u.length>0&&e.jsx("div",{className:`combobox-chips ${u.length>fe?ke?"expanded":"collapsed":""}`,children:u.map(t=>e.jsxs("span",{className:"selected-chip metric-chip",children:[e.jsx(kt,{text:Pe(t)}),e.jsx("button",{className:"chip-remove",onClick:l=>{l.stopPropagation(),Ze(t)},title:`Remove ${Pe(t)}`,children:"×"})]},t))}),e.jsxs("div",{className:"combobox-input-row",children:[e.jsx("input",{ref:Te,type:"text",className:"combobox-search",placeholder:"Search metrics...",value:B,onChange:t=>le(t.target.value),onClick:t=>t.stopPropagation()}),u.length>fe&&e.jsx("button",{className:"combobox-action",onClick:t=>{t.stopPropagation(),Ne(!ke)},children:ke?"Show less":"Show all"}),u.length>0&&e.jsx("button",{className:"combobox-action",onClick:t=>{t.stopPropagation(),w([])},children:"Clear"})]})]}),e.jsxs("div",{className:"selection-list",children:[Re.map(t=>{const l=ge[t],m=T.has(t),f=l.filter(p=>u.includes(p)).length;return e.jsxs("div",{className:"namespace-group",children:[e.jsxs("div",{className:"namespace-header",onClick:()=>Qe(t),children:[e.jsx("span",{className:"expand-icon",children:m?"▼":"▶"}),e.jsx("span",{className:"namespace-name",children:t}),e.jsxs("span",{className:"namespace-count",children:[f>0&&e.jsx("span",{className:"selected-badge",children:f}),l.length]})]}),m&&e.jsxs("div",{className:"namespace-items",children:[e.jsxs("div",{className:"namespace-actions",children:[e.jsx("button",{type:"button",className:"select-all-btn",onClick:()=>st(t,l),children:"Select all"}),e.jsx("button",{type:"button",className:"select-all-btn",onClick:()=>nt(t,l),children:"Clear"})]}),l.map(p=>{const r=U!==null&&!U.has(p)&&!u.includes(p);return e.jsxs("label",{className:`selection-item${r?" metric-incompatible":""}`,title:r?"Not compatible with selected dimensions":p,children:[e.jsx("input",{type:"checkbox",checked:u.includes(p),onChange:()=>Ke(p)}),e.jsx("span",{className:"item-name",children:Pe(p)}),U!==null&&U.has(p)&&!u.includes(p)&&e.jsx("span",{className:"metric-compatible-badge",title:"Compatible with selected dimensions",children:"✓"})]},p)})]})]},t)}),Re.length===0&&e.jsx("div",{className:"empty-list",children:B?"No metrics match your search":"No metrics available"})]})]}),e.jsx("div",{className:"section-divider draggable-divider",onMouseDown:t=>We(t,1)}),e.jsxs("div",{className:"selection-section",style:{flex:we-he},children:[e.jsxs("div",{className:"section-header",children:[e.jsx("h3",{children:"Dimensions"}),e.jsxs("span",{className:"selection-count",children:[b.length," selected",D.length>0&&` / ${D.length} available`]})]}),u.length===0?e.jsx("div",{className:"empty-list hint",children:"Select metrics to see available dimensions"}):y?e.jsx("div",{className:"empty-list",children:"Loading dimensions..."}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"combobox-input",onClick:()=>{var t;return(t=Se.current)==null?void 0:t.focus()},children:[b.length>0&&e.jsx("div",{className:`combobox-chips ${b.length>fe?X?"expanded":"collapsed":""}`,children:b.map(t=>e.jsxs("span",{className:"selected-chip dimension-chip draggable-dim",title:`${t} — drag to Filters to filter on it`,draggable:!0,onDragStart:l=>Ie(l,t),children:[e.jsx(kt,{text:ee(t)}),e.jsx("button",{className:"chip-remove",onClick:l=>{l.stopPropagation(),tt(t)},title:`Remove ${ee(t)}`,children:"×"})]},t))}),e.jsxs("div",{className:"combobox-input-row",children:[e.jsx("input",{ref:Se,type:"text",className:"combobox-search",placeholder:"Search dimensions...",value:C,onChange:t=>be(t.target.value),onClick:t=>t.stopPropagation()}),b.length>fe&&e.jsx("button",{className:"combobox-action",onClick:t=>{t.stopPropagation(),N(!X)},children:X?"Show less":"Show all"}),b.length>0&&e.jsx("button",{className:"combobox-action",onClick:t=>{t.stopPropagation(),_([])},children:"Clear"})]})]}),e.jsxs("div",{className:"selection-list dimensions-list",children:[K.map(t=>{const l=$e.has(t.nodeKey);return e.jsxs("div",{className:"dim-group",children:[e.jsxs("div",{className:"dim-group-header",onClick:()=>Ye(t.nodeKey),title:t.nodeKey,children:[e.jsx("span",{className:"expand-icon",children:l?"▼":"▶"}),e.jsx("span",{className:"dim-group-name",children:Je(t.nodeKey)}),e.jsx("span",{className:"dim-group-count",children:t.totalCount})]}),l&&t.rolePaths.map(m=>{const f=`${t.nodeKey}::${m.roleKey}`,p=G.has(f),r=ce(m.roleKey),s=r===0?"direct":`${r} hop${r>1?"s":""}`;return e.jsxs("div",{className:"dim-role-group",children:[e.jsxs("div",{className:"dim-role-header",onClick:()=>Xe(t.nodeKey,m.roleKey),children:[e.jsx("span",{className:"expand-icon",children:p?"▼":"▶"}),e.jsx("span",{className:"dim-role-label",children:Q(m.roleKey)}),e.jsx("span",{className:"dim-group-meta",children:s}),e.jsx("span",{className:"dim-group-count",children:m.dimensions.length})]}),p&&m.dimensions.map(n=>e.jsxs("label",{className:"selection-item dimension-item dim-role-item draggable-dim",title:`${n.name} — drag to Filters to filter on it`,draggable:!0,onDragStart:i=>Ie(i,n.name),children:[e.jsx("input",{type:"checkbox",checked:b.includes(n.name),onChange:()=>et(n.name)}),e.jsx("div",{className:"dimension-info",children:e.jsx("span",{className:"item-name",children:ee(n.name.replace(/\[[^\]]*\]$/,""))})}),e.jsx("button",{className:"dim-filter-btn",title:`Add "${n.name}" to filters`,onClick:i=>ct(i,n.name),children:"+ filter"})]},n.name))]},f)})]},t.nodeKey)}),K.length===0&&e.jsx("div",{className:"empty-list",children:C?"No dimensions match your search":"No shared dimensions"})]})]})]}),e.jsx("div",{className:"section-divider draggable-divider",onMouseDown:t=>We(t,2)}),e.jsxs("div",{className:`selection-section filters-section${H?" drop-active":""}`,style:{flex:Z-we},onDragOver:ut,onDragLeave:dt,onDrop:mt,children:[e.jsxs("div",{className:"section-header",children:[e.jsx("h3",{children:"Filters"}),e.jsxs("span",{className:"selection-count",children:[h.length," applied"]})]}),H&&e.jsx("div",{className:"filter-drop-hint",children:"Drop to filter on this dimension"}),h.length>0&&e.jsx("div",{className:"filter-chips-container",children:h.map((t,l)=>e.jsxs("span",{className:"filter-chip",children:[e.jsx("button",{type:"button",className:"filter-chip-text filter-chip-edit",onClick:()=>it(t),title:`${t} — click to edit`,children:t}),e.jsx("button",{className:"filter-chip-remove",onClick:()=>ot(t),title:"Remove filter",children:"×"})]},l))}),e.jsxs("div",{className:"filter-input-container",children:[e.jsx("input",{ref:R,type:"text",className:"filter-input",placeholder:"e.g. v3.date.date_id >= '2024-01-01'",value:k,onChange:t=>z(t.target.value),onKeyDown:lt}),e.jsx("button",{className:"filter-add-btn",onClick:Be,disabled:!k.trim(),children:"Add"})]})]}),e.jsx("div",{className:"section-divider draggable-divider",onMouseDown:t=>We(t,3)}),e.jsxs("div",{className:"selection-section engine-run-section",style:{flex:100-Z},children:[e.jsxs("div",{className:"engine-section",children:[e.jsx("span",{className:"engine-label",children:"Engine"}),e.jsx("div",{className:"engine-pills",children:Mt.map(({value:t,label:l})=>e.jsx("button",{className:`engine-pill${P===t?" active":""}`,onClick:()=>M&&M(t),children:l},l))})]}),e.jsxs("div",{className:"run-query-section",children:[e.jsx("button",{className:"run-query-btn",onClick:L,disabled:!A||$,children:$?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"spinner small"}),"Running..."]}):e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"run-icon",children:"▶"}),"Run Query"]})}),!A&&e.jsx("span",{className:"run-hint",children:"Select at least one metric to run a query"})]})]})]})]})}_e.SyntaxHighlighter.registerLanguage("sql",_e.sql);const bt=["#60a5fa","#34d399","#fbbf24","#f87171","#a78bfa","#22d3ee","#fb923c"],Et=2;function Nt(o){const u=o.name.toLowerCase(),w=(o.type||"").toLowerCase();return w.includes("date")||w.includes("timestamp")||w.includes("time")||u==="date"||u==="day"||u==="week"||u==="month"||u==="year"||u==="quarter"||u.endsWith("_date")||u.endsWith("_day")||u.endsWith("_week")||u.endsWith("_month")||u.endsWith("_year")||u.endsWith("_at")||u.startsWith("date")||u.startsWith("ds")}function St(o){const u=(o.type||"").toLowerCase();return u.includes("int")||u.includes("float")||u.includes("double")||u.includes("decimal")||u.includes("numeric")||u.includes("real")||u.includes("number")}function Rt(o,u){if(!o.length||!u.length)return null;const w=o.map((x,v)=>({...x,idx:v})),D=w.filter(x=>Nt(x)),b=w.filter(x=>St(x)),y=w.filter(x=>!St(x)).filter(x=>!Nt(x));if(D.length>0){const x=D[0],v=b.filter(g=>g.idx!==x.idx);if(v.length>0)return y.length===1?{type:"line",xCol:x,groupByCol:y[0],metricCols:v}:{type:"line",xCol:x,metricCols:v}}if(y.length>0&&b.length>0)return y.length===1?{type:"bar",xCol:y[0],metricCols:b}:y.length===2?{type:"bar",xCol:y[0],groupByCol:y[1],metricCols:b}:{type:"bar",xCol:y[0],metricCols:b};if(b.length>1){const x=b[0],v=b.slice(1);return{type:"line",xCol:x,metricCols:v}}return b.length>0?{type:"kpi",metricCols:b}:null}const $t=50;function At(o,u,w,D,b){const _=w.idx,y=D.idx,x=b.map(M=>M.idx),v={};for(const M of o){const L=String(M[y]??"(null)");v[L]=(v[L]||0)+(Number(M[x[0]])||0)}const g=Object.entries(v).sort((M,L)=>L[1]-M[1]).slice(0,$t).map(([M])=>M),F=new Set(g),h=b.map(()=>({}));for(const M of o){const L=String(M[y]??"(null)");if(!F.has(L))continue;const A=M[_],$=String(A??"(null)");for(let U=0;U<b.length;U++){const B=h[U];B[$]||(B[$]={[w.name]:A}),B[$][L]=M[x[U]]}}const W=(M,L)=>{const A=M[w.name],$=L[w.name];return A===null&&$===null?0:A===null?1:$===null?-1:typeof A=="number"&&typeof $=="number"?A-$:String(A).localeCompare(String($))};return{pivotedByMetric:b.map((M,L)=>{const A=Object.values(h[L]);return A.sort(W),{col:M,data:A}}),groupValues:g}}function Tt(o,u,w){const D=u.map(_=>{const y={};return o.forEach((x,v)=>{y[x.name]=_[v]}),y}),b=w.name;return D.sort((_,y)=>{const x=_[b],v=y[b];return x===null&&v===null?0:x===null?1:v===null?-1:typeof x=="number"&&typeof v=="number"?x-v:String(x).localeCompare(String(v))}),D}function Dt(o){return Math.abs(o)>=1e9?(o/1e9).toFixed(1)+"B":Math.abs(o)>=1e6?(o/1e6).toFixed(1)+"M":Math.abs(o)>=1e3?(o/1e3).toFixed(1)+"K":o}function Wt({rows:o,metricCols:u}){const w=o[0]||[];return e.jsx("div",{className:"kpi-cards",children:u.map(D=>{const b=w[D.idx],_=b==null?"—":typeof b=="number"?b.toLocaleString(void 0,{maximumFractionDigits:4}):String(b);return e.jsxs("div",{className:"kpi-card",children:[e.jsx("div",{className:"kpi-label",children:D.name}),e.jsx("div",{className:"kpi-value",children:_}),D.type&&e.jsx("div",{className:"kpi-type",children:D.type})]},D.idx)})})}const Pt={top:8,right:24,left:8,bottom:40},Oe={fontSize:11,fill:"#64748b"},_t={fontSize:12,border:"1px solid #e2e8f0"},zt={zIndex:9999},Ve=a.memo(function({type:u,xCol:w,metricCols:D,seriesKeys:b,chartData:_,seriesColors:y=bt}){const x=_.length<=60,v=b||D.map(F=>F.name),g=u==="line"?"preserveStartEnd":Math.max(0,Math.ceil(_.length/20)-1);return u==="line"?e.jsx(de.ResponsiveContainer,{width:"100%",height:"100%",children:e.jsxs(yt.LineChart,{data:_,margin:Pt,children:[e.jsx(de.CartesianGrid,{strokeDasharray:"3 3",stroke:"#e2e8f0"}),e.jsx(de.XAxis,{dataKey:w.name,tick:Oe,angle:-35,textAnchor:"end",interval:g}),e.jsx(de.YAxis,{tickFormatter:Dt,tick:Oe,width:60}),e.jsx(_e.Tooltip$1,{contentStyle:_t,wrapperStyle:zt}),v.map((F,h)=>e.jsx(yt.Line,{type:"monotone",dataKey:F,stroke:y[h%y.length],dot:x,strokeWidth:2,isAnimationActive:!1},F))]})}):e.jsx(de.ResponsiveContainer,{width:"100%",height:"100%",children:e.jsxs(de.BarChart,{data:_,margin:Pt,children:[e.jsx(de.CartesianGrid,{strokeDasharray:"3 3",stroke:"#e2e8f0"}),e.jsx(de.XAxis,{dataKey:w.name,tick:Oe,angle:-35,textAnchor:"end",interval:g}),e.jsx(de.YAxis,{tickFormatter:Dt,tick:Oe,width:60}),e.jsx(_e.Tooltip$1,{contentStyle:_t}),v.map((F,h)=>e.jsx(de.Bar,{dataKey:F,fill:y[h%y.length],isAnimationActive:!1},F))]})})}),qt=a.memo(function({chartConfig:u,chartData:w,pivotedByMetric:D,groupValues:b,rows:_,columns:y}){if(!u)return e.jsx("div",{className:"chart-no-data",children:"No chartable data detected"});if(u.type==="kpi")return e.jsx(Wt,{rows:_,metricCols:u.metricCols});const{type:x,xCol:v,metricCols:g}=u;return D&&D.length>1?e.jsx("div",{className:"small-multiples",children:D.map(({col:F,data:h})=>e.jsxs("div",{className:"small-multiple",children:[e.jsx("div",{className:"small-multiple-label",children:F.name}),e.jsx("div",{className:"small-multiple-chart",children:e.jsx(Ve,{type:x,xCol:v,metricCols:[F],seriesKeys:b,chartData:h})})]},F.idx))}):b?e.jsx(Ve,{type:x,xCol:v,metricCols:g,seriesKeys:b,chartData:w}):g.length>Et?e.jsx("div",{className:"small-multiples",children:g.map((F,h)=>e.jsxs("div",{className:"small-multiple",children:[e.jsx("div",{className:"small-multiple-label",children:F.name}),e.jsx("div",{className:"small-multiple-chart",children:e.jsx(Ve,{type:x,xCol:v,metricCols:[F],chartData:w,seriesColors:[bt[h%bt.length]]})})]},F.idx))}):e.jsx(Ve,{type:x,xCol:v,metricCols:g,chartData:w})});function Kt({sql:o,results:u,loading:w,error:D,elapsedTime:b,onBackToPlan:_,selectedMetrics:y,selectedDimensions:x,filters:v,dialect:g,cubeName:F,availability:h,links:W}){const[P,M]=a.useState(!1),[L,A]=a.useState(null),[$,U]=a.useState("asc"),[B,le]=a.useState("table"),[C,be]=a.useState(null),T=a.useRef(null),me=a.useCallback(N=>{N.preventDefault();const k=T.current;if(!k)return;const z=N.clientY,H=C??k.offsetHeight*.333,J=Fe=>{const we=Fe.clientY-z,Me=Math.max(80,Math.min(k.offsetHeight*.8,H+we));be(Me)},he=()=>{document.removeEventListener("mousemove",J),document.removeEventListener("mouseup",he)};document.addEventListener("mousemove",J),document.addEventListener("mouseup",he)},[C]),$e=a.useCallback(()=>{o&&(navigator.clipboard.writeText(o),M(!0),setTimeout(()=>M(!1),2e3))},[o]),V=a.useMemo(()=>{var N,k;return((k=(N=u==null?void 0:u.results)==null?void 0:N[0])==null?void 0:k.columns)||[]},[u]),G=a.useMemo(()=>{var N,k;return((k=(N=u==null?void 0:u.results)==null?void 0:N[0])==null?void 0:k.rows)||[]},[u]),ne=G.length,xe=a.useCallback(N=>{L===N?U(k=>k==="asc"?"desc":"asc"):(A(N),U("asc"))},[L]),je=a.useMemo(()=>L===null?G:[...G].sort((N,k)=>{const z=N[L],H=k[L];if(z===null&&H===null)return 0;if(z===null)return 1;if(H===null)return-1;let J;return typeof z=="number"&&typeof H=="number"?J=z-H:J=String(z).localeCompare(String(H)),$==="asc"?J:-J}),[G,L,$]),I=a.useMemo(()=>Rt(V,G),[V,G]),{chartData:Ce,pivotedByMetric:ke,groupValues:Ne}=a.useMemo(()=>{if(!I||!I.xCol)return{chartData:[],pivotedByMetric:null,groupValues:null};if(I.groupByCol){const{pivotedByMetric:N,groupValues:k}=At(G,V,I.xCol,I.groupByCol,I.metricCols);return{chartData:N[0].data,pivotedByMetric:N,groupValues:k}}return{chartData:Tt(V,G,I.xCol),pivotedByMetric:null,groupValues:null}},[V,G,I]),X=ne>0;return a.useEffect(()=>{!X&&B==="chart"&&le("table")},[X,B]),e.jsxs("div",{className:"results-view",children:[e.jsxs("div",{className:"results-header",children:[e.jsxs("button",{className:"back-to-plan-btn",onClick:_,children:[e.jsx("span",{className:"back-arrow",children:"←"}),e.jsx("span",{children:"Back to Plan"})]}),e.jsx("div",{className:"results-summary",children:w?e.jsx("span",{className:"results-loading-text",children:"Running query..."}):D?e.jsx("span",{className:"results-error-text",children:"Query failed"}):e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"results-count",children:[ne.toLocaleString()," rows"]}),b!=null&&e.jsxs("span",{className:"results-time",children:[b.toFixed(2),"s"]})]})})]}),e.jsxs("div",{className:"results-panes",ref:T,children:[e.jsxs("div",{className:"sql-pane",style:C!=null?{flex:`0 0 ${C}px`,maxHeight:C}:void 0,children:[e.jsxs("div",{className:"sql-pane-header",children:[e.jsx("span",{className:"sql-pane-title",children:"SQL Query"}),F&&e.jsxs("span",{className:"sql-pane-info",title:h?`Querying materialized dataset ${[h.catalog,h.schema_,h.table].filter(Boolean).join(".")}, last refreshed for data through ${new Date(h.validThroughTs).toLocaleDateString()}`:void 0,children:[e.jsxs("span",{className:"info-materialized",children:[e.jsx("span",{style:{fontFamily:"sans-serif"},children:"⚡"})," Using materialized cube"]}),(h==null?void 0:h.validThroughTs)&&e.jsxs(e.Fragment,{children:[" · Valid thru ",new Date(h.validThroughTs).toLocaleDateString()]})]}),e.jsx("button",{className:`copy-btn ${P?"copied":""}`,onClick:$e,disabled:!o,children:P?"✓ Copied":"Copy"})]}),e.jsx("div",{className:"sql-pane-content",children:o?e.jsx(_e.SyntaxHighlighter,{language:"sql",style:_e.foundation,wrapLongLines:!0,customStyle:{margin:0,padding:"12px 16px",background:"#f8fafc",fontSize:"12px",height:"100%",overflow:"auto"},children:o}):e.jsx("div",{className:"sql-pane-empty",children:"Generating SQL..."})})]}),e.jsx("div",{className:"horizontal-resizer",onMouseDown:me,title:"Drag to resize"}),e.jsx("div",{className:"results-pane",children:w?e.jsxs("div",{className:"results-loading",children:[e.jsx("div",{className:"loading-spinner large"}),e.jsx("span",{children:"Executing query..."}),e.jsxs("span",{className:"loading-hint",children:["Querying ",y.length," metric(s) with"," ",x.length," dimension(s)"]}),W&&W.length>0&&e.jsx("span",{className:"results-links",children:W.map((N,k)=>e.jsx("a",{href:N,target:"_blank",rel:"noopener noreferrer",className:"results-link",children:"View query ↗"},k))})]}):D?e.jsxs("div",{className:"results-error",children:[e.jsx("div",{className:"error-icon",children:"⚠"}),e.jsx("h3",{children:"Query Failed"}),e.jsx("p",{className:"error-message",children:D}),e.jsx("button",{className:"action-btn action-btn-primary",onClick:_,children:"Back to Plan"})]}):e.jsxs("div",{className:"results-table-section",children:[e.jsxs("div",{className:"results-tabs-bar",children:[e.jsxs("div",{className:"results-tabs",children:[e.jsx("button",{className:`results-tab ${B==="table"?"active":""}`,onClick:()=>le("table"),children:"Table"}),e.jsx("button",{className:`results-tab ${B==="chart"?"active":""} ${X?"":"disabled"}`,onClick:()=>X&&le("chart"),title:X?void 0:"No chartable data (need at least one numeric column)",children:"Chart"})]}),e.jsxs("div",{className:"results-tabs-meta",children:[e.jsxs("span",{className:"table-count",children:[ne.toLocaleString()," rows"]}),v&&v.length>0&&e.jsx("div",{className:"table-filters",children:v.map((N,k)=>e.jsx("span",{className:"filter-chip small",children:N},k))})]})]}),B==="table"?e.jsx("div",{className:"results-table-wrapper",children:ne===0?e.jsx("div",{className:"table-empty",children:e.jsx("p",{children:"No results returned"})}):e.jsxs("table",{className:"results-table",children:[e.jsx("thead",{children:e.jsx("tr",{children:V.map((N,k)=>e.jsxs("th",{title:N.semantic_name||N.name,onClick:()=>xe(k),className:L===k?"sorted":"",children:[e.jsxs("span",{className:"col-header-content",children:[N.name,e.jsxs("span",{className:"sort-arrows",children:[e.jsx("span",{className:`sort-arrow up ${L===k&&$==="asc"?"active":""}`,children:"▲"}),e.jsx("span",{className:`sort-arrow down ${L===k&&$==="desc"?"active":""}`,children:"▼"})]})]}),e.jsx("span",{className:"col-type",children:N.type})]},k))})}),e.jsx("tbody",{children:je.map((N,k)=>e.jsx("tr",{children:N.map((z,H)=>e.jsx("td",{children:z===null?e.jsx("span",{className:"null-value",children:"NULL"}):String(z)},H))},k))})]})}):e.jsx("div",{className:"results-chart-wrapper",children:X?e.jsx(qt,{chartConfig:I,chartData:Ce,pivotedByMetric:ke,groupValues:Ne,rows:G,columns:V}):e.jsx("div",{className:"chart-no-data",children:"No chartable data detected"})})]})})]})]})}const Bt=a.lazy(()=>Promise.resolve().then(()=>require("./MetricFlowGraph-B4VECq74.cjs")));function gt(o){return(o||[]).map(u=>u.split(".").pop()).sort().join(",")}function Ft(){var t,l,m,f,p;const o=a.useContext(_e.DJClientContext).DataJunctionAPI,u=vt.useLocation(),w=vt.useNavigate(),[D,b]=a.useState([]),[_,y]=a.useState([]),[x,v]=a.useState([]),[g,F]=a.useState([]),[h,W]=a.useState([]),[P,M]=a.useState(null),L=a.useRef(!1),A=a.useRef([]),$=a.useRef(null),U=a.useRef([]),[B,le]=a.useState(null),[C,be]=a.useState(null),[T,me]=a.useState(null),[$e,V]=a.useState(!1),[G,ne]=a.useState(!1),[xe,je]=a.useState(null),[I,Ce]=a.useState(!1),[ke,Ne]=a.useState(null),[X,N]=a.useState(!1),[k,z]=a.useState(null),[H,J]=a.useState(null),[he,Fe]=a.useState(null),[we,Me]=a.useState([]),[Z,Le]=a.useState([]),[pe,Ae]=a.useState(null),[Te,Se]=a.useState(null),[R,oe]=a.useState(null),[ie,De]=a.useState(null),[fe,ve]=a.useState(null),Ee=a.useRef(null),Pe=a.useCallback(r=>{r.preventDefault();const s=Ee.current;if(!s)return;const n=r.clientX,i=ie??s.offsetWidth*.2,c=E=>{const q=E.clientX-n,S=Math.max(200,Math.min(s.offsetWidth*.5,i+q));De(S)},d=()=>{document.removeEventListener("mousemove",c),document.removeEventListener("mouseup",d)};document.addEventListener("mousemove",c),document.addEventListener("mouseup",d)},[ie]),Ge=a.useCallback(r=>{r.preventDefault();const s=Ee.current;if(!s)return;const n=r.clientX,i=fe??s.offsetWidth*.4,c=E=>{const q=n-E.clientX,S=Math.max(280,Math.min(s.offsetWidth*.7,i+q));ve(S)},d=()=>{document.removeEventListener("mousemove",c),document.removeEventListener("mouseup",d)};document.addEventListener("mousemove",c),document.addEventListener("mouseup",d)},[fe]),[ye,ge]=a.useState({}),[Re,j]=a.useState(null),[He,Q]=a.useState([]),[ce,K]=a.useState(null);a.useEffect(()=>{var d,E;const r=new URLSearchParams(u.search),s=((d=r.get("metrics"))==null?void 0:d.split(",").filter(Boolean))||[],n=((E=r.get("dimensions"))==null?void 0:E.split(",").filter(Boolean))||[],i=r.getAll("filters"),c=r.get("cube");i.length>0&&Le(i),s.length>0?(F(s),n.length>0&&(A.current=n),c&&($.current=c),L.current=!0):c&&($.current=c,L.current=!0)},[]),a.useEffect(()=>{if(!L.current&&g.length===0&&!P)return;const r=new URLSearchParams;P?r.set("cube",P):(g.length>0&&r.set("metrics",g.join(",")),h.length>0&&r.set("dimensions",h.join(",")),Z.forEach(i=>r.append("filters",i)));const s=r.toString(),n=u.search.replace(/^\?/,"");s!==n&&w({pathname:u.pathname,search:s?`?${s}`:""},{replace:!0})},[g,h,Z,P,u.pathname,w]),a.useEffect(()=>{(async()=>{const[s,n]=await Promise.all([o.metrics(),o.listCubesForPreset().catch(()=>[])]);if(b(s),v(n),$.current){const i=$.current;$.current=null;try{const c=await o.cubeForPlanner(i);if(c&&Array.isArray(c.cube_node_metrics)){const d=c.cube_node_metrics||[],E=c.cube_node_dimensions||[],q=c.cube_dimension_objects||[];M(i),F(d),U.current=q,y(q),W(E);const S=c.cubeMaterialization;K(S||null),Q((S==null?void 0:S.workflowUrls)||[])}else console.error("Invalid cube data from URL:",c)}catch(c){console.error("Failed to load cube from URL:",c)}}})().catch(console.error)},[o]),a.useEffect(()=>{(async()=>{if(g.length>0){const s=U.current;s.length===0&&ne(!0);try{const n=await o.commonDimensions(g);if(!Array.isArray(n)){console.error("commonDimensions returned non-array:",n),y(s);return}const i=new Set(n.map(d=>d.name)),c=[...n,...s.filter(d=>!i.has(d.name))];if(y(c),A.current.length>0){const d=c.map(q=>q.name),E=A.current.filter(q=>d.includes(q));E.length>0&&W(E),A.current=[]}}catch(n){console.error("Failed to fetch dimensions:",n),y(s)}ne(!1)}else y([]),W([])})().catch(console.error)},[g,o]),a.useEffect(()=>{const r=_.map(n=>n.name),s=h.filter(n=>r.includes(n));s.length!==h.length&&W(s)},[_,h]),a.useEffect(()=>{if(h.length===0){le(null);return}let r=!1;return o.commonMetrics(h).then(s=>{if(!r)if(Array.isArray(s)){const n=s.map(i=>typeof i=="string"?i:i.name);le(new Set(n))}else le(null)}).catch(()=>{r||le(null)}),()=>{r=!0}},[h,o]),a.useEffect(()=>{(async()=>{if(g.length>0){V(!0),je(null),oe(null);try{const s=pe!=="trino",n=pe||null,[i,c]=await Promise.all([o.measuresV3(g,h),o.metricsV3(g,h,Z,s,n)]);be(i),me(c)}catch(s){je(s.message||"Failed to fetch data"),be(null),me(null)}V(!1)}else be(null),me(null)})().catch(console.error)},[o,g,h,Z,pe]),a.useEffect(()=>{(async()=>{var s;if(!((s=C==null?void 0:C.grain_groups)!=null&&s.length)){ge({});return}try{const n={},c=(C.requested_dimensions||[]).join(",");console.log("grainCols for pre-agg lookup (from requested_dimensions):",c),await Promise.all(C.grain_groups.map(async d=>{const E=`${d.parent_name}|${gt(d.grain)}`,q=(d.components||[]).map(O=>O.name).filter(Boolean).join(",");console.log(`Looking for pre-agg: node=${d.parent_name}, grain=${c}, measures=${q}`);let S=await o.listPreaggs({node_name:d.parent_name,grain:c,grain_mode:"exact",measures:q||void 0});console.log(`Exact match result for ${d.parent_name}:`,S);let ae=S.items||S.pre_aggregations||[],te=ae[0];te||(S=await o.listPreaggs({node_name:d.parent_name,grain:c,grain_mode:"superset",measures:q||void 0}),console.log(`Superset match result for ${d.parent_name}:`,S),ae=S.items||S.pre_aggregations||[],te=ae[0],te&&(te={...te,_isCompatible:!0})),te?(console.log(`Found pre-agg match for ${d.parent_name}:`,te),n[E]=te):console.log(`No pre-agg match found for ${d.parent_name}`)})),ge(n)}catch(n){console.error("Failed to fetch existing pre-aggs:",n)}})()},[C,o]),a.useEffect(()=>{(async()=>{const s=P||(T==null?void 0:T.cube_name);if(!s){Se(null),K(null),Q([]);return}try{const n=await o.cubeForPlanner(s);if(Se((n==null?void 0:n.availability)||null),n){const i=n.cubeMaterialization;K(i||null),Q((i==null?void 0:i.workflowUrls)||[])}else K(null),Q([])}catch(n){console.error("Failed to fetch cube info:",n),Se(null),K(null),Q([])}})()},[T==null?void 0:T.cube_name,P,o]);const ee=a.useCallback(()=>{M(null),U.current=[]},[]),Qe=a.useCallback(r=>{F(r),oe(null),ee()},[ee]),Ye=a.useCallback(async r=>{if(r)try{const s=await o.cubeForPlanner(r);if(s&&Array.isArray(s.cube_node_metrics)){const n=s.cube_node_metrics||[],i=s.cube_node_dimensions||[],c=s.cube_dimension_objects||[];M(r),F(n),U.current=c,y(c),W(i),Le([]),oe(null),Se(s.availability||null);const d=s.cubeMaterialization;K(d||null),Q((d==null?void 0:d.workflowUrls)||[])}else console.error("Invalid cube data received:",s)}catch(s){console.error("Failed to load cube preset:",s)}},[o]),Xe=a.useCallback(()=>{F([]),W([]),Le([]),Q([]),K(null),ee()},[ee]),Je=a.useCallback(r=>{W(r),oe(null),ee()},[ee]),We=a.useCallback(r=>{oe(r)},[]),Ke=a.useCallback(()=>{oe(null)},[]),Ze=a.useCallback(async(r,s)=>{var n,i,c,d,E,q;j(null);try{const S=await o.planPreaggs(g,h,s.strategy,s.schedule,s.lookbackWindow);if(S._error||S.message||S.detail){const O=S.message||S.detail||"Failed to plan pre-aggregations";throw j(O),new Error(O)}const ae=S.preaggs||S.items||S.pre_aggregations||[],te={...ye};if(ae.forEach(O=>{const re=`${O.node_name}|${gt(O.grain_columns)}`;te[re]=O}),ge(te),ae.length>0&&s.schedule){const O=[],re=[];for(const se of ae)O.push(o.materializePreagg(se.id).catch(ze=>(console.error(`Failed to create workflow for preagg ${se.id}:`,ze),null)));const Y=await Promise.all(O);for(const se of ae)s.runBackfill&&s.backfillFrom&&s.backfillTo&&re.push(o.runPreaggBackfill(se.id,s.backfillFrom,s.backfillTo).catch(ze=>(console.error(`Failed to run backfill for preagg ${se.id}:`,ze),null)));const ue=await Promise.all(re),ht={...te};ae.forEach((se,ze)=>{var wt;const jt=`${se.node_name}|${gt(se.grain_columns)}`,qe=Y[ze];((wt=qe==null?void 0:qe.workflow_urls)==null?void 0:wt.length)>0&&(ht[jt]={...ht[jt],workflow_urls:qe.workflow_urls,workflow_status:qe.workflow_status||"active"})}),ge(ht);const xt=ue.filter(se=>se==null?void 0:se.job_url);xt.length>0&&console.log("Backfills started:",xt)}if(console.log("Scheduling Druid cube materialization for:",s.enableDruidCube),s.enableDruidCube){const O=P||s.druidCubeName;if(!O){const Y="Cube name is required for Druid materialization";throw j(Y),new Error(Y)}if(console.log("Scheduling Druid cube materialization for:",O),!P&&s.druidCubeName){const Y=await o.createCube(s.druidCubeName,s.druidCubeName.split(".").pop(),`Druid cube for ${g.join(", ")}`,"published",g,h,[]);if(Y.status>=400){const ue=((n=Y.json)==null?void 0:n.message)||((i=Y.json)==null?void 0:i.detail)||"Failed to create cube";if(!ue.toLowerCase().includes("already exists"))return j(`Failed to create cube: ${ue}`),S;console.log("Cube already exists, proceeding with materialization")}M(s.druidCubeName)}const re=await o.materializeCubeV2(O,s.schedule||"0 6 * * *",s.strategy,s.lookbackWindow,s.runBackfill??!0);if(re.status>=400){const Y=((c=re.json)==null?void 0:c.message)||((d=re.json)==null?void 0:d.detail)||"Failed to schedule cube materialization";console.error("Cube materialization failed:",Y),j(`Pre-aggs created but cube materialization failed: ${Y}`)}else{console.log("Cube materialization scheduled:",re.json),console.log("Workflow URLs from response:",(E=re.json)==null?void 0:E.workflow_urls);const Y=((q=re.json)==null?void 0:q.workflow_urls)||[];if(console.log("Setting workflowUrls to:",Y),Q(Y),s.runBackfill&&s.backfillFrom&&s.backfillTo){console.log("Running cube backfill from",s.backfillFrom,"to",s.backfillTo);try{const ue=await o.runCubeBackfill(O,s.backfillFrom,s.backfillTo);ue._error?console.error("Cube backfill failed:",ue.message):console.log("Cube backfill started:",ue.job_url)}catch(ue){console.error("Failed to run cube backfill:",ue)}}}}return S}catch(S){console.error("Failed to plan materialization:",S);const ae=S.message||"Failed to plan materialization";throw j(ae),S}},[o,g,h,ye,P]),et=a.useCallback(async(r,s)=>{j(null);try{const n=await o.updatePreaggConfig(r,s.strategy,s.schedule,s.lookbackWindow);if(n._error||n.message||n.detail){const i=n.message||n.detail||"Failed to update config";throw j(i),new Error(i)}return ge(i=>{const c={...i};for(const d in c)if(c[d].id===r){c[d]={...c[d],...n};break}return c}),n}catch(n){console.error("Failed to update config:",n);const i=n.message||"Failed to update config";throw j(i),n}},[o]),tt=a.useCallback(async r=>{j(null);try{const s=await o.materializePreagg(r);if(s._error||s.message||s.detail){const n=s.message||s.detail||"Failed to create workflow";return j(n),null}return ge(n=>{const i={...n};for(const c in i)if(i[c].id===r){i[c]={...i[c],workflow_urls:s.workflow_urls,workflow_status:s.workflow_status||"active"};break}return i}),s}catch(s){return console.error("Failed to create workflow:",s),j(s.message||"Failed to create workflow"),null}},[o]),st=a.useCallback(async(r,s,n)=>{j(null);try{const i=await o.runPreaggBackfill(r,s,n);if(i._error||i.message||i.detail){const c=i.message||i.detail||"Failed to run backfill";return j(c),null}return i}catch(i){return console.error("Failed to run backfill:",i),j(i.message||"Failed to run backfill"),null}},[o]),nt=a.useCallback(async(r,s)=>{j(null);try{const n=await o.runPreaggBackfill(r,s,s);if(n._error||n.message||n.detail){const i=n.message||n.detail||"Failed to run ad-hoc job";return j(i),null}return n}catch(n){return console.error("Failed to run ad-hoc job:",n),j(n.message||"Failed to run ad-hoc job"),null}},[o]),at=a.useCallback(async r=>{var s;j(null);try{const n=await o.deactivatePreaggWorkflow(r);if(n._error||(s=n.message)!=null&&s.includes("Failed")){const i=n.message||n.detail||"Failed to deactivate workflow";return j(i),null}return ge(i=>{const c={...i};for(const d in c)if(c[d].id===r){c[d]={...c[d],strategy:null,schedule:null,lookback_window:null,workflow_status:null,workflow_urls:null};break}return c}),n}catch(n){return console.error("Failed to deactivate workflow:",n),j(n.message||"Failed to deactivate workflow"),null}},[o]),rt=a.useCallback(async()=>{var r,s;if(!P)return j("No cube loaded"),null;j(null);try{const n=await o.deactivateCubeWorkflow(P);if(n.status>=400){const i=((r=n.json)==null?void 0:r.message)||((s=n.json)==null?void 0:s.detail)||"Failed to deactivate cube workflow";return j(i),null}return Q([]),K(null),n.json}catch(n){return console.error("Failed to deactivate cube workflow:",n),j(n.message||"Failed to deactivate cube workflow"),null}},[o,P]),Be=a.useCallback(async r=>{var s,n,i;if(!P)return j("No cube loaded"),null;j(null);try{const c=await o.refreshCubeWorkflow(P,r.schedule,r.strategy,r.lookbackWindow);if(c.status>=400){const E=((s=c.json)==null?void 0:s.message)||((n=c.json)==null?void 0:n.detail)||"Failed to update cube config";return j(E),null}const d=((i=c.json)==null?void 0:i.workflow_urls)||[];return Q(d),K(E=>({...E,schedule:r.schedule,strategy:r.strategy,lookbackWindow:r.lookbackWindow,workflowUrls:d})),c.json}catch(c){return console.error("Failed to update cube config:",c),j(c.message||"Failed to update cube config"),null}},[o,P]),lt=a.useCallback(async()=>{var r,s,n;if(!P||!ce)return j("No cube materialization to refresh"),null;j(null);try{const i=await o.refreshCubeWorkflow(P,ce.schedule,ce.strategy,ce.lookbackWindow);if(i.status>=400){const d=((r=i.json)==null?void 0:r.message)||((s=i.json)==null?void 0:s.detail)||"Failed to refresh cube workflow";return j(d),null}const c=((n=i.json)==null?void 0:n.workflow_urls)||[];return Q(c),K(d=>({...d,workflowUrls:c})),i.json}catch(i){return console.error("Failed to refresh cube workflow:",i),j(i.message||"Failed to refresh cube workflow"),null}},[o,P,ce]),ot=a.useCallback(async(r,s)=>{if(!P)return j("No cube to backfill"),null;if(!r)return j("Start date is required"),null;j(null);try{const n=await o.runCubeBackfill(P,r,s);return n._error?(j(n.message||"Failed to run cube backfill"),null):n}catch(n){return console.error("Failed to run cube backfill:",n),j(n.message||"Failed to run cube backfill"),null}},[o,P]),it=a.useCallback(async()=>{try{return await o.metricsV3(g,h,"",!1)}catch(r){return console.error("Failed to fetch raw SQL:",r),null}},[o,g,h]),Ue=a.useCallback(async(r,s,n,i,c)=>{try{return await o.setPartition(r,s,n,i,c)}catch(d){throw console.error("Failed to set partition:",d),d}},[o]),ct=a.useCallback(async()=>{if(g.length>0)try{const[r,s]=await Promise.all([o.measuresV3(g,h),o.metricsV3(g,h)]);be(r),me(s)}catch(r){console.error("Failed to refresh measures:",r)}},[o,g,h]),Ie=a.useCallback(async r=>await o.getNodeColumnsWithPartitions(r),[o]),ut=a.useCallback(async()=>{if(g.length===0){z("Select at least one metric");return}N(!0),z(null),Ne(null),Me([]),Ce(!0);const r=Date.now();J(r),Fe(null);try{const s=await o.data(g,h,Z,pe||null,i=>Me(i.links||[])),n=(Date.now()-r)/1e3;Fe(n),Ne(s)}catch(s){console.error("Query failed:",s),z(s.message||"Failed to execute query")}finally{N(!1)}},[o,g,h,Z,pe]),dt=a.useCallback(()=>{Ce(!1),Ne(null),z(null)},[]),mt=a.useCallback(r=>{Le(r),ee()},[ee]);return e.jsxs("div",{className:"planner-page",children:[xe&&e.jsx("div",{className:"header-error planner-error-banner",children:xe}),e.jsxs("div",{className:"planner-layout",ref:Ee,children:[e.jsx("aside",{className:"planner-selection",style:ie!=null?{width:ie}:void 0,children:e.jsx(Lt,{metrics:D,selectedMetrics:g,onMetricsChange:Qe,dimensions:_,selectedDimensions:h,onDimensionsChange:Je,loading:G,cubes:x,onLoadCubePreset:Ye,loadedCubeName:P,onClearSelection:Xe,filters:Z,onFiltersChange:mt,selectedEngine:pe,onEngineChange:Ae,onRunQuery:ut,canRunQuery:g.length>0,queryLoading:X,compatibleMetrics:B})}),e.jsx("div",{className:"vertical-resizer",onMouseDown:Pe,title:"Drag to resize"}),I?e.jsx(Kt,{sql:T==null?void 0:T.sql,results:ke,loading:X,error:k,elapsedTime:he,onBackToPlan:dt,selectedMetrics:g,selectedDimensions:h,filters:Z,dialect:T==null?void 0:T.dialect,cubeName:T==null?void 0:T.cube_name,availability:Te,links:we}):e.jsxs(e.Fragment,{children:[e.jsx("main",{className:"planner-graph",children:$e?e.jsxs("div",{className:"graph-loading",children:[e.jsx("div",{className:"loading-spinner"}),e.jsx("span",{children:"Building data flow..."})]}):C?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"graph-header",children:e.jsxs("span",{className:"graph-stats",children:[((t=C.grain_groups)==null?void 0:t.length)||0," ","pre-aggregations →"," ",((l=C.metric_formulas)==null?void 0:l.length)||0," metrics"]})}),e.jsx(a.Suspense,{fallback:e.jsxs("div",{className:"graph-loading",children:[e.jsx("div",{className:"loading-spinner"}),e.jsx("span",{children:"Loading graph..."})]}),children:e.jsx(Bt,{grainGroups:C.grain_groups,metricFormulas:C.metric_formulas,selectedNode:R,onNodeSelect:We})})]}):e.jsxs("div",{className:"graph-empty",children:[e.jsx("div",{className:"empty-icon",children:"⊞"}),e.jsx("h3",{children:"Select Metrics & Dimensions"}),e.jsx("p",{children:"Choose metrics from the left panel, then select dimensions to see how they decompose into pre-aggregations."})]})}),e.jsx("div",{className:"vertical-resizer",onMouseDown:Ge,title:"Drag to resize"}),e.jsx("aside",{className:"planner-details",style:fe!=null?{width:fe}:void 0,children:(R==null?void 0:R.type)==="preagg"||(R==null?void 0:R.type)==="component"?e.jsx(pt.PreAggDetailsPanel,{preAgg:(R==null?void 0:R.type)==="component"?(f=C==null?void 0:C.grain_groups)==null?void 0:f[(m=R.data)==null?void 0:m.grainGroupIndex]:R.data,metricFormulas:C==null?void 0:C.metric_formulas,onClose:Ke,highlightedComponent:(R==null?void 0:R.type)==="component"?(p=R.data)==null?void 0:p.name:null}):(R==null?void 0:R.type)==="metric"?e.jsx(pt.MetricDetailsPanel,{metric:R.data,grainGroups:C==null?void 0:C.grain_groups,onClose:Ke}):e.jsx(pt.QueryOverviewPanel,{measuresResult:C,metricsResult:T,selectedMetrics:g,selectedDimensions:h,plannedPreaggs:ye,onPlanMaterialization:Ze,onUpdateConfig:et,onCreateWorkflow:tt,onRunBackfill:st,onRunAdhoc:nt,onFetchRawSql:it,onSetPartition:Ue,onRefreshMeasures:ct,onFetchNodePartitions:Ie,materializationError:Re,onClearError:()=>j(null),workflowUrls:He,onClearWorkflowUrls:()=>Q([]),loadedCubeName:P,cubeMaterialization:ce,cubeAvailability:Te,onUpdateCubeConfig:Be,onRefreshCubeWorkflow:lt,onRunCubeBackfill:ot,onDeactivatePreaggWorkflow:at,onDeactivateCubeWorkflow:rt})})]})]})]})}exports.QueryPlannerPage=Ft;exports.default=Ft; //# sourceMappingURL=index-CfXXlICc.cjs.map