You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@atlas.apache.org by pp...@apache.org on 2026/08/12 12:52:21 UTC
(atlas) 01/01: ATLAS-5349: Ability to Export Apache Atlas Business Glossary to Excel/CSV from UI
This is an automated email from the ASF dual-hosted git repository.
pawarprasad123 pushed a commit to branch ATLAS-5349
in repository https://gitbox.apache.org/repos/asf/atlas.git
commit 8bc48245ca54ee69aa77f6705e80aa313db293fa
Author: Prasad Pawar <pr...@freestoneinfotech.com>
AuthorDate: Wed Aug 12 18:21:27 2026 +0530
ATLAS-5349: Ability to Export Apache Atlas Business Glossary to Excel/CSV from UI
---
dashboard/COMPREHENSIVE_TEST_DOCUMENTATION.md | 239 +++++++++
.../apiMethods/__tests__/glossaryApiMethod.test.ts | 103 +++-
dashboard/src/api/apiMethods/glossaryApiMethod.ts | 52 ++
.../api/apiUrlLinks/__tests__/glossaryUrl.test.ts | 56 +-
dashboard/src/api/apiUrlLinks/glossaryUrl.ts | 30 ++
dashboard/src/components/ImportDialog.tsx | 5 +-
.../src/components/__tests__/ImportDialog.test.tsx | 32 +-
dashboard/src/index.scss | 1 +
dashboard/src/styles/glossary.scss | 55 ++
.../src/utils/__tests__/downloadRecords.test.ts | 222 ++++++++
.../src/utils/__tests__/glossaryExport.test.ts | 300 +++++++++++
.../src/utils/__tests__/glossaryStatus.test.ts | 41 ++
dashboard/src/utils/downloadRecords.ts | 145 +++++
dashboard/src/utils/glossaryExport.ts | 308 +++++++++++
dashboard/src/utils/glossaryStatus.ts | 76 +++
.../src/views/Glossary/GlossaryStatusBadge.tsx | 52 ++
.../src/views/Glossary/GlossaryTermsListPage.tsx | 414 +++++++++++++++
.../__tests__/GlossaryStatusBadge.test.tsx | 54 ++
.../__tests__/GlossaryTermsListPage.test.tsx | 321 ++++++++++++
.../__tests__/glossaryTermsListColumns.test.tsx | 169 ++++++
.../views/Glossary/glossaryTermsListColumns.tsx | 204 ++++++++
dashboard/src/views/Layout/Header.tsx | 147 ++++--
.../src/views/Layout/__tests__/Header.test.tsx | 272 +++++++++-
dashboard/src/views/Router.tsx | 7 +
.../src/views/SideBar/SideBarTree/SideBarTree.tsx | 43 +-
.../SideBarTree/__tests__/SideBarTree.test.tsx | 159 +++++-
dashboardv2/public/css/scss/common.scss | 87 ++-
dashboardv2/public/css/scss/downloads.scss | 51 +-
dashboardv2/public/js/collection/VDownloadList.js | 10 +
dashboardv2/public/js/router/Router.js | 31 ++
.../glossary/GlossaryLayoutView_tmpl.html | 2 +
.../glossary/GlossaryTermsListLayoutView_tmpl.html | 83 +++
.../site/DownloadSearchResultLayoutView_tmpl.html | 18 +-
dashboardv2/public/js/utils/GlossaryExport.js | 311 +++++++++++
dashboardv2/public/js/utils/UrlLinks.js | 15 +
dashboardv2/public/js/utils/Utils.js | 8 +
.../public/js/views/glossary/GlossaryLayoutView.js | 43 +-
.../views/glossary/GlossaryTermsListLayoutView.js | 582 +++++++++++++++++++++
.../views/site/DownloadSearchResultLayoutView.js | 162 +++++-
39 files changed, 4782 insertions(+), 128 deletions(-)
diff --git a/dashboard/COMPREHENSIVE_TEST_DOCUMENTATION.md b/dashboard/COMPREHENSIVE_TEST_DOCUMENTATION.md
new file mode 100644
index 000000000..61d7c4021
--- /dev/null
+++ b/dashboard/COMPREHENSIVE_TEST_DOCUMENTATION.md
@@ -0,0 +1,239 @@
+# Test documentation (dashboard / n3)
+
+## Schema tab — UI tweaks (2026-04)
+
+- Description column hidden (typedef `schemaAttributes` may still list it; UI skips `description`).
+- “Sort by name (API)” toggle removed; relationship search uses default ordering (position sort client-side).
+- Pagination footer “From X – Y” uses full dataset row count (React `TablePagination` + classic `TableLayout.renderAtlasPagination`).
+- **Classic Schema tab:** footer matches React (“Showing **N** records From **A** – **B**” with merged approximate **N** across schema relations, **Page Limit**, prev/next). Implemented via `SchemaLayoutView.js` (`getMergedApproximateTotal`, `handleSchemaAtlasFetch`, Atlas pagination options) and `TableLayout.js` (`clientAtlasPagination`, `atlasApproximateDatasetTotal`, `getAtlasPaginationCeiling`).
+- **Classic Schema relationship response handling (2026-04):** `$.when` with multiple `$.ajax` calls passes each response as three arguments (data, status, jqXHR). The schema fetch now unwraps with `.then(function(data){ return data; })` per request so `arguments.length === schemaRelationNames.length`. Approximate totals use `approximateCount` or `totalCount` (React parity) via `normalizeRelationshipApproximateCount` (reject `-1` / negative). Without this, multi-relation merges and total [...]
+- **Classic Schema pagination after row refresh (2026-04):** `generateTableData` calls **`syncSchemaAtlasTableOffsets`** (reads **Page Limit** from `showPage` / select2 and sets **`state.pageSize`** + **`tl.limit`**) **before** `captureSchemaPaginationSnapshot`, then `applySchemaPaginationSnapshot` uses `getPageByOffset`. **`syncSchemaAtlasTableOffsets`** used to derive **`tl.offset`** from **`state.pageSize` without aligning **`state.pageSize`** to the dropdown — after a page-limit chan [...]
+- **Classic Schema chunk fetch + pagination (2026-04):** While **`fetchNextSchemaChunkSync`** runs inside **`getPage`** (before **`origGetPage`** returns), **`state.currentPage`** is still the previous page. **`syncSchemaAtlasTableOffsets`** must not assign **`tl.offset` from that stale `currentPage`** — it zeroed the offset and rebuilt the grid on the wrong slice (footer vs row names / missing classification chips until another nav). **Fix:** after syncing **limit** from the dropdown, r [...]
+- **Classic Schema canonical pagination + cache index (2026-04):** **`_schemaCanonicalPagination`** stores **`{ pageSize, offset }`** as the logical index into the merged cached list (e.g. 500 rows cached, limit 10, page 5 → offset 40, rows 41–50). It is persisted on **`schemaTabCacheByGuid[guid].paginationCanonical`**, restored when reusing cache, updated from **`TableLayout`** after Next/Prev/limit (**`persistSchemaCanonicalFromTableLayout`**), and refreshed from **`applySchemaPaginati [...]
+- **Classic Schema footer vs Next / first classification refresh (2026-04):** **`TableLayout`** writes **`schemaCollection.queryParams.offset`** on Next/Prev/limit; **`syncSchemaAtlasTableOffsets`** must **prefer that** over **`currentPage * pageSize`** (Pageable **`currentPage`** can lag after **`fullCollection.reset`**, leaving the footer at “1–100” while the API already used offset 100). **`syncSchemaCollectionQueryParamsToPagination`** runs after **`applySchemaPaginationSnapshot`** a [...]
+- **Classic Schema Next/Prev footer (2026-04):** **`handleSchemaAtlasFetch`** captures **`tl.offset`** after **`onClicknextData`** / **`onClickpreviousData`** and **restores it after** **`getNextPage`** / **`getPreviousPage`** when **`options.next`** / **`options.previous`** — **`syncSchemaAtlasTableOffsets`** was zeroing **`tl.offset`** from stale **`currentPage`**, so **`renderAtlasPagination`** saw **`isFirstPage`** and left “From 1–100”. **`TableLayout.renderAtlasPagination`** (schem [...]
+- **Classic Schema Page Limit + position sort (2026-04):** **`TableLayout.changePageLimit`** calls **`fetchCollection({ fromPageLimitChange: true })`**. **`handleSchemaAtlasFetch`** runs **`resortCachedSchemaMergedAttributeByPosition()`** (sort each **`schemaRowsByRelation`** block and flatten **`attribute`** by **`sortRowsInRelation`** / **`attributes.position`**), updates **`schemaTabCacheByGuid`**, then **`generateTableData`** so the grid and cache share one position-ordered merged li [...]
+- **Classic Schema Page Limit + canonical snapshot (2026-04):** **`captureSchemaPaginationSnapshot`** reads **`_schemaCanonicalPagination`** before live **`TableLayout`**. On **`fromPageLimitChange`**, **`handleSchemaAtlasFetch`** now sets **`_schemaCanonicalPagination`** to **`{ pageSize: tl.limit, offset: 0 }`** and syncs **`schemaCollection.state.pageSize`** / **`queryParams`** **before** **`resortCachedSchemaMergedAttributeByPosition`** + **`generateTableData`**, so **`applySchemaPag [...]
+- **Classic Schema Prev page number / range (2026-04):** **`renderAtlasPagination`** had a **`previous`**-only branch that recomputed **`pageTo`** as **`pageTo - limit`** using **stale** **`pageTo`** from the prior render. If **`collection.queryParams.limit`** disagreed with the Page Limit dropdown (e.g. chunk vs UI step), **`onClickpreviousData`** subtracted the wrong **`limit`** (e.g. offset 45 → 30 instead of 40), so **Previous** from page 10 showed page **7** and **31–35**. **Fix:** [...]
+- **Classic Schema classification callbacks (2026-04):** After child GET + `generateTableData`, **do not** call `fetchCollection()` on the detail page — that refetched the parent entity, fired redundant `GET /entity/guid/{table}`, and could recreate/reset schema state (relationship chunks from offset 0, UI back to page 1). Mirrors React (`onSchemaChildEntityRefresh` without `fetchDetailPageData(parent)`). **`_lastKnownSchemaPagination` / `_schemaPaginationSnapshot`** fallbacks preserve o [...]
+- **Classic Schema loader on Next/Prev (2026-04):** **`atlasShowLoaderBeforeFetch`** (schema **`TableLayout`** options) calls **`showLoader()`** as soon as Next/Prev runs, before **`handleSchemaAtlasFetch`**. **`handleSchemaAtlasFetch`** defers **`getNextPage`/`getPreviousPage`** with **`setTimeout(0)`** after **`showLoader`** so the browser can paint the overlay before **`fetchNextSchemaChunkSync`** (sync XHR), which otherwise blocked painting until the API returned.
+- **Classic Schema atlas busy + loaders (2026-04):** `TableLayout` exposes **`setAtlasPaginationBusy(busy, navHint)`** — **`navHint`**: **`next`** / **`prev`** / **`both`** (from **`handleSchemaAtlasFetch`** options; page-limit resort uses **`both`**). Disables **Next/Prev/Page Limit** while busy; **`renderAtlasPagination`** then **`_syncAtlasPaginationBusyVisuals`** swaps the active button label(s) to **`fa-spinner fa-spin`**, adds **`ul.atlas-pagination-busy`** + **`aria-busy`**, and * [...]
+- **Classic Schema row merge + sort (parity with React `sortRowsInRelation`, 2026-04):** **`mergeSchemaRowWithFreshEntity`** still merges **`classifications`** and pins **`position` / `name`** from the relationship row. **`sortSchemaEntityBlocks`** uses **`sortRowsInRelation`** per relation block: **numeric `attributes.position` first** (rows with position before rows without), then **`localeCompare`** on **`attributes.name`**, then **`guid`**. **`refreshChildEntitiesAfterClassification` [...]
+- **React Schema `resolveEntity` (classifications only):** `classifications: r.classifications ?? row.classifications` kept old chips when the child GET omitted the property; **`resolveEntity`** treats explicit `classifications` / full-entity fallback like classic. **Position / pagination shuffle after classification** is addressed in **Classic** via **`mergeSchemaRowWithFreshEntity`** (`dashboardv2`); React UI did not need the attributes merge change.
+- **Classic Schema — historical toggle + pagination (2026-04):** Toggling **Show historical** on page 2+ only changed `fullCollection` but left **`queryParams.offset` / `_schemaCanonicalPagination` / `TableLayout.offset`** on the old page — footer could show “From 1–100” while the relationship chunk used **`offset=100`**. **Fix:** **`resetSchemaPaginationToFirstPageForToggle`** (canonical + queryParams + TL + `currentPage` → first page) then **`generateTableData()`** from **`onCheckDelet [...]
+- **Schema tab — historical entities (React + Classic, 2026-04):** Relationship requests load **active and deleted** related entities (`excludeDeletedEntities: false`; React uses **`SCHEMA_RELATIONSHIP_INCLUDE_DELETED`** / `showDeleted: true` via `buildRelationshipSearchParams`). The **Show historical entities** control only **filters cached rows** by `entityStateReadOnly` / `Enums.entityStateReadOnly` — **no API refetch** when toggling (React: `schemaHistoricalRows.ts` helpers; **`check [...]
+
+## Schema tab — relationship search + cache (2026-04)
+
+### Automated
+
+- `npx tsc --noEmit` — pass
+- `npx vite build` — pass
+- ESLint on touched files (`SchemaTab.tsx`, `TaskTab.tsx`, `relationshipSearchQuery.ts`, `schemaElementsAttributeUtils.ts`, `searchApiMethod.ts`) — pass
+
+### Manual / QA (recommended)
+
+1. **Single relation** (e.g. `hive_table` → `columns`): open entity detail → Schema tab; confirm rows load from `/api/atlas/v2/search/relationship` with `attributes=type` and `attributes=position` (network tab); classifications column populated when API returns classification data.
+2. **Multi-relation**: typedef with multiple `schemaElementsAttribute` values (or comma-separated); confirm rows appear in **one** table, **blocks** in relation order, each block ordered by `position` then name.
+3. **Tab cache**: load Schema, switch to Properties/Relationships/Audits, return to Schema — data should remain without refetch (React: state lifted in `EntityDetailPage`; classic: `schemaTabCacheByGuid`).
+4. **Guid change**: navigate to another entity detail — schema cache should reset and load fresh data.
+5. **Pagination-driven load more** (React + classic): relationship API loads up to 100 rows per relation initially; table page size is 25. Moving to a page that needs rows beyond what is loaded (e.g. page 5 after four pages of 25) triggers the next relationship fetch on **Next** / page change — not on scroll. Footer and Next use approximate totals (`mergedApproximateTotal` / per-relation totals). **Approximate count:** only `offset=0` responses contribute to stored totals (`getApproximat [...]
+6. **Refresh on Schema tab** (React): `setSchemaTabCache(null)` on every mount raced `SchemaTab` init and cleared cache after the child set it, leaving `schemaCache` null and the table stuck in skeleton (`!schemaCache`). Cache now resets only when `guid` changes (not first mount); `SchemaTab` gets `key={guid}`. **Classic:** `renderSchemaLayoutView` calls `updateTab()` after async `require` + `show` when `tabActive=schema` so the schema pane matches the URL after refresh.
+7. **Schema pagination prefetch** (React + classic): React `handleFetchForPagination` tracks **visible** row `len` from `countVisibleSchemaRows(schemaCacheRef)` and each `loadNextChunk()` return — not `mergedRowCountRef` (stale until useEffect). Classic `SchemaLayoutView.attachSchemaClientPaginationGuard` uses `getMergedSchemaRowCount()` (sum of `schemaRowsByRelation` lengths) before/after each `fetchNextSchemaChunkSync()` instead of only `fullCollection.length`, matching the same prefet [...]
+8. **Show historical entities**: With data loaded, turn the switch on/off — table updates **without** new relationship calls; deleted rows appear only when present in cache (API includes deleted). If only active columns exist and the switch is on, the **table** shows **“No Records found!”** (empty grid), not active rows with a separate message.
+9. **Classic UI**: same entity types; schema table loads via parallel relationship GETs; cache on tab switch for same guid.
+
+## Classic entity detail — relationship API on load (2026-04)
+
+- **Before:** After loading entity/header terms, `DetailPageLayoutView` called `ensureRelationshipView()`, which triggered **every** `/v2/search/relationship` request (columns, db, meanings, …) even on **Properties** — only `generateTerm` is needed for header terms (same idea as React: terms from `relationshipAttributes.meanings` / header, not a full relationship replay).
+- **After:** Removed `ensureRelationshipView()` from the meanings / header `success` paths. Relationship cards still load when the user opens the **Relationships** tab (`tab` click, `shown.bs.tab`, `tabActive=relationship`, `updateTab`).
+- **`RelationshipCardsLayoutView`:** `normalizeRelationshipApproximateCount` (parity with React `relationshipSearchQuery.ts`) so `-1` does not become the total; unknown total on a full first page uses `listLen + 1` so scroll load-more stays available; **load-more** responses can refresh totals when the API returns a valid approximate count.
+
+## Tasks tab — React parity with classic (2026-04)
+
+### Automated
+
+- Same build/tsc as above.
+
+### Manual / QA
+
+1. With `taskTabEnabled` and `uiTaskTabEnabled` true in session: open Tasks tab; list loads from `GET /api/atlas/admin/tasks` (same as `PendingTaskTableLayoutView`).
+2. Refresh icon reloads tasks.
+3. Expand “+” shows parameters JSON (excluding `entityGuid` from display like classic omit).
+
+## Glossary browse / export — restored (2026-06)
+
+Applied stashes `glossary export implementation UI` and `glossary export+ 2nd` (UI stash only; **skipped** `vite.config.ts` dev-proxy changes from the second stash — not glossary-related).
+
+### React (`dashboard/`)
+
+- **`src/utils/glossaryExport.ts`:** Glossary terms list search/export helpers — table mapping, filters, server-side download via `create_file`.
+- **`GlossaryTermsListPage.tsx`:** `/glossary/terms-list` — filter, paginate, export CSV/Excel (filtered set).
+- **`Header.tsx`:** Merged search + glossary download status in header popover.
+- **`SideBarTree.tsx`:** Glossary panel ⋮ menu includes **Export Glossary** (`data-cy="glossaryTermsListNavigate"`) → `#/glossary/terms-list`.
+- **`glossaryApiMethod.ts` / `glossaryUrl.ts`:** `getGlossaryTermsForGlossary`, `getGlossaryCategoriesForGlossary` → `GET /v2/glossary/{guid}/terms` and `/categories`.
+
+### Classic (`dashboardv2/`)
+
+- **`public/js/utils/GlossaryExport.js`:** Shared glossary search/export helpers (POST `/v2/glossary/search`, `/create_file`) — mirrors React `glossaryExport.ts`.
+- **`GlossaryTermsListLayoutView.js`:** `#!/glossary/terms-list` — filters, server pagination table, Download button.
+- **`GlossaryLayoutView`:** Sidebar ⋮ menu **Export Glossary** navigates to terms-list (replaces client CSV/XLSX).
+- **`DownloadSearchResultLayoutView`:** Merged search + glossary download status in header popover.
+- **`UrlLinks.js`:** `glossarySearchUrl`, `glossaryCreateFileUrl`, `getGlossaryDownloadsList`, `glossaryDownloadFileUrl`.
+
+### Tests added/updated
+
+- **`src/utils/__tests__/glossaryExport.test.ts`:** filter, CSV escape, header helpers, `mapGlossarySearchResultToTableRows`, removed `classificationFilter` from browse filters.
+- **`glossaryUrl.test.ts`:** `glossaryTermsUrl`, `glossaryCategoriesUrl`.
+- **`glossaryApiMethod.test.ts`:** per-glossary terms/categories GET helpers.
+
+### Glossary terms list UX parity (2026-07)
+
+- **`GlossaryTermsListPage.tsx`:** Rebuilt with shared **`TableLayout`** / **`TablePagination`** (server-side pagination via `approximateCount` from `POST /v2/glossary/search`). Filters reordered: Glossary → Record type (Terms/Categories) → Status → Search all columns; classification filter removed.
+- **`glossaryTermsListColumns.tsx`:** Name column uses search-result **chip** links to glossary detail (`/glossary/{guid}`); classifications use **`DialogShowMoreLess`** (capsule tags + show more, links to `/tag/tagAttribute/{typeName}`).
+- **API dedup:** Table search uses a stable `fetchData` callback (`glossaryGuidByNameRef`); glossary dropdown reuses Redux **`fetchGlossaryData`** (skips dispatch when already loading/loaded) instead of a separate search `limit: 0` call.
+- **Styling:** Wrapped in **`search-result-table-wrapper`** for search-result table fonts/colors.
+
+### Verification
+
+- `npm run typecheck` — pass
+- `npm run lint` — pass (0 errors)
+- `npm run build` (dashboard) — pass
+- `npm test -- glossaryExport` — pass
+
+### Patch apply — glossary-export-intellij (2026-08)
+
+- Applied `glossary-export-intellij.patch` on branch `ATLAS-5349`; resolved conflicts in `dashboard/package.json`, `dashboard/package-lock.json` (`npm install`), and `dashboard/src/index.scss` (`@use "@styles/glossary.scss"`).
+- **Dependency cleanup (2026-08-12):** Removed unused `xlsx@0.18.5` from `dashboard/package.json` and `dashboardv2/package.json` (glossary export uses server-side `POST /v2/glossary/create_file`, not client SheetJS). Removed dead `sheetjs` RequireJS alias from `dashboardv2/public/js/main.js` and `migration.js` (no `external_lib/xlsx` file and no `require('sheetjs')` usage).
+- **Build fix:** Removed invalid `width` property from `glossaryTermsListColumns.tsx` column defs (TanStack `ColumnDef` uses `size` only); updated `glossaryTermsListColumns.test.tsx` accordingly.
+- **Verification (2026-08-12):** `npm run typecheck`, `npm run lint` (0 errors), `npm run build` (dashboard), `npm run build` (dashboardv2), glossary-related Jest suites, and `apache-license-header.test.ts` — all pass.
+
+## Schema tab — classification refresh via GET entity (child guid) (React + classic, 2026-04)
+
+### Behavior
+
+After add/remove classification on a schema **column** (child entity), the UI does **not** re-call `GET /v2/search/relationship` for the visible page. Instead, after the parent detail refresh (`fetchDetailPageData` on the table entity), it calls **`GET /v2/entity/guid/{childGuid}`** with **`ignoreRelationships=true`** (same as the standard entity GET). The response entity is merged into **`referredEntities`** in Redux (`mergeReferredEntities` in `detailPageSlice`) and into the schema tab [...]
+
+### React (`dashboard/`)
+
+- `SchemaTab.tsx`: `refreshSchemaChildEntities(childGuids)` — one `getEntity(guid, "GET", {})` per guid, then `dispatch(mergeReferredEntities(...))` + `setSchemaCache` patch for `referredEntities`.
+- `DialogShowMoreLess` + `AddTag`: optional `onSchemaChildEntityRefresh(childGuids)` runs **after** `fetchDetailPageData(...).unwrap()` (add/edit/remove).
+- `detailPageSlice`: `mergeReferredEntities` reducer shallow-merges into `detailPageData.referredEntities`.
+
+### Classic (`dashboardv2/`)
+
+- `SchemaLayoutView.js`: `refreshChildEntitiesAfterClassification(childGuids, done)` — GET per guid via `UrlLinks.entitiesApiUrl({ guid, minExtInfo: true })`, merge into `referredEntities`, patch matching row in `schemaRowsByRelation`, rebuild `attribute`, update `schemaTabCacheByGuid`, `generateTableData()`. Add/remove tag callbacks no longer call relationship search replay.
+
+### Manual QA
+
+1. Schema tab: add/remove a classification on a column; Classifications column updates without full page reload. **Remove (X)** on a chip appears only for **direct** classifications (`entityGuid` matches the column); **propagated** tags (different `entityGuid`) have no X, same as basic search. `SchemaTab` passes `removeApiMethod={removeClassification}`; confirmation modal uses loader on **Remove** until the DELETE completes, then child GET + merge runs as above.
+
+### Manual QA (search parity)
+
+- Basic search results: `SearchResult` passes `removeApiMethod={removeClassification}`; schema tab now matches for chip delete + modal behavior.
+- After schema classification add/remove/edit, **do not** dispatch `fetchGlossaryDetails` / `fetchGlossaryData` unless `gtype` query param is set (matches `AddTag`). **Do not** call `fetchDetailPageData(parent)` when `onSchemaChildEntityRefresh` is provided — only the child column GET + merge runs (avoids `/glossary/null/...` and redundant parent fetches).
+2. Footer shows **100** rows per page by default; change page size and load more data; confirm the next relationship chunk uses the selected limit (network tab: `limit` query param).
+3. Classic: same checks on schema table.
+
+### Automated
+
+- `npm run build` in `dashboard/` (`tsc` + `vite build`) after changes.
+
+## dashboardv2 — Handlebars.js 4.7.8 (2026-04)
+
+- **Vendored runtime/compiler:** `dashboardv2/public/js/external_lib/require-handlebars-plugin/js/handlebars.js` replaced with Handlebars **4.7.8** (was 1.0.0-rc.3).
+- **i18n precompile:** `i18nprecompile.js` updated for v4 AST (`Program.body`, `MustacheStatement`, `ContentStatement`, `BlockStatement` / `PartialBlockStatement` recursion).
+- **require-handlebars-plugin:** `hbs.js` updated for v4 AST (partials, comments, external deps / `recursiveVarSearch`); built-in helpers list extended with `lookup` and `log`.
+- **Helpers module:** `Helpers.js` AMD deps now include `underscore` (fixes `_` used but not loaded).
+- **Template fix:** `TermRelationAttributeTable_tmpl.html` — removed stray quote and normalized the attribute input markup for `value="{{lookup ...}}"`.
+- **Verification:** `npm run build` in `dashboardv2/` (grunt: clean, copy, sass, template) — pass. **Manual QA:** glossary term relation attributes table (edit mode on/off); any screen using `hbs!` templates and custom helpers (`ifCond`, `lookup`, etc.).
+
+## React UI — HTTP 403 authorization (parity with classic, 2026-04)
+
+- **Classic:** `Utils.defaultErrorHandler` redirects only on **401** / **419**; **403** calls `serverErrorHandler` (PNotify) with `error.responseJSON.errorMessage` / `message` — user stays on the page.
+- **React (fix):** `dashboard/src/api/apiMethods/fetchApi.ts` — removed `window.location.replace("login.jsp")` on **403**; still uses `serverErrorHandler` → `toast.error` with API body text (e.g. user not authorized for classification/tag assignment). Narrowed post-catch “network failure” toast to requests **without** an HTTP response (or status `0`) so **403** does not also trigger the offline message. `dashboard/src/utils/Utils.ts` — `serverError` no-ops on **403** so modals (e.g. `Add [...]
+- **Verification:** `npm run build` in `dashboard/` — pass. **Manual QA:** logged-in user **without** create/update classification (or tag/term) permission: attempt add classification from entity detail — expect error toast with server message, **no** redirect to login/error/home.
+
+## React UI — Import Business Metadata / glossary import file name tooltip (2026-04)
+
+- **Issue:** Long selected file names in the import dropzone were truncated with ellipsis with no way to read the full name (classic UI shows full name on hover).
+- **Fix:** `dashboard/src/views/SideBar/Import/ImportLayout.tsx` — wrap the file name `Typography` in `LightTooltip` with `title={file.name}` (`placement="top"`, `arrow`); `Typography` uses `component="span"` and `display: "block"` for a correct tooltip anchor with ellipsis.
+- **Verification:** `npx tsc --noEmit` in `dashboard/` — pass. **Manual QA:** Import Business Metadata or Import Glossary, choose a long `.xlsx` / `.csv` name — hover shows full name in tooltip.
+
+## React UI — Business Metadata edit: Applicable Types chips non-removable (classic parity, 2026-04)
+
+- **Issue:** Edit attribute flow showed **×** on Applicable Types chips so users could remove types; classic uses Select2 `TagHideDeleteButtonAdapter` and `data-allowremove="false"` for types already on the attribute.
+- **Fix:** `dashboard/src/views/BusinessMetadata/BusinessMetadataAtrributeForm.tsx` — when `editbmAttribute` is set, build a `Set` from `field.options.applicableEntityTypes` (initial parsed list) and custom `renderTags`: `Chip` gets `onDelete={undefined}` for those options so the remove control is hidden; newly added types in the same session (if any) still get a delete handler.
+- **Verification:** `npx tsc --noEmit` in `dashboard/` — pass. **Manual QA:** Administrator or BM detail → edit attribute with Applicable Types → existing type chips have no **×**; create-attribute flow unchanged (all chips removable).
+
+## Classic UI — DOMPurify 3.4.0 (CVE-2026-41238, CVE-2026-41239, CVE-2026-41240, 2026-04)
+
+- **Prior:** Vendored `dashboardv2/public/js/external_lib/dompurify/purify.min.js` was **3.2.4** (within affected ranges; patched at **3.4.0** per [NVD](https://nvd.nist.gov/vuln/detail/CVE-2026-41238) / upstream release).
+- **Change:** Replaced with official **`dompurify@3.4.0`** `dist/purify.min.js` (UMD/AMD compatible). RequireJS paths in `main.js` / `migration.js` unchanged; `Utils.sanitizeHtmlContent` API unchanged.
+- **Scope:** `dashboard/` (React) uses **`sanitize-html`**, not DOMPurify — no npm change for this CVE set. `docs/` has no DOMPurify dependency. `build-tools/.../swagger-ui-bundle.js` unchanged (separate bundle).
+- **Security / XSS:** The bump **removes** exposure to CVE-2026-41238 / 41239 / 41240 (affected versions below 3.4.0); it does not introduce those flaws. Classic HTML still goes through **`Utils.sanitizeHtmlContent`** (`dashboardv2/public/js/utils/Utils.js`) with **restrictive** `ALLOWED_TAGS` / `ALLOWED_ATTR`, `FORBID_TAGS` / `FORBID_ATTR`, and `DOMPurify.sanitize` — same contract as before, stricter engine. React `dangerouslySetInnerHTML` paths remain tied to **`sanitize-html`** in `da [...]
+- **Verification:** `npm run build` in `dashboardv2/` — pass. **Manual QA:** Trumbowyg / rich text paths that call `Utils.sanitizeHtmlContent`.
+- **Lint (2026-04):** Removed unused `eslint-disable-next-line react-hooks/exhaustive-deps` in `SchemaTab.tsx` (effect deps are complete). `npx eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 200` in `dashboard/` — **0 errors** (132 warnings, pre-existing). `npm run build` in `dashboard/` (`tsc && vite build`) — pass.
+
+## React UI — 403 API errors: toast visible long enough to read (2026-04)
+
+- **Issue:** Authorization errors from `fetchApi` (e.g. create classification-def) showed the Atlas message in a toast that disappeared almost immediately, even with a long `autoClose`.
+- **Cause:** `fetchApi` showed the toast, then threw; callers such as **`ClassificationForm`** run **`toast.dismiss(toastId.current)`** in `catch`. When **`toastId.current`** is **null**, react-toastify’s **`toast.dismiss`** clears **all** toasts, removing the 403 notification in the same turn.
+- **Fix (only in `fetchApi.ts`):** Queue the 403 toast with **`setTimeout(..., 0)`** so it runs after the caller’s **`dismiss`** (microtask vs macrotask order). Use a stable **`toastId`** (`fetch-api-http-403`) and **`autoClose: 20_000`**. Message text matches the prior `serverErrorHandler` fields (`errorMessage` / `message` / `error`).
+- **Manual QA:** Trigger a 403 (e.g. classification create without permission) — toast should stay ~20s.
+
+## ATLAS-5275 — dashboard build / lint (2026-04)
+
+- **ESLint:** Removed unused `eslint-disable-next-line react-hooks/exhaustive-deps` in `SchemaTab.tsx` (report-unused-disable-directives treated as error).
+- **TypeScript / glossary export:** Temporarily stubbed — see **Glossary browse / export — temporarily stubbed (2026-05)** above (was blocked on **`xlsx`** + missing glossary export API helpers).
+- **Verification:** `npx tsc --noEmit`, `npm run lint`, and `npm run build` in `dashboard/` — pass after stub (ESLint warnings largely unchanged).
+
+## React UI — Glossary / BM import: show Atlas error message (2026-04)
+
+- **Issue:** Failed import (e.g. HTTP 409 with `{ errorCode, errorMessage: "Glossary import failed" }`) showed **“Invalid JSON response from server”** because **`ImportDialog`** treated any rejected request as that generic string; the body was valid JSON.
+- **Fix:** `dashboard/src/components/ImportDialog.tsx` — on **`catch`**, if **`axios.isAxiosError`**, read **`error.response.data`** via **`extractAtlasErrorMessage`** (`errorMessage` / `message` / `error` / `msgDesc`, same idea as classic / `serverErrorHandler`). Skip a second toast when **`fetchApi`** already handled the status (**401, 403, 404, 419, 500, 503, 504**). Fallback: **“Import failed…”** for unknown errors.
+- **Manual QA:** Glossary or BM import with a failing file — toast should match backend **`errorMessage`** (e.g. “Glossary import failed”).
+
+## npm security dependency remediation (dashboard / dashboardv2 / docs, 2026-05)
+
+- **Purpose:** Address Dependabot **high** alerts for frontend manifests (`dashboard/package-lock.json`, nested `atlas-lineage` locks, `dashboardv2/package-lock.json`, `docs/package-lock.json`).
+- **Changes (summary):**
+ - **`dashboard/`:** `vite` **6.4.1 → 6.4.2** (dev arbitrary file read via dev-server WebSocket when exposed); `axios` **→ 1.15.2**; npm **`overrides`** for **`lodash` / `lodash-es` → 4.18.1** (fixes incorrect pin on vulnerable **4.17.23**), **`flatted` → 3.4.2**.
+ - **`dashboard/.../atlas-lineage/`:** `@babel/core` **7.29.0**, `@babel/preset-env` **7.29.5**; **`overrides`:** **`lodash` 4.18.1**, **`serialize-javascript` 7.0.3**, **`@babel/plugin-transform-modules-systemjs` 7.29.4**.
+ - **`dashboardv2/`:** **`lodash` override** **4.17.23 → 4.18.1** (grunt/dagre-d3 tree).
+ - **`dashboardv2/.../atlas-lineage/`:** Same Babel / lodash / serialize-javascript / systemjs overrides as dashboard lineage.
+ - **`docs/`:** **`axios` → 1.15.2**; **`node-forge` override** **1.3.2 → 1.4.0**; **`lodash` → 4.18.1**; added **`overrides`** for **`@babel/plugin-transform-modules-systemjs` 7.29.4**, **`serialize-javascript` 7.0.3**, **`fast-uri` 3.1.2**, **`picomatch` 2.3.2**, duplicated **`axios`** override for transitive installs.
+- **Verification runs (2026-05-21):**
+ - **`dashboardv2/`:** `npm run build` — **pass** (includes lineage webpack build).
+ - **`docs/`:** `npm run build` — **pass** (`patch-package` applied **`html-minifier@4.0.0`** and **`http-proxy-middleware@0.19.1`**).
+ - **`dashboard/`:** `npm run lint` — **pass** (warnings only). **`npm run build`** — **pass** after glossary export stub (see **Glossary browse / export — temporarily stubbed** above).
+- **`npm audit`:** Registry pointed at npmmirror in this environment; audit endpoint errors are environmental — re-run **`npm audit --audit-level=high`** against **`registry.npmjs.org`** in CI.
+
+## Glossary terms list — search API integration (2026-07)
+
+- **Page:** `GlossaryTermsListPage` (`#/glossary/terms-list`) uses **`POST /api/atlas/v2/glossary/search`** for table data; glossary filter dropdown reuses Redux **`fetchGlossaryData`** (`GET /v2/glossary`, shared with sidebar — no extra search `limit: 0` on this page).
+- **Bug fix (2026-07):** `fetchGlossarySearchPage` unwraps Axios `response.data` via `unwrapGlossarySearchResponse` before mapping rows (table was empty when reading `response.glossary` on the Axios wrapper).
+- **UX parity (2026-07):** `TableLayout` + `TablePagination` (search-result styling); name + classification capsule links; filters: Glossary → Record type → Status → Search all columns (classification filter removed).
+- **Default request:** `limit: 25`, `offset: 0`, `sortBy: "glossaryName"`, `sortOrder: "ASCENDING"`, `excludeDeleted: true`.
+- **Filters → API:** Record type → `glossaryType` (`TERM` / `CATEGORY`); Glossary autocomplete → `glossary.name` + `glossary.guid`; Status → `status`; Search all columns → `searchQuery`. Pagination uses server `limit`/`offset`; total from `approximateCount`.
+- **Response mapping:** `mapGlossarySearchResultToTableRows` builds table rows with `guid`, `glossaryGuid`, `classifications`; `tableRowToExportRow` for export.
+- **API dedup:** Stable `fetchData` callback via `glossaryGuidByNameRef`; skip redundant `fetchGlossaryData` when Redux already loading/loaded.
+- **Export:** Single **Download** button enqueues export via `POST /v2/glossary/create_file` (same filter body as table search).
+- **Export navigation (2026-07):** Removed header glossary list icon; **Export Glossary** added to sidebar Glossary ⋮ menu (`SideBarTree.tsx`, `data-cy="glossaryTermsListNavigate"`). Tests: `SideBarTree.test.tsx`, `Header.test.tsx` (icon removed).
+- **Header download popover (2026-08):** Glossary export status API reuses `AtlasSearchResultDownloadStatus`, so files arrive in `searchDownloadRecords`; UI tags them as glossary based on the glossary endpoint call. Tests: `Header.test.tsx` (`searchDownloadRecords` from glossary API).
+- **Header download popover UX (2026-08-12):** Removed per-file source labels from React `Header.tsx` and classic `DownloadSearchResultLayoutView.js`. Classic header actions (toggle, refresh, close) aligned on one row via `downloads.scss`. Download toggle: **ON (default)** = all files; **OFF** = completed only. Classic variable `showAllDownloads` aligned with React `checked=true`. Tests: `Header.test.tsx` (default all files, toggle OFF hides pending, pending-only + OFF → No Data Found); [...]
+- **Classic download panel UX (2026-08-12):** Panel closes on outside click (search, page content) via document listener; filename and download/spinner icon spaced with flex `gap: 16px` (matches React `Stack spacing={2}`). Empty state uses `.download-list-empty` class (no inline styles). Manual QA: open downloads → click search or outside → panel closes; long filenames do not overlap action icon.
+- **Classic glossary dropdown (2026-08-12):** `GlossaryLayoutView.onExportGlossary` closes the sidebar ⋮ dropdown after click (same as import/template actions). Removed duplicate delegated click handler in `bindEvents`.
+- **Classic terms-list actions (2026-08-12):** Refresh and Download aligned horizontally; Download uses a dropdown menu with CSV/XLSX options that enqueue export on selection (React `GlossaryTermsListPage`, classic `GlossaryTermsListLayoutView_tmpl.html`). Removed Download button `title` tooltip on classic UI (blocked dropdown clicks). React header has 16px spacing above filters section. Header download popover lists files newest-first (`downloadRecords.ts`, classic `DownloadSearchResult [...]
+- **Classic terms-list URL stability (2026-08-12):** On `#!/glossary/terms-list`, skip `triggerUrl()` only for programmatic jstree selection (no `data.event` on refresh/tree load). User sidebar clicks still navigate to term/category detail via `triggerUrl()`.
+- **Cleanup (2026-08-12):** Fixed download toast typo in `Header.tsx` (`successfully`); removed unused sync-export helpers from `GlossaryExport.js` (`buildExportRequest`, `triggerBrowserFileDownload`, `resolveExportFileName`).
+- **Review fixes (2026-08-12):** Moved glossary term link width override to `glossary.scss`; added negative/edge tests in `glossaryExport.test.ts`, `GlossaryTermsListPage.test.tsx`, `glossaryTermsListColumns.test.tsx`, `GlossaryStatusBadge.test.tsx`. `Header.tsx`: `setNavigate` moved to `useEffect` (search result pathname); typed `toastId` (`Id`) and session selector (`HeaderSessionState`); Header toggle OFF integration tests added.
+- **Glossary import/export UX fixes (2026-08-12):** Sidebar **Download Import template** and **Import Glossary Term** always enabled (React `SideBarTree.tsx`; classic `GlossaryLayoutView.js` no longer disables ⋮ menu on Category view). React import success dispatches `fetchGlossaryData` (`ImportDialog.onImportSuccess`). Terms-list **Download** dropdown (CSV / XLSX) on React `GlossaryTermsListPage` and classic `GlossaryTermsListLayoutView`; selecting a format enqueues async export via `PO [...]
+- **Status column (2026-07):** Narrow width (76px); `GlossaryStatusBadge` — outlined MUI `Chip` with color only (`success` Active, `warning` Draft, `error` Deprecated) and tooltip. Tests: `glossaryStatus.test.ts`, `GlossaryStatusBadge.test.tsx`, `glossaryTermsListColumns.test.tsx`.
+- **Sort default:** `sortOrder: DESCENDING`.
+- **Custom attributes:** Display `key: value` string with JSON tooltip from API `customAttributes` object.
+- **Automated tests:** `glossaryExport.test.ts` — includes `mapGlossarySearchResultToTableRows`, updated filter shape (no `classificationFilter`).
+- **Manual QA:** Open Glossary terms & categories page; confirm **one** `POST .../glossary/search` on load (plus sidebar `GET /v2/glossary` if glossary tree not yet loaded); name/classification chips link to detail pages; pagination uses `approximateCount`.
+- **Bug fix (2026-07):** `TextShowMoreLess` requires `data: string[]`; description/custom-attribute columns passed plain strings and crashed the page (`data.map is not a function`). Fixed in `glossaryTermsListColumns.tsx`; test: `glossaryTermsListColumns.test.tsx`.
+- **UX update (2026-07):** Name uses search-result plain link (no chip hover scale); descriptions/custom attributes are plain ellipsis text with tooltip; columns reordered (Glossary Name → Name → Record Type → descriptions → Classifications → Custom Attributes → Status); Related Categories column removed; status filter is dropdown (`DRAFT` / `ACTIVE` / `DEPRECATED`); term rows use `DialogShowMoreLess` + `removeClassification` / `AddTag` with table refresh via `setUpdateTable`.
+- **Layout alignment (2026-07):** `GlossaryTermsListPage` wrapped in `Item` (`glossary-terms-list-page`) with header/filter/table sections using consistent 16px horizontal padding (matches Administrator / dashboardv2 spacing); filters use MUI `Grid` (4 columns). Styles in `glossary.scss`. Download still uses `requestGlossaryExportDownload` → `POST /v2/glossary/create_file`. Tests: `GlossaryTermsListPage.test.tsx`.
diff --git a/dashboard/src/api/apiMethods/__tests__/glossaryApiMethod.test.ts b/dashboard/src/api/apiMethods/__tests__/glossaryApiMethod.test.ts
index b91c5fcc9..8ba3bc33c 100644
--- a/dashboard/src/api/apiMethods/__tests__/glossaryApiMethod.test.ts
+++ b/dashboard/src/api/apiMethods/__tests__/glossaryApiMethod.test.ts
@@ -28,6 +28,11 @@
import {
removeTerm,
getGlossary,
+ getGlossaryTermsForGlossary,
+ getGlossaryCategoriesForGlossary,
+ searchGlossary,
+ createGlossaryExportFile,
+ getGlossaryDownloadStatus,
getGlossaryImportTmpl,
getGlossaryImport,
getGlossaryType,
@@ -57,7 +62,10 @@ import {
assignTermtoEntitiesUrl,
assignTermtoCategoryUrl,
assignGlossaryTypeUrl,
- removeTermorCatgeoryUrl
+ removeTermorCatgeoryUrl,
+ glossaryTermsUrl,
+ glossaryCategoriesUrl,
+ glossarySearchUrl
} from '../../../api/apiUrlLinks/glossaryUrl'
// Mock dependencies
@@ -81,6 +89,11 @@ const mockAssignTermtoEntitiesUrl = jest.fn((termId: string) => `/api/glossary/t
const mockAssignTermtoCategoryUrl = jest.fn((categoryId: string) => `/api/glossary/category/${categoryId}`)
const mockAssignGlossaryTypeUrl = jest.fn((guid: string) => `/api/glossary/type/${guid}`)
const mockRemoveTermorCatgeoryUrl = jest.fn((guid: string, type: string) => `/api/glossary/${type}/${guid}`)
+const mockGlossaryTermsUrl = jest.fn((guid: string) => `/api/glossary/${guid}/terms`)
+const mockGlossaryCategoriesUrl = jest.fn((guid: string) => `/api/glossary/${guid}/categories`)
+const mockGlossarySearchUrl = jest.fn(() => '/api/glossary/search')
+const mockGlossaryCreateFileUrl = jest.fn(() => '/api/glossary/create_file')
+const mockGlossaryDownloadStatusUrl = jest.fn(() => '/api/glossary/download/status')
jest.mock('../../../api/apiUrlLinks/glossaryUrl', () => ({
removeTermUrl: (...args: any[]) => mockRemoveTermUrl(...args),
@@ -95,7 +108,12 @@ jest.mock('../../../api/apiUrlLinks/glossaryUrl', () => ({
assignTermtoEntitiesUrl: (...args: any[]) => mockAssignTermtoEntitiesUrl(...args),
assignTermtoCategoryUrl: (...args: any[]) => mockAssignTermtoCategoryUrl(...args),
assignGlossaryTypeUrl: (...args: any[]) => mockAssignGlossaryTypeUrl(...args),
- removeTermorCatgeoryUrl: (...args: any[]) => mockRemoveTermorCatgeoryUrl(...args)
+ removeTermorCatgeoryUrl: (...args: any[]) => mockRemoveTermorCatgeoryUrl(...args),
+ glossaryTermsUrl: (...args: any[]) => mockGlossaryTermsUrl(...args),
+ glossaryCategoriesUrl: (...args: any[]) => mockGlossaryCategoriesUrl(...args),
+ glossarySearchUrl: (...args: any[]) => mockGlossarySearchUrl(...args),
+ glossaryCreateFileUrl: (...args: any[]) => mockGlossaryCreateFileUrl(...args),
+ glossaryDownloadStatusUrl: (...args: any[]) => mockGlossaryDownloadStatusUrl(...args)
}))
describe('glossaryApiMethod', () => {
@@ -132,6 +150,8 @@ describe('glossaryApiMethod', () => {
mockAssignTermtoCategoryUrl.mockImplementation((categoryId: string) => `/api/glossary/category/${categoryId}`)
mockAssignGlossaryTypeUrl.mockImplementation((guid: string) => `/api/glossary/type/${guid}`)
mockRemoveTermorCatgeoryUrl.mockImplementation((guid: string, type: string) => `/api/glossary/${type}/${guid}`)
+ mockGlossaryTermsUrl.mockImplementation((guid: string) => `/api/glossary/${guid}/terms`)
+ mockGlossaryCategoriesUrl.mockImplementation((guid: string) => `/api/glossary/${guid}/categories`)
})
describe('removeTerm', () => {
@@ -163,6 +183,85 @@ describe('glossaryApiMethod', () => {
})
})
+ describe('getGlossaryTermsForGlossary', () => {
+ it('should call _get with terms URL and list params', async () => {
+ const result = await getGlossaryTermsForGlossary('g-1')
+
+ expect(mockGlossaryTermsUrl).toHaveBeenCalledWith('g-1')
+ expect(mockGet).toHaveBeenCalledWith('/api/glossary/g-1/terms', {
+ method: 'GET',
+ params: { limit: -1, offset: 0, sort: 'ASC' }
+ })
+ expect(result).toEqual(mockResponse)
+ })
+ })
+
+ describe('getGlossaryCategoriesForGlossary', () => {
+ it('should call _get with categories URL and list params', async () => {
+ const result = await getGlossaryCategoriesForGlossary('g-2')
+
+ expect(mockGlossaryCategoriesUrl).toHaveBeenCalledWith('g-2')
+ expect(mockGet).toHaveBeenCalledWith('/api/glossary/g-2/categories', {
+ method: 'GET',
+ params: { limit: -1, offset: 0, sort: 'ASC' }
+ })
+ expect(result).toEqual(mockResponse)
+ })
+ })
+
+ describe('searchGlossary', () => {
+ it('should POST search parameters to glossary search URL', async () => {
+ const params = {
+ limit: 25,
+ offset: 0,
+ sortBy: 'glossaryName',
+ sortOrder: 'ASCENDING'
+ }
+ const result = await searchGlossary(params)
+
+ expect(mockGlossarySearchUrl).toHaveBeenCalled()
+ expect(mockPost).toHaveBeenCalledWith('/api/glossary/search', {
+ method: 'POST',
+ params: {},
+ data: params
+ })
+ expect(result).toEqual(mockResponse)
+ })
+ })
+
+ describe('createGlossaryExportFile', () => {
+ it('should POST export parameters to glossary create_file URL', async () => {
+ const params = {
+ limit: 0,
+ offset: 0,
+ sortBy: 'glossaryName',
+ sortOrder: 'DESCENDING'
+ }
+ const result = await createGlossaryExportFile(params)
+
+ expect(mockGlossaryCreateFileUrl).toHaveBeenCalled()
+ expect(mockPost).toHaveBeenCalledWith('/api/glossary/create_file', {
+ method: 'POST',
+ params: {},
+ data: params
+ })
+ expect(result).toEqual(mockResponse)
+ })
+ })
+
+ describe('getGlossaryDownloadStatus', () => {
+ it('should GET glossary download status URL', async () => {
+ const result = await getGlossaryDownloadStatus({})
+
+ expect(mockGlossaryDownloadStatusUrl).toHaveBeenCalled()
+ expect(mockGet).toHaveBeenCalledWith('/api/glossary/download/status', {
+ method: 'GET',
+ params: {}
+ })
+ expect(result).toEqual(mockResponse)
+ })
+ })
+
describe('getGlossaryImportTmpl', () => {
it('should call _get with correct URL and params', async () => {
const params = { type: 'glossary' }
diff --git a/dashboard/src/api/apiMethods/glossaryApiMethod.ts b/dashboard/src/api/apiMethods/glossaryApiMethod.ts
index 2d8f2f381..52b58d6b0 100644
--- a/dashboard/src/api/apiMethods/glossaryApiMethod.ts
+++ b/dashboard/src/api/apiMethods/glossaryApiMethod.ts
@@ -27,6 +27,11 @@ import {
glossaryImportUrl,
glossaryTypeUrl,
glossaryUrl,
+ glossaryTermsUrl,
+ glossaryCategoriesUrl,
+ glossarySearchUrl,
+ glossaryCreateFileUrl,
+ glossaryDownloadStatusUrl,
removeTermorCatgeoryUrl,
removeTermUrl
} from "../apiUrlLinks/glossaryUrl";
@@ -93,6 +98,48 @@ const getGlossaryType = (glossaryType: string, guid: string) => {
return _get(glossaryTypeUrl(glossaryType, guid), config);
};
+const getGlossaryTermsForGlossary = (glossaryGuid: string) => {
+ const config: configs = {
+ method: "GET",
+ params: { limit: -1, offset: 0, sort: "ASC" }
+ };
+ return _get(glossaryTermsUrl(glossaryGuid), config);
+};
+
+const getGlossaryCategoriesForGlossary = (glossaryGuid: string) => {
+ const config: configs = {
+ method: "GET",
+ params: { limit: -1, offset: 0, sort: "ASC" }
+ };
+ return _get(glossaryCategoriesUrl(glossaryGuid), config);
+};
+
+const searchGlossary = (params: object) => {
+ const config: importConfigs = {
+ method: "POST",
+ params: {},
+ data: params
+ };
+ return _post(glossarySearchUrl(), config);
+};
+
+const createGlossaryExportFile = (params: object) => {
+ const config: importConfigs = {
+ method: "POST",
+ params: {},
+ data: params
+ };
+ return _post(glossaryCreateFileUrl(), config);
+};
+
+const getGlossaryDownloadStatus = (params: object) => {
+ const config: configs = {
+ method: "GET",
+ params: params
+ };
+ return _get(glossaryDownloadStatusUrl(), config);
+};
+
const createGlossary = (params: any) => {
const config: importConfigs = {
method: "POST",
@@ -182,6 +229,11 @@ const removeTermorCategory = (
export {
removeTerm,
getGlossary,
+ getGlossaryTermsForGlossary,
+ getGlossaryCategoriesForGlossary,
+ searchGlossary,
+ createGlossaryExportFile,
+ getGlossaryDownloadStatus,
getGlossaryImportTmpl,
getGlossaryImport,
getGlossaryType,
diff --git a/dashboard/src/api/apiUrlLinks/__tests__/glossaryUrl.test.ts b/dashboard/src/api/apiUrlLinks/__tests__/glossaryUrl.test.ts
index 91f318d7f..ba822ec18 100644
--- a/dashboard/src/api/apiUrlLinks/__tests__/glossaryUrl.test.ts
+++ b/dashboard/src/api/apiUrlLinks/__tests__/glossaryUrl.test.ts
@@ -47,7 +47,13 @@ import {
assignTermtoEntitiesUrl,
assignTermtoCategoryUrl,
assignGlossaryTypeUrl,
- removeTermorCatgeoryUrl
+ removeTermorCatgeoryUrl,
+ glossaryTermsUrl,
+ glossaryCategoriesUrl,
+ glossarySearchUrl,
+ glossaryCreateFileUrl,
+ glossaryDownloadStatusUrl,
+ glossaryDownloadFileUrl
} from '../glossaryUrl'
import { getBaseApiUrl } from '../commonApiUrl'
@@ -289,6 +295,54 @@ describe('glossaryUrl', () => {
})
})
+ describe('glossaryTermsUrl', () => {
+ it('should return terms URL for a glossary guid', () => {
+ const result = glossaryTermsUrl('glossary-guid-1')
+ expect(result).toBe(
+ '/mock-base-url/api/atlas/v2/glossary/glossary-guid-1/terms'
+ )
+ })
+ })
+
+ describe('glossaryCategoriesUrl', () => {
+ it('should return categories URL for a glossary guid', () => {
+ const result = glossaryCategoriesUrl('glossary-guid-2')
+ expect(result).toBe(
+ '/mock-base-url/api/atlas/v2/glossary/glossary-guid-2/categories'
+ )
+ })
+ })
+
+ describe('glossarySearchUrl', () => {
+ it('should return glossary search URL', () => {
+ const result = glossarySearchUrl()
+ expect(result).toBe('/mock-base-url/api/atlas/v2/glossary/search')
+ })
+ })
+
+ describe('glossaryCreateFileUrl', () => {
+ it('should return glossary create_file URL', () => {
+ const result = glossaryCreateFileUrl()
+ expect(result).toBe('/mock-base-url/api/atlas/v2/glossary/create_file')
+ })
+ })
+
+ describe('glossaryDownloadStatusUrl', () => {
+ it('should return glossary download status URL', () => {
+ const result = glossaryDownloadStatusUrl()
+ expect(result).toBe('/mock-base-url/api/atlas/v2/glossary/download/status')
+ })
+ })
+
+ describe('glossaryDownloadFileUrl', () => {
+ it('should return glossary download file URL', () => {
+ const result = glossaryDownloadFileUrl('glossary-export.csv')
+ expect(result).toBe(
+ '/mock-base-url/api/atlas/v2/glossary/download/glossary-export.csv'
+ )
+ })
+ })
+
describe('removeTermorCatgeoryUrl', () => {
it('should return correct URL for removing term', () => {
const guid = 'term-guid-123'
diff --git a/dashboard/src/api/apiUrlLinks/glossaryUrl.ts b/dashboard/src/api/apiUrlLinks/glossaryUrl.ts
index f80028ae3..644dd33c1 100644
--- a/dashboard/src/api/apiUrlLinks/glossaryUrl.ts
+++ b/dashboard/src/api/apiUrlLinks/glossaryUrl.ts
@@ -40,6 +40,30 @@ const glossaryTypeUrl = (glossaryType: string, guid: string) => {
return `${glossaryUrl()}/${glossaryType}/${guid}`;
};
+const glossaryTermsUrl = (glossaryGuid: string) => {
+ return `${glossaryUrl()}/${glossaryGuid}/terms`;
+};
+
+const glossaryCategoriesUrl = (glossaryGuid: string) => {
+ return `${glossaryUrl()}/${glossaryGuid}/categories`;
+};
+
+const glossarySearchUrl = () => {
+ return `${glossaryUrl()}/search`;
+};
+
+const glossaryCreateFileUrl = () => {
+ return `${glossaryUrl()}/create_file`;
+};
+
+const glossaryDownloadStatusUrl = () => {
+ return `${glossaryUrl()}/download/status`;
+};
+
+const glossaryDownloadFileUrl = (fileName: string) => {
+ return `${glossaryUrl()}/download/${fileName}`;
+};
+
const editGlossaryUrl = (guid: string) => {
return `${glossaryUrl()}/${guid}`;
};
@@ -83,6 +107,12 @@ export {
glossaryImportTempUrl,
glossaryImportUrl,
glossaryTypeUrl,
+ glossaryTermsUrl,
+ glossaryCategoriesUrl,
+ glossarySearchUrl,
+ glossaryCreateFileUrl,
+ glossaryDownloadStatusUrl,
+ glossaryDownloadFileUrl,
editGlossaryUrl,
deleteGlossaryorTermUrl,
createTermorCategoryUrl,
diff --git a/dashboard/src/components/ImportDialog.tsx b/dashboard/src/components/ImportDialog.tsx
index 10d82aa1d..6bdf02618 100644
--- a/dashboard/src/components/ImportDialog.tsx
+++ b/dashboard/src/components/ImportDialog.tsx
@@ -62,12 +62,14 @@ interface CustomModalProps {
open: boolean;
onClose: () => void;
title: string;
+ onImportSuccess?: () => void;
}
export const ImportDialog: React.FC<CustomModalProps> = ({
open,
onClose,
- title
+ title,
+ onImportSuccess
}) => {
const [fileData, setFileData] = useState<any>([]);
const [progress, setProgress] = useState(0);
@@ -106,6 +108,7 @@ export const ImportDialog: React.FC<CustomModalProps> = ({
`File: ${fileData.name} imported successfully`
);
+ onImportSuccess?.();
onClose();
setErrorDetails(false);
setFileData([]);
diff --git a/dashboard/src/components/__tests__/ImportDialog.test.tsx b/dashboard/src/components/__tests__/ImportDialog.test.tsx
index d504ce785..4fdaddbd7 100644
--- a/dashboard/src/components/__tests__/ImportDialog.test.tsx
+++ b/dashboard/src/components/__tests__/ImportDialog.test.tsx
@@ -85,9 +85,15 @@ describe('ImportDialog', () => {
it('uploads business metadata file successfully', async () => {
uploadMock.mockResolvedValue({ data: {} })
const onClose = jest.fn()
+ const onImportSuccess = jest.fn()
render(
- <ImportDialog open={true} onClose={onClose} title="Import Business Metadata" />
+ <ImportDialog
+ open={true}
+ onClose={onClose}
+ onImportSuccess={onImportSuccess}
+ title="Import Business Metadata"
+ />
)
fireEvent.click(screen.getByText('Select File'))
@@ -96,10 +102,34 @@ describe('ImportDialog', () => {
await waitFor(() => {
expect(uploadMock).toHaveBeenCalled()
expect(onClose).toHaveBeenCalled()
+ expect(onImportSuccess).toHaveBeenCalled()
expect(toastSuccess).toHaveBeenCalled()
})
})
+ it('does not call onImportSuccess when upload fails', async () => {
+ uploadMock.mockRejectedValue(new Error('fail'))
+ const onImportSuccess = jest.fn()
+
+ render(
+ <ImportDialog
+ open={true}
+ onClose={jest.fn()}
+ onImportSuccess={onImportSuccess}
+ title="Import Business Metadata"
+ />
+ )
+
+ fireEvent.click(screen.getByText('Select File'))
+ fireEvent.click(screen.getByText('Upload'))
+
+ await waitFor(() => {
+ expect(toastError).toHaveBeenCalledWith('Invalid JSON response from server')
+ })
+
+ expect(onImportSuccess).not.toHaveBeenCalled()
+ })
+
it('shows error details when import returns failed info', async () => {
glossaryMock.mockResolvedValue({
data: {
diff --git a/dashboard/src/index.scss b/dashboard/src/index.scss
index a05d9fbec..329132034 100644
--- a/dashboard/src/index.scss
+++ b/dashboard/src/index.scss
@@ -35,6 +35,7 @@
@use "@styles/errorPage.scss" as *;
@use "@styles/customdatepPicker.scss" as *;
@use "@styles/administration.scss" as *;
+@use "@styles/glossary.scss" as *;
@font-face {
font-family: "Source Sans 3";
diff --git a/dashboard/src/styles/glossary.scss b/dashboard/src/styles/glossary.scss
new file mode 100644
index 000000000..0bed82e00
--- /dev/null
+++ b/dashboard/src/styles/glossary.scss
@@ -0,0 +1,55 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+.glossary-terms-list-page {
+ width: 100%;
+ text-align: left;
+
+ .glossary-terms-list-header {
+ padding: 16px 16px 0;
+ margin-bottom: 16px;
+ }
+
+ .glossary-terms-list-title {
+ margin: 0;
+ }
+
+ .glossary-terms-filters {
+ margin: 0 16px;
+ padding: 16px;
+ border: thin #e1e2e4 solid;
+ border-radius: 4px;
+ background: rgba(255, 255, 255, 0.6);
+ }
+
+ .glossary-terms-filters-label {
+ margin-bottom: 12px;
+ font-weight: 600;
+ color: rgba(0, 0, 0, 0.87);
+ }
+
+ .glossary-terms-table {
+ padding: 0 16px 16px;
+ flex: 1;
+ min-height: 0;
+
+ .searchTableName .glossary-term-name-link {
+ width: unset !important;
+ white-space: nowrap;
+ }
+ }
+}
diff --git a/dashboard/src/utils/__tests__/downloadRecords.test.ts b/dashboard/src/utils/__tests__/downloadRecords.test.ts
new file mode 100644
index 000000000..066b6bc1f
--- /dev/null
+++ b/dashboard/src/utils/__tests__/downloadRecords.test.ts
@@ -0,0 +1,222 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import {
+ dedupeDownloadRecordsByFileName,
+ extractDownloadRecords,
+ filterDownloadRecordsForToggle,
+ mergeDownloadRecords,
+ parseCreatedTime,
+ parseTimestampFromFileName,
+ resolveDownloadRecordTime,
+ sortDownloadRecordsByLatest
+} from "../downloadRecords";
+
+describe("downloadRecords utils", () => {
+ it("parseCreatedTime accepts epoch numbers", () => {
+ expect(parseCreatedTime(1_700_000_000_000)).toBe(1_700_000_000_000);
+ });
+
+ it("parseCreatedTime accepts ISO strings", () => {
+ const iso = "2026-08-12T15:36:29.000Z";
+ expect(parseCreatedTime(iso)).toBe(Date.parse(iso));
+ });
+
+ it("parseCreatedTime returns null for invalid values", () => {
+ expect(parseCreatedTime(undefined)).toBeNull();
+ expect(parseCreatedTime("not-a-date")).toBeNull();
+ });
+
+ it("parseTimestampFromFileName parses glossary export filenames", () => {
+ expect(
+ parseTimestampFromFileName(
+ "admin_GLOSSARY_EXPORT_2026-08-12_15-36-29.xlsx"
+ )
+ ).toBe(Date.parse("2026-08-12T15:36:29"));
+ });
+
+ it("parseTimestampFromFileName parses search export filenames", () => {
+ expect(
+ parseTimestampFromFileName(
+ "admin_basic_2026-08-12_12-47-19.123.csv"
+ )
+ ).toBe(Date.parse("2026-08-12T12:47:19.123"));
+ });
+
+ it("resolveDownloadRecordTime prefers API createdTime over filename", () => {
+ expect(
+ resolveDownloadRecordTime({
+ fileName: "admin_GLOSSARY_EXPORT_2026-08-12_15-36-29.xlsx",
+ createdTime: 1_700_000_000_000
+ })
+ ).toBe(1_700_000_000_000);
+ });
+
+ it("resolveDownloadRecordTime falls back to filename timestamp", () => {
+ expect(
+ resolveDownloadRecordTime({
+ fileName: "admin_GLOSSARY_EXPORT_2026-08-12_15-36-29.xlsx"
+ })
+ ).toBe(Date.parse("2026-08-12T15:36:29"));
+ });
+
+ it("sortDownloadRecordsByLatest orders newest first using createdTime", () => {
+ const sorted = sortDownloadRecordsByLatest([
+ {
+ fileName: "older.csv",
+ source: "search",
+ createdTime: 1_000
+ },
+ {
+ fileName: "newer.csv",
+ source: "search",
+ createdTime: 2_000
+ }
+ ]);
+
+ expect(sorted.map((record) => record.fileName)).toEqual([
+ "newer.csv",
+ "older.csv"
+ ]);
+ });
+
+ it("sortDownloadRecordsByLatest orders newest first using filename timestamps", () => {
+ const sorted = sortDownloadRecordsByLatest([
+ {
+ fileName: "admin_GLOSSARY_EXPORT_2026-08-12_12-11-41.csv",
+ source: "glossary"
+ },
+ {
+ fileName: "admin_GLOSSARY_EXPORT_2026-08-12_15-36-29.xlsx",
+ source: "glossary"
+ }
+ ]);
+
+ expect(sorted.map((record) => record.fileName)).toEqual([
+ "admin_GLOSSARY_EXPORT_2026-08-12_15-36-29.xlsx",
+ "admin_GLOSSARY_EXPORT_2026-08-12_12-11-41.csv"
+ ]);
+ });
+
+ it("extractDownloadRecords reads glossary records from searchDownloadRecords fallback", () => {
+ const records = extractDownloadRecords(
+ {
+ searchDownloadRecords: [
+ {
+ fileName: "admin_GLOSSARY_EXPORT_2026-08-12_15-36-29.xlsx",
+ createdTime: 100
+ }
+ ]
+ },
+ "glossary"
+ );
+
+ expect(records).toEqual([
+ {
+ fileName: "admin_GLOSSARY_EXPORT_2026-08-12_15-36-29.xlsx",
+ source: "glossary",
+ createdTime: 100,
+ status: undefined
+ }
+ ]);
+ });
+
+ it("mergeDownloadRecords combines and sorts search and glossary records", () => {
+ const merged = mergeDownloadRecords(
+ [
+ {
+ fileName: "admin_basic_2026-08-12_12-47-19.csv",
+ source: "search"
+ }
+ ],
+ [
+ {
+ fileName: "admin_GLOSSARY_EXPORT_2026-08-12_15-36-29.xlsx",
+ source: "glossary"
+ }
+ ]
+ );
+
+ expect(merged.map((record) => record.fileName)).toEqual([
+ "admin_GLOSSARY_EXPORT_2026-08-12_15-36-29.xlsx",
+ "admin_basic_2026-08-12_12-47-19.csv"
+ ]);
+ });
+
+ it("dedupeDownloadRecordsByFileName keeps the newest duplicate fileName", () => {
+ const deduped = dedupeDownloadRecordsByFileName([
+ {
+ fileName: "duplicate.csv",
+ source: "search",
+ createdTime: 100
+ },
+ {
+ fileName: "duplicate.csv",
+ source: "glossary",
+ createdTime: 200
+ }
+ ]);
+
+ expect(deduped).toEqual([
+ {
+ fileName: "duplicate.csv",
+ source: "glossary",
+ createdTime: 200
+ }
+ ]);
+ });
+
+ it("filterDownloadRecordsForToggle returns all files when showing all exports", () => {
+ const records = [
+ {
+ fileName: "ready.csv",
+ source: "search" as const,
+ status: "COMPLETE"
+ },
+ {
+ fileName: "pending.csv",
+ source: "search" as const,
+ status: "PENDING"
+ }
+ ];
+
+ expect(filterDownloadRecordsForToggle(records, true)).toEqual(records);
+ });
+
+ it("filterDownloadRecordsForToggle hides pending files when showing completed only", () => {
+ const records = [
+ {
+ fileName: "ready.csv",
+ source: "search" as const,
+ status: "COMPLETE"
+ },
+ {
+ fileName: "pending.csv",
+ source: "search" as const,
+ status: "PENDING"
+ }
+ ];
+
+ expect(filterDownloadRecordsForToggle(records, false)).toEqual([
+ {
+ fileName: "ready.csv",
+ source: "search",
+ status: "COMPLETE"
+ }
+ ]);
+ });
+});
diff --git a/dashboard/src/utils/__tests__/glossaryExport.test.ts b/dashboard/src/utils/__tests__/glossaryExport.test.ts
new file mode 100644
index 000000000..ff3c458fc
--- /dev/null
+++ b/dashboard/src/utils/__tests__/glossaryExport.test.ts
@@ -0,0 +1,300 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import {
+ createGlossaryExportFile,
+ searchGlossary
+} from "@api/apiMethods/glossaryApiMethod";
+import {
+ buildGlossarySearchExportRequest,
+ buildGlossarySearchRequest,
+ createDefaultGlossaryBrowseFilters,
+ fetchGlossarySearchPage,
+ formatCustomAttributesForDisplay,
+ formatCustomAttributesForTooltip,
+ GLOSSARY_STATUS_FILTER_OPTIONS,
+ mapGlossarySearchResultToTableRows,
+ mapRecordTypeToGlossaryType,
+ requestGlossaryExportDownload,
+ unwrapGlossarySearchResponse,
+ type GlossarySearchResponse
+} from "../glossaryExport";
+
+jest.mock("@api/apiMethods/glossaryApiMethod", () => ({
+ searchGlossary: jest.fn(),
+ createGlossaryExportFile: jest.fn()
+}));
+
+const mockSearchGlossary = searchGlossary as jest.MockedFunction<
+ typeof searchGlossary
+>;
+const mockCreateGlossaryExportFile =
+ createGlossaryExportFile as jest.MockedFunction<
+ typeof createGlossaryExportFile
+ >;
+
+describe("glossaryExport utilities", () => {
+ beforeEach(() => {
+ jest.clearAllMocks();
+ });
+
+ it("createDefaultGlossaryBrowseFilters returns empty filters", () => {
+ expect(createDefaultGlossaryBrowseFilters()).toEqual({
+ recordType: "all",
+ glossaryName: "",
+ statusFilter: "",
+ searchText: ""
+ });
+ });
+
+ it("mapRecordTypeToGlossaryType maps UI filters to API enum", () => {
+ expect(mapRecordTypeToGlossaryType("Term")).toBe("TERM");
+ expect(mapRecordTypeToGlossaryType("Category")).toBe("CATEGORY");
+ expect(mapRecordTypeToGlossaryType("all")).toBeUndefined();
+ });
+
+ it("buildGlossarySearchRequest applies defaults and filters", () => {
+ const request = buildGlossarySearchRequest(
+ {
+ ...createDefaultGlossaryBrowseFilters(),
+ recordType: "Term",
+ glossaryName: "Bank",
+ statusFilter: "DRAFT",
+ searchText: "capital"
+ },
+ 1,
+ 25,
+ { Bank: "guid-1" }
+ );
+ expect(request).toEqual({
+ limit: 25,
+ offset: 25,
+ sortBy: "glossaryName",
+ sortOrder: "DESCENDING",
+ excludeDeleted: true,
+ glossaryType: "TERM",
+ status: "DRAFT",
+ searchQuery: "capital",
+ glossary: { name: "Bank", guid: "guid-1" }
+ });
+ });
+
+ it("buildGlossarySearchExportRequest zeroes pagination for full export", () => {
+ const request = buildGlossarySearchExportRequest(
+ {
+ ...createDefaultGlossaryBrowseFilters(),
+ recordType: "Category",
+ glossaryName: "Bank",
+ statusFilter: "ACTIVE",
+ searchText: "branch"
+ },
+ { Bank: "guid-1" }
+ );
+
+ expect(request).toEqual({
+ limit: 0,
+ offset: 0,
+ sortBy: "glossaryName",
+ sortOrder: "DESCENDING",
+ excludeDeleted: true,
+ glossaryType: "CATEGORY",
+ status: "ACTIVE",
+ searchQuery: "branch",
+ glossary: { name: "Bank", guid: "guid-1" },
+ format: "CSV"
+ });
+ });
+
+ it("formatCustomAttributesForDisplay renders key-value string", () => {
+ expect(
+ formatCustomAttributesForDisplay({
+ department: "Retail",
+ status: "Active"
+ })
+ ).toBe("department: Retail, status: Active");
+ });
+
+ it("formatCustomAttributesForDisplay returns empty string for nullish values", () => {
+ expect(formatCustomAttributesForDisplay(null)).toBe("");
+ expect(formatCustomAttributesForDisplay(undefined)).toBe("");
+ expect(formatCustomAttributesForDisplay({})).toBe("");
+ });
+
+ it("formatCustomAttributesForTooltip renders JSON details", () => {
+ expect(
+ formatCustomAttributesForTooltip({
+ department: "Retail",
+ status: "Active"
+ })
+ ).toContain('"department": "Retail"');
+ });
+
+ it("exposes glossary status filter dropdown options", () => {
+ expect(GLOSSARY_STATUS_FILTER_OPTIONS).toEqual([
+ { label: "All", value: "" },
+ { label: "Draft", value: "DRAFT" },
+ { label: "Active", value: "ACTIVE" },
+ { label: "Deprecated", value: "DEPRECATED" }
+ ]);
+ });
+
+ it("mapGlossarySearchResultToTableRows maps terms and categories with guids", () => {
+ const response: GlossarySearchResponse = {
+ approximateCount: 2,
+ glossary: [
+ {
+ name: "testBankingGlossary",
+ guid: "glossary-guid-1",
+ terms: [
+ {
+ name: "CapitalTerm075",
+ guid: "term-guid-1",
+ qualifiedName: "CapitalTerm075@testBankingGlossary",
+ status: "ACTIVE",
+ classifications: [{ typeName: "class3" }],
+ customAttributes: { department: "Retail", status: "Active" }
+ }
+ ],
+ categories: [
+ {
+ name: "BranchCategory",
+ guid: "category-guid-1",
+ status: "ACTIVE"
+ }
+ ]
+ }
+ ]
+ };
+ const rows = mapGlossarySearchResultToTableRows(response);
+ expect(rows).toHaveLength(2);
+ expect(rows[0]).toMatchObject({
+ recordType: "Term",
+ name: "CapitalTerm075",
+ guid: "term-guid-1",
+ glossaryGuid: "glossary-guid-1",
+ classifications: [{ typeName: "class3" }],
+ customAttributes: { department: "Retail", status: "Active" }
+ });
+ expect(rows[1]).toMatchObject({
+ recordType: "Category",
+ name: "BranchCategory",
+ guid: "category-guid-1",
+ glossaryGuid: "glossary-guid-1",
+ customAttributes: {}
+ });
+ });
+
+ it("mapGlossarySearchResultToTableRows returns empty array for invalid responses", () => {
+ expect(mapGlossarySearchResultToTableRows(null)).toEqual([]);
+ expect(mapGlossarySearchResultToTableRows(undefined)).toEqual([]);
+ expect(
+ mapGlossarySearchResultToTableRows({
+ glossary: "not-array" as unknown as GlossarySearchResponse["glossary"]
+ })
+ ).toEqual([]);
+ });
+
+ it("unwrapGlossarySearchResponse reads axios data wrapper", () => {
+ const body: GlossarySearchResponse = {
+ approximateCount: 1,
+ glossary: [{ name: "G1", guid: "guid-1", terms: [{ name: "T1" }] }]
+ };
+ expect(unwrapGlossarySearchResponse({ data: body })).toEqual(body);
+ expect(unwrapGlossarySearchResponse(body)).toEqual(body);
+ });
+
+ it("fetchGlossarySearchPage maps API response to rows and total count", async () => {
+ mockSearchGlossary.mockResolvedValue({
+ data: {
+ approximateCount: 1,
+ glossary: [
+ {
+ name: "G1",
+ guid: "g-1",
+ terms: [{ name: "Term1", guid: "t-1" }]
+ }
+ ]
+ }
+ });
+
+ const result = await fetchGlossarySearchPage({
+ limit: 25,
+ offset: 0,
+ sortBy: "glossaryName",
+ sortOrder: "DESCENDING"
+ });
+
+ expect(mockSearchGlossary).toHaveBeenCalled();
+ expect(result.rows).toHaveLength(1);
+ expect(result.totalCount).toBe(1);
+ });
+
+ it("fetchGlossarySearchPage rejects when searchGlossary fails", async () => {
+ const error = new Error("search failed");
+ mockSearchGlossary.mockRejectedValue(error);
+
+ await expect(
+ fetchGlossarySearchPage({
+ limit: 25,
+ offset: 0,
+ sortBy: "glossaryName",
+ sortOrder: "DESCENDING"
+ })
+ ).rejects.toThrow("search failed");
+ });
+
+ it("requestGlossaryExportDownload enqueues export via create_file API", async () => {
+ mockCreateGlossaryExportFile.mockResolvedValue(undefined);
+
+ await requestGlossaryExportDownload(
+ createDefaultGlossaryBrowseFilters(),
+ { Bank: "guid-1" }
+ );
+
+ expect(mockCreateGlossaryExportFile).toHaveBeenCalledWith({
+ limit: 0,
+ offset: 0,
+ sortBy: "glossaryName",
+ sortOrder: "DESCENDING",
+ excludeDeleted: true,
+ format: "CSV"
+ });
+ });
+
+ it("requestGlossaryExportDownload sends selected XLSX format", async () => {
+ mockCreateGlossaryExportFile.mockResolvedValue(undefined);
+
+ await requestGlossaryExportDownload(
+ createDefaultGlossaryBrowseFilters(),
+ { Bank: "guid-1" },
+ "XLSX"
+ );
+
+ expect(mockCreateGlossaryExportFile).toHaveBeenCalledWith(
+ expect.objectContaining({ format: "XLSX" })
+ );
+ });
+
+ it("requestGlossaryExportDownload rejects when createGlossaryExportFile fails", async () => {
+ const error = new Error("export failed");
+ mockCreateGlossaryExportFile.mockRejectedValue(error);
+
+ await expect(
+ requestGlossaryExportDownload(createDefaultGlossaryBrowseFilters())
+ ).rejects.toThrow("export failed");
+ });
+});
diff --git a/dashboard/src/utils/__tests__/glossaryStatus.test.ts b/dashboard/src/utils/__tests__/glossaryStatus.test.ts
new file mode 100644
index 000000000..a7442c7a4
--- /dev/null
+++ b/dashboard/src/utils/__tests__/glossaryStatus.test.ts
@@ -0,0 +1,41 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import {
+ getGlossaryStatusMeta,
+ GLOSSARY_STATUS_META,
+ normalizeGlossaryStatus
+} from "@utils/glossaryStatus";
+
+describe("glossaryStatus", () => {
+ it("normalizes glossary status values", () => {
+ expect(normalizeGlossaryStatus("active")).toBe("ACTIVE");
+ expect(normalizeGlossaryStatus("DRAFT")).toBe("DRAFT");
+ expect(normalizeGlossaryStatus("Deprecated")).toBe("DEPRECATED");
+ expect(normalizeGlossaryStatus("")).toBe("UNKNOWN");
+ expect(normalizeGlossaryStatus(undefined)).toBe("UNKNOWN");
+ });
+
+ it("returns display metadata for each status", () => {
+ expect(getGlossaryStatusMeta("ACTIVE")).toEqual(
+ GLOSSARY_STATUS_META.ACTIVE
+ );
+ expect(getGlossaryStatusMeta("DRAFT").muiColor).toBe("warning");
+ expect(getGlossaryStatusMeta("DEPRECATED").muiColor).toBe("error");
+ expect(getGlossaryStatusMeta("invalid").muiColor).toBe("default");
+ });
+});
diff --git a/dashboard/src/utils/downloadRecords.ts b/dashboard/src/utils/downloadRecords.ts
new file mode 100644
index 000000000..4ff267987
--- /dev/null
+++ b/dashboard/src/utils/downloadRecords.ts
@@ -0,0 +1,145 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+export type DownloadSource = "search" | "glossary";
+
+export type DownloadRecord = {
+ fileName: string;
+ source: DownloadSource;
+ createdTime?: number | string;
+ status?: string;
+};
+
+type RawDownloadRecord = {
+ fileName?: string;
+ createdTime?: number | string;
+ status?: string;
+};
+
+const FILE_NAME_TIMESTAMP_PATTERN =
+ /(\d{4}-\d{2}-\d{2})_(\d{2})-(\d{2})-(\d{2}(?:\.\d{3})?)/;
+
+export const parseCreatedTime = (
+ createdTime?: number | string
+): number | null => {
+ if (createdTime === undefined || createdTime === null || createdTime === "") {
+ return null;
+ }
+
+ if (typeof createdTime === "number" && Number.isFinite(createdTime)) {
+ return createdTime;
+ }
+
+ const parsed = Date.parse(String(createdTime));
+ return Number.isNaN(parsed) ? null : parsed;
+};
+
+export const parseTimestampFromFileName = (fileName: string): number | null => {
+ const match = fileName.match(FILE_NAME_TIMESTAMP_PATTERN);
+ if (!match) {
+ return null;
+ }
+
+ const normalized = `${match[1]}T${match[2]}:${match[3]}:${match[4]}`;
+ const parsed = Date.parse(normalized);
+ return Number.isNaN(parsed) ? null : parsed;
+};
+
+export const resolveDownloadRecordTime = (record: {
+ fileName: string;
+ createdTime?: number | string;
+}): number => {
+ const fromApi = parseCreatedTime(record.createdTime);
+ if (fromApi !== null) {
+ return fromApi;
+ }
+
+ const fromFileName = parseTimestampFromFileName(record.fileName);
+ return fromFileName ?? 0;
+};
+
+export const sortDownloadRecordsByLatest = <T extends DownloadRecord>(
+ records: T[]
+): T[] => {
+ return [...records].sort(
+ (left, right) =>
+ resolveDownloadRecordTime(right) - resolveDownloadRecordTime(left)
+ );
+};
+
+export const dedupeDownloadRecordsByFileName = (
+ records: DownloadRecord[]
+): DownloadRecord[] => {
+ const byFileName = new Map<string, DownloadRecord>();
+
+ records.forEach((record) => {
+ const existing = byFileName.get(record.fileName);
+ if (
+ !existing ||
+ resolveDownloadRecordTime(record) > resolveDownloadRecordTime(existing)
+ ) {
+ byFileName.set(record.fileName, record);
+ }
+ });
+
+ return sortDownloadRecordsByLatest(Array.from(byFileName.values()));
+};
+
+export const filterDownloadRecordsForToggle = (
+ records: DownloadRecord[],
+ showAllFiles: boolean
+): DownloadRecord[] => {
+ if (showAllFiles) {
+ return records;
+ }
+
+ return records.filter((record) => record.status !== "PENDING");
+};
+
+export const isPendingDownloadRecord = (record: DownloadRecord): boolean =>
+ record.status === "PENDING";
+
+export const extractDownloadRecords = (
+ data: Record<string, unknown> | undefined,
+ source: DownloadSource
+): DownloadRecord[] => {
+ const records =
+ source === "glossary"
+ ? ((data?.glossaryDownloadRecords ??
+ data?.searchDownloadRecords ??
+ []) as RawDownloadRecord[])
+ : ((data?.searchDownloadRecords ?? []) as RawDownloadRecord[]);
+
+ return records
+ .filter((record) => Boolean(record?.fileName))
+ .map((record) => ({
+ fileName: record.fileName as string,
+ source,
+ createdTime: record.createdTime,
+ status: record.status
+ }));
+};
+
+export const mergeDownloadRecords = (
+ searchRecords: DownloadRecord[],
+ glossaryRecords: DownloadRecord[]
+): DownloadRecord[] => {
+ return dedupeDownloadRecordsByFileName([
+ ...searchRecords,
+ ...glossaryRecords
+ ]);
+};
diff --git a/dashboard/src/utils/glossaryExport.ts b/dashboard/src/utils/glossaryExport.ts
new file mode 100644
index 000000000..d2a238fc7
--- /dev/null
+++ b/dashboard/src/utils/glossaryExport.ts
@@ -0,0 +1,308 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import {
+ createGlossaryExportFile,
+ searchGlossary
+} from "@api/apiMethods/glossaryApiMethod";
+
+export const GLOSSARY_SEARCH_DEFAULTS = {
+ limit: 25,
+ offset: 0,
+ sortBy: "glossaryName",
+ sortOrder: "DESCENDING"
+} as const;
+
+export type GlossarySearchSortOrder = "ASCENDING" | "DESCENDING";
+
+export type GlossarySearchGlossaryType = "ALL" | "TERM" | "CATEGORY";
+
+export interface GlossarySearchRequest {
+ limit: number;
+ offset: number;
+ sortBy: string;
+ sortOrder: GlossarySearchSortOrder;
+ glossaryType?: GlossarySearchGlossaryType;
+ status?: string;
+ searchQuery?: string;
+ glossary?: { name?: string; guid?: string };
+ excludeDeleted?: boolean;
+}
+
+export interface GlossarySearchClassification {
+ typeName?: string;
+ entityGuid?: string;
+ attributes?: Record<string, unknown>;
+}
+
+export interface GlossarySearchTermDetail {
+ name?: string;
+ qualifiedName?: string;
+ guid?: string;
+ shortDescription?: string;
+ longDescription?: string;
+ status?: string;
+ classifications?: GlossarySearchClassification[];
+ customAttributes?: Record<string, unknown>;
+}
+
+export interface GlossarySearchCategoryDetail {
+ name?: string;
+ qualifiedName?: string;
+ guid?: string;
+ shortDescription?: string;
+ longDescription?: string;
+ status?: string;
+ classifications?: GlossarySearchClassification[];
+ customAttributes?: Record<string, unknown>;
+}
+
+export interface GlossarySearchGlossaryDetail {
+ name?: string;
+ guid?: string;
+ terms?: GlossarySearchTermDetail[];
+ categories?: GlossarySearchCategoryDetail[];
+}
+
+export interface GlossarySearchResponse {
+ glossary?: GlossarySearchGlossaryDetail[];
+ approximateCount?: number;
+}
+
+export interface GlossaryBrowseFilters {
+ recordType: "all" | "Term" | "Category";
+ glossaryName: string;
+ statusFilter: string;
+ searchText: string;
+}
+
+export type GlossaryExportFormat = "CSV" | "XLSX";
+
+export const GLOSSARY_EXPORT_FORMAT_OPTIONS = [
+ { label: "CSV", value: "CSV" as const },
+ { label: "XLSX", value: "XLSX" as const }
+] as const;
+
+export const GLOSSARY_STATUS_FILTER_OPTIONS = [
+ { label: "All", value: "" },
+ { label: "Draft", value: "DRAFT" },
+ { label: "Active", value: "ACTIVE" },
+ { label: "Deprecated", value: "DEPRECATED" }
+] as const;
+
+export type GlossaryTableRow = {
+ id: string;
+ recordType: "Term" | "Category";
+ name: string;
+ guid: string;
+ qualifiedName: string;
+ glossaryName: string;
+ glossaryGuid: string;
+ shortDescription: string;
+ longDescription: string;
+ status: string;
+ classifications: GlossarySearchClassification[];
+ customAttributes: Record<string, unknown>;
+};
+
+export const createDefaultGlossaryBrowseFilters = (): GlossaryBrowseFilters => ({
+ recordType: "all",
+ glossaryName: "",
+ statusFilter: "",
+ searchText: ""
+});
+
+export const mapRecordTypeToGlossaryType = (
+ recordType: GlossaryBrowseFilters["recordType"]
+): GlossarySearchGlossaryType | undefined => {
+ if (recordType === "Term") {
+ return "TERM";
+ }
+ if (recordType === "Category") {
+ return "CATEGORY";
+ }
+ return undefined;
+};
+
+export const buildGlossarySearchRequest = (
+ filters: GlossaryBrowseFilters,
+ page: number,
+ rowsPerPage: number,
+ glossaryGuidByName: Record<string, string> = {}
+): GlossarySearchRequest => {
+ const request: GlossarySearchRequest = {
+ limit: rowsPerPage,
+ offset: page * rowsPerPage,
+ sortBy: GLOSSARY_SEARCH_DEFAULTS.sortBy,
+ sortOrder: GLOSSARY_SEARCH_DEFAULTS.sortOrder,
+ excludeDeleted: true
+ };
+
+ const glossaryType = mapRecordTypeToGlossaryType(filters.recordType);
+ if (glossaryType) {
+ request.glossaryType = glossaryType;
+ }
+
+ const status = filters.statusFilter.trim();
+ if (status) {
+ request.status = status;
+ }
+
+ const searchQuery = filters.searchText.trim();
+ if (searchQuery) {
+ request.searchQuery = searchQuery;
+ }
+
+ const glossaryName = filters.glossaryName.trim();
+ if (glossaryName) {
+ request.glossary = {
+ name: glossaryName,
+ guid: glossaryGuidByName[glossaryName]
+ };
+ }
+
+ return request;
+};
+
+export const buildGlossarySearchExportRequest = (
+ filters: GlossaryBrowseFilters,
+ glossaryGuidByName: Record<string, string> = {},
+ format: GlossaryExportFormat = "CSV"
+): GlossarySearchRequest & { format: GlossaryExportFormat } => ({
+ ...buildGlossarySearchRequest(filters, 0, 0, glossaryGuidByName),
+ limit: 0,
+ offset: 0,
+ format
+});
+
+const empty = (v: unknown): string =>
+ v === null || v === undefined ? "" : String(v);
+
+export const formatCustomAttributesForDisplay = (
+ attrs: Record<string, unknown> | null | undefined
+): string => {
+ if (!attrs || typeof attrs !== "object" || Object.keys(attrs).length === 0) {
+ return "";
+ }
+ return Object.entries(attrs)
+ .map(([key, value]) => `${key}: ${empty(value)}`)
+ .join(", ");
+};
+
+export const formatCustomAttributesForTooltip = (
+ attrs: Record<string, unknown> | null | undefined
+): string => {
+ if (!attrs || typeof attrs !== "object" || Object.keys(attrs).length === 0) {
+ return "";
+ }
+ try {
+ return JSON.stringify(attrs, null, 2);
+ } catch {
+ return formatCustomAttributesForDisplay(attrs);
+ }
+};
+
+const mapDetailToTableRow = (
+ detail: GlossarySearchTermDetail | GlossarySearchCategoryDetail,
+ recordType: GlossaryTableRow["recordType"],
+ glossaryName: string,
+ glossaryGuid: string
+): GlossaryTableRow => ({
+ id: `${recordType.toLowerCase()}-${empty(detail.guid) || empty(detail.name)}`,
+ recordType,
+ name: empty(detail.name),
+ guid: empty(detail.guid),
+ qualifiedName: empty(detail.qualifiedName),
+ glossaryName,
+ glossaryGuid,
+ shortDescription: empty(detail.shortDescription),
+ longDescription: empty(detail.longDescription),
+ status: empty(detail.status),
+ classifications: detail.classifications ?? [],
+ customAttributes: detail.customAttributes ?? {}
+});
+
+export const mapGlossarySearchResultToTableRows = (
+ response: GlossarySearchResponse | null | undefined
+): GlossaryTableRow[] => {
+ const glossaries = response?.glossary;
+ if (!Array.isArray(glossaries)) {
+ return [];
+ }
+
+ const rows: GlossaryTableRow[] = [];
+ glossaries.forEach((glossary) => {
+ const glossaryName = empty(glossary?.name);
+ const glossaryGuid = empty(glossary?.guid);
+ (glossary?.terms ?? []).forEach((term) => {
+ rows.push(mapDetailToTableRow(term, "Term", glossaryName, glossaryGuid));
+ });
+ (glossary?.categories ?? []).forEach((category) => {
+ rows.push(
+ mapDetailToTableRow(category, "Category", glossaryName, glossaryGuid)
+ );
+ });
+ });
+
+ return rows;
+};
+
+/** Axios returns { data }; unwrap to GlossarySearchResponse body. */
+export const unwrapGlossarySearchResponse = (
+ response: unknown
+): GlossarySearchResponse => {
+ if (
+ response &&
+ typeof response === "object" &&
+ "data" in response &&
+ (response as { data: unknown }).data &&
+ typeof (response as { data: unknown }).data === "object"
+ ) {
+ return (response as { data: GlossarySearchResponse }).data;
+ }
+ return (response as GlossarySearchResponse) ?? {};
+};
+
+export async function fetchGlossarySearchPage(
+ request: GlossarySearchRequest
+): Promise<{
+ rows: GlossaryTableRow[];
+ totalCount: number;
+}> {
+ const raw = await searchGlossary(request);
+ const response = unwrapGlossarySearchResponse(raw);
+ const rows = mapGlossarySearchResultToTableRows(response);
+ const totalCount =
+ typeof response?.approximateCount === "number"
+ ? response.approximateCount
+ : rows.length;
+
+ return { rows, totalCount };
+}
+
+export async function requestGlossaryExportDownload(
+ filters: GlossaryBrowseFilters,
+ glossaryGuidByName: Record<string, string> = {},
+ format: GlossaryExportFormat = "CSV"
+): Promise<void> {
+ const request = buildGlossarySearchExportRequest(
+ filters,
+ glossaryGuidByName,
+ format
+ );
+ await createGlossaryExportFile(request);
+}
diff --git a/dashboard/src/utils/glossaryStatus.ts b/dashboard/src/utils/glossaryStatus.ts
new file mode 100644
index 000000000..c51bb778f
--- /dev/null
+++ b/dashboard/src/utils/glossaryStatus.ts
@@ -0,0 +1,76 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+export type GlossaryStatusKey = "ACTIVE" | "DRAFT" | "DEPRECATED" | "UNKNOWN";
+
+export type GlossaryStatusMeta = {
+ label: string;
+ shortLabel: string;
+ muiColor: "success" | "warning" | "error" | "default";
+ ariaLabel: string;
+};
+
+export const GLOSSARY_STATUS_META: Record<GlossaryStatusKey, GlossaryStatusMeta> = {
+ ACTIVE: {
+ label: "Active",
+ shortLabel: "Active",
+ muiColor: "success",
+ ariaLabel: "Active status"
+ },
+ DRAFT: {
+ label: "Draft",
+ shortLabel: "Draft",
+ muiColor: "warning",
+ ariaLabel: "Draft status"
+ },
+ DEPRECATED: {
+ label: "Deprecated",
+ shortLabel: "Depr.",
+ muiColor: "error",
+ ariaLabel: "Deprecated status"
+ },
+ UNKNOWN: {
+ label: "Unknown",
+ shortLabel: "—",
+ muiColor: "default",
+ ariaLabel: "Unknown status"
+ }
+};
+
+export const normalizeGlossaryStatus = (status?: string): GlossaryStatusKey => {
+ if (!status) {
+ return "UNKNOWN";
+ }
+
+ const normalized = status.trim().toUpperCase();
+ if (normalized === "ACTIVE") {
+ return "ACTIVE";
+ }
+ if (normalized === "DRAFT") {
+ return "DRAFT";
+ }
+ if (normalized === "DEPRECATED") {
+ return "DEPRECATED";
+ }
+
+ return "UNKNOWN";
+};
+
+export const getGlossaryStatusMeta = (status?: string): GlossaryStatusMeta => {
+ const key = normalizeGlossaryStatus(status);
+ return GLOSSARY_STATUS_META[key];
+};
diff --git a/dashboard/src/views/Glossary/GlossaryStatusBadge.tsx b/dashboard/src/views/Glossary/GlossaryStatusBadge.tsx
new file mode 100644
index 000000000..1b40895c4
--- /dev/null
+++ b/dashboard/src/views/Glossary/GlossaryStatusBadge.tsx
@@ -0,0 +1,52 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { LightTooltip } from "@components/muiComponents";
+import { Chip } from "@mui/material";
+import { getGlossaryStatusMeta } from "@utils/glossaryStatus";
+
+type GlossaryStatusBadgeProps = {
+ status?: string;
+};
+
+const GlossaryStatusBadge = ({ status }: GlossaryStatusBadgeProps) => {
+ const meta = getGlossaryStatusMeta(status);
+
+ return (
+ <LightTooltip title={`Status: ${meta.label}`}>
+ <Chip
+ size="small"
+ variant="outlined"
+ color={meta.muiColor}
+ label={meta.shortLabel}
+ aria-label={meta.ariaLabel}
+ data-cy="glossaryStatusBadge"
+ sx={{
+ maxWidth: "100%",
+ height: 22,
+ "& .MuiChip-label": {
+ px: 0.75,
+ fontSize: "0.7rem",
+ lineHeight: 1.2
+ }
+ }}
+ />
+ </LightTooltip>
+ );
+};
+
+export default GlossaryStatusBadge;
diff --git a/dashboard/src/views/Glossary/GlossaryTermsListPage.tsx b/dashboard/src/views/Glossary/GlossaryTermsListPage.tsx
new file mode 100644
index 000000000..9a88892a1
--- /dev/null
+++ b/dashboard/src/views/Glossary/GlossaryTermsListPage.tsx
@@ -0,0 +1,414 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { TableLayout } from "@components/Table/TableLayout";
+import { CustomButton, LightTooltip } from "@components/muiComponents";
+import { useAppDispatch, useAppSelector } from "@hooks/reducerHook";
+import { fetchGlossaryData } from "@redux/slice/glossarySlice";
+import {
+ buildGlossarySearchRequest,
+ createDefaultGlossaryBrowseFilters,
+ fetchGlossarySearchPage,
+ GLOSSARY_EXPORT_FORMAT_OPTIONS,
+ GLOSSARY_STATUS_FILTER_OPTIONS,
+ requestGlossaryExportDownload,
+ type GlossaryBrowseFilters,
+ type GlossaryExportFormat,
+ type GlossaryTableRow
+} from "@utils/glossaryExport";
+import { Item } from "@utils/Muiutils";
+import { serverError } from "@utils/Utils";
+import Autocomplete from "@mui/material/Autocomplete";
+import DownloadOutlinedIcon from "@mui/icons-material/DownloadOutlined";
+import ArrowDropDownIcon from "@mui/icons-material/ArrowDropDown";
+import RefreshIcon from "@mui/icons-material/Refresh";
+import TextSnippetOutlinedIcon from "@mui/icons-material/TextSnippetOutlined";
+import {
+ CircularProgress,
+ FormControl,
+ Grid,
+ InputLabel,
+ Menu,
+ MenuItem,
+ Select,
+ type SelectChangeEvent,
+ Stack,
+ TextField,
+ Typography
+} from "@mui/material";
+import moment from "moment-timezone";
+import {
+ ChangeEvent,
+ MouseEvent,
+ useCallback,
+ useEffect,
+ useMemo,
+ useRef,
+ useState
+} from "react";
+import { toast } from "react-toastify";
+import { createGlossaryTermsListColumns } from "./glossaryTermsListColumns";
+
+const FILTER_DEBOUNCE_MS = 400;
+
+const GlossaryTermsListPage = () => {
+ const toastRef = useRef<string | number | undefined>(undefined);
+ const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);
+ const filtersRef = useRef<GlossaryBrowseFilters>(
+ createDefaultGlossaryBrowseFilters()
+ );
+ const glossaryGuidByNameRef = useRef<Record<string, string>>({});
+ const dispatch = useAppDispatch();
+ const { glossaryData, loading: glossaryLoading } = useAppSelector(
+ (state) => state.glossary
+ );
+
+ const [loading, setLoading] = useState(true);
+ const [downloading, setDownloading] = useState(false);
+ const [tableRows, setTableRows] = useState<GlossaryTableRow[]>([]);
+ const [totalCount, setTotalCount] = useState(0);
+ const [pageCount, setPageCount] = useState(0);
+ const [filters, setFilters] = useState<GlossaryBrowseFilters>(
+ createDefaultGlossaryBrowseFilters()
+ );
+ const [downloadMenuAnchor, setDownloadMenuAnchor] =
+ useState<null | HTMLElement>(null);
+ const [tableKey, setTableKey] = useState(0);
+ const [updateTable, setUpdateTable] = useState(moment.now());
+
+ filtersRef.current = filters;
+
+ useEffect(() => {
+ if (!glossaryData && !glossaryLoading) {
+ void dispatch(fetchGlossaryData());
+ }
+ }, [dispatch, glossaryData, glossaryLoading]);
+
+ const glossaryGuidByName = useMemo(() => {
+ const map: Record<string, string> = {};
+ const glossaries = Array.isArray(glossaryData) ? glossaryData : [];
+ glossaries.forEach((g: { name?: string; guid?: string }) => {
+ if (g?.name && g?.guid) {
+ map[g.name] = g.guid;
+ }
+ });
+ return map;
+ }, [glossaryData]);
+
+ glossaryGuidByNameRef.current = glossaryGuidByName;
+
+ const glossaryOptions = useMemo(() => {
+ const glossaries = Array.isArray(glossaryData) ? glossaryData : [];
+ return glossaries
+ .map((g: { name?: string }) => g?.name ?? "")
+ .filter((name) => name !== "")
+ .sort((a, b) => a.localeCompare(b));
+ }, [glossaryData]);
+
+ const scheduleFilterRefresh = useCallback(() => {
+ if (debounceRef.current) {
+ clearTimeout(debounceRef.current);
+ }
+ debounceRef.current = setTimeout(() => {
+ setTableKey((k) => k + 1);
+ }, FILTER_DEBOUNCE_MS);
+ }, []);
+
+ const fetchGlossaryTableData = useCallback(
+ async ({
+ pagination
+ }: {
+ pagination: { pageIndex: number; pageSize: number };
+ }) => {
+ setLoading(true);
+ try {
+ const request = buildGlossarySearchRequest(
+ filtersRef.current,
+ pagination.pageIndex,
+ pagination.pageSize,
+ glossaryGuidByNameRef.current
+ );
+ const { rows, totalCount: count } = await fetchGlossarySearchPage(
+ request
+ );
+ setTableRows(rows);
+ setTotalCount(count);
+ setPageCount(
+ Math.ceil(count / (pagination.pageSize || 25)) || 0
+ );
+ } catch (e) {
+ serverError(e, toastRef);
+ setTableRows([]);
+ setTotalCount(0);
+ setPageCount(0);
+ } finally {
+ setLoading(false);
+ }
+ },
+ [updateTable]
+ );
+
+ const handleRefresh = () => {
+ setUpdateTable(moment.now());
+ };
+
+ const handleDownloadMenuOpen = (event: MouseEvent<HTMLButtonElement>) => {
+ setDownloadMenuAnchor(event.currentTarget);
+ };
+
+ const handleDownloadMenuClose = () => {
+ setDownloadMenuAnchor(null);
+ };
+
+ const handleDownload = async (format: GlossaryExportFormat) => {
+ handleDownloadMenuClose();
+ try {
+ setDownloading(true);
+ await requestGlossaryExportDownload(
+ filtersRef.current,
+ glossaryGuidByNameRef.current,
+ format
+ );
+ toast.dismiss(toastRef.current);
+ toastRef.current = toast.success(
+ "The current glossary export has been enqueued for download. You can access the file by clicking the download icon at the top of the page."
+ );
+ } catch (e) {
+ serverError(e, toastRef);
+ } finally {
+ setDownloading(false);
+ }
+ };
+
+ const handleSearchTextChange = (
+ e: ChangeEvent<HTMLInputElement | HTMLTextAreaElement>
+ ) => {
+ const v = e.target.value;
+ setFilters((f) => ({ ...f, searchText: v }));
+ scheduleFilterRefresh();
+ };
+
+ const handleRecordTypeChange = (e: SelectChangeEvent<string>) => {
+ setFilters((f) => ({
+ ...f,
+ recordType: e.target.value as GlossaryBrowseFilters["recordType"]
+ }));
+ setTableKey((k) => k + 1);
+ };
+
+ const handleStatusFilterChange = (e: SelectChangeEvent<string>) => {
+ setFilters((f) => ({ ...f, statusFilter: e.target.value }));
+ setTableKey((k) => k + 1);
+ };
+
+ const downloadDisabled = loading || downloading || totalCount === 0;
+
+ const columns = useMemo(
+ () => createGlossaryTermsListColumns(setUpdateTable),
+ [setUpdateTable]
+ );
+
+ return (
+ <Item
+ variant="outlined"
+ className="glossary-terms-list-page"
+ sx={{ background: "white", width: "100%", textAlign: "left" }}
+ >
+ <Stack spacing={0} sx={{ height: "100%", overflow: "hidden" }}>
+ <Stack
+ direction="row"
+ alignItems="center"
+ justifyContent="space-between"
+ flexWrap="wrap"
+ gap={1}
+ className="glossary-terms-list-header"
+ >
+ <Stack direction="row" alignItems="center" gap={1}>
+ <TextSnippetOutlinedIcon color="primary" />
+ <Typography
+ variant="h6"
+ component="h1"
+ className="glossary-terms-list-title"
+ >
+ Glossary terms & categories
+ </Typography>
+ </Stack>
+ <Stack direction="row" gap={1} flexWrap="wrap" alignItems="center">
+ <LightTooltip title="Reload from server">
+ <span>
+ <CustomButton
+ variant="outlined"
+ size="small"
+ disabled={loading}
+ onClick={handleRefresh}
+ startIcon={<RefreshIcon />}
+ data-cy="glossaryTermsListRefresh"
+ >
+ Refresh
+ </CustomButton>
+ </span>
+ </LightTooltip>
+ <CustomButton
+ variant="outlined"
+ size="small"
+ onClick={handleDownloadMenuOpen}
+ disabled={downloadDisabled}
+ startIcon={
+ downloading ? (
+ <CircularProgress size={16} color="inherit" />
+ ) : (
+ <DownloadOutlinedIcon />
+ )
+ }
+ endIcon={downloading ? undefined : <ArrowDropDownIcon />}
+ aria-haspopup="true"
+ aria-expanded={Boolean(downloadMenuAnchor)}
+ aria-controls={
+ downloadMenuAnchor ? "glossary-download-menu" : undefined
+ }
+ data-cy="glossaryTermsListDownload"
+ >
+ Download
+ </CustomButton>
+ <Menu
+ id="glossary-download-menu"
+ anchorEl={downloadMenuAnchor}
+ open={Boolean(downloadMenuAnchor)}
+ onClose={handleDownloadMenuClose}
+ anchorOrigin={{ vertical: "bottom", horizontal: "right" }}
+ transformOrigin={{ vertical: "top", horizontal: "right" }}
+ >
+ {GLOSSARY_EXPORT_FORMAT_OPTIONS.map((option) => (
+ <MenuItem
+ key={option.value}
+ onClick={() => void handleDownload(option.value)}
+ data-cy={`glossaryTermsListDownload${option.value}`}
+ >
+ {option.label}
+ </MenuItem>
+ ))}
+ </Menu>
+ </Stack>
+ </Stack>
+
+ <div className="glossary-terms-filters">
+ <Typography
+ variant="subtitle2"
+ className="glossary-terms-filters-label"
+ >
+ Filters
+ </Typography>
+ <Grid container spacing={2}>
+ <Grid item xs={12} sm={6} md={3}>
+ <Autocomplete
+ size="small"
+ fullWidth
+ options={glossaryOptions}
+ value={filters.glossaryName || null}
+ onChange={(_e, v) => {
+ setFilters((f) => ({ ...f, glossaryName: v ?? "" }));
+ setTableKey((k) => k + 1);
+ }}
+ renderInput={(params) => (
+ <TextField
+ {...params}
+ label="Glossary"
+ placeholder="All glossaries"
+ />
+ )}
+ data-cy="glossaryTermsFilterGlossary"
+ />
+ </Grid>
+ <Grid item xs={12} sm={6} md={3}>
+ <FormControl size="small" fullWidth>
+ <InputLabel id="glossary-record-type-label">
+ Record type
+ </InputLabel>
+ <Select
+ labelId="glossary-record-type-label"
+ label="Record type"
+ value={filters.recordType}
+ onChange={handleRecordTypeChange}
+ data-cy="glossaryTermsFilterRecordType"
+ >
+ <MenuItem value="all">All</MenuItem>
+ <MenuItem value="Term">Terms only</MenuItem>
+ <MenuItem value="Category">Categories only</MenuItem>
+ </Select>
+ </FormControl>
+ </Grid>
+ <Grid item xs={12} sm={6} md={3}>
+ <FormControl size="small" fullWidth>
+ <InputLabel id="glossary-status-filter-label">Status</InputLabel>
+ <Select
+ labelId="glossary-status-filter-label"
+ label="Status"
+ value={filters.statusFilter}
+ onChange={handleStatusFilterChange}
+ data-cy="glossaryTermsFilterStatus"
+ >
+ {GLOSSARY_STATUS_FILTER_OPTIONS.map((option) => (
+ <MenuItem key={option.label} value={option.value}>
+ {option.label}
+ </MenuItem>
+ ))}
+ </Select>
+ </FormControl>
+ </Grid>
+ <Grid item xs={12} sm={6} md={3}>
+ <TextField
+ size="small"
+ fullWidth
+ label="Search all columns"
+ value={filters.searchText}
+ onChange={handleSearchTextChange}
+ data-cy="glossaryTermsFilterSearch"
+ />
+ </Grid>
+ </Grid>
+ </div>
+
+ <div className="glossary-terms-table search-result-table-wrapper">
+ <TableLayout
+ key={`glossary-terms-table-${tableKey}`}
+ fetchData={fetchGlossaryTableData}
+ data={tableRows}
+ columns={columns}
+ emptyText="No rows match the current filters."
+ isFetching={loading}
+ pageCount={pageCount}
+ totalCount={totalCount}
+ isClientSidePagination={false}
+ clientSideSorting={true}
+ showPagination={true}
+ showGoToPage={true}
+ showRowSelection={false}
+ columnVisibility={false}
+ columnSort={true}
+ tableFilters={false}
+ queryBuilder={false}
+ allTableFilters={false}
+ isfilterQuery={false}
+ setUpdateTable={setUpdateTable}
+ />
+ </div>
+ </Stack>
+ </Item>
+ );
+};
+
+export default GlossaryTermsListPage;
diff --git a/dashboard/src/views/Glossary/__tests__/GlossaryStatusBadge.test.tsx b/dashboard/src/views/Glossary/__tests__/GlossaryStatusBadge.test.tsx
new file mode 100644
index 000000000..90af51ea9
--- /dev/null
+++ b/dashboard/src/views/Glossary/__tests__/GlossaryStatusBadge.test.tsx
@@ -0,0 +1,54 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { render, screen } from "@testing-library/react";
+import GlossaryStatusBadge from "../GlossaryStatusBadge";
+
+describe("GlossaryStatusBadge", () => {
+ it("renders active status with success color only", () => {
+ render(<GlossaryStatusBadge status="ACTIVE" />);
+ const badge = screen.getByLabelText("Active status");
+ expect(badge).toBeInTheDocument();
+ expect(badge).toHaveTextContent("Active");
+ expect(badge).toHaveClass("MuiChip-colorSuccess");
+ expect(badge.querySelector(".MuiChip-icon")).not.toBeInTheDocument();
+ });
+
+ it("renders draft status with warning color only", () => {
+ render(<GlossaryStatusBadge status="draft" />);
+ const badge = screen.getByLabelText("Draft status");
+ expect(badge).toHaveClass("MuiChip-colorWarning");
+ expect(badge).toHaveTextContent("Draft");
+ expect(badge.querySelector(".MuiChip-icon")).not.toBeInTheDocument();
+ });
+
+ it("renders deprecated status with error color and short label", () => {
+ render(<GlossaryStatusBadge status="DEPRECATED" />);
+ const badge = screen.getByLabelText("Deprecated status");
+ expect(badge).toHaveClass("MuiChip-colorError");
+ expect(badge).toHaveTextContent("Depr.");
+ expect(badge.querySelector(".MuiChip-icon")).not.toBeInTheDocument();
+ });
+
+ it("renders unknown status with default color and em dash label", () => {
+ render(<GlossaryStatusBadge status="INVALID" />);
+ const badge = screen.getByLabelText("Unknown status");
+ expect(badge).toHaveClass("MuiChip-colorDefault");
+ expect(badge).toHaveTextContent("—");
+ expect(badge.querySelector(".MuiChip-icon")).not.toBeInTheDocument();
+ });
+});
diff --git a/dashboard/src/views/Glossary/__tests__/GlossaryTermsListPage.test.tsx b/dashboard/src/views/Glossary/__tests__/GlossaryTermsListPage.test.tsx
new file mode 100644
index 000000000..ed0a4c267
--- /dev/null
+++ b/dashboard/src/views/Glossary/__tests__/GlossaryTermsListPage.test.tsx
@@ -0,0 +1,321 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import React from "react";
+import { render, screen, fireEvent, waitFor, act } from "@testing-library/react";
+import { Provider } from "react-redux";
+import { configureStore } from "@reduxjs/toolkit";
+import GlossaryTermsListPage from "../GlossaryTermsListPage";
+
+const mockFetchGlossarySearchPage = jest.fn();
+const mockRequestGlossaryExportDownload = jest.fn();
+const mockFetchGlossaryData = jest.fn(() => ({ type: "glossary/fetch" }));
+const mockServerError = jest.fn();
+
+jest.mock("@utils/glossaryExport", () => ({
+ buildGlossarySearchRequest: jest.fn(() => ({})),
+ createDefaultGlossaryBrowseFilters: jest.fn(() => ({
+ recordType: "all",
+ glossaryName: "",
+ statusFilter: "",
+ searchText: ""
+ })),
+ fetchGlossarySearchPage: (...args: unknown[]) =>
+ mockFetchGlossarySearchPage(...args),
+ GLOSSARY_STATUS_FILTER_OPTIONS: [
+ { label: "All", value: "" },
+ { label: "Draft", value: "DRAFT" },
+ { label: "Active", value: "ACTIVE" },
+ { label: "Deprecated", value: "DEPRECATED" }
+ ],
+ GLOSSARY_EXPORT_FORMAT_OPTIONS: [
+ { label: "CSV", value: "CSV" },
+ { label: "XLSX", value: "XLSX" }
+ ],
+ requestGlossaryExportDownload: (...args: unknown[]) =>
+ mockRequestGlossaryExportDownload(...args)
+}));
+
+jest.mock("@redux/slice/glossarySlice", () => ({
+ fetchGlossaryData: (...args: unknown[]) => mockFetchGlossaryData(...args)
+}));
+
+jest.mock("@utils/Utils", () => ({
+ serverError: (...args: unknown[]) => mockServerError(...args)
+}));
+
+jest.mock("../glossaryTermsListColumns", () => ({
+ createGlossaryTermsListColumns: jest.fn(() => [
+ { accessorKey: "name", header: "Name" }
+ ])
+}));
+
+jest.mock("@components/Table/TableLayout", () => ({
+ TableLayout: ({ fetchData }: { fetchData: (args: unknown) => void }) => {
+ React.useEffect(() => {
+ void fetchData({ pagination: { pageIndex: 0, pageSize: 25 } });
+ }, [fetchData]);
+ return <div data-testid="table-layout">Table</div>;
+ }
+}));
+
+jest.mock("react-toastify", () => ({
+ toast: {
+ success: jest.fn(),
+ dismiss: jest.fn()
+ }
+}));
+
+const createStore = () =>
+ configureStore({
+ reducer: {
+ glossary: () => ({
+ glossaryData: [{ name: "testGlossary", guid: "g-1" }],
+ loading: false
+ })
+ }
+ });
+
+const openDownloadMenu = async () => {
+ const downloadButton = await screen.findByRole("button", { name: /download/i });
+ await waitFor(() => {
+ expect(downloadButton).not.toBeDisabled();
+ });
+ fireEvent.click(downloadButton);
+};
+
+describe("GlossaryTermsListPage", () => {
+ beforeEach(() => {
+ jest.clearAllMocks();
+ mockFetchGlossarySearchPage.mockResolvedValue({
+ rows: [{ id: "term-1", name: "Term1" }],
+ totalCount: 1
+ });
+ mockRequestGlossaryExportDownload.mockResolvedValue(undefined);
+ });
+
+ it("renders page layout with aligned wrapper and filters", async () => {
+ const { container } = render(
+ <Provider store={createStore()}>
+ <GlossaryTermsListPage />
+ </Provider>
+ );
+
+ expect(
+ container.querySelector(".glossary-terms-list-page")
+ ).toBeInTheDocument();
+ expect(
+ container.querySelector(".glossary-terms-filters")
+ ).toBeInTheDocument();
+ expect(
+ container.querySelector(".glossary-terms-table")
+ ).toBeInTheDocument();
+ expect(
+ screen.getByRole("heading", { name: /glossary terms & categories/i })
+ ).toBeInTheDocument();
+
+ await waitFor(() => {
+ expect(screen.getByTestId("table-layout")).toBeInTheDocument();
+ });
+ });
+
+ it("does not enqueue export when only opening the download menu", async () => {
+ render(
+ <Provider store={createStore()}>
+ <GlossaryTermsListPage />
+ </Provider>
+ );
+
+ await waitFor(() => {
+ expect(mockFetchGlossarySearchPage).toHaveBeenCalled();
+ });
+
+ await openDownloadMenu();
+
+ expect(await screen.findByRole("menuitem", { name: /^CSV$/i })).toBeInTheDocument();
+ expect(screen.getByRole("menuitem", { name: /^XLSX$/i })).toBeInTheDocument();
+ expect(mockRequestGlossaryExportDownload).not.toHaveBeenCalled();
+ });
+
+ it("enqueues glossary export as CSV from the download menu", async () => {
+ render(
+ <Provider store={createStore()}>
+ <GlossaryTermsListPage />
+ </Provider>
+ );
+
+ await waitFor(() => {
+ expect(mockFetchGlossarySearchPage).toHaveBeenCalled();
+ });
+
+ await openDownloadMenu();
+ fireEvent.click(await screen.findByRole("menuitem", { name: /^CSV$/i }));
+
+ await waitFor(() => {
+ expect(mockRequestGlossaryExportDownload).toHaveBeenCalledWith(
+ expect.objectContaining({
+ recordType: "all",
+ glossaryName: "",
+ statusFilter: "",
+ searchText: ""
+ }),
+ expect.objectContaining({ testGlossary: "g-1" }),
+ "CSV"
+ );
+ });
+ });
+
+ it("enqueues glossary export as XLSX from the download menu", async () => {
+ render(
+ <Provider store={createStore()}>
+ <GlossaryTermsListPage />
+ </Provider>
+ );
+
+ await waitFor(() => {
+ expect(mockFetchGlossarySearchPage).toHaveBeenCalled();
+ });
+
+ await openDownloadMenu();
+ fireEvent.click(await screen.findByRole("menuitem", { name: /^XLSX$/i }));
+
+ await waitFor(() => {
+ expect(mockRequestGlossaryExportDownload).toHaveBeenCalledWith(
+ expect.any(Object),
+ expect.any(Object),
+ "XLSX"
+ );
+ });
+ });
+
+ it("disables download when table has no rows", async () => {
+ mockFetchGlossarySearchPage.mockResolvedValue({
+ rows: [],
+ totalCount: 0
+ });
+
+ render(
+ <Provider store={createStore()}>
+ <GlossaryTermsListPage />
+ </Provider>
+ );
+
+ await waitFor(() => {
+ expect(mockFetchGlossarySearchPage).toHaveBeenCalled();
+ });
+
+ expect(screen.getByRole("button", { name: /download/i })).toBeDisabled();
+ });
+
+ it("shows serverError when glossary search fetch fails", async () => {
+ const fetchError = new Error("search failed");
+ mockFetchGlossarySearchPage.mockRejectedValue(fetchError);
+
+ render(
+ <Provider store={createStore()}>
+ <GlossaryTermsListPage />
+ </Provider>
+ );
+
+ await waitFor(() => {
+ expect(mockServerError).toHaveBeenCalledWith(
+ fetchError,
+ expect.any(Object)
+ );
+ });
+ });
+
+ it("shows serverError and re-enables download when export fails", async () => {
+ const exportError = new Error("export failed");
+ mockRequestGlossaryExportDownload.mockRejectedValue(exportError);
+
+ render(
+ <Provider store={createStore()}>
+ <GlossaryTermsListPage />
+ </Provider>
+ );
+
+ await waitFor(() => {
+ expect(mockFetchGlossarySearchPage).toHaveBeenCalled();
+ });
+
+ const downloadButton = await screen.findByRole("button", { name: /download/i });
+ await waitFor(() => {
+ expect(downloadButton).not.toBeDisabled();
+ });
+ await openDownloadMenu();
+ fireEvent.click(await screen.findByRole("menuitem", { name: /^CSV$/i }));
+
+ await waitFor(() => {
+ expect(mockServerError).toHaveBeenCalledWith(
+ exportError,
+ expect.any(Object)
+ );
+ });
+
+ expect(downloadButton).not.toBeDisabled();
+ });
+
+ it("refetches table data when record type filter changes", async () => {
+ render(
+ <Provider store={createStore()}>
+ <GlossaryTermsListPage />
+ </Provider>
+ );
+
+ await waitFor(() => {
+ expect(mockFetchGlossarySearchPage).toHaveBeenCalledTimes(1);
+ });
+
+ fireEvent.mouseDown(screen.getByLabelText(/record type/i));
+ fireEvent.click(await screen.findByRole("option", { name: /terms only/i }));
+
+ await waitFor(() => {
+ expect(mockFetchGlossarySearchPage).toHaveBeenCalledTimes(2);
+ });
+ });
+
+ it("debounces search text filter refresh before refetching", async () => {
+ jest.useFakeTimers();
+
+ render(
+ <Provider store={createStore()}>
+ <GlossaryTermsListPage />
+ </Provider>
+ );
+
+ await waitFor(() => {
+ expect(mockFetchGlossarySearchPage).toHaveBeenCalledTimes(1);
+ });
+
+ fireEvent.change(screen.getByLabelText(/search all columns/i), {
+ target: { value: "capital" }
+ });
+
+ expect(mockFetchGlossarySearchPage).toHaveBeenCalledTimes(1);
+
+ await act(async () => {
+ jest.advanceTimersByTime(400);
+ });
+
+ await waitFor(() => {
+ expect(mockFetchGlossarySearchPage).toHaveBeenCalledTimes(2);
+ });
+
+ jest.useRealTimers();
+ });
+});
diff --git a/dashboard/src/views/Glossary/__tests__/glossaryTermsListColumns.test.tsx b/dashboard/src/views/Glossary/__tests__/glossaryTermsListColumns.test.tsx
new file mode 100644
index 000000000..28dda2eb9
--- /dev/null
+++ b/dashboard/src/views/Glossary/__tests__/glossaryTermsListColumns.test.tsx
@@ -0,0 +1,169 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { render, screen } from "@testing-library/react";
+import { MemoryRouter } from "react-router-dom";
+import { createGlossaryTermsListColumns } from "../glossaryTermsListColumns";
+import type { GlossaryTableRow } from "@utils/glossaryExport";
+
+jest.mock("@components/DialogShowMoreLess", () => ({
+ __esModule: true,
+ default: ({ value }: { value: { classifications?: Array<{ typeName?: string }> } }) => (
+ <div data-testid="dialog-show-more-less">
+ {(value.classifications ?? []).map((item) => item.typeName).join(",")}
+ </div>
+ )
+}));
+
+const sampleRow: GlossaryTableRow = {
+ id: "term-1",
+ recordType: "Term",
+ name: "MetricTerm015",
+ guid: "term-guid-1",
+ qualifiedName: "MetricTerm015@testBankingGlossary",
+ glossaryName: "testBankingGlossary",
+ glossaryGuid: "glossary-guid-1",
+ shortDescription: "Short desc text",
+ longDescription: "Long desc text",
+ status: "ACTIVE",
+ classifications: [{ typeName: "class3" }],
+ customAttributes: { department: "Retail", status: "Active" }
+};
+
+const glossaryTermsListColumns = createGlossaryTermsListColumns(jest.fn());
+
+const renderColumnCell = (
+ accessorKey: keyof GlossaryTableRow,
+ row: GlossaryTableRow = sampleRow
+) => {
+ const column = glossaryTermsListColumns.find(
+ (c) => "accessorKey" in c && c.accessorKey === accessorKey
+ );
+ if (!column || !column.cell || typeof column.cell !== "function") {
+ throw new Error(`Column ${accessorKey} not found`);
+ }
+
+ const cellFn = column.cell as (ctx: {
+ getValue: () => unknown;
+ row: { original: GlossaryTableRow };
+ }) => React.ReactNode;
+
+ return render(
+ <MemoryRouter>
+ {cellFn({
+ getValue: () => row[accessorKey],
+ row: { original: row }
+ })}
+ </MemoryRouter>
+ );
+};
+
+describe("glossaryTermsListColumns", () => {
+ it("orders glossary name before name and omits related categories column", () => {
+ const keys = glossaryTermsListColumns
+ .map((column) =>
+ "accessorKey" in column ? column.accessorKey : undefined
+ )
+ .filter(Boolean);
+ expect(keys).toEqual([
+ "glossaryName",
+ "name",
+ "recordType",
+ "shortDescription",
+ "longDescription",
+ "classifications",
+ "customAttributes",
+ "status"
+ ]);
+ });
+
+ it("renders name as a plain search-result style link", () => {
+ renderColumnCell("name");
+ const link = screen.getByRole("link", { name: "MetricTerm015" });
+ expect(link).toHaveClass("entity-name");
+ expect(link).toHaveAttribute(
+ "href",
+ "/glossary/term-guid-1?gid=glossary-guid-1>ype=term&viewType=term&fromView=entity&term=MetricTerm015%40testBankingGlossary"
+ );
+ });
+
+ it("renders glossary name with tooltip text", () => {
+ renderColumnCell("glossaryName");
+ expect(screen.getByText("testBankingGlossary")).toBeInTheDocument();
+ });
+
+ it("renders short and long descriptions as plain text", () => {
+ renderColumnCell("shortDescription");
+ expect(screen.getByText("Short desc text")).toBeInTheDocument();
+
+ renderColumnCell("longDescription");
+ expect(screen.getByText("Long desc text")).toBeInTheDocument();
+ });
+
+ it("renders classifications for terms", () => {
+ renderColumnCell("classifications");
+ expect(screen.getByTestId("dialog-show-more-less")).toHaveTextContent(
+ "class3"
+ );
+ });
+
+ it("renders custom attributes as readable string", () => {
+ renderColumnCell("customAttributes");
+ expect(
+ screen.getByText("department: Retail, status: Active")
+ ).toBeInTheDocument();
+ });
+
+ it("renders status as a colored badge without icons", () => {
+ renderColumnCell("status");
+ const badge = screen.getByLabelText("Active status");
+ expect(badge).toBeInTheDocument();
+ expect(badge).toHaveTextContent("Active");
+ expect(badge).toHaveClass("MuiChip-colorSuccess");
+ expect(badge.querySelector(".MuiChip-icon")).not.toBeInTheDocument();
+ });
+
+ it("uses a narrower status column width", () => {
+ const statusColumn = glossaryTermsListColumns.find(
+ (column) => "accessorKey" in column && column.accessorKey === "status"
+ );
+ expect(statusColumn?.size).toBe(76);
+ });
+
+ it("renders name as plain text when guid is missing", () => {
+ renderColumnCell("name", { ...sampleRow, guid: "" });
+ expect(screen.getByText("MetricTerm015")).toBeInTheDocument();
+ expect(screen.queryByRole("link", { name: "MetricTerm015" })).not.toBeInTheDocument();
+ });
+
+ it("renders empty custom attributes as null", () => {
+ const { container } = renderColumnCell("customAttributes", {
+ ...sampleRow,
+ customAttributes: {}
+ });
+ expect(container).toBeEmptyDOMElement();
+ });
+
+ it("renders empty classifications for category rows", () => {
+ renderColumnCell("classifications", {
+ ...sampleRow,
+ recordType: "Category",
+ classifications: []
+ });
+ expect(screen.getByTestId("dialog-show-more-less")).toHaveTextContent("");
+ });
+});
diff --git a/dashboard/src/views/Glossary/glossaryTermsListColumns.tsx b/dashboard/src/views/Glossary/glossaryTermsListColumns.tsx
new file mode 100644
index 000000000..d01985780
--- /dev/null
+++ b/dashboard/src/views/Glossary/glossaryTermsListColumns.tsx
@@ -0,0 +1,204 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { removeClassification } from "@api/apiMethods/classificationApiMethod";
+import DialogShowMoreLess from "@components/DialogShowMoreLess";
+import { LightTooltip } from "@components/muiComponents";
+import GlossaryStatusBadge from "@views/Glossary/GlossaryStatusBadge";
+import { entityStateReadOnly } from "@utils/Enum";
+import {
+ formatCustomAttributesForDisplay,
+ formatCustomAttributesForTooltip,
+ type GlossaryTableRow
+} from "@utils/glossaryExport";
+import type { CSSProperties } from "react";
+import { ColumnDef } from "@tanstack/react-table";
+import { Link } from "react-router-dom";
+
+const COL_WIDTH_NAME = 200;
+const COL_WIDTH_DESCRIPTION = 220;
+const COL_WIDTH_STATUS = 76;
+
+const ellipsisCellStyle: CSSProperties = {
+ overflow: "hidden",
+ textOverflow: "ellipsis",
+ whiteSpace: "nowrap",
+ display: "block",
+ maxWidth: "100%"
+};
+
+const buildGlossaryDetailSearch = (row: GlossaryTableRow): string => {
+ const params = new URLSearchParams();
+ const gtype = row.recordType === "Term" ? "term" : "category";
+ params.set("gid", row.glossaryGuid);
+ params.set("gtype", gtype);
+ params.set("viewType", gtype);
+ params.set("fromView", "entity");
+ if (row.recordType === "Term" && row.qualifiedName) {
+ params.set("term", row.qualifiedName);
+ }
+ return params.toString();
+};
+
+const buildClassificationRowValue = (row: GlossaryTableRow) => ({
+ guid: row.guid,
+ status: row.status,
+ classifications: (row.classifications ?? []).map((classification) => ({
+ ...classification,
+ entityGuid: classification.entityGuid ?? row.guid
+ }))
+});
+
+const renderEllipsisText = (value: string, tooltip = value) => (
+ <LightTooltip title={tooltip}>
+ <span className="entity-name" style={ellipsisCellStyle}>
+ {value}
+ </span>
+ </LightTooltip>
+);
+
+export const createGlossaryTermsListColumns = (
+ setUpdateTable: (value: number) => void
+): ColumnDef<GlossaryTableRow>[] => [
+ {
+ accessorKey: "glossaryName",
+ header: "Glossary Name",
+ cell: (info) => {
+ const value = info.getValue() as string;
+ if (!value) {
+ return null;
+ }
+ return renderEllipsisText(value);
+ },
+ size: COL_WIDTH_NAME
+ },
+ {
+ accessorKey: "name",
+ header: "Name",
+ cell: (info) => {
+ const row = info.row.original;
+ const name = row.name;
+ if (!row.guid) {
+ return <span>{name}</span>;
+ }
+ return (
+ <div className="searchTableName">
+ <LightTooltip title={name}>
+ <Link
+ className="entity-name nav-link text-decoration-none text-blue glossary-term-name-link"
+ to={{
+ pathname: `/glossary/${row.guid}`,
+ search: `?${buildGlossaryDetailSearch(row)}`
+ }}
+ data-cy="glossaryTermNameLink"
+ >
+ {name}
+ </Link>
+ </LightTooltip>
+ </div>
+ );
+ },
+ size: COL_WIDTH_NAME,
+ sortingFn: "alphanumeric"
+ },
+ {
+ accessorKey: "recordType",
+ header: "Record Type",
+ cell: (info) => <span>{info.getValue() as string}</span>,
+ size: 110
+ },
+ {
+ accessorKey: "shortDescription",
+ header: "Short Description",
+ cell: (info) => {
+ const value = info.getValue() as string;
+ return value ? renderEllipsisText(value) : null;
+ },
+ size: COL_WIDTH_DESCRIPTION,
+ enableSorting: false
+ },
+ {
+ accessorKey: "longDescription",
+ header: "Long Description",
+ cell: (info) => {
+ const value = info.getValue() as string;
+ return value ? renderEllipsisText(value) : null;
+ },
+ size: COL_WIDTH_DESCRIPTION,
+ enableSorting: false
+ },
+ {
+ accessorKey: "classifications",
+ header: "Classifications",
+ cell: (info) => {
+ const row = info.row.original;
+ if (!row.guid) {
+ return null;
+ }
+
+ const classificationValue = buildClassificationRowValue(row);
+ const isTerm = row.recordType === "Term";
+ const isReadOnly =
+ !isTerm ||
+ Boolean(row.status && entityStateReadOnly[row.status]);
+
+ return (
+ <DialogShowMoreLess
+ value={classificationValue}
+ readOnly={isReadOnly}
+ setUpdateTable={setUpdateTable}
+ columnVal="classifications"
+ colName="Classification"
+ displayText="typeName"
+ removeApiMethod={isTerm ? removeClassification : undefined}
+ isShowMoreLess={true}
+ />
+ );
+ },
+ enableSorting: false
+ },
+ {
+ accessorKey: "customAttributes",
+ header: "Custom Attributes",
+ cell: (info) => {
+ const value = info.row.original.customAttributes;
+ if (!value || Object.keys(value).length === 0) {
+ return null;
+ }
+ const displayText = formatCustomAttributesForDisplay(value);
+ if (!displayText) {
+ return null;
+ }
+ return renderEllipsisText(
+ displayText,
+ formatCustomAttributesForTooltip(value)
+ );
+ },
+ size: 160,
+ enableSorting: false
+ },
+ {
+ accessorKey: "status",
+ header: "Status",
+ cell: (info) => (
+ <GlossaryStatusBadge status={info.getValue() as string} />
+ ),
+ size: COL_WIDTH_STATUS
+ }
+];
+
+export default createGlossaryTermsListColumns;
diff --git a/dashboard/src/views/Layout/Header.tsx b/dashboard/src/views/Layout/Header.tsx
index bf7b3d075..217600a5f 100644
--- a/dashboard/src/views/Layout/Header.tsx
+++ b/dashboard/src/views/Layout/Header.tsx
@@ -15,7 +15,7 @@
* limitations under the License.
*/
-import { ChangeEvent, useRef, useState } from "react";
+import { ChangeEvent, useEffect, useMemo, useRef, useState } from "react";
import {
Divider,
IconButton,
@@ -44,12 +44,14 @@ import {
ListItemText,
Popover,
Skeleton,
- Stack
+ Stack,
+ CircularProgress
} from "@mui/material";
import DownloadIcon from "@mui/icons-material/Download";
import RefreshIcon from "@mui/icons-material/Refresh";
import CloseOutlinedIcon from "@mui/icons-material/CloseOutlined";
import { getDownloadStatus } from "@api/apiMethods/downloadApiMethod";
+import { getGlossaryDownloadStatus } from "@api/apiMethods/glossaryApiMethod";
import {
getBaseUrl,
getNavigate,
@@ -57,12 +59,30 @@ import {
serverError,
setNavigate
} from "@utils/Utils";
-import { toast } from "react-toastify";
+import { toast, type Id } from "react-toastify";
import { apiDocUrl } from "@api/apiUrlLinks/headerUrl";
import { globalSessionData } from "@utils/Enum";
import { downloadSearchResultsFileUrl } from "@api/apiUrlLinks/downloadApiUrl";
+import { glossaryDownloadFileUrl } from "@api/apiUrlLinks/glossaryUrl";
import ChevronLeftIcon from "@mui/icons-material/ChevronLeft";
import { AntSwitch } from "@utils/Muiutils";
+import {
+ type DownloadRecord,
+ extractDownloadRecords,
+ filterDownloadRecordsForToggle,
+ isPendingDownloadRecord,
+ mergeDownloadRecords
+} from "@utils/downloadRecords";
+
+interface HeaderSessionState {
+ session: {
+ sessionObj: {
+ loading: boolean;
+ data: { userName?: string } | null;
+ error: string | null;
+ };
+ };
+}
interface Header {
handleOpenModal: () => void;
@@ -75,11 +95,11 @@ const Header: React.FC<Header> = ({
}) => {
const location = useLocation();
const navigate = useNavigate();
- const toastId: any = useRef(null);
- const { sessionObj = "" }: any = useAppSelector(
- (state: any) => state.session
+ const toastId = useRef<Id | undefined>(undefined);
+ const sessionObj = useAppSelector(
+ (state: HeaderSessionState) => state.session.sessionObj
);
- const { userName } = sessionObj.data || {};
+ const userName = sessionObj?.data?.userName;
const { debugMetrics = {} } = globalSessionData || {};
const [anchorEl, setAnchorEl] = useState<null | HTMLElement>(null);
@@ -92,26 +112,65 @@ const Header: React.FC<Header> = ({
const [downloadAnchorEl, setDownloadAnchorEl] = useState<null | HTMLElement>(
null
);
- const [searchDownloadsList, setSearchDownList] = useState([]);
+ const [searchDownloadsList, setSearchDownList] = useState<DownloadRecord[]>(
+ []
+ );
const [downloadLoader, setDownloadLoader] = useState<boolean>(false);
- const [checked, setChecked] = useState(false);
+ const [checked, setChecked] = useState(true);
- if (location.pathname == "/search/searchResult") {
- setNavigate(location.pathname + location.search);
- }
+ const displayedDownloadsList = useMemo(
+ () => filterDownloadRecordsForToggle(searchDownloadsList, checked),
+ [checked, searchDownloadsList]
+ );
+
+ useEffect(() => {
+ if (location.pathname === "/search/searchResult") {
+ setNavigate(location.pathname + location.search);
+ }
+ }, [location.pathname, location.search, setNavigate]);
const fetchDownloadStatus = async () => {
- try {
- setDownloadLoader(true);
- const downListResp = await getDownloadStatus({});
- const { searchDownloadRecords } = downListResp.data;
- setSearchDownList(searchDownloadRecords);
- setDownloadLoader(false);
- } catch (error) {
+ setDownloadLoader(true);
+
+ const [searchResult, glossaryResult] = await Promise.allSettled([
+ getDownloadStatus({}),
+ getGlossaryDownloadStatus({})
+ ]);
+
+ const searchRecords =
+ searchResult.status === "fulfilled"
+ ? extractDownloadRecords(searchResult.value.data, "search")
+ : [];
+ const glossaryRecords =
+ glossaryResult.status === "fulfilled"
+ ? extractDownloadRecords(glossaryResult.value.data, "glossary")
+ : [];
+
+ if (searchResult.status === "rejected") {
+ console.error(
+ "Error occurred while fetching search download records",
+ searchResult.reason
+ );
+ }
+
+ if (glossaryResult.status === "rejected") {
+ console.error(
+ "Error occurred while fetching glossary download records",
+ glossaryResult.reason
+ );
+ }
+
+ if (
+ searchResult.status === "rejected" &&
+ glossaryResult.status === "rejected"
+ ) {
setDownloadLoader(false);
- console.error(`Error occur while fetching searchResult records`, error);
- serverError(error, toastId);
+ serverError(searchResult.reason, toastId);
+ return;
}
+
+ setSearchDownList(mergeDownloadRecords(searchRecords, glossaryRecords));
+ setDownloadLoader(false);
};
const handleClickDownload = (event: React.MouseEvent<HTMLElement>) => {
@@ -133,11 +192,15 @@ const Header: React.FC<Header> = ({
setAnchorEl(event.currentTarget);
};
- const handleFileDownload = async (file: any) => {
- const { fileName } = file;
+ const handleFileDownload = async (file: DownloadRecord) => {
+ const { fileName, source } = file;
let path = getBaseUrl(window.location.pathname);
- window.location.href = path + downloadSearchResultsFileUrl(fileName);
- toast.success("File download succesfully");
+ const downloadUrl =
+ source === "glossary"
+ ? glossaryDownloadFileUrl(fileName)
+ : downloadSearchResultsFileUrl(fileName);
+ window.location.href = path + downloadUrl;
+ toast.success("File downloaded successfully");
};
const handleNestedMenuClick = () => {
@@ -191,7 +254,10 @@ const Header: React.FC<Header> = ({
{(location.pathname === "/" || location.pathname === "/search") && (
<div style={{ flex: "1" }} />
)}
- <div className="header-menu" style={{ display: "flex", alignItems: "center", gap: 8, flexShrink: 0 }}>
+ <div
+ className="header-menu"
+ style={{ display: "flex", alignItems: "center", gap: 8, flexShrink: 0 }}
+ >
<CreateDropdown />
<LightTooltip title="Downloads">
<IconButton
@@ -383,7 +449,9 @@ const Header: React.FC<Header> = ({
<Stack direction="row" alignItems="center" gap="0.25rem">
<LightTooltip
title={
- checked ? "Display All Files" : "Display Available Files"
+ checked
+ ? "Showing all files (including in progress)"
+ : "Showing completed files only"
}
>
<AntSwitch
@@ -434,10 +502,11 @@ const Header: React.FC<Header> = ({
</ListItem>
))}
</List>
- ) : !isEmpty(searchDownloadsList) ? (
- searchDownloadsList?.map((file: { fileName: string }, index) => {
+ ) : !isEmpty(displayedDownloadsList) ? (
+ displayedDownloadsList.map((file: DownloadRecord, index) => {
+ const isPending = isPendingDownloadRecord(file);
return (
- <List dense disablePadding>
+ <List dense disablePadding key={`${file.source}-${file.fileName}`}>
<ListItem dense disablePadding>
<Stack
direction="row"
@@ -450,15 +519,19 @@ const Header: React.FC<Header> = ({
aria-hidden="true"
></i>
<ListItemText primary={file.fileName} />
- <IconButton
- color="success"
- onClick={() => handleFileDownload(file)}
- >
- <DownloadIcon />
- </IconButton>
+ {isPending ? (
+ <CircularProgress size={20} color="success" />
+ ) : (
+ <IconButton
+ color="success"
+ onClick={() => handleFileDownload(file)}
+ >
+ <DownloadIcon />
+ </IconButton>
+ )}
</Stack>
</ListItem>
- {index != searchDownloadsList?.length - 1 && <Divider />}
+ {index != displayedDownloadsList.length - 1 && <Divider />}
</List>
);
})
diff --git a/dashboard/src/views/Layout/__tests__/Header.test.tsx b/dashboard/src/views/Layout/__tests__/Header.test.tsx
index d2390fce1..3eab477b4 100644
--- a/dashboard/src/views/Layout/__tests__/Header.test.tsx
+++ b/dashboard/src/views/Layout/__tests__/Header.test.tsx
@@ -64,6 +64,12 @@ jest.mock('@api/apiMethods/downloadApiMethod', () => ({
getDownloadStatus: (...args: any[]) => mockGetDownloadStatus(...args)
}));
+const mockGetGlossaryDownloadStatus = jest.fn();
+jest.mock('@api/apiMethods/glossaryApiMethod', () => ({
+ getGlossaryDownloadStatus: (...args: any[]) =>
+ mockGetGlossaryDownloadStatus(...args)
+}));
+
// Mock Utils (factory must not close over const mocks — hoisting runs factory first)
jest.mock('@utils/Utils', () => ({
getBaseUrl: jest.fn((url: string) => '/base'),
@@ -114,6 +120,13 @@ jest.mock('@api/apiUrlLinks/downloadApiUrl', () => ({
downloadSearchResultsFileUrl: (...args: any[]) => mockDownloadSearchResultsFileUrl(...args)
}));
+const mockGlossaryDownloadFileUrl = jest.fn(
+ (fileName: string) => `/glossary-download/${fileName}`
+);
+jest.mock('@api/apiUrlLinks/glossaryUrl', () => ({
+ glossaryDownloadFileUrl: (...args: any[]) => mockGlossaryDownloadFileUrl(...args)
+}));
+
// Mock globalSessionData
jest.mock('@utils/Enum', () => ({
globalSessionData: {}
@@ -204,16 +217,17 @@ jest.mock('@mui/material', () => {
};
});
-// Mock AntSwitch
+// Mock AntSwitch — forwards change events so controlled Header toggle updates in tests
jest.mock('@utils/Muiutils', () => ({
- AntSwitch: ({ checked, onChange, onClick, ...props }: any) => (
+ AntSwitch: ({ checked, onChange, onClick, inputProps, sx: _sx, size: _size, ...rest }: any) => (
<input
type="checkbox"
data-testid="ant-switch"
checked={checked}
onChange={onChange}
onClick={onClick}
- {...props}
+ {...inputProps}
+ {...rest}
/>
)
}));
@@ -236,6 +250,11 @@ describe('Header Component', () => {
searchDownloadRecords: []
}
});
+ mockGetGlossaryDownloadStatus.mockResolvedValue({
+ data: {
+ glossaryDownloadRecords: []
+ }
+ });
mockGetBaseUrl.mockReturnValue('/base');
mockGetNavigate.mockReturnValue('/search');
mockIsEmpty.mockImplementation((value: any) => {
@@ -641,11 +660,17 @@ describe('Header Component', () => {
]
}
});
+ mockGetGlossaryDownloadStatus.mockResolvedValue({
+ data: {
+ glossaryDownloadRecords: []
+ }
+ });
const { container } = renderHeader();
const downloadButton = container.querySelector('[data-cy="showDownloads"]') as HTMLElement;
fireEvent.click(downloadButton);
await waitFor(() => {
expect(mockGetDownloadStatus).toHaveBeenCalledWith({});
+ expect(mockGetGlossaryDownloadStatus).toHaveBeenCalledWith({});
});
});
@@ -680,6 +705,11 @@ describe('Header Component', () => {
]
}
});
+ mockGetGlossaryDownloadStatus.mockResolvedValue({
+ data: {
+ glossaryDownloadRecords: [{ fileName: 'glossary-file.csv' }]
+ }
+ });
mockIsEmpty.mockReturnValue(false);
const { container } = renderHeader();
const downloadButton = container.querySelector('[data-cy="showDownloads"]') as HTMLElement;
@@ -689,6 +719,50 @@ describe('Header Component', () => {
await waitFor(() => {
expect(screen.getByText('file1.csv')).toBeInTheDocument();
expect(screen.getByText('file2.csv')).toBeInTheDocument();
+ expect(screen.getByText('glossary-file.csv')).toBeInTheDocument();
+ }, { timeout: 15000 });
+ }, 30000);
+
+ it('should sort download list with newest files first', async () => {
+ mockGetDownloadStatus.mockResolvedValue({
+ data: {
+ searchDownloadRecords: [
+ {
+ fileName: 'admin_basic_2026-08-12_12-11-41.csv',
+ createdTime: Date.parse('2026-08-12T12:11:41')
+ },
+ {
+ fileName: 'admin_basic_2026-08-12_15-36-29.csv',
+ createdTime: Date.parse('2026-08-12T15:36:29')
+ }
+ ]
+ }
+ });
+ mockGetGlossaryDownloadStatus.mockResolvedValue({
+ data: {
+ searchDownloadRecords: [
+ {
+ fileName: 'admin_GLOSSARY_EXPORT_2026-08-12_15-30-14.csv',
+ createdTime: Date.parse('2026-08-12T15:30:14')
+ }
+ ]
+ }
+ });
+ mockIsEmpty.mockReturnValue(false);
+ const { container } = renderHeader();
+ const downloadButton = container.querySelector('[data-cy="showDownloads"]') as HTMLElement;
+ await act(async () => {
+ fireEvent.click(downloadButton);
+ });
+ await waitFor(() => {
+ const fileNames = screen
+ .getAllByText(/admin_(basic|GLOSSARY_EXPORT)_2026-08-12_/i)
+ .map((element) => element.textContent);
+ expect(fileNames).toEqual([
+ 'admin_basic_2026-08-12_15-36-29.csv',
+ 'admin_GLOSSARY_EXPORT_2026-08-12_15-30-14.csv',
+ 'admin_basic_2026-08-12_12-11-41.csv'
+ ]);
}, { timeout: 15000 });
}, 30000);
@@ -715,6 +789,11 @@ describe('Header Component', () => {
searchDownloadRecords: [{ fileName: 'test-file.csv' }]
}
});
+ mockGetGlossaryDownloadStatus.mockResolvedValue({
+ data: {
+ glossaryDownloadRecords: []
+ }
+ });
mockIsEmpty.mockReturnValue(false);
const { container } = renderHeader();
const downloadButton = container.querySelector('[data-cy="showDownloads"]') as HTMLElement;
@@ -734,10 +813,69 @@ describe('Header Component', () => {
});
expect(mockGetBaseUrl).toHaveBeenCalled();
expect(mockDownloadSearchResultsFileUrl).toHaveBeenCalledWith('test-file.csv');
- expect(mockToastSuccess).toHaveBeenCalledWith('File download succesfully');
+ expect(mockToastSuccess).toHaveBeenCalledWith('File downloaded successfully');
+ }
+ }, 30000);
+
+ it('should use glossary download URL for glossary export files', async () => {
+ mockGetDownloadStatus.mockResolvedValue({
+ data: {
+ searchDownloadRecords: []
+ }
+ });
+ mockGetGlossaryDownloadStatus.mockResolvedValue({
+ data: {
+ glossaryDownloadRecords: [{ fileName: 'glossary-export.csv' }]
+ }
+ });
+ mockIsEmpty.mockReturnValue(false);
+ const { container } = renderHeader();
+ const downloadButton = container.querySelector('[data-cy="showDownloads"]') as HTMLElement;
+ await act(async () => {
+ fireEvent.click(downloadButton);
+ });
+ await waitFor(() => {
+ expect(screen.getByText('glossary-export.csv')).toBeInTheDocument();
+ }, { timeout: 15000 });
+ const downloadIcons = screen.getAllByRole('button');
+ const fileDownloadButton = downloadIcons.find((btn) =>
+ btn.querySelector('svg[data-testid="DownloadIcon"]')
+ );
+ if (fileDownloadButton) {
+ await act(async () => {
+ fireEvent.click(fileDownloadButton);
+ });
+ expect(mockGlossaryDownloadFileUrl).toHaveBeenCalledWith(
+ 'glossary-export.csv'
+ );
}
}, 30000);
+ it('should not show source labels in download list items', async () => {
+ mockGetDownloadStatus.mockResolvedValue({
+ data: {
+ searchDownloadRecords: [{ fileName: 'search-export.csv' }]
+ }
+ });
+ mockGetGlossaryDownloadStatus.mockResolvedValue({
+ data: {
+ searchDownloadRecords: [{ fileName: 'glossary-from-api.csv' }]
+ }
+ });
+ mockIsEmpty.mockReturnValue(false);
+ const { container } = renderHeader();
+ const downloadButton = container.querySelector('[data-cy="showDownloads"]') as HTMLElement;
+ await act(async () => {
+ fireEvent.click(downloadButton);
+ });
+ await waitFor(() => {
+ expect(screen.getByText('glossary-from-api.csv')).toBeInTheDocument();
+ expect(screen.getByText('search-export.csv')).toBeInTheDocument();
+ expect(screen.queryByText('Glossary export')).not.toBeInTheDocument();
+ expect(screen.queryByText('Search export')).not.toBeInTheDocument();
+ }, { timeout: 15000 });
+ }, 30000);
+
it('should refresh download list when clicking refresh button', async () => {
mockGetDownloadStatus.mockResolvedValue({
data: {
@@ -751,6 +889,7 @@ describe('Header Component', () => {
});
await waitFor(() => {
expect(mockGetDownloadStatus).toHaveBeenCalledTimes(1);
+ expect(mockGetGlossaryDownloadStatus).toHaveBeenCalledTimes(1);
}, { timeout: 15000 });
// Find refresh button by looking for RefreshIcon
await waitFor(() => {
@@ -764,11 +903,12 @@ describe('Header Component', () => {
});
await waitFor(() => {
expect(mockGetDownloadStatus).toHaveBeenCalledTimes(2);
+ expect(mockGetGlossaryDownloadStatus).toHaveBeenCalledTimes(2);
}, { timeout: 15000 });
}
}, 30000);
- it('should handle download status fetch error', async () => {
+ it('should handle download status fetch error when both APIs fail', async () => {
const consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation();
const mockError = {
response: {
@@ -778,12 +918,17 @@ describe('Header Component', () => {
}
};
mockGetDownloadStatus.mockRejectedValue(mockError);
+ mockGetGlossaryDownloadStatus.mockRejectedValue(mockError);
const { container } = renderHeader();
const downloadButton = container.querySelector('[data-cy="showDownloads"]') as HTMLElement;
fireEvent.click(downloadButton);
await waitFor(() => {
expect(consoleErrorSpy).toHaveBeenCalledWith(
- 'Error occur while fetching searchResult records',
+ 'Error occurred while fetching search download records',
+ mockError
+ );
+ expect(consoleErrorSpy).toHaveBeenCalledWith(
+ 'Error occurred while fetching glossary download records',
mockError
);
expect(mockServerError).toHaveBeenCalled();
@@ -791,25 +936,115 @@ describe('Header Component', () => {
consoleErrorSpy.mockRestore();
});
- it('should toggle switch to filter downloads', async () => {
- mockGetDownloadStatus.mockResolvedValue({
+ it('should still show downloads when one status API fails', async () => {
+ mockGetDownloadStatus.mockRejectedValue(new Error('search failed'));
+ mockGetGlossaryDownloadStatus.mockResolvedValue({
data: {
- searchDownloadRecords: [{ fileName: 'file1.csv' }]
+ glossaryDownloadRecords: [{ fileName: 'glossary-only.csv' }]
}
});
mockIsEmpty.mockReturnValue(false);
const { container } = renderHeader();
const downloadButton = container.querySelector('[data-cy="showDownloads"]') as HTMLElement;
- fireEvent.click(downloadButton);
+ await act(async () => {
+ fireEvent.click(downloadButton);
+ });
await waitFor(() => {
- expect(screen.getByText('Downloads')).toBeInTheDocument();
+ expect(screen.getByText('glossary-only.csv')).toBeInTheDocument();
+ }, { timeout: 15000 });
+ expect(mockServerError).not.toHaveBeenCalled();
+ }, 30000);
+
+ it('should show all downloads by default including pending files', async () => {
+ mockGetDownloadStatus.mockResolvedValue({
+ data: {
+ searchDownloadRecords: [
+ { fileName: 'ready.csv', status: 'COMPLETE' },
+ { fileName: 'pending.csv', status: 'PENDING' }
+ ]
+ }
});
- const switchElement = screen.getByTestId('ant-switch');
- expect(switchElement).toBeInTheDocument();
- expect(switchElement).toHaveProperty('checked', false);
- fireEvent.change(switchElement, { target: { checked: true } });
- expect(switchElement).toHaveProperty('checked', true);
- });
+ mockGetGlossaryDownloadStatus.mockResolvedValue({
+ data: {
+ searchDownloadRecords: []
+ }
+ });
+ const { container } = renderHeader();
+ const downloadButton = container.querySelector('[data-cy="showDownloads"]') as HTMLElement;
+ await act(async () => {
+ fireEvent.click(downloadButton);
+ });
+ await waitFor(() => {
+ expect(screen.getByText('ready.csv')).toBeInTheDocument();
+ expect(screen.getByText('pending.csv')).toBeInTheDocument();
+ expect(screen.getByTestId('ant-switch')).toHaveProperty('checked', true);
+ }, { timeout: 15000 });
+ }, 30000);
+
+ it('should hide pending downloads when toggle shows completed files only', async () => {
+ mockGetDownloadStatus.mockResolvedValue({
+ data: {
+ searchDownloadRecords: [
+ { fileName: 'ready.csv', status: 'COMPLETE' },
+ { fileName: 'pending.csv', status: 'PENDING' }
+ ]
+ }
+ });
+ mockGetGlossaryDownloadStatus.mockResolvedValue({
+ data: {
+ searchDownloadRecords: []
+ }
+ });
+ const { container } = renderHeader();
+ const downloadButton = container.querySelector('[data-cy="showDownloads"]') as HTMLElement;
+ await act(async () => {
+ fireEvent.click(downloadButton);
+ });
+ await waitFor(() => {
+ expect(screen.getByText('pending.csv')).toBeInTheDocument();
+ }, { timeout: 15000 });
+
+ await act(async () => {
+ fireEvent.click(screen.getByTestId('ant-switch'));
+ });
+
+ await waitFor(() => {
+ expect(screen.queryByText('pending.csv')).not.toBeInTheDocument();
+ expect(screen.getByText('ready.csv')).toBeInTheDocument();
+ }, { timeout: 15000 });
+ }, 30000);
+
+ it('should show No Data Found when only pending files exist and toggle is off', async () => {
+ mockGetDownloadStatus.mockResolvedValue({
+ data: {
+ searchDownloadRecords: [
+ { fileName: 'pending-only.csv', status: 'PENDING' }
+ ]
+ }
+ });
+ mockGetGlossaryDownloadStatus.mockResolvedValue({
+ data: {
+ searchDownloadRecords: []
+ }
+ });
+ const { container } = renderHeader();
+ const downloadButton = container.querySelector('[data-cy="showDownloads"]') as HTMLElement;
+ await act(async () => {
+ fireEvent.click(downloadButton);
+ });
+ await waitFor(() => {
+ expect(screen.getByText('pending-only.csv')).toBeInTheDocument();
+ }, { timeout: 15000 });
+
+ await act(async () => {
+ fireEvent.click(screen.getByTestId('ant-switch'));
+ });
+
+ await waitFor(() => {
+ expect(screen.queryByText('pending-only.csv')).not.toBeInTheDocument();
+ expect(screen.getByText('No Data Found')).toBeInTheDocument();
+ }, { timeout: 15000 });
+ }, 30000);
it('should stop propagation when clicking switch', async () => {
mockGetDownloadStatus.mockResolvedValue({
@@ -1071,6 +1306,9 @@ describe('Header Component', () => {
expect(container.querySelector('[data-cy="showDownloads"]')).toBeInTheDocument();
expect(container.querySelector('[data-cy="showStats"]')).toBeInTheDocument();
expect(container.querySelector('[data-cy="user-account"]')).toBeInTheDocument();
+ expect(
+ container.querySelector('[data-cy="glossaryTermsListNavigate"]')
+ ).not.toBeInTheDocument();
});
});
});
diff --git a/dashboard/src/views/Router.tsx b/dashboard/src/views/Router.tsx
index b5ab60683..19217e071 100644
--- a/dashboard/src/views/Router.tsx
+++ b/dashboard/src/views/Router.tsx
@@ -34,6 +34,9 @@ const ClassificationDetailsLayout = lazy(
const GlossaryDetailLayout = lazy(
() => import("@views/DetailPage/GlossaryDetails/GlossaryDetailsLayout")
);
+const GlossaryTermsListPage = lazy(
+ () => import("@views/Glossary/GlossaryTermsListPage")
+);
const AdministratiorLayout = lazy(
() => import("@views/Administrator/AdministratorLayout")
);
@@ -71,6 +74,10 @@ const Router = () => {
path="/administrator/businessMetadata/:bmguid"
element={<BusinessMetadataDetailsLayout />}
/>
+ <Route
+ path="/glossary/terms-list"
+ element={<GlossaryTermsListPage />}
+ />
<Route path="/glossary/:guid" element={<GlossaryDetailLayout />} />
<Route
path="/relationshipDetailPage/:guid"
diff --git a/dashboard/src/views/SideBar/SideBarTree/SideBarTree.tsx b/dashboard/src/views/SideBar/SideBarTree/SideBarTree.tsx
index ec36f54ab..eb486edf0 100644
--- a/dashboard/src/views/SideBar/SideBarTree/SideBarTree.tsx
+++ b/dashboard/src/views/SideBar/SideBarTree/SideBarTree.tsx
@@ -51,6 +51,7 @@ import {
Typography,
} from "@components/muiComponents";
import AddIcon from "@mui/icons-material/Add";
+import TableRowsOutlinedIcon from "@mui/icons-material/TableRowsOutlined";
import { getBusinessMetadataImportTmpl } from "@api/apiMethods/entitiesApiMethods";
import {
NavigateFunction,
@@ -69,7 +70,8 @@ import { toast } from "react-toastify";
import { EnumTypeDefData, TreeNode } from "@models/treeStructureType";
import ImportDialog from "@components/ImportDialog";
import TreeIcons from "@components/Treeicons";
-import { useAppSelector } from "@hooks/reducerHook";
+import { useAppDispatch, useAppSelector } from "@hooks/reducerHook";
+import { fetchGlossaryData } from "@redux/slice/glossarySlice";
import TreeNodeIcons from "@components/TreeNodeIcons";
import ClassificationForm from "@views/Classification/ClassificationForm";
import AddUpdateGlossaryForm from "@views/Glossary/AddUpdateGlossaryForm";
@@ -287,6 +289,7 @@ const BarTreeView: FC<{
searchTerm,
loader,
}) => {
+ const dispatch = useAppDispatch();
const { savedSearchData }: any = useAppSelector(
(state: any) => state.savedSearch
);
@@ -1189,11 +1192,6 @@ const BarTreeView: FC<{
handleClose();
}}
data-cy="downloadBusinessMetadata"
- disabled={
- treeName == "Glossary" && !isEmptyServicetype
- ? true
- : false
- }
className="sidebar-menu-item"
>
<ListItemIcon sx={{ minWidth: "28px !important" }}>
@@ -1215,11 +1213,6 @@ const BarTreeView: FC<{
handleClose();
}}
data-cy="importBusinessMetadata"
- disabled={
- treeName == "Glossary" && !isEmptyServicetype
- ? true
- : false
- }
className="sidebar-menu-item"
>
<ListItemIcon sx={{ minWidth: "28px !important" }}>
@@ -1236,6 +1229,27 @@ const BarTreeView: FC<{
</Typography>
</MenuItem>
)}
+ {treeName == "Glossary" && (
+ <MenuItem
+ onClick={(e) => {
+ e.stopPropagation();
+ navigate("/glossary/terms-list");
+ handleClose();
+ }}
+ data-cy="glossaryTermsListNavigate"
+ className="sidebar-menu-item"
+ >
+ <ListItemIcon sx={{ minWidth: "28px !important" }}>
+ <TableRowsOutlinedIcon
+ fontSize="small"
+ className="menuitem-icon"
+ />
+ </ListItemIcon>
+ <Typography className="menuitem-label">
+ Export Glossary
+ </Typography>
+ </MenuItem>
+ )}
</Menu>
</Stack>
}
@@ -1267,6 +1281,13 @@ const BarTreeView: FC<{
? "Import Business Metadata"
: "Import Glossary Term"
}
+ onImportSuccess={
+ treeName == "Glossary"
+ ? () => {
+ void dispatch(fetchGlossaryData());
+ }
+ : undefined
+ }
/>
</SimpleTreeView>
</Stack>
diff --git a/dashboard/src/views/SideBar/SideBarTree/__tests__/SideBarTree.test.tsx b/dashboard/src/views/SideBar/SideBarTree/__tests__/SideBarTree.test.tsx
index ab02347a9..bc1f6d3df 100644
--- a/dashboard/src/views/SideBar/SideBarTree/__tests__/SideBarTree.test.tsx
+++ b/dashboard/src/views/SideBar/SideBarTree/__tests__/SideBarTree.test.tsx
@@ -30,10 +30,11 @@ import React from 'react'
import { render, screen, waitFor, fireEvent, act, cleanup } from '@testing-library/react'
import { Provider } from 'react-redux'
import { configureStore } from '@reduxjs/toolkit'
-import { BrowserRouter, MemoryRouter } from 'react-router-dom'
+import { MemoryRouter, useLocation } from 'react-router-dom'
import SideBarTree from '../SideBarTree'
import { getBusinessMetadataImportTmpl } from '@api/apiMethods/entitiesApiMethods'
import { getGlossaryImportTmpl } from '@api/apiMethods/glossaryApiMethod'
+import { fetchGlossaryData } from '@redux/slice/glossarySlice'
// Mock dependencies
jest.mock('@api/apiMethods/entitiesApiMethods', () => ({
@@ -68,9 +69,23 @@ jest.mock('@utils/Helper', () => ({
cloneDeep: jest.fn((obj) => JSON.parse(JSON.stringify(obj)))
}))
+jest.mock('@redux/slice/glossarySlice', () => ({
+ fetchGlossaryData: jest.fn(() => ({ type: 'glossary/fetchGlossaryData' }))
+}))
+
jest.mock('@components/ImportDialog', () => {
return function MockImportDialog(props: any) {
- return props.open ? <div data-testid="import-dialog">Import Dialog</div> : null
+ return props.open ? (
+ <div data-testid="import-dialog">
+ <button
+ type="button"
+ data-testid="import-success-trigger"
+ onClick={() => props.onImportSuccess?.()}
+ >
+ Import Success
+ </button>
+ </div>
+ ) : null
}
})
@@ -161,8 +176,13 @@ jest.mock('@components/muiComponents', () => ({
Menu: ({ children, open, onClose, anchorEl }: any) => (
open ? <div data-testid="menu" onClick={onClose}>{children}</div> : null
),
- MenuItem: ({ children, onClick, disabled }: any) => (
- <div data-testid="menu-item" onClick={disabled ? undefined : onClick} data-disabled={disabled}>
+ MenuItem: ({ children, onClick, disabled, ...props }: any) => (
+ <div
+ data-testid="menu-item"
+ onClick={disabled ? undefined : onClick}
+ data-disabled={disabled}
+ {...props}
+ >
{children}
</div>
),
@@ -196,6 +216,11 @@ jest.mock('@mui/icons-material/LaunchOutlined', () => ({
default: ({ onClick }: any) => <div data-testid="launch-icon" onClick={onClick}>Launch</div>
}))
+jest.mock('@mui/icons-material/TableRowsOutlined', () => ({
+ __esModule: true,
+ default: () => <div data-testid="table-rows-icon">Export</div>
+}))
+
jest.mock('@mui/material/Stack', () => ({
__esModule: true,
default: ({ children, className, sx }: any) => (
@@ -205,6 +230,7 @@ jest.mock('@mui/material/Stack', () => ({
describe('SideBarTree', () => {
const mockDispatch = jest.fn()
+ const mockFetchGlossaryData = fetchGlossaryData as jest.MockedFunction<typeof fetchGlossaryData>
const mockGetBusinessMetadataImportTmpl = getBusinessMetadataImportTmpl as jest.MockedFunction<typeof getBusinessMetadataImportTmpl>
const mockGetGlossaryImportTmpl = getGlossaryImportTmpl as jest.MockedFunction<typeof getGlossaryImportTmpl>
@@ -258,6 +284,7 @@ describe('SideBarTree', () => {
beforeEach(() => {
jest.clearAllMocks()
+ mockFetchGlossaryData.mockReturnValue({ type: 'glossary/fetchGlossaryData' } as any)
global.URL.createObjectURL = jest.fn(() => 'blob:url')
global.URL.revokeObjectURL = jest.fn()
@@ -633,7 +660,7 @@ describe('SideBarTree', () => {
document.createElement = originalCreateElement
})
- it('should disable download for Glossary when isEmptyServicetype is false', async () => {
+ it('should keep download enabled for Glossary when isEmptyServicetype is false', async () => {
renderComponent({
treeName: 'Glossary',
isEmptyServicetype: false
@@ -651,7 +678,7 @@ describe('SideBarTree', () => {
const downloadItem = menuItems.find(item => item.textContent?.includes('Download'))
if (downloadItem) {
- expect(downloadItem).toHaveAttribute('data-disabled', 'true')
+ expect(downloadItem).not.toHaveAttribute('data-disabled', 'true')
}
})
})
@@ -782,6 +809,88 @@ describe('SideBarTree', () => {
expect(screen.getByTestId('glossary-form')).toBeInTheDocument()
})
})
+
+ it('should show Export Glossary menu item for Glossary tree', async () => {
+ renderComponent({ treeName: 'Glossary' })
+
+ await waitFor(() => {
+ expect(screen.getByTestId('simple-tree-view')).toBeInTheDocument()
+ })
+
+ fireEvent.click(screen.getByTestId('more-vert-icon'))
+
+ await waitFor(() => {
+ expect(screen.getByTestId('menu')).toBeInTheDocument()
+ })
+
+ expect(screen.getByText('Export Glossary')).toBeInTheDocument()
+ expect(screen.getByTestId('table-rows-icon')).toBeInTheDocument()
+ expect(
+ document.querySelector('[data-cy="glossaryTermsListNavigate"]')
+ ).toBeInTheDocument()
+ })
+
+ it('should navigate to glossary terms list when Export Glossary is clicked', async () => {
+ const LocationWatcher = () => {
+ const location = useLocation()
+ return <div data-testid="current-path">{location.pathname}</div>
+ }
+ const store = createMockStore()
+
+ render(
+ <Provider store={store}>
+ <MemoryRouter initialEntries={['/']}>
+ <LocationWatcher />
+ <SideBarTree
+ treeData={defaultTreeData}
+ treeName="Glossary"
+ refreshData={jest.fn()}
+ sideBarOpen={true}
+ searchTerm=""
+ />
+ </MemoryRouter>
+ </Provider>
+ )
+
+ await waitFor(() => {
+ expect(screen.getByTestId('simple-tree-view')).toBeInTheDocument()
+ })
+
+ fireEvent.click(screen.getByTestId('more-vert-icon'))
+
+ await waitFor(() => {
+ expect(screen.getByTestId('menu')).toBeInTheDocument()
+ })
+
+ const exportItem = screen
+ .getAllByTestId('menu-item')
+ .find((item) => item.textContent?.includes('Export Glossary'))
+
+ expect(exportItem).toBeTruthy()
+ fireEvent.click(exportItem as HTMLElement)
+
+ await waitFor(() => {
+ expect(screen.getByTestId('current-path')).toHaveTextContent(
+ '/glossary/terms-list'
+ )
+ })
+ })
+
+ it('should not show Export Glossary menu item for Entities tree', async () => {
+ renderComponent({ treeName: 'Entities' })
+
+ await waitFor(() => {
+ expect(screen.getByTestId('simple-tree-view')).toBeInTheDocument()
+ })
+
+ fireEvent.click(screen.getByTestId('more-vert-icon'))
+
+ await waitFor(() => {
+ expect(screen.getByTestId('menu')).toBeInTheDocument()
+ })
+
+ expect(screen.queryByText('Export Glossary')).not.toBeInTheDocument()
+ })
})
describe('Node Click Handling', () => {
@@ -1948,7 +2057,7 @@ describe('SideBarTree', () => {
}
})
- it('should disable import for Glossary when isEmptyServicetype is false', async () => {
+ it('should keep import enabled for Glossary when isEmptyServicetype is false', async () => {
renderComponent({
treeName: 'Glossary',
isEmptyServicetype: false
@@ -1969,9 +2078,43 @@ describe('SideBarTree', () => {
const importItem = menuItems.find(item => item.textContent?.includes('Import'))
if (importItem) {
- expect(importItem).toHaveAttribute('data-disabled', 'true')
+ expect(importItem).not.toHaveAttribute('data-disabled', 'true')
}
})
+
+ it('should refresh glossary sidebar after successful glossary import', async () => {
+ renderComponent({
+ treeName: 'Glossary',
+ isEmptyServicetype: false
+ })
+
+ await waitFor(() => {
+ expect(screen.getByTestId('simple-tree-view')).toBeInTheDocument()
+ })
+
+ fireEvent.click(screen.getByTestId('more-vert-icon'))
+
+ await waitFor(() => {
+ expect(screen.getByTestId('menu')).toBeInTheDocument()
+ })
+
+ const importItem = screen
+ .getAllByTestId('menu-item')
+ .find(item => item.textContent?.includes('Import Glossary Term'))
+
+ expect(importItem).toBeTruthy()
+ fireEvent.click(importItem!)
+
+ await waitFor(() => {
+ expect(screen.getByTestId('import-dialog')).toBeInTheDocument()
+ })
+
+ fireEvent.click(screen.getByTestId('import-success-trigger'))
+
+ await waitFor(() => {
+ expect(mockFetchGlossaryData).toHaveBeenCalled()
+ })
+ })
})
describe('Toggle Functionality - Edge Cases', () => {
diff --git a/dashboardv2/public/css/scss/common.scss b/dashboardv2/public/css/scss/common.scss
index 77b919ec6..0c2b0a703 100644
--- a/dashboardv2/public/css/scss/common.scss
+++ b/dashboardv2/public/css/scss/common.scss
@@ -329,10 +329,95 @@ pre {
font-size: 12px;
font-weight: normal;
margin-bottom: 5px;
- margin-left: 5px;
float: left;
}
+.glossary-terms-list-page {
+ padding: 10px 10px;
+
+ .glossary-terms-list-actions {
+ display: inline-flex;
+ align-items: center;
+ justify-content: flex-end;
+ flex-wrap: nowrap;
+ gap: 8px;
+ max-width: 100%;
+
+ .btn {
+ flex-shrink: 0;
+ white-space: nowrap;
+ }
+
+ .glossary-download-dropdown {
+ flex-shrink: 0;
+
+ .dropdown-menu {
+ z-index: 1050;
+ }
+ }
+ }
+
+ .glossary-terms-table {
+ margin-top: 10px;
+
+ .table-responsive {
+ min-height: 140px;
+ }
+
+ .backgrid {
+ width: 100%;
+ margin-bottom: 0;
+ }
+
+ .banded.pagination-box {
+ margin-top: 10px;
+ }
+ }
+}
+
+.glossary-terms-list-title {
+ margin-top: 0;
+}
+
+.glossary-terms-filters {
+ margin-bottom: 15px;
+
+ &.is-loading {
+ opacity: 0.65;
+ pointer-events: none;
+ }
+}
+
+.glossary-status-badge {
+ display: inline-block;
+ border: 1px solid transparent;
+ border-radius: 3px;
+ font-size: 11px;
+ line-height: 1.2;
+ padding: 2px 6px;
+ white-space: nowrap;
+}
+
+.glossary-status-active {
+ border-color: #37bb9b;
+ color: #1f7f67;
+}
+
+.glossary-status-draft {
+ border-color: #f0ad4e;
+ color: #9a6700;
+}
+
+.glossary-status-deprecated {
+ border-color: #bb5838;
+ color: #8f3f24;
+}
+
+.glossary-status-unknown {
+ border-color: #bdbdbd;
+ color: #686868;
+}
+
.errorValidate {
border-color: red !important;
}
diff --git a/dashboardv2/public/css/scss/downloads.scss b/dashboardv2/public/css/scss/downloads.scss
index f5f28a633..ee588aabe 100644
--- a/dashboardv2/public/css/scss/downloads.scss
+++ b/dashboardv2/public/css/scss/downloads.scss
@@ -34,6 +34,7 @@
padding: 10px;
display: flex;
align-items: center;
+ justify-content: space-between;
color: #686868;
border-bottom: 1px solid #ccc;
background-color: #eee;
@@ -41,8 +42,33 @@
border-top-right-radius: 10px;
.download-header-actions {
- position: absolute;
- right: 15px;
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ flex-shrink: 0;
+ margin-left: 12px;
+ }
+
+ .download-header-toggle-wrap {
+ display: inline-flex;
+ align-items: center;
+ flex-shrink: 0;
+ margin-right: 4px;
+ }
+
+ .download-header-toggle {
+ margin: 0;
+ display: inline-flex;
+ align-items: center;
+ flex-shrink: 0;
+ min-width: 3.5em;
+ }
+
+ .download-header-btn {
+ margin: 0;
+ flex-shrink: 0;
+ min-width: 32px;
+ padding: 5px 8px;
}
.pretty.p-switch.p-fill input:checked~.state.p-primary:before {
@@ -55,7 +81,7 @@
position: absolute;
left: 50%;
top: 50%;
- transform: translateX(-50%, -50%);
+ transform: translate(-50%, -50%);
i {
color: #37bb9b;
@@ -76,27 +102,34 @@
border-bottom: 1px solid #ccc;
display: flex;
align-items: center;
- position: relative;
+ gap: 16px;
color: #686868;
+ &.download-list-empty {
+ border-bottom: none;
+ }
+
+ > i.fa-file-excel-o {
+ flex-shrink: 0;
+ }
+
i {
color: #37bb9b;
}
a {
color: #686868 !important;
- width: 100%;
}
.file-name {
- padding: 0 10px 0 10px;
word-wrap: break-word;
- width: 90%;
+ flex: 1;
+ min-width: 0;
}
.download-state {
- position: absolute;
- right: 15px;
+ flex-shrink: 0;
+ margin-left: auto;
}
}
}
diff --git a/dashboardv2/public/js/collection/VDownloadList.js b/dashboardv2/public/js/collection/VDownloadList.js
index 65c9a36ff..3d91ce3d3 100644
--- a/dashboardv2/public/js/collection/VDownloadList.js
+++ b/dashboardv2/public/js/collection/VDownloadList.js
@@ -58,6 +58,16 @@ define(['require',
return this.constructor.nonCrudOperation.call(this, url, 'GET', options);
},
+ getGlossaryDownloadsList: function(options) {
+ var url = UrlLinks.getGlossaryDownloadsList();
+
+ options = _.extend({
+ contentType: 'application/json',
+ dataType: 'json'
+ }, options);
+
+ return this.constructor.nonCrudOperation.call(this, url, 'GET', options);
+ },
startDownloading: function(options) {
var queryParams = Utils.getUrlState.getQueryParams(),
url = queryParams.searchType === "basic" ? UrlLinks.downloadBasicSearchResultsCSV() : UrlLinks.downloadAdvanceSearchResultsCSV(),
diff --git a/dashboardv2/public/js/router/Router.js b/dashboardv2/public/js/router/Router.js
index 3f89f2d2a..2448ff40f 100644
--- a/dashboardv2/public/js/router/Router.js
+++ b/dashboardv2/public/js/router/Router.js
@@ -43,6 +43,7 @@ define([
"!/tag/tagAttribute/(*name)": "tagAttributePageLoad",
// Glossary
"!/glossary": "commonAction",
+ "!/glossary/terms-list": "glossaryTermsList",
"!/glossary/:id": "glossaryDetailPage",
// Details
"!/detailPage/:id": "detailPage",
@@ -270,8 +271,38 @@ define([
}
});
},
+ glossaryTermsList: function() {
+ var that = this;
+ require([
+ 'views/site/Header',
+ 'views/site/SideNavLayoutView',
+ 'views/glossary/GlossaryTermsListLayoutView'
+ ], function(Header, SideNavLayoutView, GlossaryTermsListLayoutView) {
+ Utils.updateInternalTabState();
+ var paramObj = Utils.getUrlState.getQueryParams(),
+ options = _.extend({}, that.preFetchedCollectionLists, that.sharedObj, that.ventObj);
+ that.renderViewIfNotExists(that.getHeaderOptions(Header));
+ that.renderViewIfNotExists({
+ view: App.rSideNav,
+ manualRender: function() {
+ this.view.currentView.selectTab();
+ },
+ render: function() {
+ return new SideNavLayoutView(options);
+ }
+ });
+ if (App.rNContent.currentView && App.rNContent.currentView.destroy) {
+ App.rNContent.currentView.destroy();
+ }
+ App.rNContent.show(new GlossaryTermsListLayoutView(options));
+ });
+ },
glossaryDetailPage: function(id) {
var that = this;
+ if (id === 'terms-list') {
+ this.glossaryTermsList();
+ return;
+ }
if (id) {
require([
'views/site/Header',
diff --git a/dashboardv2/public/js/templates/glossary/GlossaryLayoutView_tmpl.html b/dashboardv2/public/js/templates/glossary/GlossaryLayoutView_tmpl.html
index 805e5dc3c..4a793dc31 100644
--- a/dashboardv2/public/js/templates/glossary/GlossaryLayoutView_tmpl.html
+++ b/dashboardv2/public/js/templates/glossary/GlossaryLayoutView_tmpl.html
@@ -33,6 +33,8 @@
<ul class="dropdown-menu">
<li><a href="{{importTmplUrl}}">Download Import template</a></li>
<li><a href="javascript:void(0)" data-id="importGlossary">Import Glossary Term</a></li>
+ <li class="divider"></li>
+ <li><a href="#!/glossary/terms-list" data-id="exportGlossary"><i class="fa fa-table"></i> Export Glossary</a></li>
</ul>
</div>
<!-- -->
diff --git a/dashboardv2/public/js/templates/glossary/GlossaryTermsListLayoutView_tmpl.html b/dashboardv2/public/js/templates/glossary/GlossaryTermsListLayoutView_tmpl.html
new file mode 100644
index 000000000..45eb7579a
--- /dev/null
+++ b/dashboardv2/public/js/templates/glossary/GlossaryTermsListLayoutView_tmpl.html
@@ -0,0 +1,83 @@
+<!--
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+-->
+<div class="glossary-terms-list-page">
+ <div class="row form-group">
+ <div class="col-sm-8">
+ <h4 class="glossary-terms-list-title">
+ <i class="fa fa-list-alt text-green" aria-hidden="true"></i>
+ Glossary terms & categories
+ </h4>
+ </div>
+ <div class="col-sm-4 text-right">
+ <div class="glossary-terms-list-actions">
+ <button type="button" class="btn btn-action btn-sm" data-id="refreshGlossaryTermsList" title="Reload from server">
+ <i class="fa fa-refresh" aria-hidden="true"></i> Refresh
+ </button>
+ <div class="btn-group glossary-download-dropdown">
+ <button type="button" class="btn btn-action btn-sm dropdown-toggle" data-id="downloadGlossaryTermsList" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" aria-label="Download glossary export">
+ <i class="fa fa-download" aria-hidden="true"></i> Download <span class="caret"></span>
+ </button>
+ <ul class="dropdown-menu dropdown-menu-right" role="menu">
+ <li role="presentation">
+ <a href="javascript:void(0)" role="menuitem" data-id="downloadGlossaryCsv">CSV</a>
+ </li>
+ <li role="presentation">
+ <a href="javascript:void(0)" role="menuitem" data-id="downloadGlossaryXlsx">XLSX</a>
+ </li>
+ </ul>
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <div class="panel panel-default glossary-terms-filters">
+ <div class="panel-heading"><strong>Filters</strong></div>
+ <div class="panel-body">
+ <div class="row">
+ <div class="col-sm-3 form-group">
+ <label for="glossaryTermsFilterGlossary">Glossary</label>
+ <select class="form-control" data-id="filterGlossary" id="glossaryTermsFilterGlossary">
+ <option value="">All glossaries</option>
+ </select>
+ </div>
+ <div class="col-sm-3 form-group">
+ <label for="glossaryTermsFilterRecordType">Record type</label>
+ <select class="form-control" data-id="filterRecordType" id="glossaryTermsFilterRecordType">
+ <option value="all">All</option>
+ <option value="Term">Terms only</option>
+ <option value="Category">Categories only</option>
+ </select>
+ </div>
+ <div class="col-sm-3 form-group">
+ <label for="glossaryTermsFilterStatus">Status</label>
+ <select class="form-control" data-id="filterStatus" id="glossaryTermsFilterStatus">
+ <option value="">All</option>
+ <option value="DRAFT">Draft</option>
+ <option value="ACTIVE">Active</option>
+ <option value="DEPRECATED">Deprecated</option>
+ </select>
+ </div>
+ <div class="col-sm-3 form-group">
+ <label for="glossaryTermsFilterSearch">Search all columns</label>
+ <input type="text" class="form-control" data-id="filterSearchText" id="glossaryTermsFilterSearch" placeholder="Search all columns" />
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <div id="r_glossaryTermsTableLayoutView" class="glossary-terms-table searchTable"></div>
+</div>
diff --git a/dashboardv2/public/js/templates/site/DownloadSearchResultLayoutView_tmpl.html b/dashboardv2/public/js/templates/site/DownloadSearchResultLayoutView_tmpl.html
index c79bcd19e..00cb0ed44 100644
--- a/dashboardv2/public/js/templates/site/DownloadSearchResultLayoutView_tmpl.html
+++ b/dashboardv2/public/js/templates/site/DownloadSearchResultLayoutView_tmpl.html
@@ -18,12 +18,20 @@
<div id="download-header" class="download-header">
<span data-id="downloadtitle">Downloads</span>
<div class="download-header-actions">
- <div class="pretty p-switch p-fill" style="margin-right: 20px">
- <input type="checkbox" data-id="toggleDownloads" title="" />
- <div class="state p-primary">
- <label></label>
+ <span class="download-header-toggle-wrap">
+ <div class="pretty p-switch p-fill download-header-toggle">
+ <input type="checkbox" data-id="toggleDownloads" title="" />
+ <div class="state p-primary">
+ <label></label>
+ </div>
</div>
- </div><button data-id="refreshDownloads" class="btn btn-action btn-sm"><i class="fa fa-refresh" aria-hidden="true"></i></button> <button data-id="closeDownloads" class="btn btn-action btn-sm"><i class="fa fa-times" aria-hidden="true"></i></button>
+ </span>
+ <button data-id="refreshDownloads" class="btn btn-action btn-sm download-header-btn" type="button" aria-label="Refresh downloads">
+ <i class="fa fa-refresh" aria-hidden="true"></i>
+ </button>
+ <button data-id="closeDownloads" class="btn btn-action btn-sm download-header-btn" type="button" aria-label="Close downloads">
+ <i class="fa fa-times" aria-hidden="true"></i>
+ </button>
</div>
</div>
<div id="download-body" class="download-body">
diff --git a/dashboardv2/public/js/utils/GlossaryExport.js b/dashboardv2/public/js/utils/GlossaryExport.js
new file mode 100644
index 000000000..952b38bca
--- /dev/null
+++ b/dashboardv2/public/js/utils/GlossaryExport.js
@@ -0,0 +1,311 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+define(['require', 'jquery', 'underscore', 'utils/UrlLinks', 'utils/CommonViewFunction'], function(require, $, _, UrlLinks, CommonViewFunction) {
+ 'use strict';
+
+ var SEARCH_DEFAULTS = {
+ limit: 25,
+ offset: 0,
+ sortBy: 'glossaryName',
+ sortOrder: 'DESCENDING'
+ };
+
+ var STATUS_FILTER_OPTIONS = [
+ { label: 'All', value: '' },
+ { label: 'Draft', value: 'DRAFT' },
+ { label: 'Active', value: 'ACTIVE' },
+ { label: 'Deprecated', value: 'DEPRECATED' }
+ ];
+
+ var STATUS_META = {
+ ACTIVE: { label: 'Active', shortLabel: 'Active', cssClass: 'glossary-status-badge glossary-status-active' },
+ DRAFT: { label: 'Draft', shortLabel: 'Draft', cssClass: 'glossary-status-badge glossary-status-draft' },
+ DEPRECATED: { label: 'Deprecated', shortLabel: 'Depr.', cssClass: 'glossary-status-badge glossary-status-deprecated' },
+ UNKNOWN: { label: 'Unknown', shortLabel: '—', cssClass: 'glossary-status-badge glossary-status-unknown' }
+ };
+
+ var empty = function(v) {
+ return v === null || v === undefined ? '' : String(v);
+ };
+
+ var normalizeStatus = function(status) {
+ if (!status) {
+ return 'UNKNOWN';
+ }
+ var normalized = String(status).trim().toUpperCase();
+ if (normalized === 'ACTIVE' || normalized === 'DRAFT' || normalized === 'DEPRECATED') {
+ return normalized;
+ }
+ return 'UNKNOWN';
+ };
+
+ var getStatusMeta = function(status) {
+ return STATUS_META[normalizeStatus(status)];
+ };
+
+ var createDefaultFilters = function() {
+ return {
+ recordType: 'all',
+ glossaryName: '',
+ statusFilter: '',
+ searchText: ''
+ };
+ };
+
+ var mapRecordTypeToGlossaryType = function(recordType) {
+ if (recordType === 'Term') {
+ return 'TERM';
+ }
+ if (recordType === 'Category') {
+ return 'CATEGORY';
+ }
+ return undefined;
+ };
+
+ var buildGlossaryGuidByName = function(glossaryCollection) {
+ var map = {};
+ if (!glossaryCollection || !glossaryCollection.fullCollection) {
+ return map;
+ }
+ glossaryCollection.fullCollection.each(function(model) {
+ var name = model.get('name');
+ var guid = model.get('guid');
+ if (name && guid) {
+ map[name] = guid;
+ }
+ });
+ return map;
+ };
+
+ var buildSearchRequest = function(filters, pageIndex, rowsPerPage, glossaryGuidByName, sortOptions) {
+ glossaryGuidByName = glossaryGuidByName || {};
+ sortOptions = sortOptions || {};
+ var request = {
+ limit: rowsPerPage,
+ offset: pageIndex * rowsPerPage,
+ sortBy: sortOptions.sortBy || SEARCH_DEFAULTS.sortBy,
+ sortOrder: sortOptions.sortOrder || SEARCH_DEFAULTS.sortOrder,
+ excludeDeleted: true
+ };
+ var glossaryType = mapRecordTypeToGlossaryType(filters.recordType);
+ if (glossaryType) {
+ request.glossaryType = glossaryType;
+ }
+ if (filters.statusFilter && String(filters.statusFilter).trim()) {
+ request.status = String(filters.statusFilter).trim();
+ }
+ if (filters.searchText && String(filters.searchText).trim()) {
+ request.searchQuery = String(filters.searchText).trim();
+ }
+ if (filters.glossaryName && String(filters.glossaryName).trim()) {
+ var glossaryName = String(filters.glossaryName).trim();
+ request.glossary = {
+ name: glossaryName,
+ guid: glossaryGuidByName[glossaryName]
+ };
+ }
+ return request;
+ };
+
+ var formatCustomAttributesForDisplay = function(attrs) {
+ if (!attrs || typeof attrs !== 'object' || _.isEmpty(attrs)) {
+ return '';
+ }
+ return _.map(attrs, function(value, key) {
+ return key + ': ' + empty(value);
+ }).join(', ');
+ };
+
+ var formatCustomAttributesForTooltip = function(attrs) {
+ if (!attrs || typeof attrs !== 'object' || _.isEmpty(attrs)) {
+ return '';
+ }
+ try {
+ return JSON.stringify(attrs, null, 2);
+ } catch (e) {
+ return formatCustomAttributesForDisplay(attrs);
+ }
+ };
+
+ var mapDetailToRow = function(detail, recordType, glossaryName, glossaryGuid) {
+ return {
+ id: recordType.toLowerCase() + '-' + (empty(detail.guid) || empty(detail.name)),
+ recordType: recordType,
+ name: empty(detail.name),
+ guid: empty(detail.guid),
+ qualifiedName: empty(detail.qualifiedName),
+ glossaryName: glossaryName,
+ glossaryGuid: glossaryGuid,
+ shortDescription: empty(detail.shortDescription),
+ longDescription: empty(detail.longDescription),
+ status: empty(detail.status),
+ classifications: detail.classifications || [],
+ customAttributes: detail.customAttributes || {}
+ };
+ };
+
+ var mapSearchResponseToRows = function(response) {
+ var glossaries = response && response.glossary;
+ if (!_.isArray(glossaries)) {
+ return [];
+ }
+ var rows = [];
+ _.each(glossaries, function(glossary) {
+ var glossaryName = empty(glossary && glossary.name);
+ var glossaryGuid = empty(glossary && glossary.guid);
+ _.each(glossary.terms || [], function(term) {
+ rows.push(mapDetailToRow(term, 'Term', glossaryName, glossaryGuid));
+ });
+ _.each(glossary.categories || [], function(category) {
+ rows.push(mapDetailToRow(category, 'Category', glossaryName, glossaryGuid));
+ });
+ });
+ return rows;
+ };
+
+ var unwrapSearchResponse = function(response) {
+ if (response && response.glossary) {
+ return response;
+ }
+ if (response && response.data && response.data.glossary) {
+ return response.data;
+ }
+ return response || {};
+ };
+
+ var parseApproximateCount = function(value, fallback) {
+ var parsed = Number(value);
+ if (_.isFinite(parsed) && parsed >= 0) {
+ return parsed;
+ }
+ return fallback;
+ };
+
+ var postJson = function(url, data) {
+ return $.ajax({
+ url: url,
+ type: 'POST',
+ contentType: 'application/json',
+ dataType: 'json',
+ data: JSON.stringify(data),
+ beforeSend: CommonViewFunction.addRestCsrfCustomHeader
+ });
+ };
+
+ var fetchSearchPage = function(request) {
+ var deferred = $.Deferred();
+ postJson(UrlLinks.glossarySearchUrl(), request).done(function(response) {
+ var body = unwrapSearchResponse(response);
+ var rows = mapSearchResponseToRows(body);
+ var totalCount = parseApproximateCount(body.approximateCount, rows.length);
+ deferred.resolve({
+ rows: rows,
+ totalCount: totalCount
+ });
+ }).fail(function(xhr) {
+ deferred.reject(xhr);
+ });
+ return deferred.promise();
+ };
+
+ var buildSearchExportRequest = function(filters, glossaryGuidByName, format) {
+ var request = buildSearchRequest(filters, 0, 0, glossaryGuidByName, {});
+ request.limit = 0;
+ request.offset = 0;
+ if (format) {
+ request.format = format;
+ }
+ return request;
+ };
+
+ var requestExportDownload = function(filters, glossaryGuidByName, format) {
+ var deferred = $.Deferred();
+ postJson(
+ UrlLinks.glossaryCreateFileUrl(),
+ buildSearchExportRequest(filters, glossaryGuidByName, format || 'CSV')
+ ).done(function() {
+ deferred.resolve();
+ }).fail(function(xhr) {
+ deferred.reject(xhr);
+ });
+ return deferred.promise();
+ };
+
+ var formatStatusHtml = function(status) {
+ var meta = getStatusMeta(status);
+ return '<span class="' + meta.cssClass + '" title="Status: ' + _.escape(meta.label) + '">' +
+ _.escape(meta.shortLabel) + '</span>';
+ };
+
+ var formatClassificationsHtml = function(classifications) {
+ if (!_.isArray(classifications) || classifications.length === 0) {
+ return '';
+ }
+ return _.map(classifications, function(classification) {
+ if (!classification || !classification.typeName) {
+ return '';
+ }
+ var typeName = _.escape(classification.typeName);
+ return '<a href="#!/tag/tagAttribute/' + typeName + '" class="btn btn-action btn-sm btn-blue">' +
+ typeName + '</a>';
+ }).join(' ');
+ };
+
+ var buildGlossaryDetailUrl = function(row) {
+ var gType = row.recordType === 'Term' ? 'term' : 'category';
+ var params = {
+ gId: row.glossaryGuid,
+ gType: gType,
+ viewType: gType,
+ fromView: 'entity'
+ };
+ if (row.recordType === 'Term' && row.qualifiedName) {
+ params.term = row.qualifiedName;
+ }
+ var query = _.map(params, function(value, key) {
+ return encodeURIComponent(key) + '=' + encodeURIComponent(value);
+ }).join('&');
+ return '#!/glossary/' + row.guid + (query ? '?' + query : '');
+ };
+
+ var formatNameHtml = function(row) {
+ var name = _.escape(row.name);
+ if (!row.guid) {
+ return name;
+ }
+ return '<a href="' + buildGlossaryDetailUrl(row) + '" class="entity-name nav-link">' + name + '</a>';
+ };
+
+ return {
+ SEARCH_DEFAULTS: SEARCH_DEFAULTS,
+ STATUS_FILTER_OPTIONS: STATUS_FILTER_OPTIONS,
+ createDefaultFilters: createDefaultFilters,
+ buildGlossaryGuidByName: buildGlossaryGuidByName,
+ buildSearchRequest: buildSearchRequest,
+ buildSearchExportRequest: buildSearchExportRequest,
+ formatCustomAttributesForDisplay: formatCustomAttributesForDisplay,
+ formatCustomAttributesForTooltip: formatCustomAttributesForTooltip,
+ mapSearchResponseToRows: mapSearchResponseToRows,
+ fetchSearchPage: fetchSearchPage,
+ requestExportDownload: requestExportDownload,
+ formatStatusHtml: formatStatusHtml,
+ formatClassificationsHtml: formatClassificationsHtml,
+ formatNameHtml: formatNameHtml,
+ getStatusMeta: getStatusMeta
+ };
+});
diff --git a/dashboardv2/public/js/utils/UrlLinks.js b/dashboardv2/public/js/utils/UrlLinks.js
index 0594b3e0f..a107df76a 100644
--- a/dashboardv2/public/js/utils/UrlLinks.js
+++ b/dashboardv2/public/js/utils/UrlLinks.js
@@ -310,6 +310,21 @@ define(['require', 'utils/Enums', 'utils/Utils', 'underscore'], function(require
},
downloadSearchResultsFileUrl: function(fileName) {
return this.baseUrlV2 + '/search/download/' + fileName;
+ },
+ glossarySearchUrl: function() {
+ return this.glossaryApiUrl() + '/search';
+ },
+ glossaryExportUrl: function() {
+ return this.glossaryApiUrl() + '/export';
+ },
+ glossaryCreateFileUrl: function() {
+ return this.glossaryApiUrl() + '/create_file';
+ },
+ getGlossaryDownloadsList: function() {
+ return this.glossaryApiUrl() + '/download/status';
+ },
+ glossaryDownloadFileUrl: function(fileName) {
+ return this.glossaryApiUrl() + '/download/' + fileName;
}
});
diff --git a/dashboardv2/public/js/utils/Utils.js b/dashboardv2/public/js/utils/Utils.js
index 7b21a04b2..26d6a73d3 100644
--- a/dashboardv2/public/js/utils/Utils.js
+++ b/dashboardv2/public/js/utils/Utils.js
@@ -413,6 +413,14 @@ define(['require', 'utils/Globals', 'pnotify', 'utils/Messages', 'utils/Enums',
matchString: "glossary"
});
},
+ isGlossaryTermsListPage: function(url) {
+ var query = this.getQueryUrl(url),
+ lastValue = query.lastValue || '';
+ if (lastValue.indexOf('?') > -1) {
+ lastValue = lastValue.split('?')[0];
+ }
+ return query.firstValue === 'glossary' && lastValue === 'terms-list';
+ },
isDetailPage: function(url) {
return this.checkTabUrl({
url: url,
diff --git a/dashboardv2/public/js/views/glossary/GlossaryLayoutView.js b/dashboardv2/public/js/views/glossary/GlossaryLayoutView.js
index e1d52c193..2e30b2e4f 100644
--- a/dashboardv2/public/js/views/glossary/GlossaryLayoutView.js
+++ b/dashboardv2/public/js/views/glossary/GlossaryLayoutView.js
@@ -55,6 +55,7 @@ define(['require',
termTree: "[data-id='termTree']",
categoryTree: "[data-id='categoryTree']",
importGlossary: "[data-id='importGlossary']",
+ exportGlossary: "[data-id='exportGlossary']",
glossaryTreeLoader: "[data-id='glossaryTreeLoader']",
glossaryTreeView: "[data-id='glossaryTreeView']"
},
@@ -86,6 +87,7 @@ define(['require',
this.getGlossary();
};
events["click " + this.ui.importGlossary] = 'onClickImportGlossary';
+ events["click " + this.ui.exportGlossary] = 'onExportGlossary';
events["keyup " + this.ui.searchTerm] = function() {
this.ui.termTree.jstree("search", _.escape(this.ui.searchTerm.val()));
};
@@ -189,12 +191,10 @@ define(['require',
this.$('.category-view').show();
this.$('.term-view').hide();
this.viewType = "category";
- this.$('.dropdown-toggle').attr('disabled', 'disabled');
} else {
this.$('.term-view').show();
this.$('.category-view').hide();
this.viewType = "term";
- this.$('.dropdown-toggle').removeAttr('disabled');
}
var setDefaultSelector = function() {
if (!that.value) {
@@ -216,7 +216,7 @@ define(['require',
gType: "glossary"
}
}
- if (Utils.getUrlState.isGlossaryTab()) {
+ if (Utils.getUrlState.isGlossaryTab() && !Utils.getUrlState.isGlossaryTermsListPage()) {
var obj = this.query[this.viewType],
$tree = this.ui[(this.viewType == "term" ? "termTree" : "categoryTree")];
obj["gId"] = that.value ? that.value.gId : null; //this Property added, Because when we toggle the GlossaryViewButton it does not adds the gId which is required for selection.
@@ -479,7 +479,7 @@ define(['require',
}
}
}
- if (options.isTrigger) {
+ if (options.isTrigger && !Utils.getUrlState.isGlossaryTermsListPage()) {
this.triggerUrl();
}
},
@@ -590,7 +590,16 @@ define(['require',
} else if (type == that.viewType) {
if (data && data.event && data.event.skipTrigger) {
return;
- } else if (that.glossary.selectedItem.guid !== data.node.original.guid) {
+ }
+ var onTermsListPage = Utils.getUrlState.isGlossaryTermsListPage();
+ var isUserSelection = !!(data && data.event);
+ if (onTermsListPage && !isUserSelection) {
+ that.glossary.selectedItem = data.node.original;
+ return;
+ }
+ var selectedGuid = that.glossary.selectedItem && that.glossary.selectedItem.guid;
+ var clickedGuid = data.node.original.guid;
+ if (onTermsListPage || selectedGuid !== clickedGuid) {
that.glossary.selectedItem = data.node.original;
that.triggerUrl();
}
@@ -639,7 +648,7 @@ define(['require',
}
- if (Utils.getUrlState.isGlossaryTab()) {
+ if (Utils.getUrlState.isGlossaryTab() && !Utils.getUrlState.isGlossaryTermsListPage()) {
this.triggerUrl();
}
this.glossaryCollection.trigger("render:done");
@@ -877,6 +886,28 @@ define(['require',
isGlossary: true
});
});
+ },
+ closeGlossaryActionsDropdown: function(e) {
+ var $dropdown = e && e.currentTarget
+ ? $(e.currentTarget).closest('.dropdown')
+ : this.$('.dropdown');
+ $dropdown.removeClass('open');
+ $dropdown.find('.dropdown-toggle').attr('aria-expanded', 'false');
+ },
+ onExportGlossary: function(e) {
+ if (e) {
+ e.preventDefault();
+ e.stopPropagation();
+ }
+ this.closeGlossaryActionsDropdown(e);
+ if (Utils.getUrlState.isGlossaryTermsListPage()) {
+ return;
+ }
+ Utils.setUrl({
+ url: '#!/glossary/terms-list',
+ trigger: true,
+ updateTabState: true
+ });
}
});
return GlossaryLayoutView;
diff --git a/dashboardv2/public/js/views/glossary/GlossaryTermsListLayoutView.js b/dashboardv2/public/js/views/glossary/GlossaryTermsListLayoutView.js
new file mode 100644
index 000000000..652139faa
--- /dev/null
+++ b/dashboardv2/public/js/views/glossary/GlossaryTermsListLayoutView.js
@@ -0,0 +1,582 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+define(['require',
+ 'backbone',
+ 'hbs!tmpl/glossary/GlossaryTermsListLayoutView_tmpl',
+ 'utils/GlossaryExport',
+ 'utils/CommonViewFunction',
+ 'utils/Enums',
+ 'utils/Messages',
+ 'utils/Utils'
+], function(require, Backbone, GlossaryTermsListLayoutViewTmpl, GlossaryExport, CommonViewFunction, Enums, Messages, Utils) {
+ 'use strict';
+
+ var FILTER_DEBOUNCE_MS = 400;
+
+ var GlossaryTermsListLayoutView = Backbone.Marionette.LayoutView.extend({
+ _viewName: 'GlossaryTermsListLayoutView',
+
+ template: GlossaryTermsListLayoutViewTmpl,
+
+ regions: {
+ RGlossaryTermsTableLayoutView: '#r_glossaryTermsTableLayoutView'
+ },
+
+ ui: {
+ refreshButton: "[data-id='refreshGlossaryTermsList']",
+ downloadButton: "[data-id='downloadGlossaryTermsList']",
+ downloadCsv: "[data-id='downloadGlossaryCsv']",
+ downloadXlsx: "[data-id='downloadGlossaryXlsx']",
+ filterGlossary: "[data-id='filterGlossary']",
+ filterRecordType: "[data-id='filterRecordType']",
+ filterStatus: "[data-id='filterStatus']",
+ filterSearchText: "[data-id='filterSearchText']",
+ tagClick: '[data-id="tagClick"]',
+ addTag: '[data-id="addTag"]'
+ },
+
+ events: function() {
+ var events = {},
+ that = this;
+ events['click ' + this.ui.refreshButton] = 'onRefresh';
+ events['click ' + this.ui.downloadCsv] = 'onDownloadCsv';
+ events['click ' + this.ui.downloadXlsx] = 'onDownloadXlsx';
+ events['change ' + this.ui.filterGlossary] = 'onFilterChange';
+ events['change ' + this.ui.filterRecordType] = 'onFilterChange';
+ events['change ' + this.ui.filterStatus] = 'onFilterChange';
+ events['keyup ' + this.ui.filterSearchText] = 'onSearchTextChange';
+ events['click ' + this.ui.tagClick] = function(e) {
+ var scope = $(e.currentTarget);
+ if (e.target.nodeName.toLocaleLowerCase() === 'i') {
+ that.onClickTagCross(e);
+ } else {
+ Utils.setUrl({
+ url: '#!/tag/tagAttribute/' + scope.text().split('@')[0],
+ mergeBrowserUrl: false,
+ trigger: true
+ });
+ }
+ };
+ events['click ' + this.ui.addTag] = 'onClickAddTag';
+ return events;
+ },
+
+ initialize: function(options) {
+ _.extend(this, _.pick(options, 'glossaryCollection', 'classificationDefCollection', 'enumDefCollection', 'searchVent'));
+ this.filters = GlossaryExport.createDefaultFilters();
+ this.limit = GlossaryExport.SEARCH_DEFAULTS.limit;
+ this.offset = 0;
+ this.totalCount = 0;
+ this.isDownloading = false;
+ this.isFetching = false;
+ this.fetchSequence = 0;
+ this.sortBy = GlossaryExport.SEARCH_DEFAULTS.sortBy;
+ this.sortOrder = GlossaryExport.SEARCH_DEFAULTS.sortOrder;
+ this.debounceTimer = null;
+ this.tableCollection = new Backbone.Collection();
+ this.tableCollection.state = {
+ totalRecords: 0,
+ pageSize: this.limit,
+ currentPage: 0
+ };
+ this.tableCollection.queryParams = {
+ limit: this.limit,
+ offset: this.offset
+ };
+ this.commonTableOptions = {
+ collection: this.tableCollection,
+ clientAtlasPagination: true,
+ includePagination: false,
+ includeAtlasPagination: true,
+ includeFooterRecords: true,
+ includeColumnManager: false,
+ includeOrderAbleColumns: false,
+ includeSizeAbleColumns: false,
+ includeTableLoader: true,
+ includeAtlasPageSize: true,
+ includeAtlasTableSorting: false,
+ atlasShowLoaderBeforeFetch: this.showFetchLoader.bind(this),
+ atlasPaginationOpts: {
+ limit: this.limit,
+ offset: this.offset,
+ fetchCollection: this.fetchCollection.bind(this),
+ atlasApproximateDatasetTotal: this.getApproximateTotal.bind(this)
+ },
+ gridOpts: {
+ emptyText: 'No rows match the current filters.',
+ className: 'table table-hover backgrid table-quickMenu colSort'
+ },
+ filterOpts: {},
+ paginatorOpts: {}
+ };
+ },
+
+ onRender: function() {
+ var that = this;
+ if (this.glossaryCollection && !this.glossaryCollection.fullCollection.length) {
+ this.glossaryCollection.fetch({
+ reset: true,
+ success: function() {
+ that.populateGlossaryFilter();
+ }
+ });
+ } else {
+ this.populateGlossaryFilter();
+ }
+ this.renderTableLayoutView();
+ },
+
+ getApproximateTotal: function() {
+ return this.totalCount;
+ },
+
+ getGlossaryGuidByName: function() {
+ return GlossaryExport.buildGlossaryGuidByName(this.glossaryCollection);
+ },
+
+ populateGlossaryFilter: function() {
+ var $select = this.ui.filterGlossary;
+ $select.find('option:not(:first)').remove();
+ if (!this.glossaryCollection || !this.glossaryCollection.fullCollection) {
+ return;
+ }
+ var names = this.glossaryCollection.fullCollection.map(function(model) {
+ return model.get('name');
+ });
+ names = _.sortBy(_.compact(names), function(name) {
+ return name.toLowerCase();
+ });
+ _.each(names, function(name) {
+ $select.append($('<option></option>').attr('value', name).text(name));
+ });
+ },
+
+ readFiltersFromUi: function() {
+ this.filters.glossaryName = this.ui.filterGlossary.val() || '';
+ this.filters.recordType = this.ui.filterRecordType.val() || 'all';
+ this.filters.statusFilter = this.ui.filterStatus.val() || '';
+ this.filters.searchText = this.ui.filterSearchText.val() || '';
+ },
+
+ onFilterChange: function() {
+ this.readFiltersFromUi();
+ this.offset = 0;
+ this.fetchCollection({ fromUrl: true, filterChange: true });
+ },
+
+ onSearchTextChange: function() {
+ var that = this;
+ this.readFiltersFromUi();
+ if (this.debounceTimer) {
+ clearTimeout(this.debounceTimer);
+ }
+ this.debounceTimer = setTimeout(function() {
+ that.offset = 0;
+ that.fetchCollection({ fromUrl: true, filterChange: true });
+ }, FILTER_DEBOUNCE_MS);
+ },
+
+ onRefresh: function() {
+ this.fetchCollection({ fromUrl: true, refresh: true });
+ },
+
+ mapColumnToSortBy: function(columnName) {
+ var sortMap = {
+ glossaryName: 'glossaryName',
+ name: 'name',
+ recordType: 'recordType',
+ status: 'status'
+ };
+ return sortMap[columnName] || 'name';
+ },
+
+ createSortableHeaderCell: function() {
+ var that = this;
+ return Backgrid.HeaderCell.extend({
+ onClick: function(e) {
+ e.preventDefault();
+ var column = this.column;
+ if (!column.get('sortable')) {
+ return;
+ }
+ var columnName = column.get('name');
+ var direction = 'ascending';
+ if (that.sortBy === that.mapColumnToSortBy(columnName) && that.sortOrder === 'ASCENDING') {
+ direction = 'descending';
+ }
+ that.sortBy = that.mapColumnToSortBy(columnName);
+ that.sortOrder = direction === 'ascending' ? 'ASCENDING' : 'DESCENDING';
+ that.offset = 0;
+ if (that.tableLayout && that.tableLayout.columns) {
+ that.tableLayout.columns.each(function(col) {
+ col.set('direction', col.get('name') === columnName ? direction : null);
+ });
+ }
+ that.fetchCollection({ fromUrl: true, sortChange: true });
+ }
+ });
+ },
+
+ showFetchLoader: function(options) {
+ options = options || {};
+ this.isFetching = true;
+ this.$('.glossary-terms-filters').addClass('is-loading');
+ if (this.tableLayout) {
+ if (this.tableLayout.setAtlasPaginationBusy) {
+ var navHint = options.next ? 'next' : (options.previous ? 'prev' : 'both');
+ this.tableLayout.setAtlasPaginationBusy(true, navHint);
+ }
+ this.tableLayout.$('div[data-id="r_tableSpinner"]').addClass('show');
+ }
+ this.ui.filterGlossary.prop('disabled', true);
+ this.ui.filterRecordType.prop('disabled', true);
+ this.ui.filterStatus.prop('disabled', true);
+ this.ui.filterSearchText.prop('disabled', true);
+ this.ui.refreshButton.attr('disabled', true);
+ this.ui.downloadButton.attr('disabled', true);
+ },
+
+ hideFetchLoader: function() {
+ this.isFetching = false;
+ this.$('.glossary-terms-filters').removeClass('is-loading');
+ if (this.tableLayout) {
+ this.tableLayout.$('div[data-id="r_tableSpinner"]').removeClass('show');
+ if (this.tableLayout.setAtlasPaginationBusy) {
+ this.tableLayout.setAtlasPaginationBusy(false);
+ }
+ }
+ this.ui.filterGlossary.prop('disabled', false);
+ this.ui.filterRecordType.prop('disabled', false);
+ this.ui.filterStatus.prop('disabled', false);
+ this.ui.filterSearchText.prop('disabled', false);
+ this.ui.refreshButton.attr('disabled', false);
+ this.ui.downloadButton.attr('disabled', false);
+ },
+
+ completeFetch: function(result, options, fetchId) {
+ if (fetchId !== this.fetchSequence) {
+ return;
+ }
+ this.totalCount = result.totalCount;
+ this.tableCollection.state.totalRecords = result.totalCount;
+ this.tableCollection.state.pageSize = this.limit;
+ this.tableCollection.state.currentPage = Math.floor(this.offset / this.limit);
+ this.tableCollection.reset(result.rows);
+ this.tableCollection.trigger('sync');
+ this.ui.downloadButton.attr('disabled', this.totalCount === 0 || this.isDownloading);
+ this.hideFetchLoader();
+ if (this.tableLayout) {
+ this.tableLayout.trigger('grid:refresh');
+ if (this.tableLayout.renderAtlasPagination) {
+ this.tableLayout.renderAtlasPagination(options || {});
+ }
+ }
+ },
+
+ failFetch: function(xhr, fetchId) {
+ if (fetchId !== this.fetchSequence) {
+ return;
+ }
+ this.totalCount = 0;
+ this.tableCollection.state.totalRecords = 0;
+ this.tableCollection.reset([]);
+ this.tableCollection.trigger('error');
+ this.ui.downloadButton.attr('disabled', true);
+ this.hideFetchLoader();
+ var message = 'Failed to load glossary terms';
+ if (xhr && xhr.responseJSON && xhr.responseJSON.errorMessage) {
+ message = xhr.responseJSON.errorMessage;
+ }
+ Utils.notifyError({ content: message });
+ },
+
+ onDownloadCsv: function(e) {
+ if (e) {
+ e.preventDefault();
+ }
+ this.onDownload('CSV');
+ },
+
+ onDownloadXlsx: function(e) {
+ if (e) {
+ e.preventDefault();
+ }
+ this.onDownload('XLSX');
+ },
+
+ onDownload: function(format) {
+ var that = this;
+ if (this.isDownloading || this.totalCount === 0) {
+ return;
+ }
+ this.isDownloading = true;
+ this.ui.downloadButton.attr('disabled', true);
+ GlossaryExport.requestExportDownload(this.filters, this.getGlossaryGuidByName(), format || 'CSV').done(function() {
+ Utils.notifySuccess({
+ content: 'The current glossary export has been enqueued for download. You can access the file by clicking the download icon at the top of the page.'
+ });
+ }).fail(function(xhr) {
+ var message = 'Glossary export failed';
+ if (xhr && xhr.responseJSON && xhr.responseJSON.errorMessage) {
+ message = xhr.responseJSON.errorMessage;
+ }
+ Utils.notifyError({ content: message });
+ }).always(function() {
+ that.isDownloading = false;
+ that.ui.downloadButton.attr('disabled', that.totalCount === 0);
+ });
+ },
+
+ getTagList: function(guid) {
+ var model = this.tableCollection.find(function(item) {
+ return item.get('guid') === guid;
+ });
+ if (!model) {
+ return [];
+ }
+ var obj = model.toJSON();
+ return _.compact(_.map(obj.classifications, function(val) {
+ if (val.entityGuid === guid) {
+ return val.typeName;
+ }
+ }));
+ },
+
+ addTagModalView: function(guid) {
+ var that = this;
+ require(['views/tag/AddTagModalView'], function(AddTagModalView) {
+ var view = new AddTagModalView({
+ guid: guid,
+ callback: function() {
+ that.fetchCollection({ fromUrl: true, refresh: true });
+ if (that.searchVent) {
+ that.searchVent.trigger('entityList:refresh');
+ }
+ },
+ tagList: that.getTagList(guid),
+ showLoader: that.showFetchLoader.bind(that),
+ hideLoader: that.hideFetchLoader.bind(that),
+ collection: that.classificationDefCollection,
+ enumDefCollection: that.enumDefCollection
+ });
+ });
+ },
+
+ onClickAddTag: function(e) {
+ var guid = this.$(e.currentTarget).data('guid');
+ if (guid) {
+ this.addTagModalView(guid);
+ }
+ },
+
+ onClickTagCross: function(e) {
+ var that = this,
+ tagName = $(e.target).data('name'),
+ guid = $(e.target).data('guid'),
+ entityGuid = $(e.target).data('entityguid'),
+ assetName = $(e.target).data('assetname');
+ CommonViewFunction.deleteTag({
+ tagName: tagName,
+ guid: guid,
+ associatedGuid: guid !== entityGuid ? entityGuid : null,
+ msg: "<div class='ellipsis-with-margin'>Remove: " + "<b>" + _.escape(tagName) + "</b> assignment from <b>" + _.escape(assetName) + " ?</b></div>",
+ titleMessage: Messages.removeTag,
+ okText: 'Remove',
+ showLoader: that.showFetchLoader.bind(that),
+ hideLoader: that.hideFetchLoader.bind(that),
+ callback: function() {
+ that.fetchCollection({ fromUrl: true, refresh: true });
+ if (that.searchVent) {
+ that.searchVent.trigger('entityList:refresh');
+ }
+ }
+ });
+ },
+
+ formatClassificationsCell: function(model) {
+ var row = model.toJSON();
+ if (row.recordType !== 'Term' || !row.guid || !this.classificationDefCollection) {
+ return GlossaryExport.formatClassificationsHtml(row.classifications);
+ }
+ var obj = {
+ guid: row.guid,
+ status: row.status,
+ classifications: row.classifications || []
+ };
+ if (obj.status && Enums.entityStateReadOnly[obj.status]) {
+ return '<div class="readOnly">' + CommonViewFunction.tagForTable(obj, this.classificationDefCollection) + '</div>';
+ }
+ return CommonViewFunction.tagForTable(obj, this.classificationDefCollection);
+ },
+
+ fetchCollection: function(options) {
+ var that = this;
+ options = options || {};
+ this.fetchSequence += 1;
+ var fetchId = this.fetchSequence;
+ this.showFetchLoader(options);
+ this.readFiltersFromUi();
+ if (_.isFinite(options.offset)) {
+ this.offset = options.offset;
+ } else if (this.tableLayout) {
+ this.offset = this.tableLayout.offset || this.offset;
+ this.limit = this.tableLayout.limit || this.limit;
+ }
+ if (options.filterChange || options.sortChange || options.refresh) {
+ this.offset = options.offset || 0;
+ if (this.tableLayout) {
+ this.tableLayout.offset = this.offset;
+ }
+ }
+ var pageIndex = Math.floor(this.offset / this.limit);
+ var request = GlossaryExport.buildSearchRequest(
+ this.filters,
+ pageIndex,
+ this.limit,
+ this.getGlossaryGuidByName(),
+ {
+ sortBy: this.sortBy,
+ sortOrder: this.sortOrder
+ }
+ );
+ this.tableCollection.trigger('request');
+ GlossaryExport.fetchSearchPage(request).done(function(result) {
+ that.completeFetch(result, options, fetchId);
+ }).fail(function(xhr) {
+ that.failFetch(xhr, fetchId);
+ });
+ },
+
+ renderTableLayoutView: function() {
+ var that = this;
+ if (this._tableLayoutLoading) {
+ return;
+ }
+ this._tableLayoutLoading = true;
+ require(['utils/TableLayout'], function(TableLayout) {
+ var columns = new Backgrid.Columns(that.getColumns());
+ that.tableLayout = new TableLayout(_.extend({}, that.commonTableOptions, {
+ columns: columns
+ }));
+ that.RGlossaryTermsTableLayoutView.show(that.tableLayout);
+ _.extend(that.tableCollection.queryParams, {
+ limit: that.limit,
+ offset: that.offset
+ });
+ that._tableLayoutLoading = false;
+ that.fetchCollection({ fromUrl: true });
+ });
+ },
+
+ getColumns: function() {
+ var that = this;
+ var sortableHeaderCell = this.createSortableHeaderCell();
+ var colDefs = {
+ glossaryName: {
+ label: 'Glossary Name',
+ cell: 'string',
+ editable: false,
+ sortable: true,
+ headerCell: sortableHeaderCell,
+ className: 'searchTableName'
+ },
+ name: {
+ label: 'Name',
+ cell: 'html',
+ editable: false,
+ sortable: true,
+ headerCell: sortableHeaderCell,
+ className: 'searchTableName',
+ formatter: _.extend({}, Backgrid.CellFormatter.prototype, {
+ fromRaw: function(rawValue, model) {
+ return GlossaryExport.formatNameHtml(model.toJSON());
+ }
+ })
+ },
+ recordType: {
+ label: 'Record Type',
+ cell: 'string',
+ editable: false,
+ sortable: true,
+ headerCell: sortableHeaderCell
+ },
+ shortDescription: {
+ label: 'Short Description',
+ cell: 'string',
+ editable: false,
+ sortable: false,
+ className: 'searchTableName'
+ },
+ longDescription: {
+ label: 'Long Description',
+ cell: 'string',
+ editable: false,
+ sortable: false,
+ className: 'searchTableName'
+ },
+ classifications: {
+ label: 'Classifications',
+ cell: 'html',
+ editable: false,
+ sortable: false,
+ formatter: _.extend({}, Backgrid.CellFormatter.prototype, {
+ fromRaw: function(rawValue, model) {
+ return that.formatClassificationsCell(model);
+ }
+ })
+ },
+ customAttributes: {
+ label: 'Custom Attributes',
+ cell: 'html',
+ editable: false,
+ sortable: false,
+ className: 'searchTableName',
+ formatter: _.extend({}, Backgrid.CellFormatter.prototype, {
+ fromRaw: function(rawValue, model) {
+ var attrs = model.get('customAttributes');
+ var display = GlossaryExport.formatCustomAttributesForDisplay(attrs);
+ if (!display) {
+ return '';
+ }
+ var tooltip = _.escape(GlossaryExport.formatCustomAttributesForTooltip(attrs));
+ return '<span class="entity-name" title="' + tooltip + '">' + _.escape(display) + '</span>';
+ }
+ })
+ },
+ status: {
+ label: 'Status',
+ cell: 'html',
+ editable: false,
+ sortable: true,
+ headerCell: sortableHeaderCell,
+ formatter: _.extend({}, Backgrid.CellFormatter.prototype, {
+ fromRaw: function(rawValue) {
+ return GlossaryExport.formatStatusHtml(rawValue);
+ }
+ })
+ }
+ };
+ return _.map(colDefs, function(def, key) {
+ return _.extend({ name: key }, def);
+ });
+ }
+ });
+
+ return GlossaryTermsListLayoutView;
+});
diff --git a/dashboardv2/public/js/views/site/DownloadSearchResultLayoutView.js b/dashboardv2/public/js/views/site/DownloadSearchResultLayoutView.js
index 3516d7d81..95337116e 100644
--- a/dashboardv2/public/js/views/site/DownloadSearchResultLayoutView.js
+++ b/dashboardv2/public/js/views/site/DownloadSearchResultLayoutView.js
@@ -53,13 +53,9 @@ define(['require',
events['click ' + this.ui.closeDownloadsButton] = "onHideDownloads";
events['click ' + this.ui.refreshDownloadsButton] = "onRefreshDownloads";
events['change ' + this.ui.toggleDownloads] = function(e) {
- this.showCompletedDownloads = !this.showCompletedDownloads;
- if(this.showCompletedDownloads){
- this.ui.toggleDownloads.attr("data-original-title", "Display All Files");
- } else {
- this.ui.toggleDownloads.attr("data-original-title", "Display Available Files");
- }
- this.genrateDownloadList();
+ this.showAllDownloads = e.currentTarget.checked;
+ this.updateDownloadToggleTooltip();
+ this.generateDownloadList();
}
return events;
},
@@ -70,8 +66,10 @@ define(['require',
initialize: function(options) {
this.options = options;
this.showDownloads = new VDownloadList();
- this.showCompletedDownloads = true;
+ this.showAllDownloads = true;
this.downloadsData = [];
+ this.isDownloadsPanelOpen = false;
+ this.onDocumentClickBound = _.bind(this.onDocumentClick, this);
this.bindEvents();
},
bindEvents: function() {
@@ -80,51 +78,92 @@ define(['require',
});
},
onRender: function() {
- this.ui.toggleDownloads.attr("data-original-title", "Display All Files");
+ this.ui.toggleDownloads.prop('checked', this.showAllDownloads);
+ this.updateDownloadToggleTooltip();
+ },
+ updateDownloadToggleTooltip: function() {
+ var tooltip = this.showAllDownloads
+ ? "Showing all files (including in progress)"
+ : "Showing completed files only";
+ this.ui.toggleDownloads.attr("data-original-title", tooltip);
},
initializeValues: function() {},
fetchDownloadsData: function() {
- var that = this;
- var apiObj = {
- success: function(data, response) {
- that.downloadsData = data.searchDownloadRecords;
- that.genrateDownloadList();
- },
- complete: function() {
+ var that = this,
+ merged = [],
+ pending = 2,
+ hadFailure = false;
+
+ var finishIfDone = function() {
+ pending -= 1;
+ if (pending === 0) {
+ that.downloadsData = merged;
+ that.generateDownloadList();
that.hideLoader();
+ if (hadFailure && merged.length === 0) {
+ Utils.notifyError({ content: 'Failed to fetch download records' });
+ }
+ }
+ };
+
+ this.showDownloads.getDownloadsList({
+ success: function(data) {
+ var records = (data && data.searchDownloadRecords) || [];
+ _.each(records, function(record) {
+ merged.push(_.extend({}, record, { source: 'search' }));
+ });
+ },
+ error: function() {
+ hadFailure = true;
},
+ complete: finishIfDone,
reset: true
- }
- this.showDownloads.getDownloadsList(apiObj);
+ });
+
+ this.showDownloads.getGlossaryDownloadsList({
+ success: function(data) {
+ // Backend reuses searchDownloadRecords for glossary export status.
+ var records = (data && (data.glossaryDownloadRecords || data.searchDownloadRecords)) || [];
+ _.each(records, function(record) {
+ merged.push(_.extend({}, record, { source: 'glossary' }));
+ });
+ },
+ error: function() {
+ hadFailure = true;
+ },
+ complete: finishIfDone
+ });
},
- genrateDownloadList: function() {
+ // Keep timestamp parsing/sorting aligned with dashboard/src/utils/downloadRecords.ts
+ generateDownloadList: function() {
var that = this,
stateIconEl = "",
completedDownloads = "",
allDownloads = "",
downloadList = "",
- sortedData = _.sortBy(this.downloadsData, function(obj){
- return obj.createdTime;
- }).reverse();
+ sortedData = that.sortDownloadRecordsByLatest(this.downloadsData);
if (sortedData.length) {
_.each(sortedData, function(obj) {
+ var downloadUrl = obj.source === 'glossary'
+ ? UrlLinks.glossaryDownloadFileUrl(obj.fileName)
+ : UrlLinks.downloadSearchResultsFileUrl(obj.fileName);
if (obj.status === "PENDING") {
stateIconEl = "<span class='download-state'><i class='fa fa-refresh fa-spin-custom' aria-hidden='true'></i></span>";
} else {
- stateIconEl = "<span class='download-state'><a href=" + UrlLinks.downloadSearchResultsFileUrl(obj.fileName) + "><i class='fa fa-arrow-circle-o-down fa-lg' aria-hidden='true'></i></a></span>";
- completedDownloads += "<li><i class='fa fa-file-excel-o fa-lg' aria-hidden='true'></i><span class='file-name'>" + obj.fileName + "</span>" + stateIconEl + "</li>"
+ stateIconEl = "<span class='download-state'><a href='" + downloadUrl + "'><i class='fa fa-arrow-circle-o-down fa-lg' aria-hidden='true'></i></a></span>";
+ completedDownloads += "<li><i class='fa fa-file-excel-o fa-lg' aria-hidden='true'></i><span class='file-name'>" + obj.fileName + "</span>" + stateIconEl + "</li>";
}
allDownloads += "<li><i class='fa fa-file-excel-o fa-lg' aria-hidden='true'></i><span class='file-name'>" + obj.fileName + "</span>" + stateIconEl + "</li>";
});
} else {
- completedDownloads = allDownloads = "<li class='text-center' style='border-bottom:none'>No Data Found</li>"
+ completedDownloads = allDownloads = "<li class='text-center download-list-empty'>No Data Found</li>";
}
if (this.downloadsData.length && completedDownloads === "") {
- completedDownloads = "<li class='text-center' style='border-bottom:none'>No Data Found</li>";
+ completedDownloads = "<li class='text-center download-list-empty'>No Data Found</li>";
}
- downloadList = this.showCompletedDownloads ? completedDownloads : allDownloads;
+ downloadList = this.showAllDownloads ? allDownloads : completedDownloads;
this.ui.downloadListContainer.empty();
this.ui.downloadListContainer.html(downloadList);
},
@@ -138,16 +177,81 @@ define(['require',
this.fetchDownloadsData();
this.showLoader();
this.ui.downloadsPanel.css("right", "20px");
+ if (!this.isDownloadsPanelOpen) {
+ this.isDownloadsPanelOpen = true;
+ var that = this;
+ setTimeout(function() {
+ $(document).on('click.downloadsPanel', that.onDocumentClickBound);
+ }, 0);
+ }
},
onHideDownloads: function() {
- this.ui.downloadsPanel.css("right", "-700px")
+ this.ui.downloadsPanel.css("right", "-700px");
+ if (this.isDownloadsPanelOpen) {
+ this.isDownloadsPanelOpen = false;
+ $(document).off('click.downloadsPanel');
+ }
+ },
+ onDocumentClick: function(e) {
+ var $target = $(e.target);
+ if ($target.closest('.downloads-panel').length) {
+ return;
+ }
+ if ($target.closest('[data-id="showDownloads"]').length) {
+ return;
+ }
+ this.onHideDownloads();
+ },
+ onBeforeDestroy: function() {
+ $(document).off('click.downloadsPanel');
},
showLoader: function() {
this.$('.downloadListLoader').show();
},
hideLoader: function(options) {
this.$('.downloadListLoader').hide();
+ },
+ parseCreatedTime: function(createdTime) {
+ if (createdTime === undefined || createdTime === null || createdTime === '') {
+ return null;
+ }
+
+ if (typeof createdTime === 'number' && isFinite(createdTime)) {
+ return createdTime;
+ }
+
+ var parsed = Date.parse(String(createdTime));
+ return isNaN(parsed) ? null : parsed;
+ },
+ parseTimestampFromFileName: function(fileName) {
+ if (!fileName) {
+ return null;
+ }
+
+ var match = fileName.match(/(\d{4}-\d{2}-\d{2})_(\d{2})-(\d{2})-(\d{2}(?:\.\d{3})?)/);
+ if (!match) {
+ return null;
+ }
+
+ var normalized = match[1] + 'T' + match[2] + ':' + match[3] + ':' + match[4];
+ var parsed = Date.parse(normalized);
+ return isNaN(parsed) ? null : parsed;
+ },
+ resolveDownloadRecordTime: function(record) {
+ var fromApi = this.parseCreatedTime(record.createdTime);
+ if (fromApi !== null) {
+ return fromApi;
+ }
+
+ var fromFileName = this.parseTimestampFromFileName(record.fileName);
+ return fromFileName !== null ? fromFileName : 0;
+ },
+ sortDownloadRecordsByLatest: function(records) {
+ var that = this;
+ return _.sortBy(records, function(record) {
+ return -that.resolveDownloadRecordTime(record);
+ });
}
});
return DownloadSearchResultLayoutView;
-});
\ No newline at end of file
+});