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/09/20 07:32:24 UTC
(atlas) 01/01: ATLAS-5411: ATLAS-5412: ATLAS-5369: Atlas UI: React UI Audit tab show deleted entity references with Classic UI styling, Search Button, Businessmetada options as dropdown
This is an automated email from the ASF dual-hosted git repository.
pawarprasad123 pushed a commit to branch ATLAS-5411_UI_fix
in repository https://gitbox.apache.org/repos/asf/atlas.git
commit 14d8b26a87a5d2399bc300d3941521f9d1075006
Author: Prasad Pawar <pr...@gmail.com>
AuthorDate: Sun Sep 20 13:01:51 2026 +0530
ATLAS-5411: ATLAS-5412: ATLAS-5369: Atlas UI: React UI Audit tab show deleted entity references with Classic UI styling, Search Button, Businessmetada options as dropdown
---
dashboard/src/components/AuditEntityRefLink.tsx | 86 ++++
dashboard/src/components/ExtractObject.tsx | 254 +++++++++++
.../src/components/GlobalSearch/QuickSearch.tsx | 29 +-
.../GlobalSearch/__tests__/QuickSearch.test.tsx | 92 +++-
.../__tests__/AuditEntityRefLink.test.tsx | 241 +++++++++++
.../components/__tests__/commonComponents.test.tsx | 184 +++++++-
.../components/__tests__/entityRefUtils.test.ts | 73 ++++
dashboard/src/components/commonComponents.tsx | 251 ++---------
dashboard/src/components/entityRefRenderers.tsx | 51 +++
dashboard/src/components/entityRefUtils.ts | 35 ++
dashboard/src/styles/globalSearch.scss | 4 +
dashboard/src/styles/propertiesTab.scss | 94 ++++
dashboard/src/styles/table.scss | 4 +
dashboard/src/utils/Utils.ts | 15 +
dashboard/src/utils/__tests__/Utils.test.ts | 26 ++
.../src/utils/__tests__/enumTypeUtils.test.ts | 67 +++
dashboard/src/utils/enumTypeUtils.ts | 23 +
.../EntityDetailTabs/AttributeProperties.tsx | 3 +-
.../PropertiesTab/BMAttributes.tsx | 436 ++++++++++---------
.../PropertiesTab/BMAttributesFields.tsx | 385 +++++++++--------
.../BMAttributes.enum.integration.test.tsx | 244 +++++++++++
.../PropertiesTab/__tests__/BMAttributes.test.tsx | 465 ++++++++++++++++++++
.../__tests__/BMAttributesFields.test.tsx | 475 +++++++++++++++++++++
.../__tests__/AttributeProperties.test.tsx | 47 +-
.../__tests__/AuditTableDetails.test.tsx | 33 +-
dashboardv2/public/css/scss/business-metadata.scss | 8 +
.../views/entity/EntityBusinessMetaDataItemView.js | 61 ++-
27 files changed, 3044 insertions(+), 642 deletions(-)
diff --git a/dashboard/src/components/AuditEntityRefLink.tsx b/dashboard/src/components/AuditEntityRefLink.tsx
new file mode 100644
index 000000000..981a59d04
--- /dev/null
+++ b/dashboard/src/components/AuditEntityRefLink.tsx
@@ -0,0 +1,86 @@
+/*
+ * 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 { useEffect, useMemo, useState } from "react";
+import { getDetailPageData } from "../api/apiMethods/detailpageApiMethod";
+import { ExtractObject } from "./ExtractObject";
+import { getEntityRefStatus, mergeReferredEntity } from "./entityRefUtils";
+
+type AuditEntityRefLinkProps = {
+ entityRef: Record<string, unknown>;
+ referredEntities?: Record<string, unknown>;
+ properties?: string;
+};
+
+/**
+ * Classic UI parity for audit relationship refs: merge page referredEntities,
+ * then fetch entity header for current status when not already known.
+ */
+const AuditEntityRefLink = ({
+ entityRef,
+ referredEntities,
+ properties
+}: AuditEntityRefLinkProps) => {
+ const mergedRef = useMemo(
+ () => mergeReferredEntity(entityRef, referredEntities),
+ [entityRef, referredEntities]
+ );
+ const [resolvedRef, setResolvedRef] = useState(mergedRef);
+ const guid = mergedRef?.guid as string | undefined;
+ const mergedStatus = getEntityRefStatus(mergedRef);
+
+ useEffect(() => {
+ setResolvedRef(mergedRef);
+ }, [mergedRef]);
+
+ useEffect(() => {
+ if (!guid || mergedStatus) {
+ return;
+ }
+
+ let cancelled = false;
+ getDetailPageData(guid, {}, "headers")
+ .then(({ data }) => {
+ if (cancelled || !data) {
+ return;
+ }
+ setResolvedRef((prev) => ({
+ ...prev,
+ ...data,
+ status: data.status || data.entityStatus,
+ entityStatus: data.entityStatus || data.status
+ }));
+ })
+ .catch(() => {
+ // Header lookup is best-effort; keep snapshot rendering on failure.
+ });
+
+ return () => {
+ cancelled = true;
+ };
+ }, [guid, mergedStatus]);
+
+ return (
+ <ExtractObject
+ keyValue={resolvedRef}
+ properties={properties}
+ skipHeaderFetch={true}
+ />
+ );
+};
+
+export default AuditEntityRefLink;
diff --git a/dashboard/src/components/ExtractObject.tsx b/dashboard/src/components/ExtractObject.tsx
new file mode 100644
index 000000000..1c5c26a35
--- /dev/null
+++ b/dashboard/src/components/ExtractObject.tsx
@@ -0,0 +1,254 @@
+/*
+ * 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 { IconButton } from "./muiComponents";
+import {
+ escapeHtml,
+ extractKeyValueFromEntity,
+ isArray,
+ isBoolean,
+ isEmpty,
+ isNumber,
+ isObject,
+ isString
+} from "../utils/Utils";
+import { JSONPrettyPrint, getValue } from "../utils/CommonViewFunction";
+import { useSelector } from "react-redux";
+import { entityStateReadOnly } from "../utils/Enum";
+import { Link, useLocation } from "react-router-dom";
+import DeleteOutlineOutlinedIcon from "@mui/icons-material/DeleteOutlineOutlined";
+import { useRef, useState } from "react";
+import { getDetailPageData } from "../api/apiMethods/detailpageApiMethod";
+
+type EntityRefField = {
+ guid?: string;
+ name?: string;
+ status?: string;
+ entityStatus?: string;
+ state?: string;
+ id?: { state?: string };
+ typeName?: string;
+ attributes?: Record<string, unknown>;
+ values?: Record<string, unknown>;
+};
+
+type ExtractObjectProps = {
+ keyValue?: EntityRefField | EntityRefField[] | string | boolean | number | unknown[];
+ properties?: string;
+ skipHeaderFetch?: boolean;
+};
+
+type TypeHeaderEntry = {
+ name: string;
+ category?: string;
+};
+
+export const ExtractObject = (props: ExtractObjectProps) => {
+ const { skipHeaderFetch = false } = props;
+ const { typeHeaderData } = useSelector(
+ (state: { typeHeader: { typeHeaderData?: TypeHeaderEntry[] } }) =>
+ state.typeHeader
+ );
+ const location = useLocation();
+ const searchParams = new URLSearchParams(location.search);
+ const [headerData, setHeaderData] = useState<string>("");
+ const fetchedGuidsRef = useRef<Set<string>>(new Set());
+
+ const getGuid = (guid: string) => {
+ if (skipHeaderFetch || isEmpty(guid) || fetchedGuidsRef.current.has(guid)) {
+ return;
+ }
+ fetchedGuidsRef.current.add(guid);
+ getInputOutputValue(guid);
+ };
+
+ const getInputOutputValue = async (guid: string) => {
+ if (!isEmpty(guid)) {
+ try {
+ const { data: response } = await getDetailPageData(guid, {}, "headers");
+ const { name } = extractKeyValueFromEntity(response);
+ setHeaderData(name as string);
+ } catch {
+ // Error handled silently
+ }
+ }
+ };
+
+ const valueOfArray: string[] = [];
+ let keyValue = props.keyValue;
+ let nameVal = "";
+ let tempLink = "";
+ let deleteIcon = false;
+ let fetchVal = false;
+
+ if (!isArray(keyValue) && isObject(keyValue)) {
+ keyValue = [keyValue as EntityRefField];
+ }
+
+ const keyValueArray = (keyValue ?? []) as EntityRefField[];
+
+ for (let i = 0; i < keyValueArray.length; i++) {
+ const inputOutputField = keyValueArray[i];
+ const id = inputOutputField.guid;
+ const entityId = inputOutputField.id;
+ const idState = isObject(entityId) ? entityId?.state : undefined;
+ const status =
+ inputOutputField.status ||
+ inputOutputField.entityStatus ||
+ idState ||
+ inputOutputField.state;
+ const readOnly = entityStateReadOnly[status as keyof typeof entityStateReadOnly];
+
+ if (!inputOutputField.attributes && inputOutputField.values) {
+ inputOutputField.attributes = inputOutputField.values;
+ }
+ if (
+ isString(inputOutputField) ||
+ isBoolean(inputOutputField) ||
+ isNumber(inputOutputField)
+ ) {
+ const tempVarfor$check = String(inputOutputField);
+ if (tempVarfor$check.indexOf("$") == -1) {
+ const tmpVal = getValue(
+ inputOutputField as unknown as string | boolean | number
+ );
+
+ valueOfArray.push(
+ '<span class="json-string">' + escapeHtml(String(tmpVal)) + "</span>"
+ );
+ }
+ } else if (isObject(inputOutputField) && id == undefined) {
+ let attributesList: Record<string, unknown> = inputOutputField;
+ if (typeHeaderData && inputOutputField.typeName) {
+ const typeNameCategory = typeHeaderData.find(
+ (obj) => obj.name == inputOutputField.typeName
+ );
+
+ if (
+ attributesList?.attributes &&
+ typeNameCategory?.category === "STRUCT"
+ ) {
+ attributesList = attributesList.attributes as Record<string, unknown>;
+ }
+ }
+ valueOfArray.push(JSONPrettyPrint(attributesList) as string);
+ }
+
+ if (id && inputOutputField) {
+ const { name }: { name: string } = extractKeyValueFromEntity(
+ inputOutputField,
+ "",
+ "",
+ getGuid,
+ headerData
+ );
+ nameVal = name;
+ if (inputOutputField.typeName == "AtlasGlossaryTerm") {
+ tempLink = `/glossary/${id}`;
+ const keys = Array.from(searchParams.keys());
+ for (let j = 0; j < keys.length; j++) {
+ if (keys[j] != "searchType") {
+ searchParams.delete(keys[j]);
+ }
+ }
+ searchParams.set("guid", id);
+ searchParams.set("gtype", "term");
+ searchParams.set("viewType", "term");
+ fetchVal = true;
+ } else {
+ tempLink = `/detailPage/${id}`;
+ }
+ }
+
+ if (readOnly) {
+ if (!fetchVal) {
+ deleteIcon = true;
+ } else {
+ fetchVal = false;
+ }
+ }
+ }
+
+ return (
+ <>
+ {valueOfArray?.length > 0 ? (
+ props.properties != undefined ? (
+ <pre className="code-block fixed-height">
+ <code>
+ <span
+ dangerouslySetInnerHTML={{
+ __html: valueOfArray.join("")
+ }}
+ ></span>
+ </code>
+ </pre>
+ ) : (
+ <span
+ dangerouslySetInnerHTML={{
+ __html: valueOfArray.join("")
+ }}
+ ></span>
+ )
+ ) : (
+ <>
+ {tempLink != "" ? (
+ <>
+ <Link
+ className={`entity-name nav-link max-100 text-decoration-none ${
+ deleteIcon ? "entity-name-deleted" : "text-blue"
+ }`}
+ to={{
+ pathname: tempLink,
+ search: searchParams.toString() ? searchParams.toString() : ""
+ }}
+ style={{
+ display: "inline-block",
+ maxWidth: "100%",
+ textOverflow: "ellipsis",
+ overflow: "hidden",
+ whiteSpace: "nowrap",
+ verticalAlign: "bottom"
+ }}
+ title={nameVal}
+ >
+ {nameVal}
+ </Link>
+ {deleteIcon && (
+ <IconButton
+ aria-label="Deleted entity"
+ sx={{
+ display: "inline-flex",
+ position: "relative",
+ padding: "0",
+ marginLeft: "4px"
+ }}
+ >
+ <DeleteOutlineOutlinedIcon
+ className="delete-icon"
+ sx={{ fontSize: "1.25rem", height: "24px" }}
+ />
+ </IconButton>
+ )}
+ </>
+ ) : (
+ "N/A"
+ )}
+ </>
+ )}
+ </>
+ );
+};
diff --git a/dashboard/src/components/GlobalSearch/QuickSearch.tsx b/dashboard/src/components/GlobalSearch/QuickSearch.tsx
index f3f860f78..3933623ae 100644
--- a/dashboard/src/components/GlobalSearch/QuickSearch.tsx
+++ b/dashboard/src/components/GlobalSearch/QuickSearch.tsx
@@ -85,6 +85,8 @@ const SCOPE_LABELS: Record<QuickSearchScope, string> = {
businessMetadata: "Business Metadata"
};
+const hasValidSearchQuery = (value: string) => value.trim().length > 0;
+
const QuickSearch = () => {
const navigate = useNavigate();
const location = useLocation();
@@ -96,6 +98,8 @@ const QuickSearch = () => {
const [loading, setLoading] = useState<boolean>(false);
const [inputText, setInputText] = useState<string>("");
const [scope, setScope] = useState<QuickSearchScope>("default");
+ const trimmedQuery = useMemo(() => inputText.trim(), [inputText]);
+ const isSearchEnabled = hasValidSearchQuery(inputText);
const { typeHeaderData } = useAppSelector((state: any) => state.typeHeader);
const { metricsData } = useAppSelector((state: any) => state.metrics);
@@ -287,8 +291,7 @@ const QuickSearch = () => {
if (scope !== "default") {
return;
}
- const sanitizedQuery = queryValue || "*";
- searchParams.set("query", sanitizedQuery);
+ searchParams.set("query", queryValue);
searchParams.set("searchType", "basic");
navigate(
{
@@ -340,7 +343,10 @@ const QuickSearch = () => {
};
const handleSubmitSearch = () => {
- const q = inputText.trim();
+ const q = trimmedQuery;
+ if (!hasValidSearchQuery(inputText)) {
+ return;
+ }
if (scope !== "default") {
const activeOption = options.find((o) => o.title === q);
if (activeOption?.scoped) {
@@ -348,10 +354,6 @@ const QuickSearch = () => {
}
return;
}
- if (!q) {
- handleValues("*");
- return;
- }
const activeOption = options.find(
(o) => typeof o !== "string" && o.title === q
);
@@ -421,7 +423,9 @@ const QuickSearch = () => {
switch (code) {
case 13: {
e.preventDefault();
- handleSubmitSearch();
+ if (isSearchEnabled) {
+ handleSubmitSearch();
+ }
break;
}
case 9:
@@ -682,11 +686,18 @@ const QuickSearch = () => {
<CustomButton
variant="contained"
size="small"
+ className="global-search-submit-btn"
+ disabled={!isSearchEnabled}
sx={{
backgroundColor: "#4a90e2 !important",
color: "#fff !important",
textTransform: "none",
- fontWeight: 600
+ fontWeight: 600,
+ "&.Mui-disabled": {
+ backgroundColor: "#a8c8eb !important",
+ color: "#fff !important",
+ opacity: 0.7
+ }
}}
onClick={handleSubmitSearch}
aria-label="Run search"
diff --git a/dashboard/src/components/GlobalSearch/__tests__/QuickSearch.test.tsx b/dashboard/src/components/GlobalSearch/__tests__/QuickSearch.test.tsx
index 53118e3b7..3428c0f9f 100644
--- a/dashboard/src/components/GlobalSearch/__tests__/QuickSearch.test.tsx
+++ b/dashboard/src/components/GlobalSearch/__tests__/QuickSearch.test.tsx
@@ -45,8 +45,13 @@ afterAll(() => {
})
jest.mock('@components/muiComponents', () => ({
- CustomButton: ({ onClick, children }: any) => (
- <button data-testid="adv-btn" onClick={onClick}>
+ CustomButton: ({ onClick, children, disabled, 'aria-label': ariaLabel }: any) => (
+ <button
+ data-testid={ariaLabel === 'Run search' ? 'search-btn' : 'adv-btn'}
+ onClick={onClick}
+ disabled={disabled}
+ aria-label={ariaLabel}
+ >
{children}
</button>
)
@@ -506,12 +511,76 @@ describe('QuickSearch', () => {
mockExtractKeyValueFromEntity.mockReturnValue({ name: 'EntityName', found: true, key: 'k' })
})
+ describe('Search Button Validation', () => {
+ it('disables search button when input is empty', () => {
+ render(<QuickSearch />)
+
+ expect(screen.getByTestId('search-btn')).toBeDisabled()
+ })
+
+ it('enables search button when input has at least one character', () => {
+ render(<QuickSearch />)
+
+ const input = screen.getByTestId('autocomplete-input')
+ fireEvent.change(input, { target: { value: 'a' } })
+
+ expect(screen.getByTestId('search-btn')).not.toBeDisabled()
+ })
+
+ it('keeps search button disabled for whitespace-only input', () => {
+ render(<QuickSearch />)
+
+ const input = screen.getByTestId('autocomplete-input')
+ fireEvent.change(input, { target: { value: ' ' } })
+
+ expect(screen.getByTestId('search-btn')).toBeDisabled()
+ })
+
+ it('does not navigate when search button is clicked with empty input', () => {
+ render(<QuickSearch />)
+
+ fireEvent.click(screen.getByTestId('search-btn'))
+
+ expect(mockNavigate).not.toHaveBeenCalled()
+ })
+
+ it('navigates when search button is clicked with valid query', () => {
+ render(<QuickSearch />)
+
+ const input = screen.getByTestId('autocomplete-input')
+ fireEvent.change(input, { target: { value: 'my-query' } })
+ fireEvent.click(screen.getByTestId('search-btn'))
+
+ expect(mockNavigate).toHaveBeenCalledWith(
+ expect.objectContaining({
+ pathname: '/search/searchResult',
+ search: expect.stringContaining('query=my-query')
+ }),
+ { replace: true }
+ )
+ })
+
+ it('does not navigate on Enter when input is empty', () => {
+ render(<QuickSearch />)
+
+ const input = screen.getByTestId('autocomplete-input')
+ fireEvent.keyDown(input, {
+ keyCode: 13,
+ which: 13,
+ preventDefault: jest.fn()
+ })
+
+ expect(mockNavigate).not.toHaveBeenCalled()
+ })
+ })
+
describe('Component Rendering', () => {
it('renders autocomplete and advanced search button', () => {
render(<QuickSearch />)
expect(screen.getByTestId('autocomplete')).toBeTruthy()
- expect(screen.getAllByTestId('adv-btn').length).toBeGreaterThanOrEqual(1)
+ expect(screen.getByTestId('search-btn')).toBeTruthy()
+ expect(screen.getByTestId('adv-btn')).toBeTruthy()
})
it('renders search scope dropdown (Select All / entity / glossary …)', () => {
@@ -813,6 +882,7 @@ describe('QuickSearch', () => {
render(<QuickSearch />)
const input = screen.getByTestId('autocomplete-input')
+ fireEvent.change(input, { target: { value: 'search-query' } })
fireEvent.keyDown(input, {
keyCode: 13,
which: 13,
@@ -834,7 +904,7 @@ describe('QuickSearch', () => {
target: { value: ' ' }
})
- expect(mockNavigate).toHaveBeenCalled()
+ expect(mockNavigate).not.toHaveBeenCalled()
})
it('handles handleValues with null option', () => {
@@ -983,7 +1053,7 @@ describe('QuickSearch', () => {
expect(screen.getByTestId('autocomplete')).toBeTruthy()
})
- it('handles string option with wildcard search for empty input', () => {
+ it('does not wildcard search for empty input on Enter', () => {
render(<QuickSearch />)
const input = screen.getByTestId('autocomplete-input')
@@ -994,10 +1064,10 @@ describe('QuickSearch', () => {
target: { value: '' }
})
- expect(mockNavigate).toHaveBeenCalled()
+ expect(mockNavigate).not.toHaveBeenCalled()
})
- it('handles handleValues with string option that has empty value after trim', () => {
+ it('does not wildcard search for whitespace-only input on Enter', () => {
render(<QuickSearch />)
const input = screen.getByTestId('autocomplete-input')
@@ -1008,8 +1078,7 @@ describe('QuickSearch', () => {
target: { value: ' ' }
})
- // Should navigate with wildcard
- expect(mockNavigate).toHaveBeenCalled()
+ expect(mockNavigate).not.toHaveBeenCalled()
})
it('handles handleValues with option that has whitespace-only title', () => {
@@ -1105,7 +1174,7 @@ describe('QuickSearch', () => {
expect(mockNavigate).toHaveBeenCalled()
})
- it('handles Enter key with empty input - uses wildcard', () => {
+ it('handles Enter key with empty input without navigating', () => {
render(<QuickSearch />)
const input = screen.getByTestId('autocomplete-input')
@@ -1116,7 +1185,7 @@ describe('QuickSearch', () => {
target: { value: '' }
})
- expect(mockNavigate).toHaveBeenCalled()
+ expect(mockNavigate).not.toHaveBeenCalled()
})
it('handles Tab key - closes autocomplete', () => {
@@ -2020,6 +2089,7 @@ describe('QuickSearch', () => {
render(<QuickSearch />)
const input = screen.getByTestId('autocomplete-input')
+ fireEvent.change(input, { target: { value: 'test' } })
fireEvent.keyDown(input, {
keyCode: 13,
which: 13,
diff --git a/dashboard/src/components/__tests__/AuditEntityRefLink.test.tsx b/dashboard/src/components/__tests__/AuditEntityRefLink.test.tsx
new file mode 100644
index 000000000..a39b5edaf
--- /dev/null
+++ b/dashboard/src/components/__tests__/AuditEntityRefLink.test.tsx
@@ -0,0 +1,241 @@
+/*
+ * 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, waitFor } from '@testing-library/react';
+import AuditEntityRefLink from '../AuditEntityRefLink';
+
+const mockGetDetailPageData = jest.fn();
+
+jest.mock('react-redux', () => ({
+ useSelector: (fn: any) => fn({ typeHeader: { typeHeaderData: [] } })
+}));
+
+jest.mock('react-router-dom', () => ({
+ Link: ({ children, className }: any) => (
+ <a className={className}>{children}</a>
+ ),
+ useLocation: () => ({ search: '' })
+}));
+
+jest.mock('../../api/apiMethods/detailpageApiMethod', () => ({
+ getDetailPageData: (...args: any[]) => mockGetDetailPageData(...args)
+}));
+
+jest.mock('../muiComponents', () => ({
+ IconButton: ({ children, 'aria-label': ariaLabel }: any) => (
+ <button aria-label={ariaLabel}>{children}</button>
+ )
+}));
+
+jest.mock('../../utils/CommonViewFunction', () => ({
+ JSONPrettyPrint: () => '<span>json</span>',
+ getValue: (val: any) => String(val)
+}));
+
+jest.mock('../../utils/Enum', () => ({
+ entityStateReadOnly: {
+ ACTIVE: false,
+ DELETED: true,
+ STATUS_ACTIVE: false,
+ STATUS_DELETED: true
+ }
+}));
+
+jest.mock('../../utils/Utils', () => ({
+ extractKeyValueFromEntity: (input: any) => ({
+ name: input?.name || 'Entity'
+ }),
+ escapeHtml: (s: string) => String(s),
+ isArray: (val: any) => Array.isArray(val),
+ isBoolean: (val: any) => typeof val === 'boolean',
+ isEmpty: (val: any) =>
+ val == null ||
+ (Array.isArray(val) ? val.length === 0 :
+ typeof val === 'object' ? Object.keys(val).length === 0 :
+ val === ''),
+ isNumber: (val: any) => typeof val === 'number',
+ isObject: (val: any) =>
+ val !== null && typeof val === 'object' && !Array.isArray(val),
+ isString: (val: any) => typeof val === 'string'
+}));
+
+describe('AuditEntityRefLink', () => {
+ beforeEach(() => {
+ jest.clearAllMocks();
+ });
+
+ it('shows delete icon after header API returns DELETED status', async () => {
+ mockGetDetailPageData.mockResolvedValue({
+ data: {
+ guid: 'cf2-guid',
+ name: 'cf2',
+ status: 'DELETED',
+ entityStatus: 'DELETED'
+ }
+ });
+
+ const { container } = render(
+ <AuditEntityRefLink
+ entityRef={{
+ guid: 'cf2-guid',
+ typeName: 'hbase_column_family'
+ }}
+ referredEntities={{
+ 'cf2-guid': {
+ guid: 'cf2-guid',
+ name: 'cf2'
+ }
+ }}
+ />
+ );
+
+ expect(container.querySelector('.delete-icon')).toBeNull();
+
+ await waitFor(() => {
+ expect(container.querySelector('.delete-icon')).toBeTruthy();
+ });
+
+ expect(screen.getByText('cf2')).toBeTruthy();
+ expect(container.querySelector('.entity-name-deleted')).toBeTruthy();
+ expect(mockGetDetailPageData).toHaveBeenCalledWith(
+ 'cf2-guid',
+ {},
+ 'headers'
+ );
+ });
+
+ it('keeps snapshot rendering when header API returns empty data', async () => {
+ mockGetDetailPageData.mockResolvedValue({ data: null });
+
+ const { container } = render(
+ <AuditEntityRefLink
+ entityRef={{
+ guid: 'cf3-guid',
+ typeName: 'hbase_column_family'
+ }}
+ referredEntities={{
+ 'cf3-guid': {
+ guid: 'cf3-guid',
+ name: 'cf3'
+ }
+ }}
+ />
+ );
+
+ await waitFor(() => {
+ expect(mockGetDetailPageData).toHaveBeenCalled();
+ });
+
+ expect(screen.getByText('cf3')).toBeTruthy();
+ expect(container.querySelector('.delete-icon')).toBeNull();
+ expect(container.querySelector('.entity-name-deleted')).toBeNull();
+ expect(container.querySelector('.text-blue')).toBeTruthy();
+ });
+
+ it('shows delete icon when header returns only entityStatus DELETED', async () => {
+ mockGetDetailPageData.mockResolvedValue({
+ data: {
+ guid: 'cf4-guid',
+ name: 'cf4',
+ entityStatus: 'DELETED'
+ }
+ });
+
+ const { container } = render(
+ <AuditEntityRefLink
+ entityRef={{
+ guid: 'cf4-guid',
+ typeName: 'hbase_column_family'
+ }}
+ referredEntities={{
+ 'cf4-guid': {
+ guid: 'cf4-guid',
+ name: 'cf4'
+ }
+ }}
+ />
+ );
+
+ await waitFor(() => {
+ expect(container.querySelector('.delete-icon')).toBeTruthy();
+ });
+
+ expect(screen.getByText('cf4')).toBeTruthy();
+ expect(container.querySelector('.entity-name-deleted')).toBeTruthy();
+ });
+
+ it('shows delete icon when header returns only status DELETED', async () => {
+ mockGetDetailPageData.mockResolvedValue({
+ data: {
+ guid: 'cf5-guid',
+ name: 'cf5',
+ status: 'DELETED'
+ }
+ });
+
+ const { container } = render(
+ <AuditEntityRefLink
+ entityRef={{
+ guid: 'cf5-guid',
+ typeName: 'hbase_column_family'
+ }}
+ referredEntities={{
+ 'cf5-guid': {
+ guid: 'cf5-guid',
+ name: 'cf5'
+ }
+ }}
+ />
+ );
+
+ await waitFor(() => {
+ expect(container.querySelector('.delete-icon')).toBeTruthy();
+ });
+
+ expect(screen.getByText('cf5')).toBeTruthy();
+ expect(container.querySelector('.entity-name-deleted')).toBeTruthy();
+ });
+
+ it('keeps active link styling when header API rejects', async () => {
+ mockGetDetailPageData.mockRejectedValue(new Error('Network error'));
+
+ const { container } = render(
+ <AuditEntityRefLink
+ entityRef={{
+ guid: 'cf1-guid',
+ typeName: 'hbase_column_family'
+ }}
+ referredEntities={{
+ 'cf1-guid': {
+ guid: 'cf1-guid',
+ name: 'cf1'
+ }
+ }}
+ />
+ );
+
+ await waitFor(() => {
+ expect(mockGetDetailPageData).toHaveBeenCalled();
+ });
+
+ expect(screen.getByText('cf1')).toBeTruthy();
+ expect(container.querySelector('.delete-icon')).toBeNull();
+ expect(container.querySelector('.entity-name-deleted')).toBeNull();
+ expect(container.querySelector('.text-blue')).toBeTruthy();
+ });
+});
diff --git a/dashboard/src/components/__tests__/commonComponents.test.tsx b/dashboard/src/components/__tests__/commonComponents.test.tsx
index 7d6591aa1..6d4ebcdf9 100644
--- a/dashboard/src/components/__tests__/commonComponents.test.tsx
+++ b/dashboard/src/components/__tests__/commonComponents.test.tsx
@@ -23,16 +23,22 @@
import React from 'react'
import { render, screen } from '@testing-library/react'
let mockReduxState = { typeHeader: { typeHeaderData: [] } }
+let mockSearch = ''
jest.mock('react-redux', () => ({
useSelector: (fn: any) => fn(mockReduxState)
}))
jest.mock('react-router-dom', () => ({
- Link: ({ children, to }: any) => (
- <a href={to?.pathname || ''}>{children}</a>
- ),
- useLocation: () => ({ search: '' }),
+ Link: ({ children, to, className }: any) => {
+ const search = to?.search ? `?${to.search}` : ''
+ return (
+ <a href={`${to?.pathname || ''}${search}`} className={className}>
+ {children}
+ </a>
+ )
+ },
+ useLocation: () => ({ search: mockSearch }),
useNavigate: () => jest.fn()
}))
@@ -41,7 +47,9 @@ jest.mock('../../api/apiMethods/detailpageApiMethod', () => ({
}))
jest.mock('../muiComponents', () => ({
- IconButton: ({ children }: any) => <button>{children}</button>
+ IconButton: ({ children, 'aria-label': ariaLabel }: any) => (
+ <button aria-label={ariaLabel}>{children}</button>
+ )
}))
jest.mock('../../utils/CommonViewFunction', () => ({
@@ -50,7 +58,12 @@ jest.mock('../../utils/CommonViewFunction', () => ({
}))
jest.mock('../../utils/Enum', () => ({
- entityStateReadOnly: { ACTIVE: true },
+ entityStateReadOnly: {
+ ACTIVE: false,
+ DELETED: true,
+ STATUS_ACTIVE: false,
+ STATUS_DELETED: true
+ },
filterQueryValue: {},
queryBuilderDateRangeUIValueToAPI: {},
systemAttributes: {}
@@ -144,22 +157,76 @@ describe('commonComponents', () => {
expect(screen.getByText('json')).toBeTruthy()
})
- it('renders ExtractObject link and delete icon for read-only', () => {
- render(
+ it('renders ExtractObject delete icon only for DELETED status', () => {
+ const { container } = render(
+ <ExtractObject
+ keyValue={[{
+ guid: 'cf2-guid',
+ name: 'cf2',
+ status: 'DELETED',
+ typeName: 'hbase_column_family'
+ }]}
+ skipHeaderFetch={true}
+ />
+ )
+
+ expect(screen.getByText('cf2')).toBeTruthy()
+ expect(container.querySelector('.delete-icon')).toBeTruthy()
+ expect(container.querySelector('.entity-name-deleted')).toBeTruthy()
+ expect(screen.getByLabelText('Deleted entity')).toBeTruthy()
+ })
+
+ it('renders active entity link without delete icon', () => {
+ const { container } = render(
<ExtractObject
keyValue={[{
- guid: 'g1',
- name: 'EntityName',
+ guid: 'cf1-guid',
+ name: 'cf1',
status: 'ACTIVE',
- typeName: 'DataSet'
+ typeName: 'hbase_column_family'
}]}
+ skipHeaderFetch={true}
/>
)
- expect(screen.getByText('EntityName')).toBeTruthy()
+ expect(screen.getByText('cf1')).toBeTruthy()
+ expect(container.querySelector('.delete-icon')).toBeNull()
+ })
+
+ it('renders audit column families with deleted styling from referredEntities', () => {
+ const { container } = render(
+ <GetArrayValue
+ auditDetails={true}
+ values={[
+ { guid: 'cf1-guid', typeName: 'hbase_column_family' },
+ { guid: 'cf2-guid', typeName: 'hbase_column_family' }
+ ]}
+ properties="props"
+ referredEntities={{
+ 'cf1-guid': {
+ guid: 'cf1-guid',
+ name: 'cf1',
+ status: 'ACTIVE',
+ entityStatus: 'ACTIVE'
+ },
+ 'cf2-guid': {
+ guid: 'cf2-guid',
+ name: 'cf2',
+ status: 'DELETED',
+ entityStatus: 'DELETED'
+ }
+ }}
+ />
+ )
+
+ expect(screen.getByText('cf1')).toBeTruthy()
+ expect(screen.getByText('cf2')).toBeTruthy()
+ const deleteIcons = container.querySelectorAll('.delete-icon')
+ expect(deleteIcons.length).toBe(1)
})
it('renders glossary term link without delete icon', () => {
+ mockSearch = '?searchType=keyword&filter=old&guid=old-guid'
const { container } = render(
<ExtractObject
keyValue={[{
@@ -171,8 +238,34 @@ describe('commonComponents', () => {
/>
)
- expect(screen.getByText('Term1')).toBeTruthy()
+ const link = screen.getByText('Term1').closest('a')
+ expect(link?.getAttribute('href')).toContain('/glossary/t1')
+ expect(link?.getAttribute('href')).toContain('guid=t1')
+ expect(link?.getAttribute('href')).toContain('gtype=term')
+ expect(link?.getAttribute('href')).toContain('viewType=term')
+ expect(link?.getAttribute('href')).not.toContain('filter=old')
+ expect(link?.getAttribute('href')).toContain('searchType=keyword')
expect(container.querySelector('.delete-icon')).toBeNull()
+ mockSearch = ''
+ })
+
+ it('renders deleted glossary term link without delete icon', () => {
+ mockSearch = '?searchType=keyword&filter=old'
+ const { container } = render(
+ <ExtractObject
+ keyValue={[{
+ guid: 't2',
+ name: 'DeletedTerm',
+ status: 'DELETED',
+ typeName: 'AtlasGlossaryTerm'
+ }]}
+ />
+ )
+
+ const link = screen.getByText('DeletedTerm').closest('a')
+ expect(link?.getAttribute('href')).toContain('/glossary/t2')
+ expect(container.querySelector('.delete-icon')).toBeNull()
+ mockSearch = ''
})
it('renders JSON pretty for struct object', () => {
@@ -259,6 +352,59 @@ describe('commonComponents', () => {
expect(container.textContent).toContain('json')
})
+ it('getValues renders object ref when entity has no typeName', () => {
+ const result = getValues(
+ { guid: 'ref-guid', name: 'RefEntity', status: 'ACTIVE' },
+ {},
+ { name: 'relAttr' },
+ undefined,
+ 'properties',
+ undefined,
+ undefined,
+ 'relAttr'
+ )
+
+ const { container } = render(<>{result}</>)
+ expect(screen.getByText('RefEntity')).toBeTruthy()
+ expect(container.querySelector('.delete-icon')).toBeNull()
+ })
+
+ it('getValues renders audit object ref when entity has no typeName', () => {
+ const result = getValues(
+ { guid: 'ref-guid', name: 'DeletedRef', status: 'DELETED' },
+ {},
+ { name: 'relAttr' },
+ undefined,
+ 'properties',
+ undefined,
+ undefined,
+ 'relAttr',
+ true
+ )
+
+ const { container } = render(<>{result}</>)
+ expect(screen.getByText('DeletedRef')).toBeTruthy()
+ expect(container.querySelector('.delete-icon')).toBeTruthy()
+ })
+
+ it('getValues renders array refs when entity has no typeName', () => {
+ const result = getValues(
+ [
+ { guid: 'g1', name: 'First', status: 'ACTIVE' },
+ { guid: 'g2', name: 'Second', status: 'ACTIVE' }
+ ],
+ {},
+ { name: 'relAttr' },
+ undefined,
+ 'properties'
+ )
+
+ const { container } = render(<>{result}</>)
+ expect(screen.getByText('First')).toBeTruthy()
+ expect(screen.getByText('Second')).toBeTruthy()
+ expect(container.querySelector('pre')).toBeTruthy()
+ })
+
it('getValues renders array with GetArrayValue', () => {
const result = getValues(
{ getValue: () => ['a', 'b'] },
@@ -292,6 +438,18 @@ describe('commonComponents', () => {
expect(container.textContent).toContain('text')
})
+ it('getValues renders direct string value when properties param is set', () => {
+ const result = getValues(
+ 'audit-label-value',
+ {},
+ { name: 'labelName' },
+ undefined,
+ 'properties'
+ )
+ const { container } = render(<>{result}</>)
+ expect(container.textContent).toContain('audit-label-value')
+ })
+
it('getValues renders number date', () => {
const result = getValues(
123,
diff --git a/dashboard/src/components/__tests__/entityRefUtils.test.ts b/dashboard/src/components/__tests__/entityRefUtils.test.ts
new file mode 100644
index 000000000..0cd86e2cc
--- /dev/null
+++ b/dashboard/src/components/__tests__/entityRefUtils.test.ts
@@ -0,0 +1,73 @@
+/*
+ * 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 {
+ getEntityRefStatus,
+ mergeReferredEntity
+} from '../entityRefUtils';
+
+describe('entityRefUtils', () => {
+ describe('mergeReferredEntity', () => {
+ it('merges referred entity data when guid exists in map', () => {
+ const obj = { guid: 'g1', typeName: 'test_type' };
+ const referredEntities = {
+ g1: { name: 'Merged', status: 'DELETED' }
+ };
+
+ expect(mergeReferredEntity(obj, referredEntities)).toEqual({
+ guid: 'g1',
+ typeName: 'test_type',
+ name: 'Merged',
+ status: 'DELETED'
+ });
+ });
+
+ it('returns original object when referredEntities is missing', () => {
+ const obj = { guid: 'g1', name: 'Original' };
+
+ expect(mergeReferredEntity(obj)).toEqual(obj);
+ });
+
+ it('returns original object when guid is not in referredEntities', () => {
+ const obj = { guid: 'g1', name: 'Original' };
+
+ expect(mergeReferredEntity(obj, { g2: { name: 'Other' } })).toEqual(obj);
+ });
+ });
+
+ describe('getEntityRefStatus', () => {
+ it('returns status when present', () => {
+ expect(getEntityRefStatus({ status: 'ACTIVE' })).toBe('ACTIVE');
+ });
+
+ it('returns entityStatus when status is missing', () => {
+ expect(getEntityRefStatus({ entityStatus: 'DELETED' })).toBe('DELETED');
+ });
+
+ it('returns id.state when status and entityStatus are missing', () => {
+ expect(getEntityRefStatus({ id: { state: 'DELETED' } })).toBe('DELETED');
+ });
+
+ it('returns state when id is not an object', () => {
+ expect(getEntityRefStatus({ state: 'ACTIVE' })).toBe('ACTIVE');
+ });
+
+ it('returns undefined when no status fields exist', () => {
+ expect(getEntityRefStatus({ guid: 'g1' })).toBeUndefined();
+ });
+ });
+});
diff --git a/dashboard/src/components/commonComponents.tsx b/dashboard/src/components/commonComponents.tsx
index 5d320d895..60cceec0d 100644
--- a/dashboard/src/components/commonComponents.tsx
+++ b/dashboard/src/components/commonComponents.tsx
@@ -17,12 +17,8 @@
* limitations under the License.
*/
-import { IconButton } from "../components/muiComponents";
-
import {
dateFormat,
- escapeHtml,
- extractKeyValueFromEntity,
formatedDate,
isArray,
isBoolean,
@@ -32,14 +28,11 @@ import {
isObject,
isString
} from "../utils/Utils";
-import { JSONPrettyPrint, getValue } from "../utils/CommonViewFunction";
-import { useSelector } from "react-redux";
-import { entityStateReadOnly } from "../utils/Enum";
-import { Link, useLocation } from "react-router-dom";
-import DeleteOutlineOutlinedIcon from "@mui/icons-material/DeleteOutlineOutlined";
-import { useEffect, useState } from "react";
-import { getDetailPageData } from "../api/apiMethods/detailpageApiMethod";
import moment from "moment";
+import { renderEntityRefValue } from "./entityRefRenderers";
+
+export { ExtractObject } from "./ExtractObject";
+export { default as AuditEntityRefLink } from "./AuditEntityRefLink";
export const EllipsisText = (props: any) => {
const { children } = props;
@@ -47,201 +40,16 @@ export const EllipsisText = (props: any) => {
return <div className="chip-ellipsis cursor-pointer">{children}</div>;
};
-export const ExtractObject = (props: any) => {
- const { typeHeaderData }: any = useSelector((state: any) => state.typeHeader);
- const location = useLocation();
- const searchParams = new URLSearchParams(location.search);
- const [headerData, setHeaderData] = useState<string>("");
- let triggerHeaderApi = "";
-
- useEffect(() => {
- getInputOutputValue(triggerHeaderApi);
- }, [triggerHeaderApi]);
-
- const getGuid = (guid: string) => {
- if (!isEmpty(guid)) {
- triggerHeaderApi = guid;
- }
- };
-
- const getInputOutputValue = async (guid: string) => {
- if (!isEmpty(guid)) {
- try {
- const { data: response } = await getDetailPageData(guid, {}, "headers");
- const { name } = extractKeyValueFromEntity(response);
- setHeaderData(name as string);
- } catch {
- // Error handled silently
- }
- }
- };
-
- let valueOfArray = [],
- keyValue = props.keyValue,
- nameVal = "",
- tempLink = "",
- deleteIcon = false,
- fetchVal = false;
-
- if (!isArray(keyValue) && isObject(keyValue)) {
- keyValue = [keyValue];
- }
- for (var i = 0; i < keyValue?.length; i++) {
- let inputOutputField = keyValue[i],
- id = inputOutputField.guid,
- status =
- inputOutputField.status ||
- inputOutputField.entityStatus ||
- (isObject(inputOutputField.id)
- ? inputOutputField.id.state
- : inputOutputField.state),
- readOnly = entityStateReadOnly[status];
-
- if (!inputOutputField.attributes && inputOutputField.values) {
- inputOutputField["attributes"] = inputOutputField.values;
- }
- if (
- isString(inputOutputField) ||
- isBoolean(inputOutputField) ||
- isNumber(inputOutputField)
- ) {
- let tempVarfor$check = inputOutputField.toString();
- if (tempVarfor$check.indexOf("$") == -1) {
- let tmpVal = getValue(inputOutputField as any);
-
- valueOfArray.push(
- '<span class="json-string">' + escapeHtml(String(tmpVal)) + "</span>"
- );
- }
- } else if (isObject(inputOutputField) && id == undefined) {
- let attributesList = inputOutputField;
- if (typeHeaderData && inputOutputField.typeName) {
- let typeNameCategory = typeHeaderData.find(
- (obj: { name: string }) => obj.name == inputOutputField.typeName
- );
-
- if (
- attributesList?.attributes &&
- typeNameCategory?.category === "STRUCT"
- ) {
- attributesList = attributesList.attributes;
- }
- }
- valueOfArray.push(JSONPrettyPrint(attributesList));
- }
-
- if (id && inputOutputField) {
- const { name }: { name: string } = extractKeyValueFromEntity(
- inputOutputField,
- "",
- "",
- getGuid,
- headerData
- );
- nameVal = name;
- if (inputOutputField.typeName == "AtlasGlossaryTerm") {
- tempLink = `/glossary/${id}`;
- let keys = Array.from(searchParams.keys());
- for (let i = 0; i < keys.length; i++) {
- if (keys[i] != "searchType") {
- searchParams.delete(keys[i]);
- }
- }
- searchParams.set("guid", id);
- searchParams.set("gtype", "term");
- searchParams.set("viewType", "term");
- fetchVal = true;
- } else {
- tempLink = `/detailPage/${id}`;
- }
- }
-
- if (readOnly) {
- if (!fetchVal) {
- deleteIcon = true;
- } else {
- fetchVal = false;
- }
- }
- }
-
- return (
- <>
- {valueOfArray?.length > 0 ? (
- props.properties != undefined ? (
- <pre className="code-block fixed-height">
- <code>
- <span
- dangerouslySetInnerHTML={{
- __html: valueOfArray as any
- }}
- ></span>
- </code>
- </pre>
- ) : (
- <span
- dangerouslySetInnerHTML={{
- __html: valueOfArray as any
- }}
- ></span>
- )
- ) : (
- <>
- {tempLink != "" ? (
- <>
- <Link
- className="entity-name nav-link max-100 text-blue text-decoration-none"
- to={{
- pathname: tempLink,
- search: searchParams.toString() ? searchParams.toString() : ""
- }}
- style={{
- display: "inline-block",
- maxWidth: "100%",
- textOverflow: "ellipsis",
- overflow: "hidden",
- whiteSpace: "nowrap",
- verticalAlign: "bottom",
- color: deleteIcon ? "#bb5838" : "#4a90e2"
- }}
- title={nameVal}
- >
- {nameVal}
- </Link>
- {deleteIcon && (
- <IconButton
- aria-label="back"
- sx={{
- display: "inline-flex",
- position: "relative",
- padding: "0",
- marginLeft: "4px"
- }}
- >
- <DeleteOutlineOutlinedIcon
- className="delete-icon"
- sx={{ fontSize: "1.25rem", height: "24px" }}
- />
- </IconButton>
- )}
- </>
- ) : (
- "N/A"
- )}
- </>
- )}
- </>
- );
-};
-
export const GetArrayValue = ({
values,
properties,
- referredEntities
+ referredEntities,
+ auditDetails
}: {
values: string[];
properties?: string;
referredEntities?: any;
+ auditDetails?: boolean;
}) => {
return !isEmpty(values) ? (
properties != undefined ? (
@@ -250,21 +58,19 @@ export const GetArrayValue = ({
{values.map((obj: any, i: number) => {
if (isObject(obj)) {
return (
- <>
- <ExtractObject
- keyValue={
- referredEntities?.[obj?.guid] != undefined
- ? referredEntities[obj.guid]
- : obj
- }
- properties={properties}
- />
+ <span key={obj?.guid ?? i}>
+ {renderEntityRefValue({
+ entityRef: obj,
+ referredEntities,
+ properties,
+ auditDetails
+ })}
<br />
- </>
+ </span>
);
}
return (
- <span className="json-string">
+ <span key={i} className="json-string">
{obj}
{i < values?.length - 1 && ", "}
</span>
@@ -275,7 +81,7 @@ export const GetArrayValue = ({
) : (
values.map((obj: any, i: number) => {
return (
- <span className="json-string">
+ <span key={i} className="json-string">
{obj}
{i < values?.length - 1 && ", "}
</span>
@@ -295,7 +101,8 @@ export const getValues = (
properties?: string,
referredEntities?: any,
filterEntityData?: any,
- keys?: string
+ keys?: string,
+ auditDetails?: boolean
) => {
var tempObj = {
attributeDefs: [entity],
@@ -348,9 +155,12 @@ export const getValues = (
filterEntityData?.relationshipAttributes?.[keys as string] != undefined
? filterEntityData.relationshipAttributes[keys as string]
: keyValue;
- return (
- <ExtractObject keyValue={filteredValues} properties={properties} />
- );
+ return renderEntityRefValue({
+ entityRef: filteredValues,
+ referredEntities,
+ properties,
+ auditDetails
+ });
}
if (!isEmpty(currentValue) && isArray(currentValue)) {
let filteredValues =
@@ -365,6 +175,7 @@ export const getValues = (
values={filteredValues}
properties={properties}
referredEntities={referredEntities}
+ auditDetails={auditDetails}
/>
);
}
@@ -374,9 +185,12 @@ export const getValues = (
filterEntityData?.relationshipAttributes?.[keys as string] != undefined
? filterEntityData.relationshipAttributes[keys as string]
: keyValue;
- return (
- <ExtractObject keyValue={filteredValues} properties={properties} />
- );
+ return renderEntityRefValue({
+ entityRef: filteredValues,
+ referredEntities,
+ properties,
+ auditDetails
+ });
}
}
if (!isEmpty(currentValue) && isArray(currentValue)) {
@@ -391,6 +205,7 @@ export const getValues = (
values={filteredValues}
properties={properties}
referredEntities={referredEntities}
+ auditDetails={auditDetails}
/>
);
}
diff --git a/dashboard/src/components/entityRefRenderers.tsx b/dashboard/src/components/entityRefRenderers.tsx
new file mode 100644
index 000000000..f52fad8c0
--- /dev/null
+++ b/dashboard/src/components/entityRefRenderers.tsx
@@ -0,0 +1,51 @@
+/*
+ * 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 AuditEntityRefLink from "./AuditEntityRefLink";
+import { ExtractObject } from "./ExtractObject";
+import { mergeReferredEntity } from "./entityRefUtils";
+
+type RenderEntityRefValueProps = {
+ entityRef: Record<string, unknown>;
+ referredEntities?: Record<string, unknown>;
+ properties?: string;
+ auditDetails?: boolean;
+};
+
+export const renderEntityRefValue = ({
+ entityRef,
+ referredEntities,
+ properties,
+ auditDetails
+}: RenderEntityRefValueProps) => {
+ if (auditDetails) {
+ return (
+ <AuditEntityRefLink
+ entityRef={entityRef}
+ referredEntities={referredEntities}
+ properties={properties}
+ />
+ );
+ }
+
+ return (
+ <ExtractObject
+ keyValue={mergeReferredEntity(entityRef, referredEntities)}
+ properties={properties}
+ />
+ );
+};
diff --git a/dashboard/src/components/entityRefUtils.ts b/dashboard/src/components/entityRefUtils.ts
new file mode 100644
index 000000000..cad281896
--- /dev/null
+++ b/dashboard/src/components/entityRefUtils.ts
@@ -0,0 +1,35 @@
+/*
+ * 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 { isObject } from "../utils/Utils";
+
+export const mergeReferredEntity = (
+ obj: Record<string, unknown>,
+ referredEntities?: Record<string, unknown>
+) => {
+ if (obj?.guid && referredEntities?.[obj.guid as string] != undefined) {
+ return { ...obj, ...(referredEntities[obj.guid as string] as object) };
+ }
+ return obj;
+};
+
+export const getEntityRefStatus = (ref: Record<string, unknown>) =>
+ (ref?.status ||
+ ref?.entityStatus ||
+ (isObject(ref?.id) ? (ref.id as { state?: string }).state : ref?.state)) as
+ | string
+ | undefined;
diff --git a/dashboard/src/styles/globalSearch.scss b/dashboard/src/styles/globalSearch.scss
index ba1ebb4f1..fb64ab265 100644
--- a/dashboard/src/styles/globalSearch.scss
+++ b/dashboard/src/styles/globalSearch.scss
@@ -80,6 +80,10 @@
gap: "0.5rem";
}
+.global-search-submit-btn[disabled] {
+ cursor: not-allowed;
+}
+
.advanced-search-label {
text-decoration: underline;
}
diff --git a/dashboard/src/styles/propertiesTab.scss b/dashboard/src/styles/propertiesTab.scss
index 748c37198..3073dfc30 100644
--- a/dashboard/src/styles/propertiesTab.scss
+++ b/dashboard/src/styles/propertiesTab.scss
@@ -51,6 +51,100 @@
display: inline;
}
+.bm-attribute-row {
+ display: flex;
+ align-items: flex-start;
+ gap: 0.5rem;
+ width: 100%;
+}
+
+.bm-attribute-key-col {
+ flex: 0 0 38%;
+ min-width: 0;
+ max-width: 38%;
+
+ .MuiAutocomplete-root,
+ .MuiFormControl-root,
+ .MuiInputBase-root {
+ width: 100%;
+ }
+}
+
+.bm-attribute-value-col {
+ flex: 1 1 auto;
+ min-width: 0;
+
+ .MuiAutocomplete-root,
+ .MuiFormControl-root,
+ .MuiInputBase-root,
+ .MuiSelect-root,
+ .classification-form-editor {
+ width: 100%;
+ }
+}
+
+.bm-attribute-actions-col {
+ flex: 0 0 auto;
+ display: flex;
+ gap: 0.25rem;
+ align-self: center;
+ padding-top: 2px;
+}
+
+.bm-attribute-separator {
+ flex: 0 0 auto;
+ align-self: center;
+ line-height: 36px;
+ margin: 0;
+}
+
+.bm-attribute-key-label {
+ display: block;
+ word-break: break-word;
+ font-weight: 600 !important;
+ font-size: 14px !important;
+ line-height: 1.4;
+ padding-top: 6px;
+}
+
+.bm-attribute-read-row {
+ display: flex;
+ align-items: flex-start;
+ gap: 1rem;
+ margin: 0.5rem 0;
+ width: 100%;
+}
+
+.bm-attribute-read-key {
+ flex: 0 0 38%;
+ min-width: 0;
+ max-width: 38%;
+ word-break: break-word;
+ text-align: left;
+}
+
+.bm-attribute-read-value {
+ flex: 1 1 auto;
+ min-width: 0;
+ word-break: break-word;
+ text-align: left;
+}
+
+.bm-attribute-value-field {
+ width: 100%;
+}
+
+.bm-enum-loading {
+ min-height: 36px;
+ padding-top: 6px;
+}
+
+.bm-enum-unavailable-text {
+ min-height: 36px;
+ padding-top: 8px;
+ font-style: italic;
+}
+
.bmattributes-key .MuiInputBase-sizeSmall {
height: 34px;
}
diff --git a/dashboard/src/styles/table.scss b/dashboard/src/styles/table.scss
index 2ec0641dd..2beb88476 100644
--- a/dashboard/src/styles/table.scss
+++ b/dashboard/src/styles/table.scss
@@ -253,6 +253,10 @@ td:has(.searchTableName) {
height: 24px;
}
+.entity-name-deleted {
+ color: #bb5838;
+}
+
.table-filter-column {
font-size: 1rem;
cursor: pointer;
diff --git a/dashboard/src/utils/Utils.ts b/dashboard/src/utils/Utils.ts
index 3d0b0d7d6..3c275dd82 100644
--- a/dashboard/src/utils/Utils.ts
+++ b/dashboard/src/utils/Utils.ts
@@ -172,6 +172,13 @@ const getBaseUrl = (url: string, noPop?: boolean | undefined) => {
return path;
};
+const getDisplayNameFromQualifiedName = (qualifiedName: string): string => {
+ const base = qualifiedName.split("@")[0] || qualifiedName;
+ const afterColon = base.includes(":") ? base.split(":").pop()! : base;
+ const segments = afterColon.split(".");
+ return segments.length > 1 ? segments[segments.length - 1] : afterColon;
+};
+
const extractKeyValueFromEntity = (
data: any,
priorityAttribute?: any,
@@ -227,6 +234,14 @@ const extractKeyValueFromEntity = (
"id"
];
+ const snapshotQualifiedName =
+ collectionJSON?.uniqueAttributes?.qualifiedName;
+ if (snapshotQualifiedName) {
+ returnObj.name = getDisplayNameFromQualifiedName(snapshotQualifiedName);
+ returnObj.key = "qualifiedName";
+ return returnObj;
+ }
+
for (const property of propertyOrder) {
if (collectionJSON?.[property]) {
if (property === "id" && typeof collectionJSON.id === "object") {
diff --git a/dashboard/src/utils/__tests__/Utils.test.ts b/dashboard/src/utils/__tests__/Utils.test.ts
index 6101e7f27..095fa6874 100644
--- a/dashboard/src/utils/__tests__/Utils.test.ts
+++ b/dashboard/src/utils/__tests__/Utils.test.ts
@@ -555,6 +555,32 @@ describe('Utils', () => {
// found defaults to true when an attribute is found
expect(result.found).toBe(true);
});
+
+ it('should resolve display name from uniqueAttributes.qualifiedName', () => {
+ const data = {
+ guid: 'cf2-guid',
+ typeName: 'hbase_column_family',
+ uniqueAttributes: {
+ qualifiedName: 'default:test_tbl.cf2@primary'
+ }
+ };
+ const result = extractKeyValueFromEntity(data);
+ expect(result.name).toBe('cf2');
+ expect(result.key).toBe('qualifiedName');
+ });
+
+ it('should resolve display name from qualifiedName without dot segment', () => {
+ const data = {
+ guid: 'tbl-guid',
+ typeName: 'hbase_table',
+ uniqueAttributes: {
+ qualifiedName: 'default:test_tbl@primary'
+ }
+ };
+ const result = extractKeyValueFromEntity(data);
+ expect(result.name).toBe('test_tbl');
+ expect(result.key).toBe('qualifiedName');
+ });
});
describe('getNestedSuperTypes', () => {
diff --git a/dashboard/src/utils/__tests__/enumTypeUtils.test.ts b/dashboard/src/utils/__tests__/enumTypeUtils.test.ts
index 3485ba615..109e9744d 100644
--- a/dashboard/src/utils/__tests__/enumTypeUtils.test.ts
+++ b/dashboard/src/utils/__tests__/enumTypeUtils.test.ts
@@ -18,9 +18,12 @@
import {
areEnumOptionsEqual,
buildEnumOptionsForTypeName,
+ getEnumOptionLabel,
getInnerTypeName,
isArrayTypeName,
isEnumTypeName,
+ isPotentialEnumTypeName,
+ isPrimitiveTypeName,
normalizeMultiEnumValue,
serializeMultiEnumValue
} from "@utils/enumTypeUtils";
@@ -155,4 +158,68 @@ describe("enumTypeUtils", () => {
buildEnumOptionsForTypeName("unknown_enum_type", mockEnumDefs)
).toEqual([]);
});
+
+ it("identifies primitive and potential enum type names", () => {
+ expect(isPrimitiveTypeName("string")).toBe(true);
+ expect(isPrimitiveTypeName("array<int>")).toBe(true);
+ expect(isPrimitiveTypeName("byte")).toBe(true);
+ expect(isPrimitiveTypeName("array<byte>")).toBe(true);
+ expect(isPrimitiveTypeName("adls_gen2_replication")).toBe(false);
+ expect(isPotentialEnumTypeName("array<adls_gen2_replication>")).toBe(true);
+ expect(isPotentialEnumTypeName("array<string>")).toBe(false);
+ });
+
+ it("returns false for empty primitive type name (negative)", () => {
+ expect(isPrimitiveTypeName("")).toBe(false);
+ expect(isPotentialEnumTypeName("")).toBe(false);
+ });
+
+ it("builds boolean array options (positive)", () => {
+ expect(buildEnumOptionsForTypeName("array<boolean>", mockEnumDefs)).toEqual([
+ { label: "true", value: "true" },
+ { label: "false", value: "false" }
+ ]);
+ });
+
+ it("returns empty options when enum defs are missing (negative)", () => {
+ expect(buildEnumOptionsForTypeName("adls_gen2_replication", undefined)).toEqual(
+ []
+ );
+ });
+
+ it("normalizes unknown enum object values using fallback labels (positive)", () => {
+ const options = buildEnumOptionsForTypeName(
+ "array<adls_gen2_replication>",
+ mockEnumDefs
+ );
+
+ expect(
+ normalizeMultiEnumValue([{ label: "CUSTOM", value: "CUSTOM" }], options)
+ ).toEqual([{ label: "CUSTOM", value: "CUSTOM" }]);
+ });
+
+ it("normalizes plain string enum values not present in options (negative)", () => {
+ const options = buildEnumOptionsForTypeName(
+ "array<adls_gen2_replication>",
+ mockEnumDefs
+ );
+
+ expect(normalizeMultiEnumValue(["UNKNOWN"], options)).toEqual([
+ { label: "UNKNOWN", value: "UNKNOWN" }
+ ]);
+ });
+
+ it("returns enum option label for string values (positive)", () => {
+ expect(getEnumOptionLabel("LRS")).toBe("LRS");
+ expect(getEnumOptionLabel({ label: "LRS", value: "LRS" })).toBe("LRS");
+ });
+
+ it("handles malformed array type names in getInnerTypeName (negative)", () => {
+ expect(getInnerTypeName("array<>")).toBe("array<>");
+ expect(getInnerTypeName("")).toBe("");
+ });
+
+ it("returns false for isArrayTypeName with empty input (negative)", () => {
+ expect(isArrayTypeName("")).toBe(false);
+ });
});
diff --git a/dashboard/src/utils/enumTypeUtils.ts b/dashboard/src/utils/enumTypeUtils.ts
index 867707f14..38686b3bb 100644
--- a/dashboard/src/utils/enumTypeUtils.ts
+++ b/dashboard/src/utils/enumTypeUtils.ts
@@ -37,6 +37,29 @@ export const getInnerTypeName = (typeName: string): string => {
export const isArrayTypeName = (typeName: string): boolean =>
Boolean(typeName && typeName.indexOf("array<") === 0);
+const PRIMITIVE_TYPE_NAMES = new Set([
+ "string",
+ "int",
+ "short",
+ "float",
+ "double",
+ "long",
+ "boolean",
+ "date",
+ "byte"
+]);
+
+export const isPrimitiveTypeName = (typeName: string): boolean => {
+ if (!typeName) {
+ return false;
+ }
+
+ return PRIMITIVE_TYPE_NAMES.has(getInnerTypeName(typeName));
+};
+
+export const isPotentialEnumTypeName = (typeName: string): boolean =>
+ Boolean(typeName && !isPrimitiveTypeName(typeName));
+
export const isEnumTypeName = (
typeName: string,
enumDefs: EnumDef[] | undefined
diff --git a/dashboard/src/views/DetailPage/EntityDetailTabs/AttributeProperties.tsx b/dashboard/src/views/DetailPage/EntityDetailTabs/AttributeProperties.tsx
index de70ac7b2..7a6f66b9b 100644
--- a/dashboard/src/views/DetailPage/EntityDetailTabs/AttributeProperties.tsx
+++ b/dashboard/src/views/DetailPage/EntityDetailTabs/AttributeProperties.tsx
@@ -269,7 +269,8 @@ const AttributeProperties = ({
"properties",
referredEntities,
entity,
- keys
+ keys,
+ auditDetails
)}
</div>
</Stack>
diff --git a/dashboard/src/views/DetailPage/EntityDetailTabs/PropertiesTab/BMAttributes.tsx b/dashboard/src/views/DetailPage/EntityDetailTabs/PropertiesTab/BMAttributes.tsx
index b9c20418a..b59e46db8 100644
--- a/dashboard/src/views/DetailPage/EntityDetailTabs/PropertiesTab/BMAttributes.tsx
+++ b/dashboard/src/views/DetailPage/EntityDetailTabs/PropertiesTab/BMAttributes.tsx
@@ -15,9 +15,8 @@
* limitations under the License.
*/
-// @ts-nocheck
-import { useEffect, useRef, useState } from "react";
+import { useEffect, useRef, useState, type MouseEvent, type SyntheticEvent } from "react";
import {
CustomButton,
Accordion,
@@ -42,10 +41,16 @@ import {
dateFormat,
formatedDate,
isEmpty,
- isNull,
serverError
} from "@utils/Utils";
-import { Controller, useFieldArray, useForm, useWatch } from "react-hook-form";
+import {
+ Controller,
+ useFieldArray,
+ useForm,
+ useWatch,
+ type Control,
+ type FieldValues
+} from "react-hook-form";
import { useParams } from "react-router-dom";
import AddOutlinedIcon from "@mui/icons-material/AddOutlined";
import RemoveOutlinedIcon from "@mui/icons-material/RemoveOutlined";
@@ -57,18 +62,48 @@ import { toast } from "react-toastify";
import { cloneDeep } from "@utils/Helper";
import moment from "moment-timezone";
import { fetchDetailPageData } from "@redux/slice/detailPageSlice";
+import { fetchEnumData } from "@redux/slice/enumSlice";
+import type { RootState } from "@redux/store/store";
import { isEntityModificationAllowed } from "@utils/EntityStatus";
+import {
+ isEnumTypeName,
+ isPotentialEnumTypeName,
+ serializeMultiEnumValue
+} from "@utils/enumTypeUtils";
const defaultField = {
key: null,
value: ""
};
+type BusinessMetadataAttributeDef = {
+ name: string;
+ typeName: string;
+};
+
+type BusinessMetadataKey = {
+ label: string;
+ group: string;
+ value: string;
+ obj: BusinessMetadataAttributeDef;
+};
+
+type BusinessMetadataFormRow = {
+ key: BusinessMetadataKey | null;
+ value: unknown;
+};
+
+type EntitySummary = {
+ guid?: string;
+ status?: string;
+ typeName: string;
+};
+
type BMAttributesProps = {
loading: boolean | undefined;
- bmAttributes: Record<string, any>;
- entity: any;
+ bmAttributes: Record<string, Record<string, unknown>>;
+ entity: EntitySummary;
};
const BMAttributes = ({ loading, bmAttributes, entity }: BMAttributesProps) => {
@@ -81,6 +116,11 @@ const BMAttributes = ({ loading, bmAttributes, entity }: BMAttributesProps) => {
const { businessMetaData } = useAppSelector(
(state: any) => state.businessMetaData
);
+ const enumObj = useAppSelector((state: RootState) => state.enum.enumObj);
+ const enumDefs = enumObj?.data?.enumDefs ?? [];
+ const enumLoading = enumObj?.loading === true;
+ const enumLoaded = enumObj?.data != null;
+ const enumFetchAttemptedRef = useRef(false);
const { businessMetadataDefs } = businessMetaData || {};
let businessAttributes = cloneDeep(bmAttributes);
@@ -151,17 +191,16 @@ const BMAttributes = ({ loading, bmAttributes, entity }: BMAttributesProps) => {
);
const [addLabel, setAddLabel] = useState<boolean>(true);
const [expanded, setExpanded] = useState<string | false>(false);
- const [selectedIndex, setSelectedIndex] = useState();
let attributes = cloneDeep(bmAttributes);
- let defaultFieldValues = !isEmpty(attributes)
- ? Object.entries(attributes)
+ let defaultFieldValues: BusinessMetadataFormRow[] = !isEmpty(attributes)
+ ? (Object.entries(attributes) as Array<[string, Record<string, unknown>]>)
.map(([group, attrs]) =>
Object.entries(attrs)
.map(([key, value]) => {
- const matchedDef = businessAttributeDefs[group].find(
- (bm) => bm.name === key
+ const matchedDef = businessAttributeDefs[group]?.find(
+ (bm: BusinessMetadataAttributeDef) => bm.name === key
);
if (!matchedDef) {
@@ -180,7 +219,7 @@ const BMAttributes = ({ loading, bmAttributes, entity }: BMAttributesProps) => {
})
.filter((item) => item !== null)
)
- .flat()
+ .flat() as BusinessMetadataFormRow[]
: [defaultField];
const {
@@ -188,13 +227,13 @@ const BMAttributes = ({ loading, bmAttributes, entity }: BMAttributesProps) => {
handleSubmit,
reset,
watch,
- setValue,
- formState: { isSubmitting, errors }
- } = useForm({
+ formState: { isSubmitting }
+ } = useForm<{ businessMetadata: BusinessMetadataFormRow[] }>({
defaultValues: {
businessMetadata: defaultFieldValues
}
});
+ const fieldsControl = control as unknown as Control<FieldValues>;
const { fields, append, remove } = useFieldArray({
control,
name: "businessMetadata"
@@ -206,8 +245,22 @@ const BMAttributes = ({ loading, bmAttributes, entity }: BMAttributesProps) => {
}
}, [bmAttributes]);
+ useEffect(() => {
+ if (
+ enumLoaded ||
+ enumLoading ||
+ enumObj?.error ||
+ enumFetchAttemptedRef.current
+ ) {
+ return;
+ }
+
+ enumFetchAttemptedRef.current = true;
+ dispatchApi(fetchEnumData());
+ }, [dispatchApi, enumLoaded, enumLoading, enumObj?.error]);
+
const handleChange =
- (panel: string) => (_event: React.SyntheticEvent, isExpanded: boolean) => {
+ (panel: string) => (_event: SyntheticEvent, isExpanded: boolean) => {
setExpanded(isExpanded ? panel : false);
if (expanded) {
setAddLabel(true);
@@ -219,58 +272,84 @@ const BMAttributes = ({ loading, bmAttributes, entity }: BMAttributesProps) => {
control
});
- const onSubmit = async (values: { businessMetadata: any[] }) => {
+ const hasPotentialEnumFields = bmAttributesValues?.some((item) => {
+ const typeName = item?.key?.obj?.typeName;
+ return Boolean(typeName && isPotentialEnumTypeName(typeName));
+ });
+ const isEnumDataPending = enumLoading && hasPotentialEnumFields;
+
+ const onSubmit = async (values: { businessMetadata: BusinessMetadataFormRow[] }) => {
let formData = { ...values };
const { businessMetadata } = formData;
- let data: Record<string, any> = {};
+ let data: Record<string, Record<string, unknown>> = {};
for (let dataObj of businessMetadata) {
- if (isEmpty(dataObj.key)) {
+ if (!dataObj.key || isEmpty(dataObj.key)) {
return;
}
const { label, group, obj } = dataObj.key;
const { typeName } = obj;
- let atrributeType: string[] = [
+ let attributeType: string[] = [
"array<string>",
"array<int>",
"array<short>",
"array<float>",
- "array<double",
+ "array<double>",
"array<long>"
];
- if (atrributeType.includes(typeName)) {
+ if (attributeType.includes(typeName)) {
+ const arrayValue = Array.isArray(dataObj.value) ? dataObj.value : [];
data[group] = {
...data[group],
...{
- [label]: !isEmpty(dataObj)
- ? dataObj?.value?.map(
- (input: { inputValue: any }) => input.inputValue || input
- )
- : []
+ [label]: arrayValue.map(
+ (input: string | { inputValue?: string }) =>
+ typeof input === "object" && input?.inputValue
+ ? input.inputValue
+ : input
+ )
}
};
} else if (
typeName.indexOf("array") > -1 &&
- !atrributeType.includes(typeName)
+ !attributeType.includes(typeName)
) {
+ if (isEnumTypeName(typeName, enumDefs)) {
+ data[group] = {
+ ...data[group],
+ ...{
+ [label]: serializeMultiEnumValue(dataObj.value)
+ }
+ };
+ } else {
+ const arrayValue = Array.isArray(dataObj.value) ? dataObj.value : [];
+ data[group] = {
+ ...data[group],
+ ...{
+ [label]: arrayValue.map((val: string | { label?: string }) =>
+ typeName === "array<date>"
+ ? val
+ : typeof val === "string"
+ ? val
+ : val.label
+ )
+ }
+ };
+ }
+ } else if (typeName == "boolean") {
data[group] = {
...data[group],
...{
- [label]: dataObj?.value?.map((val: any) =>
- typeName === "array<date>" ? val : val.label
- )
+ [label]:
+ dataObj.value === true ||
+ dataObj.value === "true"
}
};
- } else if (typeName == "boolean") {
- data[group] = {
- ...data[group],
- ...{ [label]: dataObj.value == "true" ? true : false }
- };
} else if (typeName == "date") {
data[group] = {
...data[group],
- ...{ [label]: moment(dataObj.value).valueOf() }
+ ...{ [label]: moment(dataObj.value as moment.MomentInput).valueOf() }
};
} else {
data[group] = { ...data[group], ...{ [label]: dataObj.value } };
@@ -284,8 +363,8 @@ const BMAttributes = ({ loading, bmAttributes, entity }: BMAttributesProps) => {
}
try {
- await getEntityBusinessMetadata(guid, data);
- toast.dismiss(toastId.current);
+ await getEntityBusinessMetadata(guid ?? "", data);
+ toast.dismiss(toastId.current ?? undefined);
toastId.current = toast.success(
"One or more Business Metadata attributes were updated successfully"
);
@@ -299,25 +378,34 @@ const BMAttributes = ({ loading, bmAttributes, entity }: BMAttributesProps) => {
"Error while adding or updating business metadta attribute",
error
);
- toast.dismiss(toastId.current);
+ toast.dismiss(toastId.current ?? undefined);
serverError(error, toastId);
}
};
- const handleSave = (e: React.MouseEvent) => {
+ const handleSave = (e: MouseEvent) => {
e.stopPropagation();
handleSubmit(onSubmit)();
};
- const renderValues = (values: { value: any; typeName: string }) => {
+ const renderValues = (values: { value: unknown; typeName?: string }) => {
const { value, typeName } = values;
+ if (!typeName) {
+ return String(value ?? "");
+ }
+
if (
typeName.indexOf("array<date>") == -1 &&
- typeName.indexOf("array") > -1
+ typeName.indexOf("array") > -1 &&
+ Array.isArray(value)
) {
return value.map((obj: number) => obj).join(", ");
}
- if (value.length > 0 && typeName.indexOf("array<date>") > -1) {
+ if (
+ Array.isArray(value) &&
+ value.length > 0 &&
+ typeName.indexOf("array<date>") > -1
+ ) {
return value
.map((obj: number) =>
formatedDate({
@@ -343,7 +431,7 @@ const BMAttributes = ({ loading, bmAttributes, entity }: BMAttributesProps) => {
const selectedOptions = watch("businessMetadata");
- const getAvailableOptions = (index) => {
+ const getAvailableOptions = (index: number) => {
return bmOptions.filter((option) => {
return !selectedOptions.some(
(selected, selectedIndex) =>
@@ -409,7 +497,7 @@ const BMAttributes = ({ loading, bmAttributes, entity }: BMAttributesProps) => {
variant="outlined"
color="success"
size="small"
- disabled={isSubmitting}
+ disabled={isSubmitting || isEnumDataPending}
onClick={handleSave}
startIcon={
isSubmitting && <CircularProgress size="14px" color="inherit"/>
@@ -495,38 +583,20 @@ const BMAttributes = ({ loading, bmAttributes, entity }: BMAttributesProps) => {
<AccordionDetails
sx={{ padding: "4px 16px" }}
>
- <Stack
- direction="row"
- spacing={4}
- marginBottom={1}
- marginTop={1}
- >
- <div
- style={{
- flex: "0 0 8em",
- wordBreak: "break-all",
- textAlign: "left",
- fontWeight: "400"
- }}
- >
- <Typography fontWeight="600">{`${key} (${value.typeName})`}</Typography>
- </div>
- <div
- style={{
- flex: 1,
- wordBreak: "break-all",
- textAlign: "left"
- }}
- >
- {value.typeName == "string" ? (
- <HtmlRenderer
- htmlString={value.value}
- />
- ) : (
- renderValues(value)
- )}
- </div>
- </Stack>
+ <div className="bm-attribute-read-row">
+ <div className="bm-attribute-read-key">
+ <Typography fontWeight="600">{`${key} (${value.typeName})`}</Typography>
+ </div>
+ <div className="bm-attribute-read-value">
+ {value.typeName == "string" ? (
+ <HtmlRenderer
+ htmlString={value.value}
+ />
+ ) : (
+ renderValues(value)
+ )}
+ </div>
+ </div>
</AccordionDetails>
)}
</>
@@ -578,7 +648,7 @@ const BMAttributes = ({ loading, bmAttributes, entity }: BMAttributesProps) => {
}}
variant="outlined"
size="small"
- onClick={(e: React.MouseEvent) => {
+ onClick={(e: MouseEvent) => {
e.stopPropagation();
append(defaultField);
}}
@@ -589,139 +659,117 @@ const BMAttributes = ({ loading, bmAttributes, entity }: BMAttributesProps) => {
</LightTooltip>
)}
{fields.map((field, index) => {
- const keySelected = !isEmpty(
- bmAttributesValues?.[index]?.key
- );
return (
<Stack
- gap="0.5rem"
+ className="bm-attribute-row"
direction="row"
key={field?.id}
- alignItems={keySelected ? "flex-start" : "center"}
- sx={{
- '& .MuiAutocomplete-root': {
- alignSelf: keySelected ? 'stretch' : 'center'
- }
- }}
>
- <Controller
- control={control}
- name={`businessMetadata.${index}.key` as const}
- key={`businessMetadata.${index}.key` as const}
- defaultValue={field.key}
- render={({ field: { onChange, value } }) => (
- <>
- {field.key == null || isEmpty(bmAttributes) ? (
- <Autocomplete
- disableClearable={true}
- freeSolo
- size="small"
- value={isEmpty(value) ? null : value}
- options={getAvailableOptions(index)}
- onChange={(_, selectedOption) => {
- onChange(selectedOption);
- }}
- sx={{
- flexBasis: "35%",
- '& .MuiOutlinedInput-root': {
- height: 36
- }
- }}
- getOptionLabel={(option) => option.label}
- groupBy={(option) => option.group}
- noOptionsText="No results found"
- renderOption={(props, option, _state) => (
- <MenuItem {...props} key={option.label}>
- {`${option.label} (${option.typeName})`}
- </MenuItem>
- )}
- // className="advanced-search-autocomplete"
- className="bmattributes-key"
- renderInput={(params) => {
- return (
- <TextField
- {...params}
- placeholder="Select Attribute"
- InputProps={{
- ...params.InputProps,
- type: "search"
- }}
- />
- );
- }}
- />
- ) : (
- <InputLabel className="form-textfield-label">
- {`${value.label} (${
- value.value || value.typeName
- })`}
- </InputLabel>
- )}
- </>
- )}
- />
- <span
- style={{ margin: 0, alignSelf: "center" }}
- >
- :
- </span>
- {isEmpty(bmAttributesValues?.[index]?.key) ? (
+ <div className="bm-attribute-key-col">
<Controller
control={control}
- name={`businessMetadata.${index}.value` as const}
- rules={{
- required: true
- }}
- key={`businessMetadata.${index}.value` as const}
- render={({
- field: { onChange, value },
- fieldState: { error }
- }) => (
+ name={`businessMetadata.${index}.key` as const}
+ key={`businessMetadata.${index}.key` as const}
+ defaultValue={field.key}
+ render={({ field: { onChange, value } }) => (
<>
- <div
- style={{
- flex: "1",
- display: "flex",
- alignItems: "center"
- }}
- >
- <TextField
- margin="none"
- error={!!error}
- className="form-textfield bm-empty-field"
- onChange={onChange}
- value={value}
- variant="outlined"
+ {field.key == null || isEmpty(bmAttributes) ? (
+ <Autocomplete
+ disableClearable={true}
+ freeSolo
size="small"
- disabled
+ value={isEmpty(value) ? null : value}
+ options={getAvailableOptions(index)}
+ onChange={(_, selectedOption) => {
+ onChange(selectedOption);
+ }}
sx={{
- '& .MuiInputBase-root': {
+ width: "100%",
+ "& .MuiOutlinedInput-root": {
height: 36
- },
- "& .MuiInputBase-root.Mui-disabled": {
- backgroundColor: "#eee",
- cursor: "not-allowed"
}
}}
- type={"string"}
+ getOptionLabel={(option) => option.label}
+ groupBy={(option) => option.group}
+ noOptionsText="No results found"
+ renderOption={(props, option, _state) => (
+ <MenuItem {...props} key={option.label}>
+ {`${option.label} (${option.typeName})`}
+ </MenuItem>
+ )}
+ className="bmattributes-key"
+ renderInput={(params) => (
+ <TextField
+ {...params}
+ placeholder="Select Attribute"
+ InputProps={{
+ ...params.InputProps,
+ type: "search"
+ }}
+ />
+ )}
/>
- </div>
+ ) : (
+ <InputLabel className="bm-attribute-key-label">
+ {`${value?.label ?? ""} (${
+ value?.obj?.typeName ?? value?.value ?? ""
+ })`}
+ </InputLabel>
+ )}
</>
)}
/>
- ) : (
- <div style={{ flex: "1" }}>
- <Stack direction="row">
- <BMAttributesFields
- obj={bmAttributesValues[index].key.obj}
- control={control}
- index={index}
- />
- </Stack>
- </div>
- )}
+ </div>
+ <span className="bm-attribute-separator">:</span>
+ <div className="bm-attribute-value-col">
+ {isEmpty(bmAttributesValues?.[index]?.key) ? (
+ <Controller
+ control={control}
+ name={`businessMetadata.${index}.value` as const}
+ rules={{
+ required: true
+ }}
+ key={`businessMetadata.${index}.value` as const}
+ render={({
+ field: { onChange, value },
+ fieldState: { error }
+ }) => (
+ <TextField
+ margin="none"
+ error={!!error}
+ className="form-textfield bm-empty-field bm-attribute-value-field"
+ onChange={onChange}
+ value={value}
+ variant="outlined"
+ size="small"
+ disabled
+ fullWidth
+ sx={{
+ "& .MuiInputBase-root": {
+ height: 36
+ },
+ "& .MuiInputBase-root.Mui-disabled": {
+ backgroundColor: "#eee",
+ cursor: "not-allowed"
+ }
+ }}
+ type="string"
+ />
+ )}
+ />
+ ) : (
+ <BMAttributesFields
+ obj={bmAttributesValues[index]?.key?.obj ?? {
+ name: "",
+ typeName: ""
+ }}
+ control={fieldsControl}
+ index={index}
+ />
+ )}
+ </div>
- <Stack direction="row" gap="0.5rem">
+ <Stack className="bm-attribute-actions-col" direction="row">
{field.key === null ? (
<>
<IconButton
diff --git a/dashboard/src/views/DetailPage/EntityDetailTabs/PropertiesTab/BMAttributesFields.tsx b/dashboard/src/views/DetailPage/EntityDetailTabs/PropertiesTab/BMAttributesFields.tsx
index 9017f961e..ae4ca519b 100644
--- a/dashboard/src/views/DetailPage/EntityDetailTabs/PropertiesTab/BMAttributesFields.tsx
+++ b/dashboard/src/views/DetailPage/EntityDetailTabs/PropertiesTab/BMAttributesFields.tsx
@@ -24,47 +24,147 @@ import {
Stack,
TextField,
Autocomplete,
- createFilterOptions
+ createFilterOptions,
+ CircularProgress,
+ Typography
} from "@mui/material";
+import type { RootState } from "@redux/store/store";
+import {
+ areEnumOptionsEqual,
+ buildEnumOptionsForTypeName,
+ EnumOption,
+ getEnumOptionLabel,
+ isArrayTypeName,
+ isEnumTypeName,
+ isPotentialEnumTypeName,
+ normalizeMultiEnumValue
+} from "@utils/enumTypeUtils";
import { isEmpty } from "@utils/Utils";
import moment from "moment";
-import { Controller } from "react-hook-form";
+import { useEffect, type Ref } from "react";
+import { Control, Controller, FieldValues } from "react-hook-form";
import ReactQuill from "react-quill-new";
-const BMAttributesFields = ({ obj, control, index }: any) => {
- const { name, typeName } = obj || {};
+interface BMAttributeFieldObj {
+ name: string;
+ typeName: string;
+}
+
+interface BMAttributesFieldsProps {
+ obj: BMAttributeFieldObj;
+ control: Control<FieldValues>;
+ index: number;
+}
+
+type AutocompleteFreeSoloOption = string | EnumOption | { inputValue: string; label?: string };
- const { enumObj }: any = useAppSelector((state: any) => state.enum);
- const filter = createFilterOptions<any>();
- const { enumDefs } = enumObj?.data || {};
+interface DateValueFieldProps {
+ typeName: "date" | "array<date>";
+ value: unknown;
+ onChange: (value: unknown) => void;
+ fieldRef: Ref<unknown>;
+}
- let isMultiValued: string = typeName && typeName?.indexOf("array<") === 0;
- let multipleType: string = typeName?.match("array<(.*)>");
- let modeTypeName = typeName;
- let options: any,
- foundEnumType = {};
- if (!isMultiValued || typeName === "array<boolean>") {
- if (multipleType && multipleType[1]) {
- modeTypeName = multipleType[1];
+const DateValueField = ({
+ typeName,
+ value,
+ onChange,
+ fieldRef
+}: DateValueFieldProps) => {
+ useEffect(() => {
+ if (typeName === "date" && !value) {
+ onChange(new Date().toISOString());
}
- foundEnumType = !isEmpty(enumDefs)
- ? enumDefs.find((obj: { name: any }) => {
- return obj.name == modeTypeName;
- })
- : {};
- const { elementDefs }: any = foundEnumType || {};
+ }, [typeName, value, onChange]);
+
+ if (typeName === "date") {
+ return (
+ <CustomDatepicker
+ showPopperArrow={false}
+ popperProps={{ strategy: "fixed" }}
+ selected={
+ value && moment(value).isValid()
+ ? moment(value).toDate()
+ : moment().toDate()
+ }
+ onChange={(date: { getTime: () => number }) => {
+ onChange(date ? date.getTime() : null);
+ }}
+ ref={fieldRef}
+ dateFormat="MM/dd/yyyy"
+ />
+ );
+ }
+
+ return (
+ <CustomDatepicker
+ showPopperArrow={false}
+ popperProps={{ strategy: "fixed" }}
+ selectsMultiple
+ selectedDates={
+ Array.isArray(value)
+ ? value.map((d: string | number | Date) => new Date(d))
+ : []
+ }
+ onChange={(dates: Date[]) => {
+ onChange(
+ Array.isArray(dates) ? dates.map((date) => date.getTime()) : []
+ );
+ }}
+ shouldCloseOnSelect={false}
+ disabledKeyboardNavigation
+ ref={fieldRef}
+ dateFormat="MM/dd/yyyy"
+ />
+ );
+};
+
+const BMAttributesFields = ({ obj, control, index }: BMAttributesFieldsProps) => {
+ const { name, typeName } = obj || { name: "", typeName: "" };
+
+ const enumObj = useAppSelector((state: RootState) => state.enum.enumObj);
+ const filter = createFilterOptions<AutocompleteFreeSoloOption>();
+ const enumDefs = enumObj?.data?.enumDefs ?? [];
+ const enumLoading = enumObj?.loading === true;
+ const enumLoaded = enumObj?.data != null;
+
+ const isMultiValued = isArrayTypeName(typeName);
+ const isPotentialEnumType = isPotentialEnumTypeName(typeName);
+ const isEnumType = isEnumTypeName(typeName, enumDefs);
+ const options = buildEnumOptionsForTypeName(typeName, enumDefs);
+ const fieldWidthSx = { width: "100%" };
+ const booleanSelectId = `bm-boolean-select-${index}`;
+ const enumSelectId = `bm-enum-select-${index}`;
+
+ if (isPotentialEnumType && enumLoading) {
+ return (
+ <Stack
+ direction="row"
+ alignItems="center"
+ gap="0.5rem"
+ className="bm-enum-loading"
+ aria-label="Loading enum definitions"
+ >
+ <CircularProgress size={18} />
+ <Typography variant="body2" color="text.secondary">
+ Loading enum definitions...
+ </Typography>
+ </Stack>
+ );
+ }
- typeName == "array<boolean>"
- ? (options = [
- { label: "true", value: "true" },
- { label: "false", value: "false" }
- ])
- : (options = !isEmpty(elementDefs)
- ? elementDefs.map((obj: { value: any }) => {
- return { label: obj.value, value: obj.value };
- })
- : []);
+ if (isPotentialEnumType && enumLoaded && isEmpty(enumDefs)) {
+ return (
+ <Typography
+ variant="body2"
+ color="text.secondary"
+ className="bm-enum-unavailable-text"
+ >
+ No enum definitions present.
+ </Typography>
+ );
}
+
if (typeName === "date" || typeName === "array<date>") {
return (
<Controller
@@ -72,63 +172,23 @@ const BMAttributesFields = ({ obj, control, index }: any) => {
control={control}
key={`businessMetadata.${index}.value` as const}
defaultValue={new Date().toISOString()}
- render={({ field: { onChange, value, ref } }) => {
- if (!value) {
- const defaultDate = new Date();
- onChange(defaultDate.toISOString());
- }
-
- return typeName === "date" ? (
- <CustomDatepicker
- showPopperArrow={false}
- popperProps={{ strategy: "fixed" }}
- selected={
- value && moment(value).isValid()
- ? moment(value).toDate()
- : moment().toDate()
- }
- onChange={(date: { getTime: () => any }) => {
- onChange(date ? date.getTime() : null);
- }}
- ref={ref}
- dateFormat="MM/dd/yyyy"
- />
- ) : (
- <CustomDatepicker
- showPopperArrow={false}
- popperProps={{ strategy: "fixed" }}
- selectsMultiple
- selectedDates={
- Array.isArray(value)
- ? value.map((d: string | number | Date) => new Date(d))
- : []
- }
- onChange={(dates: any[]) => {
- onChange(
- Array.isArray(dates)
- ? dates.map((date) => date.getTime())
- : []
- );
- }}
- shouldCloseOnSelect={false}
- disabledKeyboardNavigation
- ref={ref}
- dateFormat="MM/dd/yyyy"
- />
- );
- }}
+ render={({ field: { onChange, value, ref } }) => (
+ <DateValueField
+ typeName={typeName as "date" | "array<date>"}
+ value={value}
+ onChange={onChange}
+ fieldRef={ref}
+ />
+ )}
/>
);
} else if (
- (typeName === "string" ||
- typeName === "int" ||
- typeName === "short" ||
- typeName === "float" ||
- typeName === "double" ||
- typeName === "long") &&
- typeName !== "array<boolean>" &&
- typeName !== "array<string>" &&
- typeName !== "array<date>"
+ typeName === "string" ||
+ typeName === "int" ||
+ typeName === "short" ||
+ typeName === "float" ||
+ typeName === "double" ||
+ typeName === "long"
) {
return (
<Controller
@@ -142,7 +202,7 @@ const BMAttributesFields = ({ obj, control, index }: any) => {
return (
<Stack gap="0.5rem">
<div style={{ position: "relative", flexBasis: "100%" }}>
- {typeName == "string" ? (
+ {typeName === "string" ? (
<ReactQuill
key={`quill-${index}-${name}`}
theme="snow"
@@ -157,19 +217,13 @@ const BMAttributesFields = ({ obj, control, index }: any) => {
<TextField
margin="none"
fullWidth
+ className="bm-attribute-value-field"
onChange={(e) => {
- const inputValue = e.target.value;
- // For numeric types, allow string input while typing, convert to number on blur
- if (typeName !== "string") {
- // Store as string to allow partial input (e.g., "-", "1.", etc.)
- field.onChange(inputValue);
- } else {
- field.onChange(inputValue);
- }
+ // Keep string while typing to allow partial numeric input (e.g., "-", "1.")
+ field.onChange(e.target.value);
}}
onBlur={(e) => {
- // On blur, convert valid numeric strings to numbers
- if (typeName !== "string" && e.target.value !== "") {
+ if (e.target.value !== "") {
const numValue = Number(e.target.value);
if (!isNaN(numValue)) {
field.onChange(numValue);
@@ -178,14 +232,10 @@ const BMAttributesFields = ({ obj, control, index }: any) => {
}}
variant="outlined"
size="small"
- type={typeName == "string" ? "text" : "number"}
+ type="number"
placeholder={name}
value={
- typeName == "string"
- ? typeof field.value === "string"
- ? field.value
- : ""
- : field.value !== null && field.value !== undefined
+ field.value !== null && field.value !== undefined
? String(field.value)
: ""
}
@@ -212,14 +262,16 @@ const BMAttributesFields = ({ obj, control, index }: any) => {
<div style={{ width: "100%" }}>
<Select
fullWidth
+ className="bm-attribute-value-field"
size="small"
- id="demo-select-small"
- value={value}
+ id={booleanSelectId}
+ displayEmpty
+ value={value ?? ""}
onChange={(e: SelectChangeEvent) => {
onChange(e.target.value);
}}
renderValue={(selected) => {
- if (selected.length === 0) {
+ if (!selected) {
return <em>--Select true or false--</em>;
}
@@ -242,7 +294,7 @@ const BMAttributesFields = ({ obj, control, index }: any) => {
typeName === "array<int>" ||
typeName === "array<short>" ||
typeName === "array<float>" ||
- typeName === "array<double" ||
+ typeName === "array<double>" ||
typeName === "array<boolean>" ||
typeName === "array<long>"
) {
@@ -251,9 +303,6 @@ const BMAttributesFields = ({ obj, control, index }: any) => {
name={`businessMetadata.${index}.value` as const}
control={control}
key={`autocomplete-${name}`}
- // rules={{
- // required: isOptional ? false : true
- // }}
defaultValue={[]}
render={({ field: { onChange, value }, fieldState: { error } }) => {
return (
@@ -262,25 +311,26 @@ const BMAttributesFields = ({ obj, control, index }: any) => {
size="small"
freeSolo
multiple
+ className="bm-attribute-value-field"
onChange={(_event, newValue) => {
onChange(newValue);
}}
sx={{
- flexBasis: "100%",
+ ...fieldWidthSx,
paddingTop: "4px",
paddingBottom: "4px",
paddingLeft: "6px",
gap: "4px",
- '& .MuiAutocomplete-inputRoot': {
- flexWrap: 'wrap'
+ "& .MuiAutocomplete-inputRoot": {
+ flexWrap: "wrap"
}
}}
- filterOptions={(options, params) => {
- const filtered = filter(options, params);
+ filterOptions={(optionList, params) => {
+ const filtered = filter(optionList, params);
const { inputValue } = params;
- const isExisting = options.some(
+ const isExisting = optionList.some(
(option) => inputValue === option
);
if (inputValue !== "" && !isExisting) {
@@ -289,7 +339,7 @@ const BMAttributesFields = ({ obj, control, index }: any) => {
});
}
- return typeName != "array<boolean>" ? filtered : options;
+ return typeName !== "array<boolean>" ? filtered : optionList;
}}
value={!isEmpty(value) && Array.isArray(value) ? value : []}
getOptionLabel={(option) => {
@@ -299,19 +349,25 @@ const BMAttributesFields = ({ obj, control, index }: any) => {
return !isEmpty(option?.inputValue)
? option.inputValue
- : option.label;
+ : option.label ?? "";
}}
options={!isEmpty(options) ? options : []}
renderOption={(props, option) => {
const { ...optionProps } = props;
- const { inputValue, label } = option;
- return <li {...optionProps}>{inputValue || label}</li>;
+ const optionLabel =
+ typeof option === "string"
+ ? option
+ : option.inputValue || option.label;
+ return <li {...optionProps}>{optionLabel}</li>;
}}
- isOptionEqualToValue={(option, value) => {
- if (!isEmpty(options?.label)) {
- return option.label === value.label;
+ isOptionEqualToValue={(option, selectedValue) => {
+ if (typeof option === "string" || typeof selectedValue === "string") {
+ return option === selectedValue;
}
- return option.inputValue === value.inputValue;
+ if (!isEmpty(option?.label) && !isEmpty(selectedValue?.label)) {
+ return option.label === selectedValue.label;
+ }
+ return option.inputValue === selectedValue.inputValue;
}}
filterSelectedOptions
renderInput={(params) => (
@@ -322,7 +378,7 @@ const BMAttributesFields = ({ obj, control, index }: any) => {
InputProps={{
...params.InputProps
}}
- type={typeName == "array<string>" ? "string" : "number"}
+ type={typeName === "array<string>" ? "string" : "number"}
placeholder={`Select a ${typeName} from the dropdown list`}
/>
)}
@@ -332,11 +388,7 @@ const BMAttributesFields = ({ obj, control, index }: any) => {
}}
/>
);
- } else if (
- typeName?.indexOf("array") > -1 &&
- typeName &&
- typeName !== "array<boolean>"
- ) {
+ } else if (isMultiValued && isEnumType) {
return (
<Controller
control={control}
@@ -344,50 +396,24 @@ const BMAttributesFields = ({ obj, control, index }: any) => {
key={`autocomplete-${name}`}
defaultValue={[]}
render={({ field: { onChange, value }, fieldState: { error } }) => {
+ const selectedValues = normalizeMultiEnumValue(value, options);
+
return (
<>
<Autocomplete
- freeSolo
size="small"
multiple
- onChange={(_event, item) => {
- onChange(item);
- }}
- sx={{ flexBasis: "100%" }}
- value={!isEmpty(value) && Array.isArray(value) ? value : []}
- filterOptions={(options, params) => {
- const filtered = filter(options, params);
-
- const { inputValue } = params;
-
- const isExisting = options.some(
- (option) => inputValue === option
- );
- if (inputValue !== "" && !isExisting) {
- filtered.push({
- inputValue
- });
- }
-
- return filtered;
+ disableCloseOnSelect
+ className="bm-attribute-value-field"
+ onChange={(_event, selectedOptions) => {
+ onChange(selectedOptions);
}}
+ sx={fieldWidthSx}
+ value={selectedValues}
filterSelectedOptions
- getOptionLabel={(option) => {
- if (typeof option === "string") {
- return option;
- }
-
- return !isEmpty(option?.inputValue)
- ? option.inputValue
- : option.label;
- }}
- isOptionEqualToValue={(option, value) => {
- if (!isEmpty(options?.label)) {
- return option.label === value.label;
- }
- return option.inputValue === value.inputValue;
- }}
- options={!isEmpty(options) ? options : []}
+ getOptionLabel={getEnumOptionLabel}
+ isOptionEqualToValue={areEnumOptionsEqual}
+ options={options}
renderInput={(params) => (
<TextField
{...params}
@@ -396,7 +422,7 @@ const BMAttributesFields = ({ obj, control, index }: any) => {
InputProps={{
...params.InputProps
}}
- placeholder={`Select a ${typeName} from the dropdown list`}
+ placeholder="Select enum values"
/>
)}
/>
@@ -405,10 +431,7 @@ const BMAttributesFields = ({ obj, control, index }: any) => {
}}
/>
);
- } else if (
- (typeName && typeName.indexOf("array") === -1) ||
- typeName !== "array<boolean>"
- ) {
+ } else if (isEnumType && !isMultiValued) {
return (
<Controller
name={`businessMetadata.${index}.value` as const}
@@ -420,14 +443,27 @@ const BMAttributesFields = ({ obj, control, index }: any) => {
<div style={{ width: "100%" }}>
<Select
fullWidth
+ className="bm-attribute-value-field"
size="small"
- id="demo-select-small"
+ id={enumSelectId}
+ inputProps={{ "aria-label": `Select ${name} enum value` }}
+ displayEmpty
value={!isEmpty(value) ? value : ""}
onChange={(e: SelectChangeEvent) => {
onChange(e.target.value);
}}
+ renderValue={(selected) => {
+ if (!selected) {
+ return <em>--Select Value--</em>;
+ }
+
+ return selected;
+ }}
>
- {options.map((option: any) => (
+ <MenuItem value="">
+ <em>--Select Value--</em>
+ </MenuItem>
+ {options.map((option: EnumOption) => (
<MenuItem key={option.value} value={option.value}>
{option.label}
</MenuItem>
@@ -450,11 +486,12 @@ const BMAttributesFields = ({ obj, control, index }: any) => {
margin="none"
error={!!error}
fullWidth
+ className="bm-attribute-value-field"
onChange={onChange}
value={value}
variant="outlined"
size="small"
- type={typeName == "string" ? "text" : "number"}
+ type={typeName === "string" ? "text" : "number"}
placeholder={name}
/>
</>
diff --git a/dashboard/src/views/DetailPage/EntityDetailTabs/PropertiesTab/__tests__/BMAttributes.enum.integration.test.tsx b/dashboard/src/views/DetailPage/EntityDetailTabs/PropertiesTab/__tests__/BMAttributes.enum.integration.test.tsx
new file mode 100644
index 000000000..cc077c18d
--- /dev/null
+++ b/dashboard/src/views/DetailPage/EntityDetailTabs/PropertiesTab/__tests__/BMAttributes.enum.integration.test.tsx
@@ -0,0 +1,244 @@
+/*
+ * 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 "@utils/test-utils";
+import "@testing-library/jest-dom";
+import BMAttributes from "../BMAttributes";
+import { ThemeProvider, createTheme } from "@mui/material/styles";
+
+const theme = createTheme();
+const mockEnumDefs = [
+ {
+ name: "adls_gen2_replication",
+ elementDefs: [{ value: "LRS" }, { value: "ZRS" }, { value: "GRS" }]
+ }
+];
+
+const mockDispatch = jest.fn();
+
+const buildEnumIntegrationState = () => ({
+ entity: {
+ entityData: {
+ entityDefs: [
+ {
+ name: "DataSet",
+ businessAttributeDefs: {
+ Group1: [
+ { name: "replication", typeName: "adls_gen2_replication" },
+ {
+ name: "replication_list",
+ typeName: "array<adls_gen2_replication>"
+ }
+ ]
+ }
+ }
+ ]
+ }
+ },
+ businessMetaData: {
+ businessMetaData: {
+ businessMetadataDefs: [
+ {
+ name: "Group1",
+ attributeDefs: [
+ { name: "replication", typeName: "adls_gen2_replication" },
+ {
+ name: "replication_list",
+ typeName: "array<adls_gen2_replication>"
+ }
+ ]
+ }
+ ]
+ }
+ },
+ enum: {
+ enumObj: {
+ loading: false,
+ data: { enumDefs: mockEnumDefs },
+ error: null
+ }
+ }
+});
+
+jest.mock("@hooks/reducerHook", () => ({
+ useAppDispatch: () => mockDispatch,
+ useAppSelector: jest.fn((selector) => selector(buildEnumIntegrationState()))
+}));
+
+jest.mock("react-router-dom", () => ({
+ ...jest.requireActual("react-router-dom"),
+ useParams: () => ({ guid: "test-guid-123" })
+}));
+
+const mockGetEntityBusinessMetadata = jest.fn();
+jest.mock("@api/apiMethods/detailpageApiMethod", () => ({
+ getEntityBusinessMetadata: (...args: unknown[]) =>
+ mockGetEntityBusinessMetadata(...args)
+}));
+
+jest.mock("react-toastify", () => ({
+ toast: {
+ dismiss: jest.fn(),
+ success: jest.fn(() => "toast-id"),
+ error: jest.fn(() => "toast-id")
+ }
+}));
+
+jest.mock("@utils/Utils", () => ({
+ ...jest.requireActual("@utils/Utils"),
+ serverError: jest.fn()
+}));
+
+jest.mock("@redux/slice/detailPageSlice", () => ({
+ fetchDetailPageData: jest.fn((guid: string) => ({
+ type: "fetchDetailPageData",
+ payload: guid
+ }))
+}));
+
+jest.mock("@redux/slice/enumSlice", () => ({
+ fetchEnumData: jest.fn(() => ({ type: "FETCH_ENUM_DATA" }))
+}));
+
+jest.mock("@components/DatePicker/CustomDatepicker", () => ({
+ __esModule: true,
+ default: () => <input data-testid="date-picker" />
+}));
+
+jest.mock("react-quill-new", () => ({
+ __esModule: true,
+ default: ({ placeholder }: { placeholder: string }) => (
+ <div data-testid="react-quill">{placeholder}</div>
+ )
+}));
+
+const TestWrapper: React.FC<React.PropsWithChildren<{}>> = ({ children }) => (
+ <ThemeProvider theme={theme}>{children}</ThemeProvider>
+);
+
+describe("BMAttributes enum integration (no BMAttributesFields mock)", () => {
+ const enumProps = {
+ loading: false,
+ bmAttributes: {
+ Group1: {
+ replication: "LRS",
+ replication_list: ["LRS", "ZRS"]
+ }
+ },
+ entity: { guid: "test-guid-123", status: "ACTIVE", typeName: "DataSet" }
+ };
+
+ beforeEach(() => {
+ jest.clearAllMocks();
+ mockGetEntityBusinessMetadata.mockResolvedValue({ data: {} });
+ });
+
+ it("renders real enum Select dropdown in edit mode (positive)", () => {
+ render(
+ <TestWrapper>
+ <BMAttributes {...enumProps} />
+ </TestWrapper>
+ );
+
+ fireEvent.click(screen.getByText("Edit").closest("button")!);
+
+ expect(
+ screen.getByLabelText(/Select replication enum value/i)
+ ).toBeInTheDocument();
+ expect(screen.getAllByText("LRS").length).toBeGreaterThan(0);
+ expect(screen.getByLabelText(/Select replication enum value/i)).toHaveTextContent(
+ "LRS"
+ );
+ });
+
+ it("saves single enum value end-to-end after changing dropdown (positive)", async () => {
+ render(
+ <TestWrapper>
+ <BMAttributes {...enumProps} />
+ </TestWrapper>
+ );
+
+ fireEvent.click(screen.getByText("Edit").closest("button")!);
+
+ const select = screen.getByLabelText(/Select replication enum value/i);
+ fireEvent.mouseDown(select);
+ fireEvent.click(screen.getByRole("option", { name: "GRS" }));
+
+ const saveBtn = screen.getByText("Save").closest("button")!;
+ await act(async () => {
+ fireEvent.click(saveBtn);
+ });
+
+ await waitFor(() => {
+ expect(mockGetEntityBusinessMetadata).toHaveBeenCalledWith(
+ "test-guid-123",
+ expect.objectContaining({
+ Group1: expect.objectContaining({ replication: "GRS" })
+ })
+ );
+ });
+ });
+
+ it("serializes array enum values on save via serializeMultiEnumValue (positive)", async () => {
+ render(
+ <TestWrapper>
+ <BMAttributes {...enumProps} />
+ </TestWrapper>
+ );
+
+ fireEvent.click(screen.getByText("Edit").closest("button")!);
+
+ const saveBtn = screen.getByText("Save").closest("button")!;
+ await act(async () => {
+ fireEvent.click(saveBtn);
+ });
+
+ await waitFor(() => {
+ expect(mockGetEntityBusinessMetadata).toHaveBeenCalledWith(
+ "test-guid-123",
+ {
+ Group1: {
+ replication: "LRS",
+ replication_list: ["LRS", "ZRS"]
+ }
+ }
+ );
+ });
+ });
+
+ it("does not call save API when enum field row has no key selected (negative)", async () => {
+ render(
+ <TestWrapper>
+ <BMAttributes
+ loading={false}
+ bmAttributes={{}}
+ entity={{ guid: "test-guid-123", status: "ACTIVE", typeName: "DataSet" }}
+ />
+ </TestWrapper>
+ );
+
+ fireEvent.click(screen.getByText("Add").closest("button")!);
+
+ const saveBtn = screen.getByText("Save").closest("button")!;
+ await act(async () => {
+ fireEvent.click(saveBtn);
+ });
+
+ expect(mockGetEntityBusinessMetadata).not.toHaveBeenCalled();
+ });
+});
diff --git a/dashboard/src/views/DetailPage/EntityDetailTabs/PropertiesTab/__tests__/BMAttributes.test.tsx b/dashboard/src/views/DetailPage/EntityDetailTabs/PropertiesTab/__tests__/BMAttributes.test.tsx
index 6751e3b21..e233b14bb 100644
--- a/dashboard/src/views/DetailPage/EntityDetailTabs/PropertiesTab/__tests__/BMAttributes.test.tsx
+++ b/dashboard/src/views/DetailPage/EntityDetailTabs/PropertiesTab/__tests__/BMAttributes.test.tsx
@@ -56,6 +56,13 @@ jest.mock('@hooks/reducerHook', () => ({
}
]
}
+ },
+ enum: {
+ enumObj: {
+ loading: false,
+ data: null,
+ error: null
+ }
}
};
return selector(state);
@@ -89,6 +96,10 @@ jest.mock('@redux/slice/detailPageSlice', () => ({
fetchDetailPageData: jest.fn((guid: string) => ({ type: 'fetchDetailPageData', payload: guid }))
}));
+jest.mock('@redux/slice/enumSlice', () => ({
+ fetchEnumData: jest.fn(() => ({ type: 'FETCH_ENUM_DATA' }))
+}));
+
// Mock BMAttributesFields to avoid complex form input mocks unless needed
jest.mock('../BMAttributesFields', () => {
return function MockBMAttributesFields(props: any) {
@@ -222,6 +233,173 @@ describe('BMAttributes Component', () => {
expect(serverError).toHaveBeenCalled();
});
+ it('dispatches fetchEnumData when enum data has not been loaded', () => {
+ const { fetchEnumData } = require('@redux/slice/enumSlice');
+
+ render(<TestWrapper><BMAttributes {...defaultProps} /></TestWrapper>);
+
+ expect(fetchEnumData).toHaveBeenCalled();
+ expect(mockDispatch).toHaveBeenCalledWith({ type: 'FETCH_ENUM_DATA' });
+ });
+
+ it('does not refetch enum data when enum definitions are already loaded', () => {
+ const { fetchEnumData } = require('@redux/slice/enumSlice');
+ const { useAppSelector } = require('@hooks/reducerHook');
+
+ fetchEnumData.mockClear();
+ useAppSelector.mockImplementation((selector: any) =>
+ selector({
+ entity: {
+ entityData: {
+ entityDefs: [
+ {
+ name: 'DataSet',
+ businessAttributeDefs: {
+ Group1: [
+ { name: 'attr1', typeName: 'string' },
+ { name: 'attr2', typeName: 'int' }
+ ]
+ }
+ }
+ ]
+ }
+ },
+ businessMetaData: {
+ businessMetaData: {
+ businessMetadataDefs: [
+ {
+ name: 'Group1',
+ attributeDefs: [
+ { name: 'attr1', typeName: 'string' },
+ { name: 'attr2', typeName: 'int' }
+ ]
+ }
+ ]
+ }
+ },
+ enum: {
+ enumObj: {
+ loading: false,
+ data: { enumDefs: [] },
+ error: null
+ }
+ }
+ })
+ );
+
+ render(<TestWrapper><BMAttributes {...defaultProps} /></TestWrapper>);
+
+ expect(fetchEnumData).not.toHaveBeenCalled();
+ });
+
+ it('does not refetch enum data when enum fetch previously failed', () => {
+ const { fetchEnumData } = require('@redux/slice/enumSlice');
+ const { useAppSelector } = require('@hooks/reducerHook');
+
+ fetchEnumData.mockClear();
+ useAppSelector.mockImplementation((selector: any) =>
+ selector({
+ entity: {
+ entityData: {
+ entityDefs: [
+ {
+ name: 'DataSet',
+ businessAttributeDefs: {
+ Group1: [
+ { name: 'attr1', typeName: 'string' },
+ { name: 'attr2', typeName: 'int' }
+ ]
+ }
+ }
+ ]
+ }
+ },
+ businessMetaData: {
+ businessMetaData: {
+ businessMetadataDefs: [
+ {
+ name: 'Group1',
+ attributeDefs: [
+ { name: 'attr1', typeName: 'string' },
+ { name: 'attr2', typeName: 'int' }
+ ]
+ }
+ ]
+ }
+ },
+ enum: {
+ enumObj: {
+ loading: false,
+ data: null,
+ error: 'Failed to load enum definitions'
+ }
+ }
+ })
+ );
+
+ render(<TestWrapper><BMAttributes {...defaultProps} /></TestWrapper>);
+
+ expect(fetchEnumData).not.toHaveBeenCalled();
+ });
+
+ it('disables save while enum definitions are loading for enum attributes', () => {
+ const { useAppSelector } = require('@hooks/reducerHook');
+
+ useAppSelector.mockImplementation((selector: any) =>
+ selector({
+ entity: {
+ entityData: {
+ entityDefs: [
+ {
+ name: 'DataSet',
+ businessAttributeDefs: {
+ Group1: [
+ { name: 'replication', typeName: 'adls_gen2_replication' }
+ ]
+ }
+ }
+ ]
+ }
+ },
+ businessMetaData: {
+ businessMetaData: {
+ businessMetadataDefs: [
+ {
+ name: 'Group1',
+ attributeDefs: [
+ { name: 'replication', typeName: 'adls_gen2_replication' }
+ ]
+ }
+ ]
+ }
+ },
+ enum: {
+ enumObj: {
+ loading: true,
+ data: null,
+ error: null
+ }
+ }
+ })
+ );
+
+ const enumProps = {
+ loading: false,
+ bmAttributes: {
+ Group1: {
+ replication: 'LRS'
+ }
+ },
+ entity: { guid: 'test-guid-123', status: 'ACTIVE', typeName: 'DataSet' }
+ };
+
+ render(<TestWrapper><BMAttributes {...enumProps} /></TestWrapper>);
+ fireEvent.click(screen.getByText('Edit').closest('button')!);
+
+ const saveBtn = screen.getByText('Save').closest('button');
+ expect(saveBtn).toBeDisabled();
+ });
+
it('hides Add button while loading', () => {
render(<TestWrapper><BMAttributes loading={true} bmAttributes={{}} entity={{ status: 'ACTIVE', typeName: 'DataSet' }} /></TestWrapper>);
expect(screen.queryByText('Add')).not.toBeInTheDocument();
@@ -232,4 +410,291 @@ describe('BMAttributes Component', () => {
expect(screen.queryByText('Edit')).not.toBeInTheDocument();
});
+ it('serializes array<string> values on save (positive)', async () => {
+ const { useAppSelector } = require('@hooks/reducerHook');
+ mockGetEntityBusinessMetadata.mockResolvedValueOnce({ data: {} });
+
+ useAppSelector.mockImplementation((selector: any) =>
+ selector({
+ entity: {
+ entityData: {
+ entityDefs: [{
+ name: 'DataSet',
+ businessAttributeDefs: {
+ Group1: [{ name: 'tags', typeName: 'array<string>' }]
+ }
+ }]
+ }
+ },
+ businessMetaData: {
+ businessMetaData: {
+ businessMetadataDefs: [{
+ name: 'Group1',
+ attributeDefs: [{ name: 'tags', typeName: 'array<string>' }]
+ }]
+ }
+ },
+ enum: { enumObj: { loading: false, data: { enumDefs: [] }, error: null } }
+ })
+ );
+
+ render(
+ <TestWrapper>
+ <BMAttributes
+ loading={false}
+ bmAttributes={{ Group1: { tags: ['a', 'b'] } }}
+ entity={{ guid: 'test-guid-123', status: 'ACTIVE', typeName: 'DataSet' }}
+ />
+ </TestWrapper>
+ );
+
+ fireEvent.click(screen.getByText('Edit').closest('button')!);
+ await act(async () => {
+ fireEvent.click(screen.getByText('Save').closest('button')!);
+ });
+
+ await waitFor(() => {
+ expect(mockGetEntityBusinessMetadata).toHaveBeenCalledWith('test-guid-123', {
+ Group1: { tags: ['a', 'b'] }
+ });
+ });
+ });
+
+ it('serializes array<date> timestamps on save without transformation (positive)', async () => {
+ const { useAppSelector } = require('@hooks/reducerHook');
+ mockGetEntityBusinessMetadata.mockResolvedValueOnce({ data: {} });
+
+ const dateTimestamps = [1717200000000, 1717286400000];
+
+ useAppSelector.mockImplementation((selector: any) =>
+ selector({
+ entity: {
+ entityData: {
+ entityDefs: [{
+ name: 'DataSet',
+ businessAttributeDefs: {
+ Group1: [{ name: 'eventDates', typeName: 'array<date>' }]
+ }
+ }]
+ }
+ },
+ businessMetaData: {
+ businessMetaData: {
+ businessMetadataDefs: [{
+ name: 'Group1',
+ attributeDefs: [{ name: 'eventDates', typeName: 'array<date>' }]
+ }]
+ }
+ },
+ enum: { enumObj: { loading: false, data: { enumDefs: [] }, error: null } }
+ })
+ );
+
+ render(
+ <TestWrapper>
+ <BMAttributes
+ loading={false}
+ bmAttributes={{ Group1: { eventDates: dateTimestamps } }}
+ entity={{ guid: 'test-guid-123', status: 'ACTIVE', typeName: 'DataSet' }}
+ />
+ </TestWrapper>
+ );
+
+ fireEvent.click(screen.getByText('Edit').closest('button')!);
+ await act(async () => {
+ fireEvent.click(screen.getByText('Save').closest('button')!);
+ });
+
+ await waitFor(() => {
+ expect(mockGetEntityBusinessMetadata).toHaveBeenCalledWith('test-guid-123', {
+ Group1: { eventDates: dateTimestamps }
+ });
+ });
+ });
+
+ it('serializes empty array<date> payload when value is missing (negative)', async () => {
+ const { useAppSelector } = require('@hooks/reducerHook');
+ mockGetEntityBusinessMetadata.mockResolvedValueOnce({ data: {} });
+
+ useAppSelector.mockImplementation((selector: any) =>
+ selector({
+ entity: {
+ entityData: {
+ entityDefs: [{
+ name: 'DataSet',
+ businessAttributeDefs: {
+ Group1: [{ name: 'eventDates', typeName: 'array<date>' }]
+ }
+ }]
+ }
+ },
+ businessMetaData: {
+ businessMetaData: {
+ businessMetadataDefs: [{
+ name: 'Group1',
+ attributeDefs: [{ name: 'eventDates', typeName: 'array<date>' }]
+ }]
+ }
+ },
+ enum: { enumObj: { loading: false, data: { enumDefs: [] }, error: null } }
+ })
+ );
+
+ render(
+ <TestWrapper>
+ <BMAttributes
+ loading={false}
+ bmAttributes={{ Group1: { eventDates: [] } }}
+ entity={{ guid: 'test-guid-123', status: 'ACTIVE', typeName: 'DataSet' }}
+ />
+ </TestWrapper>
+ );
+
+ fireEvent.click(screen.getByText('Edit').closest('button')!);
+ await act(async () => {
+ fireEvent.click(screen.getByText('Save').closest('button')!);
+ });
+
+ await waitFor(() => {
+ expect(mockGetEntityBusinessMetadata).toHaveBeenCalledWith('test-guid-123', {
+ Group1: { eventDates: [] }
+ });
+ });
+ });
+
+ it('serializes boolean and date values on save (positive)', async () => {
+ const { useAppSelector } = require('@hooks/reducerHook');
+ mockGetEntityBusinessMetadata.mockResolvedValueOnce({ data: {} });
+
+ useAppSelector.mockImplementation((selector: any) =>
+ selector({
+ entity: {
+ entityData: {
+ entityDefs: [{
+ name: 'DataSet',
+ businessAttributeDefs: {
+ Group1: [
+ { name: 'active', typeName: 'boolean' },
+ { name: 'created', typeName: 'date' }
+ ]
+ }
+ }]
+ }
+ },
+ businessMetaData: {
+ businessMetaData: {
+ businessMetadataDefs: [{
+ name: 'Group1',
+ attributeDefs: [
+ { name: 'active', typeName: 'boolean' },
+ { name: 'created', typeName: 'date' }
+ ]
+ }]
+ }
+ },
+ enum: { enumObj: { loading: false, data: { enumDefs: [] }, error: null } }
+ })
+ );
+
+ render(
+ <TestWrapper>
+ <BMAttributes
+ loading={false}
+ bmAttributes={{
+ Group1: {
+ active: true,
+ created: 1717200000000
+ }
+ }}
+ entity={{ guid: 'test-guid-123', status: 'ACTIVE', typeName: 'DataSet' }}
+ />
+ </TestWrapper>
+ );
+
+ fireEvent.click(screen.getByText('Edit').closest('button')!);
+ await act(async () => {
+ fireEvent.click(screen.getByText('Save').closest('button')!);
+ });
+
+ await waitFor(() => {
+ expect(mockGetEntityBusinessMetadata).toHaveBeenCalledWith(
+ 'test-guid-123',
+ expect.objectContaining({
+ Group1: expect.objectContaining({
+ active: expect.any(Boolean),
+ created: expect.any(Number)
+ })
+ })
+ );
+ });
+ });
+
+ it('renders read mode for array, date, and boolean values (positive)', () => {
+ const { useAppSelector } = require('@hooks/reducerHook');
+
+ useAppSelector.mockImplementation((selector: any) =>
+ selector({
+ entity: {
+ entityData: {
+ entityDefs: [{
+ name: 'DataSet',
+ businessAttributeDefs: {
+ Group1: [
+ { name: 'flags', typeName: 'array<int>' },
+ { name: 'dates', typeName: 'array<date>' },
+ { name: 'active', typeName: 'boolean' }
+ ]
+ }
+ }]
+ }
+ },
+ businessMetaData: {
+ businessMetaData: {
+ businessMetadataDefs: [{
+ name: 'Group1',
+ attributeDefs: [
+ { name: 'flags', typeName: 'array<int>' },
+ { name: 'dates', typeName: 'array<date>' },
+ { name: 'active', typeName: 'boolean' }
+ ]
+ }]
+ }
+ },
+ enum: { enumObj: { loading: false, data: { enumDefs: [] }, error: null } }
+ })
+ );
+
+ render(
+ <TestWrapper>
+ <BMAttributes
+ loading={false}
+ bmAttributes={{
+ Group1: {
+ flags: [1, 2],
+ dates: [1717200000000],
+ active: true
+ }
+ }}
+ entity={{ guid: 'test-guid-123', status: 'ACTIVE', typeName: 'DataSet' }}
+ />
+ </TestWrapper>
+ );
+
+ expect(screen.getByText('flags (array<int>)')).toBeInTheDocument();
+ expect(screen.getByText('1, 2')).toBeInTheDocument();
+ expect(screen.getByText('active (boolean)')).toBeInTheDocument();
+ expect(screen.getByText('true')).toBeInTheDocument();
+ });
+
+ it('cancels edit mode and restores read view (negative)', () => {
+ render(<TestWrapper><BMAttributes {...defaultProps} /></TestWrapper>);
+
+ fireEvent.click(screen.getByText('Edit').closest('button')!);
+ expect(screen.getAllByRole('button', { name: /save/i }).length).toBeGreaterThan(0);
+
+ fireEvent.click(screen.getAllByRole('button', { name: /cancel/i })[0]);
+ expect(screen.queryByText('Save')).not.toBeInTheDocument();
+ expect(screen.getByText('Edit')).toBeInTheDocument();
+ });
+
});
diff --git a/dashboard/src/views/DetailPage/EntityDetailTabs/PropertiesTab/__tests__/BMAttributesFields.test.tsx b/dashboard/src/views/DetailPage/EntityDetailTabs/PropertiesTab/__tests__/BMAttributesFields.test.tsx
new file mode 100644
index 000000000..005e7f75d
--- /dev/null
+++ b/dashboard/src/views/DetailPage/EntityDetailTabs/PropertiesTab/__tests__/BMAttributesFields.test.tsx
@@ -0,0 +1,475 @@
+/*
+ * 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 "@utils/test-utils";
+import { useForm, useWatch } from "react-hook-form";
+import { ThemeProvider, createTheme } from "@mui/material/styles";
+import BMAttributesFields from "../BMAttributesFields";
+
+const mockEnumDefs = [
+ {
+ name: "adls_gen2_replication",
+ elementDefs: [
+ { value: "LRS" },
+ { value: "ZRS" },
+ { value: "GRS" }
+ ]
+ }
+];
+
+const mockUseAppSelector = jest.fn((selector) =>
+ selector({
+ enum: {
+ enumObj: {
+ loading: false,
+ data: {
+ enumDefs: mockEnumDefs
+ },
+ error: null
+ }
+ }
+ })
+);
+
+jest.mock("@hooks/reducerHook", () => ({
+ useAppSelector: (selector: unknown) => mockUseAppSelector(selector)
+}));
+
+const SINGLE_DATE_TIMESTAMP = 1717200000000;
+const MULTI_DATE_TIMESTAMPS = [1717200000000, 1717286400000];
+
+jest.mock("@components/DatePicker/CustomDatepicker", () => ({
+ __esModule: true,
+ default: ({
+ onChange,
+ selectsMultiple,
+ selected,
+ selectedDates
+ }: {
+ onChange: (value: unknown) => void;
+ selectsMultiple?: boolean;
+ selected?: Date;
+ selectedDates?: Date[];
+ }) => (
+ <input
+ data-testid={selectsMultiple ? "date-picker-multi" : "date-picker"}
+ data-selected={selected ? String(selected.getTime()) : ""}
+ data-selected-dates={
+ selectedDates?.length
+ ? selectedDates.map((date) => date.getTime()).join(",")
+ : ""
+ }
+ onClick={() => {
+ if (selectsMultiple) {
+ onChange(
+ MULTI_DATE_TIMESTAMPS.map((timestamp) => new Date(timestamp))
+ );
+ return;
+ }
+ onChange({ getTime: () => SINGLE_DATE_TIMESTAMP });
+ }}
+ />
+ )
+}));
+
+jest.mock("react-quill-new", () => ({
+ __esModule: true,
+ default: ({
+ placeholder,
+ onChange,
+ value
+ }: {
+ placeholder: string;
+ onChange: (value: string) => void;
+ value: string;
+ }) => (
+ <input
+ data-testid="react-quill"
+ placeholder={placeholder}
+ value={value}
+ onChange={(event) => onChange(event.target.value)}
+ />
+ )
+}));
+
+const theme = createTheme();
+
+const TestHarness = ({
+ typeName,
+ name = "testAttr",
+ defaultValue,
+ showFormValue = false
+}: {
+ typeName: string;
+ name?: string;
+ defaultValue?: unknown;
+ showFormValue?: boolean;
+}) => {
+ const resolvedDefault =
+ defaultValue !== undefined
+ ? defaultValue
+ : typeName.startsWith("array<")
+ ? []
+ : "";
+
+ const { control } = useForm({
+ defaultValues: {
+ businessMetadata: [
+ { key: { obj: { name, typeName } }, value: resolvedDefault }
+ ]
+ }
+ });
+
+ const currentValue = useWatch({
+ control,
+ name: "businessMetadata.0.value"
+ });
+
+ return (
+ <ThemeProvider theme={theme}>
+ <BMAttributesFields
+ obj={{ name, typeName }}
+ control={control}
+ index={0}
+ />
+ {showFormValue && (
+ <span data-testid="form-value">{JSON.stringify(currentValue)}</span>
+ )}
+ </ThemeProvider>
+ );
+};
+
+describe("BMAttributesFields enum rendering", () => {
+ beforeEach(() => {
+ mockUseAppSelector.mockImplementation((selector) =>
+ selector({
+ enum: {
+ enumObj: {
+ loading: false,
+ data: {
+ enumDefs: mockEnumDefs
+ },
+ error: null
+ }
+ }
+ })
+ );
+ });
+
+ it("renders MUI Select dropdown for single-value enum (positive)", () => {
+ render(<TestHarness typeName="adls_gen2_replication" defaultValue="LRS" />);
+
+ expect(
+ screen.getByLabelText(/Select testAttr enum value/i)
+ ).toBeInTheDocument();
+ const select = screen.getByRole("combobox");
+ expect(select).toBeInTheDocument();
+ expect(screen.getByText("LRS")).toBeInTheDocument();
+
+ fireEvent.mouseDown(select);
+ expect(screen.getByRole("option", { name: "ZRS" })).toBeInTheDocument();
+ expect(screen.getByRole("option", { name: "GRS" })).toBeInTheDocument();
+ });
+
+ it("updates single enum value on selection change (positive)", () => {
+ render(<TestHarness typeName="adls_gen2_replication" defaultValue="" />);
+
+ const select = screen.getByRole("combobox");
+ fireEvent.mouseDown(select);
+ fireEvent.click(screen.getByRole("option", { name: "GRS" }));
+ expect(select).toHaveTextContent("GRS");
+ });
+
+ it("shows placeholder option for new single-value enum (positive)", () => {
+ render(<TestHarness typeName="adls_gen2_replication" defaultValue="" />);
+
+ expect(screen.getByText("--Select Value--")).toBeInTheDocument();
+ });
+
+ it("renders free-text Autocomplete for array<double> (positive)", () => {
+ render(<TestHarness typeName="array<double>" defaultValue={["1.5"]} />);
+
+ expect(screen.getByRole("combobox")).toBeInTheDocument();
+ expect(
+ screen.getByPlaceholderText("Select a array<double> from the dropdown list")
+ ).toBeInTheDocument();
+ });
+
+ it("renders constrained multi-select for array enum (positive)", () => {
+ render(
+ <TestHarness
+ typeName="array<adls_gen2_replication>"
+ defaultValue={["LRS", "ZRS"]}
+ />
+ );
+
+ const autocomplete = screen.getByRole("combobox");
+ expect(autocomplete).toBeInTheDocument();
+ expect(screen.getByText("LRS")).toBeInTheDocument();
+ expect(screen.getByText("ZRS")).toBeInTheDocument();
+ });
+
+ it("keeps free-text searchable Autocomplete for array<string> (negative)", () => {
+ render(<TestHarness typeName="array<string>" defaultValue={["alpha"]} />);
+
+ const autocomplete = screen.getByRole("combobox");
+ expect(autocomplete).toBeInTheDocument();
+ expect(
+ screen.getByPlaceholderText("Select a array<string> from the dropdown list")
+ ).toBeInTheDocument();
+ });
+
+ it("shows loading state while enum definitions are fetching (positive)", () => {
+ mockUseAppSelector.mockImplementationOnce((selector) =>
+ selector({
+ enum: {
+ enumObj: {
+ loading: true,
+ data: null,
+ error: null
+ }
+ }
+ })
+ );
+
+ render(<TestHarness typeName="adls_gen2_replication" defaultValue="" />);
+
+ expect(screen.getByLabelText("Loading enum definitions")).toBeInTheDocument();
+ expect(screen.getByText("Loading enum definitions...")).toBeInTheDocument();
+ expect(screen.queryByRole("combobox")).not.toBeInTheDocument();
+ });
+
+ it("shows readable message when no enum definitions are present (negative)", () => {
+ mockUseAppSelector.mockImplementationOnce((selector) =>
+ selector({
+ enum: {
+ enumObj: {
+ loading: false,
+ data: {
+ enumDefs: []
+ },
+ error: null
+ }
+ }
+ })
+ );
+
+ render(<TestHarness typeName="adls_gen2_replication" defaultValue="" />);
+
+ expect(screen.getByText("No enum definitions present.")).toBeInTheDocument();
+ expect(screen.queryByRole("combobox")).not.toBeInTheDocument();
+ });
+
+ it("falls back to TextField for unknown enum when enum definitions exist (negative)", () => {
+ render(<TestHarness typeName="array<unknown_enum>" defaultValue="" />);
+
+ expect(screen.getByPlaceholderText("testAttr")).toBeInTheDocument();
+ expect(screen.queryByText("No enum definitions present.")).not.toBeInTheDocument();
+ });
+});
+
+describe("BMAttributesFields primitive and date rendering", () => {
+ beforeEach(() => {
+ mockUseAppSelector.mockImplementation((selector) =>
+ selector({
+ enum: {
+ enumObj: {
+ loading: false,
+ data: { enumDefs: mockEnumDefs },
+ error: null
+ }
+ }
+ })
+ );
+ });
+
+ it("initializes single date when value is empty (positive)", () => {
+ render(<TestHarness typeName="date" defaultValue={null} showFormValue />);
+
+ const picker = screen.getByTestId("date-picker");
+ expect(picker.getAttribute("data-selected")).toBeTruthy();
+ });
+
+ it("sets single date timestamp on picker change (positive)", async () => {
+ render(
+ <TestHarness
+ typeName="date"
+ defaultValue={SINGLE_DATE_TIMESTAMP}
+ showFormValue
+ />
+ );
+
+ const picker = screen.getByTestId("date-picker");
+ expect(picker).toHaveAttribute(
+ "data-selected",
+ String(SINGLE_DATE_TIMESTAMP)
+ );
+
+ await act(async () => {
+ fireEvent.click(picker);
+ });
+
+ await waitFor(() => {
+ expect(screen.getByTestId("form-value")).toHaveTextContent(
+ String(SINGLE_DATE_TIMESTAMP)
+ );
+ });
+ });
+
+ it("uses current date when single date value is invalid (negative)", () => {
+ render(
+ <TestHarness typeName="date" defaultValue="not-a-valid-date" showFormValue />
+ );
+
+ const picker = screen.getByTestId("date-picker");
+ expect(picker).toBeInTheDocument();
+ expect(picker.getAttribute("data-selected")).toBeTruthy();
+ });
+
+ it("sets multi date timestamps on picker change (positive)", async () => {
+ render(
+ <TestHarness
+ typeName="array<date>"
+ defaultValue={[SINGLE_DATE_TIMESTAMP]}
+ showFormValue
+ />
+ );
+
+ const picker = screen.getByTestId("date-picker-multi");
+ expect(picker).toHaveAttribute(
+ "data-selected-dates",
+ String(SINGLE_DATE_TIMESTAMP)
+ );
+
+ await act(async () => {
+ fireEvent.click(picker);
+ });
+
+ await waitFor(() => {
+ expect(screen.getByTestId("form-value")).toHaveTextContent(
+ JSON.stringify(MULTI_DATE_TIMESTAMPS)
+ );
+ });
+ });
+
+ it("renders empty multi date picker when no dates selected (negative)", () => {
+ render(<TestHarness typeName="array<date>" defaultValue={[]} showFormValue />);
+
+ const picker = screen.getByTestId("date-picker-multi");
+ expect(picker).toHaveAttribute("data-selected-dates", "");
+ expect(screen.getByTestId("form-value")).toHaveTextContent("[]");
+ });
+
+ it("renders ReactQuill for string type (positive)", () => {
+ render(<TestHarness typeName="string" defaultValue="hello" />);
+
+ const editor = screen.getByTestId("react-quill");
+ expect(editor).toBeInTheDocument();
+ fireEvent.change(editor, { target: { value: "updated" } });
+ expect(editor).toHaveValue("updated");
+ });
+
+ it("renders numeric TextField for int and converts on blur (positive)", () => {
+ render(<TestHarness typeName="int" defaultValue="" />);
+
+ const input = screen.getByPlaceholderText("testAttr");
+ fireEvent.change(input, { target: { value: "42" } });
+ fireEvent.blur(input);
+ expect(input).toBeInTheDocument();
+ });
+
+ it("renders float TextField with step any (positive)", () => {
+ render(<TestHarness typeName="float" defaultValue={1.5} />);
+
+ expect(screen.getByPlaceholderText("testAttr")).toBeInTheDocument();
+ });
+
+ it("renders long and short numeric fields (positive)", () => {
+ render(<TestHarness typeName="long" defaultValue={100} />);
+ expect(screen.getByPlaceholderText("testAttr")).toBeInTheDocument();
+
+ render(<TestHarness typeName="short" defaultValue={5} />);
+ expect(screen.getAllByPlaceholderText("testAttr").length).toBeGreaterThan(0);
+ });
+
+ it("renders double numeric field (positive)", () => {
+ render(<TestHarness typeName="double" defaultValue={2.5} />);
+ expect(screen.getByPlaceholderText("testAttr")).toBeInTheDocument();
+ });
+
+ it("renders boolean Select with placeholder (positive)", () => {
+ render(<TestHarness typeName="boolean" defaultValue={null} />);
+
+ const select = screen.getByRole("combobox");
+ expect(select).toHaveTextContent("--Select true or false--");
+ fireEvent.mouseDown(select);
+ fireEvent.click(screen.getByRole("option", { name: "true" }));
+ expect(select).toHaveTextContent("true");
+ });
+
+ it("renders array<int> autocomplete (positive)", () => {
+ render(<TestHarness typeName="array<int>" defaultValue={[1, 2]} />);
+ expect(
+ screen.getByPlaceholderText("Select a array<int> from the dropdown list")
+ ).toBeInTheDocument();
+ });
+
+ it("renders array<boolean> without free-text filter additions (negative)", () => {
+ render(<TestHarness typeName="array<boolean>" defaultValue={["true"]} />);
+ expect(screen.getByRole("combobox")).toBeInTheDocument();
+ });
+
+ it("renders array<long> autocomplete (positive)", () => {
+ render(<TestHarness typeName="array<long>" defaultValue={[10]} />);
+ expect(
+ screen.getByPlaceholderText("Select a array<long> from the dropdown list")
+ ).toBeInTheDocument();
+ });
+
+ it("renders array<float> and array<short> autocomplete (positive)", () => {
+ render(<TestHarness typeName="array<float>" defaultValue={[1.1]} />);
+ expect(
+ screen.getByPlaceholderText("Select a array<float> from the dropdown list")
+ ).toBeInTheDocument();
+
+ render(<TestHarness typeName="array<short>" defaultValue={[2]} />);
+ expect(
+ screen.getByPlaceholderText("Select a array<short> from the dropdown list")
+ ).toBeInTheDocument();
+ });
+
+ it("updates multi enum selection through autocomplete (positive)", () => {
+ render(
+ <TestHarness
+ typeName="array<adls_gen2_replication>"
+ defaultValue={["LRS"]}
+ />
+ );
+
+ const autocomplete = screen.getByRole("combobox");
+ fireEvent.mouseDown(autocomplete);
+ fireEvent.click(screen.getByRole("option", { name: "GRS" }));
+ expect(screen.getByText("GRS")).toBeInTheDocument();
+ });
+
+ it("renders numeric input attributes for int fields (positive)", () => {
+ render(<TestHarness typeName="int" defaultValue={42} name="intAttr" />);
+ const input = screen.getByPlaceholderText("intAttr");
+ expect(input).toHaveAttribute("type", "number");
+ });
+});
diff --git a/dashboard/src/views/DetailPage/EntityDetailTabs/__tests__/AttributeProperties.test.tsx b/dashboard/src/views/DetailPage/EntityDetailTabs/__tests__/AttributeProperties.test.tsx
index f8a302595..d8d01d18d 100644
--- a/dashboard/src/views/DetailPage/EntityDetailTabs/__tests__/AttributeProperties.test.tsx
+++ b/dashboard/src/views/DetailPage/EntityDetailTabs/__tests__/AttributeProperties.test.tsx
@@ -142,13 +142,31 @@ jest.mock('@components/SkeletonLoader', () => ({
}));
jest.mock('@components/commonComponents', () => ({
- getValues: jest.fn((value, properties, typeDefEntityData, relationShipAttr, propertiesParam, referredEntities, filterEntityData, keys) => {
+ getValues: jest.fn((
+ value,
+ properties,
+ typeDefEntityData,
+ relationShipAttr,
+ propertiesParam,
+ referredEntities,
+ filterEntityData,
+ keys,
+ auditDetails
+ ) => {
// Return a simple mock value
if (Array.isArray(value)) {
// Show count for arrays like "key (count)"
- return <span data-testid={`value-${keys}`}>{keys} ({value.length})</span>;
+ return (
+ <span data-testid={`value-${keys}`} data-audit-details={String(auditDetails)}>
+ {keys} ({value.length})
+ </span>
+ );
}
- return <span data-testid={`value-${keys}`}>{String(value)}</span>;
+ return (
+ <span data-testid={`value-${keys}`} data-audit-details={String(auditDetails)}>
+ {String(value)}
+ </span>
+ );
})
}));
@@ -1502,5 +1520,28 @@ describe('AttributeProperties', () => {
expect(getValues).toHaveBeenCalled();
});
+
+ it('should pass auditDetails as 9th argument to getValues in audit mode', () => {
+ const { getValues } = require('@components/commonComponents');
+
+ render(
+ <TestWrapper>
+ <AttributeProperties
+ entity={defaultMockEntity}
+ referredEntities={defaultMockReferredEntities}
+ loading={false}
+ auditDetails={true}
+ propertiesName="Relationship"
+ />
+ </TestWrapper>
+ );
+
+ expect(getValues).toHaveBeenCalled();
+ const auditCall = getValues.mock.calls.find(
+ (call: unknown[]) => call[8] === true
+ );
+ expect(auditCall).toBeDefined();
+ expect(auditCall[8]).toBe(true);
+ });
});
});
diff --git a/dashboard/src/views/DetailPage/EntityDetailTabs/__tests__/AuditTableDetails.test.tsx b/dashboard/src/views/DetailPage/EntityDetailTabs/__tests__/AuditTableDetails.test.tsx
index e3b388c9a..07a8cb8f3 100644
--- a/dashboard/src/views/DetailPage/EntityDetailTabs/__tests__/AuditTableDetails.test.tsx
+++ b/dashboard/src/views/DetailPage/EntityDetailTabs/__tests__/AuditTableDetails.test.tsx
@@ -25,8 +25,11 @@ import AuditTableDetails from '../AuditTableDetails';
// Mock AttributeProperties
jest.mock('../AttributeProperties', () => ({
__esModule: true,
- default: ({ entity, propertiesName }: any) => (
- <div data-testid={`attribute-properties-${propertiesName.toLowerCase()}`}>
+ default: ({ entity, propertiesName, auditDetails }: any) => (
+ <div
+ data-testid={`attribute-properties-${propertiesName.toLowerCase()}`}
+ data-audit-details={String(auditDetails)}
+ >
AttributeProperties - {propertiesName} - {entity?.typeName || 'No Type'}
</div>
)
@@ -708,9 +711,31 @@ describe('AuditTableDetails', () => {
});
});
- // AttributeProperties should receive auditDetails=true
await waitFor(() => {
- expect(screen.getByTestId('attribute-properties-technical')).toBeInTheDocument();
+ const technicalProps = screen.getByTestId('attribute-properties-technical');
+ expect(technicalProps).toBeInTheDocument();
+ expect(technicalProps).toHaveAttribute('data-audit-details', 'true');
+ }, { timeout: 10000 });
+ }, 30000);
+
+ it('should pass auditDetails=true for relationship audit expand', async () => {
+ const mockRow = {
+ original: {
+ details: 'Updated: {"typeName":"test","attributes":{"name":"Test"},"relationshipAttributes":{"column_families":[{"guid":"cf1"}]}}'
+ }
+ };
+
+ await act(async () => {
+ renderWithProviders({
+ componentProps: mockComponentProps,
+ row: mockRow
+ });
+ });
+
+ await waitFor(() => {
+ const relationshipProps = screen.getByTestId('attribute-properties-relationship');
+ expect(relationshipProps).toBeInTheDocument();
+ expect(relationshipProps).toHaveAttribute('data-audit-details', 'true');
}, { timeout: 10000 });
}, 30000);
});
diff --git a/dashboardv2/public/css/scss/business-metadata.scss b/dashboardv2/public/css/scss/business-metadata.scss
index 2cadd14bf..2a9cb9d3d 100644
--- a/dashboardv2/public/css/scss/business-metadata.scss
+++ b/dashboardv2/public/css/scss/business-metadata.scss
@@ -248,4 +248,12 @@
opacity: 0.6;
cursor: not-allowed;
pointer-events: none;
+}
+
+.bm-enum-unavailable-text {
+ display: inline-block;
+ min-height: 34px;
+ padding-top: 6px;
+ font-style: italic;
+ color: #666666;
}
\ No newline at end of file
diff --git a/dashboardv2/public/js/views/entity/EntityBusinessMetaDataItemView.js b/dashboardv2/public/js/views/entity/EntityBusinessMetaDataItemView.js
index 76c748d1d..408a3e6dd 100644
--- a/dashboardv2/public/js/views/entity/EntityBusinessMetaDataItemView.js
+++ b/dashboardv2/public/js/views/entity/EntityBusinessMetaDataItemView.js
@@ -69,6 +69,33 @@ define(['require',
initialize: function(options) {
_.extend(this, options);
},
+ getInnerEnumTypeName: function(typeName) {
+ if (!typeName || typeName.indexOf("array<") !== 0) {
+ return typeName;
+ }
+ var match = typeName.match(/array<(.*)>/);
+ return match && match[1] ? match[1] : typeName;
+ },
+ getEnumTypeDef: function(typeName) {
+ if (!this.enumDefCollection || !typeName) {
+ return null;
+ }
+ var innerEnumTypeName = this.getInnerEnumTypeName(typeName);
+ return this.enumDefCollection.fullCollection.findWhere({ name: innerEnumTypeName });
+ },
+ initializeEnumSelect2: function(selectEl, val) {
+ var data = [];
+ if (selectEl.data("multi")) {
+ data = val && val.length && (_.isArray(val) ? val : val.split(",")) || [];
+ } else {
+ data = _.unescape(val);
+ }
+ selectEl.select2({
+ multiple: !!selectEl.data("multi"),
+ placeholder: "Select enum values"
+ });
+ selectEl.val(data).trigger("change");
+ },
onRender: function() {
var that = this;
this.ui.keyEl.val("");
@@ -232,25 +259,29 @@ define(['require',
} else if (typeName === "byte" || typeName === "array<byte>" || typeName === "short" || typeName === "array<short>" || typeName === "int" || typeName === "array<int>" || typeName === "float" || typeName === "array<float>" || typeName === "double" || typeName === "array<double>" || typeName === "long" || typeName === "array<long>") {
allowOnlyNum = true;
returnEL = '<' + elType + ' data-key="' + key + '" data-businessMetadata="' + businessMetadata + '" data-typename="' + typeName + '" type="number" data-multi="' + isMultiValued + '" data-tags="true" placeholder="Enter Number" class="form-control" ' + (!_.isUndefinedNull(val) ? 'value="' + val + '"' : "") + '></' + elType + '>';
- } else if (typeName) {
- isEnum = true;
- var modTypeName = typeName;
- if (isMultiValued) {
- var multipleType = typeName.match("array<(.*)>");
- if (multipleType && multipleType[1]) {
- modTypeName = multipleType[1];
- }
- }
- var foundEnumType = this.enumDefCollection.fullCollection.find({ name: modTypeName });
- if (foundEnumType) {
+ } else {
+ var enumTypeDef = this.getEnumTypeDef(typeName);
+ if (enumTypeDef) {
+ isEnum = true;
var enumOptions = "";
- _.forEach(foundEnumType.get("elementDefs"), function(obj) {
- enumOptions += '<option value="' + _.escape(obj.value) + '">' + _.escape(obj.value) + '</option>'
+ _.forEach(enumTypeDef.get("elementDefs"), function(obj) {
+ enumOptions += '<option value="' + _.escape(obj.value) + '">' + _.escape(obj.value) + '</option>';
});
- returnEL = '<select data-key="' + key + '" data-businessMetadata="' + businessMetadata + '" data-typename="' + typeName + '" data-multi="' + isMultiValued + '" data-enum="true">' + enumOptions + '</select>';
+ returnEL = '<select data-key="' + key + '" data-businessMetadata="' + businessMetadata + '" data-typename="' + typeName + '" data-multi="' + isMultiValued + '" data-enum="true" class="form-control"' + (isMultiValued ? ' multiple="multiple"' : '') + '>' + enumOptions + '</select>';
+ } else if (typeName) {
+ if (!this.enumDefCollection || this.enumDefCollection.fullCollection.length === 0) {
+ returnEL = '<span class="bm-enum-unavailable-text">No enum definitions present.</span>';
+ } else {
+ returnEL = '<input type="text" data-key="' + key + '" data-businessMetadata="' + businessMetadata + '" data-typename="' + typeName + '" data-multi="' + isMultiValued + '" placeholder="Enter Value" class="form-control" ' + (!_.isUndefinedNull(val) ? 'value="' + val + '"' : "") + '>';
+ }
}
}
- if (isEnum || elType === "select") {
+ if (isEnum) {
+ setTimeout(function() {
+ var selectEl = that.$el.find('.custom-col-1[data-id="value"] select[data-key="' + key + '"]');
+ that.initializeEnumSelect2(selectEl, val);
+ }, 0);
+ } else if (elType === "select") {
setTimeout(function() {
var selectEl = that.$el.find('.custom-col-1[data-id="value"] select[data-key="' + key + '"]');
var data = [];