@objectstack/console 7.0.0 → 7.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/dist/assets/{AiPendingActionsPage-DLWrcsds.js → AiPendingActionsPage-DfPQB-bV.js} +1 -1
  2. package/dist/assets/{ApiConsolePage-BIBykAYj.js → ApiConsolePage-CVt86JW9.js} +1 -1
  3. package/dist/assets/{AppManagementPage-BKE0rv8B.js → AppManagementPage-DuIaI8a2.js} +1 -1
  4. package/dist/assets/ApprovalsInboxPage-BRv2RqN4.js +1 -0
  5. package/dist/assets/{AuditLogPage-Bqlhi2ko.js → AuditLogPage-CDXmY4Lg.js} +1 -1
  6. package/dist/assets/{ComponentNavView-DBMxrUvH.js → ComponentNavView-B2VAx_8W.js} +1 -1
  7. package/dist/assets/{ConsoleFloatingChatbot-CBIXkoNS.js → ConsoleFloatingChatbot-c1A9X4w7.js} +1 -1
  8. package/dist/assets/{DeveloperHubPage-C3Ooh2Gg.js → DeveloperHubPage-E4ydudW4.js} +1 -1
  9. package/dist/assets/{FlowRunsPage-NjEPPv_e.js → FlowRunsPage-CF-nkx9E.js} +1 -1
  10. package/dist/assets/ProfilePage-4wnWye8l.js +1 -0
  11. package/dist/assets/PublicFormsPage-B1cdfwoQ.js +1 -0
  12. package/dist/assets/{SettingsHub-BTNCNbjZ.js → SettingsHub-B4d9Pn8t.js} +1 -1
  13. package/dist/assets/{SettingsView-BLXf7B7b.js → SettingsView-cRQBVn6H.js} +1 -1
  14. package/dist/assets/{SystemHubPage-CgN-8VKO.js → SystemHubPage-DIKmhwy1.js} +1 -1
  15. package/dist/assets/{data-adapter-Dn6-L_yI.js → data-adapter-Be-s1kWX.js} +1 -1
  16. package/dist/assets/{highlighted-body-OFNGDK62-Dua_6VJ2.js → highlighted-body-OFNGDK62-Dynkkk0t.js} +1 -1
  17. package/dist/assets/index-D7iz-IIn.js +24 -0
  18. package/dist/assets/index-Db8Nmh4R.css +2 -0
  19. package/dist/assets/mermaid-GHXKKRXX-DJsGdxYj.js +1 -0
  20. package/dist/assets/plugin-calendar-wl24Whh9.js +1 -0
  21. package/dist/assets/{plugin-charts-C11LxM1X.js → plugin-charts-Mt2y8Sdm.js} +1 -1
  22. package/dist/assets/{plugin-chatbot-COnH_NZC.js → plugin-chatbot-DXGXTdLU.js} +29 -29
  23. package/dist/assets/plugin-dashboard-DqF5vvlQ.js +3 -0
  24. package/dist/assets/{plugin-form-f39dp3V2.js → plugin-form-BBc-xwrZ.js} +1 -1
  25. package/dist/assets/plugin-gantt-scBgVq2Q.js +1 -0
  26. package/dist/assets/plugin-grid-u5JmW5Ui.js +6 -0
  27. package/dist/assets/{plugin-kanban-q2UT5MlD.js → plugin-kanban-0qj1Kr3T.js} +1 -1
  28. package/dist/assets/{plugin-map-C6vgk2bJ.js → plugin-map-CjA33cHV.js} +1 -1
  29. package/dist/assets/{plugin-markdown-DPzm2nVd.js → plugin-markdown-BPsaoDf-.js} +1 -1
  30. package/dist/assets/plugin-report-C35V4A8F.js +59 -0
  31. package/dist/assets/{plugin-timeline-lCaTr_4i.js → plugin-timeline-Bmy8v-AN.js} +1 -1
  32. package/dist/assets/plugin-view-tV_8MnpT.js +1 -0
  33. package/dist/assets/plugins-views-DM6-O61C.js +4 -0
  34. package/dist/assets/{src-Con14F4e.js → src-BJJhwsID.js} +1 -1
  35. package/dist/assets/{types-CuyLcCWX.js → types-BsFD2pPK.js} +1 -1
  36. package/dist/assets/{ui-components-ZN8XdmwJ.js → ui-components-DYQ4Pai7.js} +7 -7
  37. package/dist/assets/{ui-layout-HiDSueut.js → ui-layout-Dmw4Ab7P.js} +1 -1
  38. package/dist/index.html +3 -3
  39. package/package.json +1 -1
  40. package/dist/assets/ApprovalsInboxPage-D7gF2CM8.js +0 -1
  41. package/dist/assets/ObjectManagerListPage-DEPokJwV.js +0 -1
  42. package/dist/assets/ProfilePage-zYSeu2-d.js +0 -1
  43. package/dist/assets/PublicFormsPage-BrLPiHf1.js +0 -1
  44. package/dist/assets/index-Ca4KaljM.js +0 -23
  45. package/dist/assets/index-DsQwZDFr.css +0 -2
  46. package/dist/assets/mermaid-GHXKKRXX-BvEKnLTo.js +0 -1
  47. package/dist/assets/plugin-calendar-Dnr7itgk.js +0 -1
  48. package/dist/assets/plugin-dashboard-DvBectcr.js +0 -3
  49. package/dist/assets/plugin-gantt-7ui7uiVc.js +0 -1
  50. package/dist/assets/plugin-grid-DtceFt_J.js +0 -6
  51. package/dist/assets/plugin-report-BJM4LH87.js +0 -59
  52. package/dist/assets/plugin-view-b7gS6gIn.js +0 -1
  53. package/dist/assets/plugins-views-Dvl7pQvR.js +0 -4
@@ -1,6 +0,0 @@
1
- import{o as e,r as t}from"./rolldown-runtime-CMxvf4Kt.js";import{g as n,h as r,r as i}from"./vendor-react-CIpZOxG3.js";import{E as a,H as o,L as s,M as c,V as l,Z as u,at as d,it as f,r as p,ut as m}from"./framework-ClI3DbWX.js";import{$t as h,A as g,Ar as _,B as v,Bn as ee,Br as y,Bt as b,D as te,E as x,Er as S,Fn as C,Ga as w,Go as ne,Ht as T,In as re,Jr as ie,Ln as E,N as ae,Nr as D,Or as O,Q as k,Qn as A,Qt as oe,Ra as se,Rn as ce,Rr as le,Rt as j,S as ue,Ta as de,To as fe,Uo as pe,Ut as me,Vt as he,Xr as ge,Xt as _e,Y as ve,Zo as M,Zt as ye,_o as N,a as P,an as F,at as I,br as be,c as xe,cn as L,ct as R,en as z,es as Se,f as Ce,fi as we,hi as Te,ho as Ee,i as De,in as Oe,it as ke,jr as Ae,l as je,lt as Me,m as Ne,mi as Pe,mn as Fe,mr as B,na as Ie,on as V,ot as Le,pi as Re,po as ze,q as Be,qa as Ve,r as He,ro as Ue,rt as We,s as Ge,so as Ke,st as qe,yo as Je,zn as Ye,zt as Xe}from"./ui-components-ZN8XdmwJ.js";var H=e(n(),1),U={xs:0,sm:640,md:768,lg:1024,xl:1280,"2xl":1536},W=[`xs`,`sm`,`md`,`lg`,`xl`,`2xl`];function G(e){for(let t=W.length-1;t>=0;t--){let n=W[t];if(e>=U[n])return n}return`xs`}function K(){let[e,t]=(0,H.useState)(()=>typeof window<`u`?window.innerWidth:1024);(0,H.useEffect)(()=>{if(typeof window>`u`)return;let e,n=()=>{clearTimeout(e),e=setTimeout(()=>{t(window.innerWidth)},100)};return window.addEventListener(`resize`,n),()=>{clearTimeout(e),window.removeEventListener(`resize`,n)}},[]);let n=G(e),r=W.indexOf(n);return{breakpoint:n,width:e,isMobile:r<W.indexOf(`md`),isTablet:r>=W.indexOf(`md`)&&r<W.indexOf(`lg`),isDesktop:r>=W.indexOf(`lg`),isAbove:t=>e>=U[t],isBelow:t=>e<U[t]}}function Ze(e){let{onRefresh:t,threshold:n=80,enabled:r=!0}=e,i=(0,H.useRef)(null),[a,o]=(0,H.useState)(!1),[s,c]=(0,H.useState)(0),l=(0,H.useRef)(0),u=(0,H.useCallback)(e=>{if(!r||a)return;let t=i.current;t&&t.scrollTop===0&&(l.current=e.touches[0].clientY)},[r,a]),d=(0,H.useCallback)(e=>{if(!r||a||!l.current)return;let t=e.touches[0].clientY-l.current;t>0&&c(Math.min(t,n*1.5))},[r,a,n]),f=(0,H.useCallback)(async()=>{if(!r||a)return;let e=s;if(c(0),l.current=0,e>=n){o(!0);try{await t()}finally{o(!1)}}},[r,a,s,n,t]);return(0,H.useEffect)(()=>{let e=i.current;if(!(!e||!r))return e.addEventListener(`touchstart`,u,{passive:!0}),e.addEventListener(`touchmove`,d,{passive:!0}),e.addEventListener(`touchend`,f,{passive:!0}),()=>{e.removeEventListener(`touchstart`,u),e.removeEventListener(`touchmove`,d),e.removeEventListener(`touchend`,f)}},[u,d,f,r]),{ref:i,isRefreshing:a,pullDistance:s}}var q=i(),J=(0,H.createContext)(null);J.displayName=`MobileContext`;function Qe({pwa:e,offline:t,children:n}){let r=K(),i=(0,H.useMemo)(()=>({...r,pwa:e,offline:t}),[r,e,t]);return(0,q.jsx)(J.Provider,{value:i,children:n})}var Y={red:`bg-red-100`,green:`bg-green-100`,blue:`bg-blue-100`,yellow:`bg-yellow-100`,orange:`bg-orange-100`,purple:`bg-purple-100`,pink:`bg-pink-100`,gray:`bg-gray-100`,grey:`bg-gray-100`,indigo:`bg-indigo-100`,teal:`bg-teal-100`,cyan:`bg-cyan-100`,amber:`bg-amber-100`,lime:`bg-lime-100`,emerald:`bg-emerald-100`,rose:`bg-rose-100`,sky:`bg-sky-100`,violet:`bg-violet-100`,fuchsia:`bg-fuchsia-100`,slate:`bg-slate-100`,zinc:`bg-zinc-100`,stone:`bg-stone-100`,neutral:`bg-neutral-100`};function $e(e){return e.startsWith(`bg-`)?e:Y[e.toLowerCase().trim()]}function et(e){return(0,H.useCallback)(t=>{if(!e?.field||!e.colors)return;let n=String(t[e.field]??``),r=e.colors[n];if(r)return $e(r)},[e?.field,e?.colors])}function tt(e){if(e==null||e===``)return``;if(Array.isArray(e))return e.map(e=>tt(e)).join(`|`);if(typeof e==`object`){let t=e.id??e._id??e.pk??e.value;if(t!=null&&t!==``)return String(t);let n=e.name??e.label??e.title;if(n!=null&&n!==``)return String(n);try{return JSON.stringify(e)}catch{return``}}return String(e)}function X(e,t){return tt(e[t])}function nt(e,t,n){if(e==null||e===``)return`(empty)`;if(n){let r=n(t,e);if(r!==void 0&&r!==``)return r}if(Array.isArray(e))return e.map(e=>{if(n){let r=n(t,e);if(r!==void 0&&r!==``)return r}return nt(e,t)}).join(`, `)||`(empty)`;if(typeof e==`object`){let t=e.name??e.label??e.title??e.display_name??e.displayName??e.fullName??e.full_name;if(t!=null&&t!==``)return String(t);let n=e.id??e._id??e.pk;return n!=null&&n!==``?String(n):`(empty)`}return String(e)}function rt(e,t){return t.map(({field:t,type:n})=>{if(n===`count_distinct`){let r=new Set;for(let n of e){let e=n[t];e!=null&&e!==``&&r.add(e)}return{field:t,type:n,value:r.size}}if(n===`count`)return{field:t,type:n,value:e.length};let r=e.map(e=>Number(e[t])).filter(e=>Number.isFinite(e)),i;switch(n){case`sum`:i=r.reduce((e,t)=>e+t,0);break;case`avg`:i=r.length>0?r.reduce((e,t)=>e+t,0)/r.length:0;break;case`min`:i=r.length>0?Math.min(...r):0;break;case`max`:i=r.length>0?Math.max(...r):0;break;default:i=0}return{field:t,type:n,value:i}})}function it(e,t,n){let r=e.localeCompare(t,void 0,{numeric:!0,sensitivity:`base`});return n===`desc`?-r:r}function at(e,t,n,r){let i=e?.fields,a=!!(i&&i.length>0),[o,s]=(0,H.useState)({});return{groups:(0,H.useMemo)(()=>{if(!a||!i)return[];let e=(t,a,s)=>{if(a>=i.length)return[];let c=i[a],l=new Map,u=[];for(let e of t){let t=X(e,c.field);l.has(t)||(l.set(t,{label:nt(e[c.field],c.field,r),rows:[]}),u.push(t)),l.get(t).rows.push(e)}let d=c.order??`asc`;return u.sort((e,t)=>it(l.get(e)?.label??e,l.get(t)?.label??t,d)),u.map(t=>{let r=l.get(t),u=s?`${s}__${a}:${t}`:`${a}:${t}`,d=!!c.collapsed,f=u in o?o[u]:d,p=n&&n.length>0?rt(r.rows,n):[],m=a+1<i.length?e(r.rows,a+1,u):[];return{key:u,label:r.label,field:c.field,depth:a,rows:r.rows,collapsed:f,aggregations:p,subgroups:m}})};return e(t,0,``)},[t,i,a,o,n,r]),isGrouped:a,toggleGroup:(0,H.useCallback)(e=>{s(t=>{let n=e.split(`__`).pop()||``,r=/^(\d+):/.exec(n),a=r?Number(r[1]):0,o=!!i?.[a]?.collapsed;return{...t,[e]:t[e]===void 0?!o:!t[e]}})},[i])}}var ot=({groupKey:e,label:t,count:n,collapsed:r,aggregations:i,fieldLabel:a,labelColorClass:o,onToggle:s,children:c})=>{let l=o?M(`inline-flex items-center rounded-md border px-2 py-0.5 text-xs font-medium`,o):`inline-flex items-center rounded-md bg-muted px-2 py-0.5 text-xs font-medium text-foreground`;return(0,q.jsxs)(`div`,{"data-testid":`group-row-${e}`,className:`group/grouprow`,children:[a&&(0,q.jsx)(`div`,{className:`px-1 pb-1 text-[11px] font-medium text-muted-foreground tracking-wide group-label-caption`,children:a}),(0,q.jsxs)(`button`,{type:`button`,className:`flex w-full items-center gap-2 px-1 py-1 text-sm text-left rounded-md hover:bg-muted/40 transition-colors`,onClick:()=>s(e),"aria-expanded":!r,children:[r?(0,q.jsx)(N,{className:`h-3.5 w-3.5 shrink-0 text-muted-foreground`}):(0,q.jsx)(Je,{className:`h-3.5 w-3.5 shrink-0 text-muted-foreground`}),(0,q.jsx)(`span`,{className:M(l,`group-label`),children:t}),(0,q.jsx)(`span`,{className:`text-xs text-muted-foreground tabular-nums group-count`,children:n}),i&&i.length>0&&(0,q.jsx)(`span`,{className:`ml-2 text-xs text-muted-foreground group-aggregations`,children:i.map(e=>(0,q.jsxs)(`span`,{className:`mr-2`,children:[e.type,`: `,Number.isInteger(e.value)?e.value:e.value.toFixed(2)]},`${e.field}-${e.type}`))})]}),!r&&(0,q.jsx)(`div`,{className:`mt-1 ml-1.5 pl-3 border-l border-border/60`,children:c})]})};function st(e){return typeof e==`string`?{type:e}:e}function ct(e,t){if(t.length===0)return null;switch(e){case`count`:return t.length;case`sum`:return t.reduce((e,t)=>e+t,0);case`avg`:return t.reduce((e,t)=>e+t,0)/t.length;case`min`:return Math.min(...t);case`max`:return Math.max(...t);default:return null}}function lt(e,t,n){if(t===null)return``;let r={count:`Count`,sum:`Sum`,avg:`Avg`,min:`Min`,max:`Max`}[e]||e,i=n?.type,a;if(e!==`count`&&i===`currency`){let e=n?.currency||n?.defaultCurrency,r=n?.precision??n?.scale??0;try{a=e?new Intl.NumberFormat(void 0,{style:`currency`,currency:e,minimumFractionDigits:r,maximumFractionDigits:r}).format(t):new Intl.NumberFormat(void 0,{minimumFractionDigits:r,maximumFractionDigits:r}).format(t)}catch{a=t.toLocaleString()}}else if(e!==`count`&&i===`percent`){let e=n?.precision??0;a=`${(t>-1&&t<1?t*100:t).toFixed(e)}%`}else a=e===`avg`?t.toLocaleString(void 0,{maximumFractionDigits:2}):t.toLocaleString();return`${r}: ${a}`}function ut(e,t,n){return(0,H.useMemo)(()=>{let r=new Map;if(!e||e.length===0||t.length===0)return{summaries:r,hasSummary:!1};for(let i of e){if(!i.summary)continue;let e=st(i.summary),a=e.field||i.field,o=[];for(let e of t){let t=e[a];if(t!=null&&typeof t==`number`&&!isNaN(t))o.push(t);else if(t!=null&&typeof t==`string`){let e=parseFloat(t);isNaN(e)||o.push(e)}}let s;if(e.type===`count`){let e=t.filter(e=>e[a]!=null&&e[a]!==``).length;s=e>0?e:null}else s=ct(e.type,o);let c=n?.[a],l={type:i.type??c?.type,currency:i.currency??c?.currency,defaultCurrency:i.defaultCurrency??c?.defaultCurrency,precision:i.precision??c?.precision,scale:i.scale??c?.scale};r.set(i.field,{field:i.field,value:s,label:lt(e.type,s,l)})}return{summaries:r,hasSummary:r.size>0}},[e,t,n])}var dt={"grid.openMenu":`Open menu`,"grid.edit":`Edit`,"grid.delete":`Delete`};function ft(){try{let{t:e}=p();return t=>{let n=e(t);return n===t?dt[t]??t:n}}catch{return e=>dt[e]??e}}function pt(e){return e.replace(/_/g,` `).replace(/\b\w/g,e=>e.toUpperCase())}var mt=({row:e,rowActions:t,rowActionDefs:n,canEdit:r,canDelete:i,onEdit:a,onDelete:o,onAction:s,onActionDef:c})=>{let l=ft();return(0,q.jsxs)(F,{children:[(0,q.jsx)(Fe,{asChild:!0,children:(0,q.jsxs)(B,{variant:`ghost`,size:`icon`,className:`h-8 w-8 min-h-[44px] min-w-[44px] sm:min-h-0 sm:min-w-0`,"data-testid":`row-action-trigger`,children:[(0,q.jsx)(w,{className:`h-4 w-4`}),(0,q.jsx)(`span`,{className:`sr-only`,children:l(`grid.openMenu`)})]})}),(0,q.jsxs)(V,{align:`end`,onClick:e=>e.stopPropagation(),children:[r&&a&&(0,q.jsxs)(L,{onClick:()=>a(e),children:[(0,q.jsx)(ie,{className:`mr-2 h-4 w-4`}),l(`grid.edit`)]}),i&&o&&(0,q.jsxs)(L,{onClick:()=>o(e),children:[(0,q.jsx)(D,{className:`mr-2 h-4 w-4`}),l(`grid.delete`)]}),n?.map(t=>(0,q.jsx)(L,{onClick:()=>c?.(t,e),"data-testid":`row-action-${t.name}`,className:t.variant===`danger`?`text-destructive focus:text-destructive`:void 0,children:t.label??pt(t.name)},t.name)),t?.map(t=>(0,q.jsx)(L,{onClick:()=>s?.(t,e),"data-testid":`row-action-${t}`,children:pt(t)},t))]})]})},ht=({selectedRows:e,actions:t,actionDefs:n,onAction:r,onActionDef:i,onClearSelection:a,pageSize:o,totalMatching:s,allMatchingSelected:c,onSelectAllMatching:l})=>{let u=Array.isArray(n)&&n.length>0,d=Array.isArray(t)&&t.length>0;return!u&&!d||e.length===0?null:(0,q.jsxs)(`div`,{className:`border-t border-primary/30 px-4 py-2 flex flex-col gap-1.5 text-xs bg-primary/10 text-foreground shrink-0 shadow-sm motion-safe:animate-in motion-safe:slide-in-from-bottom-2 motion-safe:fade-in-0 motion-safe:duration-200`,role:`region`,"aria-label":`Bulk actions`,"data-testid":`bulk-actions-bar`,children:[(!c&&typeof s==`number`&&typeof o==`number`&&o>0&&e.length>=o&&s>o||c)&&(0,q.jsx)(`div`,{className:`flex items-center gap-2 text-[11px] text-muted-foreground`,"data-testid":`bulk-cross-page-banner`,children:c?(0,q.jsxs)(q.Fragment,{children:[(0,q.jsx)(ge,{className:`h-3 w-3 text-primary shrink-0`}),(0,q.jsxs)(`span`,{children:[`All `,s,` matching records are selected.`]})]}):(0,q.jsxs)(q.Fragment,{children:[(0,q.jsxs)(`span`,{children:[`All `,o,` on this page are selected.`]}),(0,q.jsxs)(`button`,{type:`button`,className:`font-medium text-primary underline-offset-2 hover:underline`,onClick:l,"data-testid":`bulk-select-all-matching`,children:[`Select all `,s,` matching`]})]})}),(0,q.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,q.jsx)(ge,{className:`h-3.5 w-3.5 text-primary shrink-0`}),(0,q.jsx)(`span`,{className:`font-medium tabular-nums`,children:(0,q.jsx)(`span`,{className:`inline-block motion-safe:animate-in motion-safe:zoom-in-90 motion-safe:duration-150`,children:c?`${s} items selected (all matches)`:`${e.length} ${e.length===1?`item`:`items`} selected`},c?`all-${s}`:e.length)}),(0,q.jsxs)(`div`,{className:`flex items-center gap-1.5 ml-3`,children:[u&&n.map(t=>{let n=t.variant===`danger`||t.operation===`delete`,r=t.icon?ve(t.icon):null;return(0,q.jsxs)(B,{variant:n?`destructive`:`outline`,size:`sm`,className:`h-7 px-2.5 text-xs gap-1.5`,onClick:()=>i?.(t,e),"data-testid":`bulk-action-${t.name}`,children:[r?(0,q.jsx)(Be,{name:r,className:`h-3 w-3`}):n?(0,q.jsx)(D,{className:`h-3 w-3`}):null,t.label??pt(t.name)]},t.name)}),!u&&d&&t.map(t=>{let n=String(t).toLowerCase(),i=n.includes(`delete`)||n.includes(`remove`)||n.includes(`destroy`),a=i?D:null;return(0,q.jsxs)(B,{variant:i?`destructive`:`outline`,size:`sm`,className:`h-7 px-2.5 text-xs gap-1.5`,onClick:()=>r?.(t,e),"data-testid":`bulk-action-${t}`,children:[a&&(0,q.jsx)(a,{className:`h-3 w-3`}),pt(t)]},t)})]}),(0,q.jsxs)(B,{variant:`ghost`,size:`sm`,className:`h-7 px-2 text-xs ml-auto gap-1`,onClick:a,children:[(0,q.jsx)(be,{className:`h-3 w-3`}),`Clear`]})]})]})};function gt({resource:e,dataSource:t}){let[n,r]=(0,H.useState)({total:0,done:0,failed:0,inFlight:!1}),[i,a]=(0,H.useState)(null),o=(0,H.useRef)([]),s=(0,H.useRef)(null),c=(0,H.useCallback)(()=>{r({total:0,done:0,failed:0,inFlight:!1}),a(null),o.current=[],s.current=null},[]);return{run:(0,H.useCallback)(async(n,i,c)=>{let l=i.length,d=Math.max(1,n.batchSize??200),f=[],p=0,m=0;a(null),r({total:l,done:0,failed:0,inFlight:!0});let h=()=>({...n.patch??{},...c}),g=[];if(n.operation===`update`){let e=Object.keys(h());for(let t of i){let n=String(t.id??``);if(!n)continue;let r={};for(let n of e)r[n]=t[n];g.push({id:n,prev:r})}}for(let a=0;a<i.length;a+=d){let o=i.slice(a,a+d),s=[];for(let e=0;e<o.length;e+=1){let t=o[e].id==null?``:String(o[e].id);t?s.push(t):(m+=1,f.push({id:`index_${a+e}`,error:`Missing record id`}))}if(s.length===0){r({total:l,done:p,failed:m,inFlight:!0});continue}let c=s.length>=2,g,_=`bulk`;n.operation===`update`&&typeof t.bulkUpdate==`function`?(g=n=>t.bulkUpdate(e,n,h()),_=`bulk update`):n.operation===`delete`&&typeof t.bulkDelete==`function`&&(g=n=>t.bulkDelete(e,n),_=`bulk delete`);let v=await u({ids:s,originalSize:o.length,offset:a,allowBulk:c,label:_},{bulkCall:g,perRow:r=>{switch(n.operation){case`delete`:return t.delete(e,r);case`update`:return t.update(e,r,h());case`custom`:return Promise.resolve();default:return Promise.reject(Error(`Unknown operation: ${n.operation}`))}}});p+=v.succeeded,m+=v.failed,f.push(...v.errors),r({total:l,done:p,failed:m,inFlight:!0})}let _={total:l,succeeded:p,failed:m,errors:f},v=new Set(f.map(e=>e.id));return o.current=g.filter(e=>!v.has(e.id)),s.current={def:n,rows:i,params:c},r({total:l,done:p,failed:m,inFlight:!1}),a(_),p>0&&x.invalidate(e),_},[e,t]),undo:(0,H.useCallback)(async()=>{let n=o.current;if(!n.length)return null;let i=n.length,s=[],c=0,l=0;a(null),r({total:i,done:0,failed:0,inFlight:!0}),(await Promise.allSettled(n.map(n=>t.update(e,n.id,n.prev)))).forEach((e,t)=>{e.status===`fulfilled`?c+=1:(l+=1,s.push({id:n[t].id,error:e.reason instanceof Error?e.reason.message:String(e.reason)}))});let u={total:i,succeeded:c,failed:l,errors:s};return o.current=[],r({total:i,done:c,failed:l,inFlight:!1}),a(u),u},[e,t]),retry:(0,H.useCallback)(async n=>{let r=s.current;if(!r||!r.rows.find(e=>String(e.id??``)===n))return!1;let i={...r.def.patch??{},...r.params};try{switch(r.def.operation){case`delete`:await t.delete(e,n);break;case`update`:await t.update(e,n,i);break;case`custom`:return!0;default:return!1}return a(e=>{if(!e)return e;let t=e.errors.filter(e=>e.id!==n);return{...e,errors:t,succeeded:e.succeeded+1,failed:Math.max(0,e.failed-1)}}),!0}catch{return!1}},[e,t]),progress:n,result:i,reset:c}}var _t=({def:e,rows:t,resource:n,dataSource:r,open:i,onClose:a,labelKey:o=`name`})=>{let s=e?.params??[],c=(0,H.useMemo)(()=>{let e={};for(let t of s)t.default!==void 0&&(e[t.name]=t.default);return e},[e?.name]),[l,u]=(0,H.useState)(`params`),[d,f]=(0,H.useState)(c),[p,m]=(0,H.useState)({}),{run:h,undo:g,retry:_,progress:v,result:y,reset:b}=gt({resource:n,dataSource:r}),[te,x]=(0,H.useState)(null),[S,w]=(0,H.useState)(!1),[ne,T]=(0,H.useState)(null);(0,H.useEffect)(()=>{i&&(b(),f(c),T(null),w(!1),x(null),u(s.length===0?`confirm`:`params`))},[i,e?.name,c,s.length,b]),(0,H.useEffect)(()=>{if(!i||typeof r.find!=`function`)return;let e=s.filter(e=>e.type===`lookup`&&e.object&&!p[e.name]);if(e.length===0)return;let t=!1;return(async()=>{let n={};for(let t of e)try{let e=await r.find(t.object,{$top:200}),i=Array.isArray(e)?e:e?.data??[];n[t.name]=i.map(e=>({value:String(e.id??e._id??``),label:String(e.name??e.full_name??e.email??e.id??`(unnamed)`)})).filter(e=>e.value)}catch{n[t.name]=[]}t||m(e=>({...e,...n}))})(),()=>{t=!0}},[i,e?.name]);let ie=(0,H.useMemo)(()=>{for(let e of s)if(e.required){let t=d[e.name];if(t==null||t===``)return!1}return!0},[s,d]),ae=e?.maxRecords??1/0,D=t.length>ae,O=(0,H.useCallback)(async()=>{e&&(u(`running`),await h(e,t,d),u(`result`))},[e,t,d,h]),k=(0,H.useCallback)(()=>{if(!y?.errors?.length)return;let t=[`record_id,error_message`,...y.errors.map(e=>`${e.id},"${e.error.replace(/"/g,`""`)}"`)].join(`
2
- `),n=new Blob([t],{type:`text/csv;charset=utf-8`}),r=URL.createObjectURL(n),i=document.createElement(`a`);i.href=r,i.download=`bulk_errors_${e?.name??`action`}_${Date.now()}.csv`,i.click(),URL.revokeObjectURL(r)},[y,e?.name]),A=!!e&&e.operation===`update`&&!!y&&y.succeeded>0&&ne===null,oe=(0,H.useCallback)(async()=>{w(!0);try{await g()&&T(Date.now())}finally{w(!1)}},[g]),se=(0,H.useCallback)(async e=>{x(e);try{await _(e)}finally{x(null)}},[_]);if(!e)return null;let le=e.label??e.name,j=t.slice(0,5),ue=Math.max(0,t.length-j.length);return(0,q.jsx)(C,{open:i,onOpenChange:e=>{e||a(y)},children:(0,q.jsxs)(re,{className:`max-w-md`,children:[(0,q.jsxs)(Ye,{children:[(0,q.jsxs)(ee,{className:`flex items-center gap-2`,children:[l===`running`&&(0,q.jsx)(Ie,{className:`h-4 w-4 animate-spin`}),le]}),l===`confirm`&&(0,q.jsx)(E,{children:e.confirmText??`This will apply to ${t.length} record${t.length===1?``:`s`}.`})]}),l===`params`&&(0,q.jsx)(`div`,{className:`space-y-3`,children:s.map(e=>(0,q.jsx)(yt,{param:e,value:d[e.name],lookupOptions:p[e.name],onChange:t=>f(n=>({...n,[e.name]:t}))},e.name))}),l===`confirm`&&(0,q.jsxs)(`div`,{className:`space-y-3 text-sm`,children:[D&&(0,q.jsxs)(`div`,{className:`rounded-md bg-destructive/10 text-destructive px-3 py-2 flex items-start gap-2`,children:[(0,q.jsx)(Ae,{className:`h-4 w-4 mt-0.5 shrink-0`}),(0,q.jsxs)(`div`,{children:[`Selection (`,t.length,`) exceeds the action limit (`,ae,`). Reduce the selection to proceed.`]})]}),(0,q.jsxs)(`div`,{className:`text-muted-foreground`,children:[`Affected records (`,t.length,`):`]}),(0,q.jsx)(me,{className:`max-h-32 rounded border bg-muted/30 p-2`,children:(0,q.jsxs)(`ul`,{className:`text-xs space-y-1`,children:[j.map((e,t)=>(0,q.jsxs)(`li`,{className:`truncate`,children:[`• `,String(e[o]??e.id??`Row ${t+1}`)]},String(e.id??t))),ue>0&&(0,q.jsxs)(`li`,{className:`text-muted-foreground`,children:[`… and `,ue,` more`]})]})}),Object.keys(d).length>0&&(0,q.jsx)(`div`,{className:`rounded border bg-muted/30 p-2 text-xs space-y-0.5`,children:Object.entries(d).map(([e,t])=>(0,q.jsxs)(`div`,{children:[(0,q.jsxs)(`span`,{className:`text-muted-foreground`,children:[e,`:`]}),` `,vt(t)]},e))})]}),l===`running`&&(0,q.jsxs)(`div`,{className:`space-y-2`,children:[(0,q.jsx)(_e,{value:v.total?(v.done+v.failed)/v.total*100:0}),(0,q.jsxs)(`div`,{className:`text-xs text-muted-foreground text-center`,children:[v.done+v.failed,` / `,v.total,` processed`,v.failed>0&&` · ${v.failed} failed`]})]}),l===`result`&&y&&(0,q.jsxs)(`div`,{className:`space-y-3 text-sm`,children:[(0,q.jsxs)(`div`,{className:`flex items-center gap-2`,children:[y.failed===0?(0,q.jsx)(ze,{className:`h-5 w-5 text-emerald-500`}):(0,q.jsx)(Ae,{className:`h-5 w-5 text-amber-500`}),(0,q.jsxs)(`span`,{children:[ne===null?``:`Undone — `,`Succeeded `,y.succeeded,` / `,y.total,y.failed>0&&` · Failed ${y.failed}`]})]}),y.errors.length>0&&(0,q.jsxs)(q.Fragment,{children:[(0,q.jsx)(me,{className:`max-h-48 rounded border bg-destructive/5 p-2`,"data-testid":`bulk-error-inspector`,children:(0,q.jsx)(`ul`,{className:`text-xs space-y-1.5`,children:y.errors.map(t=>(0,q.jsxs)(`li`,{className:`flex items-start gap-2`,"data-testid":`bulk-error-row-${t.id}`,children:[(0,q.jsx)(Ke,{className:`h-3 w-3 mt-0.5 shrink-0 text-destructive`}),(0,q.jsx)(`div`,{className:`min-w-0 flex-1`,children:(0,q.jsxs)(`div`,{className:`truncate`,children:[(0,q.jsxs)(`span`,{className:`text-muted-foreground`,children:[t.id,`:`]}),` `,t.error]})}),e.operation!==`custom`&&(0,q.jsx)(B,{variant:`ghost`,size:`sm`,className:`h-5 px-1.5 text-[10px]`,onClick:()=>se(t.id),disabled:te===t.id,"data-testid":`bulk-error-retry-${t.id}`,children:te===t.id?`…`:`Retry`})]},t.id))})}),(0,q.jsx)(B,{variant:`outline`,size:`sm`,onClick:k,children:`Download error CSV`})]})]}),(0,q.jsxs)(ce,{children:[l===`params`&&(0,q.jsxs)(q.Fragment,{children:[(0,q.jsx)(B,{variant:`ghost`,onClick:()=>a(),children:`Cancel`}),(0,q.jsx)(B,{onClick:()=>u(`confirm`),disabled:!ie,children:`Next`})]}),l===`confirm`&&(0,q.jsxs)(q.Fragment,{children:[(0,q.jsx)(B,{variant:`ghost`,onClick:()=>s.length?u(`params`):a(),children:s.length?`Back`:`Cancel`}),(0,q.jsx)(B,{variant:e.variant===`danger`?`destructive`:`default`,onClick:O,disabled:D,children:e.confirmLabel??`Run`})]}),l===`running`&&(0,q.jsx)(B,{variant:`ghost`,disabled:!0,children:`Running…`}),l===`result`&&(0,q.jsxs)(q.Fragment,{children:[A&&(0,q.jsx)(B,{variant:`outline`,onClick:oe,disabled:S,"data-testid":`bulk-undo-button`,children:S?`Undoing…`:`Undo`}),(0,q.jsx)(B,{onClick:()=>a(y),children:`Done`})]})]})]})})};function vt(e){return e==null||e===``?`—`:typeof e==`boolean`?e?`Yes`:`No`:String(e)}var yt=({param:e,value:t,onChange:n,lookupOptions:r})=>{let i=`bulk-param-${e.name}`,a=(0,q.jsxs)(Oe,{htmlFor:i,className:`text-xs`,children:[e.label??e.name,e.required&&(0,q.jsx)(`span`,{className:`text-destructive ml-0.5`,children:`*`})]}),o=null;switch(e.type){case`boolean`:o=(0,q.jsx)(Me,{id:i,checked:!!t,onCheckedChange:n});break;case`textarea`:o=(0,q.jsx)(k,{id:i,value:t??``,onChange:e=>n(e.target.value),placeholder:e.placeholder});break;case`select`:{let r=e.options??[];o=(0,q.jsxs)(j,{value:t==null?``:String(t),onValueChange:n,children:[(0,q.jsx)(he,{id:i,children:(0,q.jsx)(T,{placeholder:e.placeholder??`Select…`})}),(0,q.jsx)(Xe,{children:r.map(e=>(0,q.jsx)(b,{value:String(e.value),children:e.label},String(e.value)))})]});break}case`lookup`:{let a=r??[];o=(0,q.jsxs)(j,{value:t??``,onValueChange:n,children:[(0,q.jsx)(he,{id:i,children:(0,q.jsx)(T,{placeholder:a.length===0?`Loading…`:e.placeholder??`Select…`})}),(0,q.jsx)(Xe,{children:a.map(e=>(0,q.jsx)(b,{value:e.value,children:e.label},e.value))})]});break}case`number`:o=(0,q.jsx)(z,{id:i,type:`number`,value:t??``,onChange:e=>n(e.target.value===``?void 0:Number(e.target.value)),placeholder:e.placeholder});break;default:o=(0,q.jsx)(z,{id:i,type:`text`,value:t??``,onChange:e=>n(e.target.value),placeholder:e.placeholder})}return(0,q.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,q.jsx)(`div`,{className:`flex items-center justify-between`,children:a}),o,e.help&&(0,q.jsx)(`p`,{className:`text-[11px] text-muted-foreground`,children:e.help})]})},bt=({testId:e,onActivate:t,children:n})=>(0,q.jsx)(`span`,{role:`link`,tabIndex:0,"data-testid":e,className:`text-primary font-medium underline-offset-4 hover:underline cursor-pointer truncate block max-w-full`,onClick:e=>{e.stopPropagation(),t()},onKeyDown:e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),e.stopPropagation(),t())},children:n}),xt={"grid.actions":`Actions`,"grid.edit":`Edit`,"grid.delete":`Delete`,"grid.export":`Export`,"grid.exportAs":`Export as {{format}}`,"grid.loading":`Loading grid...`,"grid.errorLoading":`Error loading grid`,"grid.pullToRefresh":`Pull to refresh`,"grid.refreshing":`Refreshing…`,"grid.openRecord":`Open record`,"grid.empty":`Empty`,"grid.yes":`Yes`,"grid.no":`No`,"grid.systemFields":`System`};function St(){try{let e=p();return e.t(`grid.actions`)===`grid.actions`?{t:(e,t)=>{let n=xt[e]||e;if(t)for(let[e,r]of Object.entries(t))n=n.replace(`{{${e}}}`,String(r));return n}}:{t:e.t}}catch{return{t:(e,t)=>{let n=xt[e]||e;if(t)for(let[e,r]of Object.entries(t))n=n.replace(`{{${e}}}`,String(r));return n}}}}function Ct(e){if(e!=null)return typeof e==`string`?e:void 0}function wt(e){return e.data?Array.isArray(e.data)?{provider:`value`,items:e.data}:e.data:e.staticData?{provider:`value`,items:e.staticData}:e.objectName?{provider:`object`,object:e.objectName}:null}function Tt(e){if(!(!e||e.length===0))return typeof e[0]==`object`&&e[0],e}var Z=({schema:e,dataSource:t,onEdit:n,onDelete:r,onBulkDelete:i,onRowSelect:o,onRowClick:u,onCellChange:p,onRowSave:m,onBatchSave:ee,onAddRecord:b,...x})=>{let[C,w]=(0,H.useState)([]),[ne,T]=(0,H.useState)(!0),[re,ie]=(0,H.useState)(null),{t:E}=St(),{fieldLabel:D,translateOptions:O}=Se(),[k,se]=(0,H.useState)(null),[ce,j]=(0,H.useState)(!1),[pe,me]=(0,H.useState)(0),[he,_e]=(0,H.useState)(!1),[ve,M]=(0,H.useState)(!1),N=ue({dataSource:t}),[F,I]=(0,H.useState)(e.rowHeight??`compact`),[be,L]=(0,H.useState)([]),[R,z]=(0,H.useState)(!1),[we,Ee]=(0,H.useState)(void 0),[Oe,ke]=(0,H.useState)(null),[Ae,Me]=(0,H.useState)([]),Fe=H.useRef(null);H.useEffect(()=>{e.rowHeight&&e.rowHeight!==F&&I(e.rowHeight)},[e.rowHeight]);let Ie=H.useMemo(()=>e.id?`grid-columns-${e.objectName}-${e.id}`:`grid-columns-${e.objectName}`,[e.objectName,e.id]),[V,Le]=(0,H.useState)(()=>{let t=e.columnState;if(t&&typeof t==`object`)return t;try{let e=localStorage.getItem(Ie);return e?JSON.parse(e):{}}catch{return{}}}),ze=H.useMemo(()=>JSON.stringify(e.columnState??null),[e.columnState]);H.useEffect(()=>{let t=e.columnState;t&&typeof t==`object`&&Le(t)},[ze]);let Be=(0,H.useCallback)(e=>{Le(e);try{localStorage.setItem(Ie,JSON.stringify(e))}catch(e){console.warn(`Failed to persist column state:`,e)}let t=x.onColumnStateChange;if(typeof t==`function`)try{t(e)}catch(e){console.warn(`onColumnStateChange threw:`,e)}},[Ie,x]),{ref:We,isRefreshing:Ke,pullDistance:qe}=Ze({onRefresh:(0,H.useCallback)(async()=>{me(e=>e+1)},[]),enabled:!!t&&!!e.objectName});(0,H.useEffect)(()=>{let e=()=>j(window.innerWidth<480);return e(),window.addEventListener(`resize`,e),()=>window.removeEventListener(`resize`,e)},[]);let Je=x.data,Ye=l(e.bind),Xe=wt(e),U=H.useMemo(()=>Je&&Array.isArray(Je)?{provider:`value`,items:Je}:Ye&&Array.isArray(Ye)?{provider:`value`,items:Ye}:Xe,[JSON.stringify(Xe),Ye,Je]),W=U?.provider===`value`,G=U?.provider===`object`&&U&&`object`in U?U.object:e.objectName,K=e.fields,J=e.columns,Qe=e.filter,Y=e.sort,$e=e.pagination,tt=e.pageSize;(0,H.useEffect)(()=>{W&&U?.provider===`value`&&(w(e=>{let t=U.items;return JSON.stringify(e)===JSON.stringify(t)?e:t}),T(!1))},[W,U]),(0,H.useEffect)(()=>{if(!W||!G||!t)return;let e=!1;return(async()=>{try{if(typeof t.getObjectSchema!=`function`)return;let n=await t.getObjectSchema(G);e||se(n)}catch(e){console.warn(`[ObjectGrid] Failed to fetch objectSchema for inline data (objectName: ${G}):`,e)}})(),()=>{e=!0}},[W,G,t]),(0,H.useEffect)(()=>{if(W)return;let n=!1;return(async()=>{T(!0),ie(null);try{let r=null,i=Tt(J)||K;if(G&&t)if(typeof t.getObjectSchema==`function`){let e=await t.getObjectSchema(G);if(n)return;r=e}else r={name:G,fields:{}};else if(i&&G)r={name:G,fields:{}};else if(G)throw Error(`DataSource required`);else throw Error(`Object name required for data fetching`);if(n||se(r),t&&G){let i={$select:(()=>{let e=e=>e.map(e=>typeof e==`string`?e:e?.name||e?.field).includes(`id`)?e:[`id`,...e];if(K)return e(K);if(J&&Array.isArray(J))return e(J.map(e=>typeof e==`string`?e:e.field))})(),$top:$e?.pageSize||tt||50};Qe&&Array.isArray(Qe)?i.$filter=Qe:e.defaultFilters&&(i.$filter=e.defaultFilters),Y?typeof Y==`string`?i.$orderby=Y:Array.isArray(Y)&&(i.$orderby=Y.map(e=>`${e.field} ${e.order}`).join(`, `)):e.defaultSort&&(i.$orderby=`${e.defaultSort.field} ${e.defaultSort.order}`);let a=d(r?.fields,J??K);a.length>0&&(i.$expand=a);let o=await t.find(G,i);if(n)return;w(o.data||[]);let s=o.total;Ee(typeof s==`number`?s:void 0),Fe.current={...i},z(!1)}}catch(e){n||ie(e)}finally{n||T(!1)}})(),()=>{n=!0}},[G,K,J,Qe,Y,$e,tt,t,W,U,pe]);let X=c({navigation:e.navigation,objectName:e.objectName,onNavigate:e.onNavigate,onRowClick:u}),{execute:nt}=a(),rt=et(e.rowColor),it=(0,H.useCallback)(t=>{let n=e.conditionalFormatting;if(!(!n||n.length===0))for(let e of n){let n=!1,r=(`condition`in e?e.condition:void 0)||(`expression`in e?e.expression:void 0)||void 0;if(r)n=f(r,t);else if(`field`in e&&`operator`in e&&e.field&&e.operator){let r=e,i=t[r.field];switch(r.operator){case`equals`:n=i===r.value;break;case`not_equals`:n=i!==r.value;break;case`contains`:n=typeof i==`string`&&typeof r.value==`string`&&i.includes(r.value);break;case`greater_than`:n=typeof i==`number`&&typeof r.value==`number`&&i>r.value;break;case`less_than`:n=typeof i==`number`&&typeof r.value==`number`&&i<r.value;break;case`in`:n=Array.isArray(r.value)&&r.value.includes(i);break}}if(n){let t={};return`style`in e&&e.style&&Object.assign(t,e.style),`backgroundColor`in e&&e.backgroundColor&&(t.backgroundColor=e.backgroundColor),`textColor`in e&&e.textColor&&(t.color=e.textColor),`borderColor`in e&&e.borderColor&&(t.borderColor=e.borderColor),t}}},[e.conditionalFormatting]),st=H.useMemo(()=>{let t=e.grouping;if(!t?.fields?.length)return;let n=new Map;for(let r of t.fields){let t=r.field,i=k?.fields?.[t],a=Tt(e.columns)?.find?.(e=>typeof e==`object`&&e?.field===t),o=a?.type||i?.type,s=a?.options||i?.options,c=new Map;if(Array.isArray(s)&&s.length>0){let n=e.objectName?O(e.objectName,t,s):s;for(let e of n)if(e&&e.value!==void 0&&e.value!==null){let t=e.label;c.set(String(e.value),String(t??e.value))}}n.set(t,{type:o||void 0,options:c.size>0?c:void 0})}return(e,t)=>{let r=n.get(e);if(r){if(r.options){let e=r.options.get(String(t));if(e!==void 0)return e}if(r.type===`boolean`||typeof t==`boolean`){if(t===!0||t===`true`)return E(`grid.booleanTrue`,`Yes`);if(t===!1||t===`false`)return E(`grid.booleanFalse`,`No`)}}}},[e.grouping,e.columns,e.objectName,k,O,E]),{groups:ct,isGrouped:lt,toggleGroup:dt}=at(e.grouping,C,e.aggregations,st),{summaries:ft,hasSummary:gt}=ut(H.useMemo(()=>{let t=Tt(e.columns);if(t&&t.length>0&&typeof t[0]==`object`)return t},[e.columns]),C,k?.fields),vt=(0,H.useCallback)(()=>{let t=e=>e&&{text:(0,q.jsx)(_,{className:`h-3.5 w-3.5`}),number:(0,q.jsx)(de,{className:`h-3.5 w-3.5`}),currency:(0,q.jsx)(de,{className:`h-3.5 w-3.5`}),percent:(0,q.jsx)(de,{className:`h-3.5 w-3.5`}),date:(0,q.jsx)(fe,{className:`h-3.5 w-3.5`}),datetime:(0,q.jsx)(Ue,{className:`h-3.5 w-3.5`}),boolean:(0,q.jsx)(ge,{className:`h-3.5 w-3.5`}),user:(0,q.jsx)(S,{className:`h-3.5 w-3.5`}),select:(0,q.jsx)(y,{className:`h-3.5 w-3.5`})}[e]||(0,q.jsx)(_,{className:`h-3.5 w-3.5`}),n=e=>{if(e.type)return e.type;let t=e.field.toLowerCase();if([`completed`,`is_completed`,`done`,`active`,`enabled`,`archived`].some(e=>t===e||t===`is_${e}`))return`boolean`;if([`created_time`,`modified_time`,`updated_time`,`created_at`,`updated_at`,`modified_at`,`last_login`,`logged_at`].some(e=>t===e||t.endsWith(`_${e}`)))return`datetime`;if([`date`,`due`,`created`,`updated`,`deadline`,`start`,`end`,`expires`].some(e=>t.includes(e))){if(C.length>0){let t=C.find(t=>t[e.field]!=null)?.[e.field];if(typeof t==`string`&&!isNaN(Date.parse(t)))return`date`}return`date`}if([`probability`,`percent`,`percentage`,`completion`,`progress`,`rate`].some(e=>t.includes(e))&&C.length>0&&typeof C.find(t=>t[e.field]!=null)?.[e.field]==`number`)return`percent`;if([`status`,`priority`,`category`,`stage`,`type`,`severity`,`level`].some(e=>t.includes(e))&&C.length>0){let t=new Set(C.map(t=>t[e.field]).filter(Boolean));if(t.size>0&&t.size<=10)return`select`}if([`assignee`,`owner`,`author`,`reporter`,`creator`,`user`].some(e=>t.includes(e)))return`user`;if([`amount`,`price`,`total`,`revenue`,`cost`,`budget`,`salary`].some(e=>t.includes(e))&&C.length>0&&typeof C.find(t=>t[e.field]!=null)?.[e.field]==`number`)return`currency`;if(C.length>0){let t=C.find(t=>t[e.field]!=null)?.[e.field];if(typeof t==`string`&&/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}/.test(t))return`datetime`}return null},r=Tt(J);if(r){if(r.length>0&&typeof r[0]==`object`&&r[0]!==null){let i=r[0];if(`accessorKey`in i)return r.map(r=>{if(r.cell)return r;let i=n({field:r.accessorKey,label:r.header,type:r.type});if(!i)return r;let a=je(i),o={name:r.accessorKey,type:i};return i===`select`&&(o.options=Array.from(new Set(C.map(e=>e[r.accessorKey]).filter(Boolean))).map(e=>({value:e,label:Ce(String(e))}))),r.appearance!=null&&(o.appearance=r.appearance),{...r,...e.showColumnTypeIcons&&{headerIcon:t(i)},cell:e=>(0,q.jsx)(a,{value:e,field:o})}});if(`field`in i)return r.filter(e=>e?.field&&typeof e.field==`string`&&!e.hidden).map((r,i)=>{let a=Ct(r.label)||r.field.charAt(0).toUpperCase()+r.field.slice(1).replace(/_/g,` `),o=e.objectName?D(e.objectName,r.field,a):a,s,c=k?.fields?.[r.field],l=r.type||c?.type||n({field:r.field})||null,u=r.format??c?.format,d=l?Ne({type:l,format:u}):null,f=d?je(d):null,p={name:r.field,type:d||`text`};c&&(c.label&&(p.label=c.label),c.currency&&(p.currency=c.currency),c.precision!==void 0&&(p.precision=c.precision),c.format&&(p.format=c.format),c.options&&(p.options=O(e.objectName,r.field,c.options))),d===`select`&&!p.options&&(p.options=Array.from(new Set(C.map(e=>e[r.field]).filter(Boolean))).map(e=>({value:e,label:Ce(String(e))}))),r.options&&(p.options=O(e.objectName,r.field,r.options));let m=r.appearance??c?.appearance;m!=null&&(p.appearance=m);let h=i===0&&!r.link&&!r.action,g=r.link||h;s=r.link&&r.action||h&&r.action||g?(e,t)=>(0,q.jsx)(bt,{testId:h?`primary-field-link`:`link-cell`,onActivate:()=>X.handleClick(t),children:f?(0,q.jsx)(f,{value:e,field:p}):e!=null&&e!==``?String(e):(0,q.jsx)(`span`,{className:`text-muted-foreground/50 text-xs italic`,children:`—`})}):r.action?(e,t)=>(0,q.jsx)(B,{variant:`outline`,size:`sm`,className:`h-7 text-xs`,"data-testid":`action-cell`,onClick:n=>{n.stopPropagation(),nt({type:r.action,params:{record:t,field:r.field,value:e}})},children:pt(r.action)}):f?e=>(0,q.jsx)(f,{value:e,field:p}):e=>e!=null&&e!==``?(0,q.jsx)(`span`,{children:String(e)}):(0,q.jsx)(v,{});let _=r.prefix;if(_?.field){let e=s,t=_.type===`badge`?je(`select`):null;s=(n,r)=>{let i=r[_.field];return(0,q.jsxs)(`span`,{className:`flex items-center gap-1.5`,children:[i!=null&&i!==``?t?(0,q.jsx)(t,{value:i,field:{name:_.field,type:`select`}}):(0,q.jsx)(`span`,{className:`text-muted-foreground text-xs mr-1.5`,children:String(i)}):null,e(n,r)]})}}let ee=[`number`,`currency`,`percent`],y=d||r.type,b=r.align||(y&&ee.includes(y)?`right`:void 0),te=i===0||r.essential===!0;return{header:o,accessorKey:r.field,...e.showColumnTypeIcons&&{headerIcon:t(d)},...!te&&{className:`hidden sm:table-cell`},...r.width&&{width:r.width},...b&&{align:b},sortable:r.sortable!==!1,...r.resizable!==void 0&&{resizable:r.resizable},...r.wrap!==void 0&&{wrap:r.wrap},...s&&{cell:s},...r.pinned&&{pinned:r.pinned}}})}return r.filter(e=>typeof e==`string`&&e.trim().length>0).map((r,i)=>{let a=k?.fields?.[r],o=a?.label||r.charAt(0).toUpperCase()+r.slice(1).replace(/_/g,` `),s=e.objectName?D(e.objectName,r,o):o,c=a?.type||n({field:r})||null,l=c?je(c):null,u={name:r,type:c||`text`};a&&(a.label&&(u.label=a.label),a.currency&&(u.currency=a.currency),a.precision!==void 0&&(u.precision=a.precision),a.format&&(u.format=a.format),a.options&&(u.options=O(e.objectName,r,a.options))),c===`select`&&!u.options&&(u.options=Array.from(new Set(C.map(e=>e[r]).filter(Boolean))).map(e=>({value:e,label:Ce(String(e))}))),(c===`select`||c===`status`)&&a?.appearance!=null&&(u.appearance=a.appearance);let d=c&&[`number`,`currency`,`percent`].includes(c)?`right`:void 0,f=i===0,p;return f&&l?p=(e,t)=>(0,q.jsx)(bt,{testId:`primary-field-link`,onActivate:()=>X.handleClick(t),children:(0,q.jsx)(l,{value:e,field:u})}):f?p=(e,t)=>(0,q.jsx)(bt,{testId:`primary-field-link`,onActivate:()=>X.handleClick(t),children:e!=null&&e!==``?String(e):(0,q.jsx)(`span`,{className:`text-muted-foreground/50 text-xs italic`,children:`—`})}):l&&(p=e=>(0,q.jsx)(l,{value:e,field:u})),{header:s,accessorKey:r,...e.showColumnTypeIcons&&c&&{headerIcon:t(c)},...d&&{align:d},...p&&{cell:p},sortable:a?.sortable!==!1}})}if(W){let r=U?.provider===`value`?U.items:[];if(r.length>0)return(K||Object.keys(r[0])).map(r=>{let i=k?.fields?.[r],a=i?.type||n({field:r})||null,o=a?je(a):null,s=i?.label||r.charAt(0).toUpperCase()+r.slice(1).replace(/_/g,` `),c={name:r,type:a||`text`};i&&(i.label&&(c.label=i.label),i.currency&&(c.currency=i.currency),i.precision!==void 0&&(c.precision=i.precision),i.format&&(c.format=i.format),i.options&&(c.options=O(e.objectName,r,i.options))),a===`select`&&!c.options&&(c.options=Array.from(new Set(C.map(e=>e[r]).filter(Boolean))).map(e=>({value:e,label:Ce(String(e))}))),(a===`select`||a===`status`)&&i?.appearance!=null&&(c.appearance=i.appearance);let l=a&&[`number`,`currency`,`percent`].includes(a)?`right`:void 0;return{header:s,accessorKey:r,...e.showColumnTypeIcons&&a&&{headerIcon:t(a)},...l&&{align:l},...o&&{cell:e=>(0,q.jsx)(o,{value:e,field:c})},sortable:i?.sortable!==!1}})}if(!k)return[];let i=[],a=new Set([`id`,`created_at`,`createdAt`,`updated_at`,`updatedAt`,`deleted_at`,`deletedAt`,`created_by`,`createdBy`,`updated_by`,`updatedBy`,`_version`,`_rev`]),o=k?.compactLayout,s=Object.keys(k.fields||{}),c;if(K)c=K;else if(o?.length)c=o.filter(e=>k.fields?.[e]);else{let e=s.filter(e=>{let t=k.fields?.[e];return!(!t||t.hidden||t.readonly&&a.has(e))});c=[...e.filter(e=>!a.has(e)),...e.filter(e=>a.has(e))]}return c.forEach(t=>{let n=k.fields?.[t];if(!n||n.permissions&&n.permissions.read===!1)return;let r=je(n.type),a=[`number`,`currency`,`percent`],o=n.options?{...n,options:O(e.objectName,t,n.options)}:n;i.push({header:e.objectName?D(e.objectName,t,n.label||t):n.label||t,accessorKey:t,...a.includes(n.type)&&{align:`right`},cell:e=>(0,q.jsx)(r,{value:e,field:o}),sortable:n.sortable!==!1})}),i},[k,K,J,U,W,X.handleClick,nt,C,D,O,e.objectName]),yt=(0,H.useCallback)(t=>{let n=e.exportOptions,r=n?.maxRecords||0,i=n?.includeHeaders!==!1,a=n?.fileNamePrefix||e.objectName||`export`;if((t===`csv`||t===`xlsx`||t===`json`)&&N.isSupported&&e.objectName&&!W&&n?.streaming!==!1){let n=vt().filter(e=>e.accessorKey!==`_actions`).map(e=>e.accessorKey).filter(Boolean);_e(!1),M(!0),N.start(e.objectName,{format:t===`json`?`json`:t,fields:n.length?n:void 0,includeHeaders:i,limit:r>0?r:void 0});return}let o=r>0?C.slice(0,r):C,s=(e,t)=>{let n=URL.createObjectURL(e),r=document.createElement(`a`);r.href=n,r.download=t,r.click(),URL.revokeObjectURL(n)},c=e=>{let t=e==null?``:String(e);return t.includes(`,`)||t.includes(`"`)||t.includes(`
3
- `)||t.includes(`\r`)?`"${t.replace(/"/g,`""`)}"`:t};if(t===`csv`){let e=vt().filter(e=>e.accessorKey!==`_actions`),t=e.map(e=>e.accessorKey),n=e.map(e=>e.header),r=[];i&&r.push(n.join(`,`)),o.forEach(e=>{r.push(t.map(t=>c(e[t])).join(`,`))}),s(new Blob([r.join(`
4
- `)],{type:`text/csv;charset=utf-8;`}),`${a}.csv`)}else t===`json`&&s(new Blob([JSON.stringify(o,null,2)],{type:`application/json`}),`${a}.json`);_e(!1)},[C,e.exportOptions,e.objectName,vt,N,W]);if(re)return(0,q.jsxs)(`div`,{className:`p-3 sm:p-4 border border-red-300 bg-red-50 rounded-md`,children:[(0,q.jsx)(`h3`,{className:`text-red-800 font-semibold`,children:E(`grid.errorLoading`)}),(0,q.jsx)(`p`,{className:`text-red-600 text-sm mt-1`,children:re.message})]});if(ne&&C.length===0)return ce?(0,q.jsx)(`div`,{className:`space-y-2 p-2`,children:[1,2,3].map(e=>(0,q.jsxs)(`div`,{className:`border rounded-lg p-3 bg-card animate-pulse`,children:[(0,q.jsx)(`div`,{className:`h-5 bg-muted rounded w-3/4 mb-3`}),(0,q.jsxs)(`div`,{className:`flex items-center justify-between mb-2`,children:[(0,q.jsx)(`div`,{className:`h-4 bg-muted rounded w-1/4`}),(0,q.jsx)(`div`,{className:`h-5 bg-muted rounded-full w-20`})]}),(0,q.jsx)(`div`,{className:`h-3 bg-muted rounded w-1/3`})]},e))}):(0,q.jsxs)(`div`,{className:`p-4 sm:p-8 text-center`,children:[(0,q.jsx)(`div`,{className:`inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-foreground`}),(0,q.jsx)(`p`,{className:`mt-2 text-sm text-muted-foreground`,children:E(`grid.loading`)})]});let xt=[...vt()];if(V.widths&&(xt=xt.map(e=>{let t=V.widths?.[e.accessorKey];return t?{...e,size:t}:e})),V.order&&V.order.length>0){let e=new Map(V.order.map((e,t)=>[e,t]));xt.sort((t,n)=>(e.get(t.accessorKey)??1/0)-(e.get(n.accessorKey)??1/0))}let Z=(`operations`in e?e.operations:void 0)??{update:!!n,delete:!!r},Et=Array.isArray(e.rowActions)?e.rowActions:[],Dt=Array.isArray(e.rowActionDefs)?e.rowActionDefs:[],Q=Et.includes(`edit`),Ot=Et.includes(`delete`),kt=Et.filter(e=>e!==`edit`&&e!==`delete`),At=!!((Z?.update||Q)&&n),jt=!!((Z?.delete||Ot)&&r),Mt=!!(Z&&(Z.update||Z.delete)),Nt=kt.length>0||Dt.length>0||Q||Ot,Pt=Mt||Nt?[...xt,{header:E(`grid.actions`),accessorKey:`_actions`,cell:(e,t)=>(0,q.jsx)(mt,{row:t,rowActions:kt,rowActionDefs:Dt,canEdit:At,canDelete:jt,onEdit:n,onDelete:r,onAction:(e,t)=>nt({type:e,params:{record:t}}),onActionDef:(e,t)=>{let{params:n,...r}=e,i={...r};Array.isArray(n)&&n.length>0&&(i.actionParams=n),i.params={_rowRecord:t},nt(i)}}),sortable:!1}]:xt,Ft=Pt.filter(e=>e.pinned===`left`),It=Pt.filter(e=>e.pinned===`right`),Lt=Pt.filter(e=>!e.pinned),Rt=Ft.length>0||It.length>0,zt=`sticky right-0 z-10 bg-background border-l border-border`,Bt=F===`compact`?`px-3 py-1 h-9 text-[13px] leading-tight`:F===`short`?`px-3 py-1 h-9 text-[13px] leading-normal`:F===`tall`?`px-3 py-2.5 h-14 text-sm`:F===`extra_tall`?`px-3 py-3.5 h-16 text-sm leading-relaxed`:`px-3 py-1.5 h-11 text-[13px] leading-normal`,Vt=e=>({...e,cellClassName:[Bt,e.cellClassName].filter(Boolean).join(` `)}),Ht=Rt?[...Ft.map(Vt),...Lt.map(Vt),...It.map(e=>({...Vt(e),className:[e.className,zt].filter(Boolean).join(` `),cellClassName:[Bt,e.cellClassName,zt].filter(Boolean).join(` `)}))]:Pt.map(Vt),Ut=Rt?Ft.length:e.frozenColumns??1,Wt=e.batchActions??e.bulkActions,Gt=Array.isArray(e.bulkActionDefs)?e.bulkActionDefs:[],Kt=Wt&&Wt.length>0?Wt:jt&&i&&Gt.length===0?[`delete`]:[],qt=Kt.length>0||Gt.length>0,Jt=!1;e.selection?.type?Jt=e.selection.type===`none`?!1:e.selection.type:e.selectable===void 0?qt&&(Jt=`multiple`):Jt=e.selectable;let Yt=async n=>{if(!R)return n;let r=e.objectName;if(!t||!r)return n;let i={...Fe.current??{}};delete i.$top,delete i.$skip;let a=5e3,o=[],s=0;for(;o.length<a;){let e=(await t.find(r,{...i,$top:500,$skip:s})).data??[];if(e.length===0||(o.push(...e),e.length<500))break;s+=500}return o.slice(0,a)},Xt=(e,t)=>{(async()=>{let n=await Yt(t);if(e===`delete`&&i){i(n),L([]),z(!1);return}nt({type:e,params:{records:n}})})()},$=(e,t)=>{(async()=>{let n=await Yt(t);ke(e),Me(n)})()},Zt=e=>{ke(null),Me([]),e&&(L([]),z(!1),me(e=>e+1))},Qt=e.pagination===void 0?e.showPagination===void 0?!0:e.showPagination:!0,$t=e.pagination?.pageSize||e.pageSize||10,en=e.searchableFields===void 0?e.showSearch===void 0?!0:e.showSearch:e.searchableFields.length>0,tn={type:`data-table`,caption:e.label||e.title,columns:Ht,data:C,pagination:Qt,pageSize:$t,searchable:en,selectable:Jt,sortable:!0,exportable:Z?.export,borderless:!0,rowActions:!!(e.editable&&Mt),resizableColumns:e.resizable??e.resizableColumns??!0,reorderableColumns:e.reorderableColumns??!1,editable:e.editable??!1,singleClickEdit:e.singleClickEdit??!0,className:e.className,cellClassName:F===`compact`?`px-3 py-1 text-[13px] leading-tight`:F===`short`?`px-3 py-1 text-[13px] leading-normal`:F===`tall`?`px-3 py-2.5 text-sm`:F===`extra_tall`?`px-3 py-3.5 text-sm leading-relaxed`:`px-3 py-1.5 text-[13px] leading-normal`,showRowNumbers:!0,showAddRow:!!Z?.create,onAddRecord:b,rowClassName:e.rowColor?(e,t)=>rt(e):void 0,rowStyle:e.conditionalFormatting?.length?(e,t)=>it(e):void 0,frozenColumns:Ut,onSelectionChange:e=>{L(e),o?.(e)},onRowClick:X.handleClick,onCellChange:p,onRowSave:m,onBatchSave:ee,onColumnResize:(e,t)=>{Be({...V,widths:{...V.widths,[e]:t}})},onColumnReorder:e=>{Be({...V,order:e})}},nn=e=>({...tn,caption:void 0,data:e,pagination:!1,searchable:!1,borderless:!0}),rn=e.label?`${e.label} Detail`:e.objectName?`${e.objectName.charAt(0).toUpperCase()+e.objectName.slice(1)} Detail`:`Record Detail`;if(ce&&C.length>0&&!lt){let e=vt().filter(e=>e.accessorKey!==`_actions`),t=new Map;e.forEach(e=>t.set(e.accessorKey,e));let n=e[0],r=[`amount`,`price`,`total`,`revenue`,`cost`,`value`,`budget`,`salary`],i=[`stage`,`status`,`priority`,`category`,`severity`,`level`],a=[`date`,`due`,`created`,`updated`,`deadline`,`start`,`end`,`expires`],o=[`probability`,`percent`,`rate`,`ratio`,`confidence`,`score`],s=e=>{let t=(e||``).toLowerCase();return t.includes(`won`)||t.includes(`completed`)||t.includes(`done`)||t.includes(`active`)||t===`activated`||t===`success`||t===`approved`||t===`paid`?`bg-green-50 text-green-700 border-green-200 dark:bg-green-950/40 dark:text-green-300 dark:border-green-900/60`:t.includes(`lost`)||t.includes(`cancelled`)||t.includes(`rejected`)||t.includes(`closed lost`)||t===`expired`||t===`terminated`||t===`failed`||t===`overdue`?`bg-red-50 text-red-700 border-red-200 dark:bg-red-950/40 dark:text-red-300 dark:border-red-900/60`:t.includes(`negotiation`)||t.includes(`review`)||t.includes(`in progress`)||t.includes(`approval`)||t===`in_approval`||t===`pending_approval`?`bg-yellow-50 text-yellow-800 border-yellow-200 dark:bg-yellow-950/40 dark:text-yellow-300 dark:border-yellow-900/60`:t.includes(`proposal`)||t.includes(`pending`)?`bg-blue-50 text-blue-700 border-blue-200 dark:bg-blue-950/40 dark:text-blue-300 dark:border-blue-900/60`:t.includes(`qualification`)||t.includes(`qualified`)?`bg-indigo-50 text-indigo-700 border-indigo-200 dark:bg-indigo-950/40 dark:text-indigo-300 dark:border-indigo-900/60`:t.includes(`prospecting`)||t.includes(`new`)||t.includes(`open`)?`bg-purple-50 text-purple-700 border-purple-200 dark:bg-purple-950/40 dark:text-purple-300 dark:border-purple-900/60`:t===`draft`||t.includes(`draft`)?`bg-slate-50 text-slate-700 border-slate-200 dark:bg-slate-950/40 dark:text-slate-300 dark:border-slate-900/60`:`bg-muted text-muted-foreground border-border`},c=e=>{let t=(e||``).toLowerCase();return t.includes(`won`)||t.includes(`completed`)||t.includes(`done`)||t.includes(`active`)||t===`activated`?`border-l-green-500`:t.includes(`lost`)||t.includes(`cancelled`)||t.includes(`rejected`)||t===`expired`||t===`terminated`?`border-l-red-500`:t.includes(`negotiation`)||t.includes(`review`)||t.includes(`in progress`)||t.includes(`approval`)?`border-l-yellow-500`:t.includes(`proposal`)||t.includes(`pending`)?`border-l-blue-500`:t.includes(`qualification`)||t.includes(`qualified`)?`border-l-indigo-500`:t.includes(`prospecting`)||t.includes(`new`)||t.includes(`open`)?`border-l-purple-500`:t===`draft`||t.includes(`draft`)?`border-l-slate-400`:`border-l-gray-300`},l=e=>{let t=e.toLowerCase();return r.some(e=>t.includes(e))?`amount`:i.some(e=>t.includes(e))?`stage`:a.some(e=>t.includes(e))?`date`:o.some(e=>t.includes(e))?`percent`:`other`};return(0,q.jsxs)(q.Fragment,{children:[(0,q.jsx)(`div`,{className:`space-y-2 p-2`,children:C.map((t,r)=>{let i=e.slice(1,5),a=i.find(e=>l(e.accessorKey)===`amount`),o=i.find(e=>l(e.accessorKey)===`stage`),u=i.filter(e=>l(e.accessorKey)===`date`),d=i.filter(e=>l(e.accessorKey)===`percent`),f=i.filter(e=>e!==a&&e!==o&&!u.includes(e)&&!d.includes(e)),p=o?String(t[o.accessorKey]??``):``,m=p?c(p):``;return(0,q.jsxs)(`div`,{className:[`border rounded-lg p-2.5 bg-card hover:bg-accent/50 cursor-pointer transition-colors touch-manipulation`,m?`border-l-[3px] ${m}`:``].filter(Boolean).join(` `),onClick:()=>X.handleClick(t),children:[n&&(0,q.jsx)(`div`,{className:`font-semibold text-sm truncate mb-1`,children:t[n.accessorKey]!=null&&typeof t[n.accessorKey]==`object`?String(t[n.accessorKey]):t[n.accessorKey]??`—`}),(a||o)&&(0,q.jsxs)(`div`,{className:`flex items-center justify-between gap-2 mb-1`,children:[a&&(0,q.jsx)(`span`,{className:`text-sm tabular-nums font-medium`,children:typeof t[a.accessorKey]==`number`?He(t[a.accessorKey]):t[a.accessorKey]!=null&&typeof t[a.accessorKey]==`object`?String(t[a.accessorKey]):t[a.accessorKey]??`—`}),o&&t[o.accessorKey]&&(0,q.jsx)(A,{variant:`outline`,className:`text-xs shrink-0 max-w-[140px] truncate ${s(String(t[o.accessorKey]))}`,children:String(t[o.accessorKey])})]}),(u.length>0||d.length>0)&&(0,q.jsxs)(`div`,{className:`flex items-center justify-between py-0.5 text-xs text-muted-foreground`,children:[u[0]&&(0,q.jsx)(`span`,{className:`tabular-nums`,children:t[u[0].accessorKey]?P(t[u[0].accessorKey],`short`):`—`}),d[0]&&t[d[0].accessorKey]!=null&&(0,q.jsx)(`span`,{className:`tabular-nums`,children:Ge(Number(t[d[0].accessorKey]))})]}),u.slice(1).map(e=>(0,q.jsxs)(`div`,{className:`flex justify-between items-center py-0.5`,children:[(0,q.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:e.header}),(0,q.jsx)(`span`,{className:`text-xs text-muted-foreground tabular-nums`,children:t[e.accessorKey]?P(t[e.accessorKey],`short`):`—`})]},e.accessorKey)),f.map(e=>{let n=t[e.accessorKey];return n==null||n===``?null:(0,q.jsxs)(`div`,{className:`flex justify-between items-center py-0.5`,children:[(0,q.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:e.header}),(0,q.jsx)(`span`,{className:`text-xs font-medium truncate ml-2 text-right`,children:e.cell?e.cell(n,t):String(n)})]},e.accessorKey)})]},t.id||t._id||r)})}),X.isOverlay&&(0,q.jsx)(ae,{...X,title:rn,children:e=>(0,q.jsx)(`div`,{className:`space-y-3`,children:Object.entries(e).map(([e,t])=>(0,q.jsxs)(`div`,{className:`flex flex-col`,children:[(0,q.jsx)(`span`,{className:`text-xs font-medium text-muted-foreground uppercase tracking-wide`,children:e.replace(/_/g,` `)}),(0,q.jsx)(`span`,{className:`text-sm`,children:String(t??`—`)})]},e))})})]})}let an=()=>{I(e=>e===`compact`?`short`:e===`short`?`medium`:e===`medium`?`tall`:e===`tall`?`extra_tall`:`compact`)},on={compact:Re,short:Pe,medium:Te,tall:le,extra_tall:le}[F],sn=e.rowHeight!==void 0&&!e.hideRowHeightToggle,cn=e.exportOptions||sn?(0,q.jsxs)(`div`,{className:`flex items-center justify-end gap-1 px-2 py-1`,children:[sn&&(0,q.jsxs)(B,{variant:`ghost`,size:`sm`,className:`h-7 px-2 text-muted-foreground hover:text-primary text-xs`,onClick:an,title:`Row height: ${F}`,children:[(0,q.jsx)(on,{className:`h-3.5 w-3.5 mr-1.5`}),(0,q.jsx)(`span`,{className:`hidden sm:inline capitalize`,children:F})]}),e.exportOptions&&(0,q.jsxs)(ye,{open:he,onOpenChange:_e,children:[(0,q.jsx)(h,{asChild:!0,children:(0,q.jsxs)(B,{variant:`ghost`,size:`sm`,className:`h-7 px-2 text-muted-foreground hover:text-primary text-xs`,children:[(0,q.jsx)(Ve,{className:`h-3.5 w-3.5 mr-1.5`}),(0,q.jsx)(`span`,{className:`hidden sm:inline`,children:E(`grid.export`)})]})}),(0,q.jsx)(oe,{align:`end`,className:`w-48 p-2`,children:(0,q.jsx)(`div`,{className:`space-y-1`,children:(e.exportOptions.formats||[`csv`,`json`]).map(e=>(0,q.jsxs)(B,{variant:`ghost`,size:`sm`,className:`w-full justify-start h-8 text-xs`,onClick:()=>yt(e),children:[(0,q.jsx)(Ve,{className:`h-3.5 w-3.5 mr-2`}),E(`grid.exportAs`,{format:e.toUpperCase()})]},e))})})]})]}):null,ln=e=>{let t=[`_id`,`id`,`created_at`,`updated_at`,`created_by`,`updated_by`],n=Object.entries(e),r=e=>k?.fields?.[e]?.hidden===!0,i=n.filter(([e])=>!t.includes(e)&&!r(e)),a=n.filter(([e])=>t.includes(e)&&e!==`_id`&&e!==`id`),o=e=>e.charAt(0).toUpperCase()+e.slice(1).replace(/_/g,` `),s=(e,t)=>{if(t==null||t===``)return(0,q.jsx)(`span`,{className:`text-muted-foreground/50 text-sm italic`,children:E(`grid.empty`)});let n=k?.fields?.[e];if(n?.type){let e=je(n.type);if(e)return(0,q.jsx)(e,{value:t,field:n})}return typeof t==`boolean`?(0,q.jsx)(A,{variant:t?`default`:`outline`,children:E(t?`grid.yes`:`grid.no`)}):typeof t==`string`&&!isNaN(Date.parse(t))&&(e.includes(`date`)||e.includes(`_at`)||e.includes(`time`))?(0,q.jsx)(`span`,{className:`text-sm tabular-nums`,children:P(t)}):typeof t==`number`&&[`amount`,`price`,`total`,`revenue`,`cost`,`value`,`budget`,`salary`].some(t=>e.toLowerCase().includes(t))?(0,q.jsx)(`span`,{className:`text-sm tabular-nums font-medium`,children:De(t)}):(0,q.jsx)(`span`,{className:`text-sm break-words`,children:String(t)})};return(0,q.jsxs)(`div`,{className:`space-y-4`,"data-testid":`record-detail-panel`,children:[(0,q.jsx)(`div`,{className:`rounded-lg border bg-card`,children:(0,q.jsx)(`div`,{className:`divide-y`,children:i.map(([e,t])=>(0,q.jsxs)(`div`,{className:`flex flex-col sm:flex-row sm:items-start gap-1 sm:gap-4 px-4 py-3`,children:[(0,q.jsx)(`span`,{className:`text-xs font-medium text-muted-foreground sm:w-1/3 sm:text-right sm:pt-0.5 uppercase tracking-wide shrink-0`,children:o(e)}),(0,q.jsx)(`div`,{className:`flex-1 min-w-0`,children:s(e,t)})]},e))})}),a.length>0&&(0,q.jsxs)(`div`,{className:`rounded-lg border bg-muted/30`,children:[(0,q.jsx)(`div`,{className:`px-4 py-2 border-b`,children:(0,q.jsx)(`span`,{className:`text-xs font-medium text-muted-foreground uppercase tracking-wide`,children:E(`grid.systemFields`)})}),(0,q.jsx)(`div`,{className:`divide-y divide-border/50`,children:a.map(([e,t])=>(0,q.jsxs)(`div`,{className:`flex items-center gap-4 px-4 py-2`,children:[(0,q.jsx)(`span`,{className:`text-xs text-muted-foreground w-1/3 text-right shrink-0`,children:o(e)}),(0,q.jsx)(`span`,{className:`text-xs text-muted-foreground flex-1 min-w-0 break-words`,children:String(t??``)})]},e))})]})]})},un=gt?(0,q.jsx)(`div`,{className:`border-t bg-muted/30 px-2 py-1.5`,"data-testid":`column-summary-footer`,children:(0,q.jsx)(`div`,{className:`flex gap-4 text-xs text-muted-foreground font-medium`,children:Ht.filter(e=>ft.has(e.accessorKey)).map(e=>{let t=ft.get(e.accessorKey);return(0,q.jsxs)(`span`,{"data-testid":`summary-${e.accessorKey}`,children:[e.header,`: `,t.label]},e.accessorKey)})})}):null,dn=(t,n)=>{let r=k?.fields?.[t],i=e.objectName?D(e.objectName,t,r?.label||t):r?.label||t,a,o=r?.type;if(o===`select`||o===`status`){let i=r?.options?O(e.objectName,t,r.options):void 0,o=Array.isArray(i)?i.find(e=>String(e.label)===n||String(e.value)===n):void 0;a=xe(o?.color,o?.value??n)}return{fieldLabel:i,labelColorClass:a}},fn=e=>{let{fieldLabel:t,labelColorClass:n}=dn(e.field,e.label);return(0,q.jsx)(`div`,{children:(0,q.jsx)(ot,{groupKey:e.key,label:e.label,count:e.rows.length,collapsed:e.collapsed,aggregations:e.aggregations,fieldLabel:e.depth===0?t:void 0,labelColorClass:n,onToggle:dt,children:e.subgroups.length>0?(0,q.jsx)(`div`,{className:`space-y-4 mt-2`,children:e.subgroups.map(fn)}):(0,q.jsx)(s,{schema:nn(e.rows)})})},e.key)},pn=lt?(0,q.jsx)(`div`,{className:`space-y-4 px-3 sm:px-4 pt-2 pb-4`,children:ct.map(fn)}):(0,q.jsxs)(q.Fragment,{children:[(0,q.jsx)(s,{schema:tn}),un]}),mn=(0,q.jsx)(te,{open:ve,onOpenChange:M,job:N,filename:`${e.exportOptions?.fileNamePrefix||e.objectName||`export`}.${N.progress?.format||`csv`}`,closeAfterDownloadMs:400}),hn=(0,q.jsx)(_t,{def:Oe,rows:Ae,open:!!Oe,onClose:Zt,dataSource:t,resource:e.objectName??``});return X.isOverlay&&X.mode===`split`?(0,q.jsxs)(q.Fragment,{children:[(0,q.jsx)(ae,{...X,title:rn,mainContent:(0,q.jsxs)(q.Fragment,{children:[cn,pn,(0,q.jsx)(ht,{selectedRows:be,actions:Kt??[],actionDefs:Gt,onAction:Xt,onActionDef:$,onClearSelection:()=>{L([]),z(!1)},pageSize:C.length,totalMatching:we,allMatchingSelected:R,onSelectAllMatching:()=>z(!0)})]}),children:e=>ln(e)}),mn,hn]}):(0,q.jsxs)(`div`,{ref:We,className:`relative h-full`,children:[(0,q.jsx)(g,{active:ne&&C.length>0}),qe>0&&(0,q.jsx)(`div`,{className:`flex items-center justify-center text-xs text-muted-foreground`,style:{height:qe},children:E(Ke?`grid.refreshing`:`grid.pullToRefresh`)}),cn,pn,(0,q.jsx)(ht,{selectedRows:be,actions:Kt??[],actionDefs:Gt,onAction:Xt,onActionDef:$,onClearSelection:()=>{L([]),z(!1)},pageSize:C.length,totalMatching:we,allMatchingSelected:R,onSelectAllMatching:()=>z(!0)}),X.isOverlay&&(0,q.jsx)(ae,{...X,title:rn,children:e=>ln(e)}),mn,hn]})},Et=e(r(),1);function Dt(e,t,n){let r=Array(e);return new Proxy(r,{get(r,i,a){if(typeof i==`string`){let a=i.charCodeAt(0);if(a>=48&&a<=57){let a=+i;if(Number.isInteger(a)&&a>=0&&a<e){let e=r[a];if(!e){let i=t[a*2];e=r[a]={index:a,key:n(a),start:i,size:t[a*2+1],end:i+t[a*2+1],lane:0}}return e}}if(i===`length`)return e}return Reflect.get(r,i,a)}})}function Q(e,t,n){let r=n.initialDeps??[],i,a=!0;function o(){let o=e();return o.length!==r.length||o.some((e,t)=>r[t]!==e)?(r=o,i=t(...o),n?.onChange&&!(a&&n.skipInitialOnChange)&&n.onChange(i),a=!1,i):i}return o.updateDeps=e=>{r=e},o}function Ot(e,t){if(e===void 0)throw Error(`Unexpected undefined${t?`: ${t}`:``}`);return e}var kt=(e,t)=>Math.abs(e-t)<1.01,At=(e,t,n)=>{let r;return function(...i){e.clearTimeout(r),r=e.setTimeout(()=>t.apply(this,i),n)}},jt,Mt=()=>{if(jt!==void 0)return jt;if(typeof navigator>`u`)return jt=!1;if(/iP(hone|od|ad)/.test(navigator.userAgent))return jt=!0;let e=navigator.maxTouchPoints;return jt=navigator.platform===`MacIntel`&&e!==void 0&&e>0},Nt=e=>{let{offsetWidth:t,offsetHeight:n}=e;return{width:t,height:n}},Pt=e=>e,Ft=e=>{let t=Math.max(e.startIndex-e.overscan,0),n=Math.min(e.endIndex+e.overscan,e.count-1)-t+1,r=Array(n);for(let e=0;e<n;e++)r[e]=t+e;return r},It=(e,t)=>{let n=e.scrollElement;if(!n)return;let r=e.targetWindow;if(!r)return;let i=e=>{let{width:n,height:r}=e;t({width:Math.round(n),height:Math.round(r)})};if(i(Nt(n)),!r.ResizeObserver)return()=>{};let a=new r.ResizeObserver(t=>{let r=()=>{let e=t[0];if(e?.borderBoxSize){let t=e.borderBoxSize[0];if(t){i({width:t.inlineSize,height:t.blockSize});return}}i(Nt(n))};e.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(r):r()});return a.observe(n,{box:`border-box`}),()=>{a.unobserve(n)}},Lt={passive:!0},Rt=typeof window>`u`?!0:`onscrollend`in window,zt=(e,t,n)=>{let r=e.scrollElement;if(!r)return;let i=e.targetWindow;if(!i)return;let a=e.options.useScrollendEvent&&Rt,o=0,s=a?null:At(i,()=>t(o,!1),e.options.isScrollingResetDelay),c=e=>()=>{o=n(r),s?.(),t(o,e)},l=c(!0),u=c(!1);return r.addEventListener(`scroll`,l,Lt),a&&r.addEventListener(`scrollend`,u,Lt),()=>{r.removeEventListener(`scroll`,l),a&&r.removeEventListener(`scrollend`,u)}},Bt=(e,t)=>zt(e,t,t=>{let{horizontal:n,isRtl:r}=e.options;return n?t.scrollLeft*(r&&-1||1):t.scrollTop}),Vt=(e,t,n)=>{if(t?.borderBoxSize){let e=t.borderBoxSize[0];if(e)return Math.round(e[n.options.horizontal?`inlineSize`:`blockSize`])}return e[n.options.horizontal?`offsetWidth`:`offsetHeight`]},Ht=(e,{adjustments:t=0,behavior:n},r)=>{var i,a;(a=(i=r.scrollElement)?.scrollTo)==null||a.call(i,{[r.options.horizontal?`left`:`top`]:e+t,behavior:n})},Ut=class{constructor(e){this.unsubs=[],this.scrollElement=null,this.targetWindow=null,this.isScrolling=!1,this.scrollState=null,this.measurementsCache=[],this._flatMeasurements=null,this.itemSizeCache=new Map,this.itemSizeCacheVersion=0,this.laneAssignments=new Map,this.pendingMin=null,this.prevLanes=void 0,this.lanesChangedFlag=!1,this.lanesSettling=!1,this.scrollRect=null,this.scrollOffset=null,this.scrollDirection=null,this.scrollAdjustments=0,this._iosDeferredAdjustment=0,this._iosTouching=!1,this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._intendedScrollOffset=null,this.elementsCache=new Map,this.now=()=>{var e;return((e=this.targetWindow?.performance)?.now)?.call(e)??Date.now()},this.observer=(()=>{let e=null,t=()=>e||(!this.targetWindow||!this.targetWindow.ResizeObserver?null:e=new this.targetWindow.ResizeObserver(e=>{e.forEach(e=>{let t=()=>{let t=e.target,n=this.indexFromElement(t);if(!t.isConnected){this.observer.unobserve(t);for(let[e,n]of this.elementsCache)if(n===t){this.elementsCache.delete(e);break}return}this.shouldMeasureDuringScroll(n)&&this.resizeItem(n,this.options.measureElement(t,e,this))};this.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(t):t()})}));return{disconnect:()=>{var n;(n=t())==null||n.disconnect(),e=null},observe:e=>t()?.observe(e,{box:`border-box`}),unobserve:e=>t()?.unobserve(e)}})(),this.range=null,this.setOptions=e=>{let t={debug:!1,initialOffset:0,overscan:1,paddingStart:0,paddingEnd:0,scrollPaddingStart:0,scrollPaddingEnd:0,horizontal:!1,getItemKey:Pt,rangeExtractor:Ft,onChange:()=>{},measureElement:Vt,initialRect:{width:0,height:0},scrollMargin:0,gap:0,indexAttribute:`data-index`,initialMeasurementsCache:[],lanes:1,isScrollingResetDelay:150,enabled:!0,isRtl:!1,useScrollendEvent:!1,useAnimationFrameWithResizeObserver:!1,laneAssignmentMode:`estimate`};for(let n in e){let r=e[n];r!==void 0&&(t[n]=r)}this.options=t},this.notify=e=>{var t,n;(n=(t=this.options).onChange)==null||n.call(t,this,e)},this.maybeNotify=Q(()=>(this.calculateRange(),[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]),e=>{this.notify(e)},{key:!1,debug:()=>this.options.debug,initialDeps:[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]}),this.cleanup=()=>{this.unsubs.filter(Boolean).forEach(e=>e()),this.unsubs=[],this.observer.disconnect(),this.rafId!=null&&this.targetWindow&&(this.targetWindow.cancelAnimationFrame(this.rafId),this.rafId=null),this.scrollState=null,this.scrollElement=null,this.targetWindow=null},this._didMount=()=>()=>{this.cleanup()},this._willUpdate=()=>{let e=this.options.enabled?this.options.getScrollElement():null;if(this.scrollElement!==e){if(this.cleanup(),!e){this.maybeNotify();return}if(this.scrollElement=e,this.scrollElement&&`ownerDocument`in this.scrollElement?this.targetWindow=this.scrollElement.ownerDocument.defaultView:this.targetWindow=this.scrollElement?.window??null,this.elementsCache.forEach(e=>{this.observer.observe(e)}),this.unsubs.push(this.options.observeElementRect(this,e=>{this.scrollRect=e,this.maybeNotify()})),this.unsubs.push(this.options.observeElementOffset(this,(e,t)=>{this._intendedScrollOffset!==null&&Math.abs(e-this._intendedScrollOffset)<1.5&&(e=this._intendedScrollOffset),this._intendedScrollOffset=null,this.scrollAdjustments=0,this.scrollDirection=t?this.getScrollOffset()<e?`forward`:`backward`:null,this.scrollOffset=e,this.isScrolling=t,this._flushIosDeferredIfReady(),this.scrollState&&this.scheduleScrollReconcile(),this.maybeNotify()})),`addEventListener`in this.scrollElement){let e=this.scrollElement,t=()=>{this._iosTouching=!0,this._iosJustTouchEnded=!1,this._iosTouchEndTimerId!==null&&this.targetWindow!=null&&(this.targetWindow.clearTimeout(this._iosTouchEndTimerId),this._iosTouchEndTimerId=null)},n=()=>{this._iosTouching=!1,!(!Mt()||this.targetWindow==null)&&(this._iosJustTouchEnded=!0,this._iosTouchEndTimerId=this.targetWindow.setTimeout(()=>{this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._flushIosDeferredIfReady()},150))};e.addEventListener(`touchstart`,t,Lt),e.addEventListener(`touchend`,n,Lt),this.unsubs.push(()=>{e.removeEventListener(`touchstart`,t),e.removeEventListener(`touchend`,n),this._iosTouchEndTimerId!==null&&this.targetWindow!=null&&(this.targetWindow.clearTimeout(this._iosTouchEndTimerId),this._iosTouchEndTimerId=null)})}this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})}},this._flushIosDeferredIfReady=()=>{if(this._iosDeferredAdjustment===0||this.isScrolling||this._iosTouching||this._iosJustTouchEnded)return;let e=this.getScrollOffset(),t=this.getMaxScrollOffset();if(e<0||e>t)return;let n=this._iosDeferredAdjustment;this._iosDeferredAdjustment=0,this._scrollToOffset(e,{adjustments:this.scrollAdjustments+=n,behavior:void 0})},this.rafId=null,this.getSize=()=>this.options.enabled?(this.scrollRect=this.scrollRect??this.options.initialRect,this.scrollRect[this.options.horizontal?`width`:`height`]):(this.scrollRect=null,0),this.getScrollOffset=()=>this.options.enabled?(this.scrollOffset=this.scrollOffset??(typeof this.options.initialOffset==`function`?this.options.initialOffset():this.options.initialOffset),this.scrollOffset):(this.scrollOffset=null,0),this.getFurthestMeasurement=(e,t)=>{let n=new Map,r=new Map;for(let i=t-1;i>=0;i--){let t=e[i];if(n.has(t.lane))continue;let a=r.get(t.lane);if(a==null||t.end>a.end?r.set(t.lane,t):t.end<a.end&&n.set(t.lane,!0),n.size===this.options.lanes)break}return r.size===this.options.lanes?Array.from(r.values()).sort((e,t)=>e.end===t.end?e.index-t.index:e.end-t.end)[0]:void 0},this.getMeasurementOptions=Q(()=>[this.options.count,this.options.paddingStart,this.options.scrollMargin,this.options.getItemKey,this.options.enabled,this.options.lanes,this.options.laneAssignmentMode],(e,t,n,r,i,a,o)=>(this.prevLanes!==void 0&&this.prevLanes!==a&&(this.lanesChangedFlag=!0),this.prevLanes=a,this.pendingMin=null,{count:e,paddingStart:t,scrollMargin:n,getItemKey:r,enabled:i,lanes:a,laneAssignmentMode:o}),{key:!1}),this.getMeasurements=Q(()=>[this.getMeasurementOptions(),this.itemSizeCacheVersion],({count:e,paddingStart:t,scrollMargin:n,getItemKey:r,enabled:i,lanes:a,laneAssignmentMode:o},s)=>{let c=this.itemSizeCache;if(!i)return this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),[];if(this.laneAssignments.size>e)for(let t of this.laneAssignments.keys())t>=e&&this.laneAssignments.delete(t);this.lanesChangedFlag&&(this.lanesChangedFlag=!1,this.lanesSettling=!0,this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),this.pendingMin=null),this.measurementsCache.length===0&&!this.lanesSettling&&(this.measurementsCache=this.options.initialMeasurementsCache,this.measurementsCache.forEach(e=>{this.itemSizeCache.set(e.key,e.size)}));let l=this.lanesSettling?0:this.pendingMin??0;if(this.pendingMin=null,this.lanesSettling&&this.measurementsCache.length===e&&(this.lanesSettling=!1),a===1){let i=this.options.gap,a=e*2,o=this._flatMeasurements;if(!o||o.length<a){let e=new Float64Array(a);o&&l>0&&e.set(o.subarray(0,l*2)),o=e,this._flatMeasurements=o}let s;if(l===0)s=t+n;else{let e=l-1;s=o[e*2]+o[e*2+1]+i}for(let t=l;t<e;t++){let e=r(t),n=c.get(e),a=typeof n==`number`?n:this.options.estimateSize(t);o[t*2]=s,o[t*2+1]=a,s+=a+i}let u=Dt(e,o,r);return this.measurementsCache=u,u}let u=this.measurementsCache.slice(0,l),d=Array(a).fill(void 0);for(let e=0;e<l;e++){let t=u[e];t&&(d[t.lane]=e)}for(let i=l;i<e;i++){let e=r(i),a=this.laneAssignments.get(i),s,l,f=o===`estimate`||c.has(e);if(a!==void 0&&this.options.lanes>1){s=a;let e=d[s],r=e===void 0?void 0:u[e];l=r?r.end+this.options.gap:t+n}else{let e=this.options.lanes===1?u[i-1]:this.getFurthestMeasurement(u,i);l=e?e.end+this.options.gap:t+n,s=e?e.lane:i%this.options.lanes,this.options.lanes>1&&f&&this.laneAssignments.set(i,s)}let p=c.get(e),m=typeof p==`number`?p:this.options.estimateSize(i),h=l+m;u[i]={index:i,start:l,size:m,end:h,key:e,lane:s},d[s]=i}return this.measurementsCache=u,u},{key:!1,debug:()=>this.options.debug}),this.calculateRange=Q(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(e,t,n,r)=>this.range=e.length>0&&t>0?Gt({measurements:e,outerSize:t,scrollOffset:n,lanes:r,flat:r===1&&this._flatMeasurements!=null?this._flatMeasurements:null}):null,{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=Q(()=>{let e=null,t=null,n=this.calculateRange();return n&&(e=n.startIndex,t=n.endIndex),this.maybeNotify.updateDeps([this.isScrolling,e,t]),[this.options.rangeExtractor,this.options.overscan,this.options.count,e,t]},(e,t,n,r,i)=>r===null||i===null?[]:e({startIndex:r,endIndex:i,overscan:t,count:n}),{key:!1,debug:()=>this.options.debug}),this.indexFromElement=e=>{let t=this.options.indexAttribute,n=e.getAttribute(t);return n?parseInt(n,10):(console.warn(`Missing attribute name '${t}={index}' on measured element.`),-1)},this.shouldMeasureDuringScroll=e=>{if(!this.scrollState||this.scrollState.behavior!==`smooth`)return!0;let t=this.scrollState.index??this.getVirtualItemForOffset(this.scrollState.lastTargetOffset)?.index;if(t!==void 0&&this.range){let n=Math.max(this.options.overscan,Math.ceil((this.range.endIndex-this.range.startIndex)/2)),r=Math.max(0,t-n),i=Math.min(this.options.count-1,t+n);return e>=r&&e<=i}return!0},this.measureElement=e=>{if(!e){this.elementsCache.forEach((e,t)=>{e.isConnected||(this.observer.unobserve(e),this.elementsCache.delete(t))});return}let t=this.indexFromElement(e),n=this.options.getItemKey(t),r=this.elementsCache.get(n);r!==e&&(r&&this.observer.unobserve(r),this.observer.observe(e),this.elementsCache.set(n,e)),(!this.isScrolling||this.scrollState)&&this.shouldMeasureDuringScroll(t)&&this.resizeItem(t,this.options.measureElement(e,void 0,this))},this.resizeItem=(e,t)=>{if(e<0||e>=this.options.count)return;let n,r,i,a=this._flatMeasurements;if(this.options.lanes===1&&a!==null)i=this.options.getItemKey(e),r=a[e*2],n=a[e*2+1];else{let t=this.measurementsCache[e];if(!t)return;i=t.key,r=t.start,n=t.size}let o=t-(this.itemSizeCache.get(i)??n);o!==0&&(this.scrollState?.behavior!==`smooth`&&(this.shouldAdjustScrollPositionOnItemSizeChange===void 0?r<this.getScrollOffset()+this.scrollAdjustments&&this.scrollDirection!==`backward`:this.shouldAdjustScrollPositionOnItemSizeChange(this.measurementsCache[e]??{index:e,key:i,start:r,size:n,end:r+n,lane:0},o,this))&&(Mt()&&(this.isScrolling||this._iosTouching||this._iosJustTouchEnded)?this._iosDeferredAdjustment+=o:this._scrollToOffset(this.getScrollOffset(),{adjustments:this.scrollAdjustments+=o,behavior:void 0})),(this.pendingMin===null||e<this.pendingMin)&&(this.pendingMin=e),this.itemSizeCache.set(i,t),this.itemSizeCacheVersion++,this.notify(!1))},this.getVirtualItems=Q(()=>[this.getVirtualIndexes(),this.getMeasurements()],(e,t)=>{let n=[];for(let r=0,i=e.length;r<i;r++){let i=t[e[r]];n.push(i)}return n},{key:!1,debug:()=>this.options.debug}),this.getVirtualItemForOffset=e=>{let t=this.getMeasurements();if(t.length===0)return;let n=this._flatMeasurements,r=this.options.lanes===1&&n!=null;return Ot(t[Wt(0,t.length-1,r?e=>n[e*2]:e=>Ot(t[e]).start,e)])},this.getMaxScrollOffset=()=>{if(!this.scrollElement)return 0;if(`scrollHeight`in this.scrollElement)return this.options.horizontal?this.scrollElement.scrollWidth-this.scrollElement.clientWidth:this.scrollElement.scrollHeight-this.scrollElement.clientHeight;{let e=this.scrollElement.document.documentElement;return this.options.horizontal?e.scrollWidth-this.scrollElement.innerWidth:e.scrollHeight-this.scrollElement.innerHeight}},this.getOffsetForAlignment=(e,t,n=0)=>{if(!this.scrollElement)return 0;let r=this.getSize(),i=this.getScrollOffset();t===`auto`&&(t=e>=i+r?`end`:`start`),t===`center`?e+=(n-r)/2:t===`end`&&(e-=r);let a=this.getMaxScrollOffset();return Math.max(Math.min(a,e),0)},this.getOffsetForIndex=(e,t=`auto`)=>{e=Math.max(0,Math.min(e,this.options.count-1));let n=this.getSize(),r=this.getScrollOffset(),i=this.measurementsCache[e];if(!i)return;if(t===`auto`)if(i.end>=r+n-this.options.scrollPaddingEnd)t=`end`;else if(i.start<=r+this.options.scrollPaddingStart)t=`start`;else return[r,t];if(t===`end`&&e===this.options.count-1)return[this.getMaxScrollOffset(),t];let a=t===`end`?i.end+this.options.scrollPaddingEnd:i.start-this.options.scrollPaddingStart;return[this.getOffsetForAlignment(a,t,i.size),t]},this.scrollToOffset=(e,{align:t=`start`,behavior:n=`auto`}={})=>{let r=this.getOffsetForAlignment(e,t),i=this.now();this.scrollState={index:null,align:t,behavior:n,startedAt:i,lastTargetOffset:r,stableFrames:0},this._scrollToOffset(r,{adjustments:void 0,behavior:n}),this.scheduleScrollReconcile()},this.scrollToIndex=(e,{align:t=`auto`,behavior:n=`auto`}={})=>{e=Math.max(0,Math.min(e,this.options.count-1));let r=this.getOffsetForIndex(e,t);if(!r)return;let[i,a]=r,o=this.now();this.scrollState={index:e,align:a,behavior:n,startedAt:o,lastTargetOffset:i,stableFrames:0},this._scrollToOffset(i,{adjustments:void 0,behavior:n}),this.scheduleScrollReconcile()},this.scrollBy=(e,{behavior:t=`auto`}={})=>{let n=this.getScrollOffset()+e,r=this.now();this.scrollState={index:null,align:`start`,behavior:t,startedAt:r,lastTargetOffset:n,stableFrames:0},this._scrollToOffset(n,{adjustments:void 0,behavior:t}),this.scheduleScrollReconcile()},this.getTotalSize=()=>{let e=this.getMeasurements(),t;if(e.length===0)t=this.options.paddingStart;else if(this.options.lanes===1){let n=e.length-1,r=this._flatMeasurements;t=r==null?e[n]?.end??0:r[n*2]+r[n*2+1]}else{let n=Array(this.options.lanes).fill(null),r=e.length-1;for(;r>=0&&n.some(e=>e===null);){let t=e[r];n[t.lane]===null&&(n[t.lane]=t.end),r--}t=Math.max(...n.filter(e=>e!==null))}return Math.max(t-this.options.scrollMargin+this.options.paddingEnd,0)},this.takeSnapshot=()=>{let e=[];if(this.itemSizeCache.size===0)return e;let t=this.getMeasurements();for(let n of t)n&&this.itemSizeCache.has(n.key)&&e.push({index:n.index,key:n.key,start:n.start,size:n.size,end:n.end,lane:n.lane});return e},this._scrollToOffset=(e,{adjustments:t,behavior:n})=>{this._intendedScrollOffset=e+(t??0),this.options.scrollToFn(e,{behavior:n,adjustments:t},this)},this.measure=()=>{this.pendingMin=null,this.itemSizeCache.clear(),this.laneAssignments.clear(),this.itemSizeCacheVersion++,this.notify(!1)},this.setOptions(e)}scheduleScrollReconcile(){if(!this.targetWindow){this.scrollState=null;return}this.rafId??=this.targetWindow.requestAnimationFrame(()=>{this.rafId=null,this.reconcileScroll()})}reconcileScroll(){if(!this.scrollState||!this.scrollElement)return;if(this.now()-this.scrollState.startedAt>5e3){this.scrollState=null;return}let e=this.scrollState.index==null?void 0:this.getOffsetForIndex(this.scrollState.index,this.scrollState.align),t=e?e[0]:this.scrollState.lastTargetOffset,n=t!==this.scrollState.lastTargetOffset;if(!n&&kt(t,this.getScrollOffset())){if(this.scrollState.stableFrames++,this.scrollState.stableFrames>=1){this.getScrollOffset()!==t&&this._scrollToOffset(t,{adjustments:void 0,behavior:`auto`}),this.scrollState=null;return}}else if(this.scrollState.stableFrames=0,n){let e=this.getSize()||600,n=Math.abs(t-this.getScrollOffset()),r=this.scrollState.behavior===`smooth`&&n>e;this.scrollState.lastTargetOffset=t,r||(this.scrollState.behavior=`auto`),this._scrollToOffset(t,{adjustments:void 0,behavior:r?`smooth`:`auto`})}this.scheduleScrollReconcile()}},Wt=(e,t,n,r)=>{for(;e<=t;){let i=(e+t)/2|0,a=n(i);if(a<r)e=i+1;else if(a>r)t=i-1;else return i}return e>0?e-1:0};function Gt({measurements:e,outerSize:t,scrollOffset:n,lanes:r,flat:i}){let a=e.length-1,o=i?e=>i[e*2]:t=>e[t].start,s=i?e=>i[e*2]+i[e*2+1]:t=>e[t].end;if(e.length<=r)return{startIndex:0,endIndex:a};let c=Wt(0,a,o,n),l=c;if(r===1)for(;l<a&&s(l)<n+t;)l++;else if(r>1){let i=Array(r).fill(0);for(;l<a&&i.some(e=>e<n+t);){let t=e[l];i[t.lane]=t.end,l++}let o=Array(r).fill(n+t);for(;c>=0&&o.some(e=>e>=n);){let t=e[c];o[t.lane]=t.start,c--}c=Math.max(0,c-c%r),l=Math.min(a,l+(r-1-l%r))}return{startIndex:c,endIndex:l}}var Kt=typeof document<`u`?H.useLayoutEffect:H.useEffect;function qt({useFlushSync:e=!0,...t}){let n=H.useReducer(e=>e+1,0)[1],r={...t,onChange:(r,i)=>{var a;e&&i?(0,Et.flushSync)(n):n(),(a=t.onChange)==null||a.call(t,r,i)}},[i]=H.useState(()=>new Ut(r));return i.setOptions(r),Kt(()=>i._didMount(),[]),Kt(()=>i._willUpdate()),i}function Jt(e){return qt({observeElementRect:It,observeElementOffset:Bt,scrollToFn:Ht,...e})}var Yt={"grid.import.title":`Import {{object}}`,"grid.import.stepUpload":`Upload`,"grid.import.stepMapping":`Mapping`,"grid.import.stepPreview":`Preview`,"grid.import.uploadDescription":`Upload a CSV file to get started.`,"grid.import.mappingDescription":`Map CSV columns to object fields.`,"grid.import.previewDescription":`Review data before importing.`,"grid.import.dragDrop":`Drag & drop a CSV file here, or click to browse`,"grid.import.browseFiles":`Browse Files`,"grid.import.onlyCsv":`Only CSV files are supported.`,"grid.import.fileNeedsHeader":`File must contain a header row and at least one data row.`,"grid.import.mappingTemplate":`Mapping template:`,"grid.import.chooseTemplate":`Choose template…`,"grid.import.noSavedTemplates":`No saved templates`,"grid.import.noneOption":`— None —`,"grid.import.saveCurrent":`Save current`,"grid.import.templateName":`Template name`,"grid.import.save":`Save`,"grid.import.deleteTemplate":`Delete template`,"grid.import.csvColumn":`CSV Column`,"grid.import.mapsTo":`Maps To`,"grid.import.status":`Status`,"grid.import.skipColumn":`Skip column`,"grid.import.skip":`— Skip —`,"grid.import.mapped":`Mapped`,"grid.import.skipped":`Skipped`,"grid.import.rowsWithErrors":`{{count}} row(s) with errors`,"grid.import.rowsCorrected":`{{count}} row(s) corrected`,"grid.import.clickToFix":`— click a highlighted cell to fix it inline.`,"grid.import.showingRows":`Showing {{shown}} of {{total}} rows`,"grid.import.importing":`Importing… {{progress}}%`,"grid.import.importComplete":`Import Complete`,"grid.import.imported":`{{count}} imported`,"grid.import.skippedCount":`{{count}} skipped`,"grid.import.moreErrors":`…and {{count}} more errors`,"grid.import.cancel":`Cancel`,"grid.import.back":`Back`,"grid.import.next":`Next`,"grid.import.close":`Close`,"grid.import.importNRows":`Import {{count}} Rows`,"grid.import.importingProgress":`Importing…`,"grid.import.required":`Required`,"grid.import.invalidType":`Invalid {{type}}`};function Xt(e,t){if(!t)return e;let n=e;for(let[e,r]of Object.entries(t))n=n.replace(RegExp(`{{${e}}}`,`g`),String(r));return n}function $(){let e=(e,t)=>Xt(Yt[e]??e,t);try{let t=p();return t.t(`grid.import.title`)===`grid.import.title`?{t:e}:{t:(n,r)=>{let i=t.t(n,r);return i===n?e(n,r):i}}}catch{return{t:e}}}var Zt=10;function Qt(e){let t=[],n=[],r=``,i=!1;for(let a=0;a<e.length;a++){let o=e[a],s=e[a+1];i?o===`"`&&s===`"`?(r+=`"`,a++):o===`"`?i=!1:r+=o:o===`"`?i=!0:o===`,`?(n.push(r.trim()),r=``):o===`
5
- `||o===`\r`&&s===`
6
- `?(n.push(r.trim()),n.some(e=>e!==``)&&t.push(n),n=[],r=``,o===`\r`&&a++):r+=o}return n.push(r.trim()),n.some(e=>e!==``)&&t.push(n),t}function $t(e,t){if(!e)return!0;switch(t){case`number`:case`currency`:case`percent`:return!isNaN(Number(e));case`boolean`:return[`true`,`false`,`1`,`0`,`yes`,`no`].includes(e.toLowerCase());case`date`:case`datetime`:return!isNaN(Date.parse(e));default:return!0}}function en(e,t){let n={};return e.forEach((e,r)=>{let i=e.toLowerCase().replace(/[_\s-]/g,``),a=t.find(e=>{let t=e.name.toLowerCase().replace(/[_\s-]/g,``),n=e.label.toLowerCase().replace(/[_\s-]/g,``);return t===i||n===i});a&&(n[r]=a.name)}),n}function tn(){if(typeof window>`u`)return null;try{return window.localStorage}catch{return null}}function nn(e,t){if(!e)return[];try{let n=e.getItem(t);if(!n)return[];let r=JSON.parse(n);return Array.isArray(r)?r.filter(e=>e&&e.id&&e.name&&e.mapping):[]}catch{return[]}}function rn(e,t,n){if(e)try{e.setItem(t,JSON.stringify(n))}catch{}}function an(e,t){let n={};return Object.entries(t).forEach(([t,r])=>{let i=e[Number(t)];i&&(n[i.trim().toLowerCase()]=r)}),n}function on(e,t,n){let r=new Set(n.map(e=>e.name)),i={};return t.forEach((t,n)=>{let a=e.mapping[t.trim().toLowerCase()];a&&r.has(a)&&(i[n]=a)}),i}function sn(e,t,n){let r=[],i={};for(let a of t){let t=e[a.csvIdx]??``;if(a.field.required&&!t){r.push({row:n,field:a.field.name,message:`Required field is empty`});continue}if(t&&!$t(t,a.field.type)){r.push({row:n,field:a.field.name,message:`Invalid ${a.field.type} value: "${t}"`});continue}i[a.field.name]=t}return{record:i,errors:r}}var cn=({onFileLoaded:e})=>{let{t}=$(),[n,r]=(0,H.useState)(!1),[i,a]=(0,H.useState)(null),o=(0,H.useCallback)(n=>{if(a(null),!n.name.endsWith(`.csv`)){a(t(`grid.import.onlyCsv`));return}let r=new FileReader;r.onload=n=>{let r=Qt(n.target?.result);if(r.length<2){a(t(`grid.import.fileNeedsHeader`));return}e(r[0],r.slice(1))},r.readAsText(n)},[e,t]);return(0,q.jsxs)(`div`,{className:`flex flex-col items-center gap-4 py-6`,children:[(0,q.jsxs)(`div`,{className:M(`flex w-full flex-col items-center justify-center gap-3 rounded-lg border-2 border-dashed p-10 transition-colors`,n?`border-primary bg-primary/5`:`border-muted-foreground/25`),onDragOver:e=>{e.preventDefault(),r(!0)},onDragLeave:()=>r(!1),onDrop:e=>{e.preventDefault(),r(!1);let t=e.dataTransfer.files[0];t&&o(t)},children:[(0,q.jsx)(O,{className:`h-10 w-10 text-muted-foreground`}),(0,q.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:t(`grid.import.dragDrop`)}),(0,q.jsxs)(`label`,{children:[(0,q.jsx)(`input`,{type:`file`,accept:`.csv`,className:`hidden`,onChange:e=>{let t=e.target.files?.[0];t&&o(t)}}),(0,q.jsx)(B,{variant:`outline`,size:`sm`,asChild:!0,children:(0,q.jsx)(`span`,{children:t(`grid.import.browseFiles`)})})]})]}),i&&(0,q.jsxs)(`p`,{className:`flex items-center gap-1 text-sm text-destructive`,children:[(0,q.jsx)(Ee,{className:`h-4 w-4`}),` `,i]})]})},ln=({templates:e,selectedId:t,onSelect:n,onSaveAs:r,onDelete:i,disabled:a})=>{let{t:o}=$(),[s,c]=(0,H.useState)(``),[l,u]=(0,H.useState)(!1);return(0,q.jsxs)(`div`,{className:`mb-3 flex flex-wrap items-center gap-2 rounded-md border bg-muted/30 p-2`,"data-testid":`import-template-bar`,children:[(0,q.jsx)(we,{className:`h-4 w-4 text-muted-foreground`}),(0,q.jsx)(`span`,{className:`text-xs font-medium text-muted-foreground`,children:o(`grid.import.mappingTemplate`)}),(0,q.jsxs)(j,{value:t??`__none__`,onValueChange:e=>e!==`__none__`&&n(e),children:[(0,q.jsx)(he,{className:`h-7 w-48 text-xs`,"data-testid":`import-template-select`,children:(0,q.jsx)(T,{placeholder:e.length?o(`grid.import.chooseTemplate`):o(`grid.import.noSavedTemplates`)})}),(0,q.jsxs)(Xe,{children:[(0,q.jsx)(b,{value:`__none__`,disabled:e.length===0,children:e.length?o(`grid.import.noneOption`):o(`grid.import.noSavedTemplates`)}),e.map(e=>(0,q.jsx)(b,{value:e.id,children:e.name},e.id))]})]}),l?(0,q.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,q.jsx)(z,{value:s,onChange:e=>c(e.target.value),placeholder:o(`grid.import.templateName`),className:`h-7 w-40 text-xs`,"data-testid":`import-template-name-input`,autoFocus:!0}),(0,q.jsx)(B,{type:`button`,size:`sm`,onClick:()=>{s.trim()&&(r(s.trim()),c(``),u(!1))},disabled:!s.trim()||a,"data-testid":`import-template-confirm-save`,children:o(`grid.import.save`)}),(0,q.jsx)(B,{type:`button`,variant:`ghost`,size:`sm`,onClick:()=>{u(!1),c(``)},children:o(`grid.import.cancel`)})]}):(0,q.jsx)(B,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>u(!0),disabled:a,"data-testid":`import-template-save-btn`,children:o(`grid.import.saveCurrent`)}),t&&(0,q.jsx)(B,{type:`button`,variant:`ghost`,size:`sm`,onClick:i,"aria-label":o(`grid.import.deleteTemplate`),"data-testid":`import-template-delete-btn`,children:(0,q.jsx)(D,{className:`h-3.5 w-3.5`})})]})},un=({headers:e,fields:t,mapping:n,onMappingChange:r,templates:i,selectedTemplateId:a,onSelectTemplate:o,onSaveTemplate:s,onDeleteTemplate:c})=>{let{t:l}=$(),u=(0,H.useMemo)(()=>new Set(Object.values(n)),[n]),d=(0,H.useCallback)((e,t)=>{let i={...n};t===`__skip__`?delete i[e]:i[e]=t,r(i)},[n,r]);return(0,q.jsxs)(`div`,{children:[(0,q.jsx)(ln,{templates:i,selectedId:a,onSelect:o,onSaveAs:s,onDelete:c,disabled:Object.keys(n).length===0}),(0,q.jsx)(`div`,{className:`max-h-[420px] overflow-auto`,children:(0,q.jsxs)(We,{children:[(0,q.jsx)(qe,{children:(0,q.jsxs)(R,{children:[(0,q.jsx)(Le,{children:l(`grid.import.csvColumn`)}),(0,q.jsx)(Le,{children:l(`grid.import.mapsTo`)}),(0,q.jsx)(Le,{className:`w-24 text-center`,children:l(`grid.import.status`)})]})}),(0,q.jsx)(ke,{children:e.map((e,r)=>(0,q.jsxs)(R,{children:[(0,q.jsx)(I,{className:`font-medium`,children:e}),(0,q.jsx)(I,{children:(0,q.jsxs)(j,{value:n[r]??`__skip__`,onValueChange:e=>d(r,e),children:[(0,q.jsx)(he,{className:`h-8 w-56`,children:(0,q.jsx)(T,{placeholder:l(`grid.import.skipColumn`)})}),(0,q.jsxs)(Xe,{children:[(0,q.jsx)(b,{value:`__skip__`,children:l(`grid.import.skip`)}),t.map(e=>(0,q.jsxs)(b,{value:e.name,disabled:u.has(e.name)&&n[r]!==e.name,children:[e.label,e.required?` *`:``]},e.name))]})]})}),(0,q.jsx)(I,{className:`text-center`,children:n[r]?(0,q.jsx)(A,{variant:`default`,className:`text-xs`,children:l(`grid.import.mapped`)}):(0,q.jsx)(A,{variant:`secondary`,className:`text-xs`,children:l(`grid.import.skipped`)})})]},r))})]})})]})},dn=({headers:e,rows:t,mapping:n,fields:r,corrections:i,onCorrect:a})=>{let{t:o}=$(),s=(0,H.useMemo)(()=>Object.entries(n).map(([t,n])=>({csvIdx:Number(t),header:e[Number(t)],field:r.find(e=>e.name===n)})),[n,e,r]),c=t.slice(0,Zt),l=(0,H.useCallback)((e,t)=>{let n=i[e]?.[t];return n===void 0?c[e]?.[t]??``:n},[i,c]),u=(0,H.useMemo)(()=>c.map((e,t)=>{let n={};for(let e of s){let r=l(t,e.csvIdx);e.field.required&&!r?n[e.csvIdx]=o(`grid.import.required`):r&&!$t(r,e.field.type)&&(n[e.csvIdx]=o(`grid.import.invalidType`,{type:e.field.type}))}return n}),[c,s,l,o]),d=u.filter(e=>Object.keys(e).length>0).length,f=Object.keys(i).length;return(0,q.jsxs)(`div`,{className:`max-h-[440px] overflow-auto`,children:[(d>0||f>0)&&(0,q.jsxs)(`p`,{className:`mb-2 flex items-center gap-2 text-xs`,"data-testid":`import-preview-status`,children:[d>0&&(0,q.jsxs)(`span`,{className:`flex items-center gap-1 text-destructive`,children:[(0,q.jsx)(Ee,{className:`h-3.5 w-3.5`}),` `,o(`grid.import.rowsWithErrors`,{count:d})]}),f>0&&(0,q.jsxs)(`span`,{className:`flex items-center gap-1 text-emerald-600`,children:[(0,q.jsx)(ze,{className:`h-3.5 w-3.5`}),` `,o(`grid.import.rowsCorrected`,{count:f})]}),(0,q.jsx)(`span`,{className:`text-muted-foreground`,children:o(`grid.import.clickToFix`)})]}),(0,q.jsxs)(We,{children:[(0,q.jsx)(qe,{children:(0,q.jsxs)(R,{children:[(0,q.jsx)(Le,{className:`w-12`,children:`#`}),s.map(e=>(0,q.jsx)(Le,{children:e.field.label},e.csvIdx))]})}),(0,q.jsx)(ke,{children:c.map((e,t)=>{let n=u[t],r=Object.keys(n).length>0,o=i[t]!==void 0;return(0,q.jsxs)(R,{className:M(r&&`bg-destructive/5`,!r&&o&&`bg-emerald-50 dark:bg-emerald-950/20`),"data-testid":`import-preview-row-${t}`,children:[(0,q.jsx)(I,{className:`text-xs text-muted-foreground`,children:t+1}),s.map(e=>{let r=l(t,e.csvIdx),o=n[e.csvIdx],s=i[t]?.[e.csvIdx]!==void 0;return(0,q.jsx)(I,{className:M(o&&`text-destructive`,s&&!o&&`text-emerald-600`),title:o,children:(0,q.jsx)(z,{value:r,onChange:n=>a(t,e.csvIdx,n.target.value),className:M(`h-7 px-1 text-xs`,o&&`border-destructive`,s&&!o&&`border-emerald-500`),"data-testid":`import-preview-cell-${t}-${e.csvIdx}`,"aria-invalid":o?`true`:`false`,"aria-label":`${e.field.label} for row ${t+1}`})},e.csvIdx)})]},t)})})]}),(0,q.jsx)(`p`,{className:`mt-2 text-xs text-muted-foreground`,children:o(`grid.import.showingRows`,{shown:c.length,total:t.length})})]})},fn=({objectName:e,objectLabel:t,fields:n,dataSource:r,onComplete:i,onCancel:a,open:o,onOpenChange:s,onErrorMode:c=`skip`,templateStorageKey:l,templateStorage:u})=>{let[d,f]=(0,H.useState)(`upload`),[p,m]=(0,H.useState)([]),[h,g]=(0,H.useState)([]),[_,v]=(0,H.useState)({}),[y,b]=(0,H.useState)(!1),[te,x]=(0,H.useState)(0),[S,w]=(0,H.useState)(null),[T,ie]=(0,H.useState)({}),ae=t??e,D=(0,H.useMemo)(()=>u===void 0?tn():u,[u]),O=l??`objectui:import-templates:${e}`,[k,oe]=(0,H.useState)(()=>nn(D,O)),[le,j]=(0,H.useState)(null);(0,H.useEffect)(()=>{oe(nn(D,O))},[D,O]);let ue=(0,H.useCallback)(e=>{let t=k.find(t=>t.id===e);t&&(j(e),v(on(t,p,n)))},[k,p,n]),de=(0,H.useCallback)(e=>{let t={id:`tpl-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,6)}`,name:e,mapping:an(p,_),updatedAt:Date.now()},n=[...k,t];oe(n),j(t.id),rn(D,O,n)},[k,p,_,D,O]),fe=(0,H.useCallback)(()=>{if(!le)return;let e=k.filter(e=>e.id!==le);oe(e),j(null),rn(D,O,e)},[k,le,D,O]),me=(0,H.useCallback)((e,t,n)=>{ie(r=>{let i={...r},a={...i[e]??{}};return n===(h[e]?.[t]??``)?delete a[t]:a[t]=n,Object.keys(a).length===0?delete i[e]:i[e]=a,i})},[h]),he=(0,H.useMemo)(()=>{let e=new Set(Object.values(_));return n.filter(t=>t.required&&!e.has(t.name))},[n,_]),ge=(0,H.useCallback)((e,t)=>{m(e),g(t),v(en(e,n)),ie({}),f(`mapping`)},[n]),ve=(0,H.useCallback)(async()=>{b(!0),x(0);let t=[],a=0,o=0,s=Object.entries(_).map(([e,t])=>({csvIdx:Number(e),field:n.find(e=>e.name===t)}));for(let n=0;n<h.length;n++){let i=h[n],l=T[n],{record:u,errors:d}=sn(l?i.map((e,t)=>l[t]===void 0?e:l[t]):i,s,n+1);if(d.length>0){if(o++,t.push(...d),c===`stop`)break}else try{r?.create&&await r.create(e,u),a++}catch(e){o++;let r=e instanceof Error?e.message:`Failed to create record`;if(t.push({row:n+1,field:``,message:r}),c===`stop`)break}x(Math.round((n+1)/h.length*100))}let l={totalRows:h.length,importedRows:a,skippedRows:o,errors:t};w(l),b(!1),i?.(l)},[h,_,n,r,e,i,c,T]),ye=(0,H.useCallback)(()=>{f(`upload`),m([]),g([]),v({}),x(0),w(null),ie({}),j(null)},[]),N=(0,H.useCallback)(()=>{ye(),s?.(!1),a?.()},[ye,s,a]),{t:P}=$();return(0,q.jsx)(C,{open:o,onOpenChange:e=>{e?s?.(e):N()},children:(0,q.jsxs)(re,{className:`flex max-h-[85vh] flex-col gap-4 overflow-hidden sm:max-w-4xl`,children:[(0,q.jsxs)(Ye,{children:[(0,q.jsxs)(ee,{className:`flex items-center gap-2`,children:[(0,q.jsx)(se,{className:`h-5 w-5`}),` `,P(`grid.import.title`,{object:ae})]}),(0,q.jsxs)(E,{children:[d===`upload`&&P(`grid.import.uploadDescription`),d===`mapping`&&P(`grid.import.mappingDescription`),d===`preview`&&P(`grid.import.previewDescription`)]})]}),(0,q.jsx)(`div`,{className:`flex items-center justify-center gap-2 text-xs text-muted-foreground`,children:[`upload`,`mapping`,`preview`].map((e,t)=>(0,q.jsxs)(H.Fragment,{children:[t>0&&(0,q.jsx)(pe,{className:`h-3 w-3`}),(0,q.jsxs)(`span`,{className:M(`rounded-full px-3 py-1`,d===e?`bg-primary text-primary-foreground`:`bg-muted`),children:[t+1,`. `,P(e===`upload`?`grid.import.stepUpload`:e===`mapping`?`grid.import.stepMapping`:`grid.import.stepPreview`)]})]},e))}),(0,q.jsx)(`div`,{className:`min-h-0 flex-1 overflow-auto`,children:S?(0,q.jsxs)(`div`,{className:`flex flex-col items-center gap-3 py-4`,children:[(0,q.jsx)(ze,{className:`h-10 w-10 text-green-500`}),(0,q.jsx)(`p`,{className:`text-lg font-semibold`,children:P(`grid.import.importComplete`)}),(0,q.jsxs)(`div`,{className:`flex gap-3`,children:[(0,q.jsx)(A,{variant:`default`,children:P(`grid.import.imported`,{count:S.importedRows})}),S.skippedRows>0&&(0,q.jsx)(A,{variant:`destructive`,children:P(`grid.import.skippedCount`,{count:S.skippedRows})})]}),S.errors.length>0&&(0,q.jsxs)(`div`,{className:`max-h-32 w-full overflow-auto rounded border p-2 text-xs`,children:[S.errors.slice(0,10).map((e,t)=>(0,q.jsxs)(`p`,{className:`text-destructive`,children:[`Row `,e.row,e.field?` (${e.field})`:``,`: `,e.message]},t)),S.errors.length>10&&(0,q.jsx)(`p`,{className:`text-muted-foreground`,children:P(`grid.import.moreErrors`,{count:S.errors.length-10})})]})]}):(0,q.jsxs)(q.Fragment,{children:[d===`upload`&&(0,q.jsx)(cn,{onFileLoaded:ge}),d===`mapping`&&(0,q.jsx)(un,{headers:p,fields:n,mapping:_,onMappingChange:v,templates:k,selectedTemplateId:le,onSelectTemplate:ue,onSaveTemplate:de,onDeleteTemplate:fe}),d===`preview`&&(0,q.jsx)(dn,{headers:p,rows:h,mapping:_,fields:n,corrections:T,onCorrect:me}),y&&(0,q.jsxs)(`div`,{className:`flex flex-col gap-1`,children:[(0,q.jsx)(_e,{value:te,className:`h-2`}),(0,q.jsx)(`p`,{className:`text-center text-xs text-muted-foreground`,children:P(`grid.import.importing`,{progress:te})})]})]})}),(0,q.jsx)(ce,{className:`gap-2 sm:gap-0`,children:S?(0,q.jsx)(B,{onClick:N,children:P(`grid.import.close`)}):(0,q.jsxs)(q.Fragment,{children:[(0,q.jsxs)(B,{variant:`ghost`,onClick:N,disabled:y,children:[(0,q.jsx)(be,{className:`mr-1 h-4 w-4`}),` `,P(`grid.import.cancel`)]}),(d===`mapping`||d===`preview`)&&(0,q.jsxs)(B,{variant:`outline`,onClick:()=>f(d===`mapping`?`upload`:`mapping`),disabled:y,children:[(0,q.jsx)(ne,{className:`mr-1 h-4 w-4`}),` `,P(`grid.import.back`)]}),d===`mapping`&&(0,q.jsxs)(B,{onClick:()=>f(`preview`),disabled:Object.keys(_).length===0||he.length>0,children:[P(`grid.import.next`),` `,(0,q.jsx)(pe,{className:`ml-1 h-4 w-4`})]}),d===`preview`&&(0,q.jsx)(B,{onClick:ve,disabled:y,children:y?P(`grid.import.importingProgress`):P(`grid.import.importNRows`,{count:h.length})})]})})]})})},pn=t({ImportWizard:()=>fn,ObjectGrid:()=>Z,ObjectGridRenderer:()=>mn}),mn=({schema:e,...t})=>{let{dataSource:n}=o()||{};return(0,q.jsx)(Z,{schema:e,dataSource:n,...t})};m.register(`object-grid`,mn,{namespace:`plugin-grid`,label:`Object Grid`,category:`plugin`,inputs:[{name:`objectName`,type:`string`,label:`Object Name`,required:!0},{name:`columns`,type:`array`,label:`Columns`},{name:`filters`,type:`array`,label:`Filters`}]}),m.register(`grid`,mn,{namespace:`view`,label:`Data Grid`,category:`view`,inputs:[{name:`objectName`,type:`string`,label:`Object Name`,required:!0},{name:`columns`,type:`array`,label:`Columns`},{name:`filters`,type:`array`,label:`Filters`}]}),m.register(`import-wizard`,({schema:e,...t})=>{let{dataSource:n}=o()||{};return(0,q.jsx)(fn,{objectName:e.objectName,objectLabel:e.objectLabel,fields:e.fields??[],dataSource:n,...t})},{namespace:`plugin-grid`,label:`Import Wizard`,category:`plugin`,inputs:[{name:`objectName`,type:`string`,label:`Object Name`,required:!0},{name:`fields`,type:`array`,label:`Fields`,required:!0}]});export{Ze as a,Qe as i,Jt as n,Z as r,pn as t};
@@ -1,59 +0,0 @@
1
- import{o as e,r as t}from"./rolldown-runtime-CMxvf4Kt.js";import{g as n,r}from"./vendor-react-CIpZOxG3.js";import{$ as i,L as a,et as o,ut as s,z as c}from"./framework-ClI3DbWX.js";import{n as l}from"./vendor-i18n-CnFu8bdi.js";import{$ as u,$i as d,At as f,Bn as p,Bo as m,Fn as h,Gn as g,In as _,Jn as v,Kn as y,Ko as b,Ln as x,Na as S,Nr as C,Qn as w,Rn as T,Si as E,To as D,V as O,Vn as k,Xn as A,Yn as j,Zo as M,_o as N,en as P,es as F,et as I,fa as L,fi as ee,in as R,jr as z,l as B,li as te,m as ne,mr as V,nt as H,oi as re,qa as ie,qn as U,ro as ae,tt as oe,vi as se,w as ce,wi as W,yo as le,zn as ue}from"./ui-components-ZN8XdmwJ.js";import{r as de}from"./plugin-grid-DtceFt_J.js";var G=e(n(),1),K=r(),fe=({schema:e})=>{let{title:t,description:n,data:r,columns:i}=e;e.chart?.type;let a=!!e.chart;return(0,K.jsxs)(y,{className:`h-full flex flex-col ${e.className||``}`,children:[(0,K.jsxs)(j,{children:[t&&(0,K.jsx)(A,{children:t}),n&&(0,K.jsx)(v,{children:n})]}),(0,K.jsxs)(U,{className:`flex-1 overflow-auto space-y-4`,children:[a&&(()=>{let t=e.chart?.type,n=t?s.get(t):null;return n||=s.get(`chart`),n?(0,K.jsx)(`div`,{className:`min-h-[300px] border rounded-lg p-4 bg-background/50`,children:(0,K.jsx)(n,{schema:{...e.chart,data:e.chart.data||r}})}):(0,K.jsxs)(`div`,{className:`min-h-[100px] border rounded-md p-4 bg-muted/20 text-muted-foreground flex items-center justify-center`,children:[`Unknown component type: `,t||`chart`]})})(),r&&r.length>0&&(0,K.jsx)(`div`,{className:`border rounded-lg`,children:(()=>{let e=s.get(`grid`)||s.get(`table`);return e?(0,K.jsx)(e,{schema:{type:`grid`,rowData:r,columnDefs:i,domLayout:`autoHeight`}}):(0,K.jsx)(`div`,{className:`overflow-x-auto`,children:(0,K.jsxs)(`table`,{className:`w-full text-sm text-left`,children:[(0,K.jsx)(`thead`,{className:`text-xs uppercase bg-muted`,children:(0,K.jsx)(`tr`,{children:i?.map(e=>(0,K.jsx)(`th`,{className:`px-6 py-3`,children:e.headerName||e.label||e.field},e.field))})}),(0,K.jsx)(`tbody`,{children:r.map((e,t)=>(0,K.jsx)(`tr`,{className:`bg-background border-b`,children:i?.map(t=>(0,K.jsx)(`td`,{className:`px-6 py-4`,children:e[t.field]},t.field))},t))})]})})})()})]})]})};function q(e){return e.aggregate?`${e.field}__${e.aggregate}`:e.field}function pe(e,t){if(e==null)return null;let n=e instanceof Date?e:new Date(String(e));if(Number.isNaN(n.getTime()))return null;let r=n.getUTCFullYear(),i=n.getUTCMonth(),a=n.getUTCDate();switch(t){case`year`:return String(r);case`quarter`:return`${r}-Q${Math.floor(i/3)+1}`;case`month`:return`${r}-${String(i+1).padStart(2,`0`)}`;case`week`:{let e=new Date(Date.UTC(r,i,a)),t=e.getUTCDay()||7;e.setUTCDate(e.getUTCDate()+4-t);let n=new Date(Date.UTC(e.getUTCFullYear(),0,1)),o=Math.ceil(((e.getTime()-n.getTime())/864e5+1)/7);return`${e.getUTCFullYear()}-W${String(o).padStart(2,`0`)}`}case`day`:return`${r}-${String(i+1).padStart(2,`0`)}-${String(a).padStart(2,`0`)}`;default:return String(e)}}function J(e,t){let n=e[t.field];return t.dateGranularity?pe(n,t.dateGranularity)??`(empty)`:n==null||n===``?`(empty)`:String(n)}function Y(e,t){let n={};for(let r of t){if(!r.aggregate){let t=e.find(e=>e[r.field]!=null);n[q(r)]=t?t[r.field]:null;continue}let t=e.map(e=>e[r.field]);switch(r.aggregate){case`count`:n[q(r)]=t.length;break;case`unique`:{let e=new Set;for(let n of t)n!=null&&e.add(n);n[q(r)]=e.size;break}case`sum`:{let e=0;for(let n of t)e+=Number(n)||0;n[q(r)]=e;break}case`avg`:{let e=0,i=0;for(let n of t){if(n==null||n===``)continue;let t=Number(n);Number.isNaN(t)||(e+=t,i+=1)}n[q(r)]=i===0?null:e/i;break}case`min`:{let e=null;for(let n of t){if(n==null)continue;let t=Number(n);Number.isNaN(t)||(e===null||t<e)&&(e=t)}n[q(r)]=e;break}case`max`:{let e=null;for(let n of t){if(n==null)continue;let t=Number(n);Number.isNaN(t)||(e===null||t>e)&&(e=t)}n[q(r)]=e;break}default:n[q(r)]=null}}return n}function me(e,t,n,r={},i=[]){if(t.length===0)return[];let[a,...o]=t,s=new Map;for(let t of e){let e=J(t,a),n=s.get(e);n||(n=[],s.set(e,n)),n.push(t)}let c=[];for(let[e,t]of s){let s={...r,[a.field]:e},l=[...i,e],u=Y(t,n),d=o.length>0?me(t,o,n,s,l):void 0;c.push({groupKey:s,groupPath:l,values:u,count:t.length,children:d})}let l=a.sort===`desc`?-1:1;return c.sort((e,t)=>{let n=String(e.groupPath[e.groupPath.length-1]),r=String(t.groupPath[t.groupPath.length-1]);return n.localeCompare(r)*l}),typeof a.limit==`number`&&a.limit>0?c.slice(0,a.limit):c}function he(e,t,n,r){let i=ge(e,n),a=ge(e,r),o={},s={},c={};for(let c of i){o[c.id]={};let i=_e(e,c.key,n);s[c.id]=Y(i,t);for(let e of a){let n=_e(i,e.key,r);n.length!==0&&(o[c.id][e.id]=Y(n,t))}}for(let n of a){let i=_e(e,n.key,r);c[n.id]=Y(i,t)}return{rowHeaders:i,colHeaders:a,cells:o,rowTotals:s,colTotals:c,grandTotal:Y(e,t),columns:t,downGroupings:n,acrossGroupings:r}}function ge(e,t){if(t.length===0)return[{key:{},path:[],id:``}];let n=new Map;for(let r of e){let e=[],i={};for(let n of t){let t=J(r,n);e.push(t),i[n.field]=t}let a=e.join(``);n.has(a)||n.set(a,{key:i,path:e,id:a})}let r=Array.from(n.values());r.sort((e,n)=>{for(let r=0;r<t.length;r++){let i=t[r].sort===`desc`?-1:1,a=e.path[r].localeCompare(n.path[r])*i;if(a!==0)return a}return 0});let i=t[0].limit;if(typeof i==`number`&&i>0){let e=new Set;for(let t of r)e.size>=i&&!e.has(t.path[0])||e.add(t.path[0]);return r.filter(t=>e.has(t.path[0]))}return r}function _e(e,t,n){let r=Object.entries(t);if(r.length===0)return e;let i=new Map;for(let e of n)i.set(e.field,e);return e.filter(e=>{for(let[t,n]of r){let r=i.get(t);if((r?J(e,r):e[t]==null?`(null)`:String(e[t]))!==String(n))return!1}return!0})}function ve(e,t){let n={};for(let r of t){if(!r.aggregate)continue;let t=q(r),i=0,a=0,o=null,s=null;for(let n of e){let e=n[t];typeof e==`number`&&(i+=e,a+=1,(o==null||e<o)&&(o=e),(s==null||e>s)&&(s=e))}r.aggregate===`min`?n[t]=o:r.aggregate===`max`?n[t]=s:r.aggregate===`avg`?n[t]=a===0?null:i/a:n[t]=i}return n}function ye(e,t,n,r){let i=be(e,n),a=be(e,r),o={},s={},c={};for(let n of i){o[n.id]={};let r=e.filter(e=>xe(e,n.key));s[n.id]=ve(r,t);for(let e of a){let i=r.filter(t=>xe(t,e.key));if(i.length===0)continue;let a={};for(let e of t){if(!e.aggregate)continue;let t=q(e);a[t]=i[0][t]}o[n.id][e.id]=a}}for(let n of a){let r=e.filter(e=>xe(e,n.key));c[n.id]=ve(r,t)}return{rowHeaders:i,colHeaders:a,cells:o,rowTotals:s,colTotals:c,grandTotal:ve(e,t),columns:t,downGroupings:n,acrossGroupings:r}}function be(e,t){if(t.length===0)return[{key:{},path:[],id:``}];let n=new Map;for(let r of e){let e=[],i={};for(let n of t){let t=r[n.field],a=t==null?`(null)`:String(t);e.push(a),i[n.field]=a}let a=e.join(``);n.has(a)||n.set(a,{key:i,path:e,id:a})}let r=Array.from(n.values());return r.sort((e,n)=>{for(let r=0;r<t.length;r++){let i=t[r].sort===`desc`?-1:1,a=e.path[r].localeCompare(n.path[r])*i;if(a!==0)return a}return 0}),r}function xe(e,t){for(let[n,r]of Object.entries(t))if((e[n]==null?`(null)`:String(e[n]))!==String(r))return!1;return!0}function X(e,t){let n=e&&Object.keys(e).length>0,r=t&&Object.keys(t).length>0;if(n&&r)return{$and:[e,t]};if(n)return e;if(r)return t}function Se(e){let t=new Set;for(let n of e.groupingsDown??[])t.add(n.field);for(let n of e.groupingsAcross??[])t.add(n.field);for(let n of e.columns??[])t.add(n.field);for(let n of e.sort??[])t.add(n.field);return Array.from(t)}function Ce(e,t,n){let r=[...e.groupingsDown??[],...e.groupingsAcross??[]],i=(e.columns??[]).filter(e=>!!e.aggregate);if(r.length===0&&i.length===0)return null;let a=r.map(e=>e.dateGranularity?{field:e.field,dateGranularity:e.dateGranularity}:e.field),o=i.map(e=>({function:e.aggregate===`unique`?`count_distinct`:e.aggregate,field:e.field,alias:q(e)})),s=X(e.filter,t),c={object:e.objectName,limit:n};return a.length>0&&(c.groupBy=a),o.length>0&&(c.aggregations=o),s&&(c.where=s),c}function we(e,t,n){for(let[r,i]of Object.entries(t)){let t=n.find(e=>e.field===r);if((t?J(e,t):String(e[r]??`(empty)`))!==String(i))return!1}return!0}var Z=[];function Te(e,t={}){let{dataSource:n,runtimeFilter:r,maxRows:i=5e3,enabled:a=!0,rows:o,preferServerAggregation:s=!0}=t,[c,l]=(0,G.useState)(o??Z),[u,d]=(0,G.useState)(!1),[f,p]=(0,G.useState)(()=>o?!1:!!(e&&a&&n)),[m,h]=(0,G.useState)(null),g=(0,G.useRef)(0),_=(0,G.useCallback)(async()=>{if(!e||!a)return;if(o){l(o),d(!1);return}if(!n){l(Z);return}let t=++g.current;p(!0),h(null);try{let a=s?Ce(e,r,i):null;if(a&&typeof n.aggregate==`function`)try{let r=Ee(await n.aggregate(e.objectName,a));if(t!==g.current)return;l(r),d(!0);return}catch(e){typeof console<`u`&&console.warn&&console.warn(`[useReportData] dataSource.aggregate() failed, falling back to find():`,e)}if(typeof n.find!=`function`){l(Z),d(!1);return}let o=X(e.filter,r),c=Se(e),u={$top:i};o&&(u.$filter=o),c.length>0&&(u.$select=c),e.sort&&e.sort.length>0&&(u.$orderBy=e.sort.map(e=>`${e.field} ${e.direction??`asc`}`).join(`,`));let f=Ee(await n.find(e.objectName,u));if(t!==g.current)return;l(f),d(!1)}catch(e){if(t!==g.current)return;h(e instanceof Error?e:Error(String(e))),l(Z),d(!1)}finally{t===g.current&&p(!1)}},[e,a,o,n,r,i,s]);(0,G.useEffect)(()=>{_()},[_]);let{rows:v,totals:y,pivot:b}=(0,G.useMemo)(()=>{if(!e)return{rows:[],totals:{},pivot:null};let t=e.groupingsDown??[],n=e.groupingsAcross??[],r=e.columns??[],i=n.length>0;if(u){let e=[...t,...n],a=c.map(t=>{let n={},r=[];for(let i of e){let e=t[i.field];n[i.field]=e,r.push(e==null?`(null)`:String(e))}let i={...t};for(let t of e)delete i[t.field];return{groupKey:n,groupPath:r,values:i,count:1}}),o=ve(c,r),s=i?ye(c,r,t,n):null;return{rows:i&&s?s.rowHeaders.map(e=>({groupKey:e.key,groupPath:e.path,values:s.rowTotals[e.id]??{},count:1})):a,totals:o,pivot:s}}let a=i?t:[...t,...n];return{rows:a.length>0?me(c,a,r):c.map(e=>({groupKey:{},groupPath:[],values:r.length>0?Y([e],r):{...e},count:1})),totals:Y(c,r),pivot:i?he(c,r,t,n):null}},[e,c,u]);return{rows:v,rawRows:c,totals:y,pivot:b,serverAggregated:u,loading:f,error:m,refetch:_,drillDown:(0,G.useCallback)(t=>{if(!e)return[];let n=[...e.groupingsDown??[],...e.groupingsAcross??[]];return c.filter(e=>we(e,t,n))},[e,c])}}function Ee(e){if(Array.isArray(e))return e;if(e&&typeof e==`object`){let t=e;if(Array.isArray(t.data))return t.data;if(Array.isArray(t.records))return t.records;if(Array.isArray(t.results))return t.results;if(Array.isArray(t.value))return t.value}return Z}function De(e){return e.aggregate?`${e.field}__${e.aggregate}`:e.field}function Oe(e){let t=[],n=e=>{e.children&&e.children.length>0?e.children.forEach(n):t.push(e)};return e.forEach(n),t}function ke({report:e,rows:t,labels:n}){let r=e.chart;if(!r||!r.type)return{schema:null};let i=e.groupingsDown??[],a=r.xAxis||(i.length>0?i[0]?.field:void 0);if(!a)return{schema:null,diagnostic:`chart.xAxis missing and no groupingsDown[0] to default to.`};let o=e.columns??[],s=r.yAxis,c=`count`,l=`Count`,u=!0;if(s){let e=o.find(e=>e.field===s&&e.aggregate);e?(c=De(e),l=n?.resolveColumnLabel?.(e)??(typeof e.label==`string`?e.label:`${e.aggregate}(${e.field})`),u=!1):(c=`count`,l=n?.resolveCountLabel?.(s)??`Count of ${s}`)}let d=Oe(t),f=new Map;for(let e of d){let t=e.groupKey[a];if(t===void 0)continue;let n=String(t??``),r=u?e.count:Number(e.values[c]??0),i=f.get(n);i?i.measure+=Number.isFinite(r)?r:0:f.set(n,{x:t,measure:Number.isFinite(r)?r:0})}let p=Array.from(f.values()).map(e=>{let t=n?.resolveAxisValue?.(a,e.x)??e.x??`(null)`;return{[a]:t,[c]:e.measure}});return(r.type===`pie`||r.type===`donut`||r.type===`funnel`)&&(p=[...p].sort((e,t)=>Number(t[c]??0)-Number(e[c]??0))),{schema:{type:`chart`,chartType:r.type,data:p,xAxisKey:a,series:[{dataKey:c,label:l}],title:r.title,showLegend:r.showLegend??!0,showDataLabels:r.showDataLabels??!1,className:`w-full h-[320px]`}}}function Ae(e,t,n={}){let r=X(X(e.filter,n.runtimeFilter),Object.keys(t).length>0?t:void 0);return{type:`drill`,name:`drill-${e.name}`,objectName:e.objectName,...r?{filter:r}:{},view:n.view??`list`,...n.recordId===void 0?{}:{recordId:n.recordId},openIn:n.openIn??`current`}}function je(e){return!!e&&e.type===`drill`}function Me(e){return async t=>{if(!je(t))return{success:!1,error:`drill handler invoked with non-drill action`};try{return await e.navigate({objectName:t.objectName,filter:t.filter,view:t.view,recordId:t.recordId,openIn:t.openIn}),{success:!0}}catch(e){return{success:!1,error:e instanceof Error?e.message:String(e)}}}}function Ne(e,t){return e.registerHandler(`drill`,Me(t)),()=>e.unregisterHandler(`drill`)}function Pe(e){return e?e===`unique`?`count_distinct`:e:null}function Fe(e){if(!(!e||e.length===0))return{fields:e.map(e=>({field:e.field,order:e.sort??`asc`,collapsed:!1}))}}function Ie(e){return(e.columns??[]).map(e=>{let t={field:e.field};return e.label&&(t.label=typeof e.label==`string`?e.label:String(e.label)),e.format&&(t.format=e.format),e.width&&(t.width=e.width),t})}var Le={padding:`12px 16px`,border:`1px dashed rgb(203 213 225)`,borderRadius:8,color:`rgb(100 116 139)`,fontSize:14},Re=({report:e,dataSource:t,rows:n,runtimeFilter:r,onDrillDown:i,actionRunner:o,drillView:s,drillOpenIn:c,className:u})=>{let d=e.type??`tabular`,{t:f}=l(),{fieldLabel:p,translateOptions:m}=F(),[h,g]=G.useState(null);G.useEffect(()=>{let n=t;if(!n||typeof n.getObjectSchema!=`function`||!e.objectName)return;let r=!1;return n.getObjectSchema(e.objectName).then(e=>{r||g(e??null)}).catch(()=>{}),()=>{r=!0}},[t,e.objectName]);let _=G.useCallback(t=>{if(t.label)return String(t.label);let n=h?.fields?.[t.field]?.label??t.field,r=p(e.objectName,t.field,n);return t.aggregate?`${r} · ${f(`report.aggregate.${t.aggregate}`,t.aggregate)}`:r},[h,e.objectName,p,f]),v=G.useCallback((t,n)=>{if(n==null)return;let r=h?.fields?.[t];if(!r||!(r.type===`select`||r.type===`status`)||!Array.isArray(r.options)||r.options.length===0)return;let i=m(e.objectName,t,r.options),a=String(n);for(let e of i)if(e&&e.value!==void 0&&e.value!==null&&String(e.value)===a)return e.label==null?a:String(e.label)},[h,e.objectName,m]),{rawRows:y,rows:b,totals:x,serverAggregated:S,loading:C,error:w,drillDown:T}=Te(e,{dataSource:t,rows:n,runtimeFilter:r});if(d===`matrix`||d===`joined`)return(0,K.jsxs)(`div`,{className:u,style:Le,children:[`Report type `,(0,K.jsx)(`code`,{children:d}),` is not yet supported by SpecReportGrid. It will be rendered by a dedicated component in M2 (matrix) / M3 (joined).`]});let E=G.useMemo(()=>{if(S){let t=(e.groupingsDown??[]).map(e=>({field:e.field,label:e.field.replace(/_/g,` `).replace(/\b\w/g,e=>e.toUpperCase())})),n=(e.columns??[]).filter(e=>e.aggregate).map(e=>({field:q(e),label:`${(typeof e.label==`string`?e.label:null)??e.field} (${e.aggregate})`,...e.format?{format:e.format}:{}}));return{type:`object-grid`,objectName:e.objectName,columns:[...t,...n]}}let t=d===`summary`?Fe(e.groupingsDown):void 0,n=(e.columns??[]).map(e=>{let t=Pe(e.aggregate);return t?{field:e.field,type:t}:null}).filter(e=>e!==null);return{type:`object-grid`,objectName:e.objectName,columns:Ie(e),grouping:t,aggregations:n.length>0?n:void 0}},[e,d,S]),D=y,O=G.useCallback(t=>{let n=e.groupingsDown??[],a={};for(let e of n)a[e.field]=t[e.field];if(o){let t=Ae(e,a,{runtimeFilter:r,view:s,openIn:c});o.execute(t)}i&&i(a,T(a))},[o,T,c,s,i,e,r]),k=!!i||!!o,A=(e.columns??[]).filter(e=>e.aggregate),j=A.length>0&&x&&Object.keys(x).length>0,M=G.useMemo(()=>d!==`summary`||!e.chart||!e.chart.type?null:ke({report:e,rows:b,labels:{resolveColumnLabel:_,resolveCountLabel:t=>{let n=h?.fields?.[t]?.label??t;return`${p(e.objectName,t,n)} · ${f(`report.aggregate.count`,`Count`)}`},resolveAxisValue:v}}).schema,[e,b,d,_,v,h,p,f]);return(0,K.jsxs)(`div`,{className:u,"data-testid":`spec-report-grid`,"aria-busy":C||void 0,children:[w?(0,K.jsx)(`div`,{role:`alert`,style:{...Le,color:`rgb(190 18 60)`},children:w.message}):null,j?(0,K.jsxs)(`div`,{"data-testid":`spec-report-totals`,className:`mb-3 flex flex-wrap items-baseline gap-x-6 gap-y-1 rounded-md border bg-muted/40 px-3 py-2 text-sm`,children:[(0,K.jsx)(`span`,{className:`text-xs font-medium uppercase tracking-wide text-muted-foreground`,children:f(`report.totals`,`Totals`)}),A.map(e=>{let t=q(e),n=x[t],r=_(e),i=typeof n==`number`?n.toLocaleString(void 0,{maximumFractionDigits:2}):String(n??`—`);return(0,K.jsxs)(`span`,{"data-testid":`spec-report-total-${t}`,className:`inline-flex items-baseline gap-1.5`,children:[(0,K.jsxs)(`span`,{className:`text-muted-foreground`,children:[r,`:`]}),(0,K.jsx)(`span`,{className:`font-mono font-medium tabular-nums`,children:i})]},t)})]}):null,M?(0,K.jsx)(`div`,{className:`mb-4`,"data-testid":`spec-report-chart`,children:(0,K.jsx)(a,{schema:M})}):null,(0,K.jsx)(de,{schema:E,data:D,dataSource:t,onRowClick:k?O:void 0})]})};Re.displayName=`SpecReportGrid`;var ze=`—`;function Be(e){return e==null?ze:typeof e==`number`?e.toLocaleString():String(e)}function Ve(e,t,n){if(e==null||e===``||e===`(null)`)return n;let r=t?.options;if(r){let t=r.get(e);if(t!==void 0&&t!==``)return t}return e}function He({header:e,groupings:t,metaByField:n,fallback:r,emptyLabel:i}){return e.path.length===0?(0,K.jsx)(K.Fragment,{children:r}):(0,K.jsx)(K.Fragment,{children:e.path.map((e,r)=>{let a=t[r]?.field;return Ve(e,a?n.get(a):void 0,i)}).join(` / `)})}var Ue=({report:e,dataSource:t,rows:n,runtimeFilter:r,onCellClick:i,actionRunner:a,drillView:o,drillOpenIn:s,className:c,emptyCellText:u=ze})=>{let{pivot:d,loading:f,error:p}=Te(e,{dataSource:t,rows:n,runtimeFilter:r}),m=e.columns??[],h=m.length>1,{fieldLabel:g,translateOptions:_}=F(),{t:v}=l(),y=v(`report.emptyLabel`,`(Empty)`),b=v(`report.allLabel`,`(All)`),[x,S]=G.useState(null);G.useEffect(()=>{let n=t;if(!n||typeof n.getObjectSchema!=`function`||!e.objectName)return;let r=!1;return n.getObjectSchema(e.objectName).then(e=>{r||S(e??null)}).catch(()=>{}),()=>{r=!0}},[t,e.objectName]);let C=e.groupingsDown??[],w=e.groupingsAcross??[],T=G.useMemo(()=>{let t=new Map,n=x?.fields??{},r=[...C,...w];for(let i of r){let r=n[i.field],a=r?.label??i.field,o=g(e.objectName,i.field,a),s=r?.type===`select`||r?.type===`status`,c;if(s&&Array.isArray(r?.options)&&r.options.length>0){let t=_(e.objectName,i.field,r.options);c=new Map;for(let e of t)e&&e.value!==void 0&&e.value!==null&&c.set(String(e.value),e.label==null?String(e.value):String(e.label))}t.set(i.field,{fieldLabel:o,options:c})}return t},[x,C,w,e.objectName,g,_]),E=G.useMemo(()=>{let t=new Map,n=x?.fields??{};for(let r of m){let i=q(r);if(r.label){t.set(i,String(r.label));continue}let a=n[r.field]?.label??r.field,o=g(e.objectName,r.field,a);if(r.aggregate){let e=v(`report.aggregate.${r.aggregate}`,r.aggregate);t.set(i,`${o} · ${e}`)}else t.set(i,o)}return t},[m,x,e.objectName,g,v]),D=G.useCallback((t,n,c)=>{let l={...t.key,...n.key};if(a){let t=Ae(e,l,{runtimeFilter:r,view:o,openIn:s});a.execute(t)}i&&i({rowKey:t.key,colKey:n.key,combinedKey:l,values:c})},[a,s,o,i,e,r]);if(p)return(0,K.jsx)(`div`,{className:M(`rounded-md border border-destructive/30 bg-destructive/5 px-4 py-3 text-sm text-destructive`,c),role:`alert`,"data-testid":`matrix-error`,children:v(`report.failedToLoad`,`Failed to load matrix: {{message}}`,{message:p.message})});if(!d)return(0,K.jsx)(`div`,{className:M(`rounded-md border border-dashed border-border bg-muted/30 px-4 py-6 text-center text-sm text-muted-foreground`,c),"aria-busy":f||void 0,"data-testid":`matrix-empty`,children:f?v(`report.loading`,`Loading…`):v(`report.needsAcross`,"Matrix report requires at least one `groupingsAcross` field.")});let O=!!i||!!a,k=C.map(e=>T.get(e.field)?.fieldLabel??e.field).join(` / `)||v(`report.rowsLabel`,`Row`),A=w.map(e=>T.get(e.field)?.fieldLabel??e.field).join(` / `)||v(`report.columnsLabel`,`Column`),j=m.length>0?q(m[0]):null,N=0;if(j)for(let e of d.rowHeaders)for(let t of d.colHeaders){let n=d.cells[e.id]?.[t.id]?.[j];typeof n==`number`&&n>N&&(N=n)}let P=e=>{if(!j||N<=0||!e)return 0;let t=e[j];return typeof t!=`number`||t<=0?0:Math.min(1,t/N)};return(0,K.jsx)(`div`,{className:M(`overflow-auto rounded-lg border border-border bg-card shadow-sm`,c),"data-testid":`matrix-renderer`,"aria-busy":f||void 0,children:(0,K.jsxs)(`table`,{role:`table`,className:`w-full border-separate border-spacing-0 text-sm`,children:[(0,K.jsx)(`thead`,{children:(0,K.jsxs)(`tr`,{children:[(0,K.jsxs)(`th`,{scope:`col`,className:M(`sticky left-0 top-0 z-30 border-b border-r border-border bg-muted/60`,`px-3 py-2 text-left text-xs font-semibold uppercase tracking-wide text-muted-foreground`),"aria-label":`${k} \u2192 ${A}`,children:[(0,K.jsx)(`span`,{className:`text-muted-foreground/70`,children:k}),(0,K.jsx)(`span`,{className:`mx-1 text-muted-foreground/40`,children:`\\`}),(0,K.jsx)(`span`,{className:`text-foreground/80`,children:A})]}),d.colHeaders.map(e=>(0,K.jsx)(`th`,{scope:`col`,className:`sticky top-0 z-20 whitespace-nowrap border-b border-border bg-muted/60 px-3 py-2 text-right text-xs font-semibold text-foreground`,children:(0,K.jsx)(He,{header:e,groupings:w,metaByField:T,fallback:b,emptyLabel:y})},`col-${e.id}`)),(0,K.jsx)(`th`,{scope:`col`,className:`sticky top-0 z-20 whitespace-nowrap border-b border-l border-border bg-muted px-3 py-2 text-right text-xs font-semibold uppercase tracking-wide text-foreground`,children:v(`report.rowTotal`,`Row Total`)})]})}),(0,K.jsx)(`tbody`,{children:d.rowHeaders.map((e,t)=>(0,K.jsxs)(`tr`,{className:`group`,children:[(0,K.jsx)(`th`,{scope:`row`,className:M(`sticky left-0 z-10 whitespace-nowrap border-b border-r border-border bg-card px-3 py-2 text-left text-sm font-medium text-foreground`,`group-hover:bg-muted/50`,t===0&&`border-t-0`),children:(0,K.jsx)(He,{header:e,groupings:C,metaByField:T,fallback:b,emptyLabel:y})}),d.colHeaders.map(t=>{let n=d.cells[e.id]?.[t.id],r=!n,i=P(n);return(0,K.jsx)(`td`,{className:M(`border-b border-border px-3 py-2 text-right tabular-nums transition-colors`,r?`text-muted-foreground/40`:`text-foreground`,O&&!r&&`cursor-pointer hover:outline hover:outline-2 hover:-outline-offset-2 hover:outline-primary/50`,`group-hover:bg-muted/30`),style:i>0?{backgroundColor:`rgba(59, 130, 246, ${.06+i*.28})`}:void 0,onClick:O&&!r?()=>D(e,t,n):void 0,"data-row":e.id,"data-col":t.id,children:r?u:We(m,n,h,E)},`cell-${e.id}-${t.id}`)}),(0,K.jsx)(`td`,{className:M(`border-b border-l border-border bg-muted/40 px-3 py-2 text-right text-sm font-semibold tabular-nums text-foreground`,`group-hover:bg-muted/60`),children:We(m,d.rowTotals[e.id]??{},h,E)})]},`row-${e.id}`))}),(0,K.jsx)(`tfoot`,{children:(0,K.jsxs)(`tr`,{children:[(0,K.jsx)(`th`,{scope:`row`,className:`sticky left-0 z-10 whitespace-nowrap border-t-2 border-r border-border bg-muted px-3 py-2 text-left text-xs font-semibold uppercase tracking-wide text-foreground`,children:v(`report.columnTotal`,`Column Total`)}),d.colHeaders.map(e=>(0,K.jsx)(`td`,{className:`border-t-2 border-border bg-muted/40 px-3 py-2 text-right text-sm font-semibold tabular-nums text-foreground`,children:We(m,d.colTotals[e.id]??{},h,E)},`coltotal-${e.id}`)),(0,K.jsx)(`td`,{className:`border-l border-t-2 border-border bg-primary/10 px-3 py-2 text-right text-sm font-bold tabular-nums text-foreground`,children:We(m,d.grandTotal,h,E)})]})})]})})};function We(e,t,n,r){return e.length?n?(0,K.jsx)(`div`,{className:`flex flex-col gap-0.5`,children:e.map(e=>{let n=q(e);return(0,K.jsxs)(`div`,{className:`flex items-baseline justify-between gap-2`,children:[(0,K.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:r?.get(n)??e.label??n}),(0,K.jsx)(`span`,{className:`tabular-nums`,children:Be(t[n])})]},n)})}):Be(t[q(e[0])]):ze}function Ge(e,t){return e?typeof e==`string`?e:typeof e==`object`&&typeof e.default==`string`?e.default:t:t}function Ke(e,t){if(!t||Object.keys(t).length===0)return e;let n=X(t,e.filter);return{...e,filter:n}}var qe=({report:e,dataSource:t,runtimeFilter:n,actionRunner:r,drillView:a,drillOpenIn:o,className:s,renderBlock:c})=>{if(!i(e))return(0,K.jsxs)(`div`,{className:s,"data-testid":`joined-report-invalid`,style:{color:`var(--color-destructive, #b91c1c)`,fontSize:13,padding:12},children:[`JoinedReportRenderer requires a report with `,(0,K.jsx)(`code`,{children:`type: 'joined'`}),` and a `,(0,K.jsx)(`code`,{children:`blocks`}),` array.`]});let l=e.blocks??[],u=e.filter,d=e.objectName;return(0,K.jsx)(`div`,{className:s,"data-testid":`joined-report`,"data-report-name":e.name,style:{display:`flex`,flexDirection:`column`,gap:24},children:l.map((e,i)=>{let s=e.objectName??d??``,l=Ke({...e,objectName:s,type:e.type??`tabular`,columns:e.columns??[]},u),f=Ge(e.label,e.name),p=e.description?Ge(e.description,``):``,m=e.name??`block-${i}`,h=(0,K.jsxs)(`section`,{"data-testid":`joined-report-block`,"data-block-id":m,style:{display:`flex`,flexDirection:`column`,gap:8,border:`1px solid var(--color-border, #e4e4e7)`,borderRadius:8,padding:16,background:`var(--color-card, #ffffff)`},children:[(0,K.jsxs)(`header`,{style:{display:`flex`,flexDirection:`column`,gap:2},children:[(0,K.jsx)(`h3`,{style:{margin:0,fontSize:16,fontWeight:600},children:f}),p?(0,K.jsx)(`p`,{style:{margin:0,fontSize:13,color:`var(--color-muted-foreground, #71717a)`},children:p}):null]}),(0,K.jsx)(Ye,{schema:l,dataSource:t,runtimeFilter:n,actionRunner:r,drillView:a,drillOpenIn:o})]},m);return c?c(e,i,h):h})})},Je={border:`1px dashed var(--color-border, #d4d4d8)`,borderRadius:8,padding:16,color:`var(--color-muted-foreground, #71717a)`,background:`var(--color-muted, #f4f4f5)`,fontSize:13},Ye=e=>{let{dataSource:t,rows:n,runtimeFilter:r,actionRunner:a,drillView:s,drillOpenIn:l,className:u}=e,d=G.useContext(c),f=t??d?.dataSource,p=e.schema;if(p&&typeof p==`object`&&p.type===`spec-report`&&p.report&&typeof p.report==`object`&&(p=p.report),o(p)){let e=p.type??`tabular`;return e===`matrix`?(0,K.jsx)(Ue,{report:p,dataSource:f,rows:n,runtimeFilter:r,actionRunner:a,drillView:s,drillOpenIn:l,className:u}):e===`joined`?i(p)?(0,K.jsx)(qe,{report:p,dataSource:f,runtimeFilter:r,actionRunner:a,drillView:s,drillOpenIn:l,className:u}):(0,K.jsxs)(`div`,{className:u,style:Je,"data-testid":`report-joined-placeholder`,children:[`Joined report (`,(0,K.jsx)(`code`,{children:p.name}),`) is missing a `,(0,K.jsx)(`code`,{children:`blocks`}),` array.`]}):(0,K.jsx)(Re,{report:p,dataSource:f,rows:n,runtimeFilter:r,actionRunner:a,drillView:s,drillOpenIn:l,className:u})}return(0,K.jsx)(fe,{schema:p})};function Xe(e,t,n){let r=e.fields||[],i=r.map(e=>e.label||e.name),a=t.map(e=>r.map(t=>{let n=e[t.name];return n=nt(n),typeof n==`string`&&(n.includes(`,`)||n.includes(`"`)||n.includes(`
2
- `))?`"${n.replace(/"/g,`""`)}"`:n??``}));at([...n?.includeHeaders===!1?[]:[i.join(`,`)],...a.map(e=>e.join(`,`))].join(`
3
- `),n?.filename||`${e.title||`report`}.csv`,`text/csv`)}function Ze(e,t,n){let r={title:e.title,description:e.description,generatedAt:new Date().toISOString(),data:t};at(JSON.stringify(r,null,2),n?.filename||`${e.title||`report`}.json`,`application/json`)}function Qe(e,t,n){let r=e.fields||[],i=it(n?.orientation),a=rt(n?.pageSize);at(`<!DOCTYPE html>
4
- <html>
5
- <head>
6
- <meta charset="utf-8">
7
- <title>${Q(e.title||`Report`)}</title>
8
- <style>
9
- @page { size: ${a} ${i}; margin: 20mm; }
10
- body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; color: #333; }
11
- h1 { font-size: 24px; margin-bottom: 8px; }
12
- .description { color: #666; margin-bottom: 24px; }
13
- .meta { color: #999; font-size: 12px; margin-bottom: 16px; }
14
- table { width: 100%; border-collapse: collapse; margin-top: 16px; }
15
- th { background: #f5f5f5; text-align: left; padding: 8px 12px; border: 1px solid #ddd; font-weight: 600; }
16
- td { padding: 8px 12px; border: 1px solid #ddd; }
17
- tr:nth-child(even) { background: #fafafa; }
18
- </style>
19
- </head>
20
- <body>
21
- <h1>${Q(e.title||`Report`)}</h1>
22
- ${e.description?`<p class="description">${Q(e.description)}</p>`:``}
23
- <p class="meta">Generated: ${new Date().toLocaleString()}</p>
24
- <table>
25
- <thead><tr>${r.map(e=>`<th>${Q(e.label||e.name)}</th>`).join(``)}</tr></thead>
26
- <tbody>${t.map(e=>`<tr>${r.map(t=>`<td>${Q(String(e[t.name]??``))}</td>`).join(``)}</tr>`).join(``)}</tbody>
27
- </table>
28
- </body>
29
- </html>`,n?.filename||`${e.title||`report`}.html`,`text/html`)}function $e(e,t,n){let r=e.fields||[],i=it(n?.orientation),a=rt(n?.pageSize),o=window.open(``,`_blank`);if(!o){Qe(e,t,{...n,format:`html`,filename:n?.filename?.replace(/\.pdf$/,`.html`)||`${e.title||`report`}.html`});return}o.document.write(`<!DOCTYPE html>
30
- <html>
31
- <head>
32
- <meta charset="utf-8">
33
- <title>${Q(e.title||`Report`)}</title>
34
- <style>
35
- @page { size: ${a} ${i}; margin: 20mm; }
36
- @media print { .no-print { display: none; } }
37
- body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; color: #333; }
38
- h1 { font-size: 24px; margin-bottom: 8px; }
39
- .description { color: #666; margin-bottom: 24px; }
40
- .meta { color: #999; font-size: 12px; margin-bottom: 16px; }
41
- table { width: 100%; border-collapse: collapse; margin-top: 16px; }
42
- th { background: #f5f5f5; text-align: left; padding: 8px 12px; border: 1px solid #ddd; font-weight: 600; }
43
- td { padding: 8px 12px; border: 1px solid #ddd; }
44
- tr:nth-child(even) { background: #fafafa; }
45
- </style>
46
- </head>
47
- <body>
48
- <h1>${Q(e.title||`Report`)}</h1>
49
- ${e.description?`<p class="description">${Q(e.description)}</p>`:``}
50
- <p class="meta">Generated: ${new Date().toLocaleString()}</p>
51
- <table>
52
- <thead><tr>${r.map(e=>`<th>${Q(e.label||e.name)}</th>`).join(``)}</tr></thead>
53
- <tbody>${t.map(e=>`<tr>${r.map(t=>`<td>${Q(String(e[t.name]??``))}</td>`).join(``)}</tr>`).join(``)}</tbody>
54
- </table>
55
- </body>
56
- </html>`),o.document.close(),o.onload=()=>{o.print()}}function et(e,t,n){let r=e.fields||[],i=r.map(e=>e.label||e.name),a=t.map(e=>r.map(t=>{let n=e[t.name];return n=nt(n),typeof n==`string`&&(n.includes(`,`)||n.includes(`"`)||n.includes(`
57
- `)||n.includes(` `))?`"${n.replace(/"/g,`""`)}"`:n??``}));at(``+[...n?.includeHeaders===!1?[]:[i.join(` `)],...a.map(e=>e.join(` `))].join(`
58
- `),n?.filename||`${e.title||`report`}.tsv`,`text/tab-separated-values`)}function tt(e,t,n,r){switch(e){case`csv`:Xe(t,n,r);break;case`json`:Ze(t,n,r);break;case`html`:Qe(t,n,r);break;case`pdf`:$e(t,n,r);break;case`excel`:et(t,n,r);break;default:console.warn(`Unsupported export format: ${e}`)}}function Q(e){return e.replace(/&/g,`&amp;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`).replace(/"/g,`&quot;`).replace(/'/g,`&#039;`)}function nt(e){if(typeof e==`string`&&e.length>0){let t=e.charAt(0);if(t===`=`||t===`+`||t===`-`||t===`@`||t===`|`)return`\t${e}`}return e}function rt(e){return[`A4`,`A3`,`Letter`,`Legal`].includes(e||``)?e:`A4`}function it(e){return e===`landscape`?`landscape`:`portrait`}function at(e,t,n){let r=new Blob([e],{type:`${n};charset=utf-8`}),i=URL.createObjectURL(r),a=document.createElement(`a`);a.href=i,a.download=t,document.body.appendChild(a),a.click(),document.body.removeChild(a),URL.revokeObjectURL(i)}function ot(e,t){if(e==null||e===``)return``;let n=t?.type,r=t?.format;if(n===`date`||r===`date`||st(e))return ct(e);if(n===`number`||typeof e==`number`){let t=typeof e==`number`?e:Number(e);return isNaN(t)?String(e):r===`currency`||r===`currency_cny`?`¥${t.toLocaleString(`en-US`,{minimumFractionDigits:0,maximumFractionDigits:0})}`:r===`currency_usd`?`$${t.toLocaleString(`en-US`,{minimumFractionDigits:0,maximumFractionDigits:0})}`:r===`percent`?`${t.toLocaleString(`en-US`,{minimumFractionDigits:1,maximumFractionDigits:1})}%`:t.toLocaleString(`en-US`)}return String(e)}function st(e){return typeof e==`string`?/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2})?/.test(e):!1}function ct(e){try{let t=new Date(e);return isNaN(t.getTime())?String(e):`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,`0`)}-${String(t.getDate()).padStart(2,`0`)}`}catch{return String(e)}}function lt(e,t){if(!t||t.length===0||!e||e.length===0)return null;let n=t[0],r=n.field,i=new Map;for(let t of e){let e=String(t[r]??`(empty)`);i.has(e)||i.set(e,[]),i.get(e).push(t)}let a=[];for(let[e,t]of i)a.push({key:e,label:`${n.label||r}: ${e}`,rows:t});let o=n.sort===`desc`?-1:1;return a.sort((e,t)=>e.key.localeCompare(t.key)*o),a}var ut=({schema:e,onRefresh:t})=>{let{report:n,data:r,showToolbar:i=!0,allowExport:o=!0,allowPrint:c=!0,loading:l=!1}=e,u=e=>{if(!n){console.warn(`ReportViewer: Cannot export, no report defined`);return}tt(e,n,r||[],n.exportConfigs?.[e])},d=()=>{window.print()},p=()=>{t?.()},m=(e,t)=>{if(!r)return 0;let n=r.map(t=>Number(t[e])||0);switch(t){case`count`:return r.length;case`sum`:return n.reduce((e,t)=>e+t,0);case`avg`:return n.length>0?(n.reduce((e,t)=>e+t,0)/n.length).toFixed(2):0;case`min`:return n.length>0?Math.min(...n):0;case`max`:return n.length>0?Math.max(...n):0;default:return``}},h=(e,t)=>{let r=n?.conditionalFormatting;if(!(!r||!Array.isArray(r)))for(let n of r){if(n.field!==e)continue;let r=String(t??``),i=String(n.value??``),a=!1;switch(n.operator){case`equals`:a=r===i;break;case`not_equals`:a=r!==i;break;case`contains`:a=r.includes(i);break;case`greater_than`:a=Number(t)>Number(n.value);break;case`less_than`:a=Number(t)<Number(n.value);break}if(a){let e={};return n.backgroundColor&&(e.backgroundColor=n.backgroundColor),n.textColor&&(e.color=n.textColor),e}}},g=(e,t)=>{if(e==null||e===``)return``;if(t.renderAs===`badge`&&(!t.type||t.type===`string`||t.type===`text`))return(0,K.jsx)(w,{className:t.colorMap?.[String(e)]||``,children:String(e)});if(t.aggregation)return ot(e,t);if(t.type){let n={...t};return t.colorMap&&!n.options&&(n.options=Object.entries(t.colorMap).map(([e,t])=>({value:e,label:e,color:t}))),(0,K.jsx)(B(ne(n)),{value:e,field:n})}return ot(e,t)};return n?(0,K.jsxs)(`div`,{className:`space-y-4`,children:[i&&(0,K.jsxs)(`div`,{className:`flex items-center justify-between gap-2 p-4 bg-card rounded-lg border`,children:[(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`h2`,{className:`text-lg font-semibold`,children:n.title}),n.description&&(0,K.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:n.description})]}),(0,K.jsxs)(`div`,{className:`flex items-center gap-2`,children:[n.refreshInterval&&(0,K.jsxs)(V,{variant:`outline`,size:`sm`,onClick:p,children:[(0,K.jsx)(se,{className:`h-4 w-4 mr-2`}),`Refresh`]}),c&&(0,K.jsxs)(V,{variant:`outline`,size:`sm`,onClick:d,children:[(0,K.jsx)(E,{className:`h-4 w-4 mr-2`}),`Print`]}),o&&n.showExportButtons&&(0,K.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,K.jsxs)(V,{variant:`outline`,size:`sm`,onClick:()=>u(`pdf`),children:[(0,K.jsx)(ie,{className:`h-4 w-4 mr-2`}),`PDF`]}),(0,K.jsxs)(V,{variant:`outline`,size:`sm`,onClick:()=>u(`excel`),children:[(0,K.jsx)(ie,{className:`h-4 w-4 mr-2`}),`Excel`]}),(0,K.jsxs)(V,{variant:`outline`,size:`sm`,onClick:()=>u(`csv`),children:[(0,K.jsx)(ie,{className:`h-4 w-4 mr-2`}),`CSV`]})]})]})]}),(0,K.jsxs)(y,{children:[(0,K.jsxs)(j,{children:[!i&&n.title&&(0,K.jsx)(A,{children:n.title}),!i&&n.description&&(0,K.jsx)(v,{children:n.description})]}),(0,K.jsxs)(U,{className:`space-y-6`,children:[l&&(0,K.jsxs)(`div`,{className:`space-y-6`,children:[(0,K.jsx)(`div`,{className:`grid grid-cols-1 md:grid-cols-3 gap-4`,children:[1,2,3].map(e=>(0,K.jsx)(y,{children:(0,K.jsxs)(U,{className:`p-4 space-y-2`,children:[(0,K.jsx)(f,{className:`h-4 w-20`}),(0,K.jsx)(f,{className:`h-8 w-28`})]})},e))}),(0,K.jsxs)(`div`,{className:`space-y-2`,children:[(0,K.jsx)(f,{className:`h-10 w-full`}),[1,2,3,4,5].map(e=>(0,K.jsx)(f,{className:`h-8 w-full`},e))]})]}),!l&&n.sections?.map((e,t)=>e.visible===!1?null:(0,K.jsxs)(`div`,{className:`space-y-2`,children:[e.title&&e.type!==`header`&&(0,K.jsx)(`h3`,{className:`text-lg font-semibold border-b pb-2`,children:e.title}),e.type===`header`&&e.title&&(0,K.jsx)(`div`,{className:`text-2xl font-bold py-4`,children:e.title}),e.type===`summary`&&(0,K.jsx)(`div`,{className:`grid grid-cols-1 md:grid-cols-3 gap-4`,children:n.fields?.filter(e=>e.showInSummary).map((e,t)=>(0,K.jsx)(y,{children:(0,K.jsxs)(U,{className:`p-4`,children:[(0,K.jsx)(`div`,{className:`text-sm text-muted-foreground`,children:e.label||e.name}),(0,K.jsx)(`div`,{className:`text-2xl font-bold`,children:ot(m(e.name,e.aggregation),e)})]})},t))}),e.type===`chart`&&e.chart&&(0,K.jsx)(`div`,{className:`min-h-[300px]`,children:(()=>{let t=e.chart.type,n=!!e.chart.chartType;!t&&n&&(t=`chart`),t&&s.get(t)||(t=`chart`);let i=t===`chart`?{xAxisKey:e.chart.xAxisKey||e.chart.xAxisField||`name`,series:e.chart.series||(e.chart.yAxisFields?e.chart.yAxisFields.map(e=>({dataKey:e})):[]),chartType:e.chart.chartType||`bar`}:{};return(0,K.jsx)(a,{schema:{...e.chart,type:t,...i,data:r||e.chart.data,className:e.chart.className||`w-full h-[350px]`}})})()}),e.type===`table`&&(0,K.jsx)(`div`,{className:`border rounded-lg overflow-x-auto`,children:(0,K.jsxs)(`table`,{className:`w-full text-sm min-w-[600px]`,children:[(0,K.jsx)(`thead`,{className:`bg-muted`,children:(0,K.jsx)(`tr`,{children:e.columns?.map((e,t)=>(0,K.jsx)(`th`,{className:`px-4 py-2 font-medium ${e.type===`number`?`text-right`:`text-left`}`,children:e.label||e.name},t))})}),(0,K.jsx)(`tbody`,{children:(()=>{let t=lt(r||[],n.groupBy||[]);return t?t.map(t=>(0,K.jsxs)(G.Fragment,{children:[(0,K.jsx)(`tr`,{className:`bg-muted/60`,children:(0,K.jsxs)(`td`,{colSpan:e.columns?.length||1,className:`px-4 py-2 font-semibold text-sm`,children:[t.label,` (`,t.rows.length,`)`]})}),t.rows.map((t,n)=>(0,K.jsx)(`tr`,{className:`border-t hover:bg-muted/50 even:bg-muted/20`,children:e.columns?.map((e,n)=>(0,K.jsx)(`td`,{className:`px-4 py-2 ${e.type===`number`?`text-right tabular-nums`:``}`,style:h(e.name,t[e.name]),children:g(t[e.name],e)},n))},n))]},t.key)):r?.map((t,n)=>(0,K.jsx)(`tr`,{className:`border-t hover:bg-muted/50 even:bg-muted/20`,children:e.columns?.map((e,n)=>(0,K.jsx)(`td`,{className:`px-4 py-2 ${e.type===`number`?`text-right tabular-nums`:``}`,style:h(e.name,t[e.name]),children:g(t[e.name],e)},n))},n))})()})]})}),e.type===`text`&&e.text&&(0,K.jsx)(`div`,{className:`prose max-w-none`,children:(0,K.jsx)(`p`,{children:e.text})}),e.type===`page-break`&&(0,K.jsx)(`div`,{className:`border-t-2 border-dashed my-8 print:page-break-after-always`}),e.content&&(0,K.jsx)(a,{schema:e.content})]},t)),!n.sections&&r&&r.length>0&&(0,K.jsx)(`div`,{className:`border rounded-lg overflow-x-auto`,children:(0,K.jsxs)(`table`,{className:`w-full text-sm min-w-[600px]`,children:[(0,K.jsx)(`thead`,{className:`bg-muted`,children:(0,K.jsx)(`tr`,{children:n.fields?.map((e,t)=>(0,K.jsx)(`th`,{className:`px-4 py-2 font-medium ${e.type===`number`?`text-right`:`text-left`}`,children:e.label||e.name},t))})}),(0,K.jsx)(`tbody`,{children:r.map((e,t)=>(0,K.jsx)(`tr`,{className:`border-t hover:bg-muted/50 even:bg-muted/20`,children:n.fields?.map((t,n)=>(0,K.jsx)(`td`,{className:`px-4 py-2 ${t.type===`number`?`text-right tabular-nums`:``}`,style:h(t.name,e[t.name]),children:g(e[t.name],t)},n))},t))})]})})]})]})]}):(0,K.jsx)(y,{children:(0,K.jsx)(U,{className:`p-8 text-center text-muted-foreground`,children:`No report to display`})})},dt=({schedule:e,onChange:t})=>{let[n,r]=(0,G.useState)(e||{enabled:!1,frequency:`weekly`,time:`09:00`,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone,recipients:[],formats:[`pdf`]}),i=e=>{let i={...n,...e};r(i),t?.(i)};return(0,K.jsxs)(y,{children:[(0,K.jsx)(j,{children:(0,K.jsxs)(A,{className:`flex items-center gap-2`,children:[(0,K.jsx)(D,{className:`h-5 w-5`}),`Schedule Configuration`]})}),(0,K.jsxs)(U,{className:`space-y-4`,children:[(0,K.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,K.jsx)(`input`,{type:`checkbox`,id:`schedule-enabled`,checked:n.enabled||!1,onChange:e=>i({enabled:e.target.checked}),className:`rounded`}),(0,K.jsx)(R,{htmlFor:`schedule-enabled`,children:`Enable Scheduled Report`})]}),n.enabled&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsxs)(`div`,{className:`space-y-2`,children:[(0,K.jsx)(R,{children:`Frequency`}),(0,K.jsx)(`select`,{className:`w-full border rounded-md p-2 bg-background`,value:n.frequency||`weekly`,onChange:e=>i({frequency:e.target.value}),children:[{value:`once`,label:`Once`},{value:`daily`,label:`Daily`},{value:`weekly`,label:`Weekly`},{value:`monthly`,label:`Monthly`},{value:`quarterly`,label:`Quarterly`},{value:`yearly`,label:`Yearly`}].map(e=>(0,K.jsx)(`option`,{value:e.value,children:e.label},e.value))})]}),n.frequency===`weekly`&&(0,K.jsxs)(`div`,{className:`space-y-2`,children:[(0,K.jsx)(R,{children:`Day of Week`}),(0,K.jsx)(`select`,{className:`w-full border rounded-md p-2 bg-background`,value:n.dayOfWeek??1,onChange:e=>i({dayOfWeek:Number(e.target.value)}),children:[{value:0,label:`Sunday`},{value:1,label:`Monday`},{value:2,label:`Tuesday`},{value:3,label:`Wednesday`},{value:4,label:`Thursday`},{value:5,label:`Friday`},{value:6,label:`Saturday`}].map(e=>(0,K.jsx)(`option`,{value:e.value,children:e.label},e.value))})]}),n.frequency===`monthly`&&(0,K.jsxs)(`div`,{className:`space-y-2`,children:[(0,K.jsx)(R,{children:`Day of Month`}),(0,K.jsx)(P,{type:`number`,min:1,max:31,value:n.dayOfMonth??1,onChange:e=>i({dayOfMonth:Number(e.target.value)})})]}),(0,K.jsxs)(`div`,{className:`space-y-2`,children:[(0,K.jsxs)(R,{className:`flex items-center gap-2`,children:[(0,K.jsx)(ae,{className:`h-4 w-4`}),`Time`]}),(0,K.jsx)(P,{type:`time`,value:n.time||`09:00`,onChange:e=>i({time:e.target.value})})]}),(0,K.jsxs)(`div`,{className:`space-y-2`,children:[(0,K.jsx)(R,{children:`Timezone`}),(0,K.jsx)(P,{value:n.timezone||``,onChange:e=>i({timezone:e.target.value}),placeholder:`e.g. America/New_York`})]}),(0,K.jsxs)(`div`,{className:`space-y-2`,children:[(0,K.jsx)(R,{children:`Export Formats`}),(0,K.jsx)(`div`,{className:`flex flex-wrap gap-2`,children:[{value:`pdf`,label:`PDF`},{value:`excel`,label:`Excel`},{value:`csv`,label:`CSV`},{value:`html`,label:`HTML`}].map(e=>(0,K.jsxs)(`label`,{className:`flex items-center gap-1.5 px-3 py-1.5 border rounded-md cursor-pointer hover:bg-muted/50`,children:[(0,K.jsx)(`input`,{type:`checkbox`,checked:n.formats?.includes(e.value)||!1,onChange:t=>{let r=n.formats||[];i({formats:t.target.checked?[...r,e.value]:r.filter(t=>t!==e.value)})},className:`rounded`}),(0,K.jsx)(`span`,{className:`text-sm`,children:e.label})]},e.value))})]}),(0,K.jsxs)(`div`,{className:`space-y-2`,children:[(0,K.jsxs)(R,{className:`flex items-center gap-2`,children:[(0,K.jsx)(d,{className:`h-4 w-4`}),`Email Recipients`]}),(0,K.jsx)(P,{placeholder:`email1@example.com, email2@example.com`,value:n.recipients?.join(`, `)||``,onChange:e=>i({recipients:e.target.value.split(`,`).map(e=>e.trim()).filter(Boolean)})})]}),(0,K.jsxs)(`div`,{className:`space-y-2`,children:[(0,K.jsx)(R,{children:`Email Subject`}),(0,K.jsx)(P,{value:n.subject||``,onChange:e=>i({subject:e.target.value}),placeholder:`Scheduled Report: {report_title}`})]})]})]})]})},ft=({schema:e})=>{let{report:t,dataSources:n=[],availableFields:r=[],showPreview:i=!0,onSave:a,onCancel:o}=e,[s,c]=(0,G.useState)(t||{type:`report`,title:`New Report`,fields:[],filters:[],groupBy:[],sections:[],showExportButtons:!0,showPrintButton:!0}),[l,d]=(0,G.useState)(s.fields||[]),[f,p]=(0,G.useState)(s.filters||[]),[m,h]=(0,G.useState)(s.groupBy||[]),[g,_]=(0,G.useState)(s.sections||[]),b=()=>{if(r.length>0&&l.length<r.length){let e=r.find(e=>!l.some(t=>t.name===e.name));if(e){let t=[...l,e];d(t),c({...s,fields:t})}}},x=e=>{let t=l.filter((t,n)=>n!==e);d(t),c({...s,fields:t})},w=(e,t)=>{let n=[...l];n[e]=t,d(n),c({...s,fields:n})},T=()=>{let e={field:r[0]?.name||``,operator:`equals`,value:``},t=[...f,e];p(t),c({...s,filters:t})},E=e=>{let t=f.filter((t,n)=>n!==e);p(t),c({...s,filters:t})},O=(e,t)=>{let n=[...f];n[e]=t,p(n),c({...s,filters:n})},k=()=>{let e={field:r[0]?.name||``,sort:`asc`},t=[...m,e];h(t),c({...s,groupBy:t})},M=e=>{let t=m.filter((t,n)=>n!==e);h(t),c({...s,groupBy:t})},N=(e,t)=>{let n=[...m];n[e]=t,h(n),c({...s,groupBy:n})},F=e=>{let t={type:e,title:`New ${e} Section`},n=[...g,t];_(n),c({...s,sections:n})},z=e=>{let t=g.filter((t,n)=>n!==e);_(t),c({...s,sections:t})},B=(e,t)=>{let n=[...g];n[e]=t,_(n),c({...s,sections:n})};return(0,K.jsxs)(`div`,{className:`space-y-4`,children:[(0,K.jsxs)(y,{children:[(0,K.jsxs)(j,{children:[(0,K.jsx)(A,{children:`Report Builder`}),(0,K.jsx)(v,{children:`Configure your report settings, fields, filters, and sections`})]}),(0,K.jsxs)(U,{children:[(0,K.jsxs)(u,{defaultValue:`basic`,className:`w-full`,children:[(0,K.jsxs)(oe,{className:`grid w-full grid-cols-6`,children:[(0,K.jsxs)(H,{value:`basic`,children:[(0,K.jsx)(re,{className:`h-4 w-4 mr-2`}),`Basic`]}),(0,K.jsxs)(H,{value:`fields`,children:[(0,K.jsx)(L,{className:`h-4 w-4 mr-2`}),`Fields`]}),(0,K.jsxs)(H,{value:`filters`,children:[(0,K.jsx)(S,{className:`h-4 w-4 mr-2`}),`Filters`]}),(0,K.jsxs)(H,{value:`grouping`,children:[(0,K.jsx)(L,{className:`h-4 w-4 mr-2`}),`Group By`]}),(0,K.jsxs)(H,{value:`sections`,children:[(0,K.jsx)(L,{className:`h-4 w-4 mr-2`}),`Sections`]}),(0,K.jsxs)(H,{value:`schedule`,children:[(0,K.jsx)(D,{className:`h-4 w-4 mr-2`}),`Schedule`]})]}),(0,K.jsx)(I,{value:`basic`,className:`space-y-4 mt-4`,children:(0,K.jsxs)(`div`,{className:`space-y-4`,children:[(0,K.jsxs)(`div`,{className:`space-y-2`,children:[(0,K.jsx)(R,{htmlFor:`report-title`,children:`Report Title`}),(0,K.jsx)(P,{id:`report-title`,value:s.title||``,onChange:e=>c({...s,title:e.target.value}),placeholder:`Enter report title`})]}),(0,K.jsxs)(`div`,{className:`space-y-2`,children:[(0,K.jsx)(R,{htmlFor:`report-description`,children:`Description`}),(0,K.jsx)(P,{id:`report-description`,value:s.description||``,onChange:e=>c({...s,description:e.target.value}),placeholder:`Enter report description`})]}),n.length>0&&(0,K.jsxs)(`div`,{className:`space-y-2`,children:[(0,K.jsx)(R,{children:`Data Source`}),(0,K.jsxs)(`select`,{className:`w-full border rounded-md p-2`,children:[(0,K.jsx)(`option`,{value:``,children:`Select a data source`}),n.map((e,t)=>(0,K.jsxs)(`option`,{value:t,children:[`Data Source `,t+1]},t))]})]}),(0,K.jsxs)(`div`,{className:`space-y-2`,children:[(0,K.jsx)(R,{children:`Export Options`}),(0,K.jsxs)(`div`,{className:`flex items-center gap-4`,children:[(0,K.jsxs)(`label`,{className:`flex items-center gap-2`,children:[(0,K.jsx)(`input`,{type:`checkbox`,checked:s.showExportButtons||!1,onChange:e=>c({...s,showExportButtons:e.target.checked})}),(0,K.jsx)(`span`,{className:`text-sm`,children:`Show Export Buttons`})]}),(0,K.jsxs)(`label`,{className:`flex items-center gap-2`,children:[(0,K.jsx)(`input`,{type:`checkbox`,checked:s.showPrintButton||!1,onChange:e=>c({...s,showPrintButton:e.target.checked})}),(0,K.jsx)(`span`,{className:`text-sm`,children:`Show Print Button`})]})]})]}),(0,K.jsxs)(`div`,{className:`space-y-2`,children:[(0,K.jsx)(R,{htmlFor:`export-format`,children:`Default Export Format`}),(0,K.jsxs)(`select`,{id:`export-format`,className:`w-full border rounded-md p-2`,value:s.defaultExportFormat||`pdf`,onChange:e=>c({...s,defaultExportFormat:e.target.value}),children:[(0,K.jsx)(`option`,{value:`pdf`,children:`PDF`}),(0,K.jsx)(`option`,{value:`excel`,children:`Excel`}),(0,K.jsx)(`option`,{value:`csv`,children:`CSV`}),(0,K.jsx)(`option`,{value:`json`,children:`JSON`}),(0,K.jsx)(`option`,{value:`html`,children:`HTML`})]})]})]})}),(0,K.jsxs)(I,{value:`fields`,className:`space-y-4 mt-4`,children:[(0,K.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,K.jsx)(R,{children:`Report Fields`}),(0,K.jsxs)(V,{size:`sm`,variant:`outline`,onClick:b,disabled:l.length>=r.length,children:[(0,K.jsx)(W,{className:`h-4 w-4 mr-2`}),`Add Field`]})]}),(0,K.jsxs)(`div`,{className:`space-y-2`,children:[l.map((e,t)=>(0,K.jsx)(`div`,{className:`flex items-center gap-2 p-3 border rounded-lg`,children:(0,K.jsxs)(`div`,{className:`flex-1 grid grid-cols-4 gap-2`,children:[(0,K.jsxs)(`div`,{children:[(0,K.jsx)(R,{className:`text-xs`,children:`Field Name`}),(0,K.jsx)(`div`,{className:`text-sm font-medium`,children:e.name})]}),(0,K.jsxs)(`div`,{children:[(0,K.jsx)(R,{className:`text-xs`,children:`Label`}),(0,K.jsx)(P,{className:`h-8 text-sm`,value:e.label||e.name,onChange:n=>w(t,{...e,label:n.target.value})})]}),(0,K.jsxs)(`div`,{children:[(0,K.jsx)(R,{className:`text-xs`,children:`Aggregation`}),(0,K.jsxs)(`select`,{className:`w-full border rounded-md h-8 text-sm px-2`,value:e.aggregation||``,onChange:n=>w(t,{...e,aggregation:n.target.value}),children:[(0,K.jsx)(`option`,{value:``,children:`None`}),(0,K.jsx)(`option`,{value:`sum`,children:`Sum`}),(0,K.jsx)(`option`,{value:`count`,children:`Count`}),(0,K.jsx)(`option`,{value:`avg`,children:`Average`}),(0,K.jsx)(`option`,{value:`min`,children:`Min`}),(0,K.jsx)(`option`,{value:`max`,children:`Max`})]})]}),(0,K.jsx)(`div`,{className:`flex items-end justify-end`,children:(0,K.jsx)(V,{size:`sm`,variant:`ghost`,className:`text-red-500 hover:text-red-700 hover:bg-red-50`,onClick:()=>x(t),children:(0,K.jsx)(C,{className:`h-4 w-4`})})})]})},t)),l.length===0&&(0,K.jsx)(`div`,{className:`text-center py-8 text-muted-foreground border-2 border-dashed rounded-lg`,children:`No fields selected. Click "Add Field" to begin.`})]})]}),(0,K.jsxs)(I,{value:`filters`,className:`space-y-4 mt-4`,children:[(0,K.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,K.jsx)(R,{children:`Report Filters`}),(0,K.jsxs)(V,{size:`sm`,variant:`outline`,onClick:T,children:[(0,K.jsx)(W,{className:`h-4 w-4 mr-2`}),`Add Filter`]})]}),(0,K.jsxs)(`div`,{className:`space-y-2`,children:[f.map((e,t)=>(0,K.jsxs)(`div`,{className:`flex items-center gap-2 p-3 border rounded-lg`,children:[(0,K.jsxs)(`div`,{className:`flex-1 grid grid-cols-3 gap-2`,children:[(0,K.jsxs)(`div`,{children:[(0,K.jsx)(R,{className:`text-xs`,children:`Field`}),(0,K.jsx)(`select`,{className:`w-full border rounded-md h-8 text-sm px-2`,value:e.field,onChange:n=>O(t,{...e,field:n.target.value}),children:r.map((e,t)=>(0,K.jsx)(`option`,{value:e.name,children:e.label||e.name},t))})]}),(0,K.jsxs)(`div`,{children:[(0,K.jsx)(R,{className:`text-xs`,children:`Operator`}),(0,K.jsxs)(`select`,{className:`w-full border rounded-md h-8 text-sm px-2`,value:e.operator,onChange:n=>O(t,{...e,operator:n.target.value}),children:[(0,K.jsx)(`option`,{value:`equals`,children:`Equals`}),(0,K.jsx)(`option`,{value:`contains`,children:`Contains`}),(0,K.jsx)(`option`,{value:`gt`,children:`Greater Than`}),(0,K.jsx)(`option`,{value:`lt`,children:`Less Than`}),(0,K.jsx)(`option`,{value:`between`,children:`Between`})]})]}),(0,K.jsxs)(`div`,{children:[(0,K.jsx)(R,{className:`text-xs`,children:`Value`}),(0,K.jsx)(P,{className:`h-8 text-sm`,value:String(e.value),onChange:n=>O(t,{...e,value:n.target.value})})]})]}),(0,K.jsx)(V,{size:`sm`,variant:`ghost`,className:`text-red-500 hover:text-red-700 hover:bg-red-50 self-end`,onClick:()=>E(t),children:(0,K.jsx)(C,{className:`h-4 w-4`})})]},t)),f.length===0&&(0,K.jsx)(`div`,{className:`text-center py-8 text-muted-foreground border-2 border-dashed rounded-lg`,children:`No filters defined.`})]})]}),(0,K.jsxs)(I,{value:`grouping`,className:`space-y-4 mt-4`,children:[(0,K.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,K.jsx)(R,{children:`Grouping Rules`}),(0,K.jsxs)(V,{size:`sm`,variant:`outline`,onClick:k,children:[(0,K.jsx)(W,{className:`h-4 w-4 mr-2`}),`Add Group`]})]}),(0,K.jsxs)(`div`,{className:`space-y-2`,children:[m.map((e,t)=>(0,K.jsxs)(`div`,{className:`flex items-center gap-2 p-3 border rounded-lg`,children:[(0,K.jsxs)(`div`,{className:`flex-1 grid grid-cols-2 gap-2`,children:[(0,K.jsxs)(`div`,{children:[(0,K.jsx)(R,{className:`text-xs`,children:`Field`}),(0,K.jsx)(`select`,{className:`w-full border rounded-md h-8 text-sm px-2`,value:e.field,onChange:n=>N(t,{...e,field:n.target.value}),children:r.map((e,t)=>(0,K.jsx)(`option`,{value:e.name,children:e.label||e.name},t))})]}),(0,K.jsxs)(`div`,{children:[(0,K.jsx)(R,{className:`text-xs`,children:`Sort Order`}),(0,K.jsxs)(`select`,{className:`w-full border rounded-md h-8 text-sm px-2`,value:e.sort||`asc`,onChange:n=>N(t,{...e,sort:n.target.value}),children:[(0,K.jsx)(`option`,{value:`asc`,children:`Ascending`}),(0,K.jsx)(`option`,{value:`desc`,children:`Descending`})]})]})]}),(0,K.jsx)(V,{size:`sm`,variant:`ghost`,className:`text-red-500 hover:text-red-700 hover:bg-red-50 self-end`,onClick:()=>M(t),children:(0,K.jsx)(C,{className:`h-4 w-4`})})]},t)),m.length===0&&(0,K.jsx)(`div`,{className:`text-center py-8 text-muted-foreground border-2 border-dashed rounded-lg`,children:`No grouping rules applied.`})]})]}),(0,K.jsxs)(I,{value:`sections`,className:`space-y-4 mt-4`,children:[(0,K.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,K.jsx)(R,{children:`Report Sections`}),(0,K.jsxs)(`div`,{className:`flex gap-2`,children:[(0,K.jsxs)(V,{size:`sm`,variant:`outline`,onClick:()=>F(`header`),children:[(0,K.jsx)(W,{className:`h-4 w-4 mr-2`}),`Header`]}),(0,K.jsxs)(V,{size:`sm`,variant:`outline`,onClick:()=>F(`chart`),children:[(0,K.jsx)(W,{className:`h-4 w-4 mr-2`}),`Chart`]}),(0,K.jsxs)(V,{size:`sm`,variant:`outline`,onClick:()=>F(`table`),children:[(0,K.jsx)(W,{className:`h-4 w-4 mr-2`}),`Table`]})]})]}),(0,K.jsxs)(`div`,{className:`space-y-2`,children:[g.map((e,t)=>(0,K.jsxs)(`div`,{className:`p-3 border rounded-lg space-y-2`,children:[(0,K.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,K.jsxs)(`div`,{className:`font-medium flex items-center gap-2`,children:[(0,K.jsx)(`div`,{className:`text-xs bg-muted px-2 py-0.5 rounded uppercase`,children:e.type}),e.title]}),(0,K.jsx)(V,{size:`sm`,variant:`ghost`,className:`text-red-500 hover:text-red-700 hover:bg-red-50`,onClick:()=>z(t),children:(0,K.jsx)(C,{className:`h-4 w-4`})})]}),(0,K.jsxs)(`div`,{className:`grid grid-cols-2 gap-2`,children:[(0,K.jsxs)(`div`,{children:[(0,K.jsx)(R,{className:`text-xs`,children:`Title`}),(0,K.jsx)(P,{className:`h-8 text-sm`,value:e.title||``,onChange:n=>B(t,{...e,title:n.target.value})})]}),e.type===`text`&&(0,K.jsxs)(`div`,{className:`col-span-2`,children:[(0,K.jsx)(R,{className:`text-xs`,children:`Content`}),(0,K.jsx)(P,{className:`h-8 text-sm`,value:e.text||``,onChange:n=>B(t,{...e,text:n.target.value})})]}),e.type===`chart`&&(0,K.jsxs)(`div`,{className:`col-span-2 grid grid-cols-2 gap-2 mt-2 p-2 bg-muted/20 rounded`,children:[(0,K.jsx)(`div`,{className:`col-span-2`,children:(0,K.jsx)(R,{className:`text-xs font-semibold`,children:`Chart Configuration`})}),(0,K.jsxs)(`div`,{children:[(0,K.jsx)(R,{className:`text-xs`,children:`Chart Type`}),(0,K.jsxs)(`select`,{className:`flex h-8 w-full rounded-md border border-input bg-background px-3 py-1 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50`,value:e.chart?.chartType||`bar`,onChange:n=>B(t,{...e,chart:{...e.chart,type:`chart`,chartType:n.target.value}}),children:[(0,K.jsx)(`option`,{value:`bar`,children:`Bar`}),(0,K.jsx)(`option`,{value:`line`,children:`Line`}),(0,K.jsx)(`option`,{value:`area`,children:`Area`}),(0,K.jsx)(`option`,{value:`pie`,children:`Pie`})]})]}),(0,K.jsxs)(`div`,{children:[(0,K.jsx)(R,{className:`text-xs`,children:`X-Axis Field`}),(0,K.jsxs)(`select`,{className:`flex h-8 w-full rounded-md border border-input bg-background px-3 py-1 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50`,value:e.chart?.xAxisField||``,onChange:n=>B(t,{...e,chart:{...e.chart,type:`chart`,xAxisField:n.target.value}}),children:[(0,K.jsx)(`option`,{value:``,children:`Select Field...`}),r.map(e=>(0,K.jsx)(`option`,{value:e.name,children:e.label||e.name},e.name)),r.length===0&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`option`,{value:`name`,children:`Name`}),(0,K.jsx)(`option`,{value:`month`,children:`Month`})]})]})]}),(0,K.jsxs)(`div`,{className:`col-span-2`,children:[(0,K.jsx)(R,{className:`text-xs`,children:`Y-Axis Fields (comma separated)`}),(0,K.jsx)(P,{className:`h-8 text-sm`,placeholder:`e.g. value, count`,value:e.chart?.yAxisFields?.join(`, `)||``,onChange:n=>B(t,{...e,chart:{...e.chart,type:`chart`,yAxisFields:n.target.value.split(`,`).map(e=>e.trim()).filter(Boolean)}})})]})]})]})]},t)),g.length===0&&(0,K.jsx)(`div`,{className:`text-center py-8 text-muted-foreground border-2 border-dashed rounded-lg`,children:`No customized sections. The default report layout will be used.`})]})]}),(0,K.jsx)(I,{value:`schedule`,className:`space-y-4 mt-4`,children:(0,K.jsx)(dt,{schedule:s.schedule,onChange:e=>c({...s,schedule:e})})})]}),(0,K.jsxs)(`div`,{className:`flex items-center justify-end gap-2 mt-6 pt-4 border-t`,children:[(0,K.jsx)(V,{variant:`outline`,onClick:()=>{o&&console.log(`Report cancelled:`,o)},children:`Cancel`}),(0,K.jsxs)(V,{onClick:()=>{console.log(`Saving report:`,s),a&&alert(`Report saved! (Handler: `+a+`)`)},children:[(0,K.jsx)(ee,{className:`h-4 w-4 mr-2`}),`Save Report`]})]})]})]}),i&&(0,K.jsxs)(y,{className:`mt-8 border-2 border-blue-100`,children:[(0,K.jsx)(j,{className:`bg-blue-50/50`,children:(0,K.jsx)(A,{className:`text-blue-900 text-sm uppercase tracking-wide`,children:`Live Preview`})}),(0,K.jsx)(U,{className:`pt-6`,children:(0,K.jsx)(ut,{schema:{type:`report-viewer`,report:{...s,fields:l,filters:f,groupBy:m,sections:g},data:[{id:1,name:`Sample Item A`,value:100,status:`New`},{id:2,name:`Sample Item B`,value:250,status:`Active`},{id:3,name:`Sample Item C`,value:75,status:`Closed`}]}})})]})]})},pt=[`tabular`,`summary`,`matrix`];function mt(e){let t=e.length+1,n=new Set(e.map(e=>e.name).filter(Boolean)),r=`block_${t}`;for(;n.has(r);)t+=1,r=`block_${t}`;return{name:r,type:`tabular`,columns:[]}}function ht(e){return typeof e.label==`string`?e.label:e.label&&typeof e.label==`object`?e.label.default??``:``}function gt(e){return typeof e.description==`string`?e.description:e.description&&typeof e.description==`object`?e.description.default??``:``}function _t({block:e,index:t,total:n,availableFields:r,t:i,duplicateName:a,onChange:o,onRemove:s,onMove:c}){let[l,u]=G.useState(t===0),d=e.type??`tabular`,f=d===`summary`,p=d===`matrix`,h=f||p,g=!e.name||!e.name.trim(),_=g||a,v=t=>o({...e,...t});return(0,K.jsxs)(`div`,{className:`border rounded-md bg-card text-card-foreground`,"data-testid":`joined-block-${t}`,children:[(0,K.jsxs)(`div`,{className:`flex items-center gap-1 p-1.5 border-b bg-muted/30`,children:[(0,K.jsx)(V,{type:`button`,size:`sm`,variant:`ghost`,className:`h-6 w-6 p-0 shrink-0`,onClick:()=>u(e=>!e),"aria-label":l?`Collapse block`:`Expand block`,"aria-expanded":l,"data-testid":`joined-block-toggle-${t}`,children:l?(0,K.jsx)(le,{className:`h-3.5 w-3.5`}):(0,K.jsx)(N,{className:`h-3.5 w-3.5`})}),(0,K.jsx)(`input`,{type:`text`,className:`h-6 text-xs border rounded px-1.5 bg-background flex-1 min-w-0 ${_?`border-destructive`:``}`,value:e.name??``,onChange:e=>v({name:e.target.value}),placeholder:i(`report.editor.blockNamePlaceholder`),"aria-label":i(`report.editor.blockName`),"aria-invalid":_,"data-testid":`joined-block-name-${t}`}),(0,K.jsx)(`select`,{className:`h-6 text-xs border rounded px-1 bg-background shrink-0`,value:d,onChange:e=>v({type:e.target.value}),"aria-label":i(`report.editor.type`),"data-testid":`joined-block-type-${t}`,children:pt.map(e=>(0,K.jsx)(`option`,{value:e,children:i(`report.editor.type${e.charAt(0).toUpperCase()}${e.slice(1)}`)},e))}),(0,K.jsxs)(`div`,{className:`flex flex-col gap-0.5 shrink-0`,children:[(0,K.jsx)(`button`,{type:`button`,className:`text-muted-foreground hover:text-foreground disabled:opacity-30`,disabled:t===0,onClick:()=>c(-1),"aria-label":`Move block up`,children:(0,K.jsx)(m,{className:`h-2.5 w-2.5`})}),(0,K.jsx)(`button`,{type:`button`,className:`text-muted-foreground hover:text-foreground disabled:opacity-30`,disabled:t===n-1,onClick:()=>c(1),"aria-label":`Move block down`,children:(0,K.jsx)(b,{className:`h-2.5 w-2.5`})})]}),(0,K.jsx)(V,{type:`button`,size:`sm`,variant:`ghost`,className:`h-6 w-6 p-0 shrink-0 text-destructive hover:text-destructive`,onClick:s,"aria-label":i(`report.editor.removeBlock`),"data-testid":`joined-block-remove-${t}`,children:(0,K.jsx)(C,{className:`h-3 w-3`})})]}),_&&(0,K.jsxs)(`div`,{className:`flex items-center gap-1 px-2 py-1 text-[10px] text-destructive bg-destructive/5 border-b`,children:[(0,K.jsx)(z,{className:`h-3 w-3`}),i(g?`report.editor.validationBlockNameRequired`:`report.editor.validationBlockNameDuplicate`)]}),l&&(0,K.jsxs)(`div`,{className:`p-2 space-y-2 text-xs`,children:[(0,K.jsxs)(`div`,{className:`grid grid-cols-2 gap-2`,children:[(0,K.jsxs)(`label`,{className:`flex flex-col gap-0.5`,children:[(0,K.jsx)(`span`,{className:`text-[10px] text-muted-foreground`,children:i(`report.editor.blockLabel`)}),(0,K.jsx)(`input`,{type:`text`,className:`h-6 text-xs border rounded px-1.5 bg-background`,value:ht(e),onChange:e=>v({label:e.target.value||void 0}),placeholder:i(`report.editor.blockLabelPlaceholder`),"data-testid":`joined-block-label-${t}`})]}),(0,K.jsxs)(`label`,{className:`flex flex-col gap-0.5`,children:[(0,K.jsx)(`span`,{className:`text-[10px] text-muted-foreground`,children:i(`report.editor.objectName`)}),(0,K.jsx)(`input`,{type:`text`,className:`h-6 text-xs border rounded px-1.5 bg-background`,value:e.objectName??``,onChange:e=>v({objectName:e.target.value||void 0}),placeholder:i(`report.editor.objectNamePlaceholder`),"data-testid":`joined-block-object-${t}`})]})]}),(0,K.jsxs)(`label`,{className:`flex flex-col gap-0.5`,children:[(0,K.jsx)(`span`,{className:`text-[10px] text-muted-foreground`,children:i(`report.editor.blockDescription`)}),(0,K.jsx)(`textarea`,{className:`text-xs border rounded px-1.5 py-1 bg-background resize-y min-h-[2rem]`,rows:2,value:gt(e),onChange:e=>v({description:e.target.value||void 0}),placeholder:i(`report.editor.blockDescriptionPlaceholder`),"data-testid":`joined-block-description-${t}`})]}),(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`div`,{className:`text-[10px] text-muted-foreground mb-0.5`,children:i(`report.editor.columns`)}),(0,K.jsx)(It,{availableFields:r,value:e.columns,onChange:e=>v({columns:e}),t:i})]}),(f||p)&&(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`div`,{className:`text-[10px] text-muted-foreground mb-0.5`,children:i(`report.editor.rows`)}),(0,K.jsx)(Lt,{availableFields:r,value:e.groupingsDown,onChange:e=>v({groupingsDown:e}),t:i})]}),p&&(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`div`,{className:`text-[10px] text-muted-foreground mb-0.5`,children:i(`report.editor.columnsAxis`)}),(0,K.jsx)(Lt,{availableFields:r,value:e.groupingsAcross,onChange:e=>v({groupingsAcross:e}),t:i})]}),(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`div`,{className:`text-[10px] text-muted-foreground mb-0.5`,children:i(`report.editor.filters`)}),(0,K.jsx)(kt,{availableFields:r,value:e.filter,onChange:e=>v({filter:e}),t:i})]}),h&&(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`div`,{className:`text-[10px] text-muted-foreground mb-0.5`,children:i(`report.editor.chart`)}),(0,K.jsx)(Rt,{availableFields:r,columns:Ft(e.columns),value:e.chart,onChange:e=>v({chart:e}),t:i})]})]})]})}function vt(e){return Array.isArray(e)?e.map(e=>{let t=e??{};return{name:t.name??``,type:t.type??`tabular`,columns:Array.isArray(t.columns)?t.columns:[],...t}}):[]}function yt({value:e,onChange:t,availableFields:n,getFieldsForObject:r,containerObjectName:i,t:a}){let o=vt(e),s=e=>r?r(e.objectName??i)??n:n,c={};for(let e of o)e.name&&(c[e.name]=(c[e.name]??0)+1);let l=(e,n)=>{t(o.map((t,r)=>r===e?n:t))},u=e=>{t(o.filter((t,n)=>n!==e))},d=(e,n)=>{let r=e+n;if(r<0||r>=o.length)return;let i=[...o];[i[e],i[r]]=[i[r],i[e]],t(i)};return(0,K.jsxs)(`div`,{className:`space-y-2`,"data-testid":`joined-blocks-editor`,children:[o.length===0&&(0,K.jsx)(`div`,{className:`text-[10px] text-muted-foreground italic px-1`,children:a(`report.editor.validationJoinedNeedsBlocks`)}),o.map((e,t)=>(0,K.jsx)(_t,{block:e,index:t,total:o.length,availableFields:s(e),t:a,duplicateName:!!e.name&&(c[e.name]??0)>1,onChange:e=>l(t,e),onRemove:()=>u(t),onMove:e=>d(t,e)},t)),(0,K.jsxs)(V,{type:`button`,size:`sm`,variant:`outline`,className:`h-7 text-xs w-full`,onClick:()=>{t([...o,mt(o)])},"data-testid":`joined-block-add`,children:[(0,K.jsx)(W,{className:`h-3 w-3 mr-1`}),a(`report.editor.addBlock`)]})]})}function bt(e,t){let n=[];if(!Array.isArray(e)||e.length===0)return n.push(t(`report.editor.validationJoinedNeedsBlocks`)),n;let r=new Map,i=!1,a=!1,o=!1;for(let t of e){let e=t??{};if(!e.name||!String(e.name).trim())i=!0;else{let t=(r.get(e.name)??0)+1;r.set(e.name,t),t===2&&(a=!0)}(!Array.isArray(e.columns)||e.columns.length===0)&&(o=!0)}return i&&n.push(t(`report.editor.validationBlockNameRequired`)),a&&n.push(t(`report.editor.validationBlockNameDuplicate`)),o&&n.push(t(`report.editor.validationBlockNeedsColumns`)),n}var xt={$eq:`equals`,$ne:`notEquals`,$gt:`greaterThan`,$gte:`greaterOrEqual`,$lt:`lessThan`,$lte:`lessOrEqual`,$in:`in`,$nin:`notIn`,$contains:`contains`,$notContains:`notContains`,$exists:`isNotEmpty`},St={equals:`$eq`,notEquals:`$ne`,greaterThan:`$gt`,greaterOrEqual:`$gte`,lessThan:`$lt`,lessOrEqual:`$lte`,in:`$in`,notIn:`$nin`,contains:`$contains`,notContains:`$notContains`},Ct=()=>({id:`root`,logic:`and`,conditions:[]});function wt(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function $(){return Math.random().toString(36).slice(2,10)}function Tt(e,t){if(typeof t!=`object`||!t||Array.isArray(t))return[{id:$(),field:e,operator:Array.isArray(t)?`in`:`equals`,value:t}];let n=[];for(let[r,i]of Object.entries(t)){if(r===`$exists`){n.push({id:$(),field:e,operator:i===!1?`isEmpty`:`isNotEmpty`,value:``});continue}if(r===`$null`){n.push({id:$(),field:e,operator:i===!1?`isNotEmpty`:`isEmpty`,value:``});continue}let t=xt[r];if(!t||wt(i)&&`$field`in i)return null;n.push({id:$(),field:e,operator:t,value:i})}return n.length>0?n:null}function Et(e){if(e==null)return{group:Ct(),complex:!1};if(!wt(e))return{group:Ct(),complex:!0};let t=Object.keys(e);if(t.length===1&&(t[0]===`$and`||t[0]===`$or`)){let n=t[0]===`$or`?`or`:`and`,r=e[t[0]];if(!Array.isArray(r))return{group:Ct(),complex:!0};let i=[],a=!1;for(let e of r){if(!wt(e)){a=!0;continue}if(Object.keys(e).some(e=>e===`$and`||e===`$or`||e===`$not`)){a=!0;continue}for(let[t,n]of Object.entries(e)){let e=Tt(t,n);e?i.push(...e):a=!0}}return{group:{id:`root`,logic:n,conditions:i},complex:a}}if(t.includes(`$not`)||t.includes(`$and`)||t.includes(`$or`))return{group:Ct(),complex:!0};let n=[],r=!1;for(let[t,i]of Object.entries(e)){let e=Tt(t,i);e?n.push(...e):r=!0}return{group:{id:`root`,logic:`and`,conditions:n},complex:r}}function Dt(e){if(!e||!Array.isArray(e.conditions)||e.conditions.length===0)return;let t=e.conditions.filter(e=>e.field).map(e=>Ot(e));if(t.length!==0)return t.length===1?t[0]:{[e.logic===`or`?`$or`:`$and`]:t}}function Ot(e){let{field:t,operator:n,value:r}=e;if(n===`isEmpty`)return{[t]:{$exists:!1}};if(n===`isNotEmpty`)return{[t]:{$exists:!0}};if(n===`equals`)return{[t]:r};let i=St[n];return i?{[t]:{[i]:r}}:{[t]:r}}function kt({availableFields:e,value:t,onChange:n,t:r}){let i=G.useMemo(()=>JSON.stringify(t??null),[t]),a=G.useMemo(()=>Et(t),[i]),[o,s]=G.useState(a.group),c=G.useRef(i);G.useEffect(()=>{c.current!==i&&(s(a.group),c.current=i)},[i,a.group]);let l=e=>{s(e);let t=Dt(e);c.current=JSON.stringify(t??null),n(t)};if(a.complex)return(0,K.jsxs)(`div`,{className:`flex items-start gap-2 p-2 rounded border border-amber-300 bg-amber-50 text-amber-900 text-[11px]`,children:[(0,K.jsx)(z,{className:`h-3.5 w-3.5 mt-0.5 shrink-0`}),(0,K.jsx)(`span`,{children:r(`report.editor.filtersComplex`)})]});let u=()=>{l({...o,conditions:[...o.conditions,{id:$(),field:e[0]?.value??``,operator:`equals`,value:``}]})},d=e=>{l({...o,conditions:o.conditions.filter(t=>t.id!==e)})},f=(e,t)=>{l({...o,conditions:o.conditions.map(n=>n.id===e?{...n,...t}:n)})},p=[{value:`equals`,label:`=`},{value:`notEquals`,label:`≠`},{value:`greaterThan`,label:`>`},{value:`greaterOrEqual`,label:`≥`},{value:`lessThan`,label:`<`},{value:`lessOrEqual`,label:`≤`},{value:`contains`,label:r(`report.editor.opContains`,`contains`)},{value:`in`,label:`in`},{value:`notIn`,label:`not in`},{value:`isEmpty`,label:r(`report.editor.opIsEmpty`,`is empty`)},{value:`isNotEmpty`,label:r(`report.editor.opIsNotEmpty`,`is not empty`)}];return(0,K.jsxs)(`div`,{className:`space-y-1.5 py-1`,"data-testid":`spec-filter-adapter`,children:[o.conditions.length>1&&(0,K.jsxs)(`div`,{className:`flex items-center gap-2 text-[10px] text-muted-foreground`,children:[(0,K.jsx)(`span`,{children:r(`report.editor.combineLogic`,`Combine with`)}),(0,K.jsxs)(`select`,{className:`h-5 text-[10px] border rounded px-1 bg-background`,value:o.logic,onChange:e=>l({...o,logic:e.target.value}),"data-testid":`filter-logic-select`,children:[(0,K.jsx)(`option`,{value:`and`,children:`AND`}),(0,K.jsx)(`option`,{value:`or`,children:`OR`})]})]}),o.conditions.map(t=>(0,K.jsxs)(`div`,{className:`flex items-center gap-1 text-[10px] p-1 border rounded bg-muted/20`,children:[(0,K.jsx)(`select`,{className:`h-5 text-[10px] border rounded px-1 bg-background flex-1 min-w-0`,value:t.field,onChange:e=>f(t.id,{field:e.target.value}),"data-testid":`filter-field-${t.id}`,children:e.map(e=>(0,K.jsx)(`option`,{value:e.value,children:e.label},e.value))}),(0,K.jsx)(`select`,{className:`h-5 text-[10px] border rounded px-1 bg-background w-20 shrink-0`,value:t.operator,onChange:e=>f(t.id,{operator:e.target.value}),"data-testid":`filter-op-${t.id}`,children:p.map(e=>(0,K.jsx)(`option`,{value:e.value,children:e.label},e.value))}),t.operator!==`isEmpty`&&t.operator!==`isNotEmpty`&&(0,K.jsx)(`input`,{className:`h-5 text-[10px] border rounded px-1 bg-background w-24 shrink-0`,value:Array.isArray(t.value)?t.value.join(`,`):(t.value??``).toString(),placeholder:`value`,onChange:e=>{let n=e.target.value,r=t.operator===`in`||t.operator===`notIn`?n.split(`,`).map(e=>e.trim()).filter(Boolean):n;f(t.id,{value:r})},"data-testid":`filter-value-${t.id}`}),(0,K.jsx)(V,{type:`button`,size:`sm`,variant:`ghost`,className:`h-5 w-5 p-0 shrink-0`,onClick:()=>d(t.id),"data-testid":`filter-remove-${t.id}`,children:(0,K.jsx)(C,{className:`h-3 w-3`})})]},t.id)),(0,K.jsxs)(V,{type:`button`,size:`sm`,variant:`outline`,className:`h-6 text-[10px] w-full`,onClick:u,disabled:e.length===0,"data-testid":`filter-add`,children:[(0,K.jsx)(W,{className:`h-3 w-3 mr-1`}),r(`report.editor.addCondition`,`Add condition`)]})]})}var At=new Set([`date`,`datetime`,`time`]),jt=new Set([`number`,`currency`,`percent`,`rating`,`integer`]);function Mt({availableFields:e,selectedValues:t,onAdd:n,t:r,triggerLabel:i,title:a,description:o,testIdPrefix:s=`field-picker`,singleSelect:c=!1,commitOnSelect:l=!1,disabled:u=!1,triggerClassName:d,trigger:f}){let[m,v]=G.useState(!1),[y,b]=G.useState(``),[S,C]=G.useState(new Set),w=G.useMemo(()=>new Set(t),[t]);G.useEffect(()=>{m&&(b(``),C(new Set))},[m]);let E=y.trim().toLowerCase(),D=e.filter(e=>!w.has(e.value)),O=E?D.filter(e=>e.label.toLowerCase().includes(E)||e.value.toLowerCase().includes(E)):D,A=e=>{if(c&&l){n([e]),v(!1);return}C(t=>{let n=new Set(c?[]:t);return t.has(e)?n.delete(e):n.add(e),n})},j=()=>{if(S.size===0){v(!1);return}n(D.map(e=>e.value).filter(e=>S.has(e))),v(!1)},M=()=>{v(!1)},N=e.length===0,P=!N&&D.length===0,F=i??r(`report.editor.addColumns`,`Add fields`),I=a??r(`report.editor.fieldPickerTitle`,`Select fields`),L=o??r(`report.editor.fieldPickerDescription`,`Pick one or more fields to add. Use the search box to narrow the list.`);return(0,K.jsxs)(h,{open:m,onOpenChange:v,children:[(0,K.jsx)(k,{asChild:!0,children:f??(0,K.jsxs)(V,{type:`button`,variant:`outline`,size:`sm`,className:d??`h-8 gap-1.5`,disabled:u||N||P,"data-testid":`${s}-trigger`,children:[(0,K.jsx)(W,{className:`h-3.5 w-3.5`}),(0,K.jsx)(`span`,{children:F})]})}),(0,K.jsxs)(_,{className:`sm:max-w-md max-w-[92vw] gap-3`,"data-testid":`${s}-dialog`,children:[(0,K.jsxs)(ue,{children:[(0,K.jsx)(p,{children:I}),(0,K.jsx)(x,{children:L})]}),(0,K.jsxs)(`div`,{className:`relative`,children:[(0,K.jsx)(te,{className:`pointer-events-none absolute left-2 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground`}),(0,K.jsx)(`input`,{type:`text`,className:`h-9 w-full text-sm border rounded pl-7 pr-2 bg-background`,placeholder:r(`report.editor.searchFields`,`Search fields…`),value:y,onChange:e=>b(e.target.value),"data-testid":`${s}-search`,autoFocus:!0})]}),(0,K.jsxs)(`div`,{className:`text-[11px] text-muted-foreground flex items-center justify-between`,children:[(0,K.jsxs)(`span`,{children:[O.length,`/`,D.length,S.size>0?` · ${r(`report.editor.fieldPickerSelected`,`{n} selected`).replace(`{n}`,String(S.size))}`:``]}),S.size>0&&(0,K.jsx)(`button`,{type:`button`,className:`text-[11px] underline-offset-2 hover:underline text-muted-foreground`,onClick:()=>C(new Set),"data-testid":`${s}-clear`,children:r(`report.editor.fieldPickerClear`,`Clear selection`)})]}),(0,K.jsx)(`div`,{className:`max-h-72 overflow-auto border rounded bg-background/40 p-1 space-y-0.5`,"data-testid":`${s}-list`,children:N?(0,K.jsx)(`div`,{className:`text-xs text-muted-foreground px-2 py-3 text-center`,children:r(`report.editor.noFields`,`No fields available — pick a data source first.`)}):P?(0,K.jsx)(`div`,{className:`text-xs text-muted-foreground px-2 py-3 text-center`,children:r(`report.editor.noFieldsAvailable`,`All fields already added.`)}):O.length===0?(0,K.jsx)(`div`,{className:`text-xs text-muted-foreground px-2 py-3 text-center`,children:r(`report.editor.noMatchingFields`,`No fields match your search.`)}):O.map(e=>{let t=S.has(e.value);return(0,K.jsxs)(`label`,{className:`flex items-center gap-2 px-2 py-1.5 rounded hover:bg-muted/50 text-sm cursor-pointer`,"data-testid":`${s}-row-${e.value}`,children:[(0,K.jsx)(g,{checked:t,onCheckedChange:()=>A(e.value),"data-testid":`${s}-toggle-${e.value}`}),(0,K.jsx)(`span`,{className:`flex-1 truncate`,title:e.label,children:e.label}),e.type&&(0,K.jsx)(`span`,{className:`text-[10px] text-muted-foreground shrink-0`,children:e.type})]},e.value)})}),!(c&&l)&&(0,K.jsxs)(T,{className:`gap-2 sm:gap-2`,children:[(0,K.jsx)(V,{type:`button`,variant:`ghost`,size:`sm`,onClick:M,"data-testid":`${s}-cancel`,children:r(`common.cancel`,`Cancel`)}),(0,K.jsx)(V,{type:`button`,size:`sm`,onClick:j,disabled:S.size===0,"data-testid":`${s}-confirm`,children:S.size>0?r(`report.editor.fieldPickerAddN`,`Add {n}`).replace(`{n}`,String(S.size)):r(`report.editor.fieldPickerAdd`,`Add`)})]})]})]})}function Nt(e){return[{value:``,label:e(`report.editor.noneOption`)},{value:`sum`,label:e(`report.aggregate.sum`)},{value:`count`,label:e(`report.aggregate.count`)},{value:`unique`,label:e(`report.aggregate.countDistinct`)},{value:`avg`,label:e(`report.aggregate.avg`)},{value:`min`,label:e(`report.aggregate.min`)},{value:`max`,label:e(`report.aggregate.max`)}]}function Pt(e){return[{value:``,label:e(`report.editor.formatAuto`,`Auto`)},{value:`currency`,label:e(`report.editor.formatCurrency`,`Currency`)},{value:`percent`,label:e(`report.editor.formatPercent`,`Percent`)},{value:`integer`,label:e(`report.editor.formatInteger`,`Integer`)},{value:`date`,label:e(`report.editor.formatDate`,`Date`)},{value:`datetime`,label:e(`report.editor.formatDatetime`,`Date & time`)}]}function Ft(e){return Array.isArray(e)?e.map(e=>typeof e==`string`?{field:e,label:e,type:`string`}:{field:e.field||e.name||e.value,label:e.label,type:e.type||`string`,aggregate:e.aggregate??e.aggregation,format:e.format}):[]}function It({availableFields:e,value:t,onChange:n,t:r}){let i=Ft(t),a=new Set(i.map(e=>e.field)),o=Nt(r),s=Pt(r),c=t=>{if(t.length===0)return;let r=t.filter(e=>!a.has(e)).map(t=>{let n=e.find(e=>e.value===t);return{field:t,label:n?.label,type:n?.type||`string`}});r.length!==0&&n([...i,...r])},l=e=>{n(i.filter(t=>t.field!==e))},u=(e,t)=>{n(i.map(n=>n.field===e?{...n,...t}:n))},d=(e,t)=>{let r=[...i],a=e+t;a<0||a>=r.length||([r[e],r[a]]=[r[a],r[e]],n(r))};return e.length===0?(0,K.jsx)(`div`,{className:`text-xs text-muted-foreground py-2`,"data-testid":`columns-editor-empty`,children:r(`report.editor.noFields`,`No fields available — pick a data source first.`)}):(0,K.jsxs)(`div`,{className:`space-y-2 py-1`,"data-testid":`columns-editor`,children:[i.length>0&&(0,K.jsx)(`div`,{className:`space-y-1.5`,"data-testid":`columns-selected`,children:i.map((t,n)=>{let a=e.find(e=>e.value===t.field);return(0,K.jsxs)(`div`,{className:`grid grid-cols-[auto_1fr_auto] gap-1.5 p-1.5 border rounded bg-muted/30 text-xs`,"data-testid":`column-row-${t.field}`,children:[(0,K.jsxs)(`div`,{className:`row-span-2 flex flex-col items-center justify-center gap-0.5`,children:[(0,K.jsx)(`button`,{type:`button`,className:`text-muted-foreground hover:text-foreground disabled:opacity-30`,disabled:n===0,onClick:()=>d(n,-1),"aria-label":`Move up`,"data-testid":`column-up-${t.field}`,children:(0,K.jsx)(m,{className:`h-3 w-3`})}),(0,K.jsx)(`button`,{type:`button`,className:`text-muted-foreground hover:text-foreground disabled:opacity-30`,disabled:n===i.length-1,onClick:()=>d(n,1),"aria-label":`Move down`,"data-testid":`column-down-${t.field}`,children:(0,K.jsx)(b,{className:`h-3 w-3`})})]}),(0,K.jsx)(`input`,{className:`h-7 text-xs border rounded px-2 bg-background min-w-0 w-full`,value:t.label??``,placeholder:a?.label??t.field,onChange:e=>u(t.field,{label:e.target.value||void 0}),"data-testid":`column-label-${t.field}`,title:a?.label??t.field}),(0,K.jsx)(V,{type:`button`,size:`sm`,variant:`ghost`,className:`row-span-2 h-7 w-7 p-0 shrink-0 self-start`,onClick:()=>l(t.field),"data-testid":`column-remove-${t.field}`,"aria-label":`Remove column`,children:(0,K.jsx)(C,{className:`h-3.5 w-3.5`})}),(0,K.jsxs)(`div`,{className:`grid grid-cols-2 gap-1.5`,children:[(0,K.jsxs)(`label`,{className:`flex flex-col gap-0.5 min-w-0`,children:[(0,K.jsx)(`span`,{className:`text-[10px] text-muted-foreground uppercase tracking-wide`,children:r(`report.editor.aggregateColumn`,`Aggregate`)}),(0,K.jsx)(`select`,{className:`h-7 text-xs border rounded px-1 bg-background w-full min-w-0`,value:t.aggregate??``,onChange:e=>u(t.field,{aggregate:e.target.value===``?void 0:e.target.value}),"data-testid":`column-agg-${t.field}`,children:o.map(e=>(0,K.jsx)(`option`,{value:e.value,children:e.label},e.value))})]}),(0,K.jsxs)(`label`,{className:`flex flex-col gap-0.5 min-w-0`,children:[(0,K.jsx)(`span`,{className:`text-[10px] text-muted-foreground uppercase tracking-wide`,children:r(`report.editor.formatColumn`,`Format`)}),(0,K.jsx)(`select`,{className:`h-7 text-xs border rounded px-1 bg-background w-full min-w-0`,value:t.format??``,onChange:e=>u(t.field,{format:e.target.value===``?void 0:e.target.value}),"data-testid":`column-fmt-${t.field}`,children:s.map(e=>(0,K.jsx)(`option`,{value:e.value,children:e.label},e.value))})]})]})]},t.field)})}),(0,K.jsxs)(`div`,{className:`flex items-center justify-between gap-2 pt-1`,children:[(0,K.jsx)(`div`,{className:`text-xs text-muted-foreground`,children:i.length>0?r(`report.editor.columnsCount`,`{n} column(s) selected`).replace(`{n}`,String(i.length)):r(`report.editor.columnsEmpty`,`No columns selected yet.`)}),(0,K.jsx)(Mt,{availableFields:e,selectedValues:i.map(e=>e.field),onAdd:c,t:r,testIdPrefix:`columns-picker`,triggerLabel:r(`report.editor.addColumns`,`Add fields`)})]})]})}function Lt({availableFields:e,value:t,onChange:n,t:r,testIdPrefix:i=`grouping`}){let a=Array.isArray(t)?t.map(e=>({field:e.field??``,sortOrder:e.sortOrder??e.sort??`asc`,dateGranularity:e.dateGranularity})):[],o=[{value:``,label:r(`report.editor.dateGranularityNone`)},{value:`day`,label:r(`report.editor.day`)},{value:`week`,label:r(`report.editor.week`)},{value:`month`,label:r(`report.editor.month`)},{value:`quarter`,label:r(`report.editor.quarter`)},{value:`year`,label:r(`report.editor.year`)}],s=a.map(e=>e.field).filter(Boolean),c=e=>{n(a.filter((t,n)=>n!==e))},l=(e,t)=>{n(a.map((n,r)=>r===e?{...n,...t}:n))},u=(e,t)=>{let r=[...a],i=e+t;i<0||i>=r.length||([r[e],r[i]]=[r[i],r[e]],n(r))},d=e=>{if(e.length===0)return;let t=e.map(e=>({field:e,sortOrder:`asc`}));n([...a,...t])},f=(t,n)=>{let r=n[0];if(!r)return;let i=e.find(e=>e.value===r);l(t,{field:r,dateGranularity:i&&At.has(i.type??``)?a[t]?.dateGranularity:void 0})};return(0,K.jsxs)(`div`,{className:`space-y-1.5 py-1`,"data-testid":`${i}s-builder`,children:[a.map((t,n)=>{let d=e.find(e=>e.value===t.field),p=d&&At.has(d.type??``),h=d?.label??t.field??r(`report.editor.fieldPickerEmpty`,`(pick field)`);return(0,K.jsxs)(`div`,{className:`flex items-center gap-1.5 p-1.5 border rounded bg-muted/20 text-xs`,"data-testid":`${i}-row-${n}`,children:[(0,K.jsxs)(`div`,{className:`flex flex-col gap-0.5 shrink-0`,children:[(0,K.jsx)(`button`,{type:`button`,className:`text-muted-foreground hover:text-foreground disabled:opacity-30`,disabled:n===0,onClick:()=>u(n,-1),"aria-label":`Move up`,"data-testid":`${i}-up-${n}`,children:(0,K.jsx)(m,{className:`h-3 w-3`})}),(0,K.jsx)(`button`,{type:`button`,className:`text-muted-foreground hover:text-foreground disabled:opacity-30`,disabled:n===a.length-1,onClick:()=>u(n,1),"aria-label":`Move down`,"data-testid":`${i}-down-${n}`,children:(0,K.jsx)(b,{className:`h-3 w-3`})})]}),(0,K.jsx)(Mt,{availableFields:e,selectedValues:s.filter(e=>e!==t.field),onAdd:e=>f(n,e),t:r,singleSelect:!0,commitOnSelect:!0,testIdPrefix:`${i}-field-picker-${n}`,title:r(`report.editor.fieldPickerChangeTitle`,`Change field`),trigger:(0,K.jsxs)(`button`,{type:`button`,className:`h-7 flex-1 min-w-0 text-left text-xs border rounded px-2 bg-background hover:bg-muted/40 inline-flex items-center justify-between gap-1.5`,"data-testid":`${i}-field-${n}`,title:h,children:[(0,K.jsx)(`span`,{className:`truncate`,children:h}),(0,K.jsx)(le,{className:`h-3 w-3 text-muted-foreground shrink-0`})]})}),(0,K.jsxs)(`select`,{className:`h-7 text-xs border rounded px-1.5 bg-background w-20 shrink-0`,value:t.sortOrder??`asc`,onChange:e=>l(n,{sortOrder:e.target.value}),"data-testid":`${i}-sort-${n}`,children:[(0,K.jsx)(`option`,{value:`asc`,children:r(`report.editor.sortAsc`)}),(0,K.jsx)(`option`,{value:`desc`,children:r(`report.editor.sortDesc`)})]}),p&&(0,K.jsx)(`select`,{className:`h-7 text-xs border rounded px-1.5 bg-background w-24 shrink-0`,value:t.dateGranularity??``,onChange:e=>l(n,{dateGranularity:e.target.value||void 0}),"data-testid":`${i}-granularity-${n}`,children:o.map(e=>(0,K.jsx)(`option`,{value:e.value,children:e.label},e.value))}),(0,K.jsx)(V,{type:`button`,size:`sm`,variant:`ghost`,className:`h-7 w-7 p-0 shrink-0`,onClick:()=>c(n),"aria-label":`Remove grouping`,"data-testid":`${i}-remove-${n}`,children:(0,K.jsx)(C,{className:`h-3.5 w-3.5`})})]},n)}),(0,K.jsx)(Mt,{availableFields:e,selectedValues:s,onAdd:d,t:r,singleSelect:!0,commitOnSelect:!0,testIdPrefix:`${i}-add-picker`,triggerLabel:r(`report.editor.addGrouping`),title:r(`report.editor.fieldPickerAddGroupingTitle`,`Add grouping`),triggerClassName:`h-8 w-full justify-center gap-1.5`})]})}function Rt({availableFields:e,columns:t,value:n,onChange:r,t:i}){let a=n||{},o=a.type??a.chartType??``,s=a.xAxis??a.xAxisField??``,c=a.yAxis??a.yAxisFields?.[0]??``,l=e=>{let t={...a,...e};if(`type`in e&&delete t.chartType,`xAxis`in e&&delete t.xAxisField,`yAxis`in e&&delete t.yAxisFields,!e.type&&e.type===``)return r(void 0);r(t)},u=()=>r(void 0),d=[{value:``,label:i(`report.editor.chartNone`)},{value:`bar`,label:i(`report.editor.chartBar`)},{value:`line`,label:i(`report.editor.chartLine`)},{value:`area`,label:i(`report.editor.chartArea`)},{value:`pie`,label:i(`report.editor.chartPie`)},{value:`donut`,label:i(`report.editor.chartDonut`)},{value:`funnel`,label:i(`report.editor.chartFunnel`)}],f=t.filter(e=>e.aggregate).map(e=>e.field),p=e.filter(e=>jt.has(e.type??``)).map(e=>e.value),m=new Set([...f,...p]),h=e.filter(e=>m.has(e.value));return(0,K.jsxs)(`div`,{className:`space-y-2 py-1`,"data-testid":`chart-config`,children:[(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`label`,{className:`text-[10px] text-muted-foreground`,children:i(`report.editor.chartType`)}),(0,K.jsx)(`select`,{className:`w-full h-7 text-xs border rounded px-2 bg-background`,value:o,onChange:e=>{let t=e.target.value;t?l({type:t}):u()},"data-testid":`chart-type-select`,children:d.map(e=>(0,K.jsx)(`option`,{value:e.value,children:e.label},e.value))})]}),o&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`label`,{className:`text-[10px] text-muted-foreground`,children:i(`report.editor.chartTitle`)}),(0,K.jsx)(`input`,{className:`w-full h-7 text-xs border rounded px-2 bg-background`,value:a.title??``,placeholder:i(`report.editor.chartTitlePlaceholder`),onChange:e=>l({title:e.target.value||void 0}),"data-testid":`chart-title`})]}),(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`label`,{className:`text-[10px] text-muted-foreground`,children:i(`report.editor.chartXAxis`)}),(0,K.jsxs)(`select`,{className:`w-full h-7 text-xs border rounded px-2 bg-background`,value:s,onChange:e=>l({xAxis:e.target.value||void 0}),"data-testid":`chart-x-field`,children:[(0,K.jsx)(`option`,{value:``,children:`—`}),e.map(e=>(0,K.jsx)(`option`,{value:e.value,children:e.label},e.value))]})]}),(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`label`,{className:`text-[10px] text-muted-foreground`,children:i(`report.editor.chartYAxis`)}),(0,K.jsxs)(`select`,{className:`w-full h-7 text-xs border rounded px-2 bg-background`,value:c,onChange:e=>l({yAxis:e.target.value||void 0}),"data-testid":`chart-y-field`,children:[(0,K.jsx)(`option`,{value:``,children:`—`}),(h.length>0?h:e).map(e=>(0,K.jsx)(`option`,{value:e.value,children:e.label},e.value))]})]}),(0,K.jsxs)(`label`,{className:`flex items-center gap-2 text-[10px]`,children:[(0,K.jsx)(g,{checked:a.showLegend!==!1,onCheckedChange:e=>l({showLegend:e===!0}),"data-testid":`chart-show-legend`}),(0,K.jsx)(`span`,{children:i(`report.editor.chartShowLegend`)})]}),(0,K.jsxs)(`label`,{className:`flex items-center gap-2 text-[10px]`,children:[(0,K.jsx)(g,{checked:!!a.showDataLabels,onCheckedChange:e=>l({showDataLabels:e===!0}),"data-testid":`chart-show-data-labels`}),(0,K.jsx)(`span`,{children:i(`report.editor.chartShowDataLabels`)})]})]})]})}function zt(e,t,n){let r=e=>e.type===`summary`,i=e=>e.type===`matrix`,a=e=>e.type===`summary`||e.type===`matrix`,o=[{key:`basic`,title:t(`report.editor.basic`),fields:[{key:`label`,label:t(`report.editor.title`),type:`input`,placeholder:t(`report.editor.titlePlaceholder`)},{key:`description`,label:t(`report.editor.description`),type:`textarea`,placeholder:t(`report.editor.descriptionPlaceholder`)},{key:`type`,label:t(`report.editor.type`),type:`select`,defaultValue:`tabular`,options:[{value:`tabular`,label:t(`report.editor.typeTabular`)},{value:`summary`,label:t(`report.editor.typeSummary`)},{value:`matrix`,label:t(`report.editor.typeMatrix`)},{value:`joined`,label:t(`report.editor.typeJoined`)}],helpText:t(`report.editor.typeHelp`)}]},{key:`data`,title:t(`report.editor.data`),collapsible:!0,fields:[{key:`objectName`,label:t(`report.editor.objectName`),type:`input`,placeholder:t(`report.editor.objectNamePlaceholder`),helpText:t(`report.editor.objectNameHelp`)},{key:`limit`,label:t(`report.editor.limit`),type:`input`,placeholder:t(`report.editor.limitPlaceholder`)}]},{key:`rows`,title:t(`report.editor.rows`),collapsible:!0,hint:t(`report.editor.rowsHint`),visibleWhen:e=>r(e)||i(e),fields:[{key:`groupingsDown`,label:t(`report.editor.grouping`),type:`custom`,render:(n,r)=>(0,K.jsx)(Lt,{availableFields:e,value:n,onChange:r,t,testIdPrefix:`rows-grouping`})}]},{key:`columnsAxis`,title:t(`report.editor.columnsAxis`),collapsible:!0,hint:t(`report.editor.columnsAxisHint`),visibleWhen:e=>i(e),fields:[{key:`groupingsAcross`,label:t(`report.editor.grouping`),type:`custom`,render:(n,r)=>(0,K.jsx)(Lt,{availableFields:e,value:n,onChange:r,t,testIdPrefix:`cols-grouping`})}]},{key:`tabular-columns`,title:t(`report.editor.columns`),collapsible:!0,hint:t(`report.editor.columnsHint`),visibleWhen:e=>e.type!==`joined`&&!r(e)&&!i(e),fields:[{key:`columns`,label:t(`report.editor.columns`),type:`custom`,render:(n,r)=>(0,K.jsx)(It,{availableFields:e,value:n,onChange:r,t})}]},{key:`values`,title:t(`report.editor.values`),collapsible:!0,hint:t(`report.editor.valuesHint`),visibleWhen:e=>r(e)||i(e),fields:[{key:`columns`,label:t(`report.editor.values`),type:`custom`,render:(n,r)=>(0,K.jsx)(It,{availableFields:e,value:n,onChange:r,t})}]},{key:`filters`,title:t(`report.editor.filters`),collapsible:!0,hint:t(`report.editor.filtersHint`),visibleWhen:e=>e.type!==`joined`,fields:[{key:`filter`,label:t(`report.editor.filters`),type:`custom`,render:(n,r)=>(0,K.jsx)(kt,{availableFields:e,value:n,onChange:r,t})}]},{key:`blocks`,title:t(`report.editor.blocks`),collapsible:!0,hint:t(`report.editor.blocksHint`),visibleWhen:e=>e.type===`joined`,fields:[{key:`blocks`,label:t(`report.editor.blocks`),type:`custom`,render:(r,i,a)=>(0,K.jsx)(yt,{value:r,onChange:i,availableFields:e,getFieldsForObject:n,containerObjectName:a?.objectName,t})}]},{key:`chart`,title:t(`report.editor.chart`),collapsible:!0,defaultCollapsed:!0,hint:t(`report.editor.chartHint`),visibleWhen:e=>a(e),fields:[{key:`chart`,label:t(`report.editor.chart`),type:`custom`,render:(n,r,i)=>(0,K.jsx)(Rt,{availableFields:e,columns:Ft(i.columns),value:n,onChange:r,t})}]}];return{breadcrumb:[t(`report.editor.breadcrumb`,`Configuration`)],sections:o}}function Bt(e,t){let n=[],r=e.type??`tabular`,i=Array.isArray(e.groupingsDown)?e.groupingsDown.length:0,a=Array.isArray(e.groupingsAcross)?e.groupingsAcross.length:0,o=Array.isArray(e.columns)?e.columns.length:0;if(e.objectName||n.push({level:o>0?`error`:`warning`,message:t(`report.editor.validationNeedsObject`)}),r===`matrix`&&(i===0||a===0)&&n.push({level:`error`,message:t(`report.editor.validationMatrixNeedsRowsCols`)}),r===`summary`&&i===0&&n.push({level:`error`,message:t(`report.editor.validationSummaryNeedsRows`)}),r===`joined`)for(let r of bt(e.blocks,t))n.push({level:`error`,message:r});return n}function Vt({problems:e}){return e.length===0?null:(0,K.jsx)(`div`,{className:`space-y-1 p-2 border-b`,"data-testid":`report-validation-banner`,children:e.map((e,t)=>(0,K.jsxs)(`div`,{className:`flex items-start gap-2 text-[11px] rounded px-2 py-1 `+(e.level===`error`?`bg-red-50 border border-red-200 text-red-900`:`bg-amber-50 border border-amber-200 text-amber-900`),children:[(0,K.jsx)(z,{className:`h-3.5 w-3.5 mt-0.5 shrink-0`}),(0,K.jsx)(`span`,{children:e.message})]},t))})}function Ht({open:e,onClose:t,config:n,onSave:r,onFieldChange:i,availableFields:a,getFieldsForObject:o}){let{t:s}=l(),c=G.useCallback((e,t,n)=>t===void 0?s(e,n):s(e,{defaultValue:t,...n||{}}),[s]),u=a??[],d=G.useMemo(()=>zt(u,c,o),[u,c,o]),{draft:f,isDirty:p,updateField:m,discard:h}=ce(G.useMemo(()=>n??{},[n])),g=G.useCallback((e,t)=>{m(e,t),i?.(e,t,{...f,[e]:t})},[m,i,f]),_=G.useCallback(()=>{r(f),t()},[f,r,t]),v=G.useMemo(()=>Bt(f,c),[f,c]);return e?(0,K.jsx)(O,{open:e,onClose:t,schema:d,draft:f,isDirty:p,onFieldChange:g,onSave:_,onDiscard:h,headerExtra:(0,K.jsx)(Vt,{problems:v}),style:{"--config-panel-width":`440px`}}):null}async function Ut(e,t){let{dataSource:n,resource:r,queryParams:i,format:a,exportConfig:o}=t,s=a||e.defaultExportFormat||`pdf`;try{let t=(await n.find(r,i)).data||[];return tt(s,e,t,{format:s,...e.exportConfigs?.[s],...o}),{success:!0,recordCount:t.length,format:s}}catch(e){return{success:!1,recordCount:0,format:s,error:e.message}}}function Wt(e,t,n={}){let{columns:r,filename:i,includeAggregationRow:a=!1}=n,o=r||(e.fields||[]).map(Kt),s=o.map(e=>e.header),c=t.map((e,t)=>o.map(n=>{if(n.formula)return n.formula.replace(/\{ROW\}/g,String(t+2));let r=e[n.name];return qt(r,n.numberFormat)}));if(a&&t.length>0){let n=o.map((n,r)=>{let i=(e.fields||[]).find(e=>e.name===n.name);if(i?.aggregation){let e=Yt(r),n=t.length+1;switch(i.aggregation){case`sum`:return`=SUM(${e}2:${e}${n})`;case`avg`:return`=AVERAGE(${e}2:${e}${n})`;case`count`:return`=COUNTA(${e}2:${e}${n})`;case`min`:return`=MIN(${e}2:${e}${n})`;case`max`:return`=MAX(${e}2:${e}${n})`;default:return``}}return``});c.push(n)}Zt(``+[s.join(` `),...c.map(e=>e.join(` `))].join(`
59
- `),i||`${e.title||`report`}.tsv`,`text/tab-separated-values`)}function Gt(e,t,n,r){return async()=>{let i=e.schedule;if(!i?.enabled)return[];let a=i.formats||[e.defaultExportFormat||`pdf`],o=[];for(let r of a){let i=await Ut(e,{dataSource:t,resource:n,format:r});o.push(i)}return r(e,i),o}}function Kt(e){return{name:e.name,header:e.label||e.name}}function qt(e,t){return e==null?``:typeof e==`number`&&t?e.toLocaleString(`en-US`,Jt(t)):Xt(String(e))}function Jt(e){if(e.includes(`%`))return{style:`percent`,minimumFractionDigits:0};let t=(e.match(/0/g)||[]).length;return{minimumFractionDigits:Math.max(0,t-1),maximumFractionDigits:Math.max(0,t-1)}}function Yt(e){let t=``,n=e;for(;n>=0;)t=String.fromCharCode(n%26+65)+t,n=Math.floor(n/26)-1;return t}function Xt(e){if(e.length>0){let t=e.charAt(0);if(t===`=`||t===`+`||t===`-`||t===`@`||t===`|`)return`'${e}`}return e}function Zt(e,t,n){let r=new Blob([e],{type:`${n};charset=utf-8`}),i=URL.createObjectURL(r),a=document.createElement(`a`);a.href=i,a.download=t,document.body.appendChild(a),a.click(),document.body.removeChild(a),URL.revokeObjectURL(i)}var Qt=t({JoinedBlocksEditor:()=>yt,JoinedReportRenderer:()=>qe,LegacyReportRenderer:()=>fe,MatrixRenderer:()=>Ue,ReportBuilder:()=>ft,ReportConfigPanel:()=>Ht,ReportRenderer:()=>Ye,ReportViewer:()=>ut,ScheduleConfig:()=>dt,SpecReportGrid:()=>Re,aggregateRows:()=>Y,bucketDate:()=>pe,buildAggregateQuery:()=>Ce,buildDrillAction:()=>Ae,collectFields:()=>Se,columnKey:()=>q,createDrillHandler:()=>Me,createScheduleTrigger:()=>Gt,exportAsCSV:()=>Xe,exportAsExcel:()=>et,exportAsHTML:()=>Qe,exportAsJSON:()=>Ze,exportAsPDF:()=>$e,exportExcelWithFormulas:()=>Wt,exportReport:()=>tt,exportWithLiveData:()=>Ut,formatValue:()=>ot,groupAndAggregate:()=>me,groupingValue:()=>J,isDrillAction:()=>je,mergeFilters:()=>X,pivotRows:()=>he,registerDrillHandler:()=>Ne,useReportData:()=>Te,validateJoinedBlocks:()=>bt});s.register(`report`,Ye,{namespace:`report`,label:`Report`,category:`Report`,inputs:[{name:`title`,type:`string`,label:`Title`},{name:`description`,type:`string`,label:`Description`},{name:`chart`,type:`code`,label:`Chart Configuration`}]}),s.register(`spec-report`,Ye,{namespace:`report`,label:`Spec Report`,category:`Report`,inputs:[{name:`objectName`,type:`string`,label:`Object Name`},{name:`type`,type:`string`,label:`Report Type`}]}),s.register(`report-viewer`,ut,{namespace:`report`,label:`Report Viewer`,category:`Report`,inputs:[{name:`report`,type:`code`,label:`Report Definition`},{name:`showToolbar`,type:`boolean`,label:`Show Toolbar`}]}),s.register(`report-builder`,ft,{namespace:`report`,label:`Report Builder`,category:`Report`,inputs:[{name:`report`,type:`code`,label:`Initial Report`}]});export{Qt as t};