This is an automated email from the ASF dual-hosted git repository.

jerryshao pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/gravitino.git


The following commit(s) were added to refs/heads/main by this push:
     new 2ff80faa85 [#14275] web-v2(UI): Support UI for associating policies 
with tag (#14314)
2ff80faa85 is described below

commit 2ff80faa85df32cd76364f5218e952a692ab8171
Author: Qian Xia <[email protected]>
AuthorDate: Fri Nov 13 14:13:57 2026 +0800

    [#14275] web-v2(UI): Support UI for associating policies with tag (#14314)
    
    ### What changes were proposed in this pull request?
    
    1. Added a Policies column to the tags table and extended PolicyTag to
    use tag-specific policy APIs.
    2. Existing entity policy behavior remains unchanged.
    3. remove policy column for objects table
    4. The option `moduleResolution=node` is deprecated and will stop
    working in TypeScript 7.0. update to `moduleResolution=bundler`
    
    <img width="1517" height="824" alt="image"
    
src="https://github.com/user-attachments/assets/e1713ee9-4092-4fa7-9d96-6fa947be4817";
    />
    
    ### Why are the changes needed?
    
    Fixes #14275
    
    ### Does this PR introduce _any_ user-facing change?
    N/A
    
    ### How was this patch tested?
    N/A
---
 .../test/web/ui/pages/CatalogsPage.java            |   2 +-
 web-v2/web/jsconfig.json                           |   2 +-
 .../rightContent/entitiesContent/CatalogsPage.js   |  15 --
 .../entitiesContent/SchemaDetailsPage.js           |  12 --
 .../entitiesContent/SharedSchemaColumns.js         |  14 --
 .../entitiesContent/TableDetailsPage.js            |  12 --
 web-v2/web/src/app/compliance/policies/page.js     |   6 -
 web-v2/web/src/app/compliance/tags/page.js         |  21 ++-
 .../web/src/app/metadataObjectsForPolicy/page.js   | 167 ---------------------
 web-v2/web/src/components/PolicyTag.js             |  93 +++++++-----
 web-v2/web/src/components/PolicyTag.test.jsx       | 137 ++++++++++++++---
 web-v2/web/src/lib/api/policies/index.js           |  25 ++-
 web-v2/web/src/lib/store/policies/index.js         |  46 +++++-
 13 files changed, 254 insertions(+), 298 deletions(-)

diff --git 
a/web-v2/integration-test/src/test/java/org/apache/gravitino/integration/test/web/ui/pages/CatalogsPage.java
 
b/web-v2/integration-test/src/test/java/org/apache/gravitino/integration/test/web/ui/pages/CatalogsPage.java
index 2b6eeaeb32..ccffb5c782 100644
--- 
a/web-v2/integration-test/src/test/java/org/apache/gravitino/integration/test/web/ui/pages/CatalogsPage.java
+++ 
b/web-v2/integration-test/src/test/java/org/apache/gravitino/integration/test/web/ui/pages/CatalogsPage.java
@@ -1392,7 +1392,7 @@ public class CatalogsPage extends BaseWebIT {
 
   public boolean verifyTableColumns() {
     try {
-      List<String> columns = Arrays.asList("Column Name", "Data Type", "Tags", 
"Policies");
+      List<String> columns = Arrays.asList("Column Name", "Data Type", "Tags");
 
       // Ant Design Table structure: thead > tr > th
       List<WebElement> columnHeadersRows =
diff --git a/web-v2/web/jsconfig.json b/web-v2/web/jsconfig.json
index 7b36ad9798..d5e4446f30 100644
--- a/web-v2/web/jsconfig.json
+++ b/web-v2/web/jsconfig.json
@@ -11,7 +11,7 @@
     "incremental": true,
     "esModuleInterop": true,
     "module": "esnext",
-    "moduleResolution": "node",
+    "moduleResolution": "bundler",
     "resolveJsonModule": true,
     "isolatedModules": true,
     "jsx": "preserve",
diff --git 
a/web-v2/web/src/app/catalogs/rightContent/entitiesContent/CatalogsPage.js 
b/web-v2/web/src/app/catalogs/rightContent/entitiesContent/CatalogsPage.js
index d094ae7544..a04be2ef64 100644
--- a/web-v2/web/src/app/catalogs/rightContent/entitiesContent/CatalogsPage.js
+++ b/web-v2/web/src/app/catalogs/rightContent/entitiesContent/CatalogsPage.js
@@ -31,7 +31,6 @@ import { switchInUseCatalog, deleteCatalog, 
updateCatalogInUse } from '@/lib/sto
 import { TreeRefContext } from '../../page'
 import Tags from '@/components/CustomTags'
 import Icons from '@/components/Icons'
-import Policies from '@/components/PolicyTag'
 import Link from 'next/link'
 import Loading from '@/components/Loading'
 
@@ -255,20 +254,6 @@ export default function CatalogsPage() {
             />
           ) : null
       },
-      {
-        title: 'Policies',
-        dataIndex: 'policies',
-        key: 'policies',
-        ellipsis: true,
-        render: (_, record) =>
-          record?.node === 'catalog' ? (
-            <Policies
-              metadataObjectType={'catalog'}
-              metadataObjectFullName={record.name}
-              key={`catalog-${record.name}-policies`}
-            />
-          ) : null
-      },
       {
         title: 'Actions',
         dataIndex: 'action',
diff --git 
a/web-v2/web/src/app/catalogs/rightContent/entitiesContent/SchemaDetailsPage.js 
b/web-v2/web/src/app/catalogs/rightContent/entitiesContent/SchemaDetailsPage.js
index 452276901c..72e9d6e56b 100644
--- 
a/web-v2/web/src/app/catalogs/rightContent/entitiesContent/SchemaDetailsPage.js
+++ 
b/web-v2/web/src/app/catalogs/rightContent/entitiesContent/SchemaDetailsPage.js
@@ -591,18 +591,6 @@ export default function SchemaDetailsPage() {
             />
           ) : null
       },
-      {
-        title: 'Policies',
-        dataIndex: 'policies',
-        key: 'policies',
-        render: (_, record) =>
-          record?.node === entityType ? (
-            <Policies
-              metadataObjectType={entityType}
-              
metadataObjectFullName={`${record.namespace.at(-2)}.${record.namespace.at(-1)}.${record.name}`}
-            />
-          ) : null
-      },
       {
         title: 'Actions',
         dataIndex: 'action',
diff --git 
a/web-v2/web/src/app/catalogs/rightContent/entitiesContent/SharedSchemaColumns.js
 
b/web-v2/web/src/app/catalogs/rightContent/entitiesContent/SharedSchemaColumns.js
index f8e29cfe11..ec4c30b331 100644
--- 
a/web-v2/web/src/app/catalogs/rightContent/entitiesContent/SharedSchemaColumns.js
+++ 
b/web-v2/web/src/app/catalogs/rightContent/entitiesContent/SharedSchemaColumns.js
@@ -22,7 +22,6 @@ import React from 'react'
 import Link from 'next/link'
 import { Tooltip, Dropdown } from 'antd'
 import Tags from '@/components/CustomTags'
-import Policies from '@/components/PolicyTag'
 import Icons from '@/components/Icons'
 
 export function buildSchemaColumns({
@@ -62,19 +61,6 @@ export function buildSchemaColumns({
           <Tags metadataObjectType={'schema'} 
metadataObjectFullName={`${record.namespace?.at(-1)}.${record.name}`} />
         ) : null
     },
-    {
-      title: 'Policies',
-      dataIndex: 'policies',
-      key: 'policies',
-      ellipsis: true,
-      render: (_, record) =>
-        record?.node === 'schema' ? (
-          <Policies
-            metadataObjectType={'schema'}
-            
metadataObjectFullName={`${record.namespace?.at(-1)}.${record.name}`}
-          />
-        ) : null
-    },
     ...(provider !== 'kafka'
       ? [
           {
diff --git 
a/web-v2/web/src/app/catalogs/rightContent/entitiesContent/TableDetailsPage.js 
b/web-v2/web/src/app/catalogs/rightContent/entitiesContent/TableDetailsPage.js
index 9bf4a95855..f580421672 100644
--- 
a/web-v2/web/src/app/catalogs/rightContent/entitiesContent/TableDetailsPage.js
+++ 
b/web-v2/web/src/app/catalogs/rightContent/entitiesContent/TableDetailsPage.js
@@ -411,18 +411,6 @@ export default function TableDetailsPage({ ...props }) {
               
metadataObjectFullName={`${catalog}.${schema}.${table}.${record.name}`}
             />
           ) : null
-      },
-      {
-        title: 'Policies',
-        dataIndex: 'policies',
-        key: 'policies',
-        render: (_, record) =>
-          record?.node === 'tableColumn' ? (
-            <Policies
-              metadataObjectType={'column'}
-              
metadataObjectFullName={`${catalog}.${schema}.${table}.${record.name}`}
-            />
-          ) : null
       }
     ],
     [store.activatedDetails]
diff --git a/web-v2/web/src/app/compliance/policies/page.js 
b/web-v2/web/src/app/compliance/policies/page.js
index ed8dda2f1a..399830190c 100644
--- a/web-v2/web/src/app/compliance/policies/page.js
+++ b/web-v2/web/src/app/compliance/policies/page.js
@@ -138,10 +138,6 @@ export default function PoliciesPage() {
     })
   }
 
-  const handleClick = name => () => {
-    
router.push(`/metadataObjectsForPolicy?policy=${name}&metalake=${currentMetalake}`)
-  }
-
   const handleViewPolicy = async policy => {
     setDetailsLoading(true)
     const { payload: policyDetail } = await dispatch(getPolicyDetails({ 
metalake: currentMetalake, policy }))
@@ -172,10 +168,8 @@ export default function PoliciesPage() {
             key={record.name}
             icon={!record.enabled ? <StopOutlined style={{ color: 'white' }} 
/> : null}
             closable={false}
-            onClick={handleClick(record.name)}
             color={record.enabled ? token.colorPrimary : 
token.colorTextDisabled}
             style={{ userSelect: 'none' }}
-            className='cursor-pointer'
           >
             <span>{record.name.length > 20 ? `${record.name.slice(0, 20)}...` 
: record.name}</span>
           </Tag>
diff --git a/web-v2/web/src/app/compliance/tags/page.js 
b/web-v2/web/src/app/compliance/tags/page.js
index 74a27f0644..27cc01fc8a 100644
--- a/web-v2/web/src/app/compliance/tags/page.js
+++ b/web-v2/web/src/app/compliance/tags/page.js
@@ -31,8 +31,9 @@ import AssociatedTable from '@/components/AssociatedTable'
 import CreateTagDialog from './CreateTagDialog'
 import { formatToDateTime } from '@/lib/utils'
 import { useAppSelector, useAppDispatch } from '@/lib/hooks/useStore'
-import { use } from 'react'
 import { fetchTags, deleteTag } from '@/lib/store/tags'
+import { fetchPolicies } from '@/lib/store/policies'
+import PolicyTag from '@/components/PolicyTag'
 
 const { Title, Paragraph } = Typography
 const { Search } = Input
@@ -53,7 +54,10 @@ export default function TagsPage() {
   const { anthEnable } = auth
 
   useEffect(() => {
-    currentMetalake && dispatch(fetchTags({ metalake: currentMetalake, 
details: true }))
+    if (currentMetalake) {
+      dispatch(fetchTags({ metalake: currentMetalake, details: true }))
+      dispatch(fetchPolicies({ metalake: currentMetalake, details: true }))
+    }
   }, [dispatch, currentMetalake])
 
   const tableData = store.tagsData
@@ -171,6 +175,19 @@ export default function TagsPage() {
         ellipsis: true,
         render: comment => <span>{comment || '-'}</span>
       },
+      {
+        title: 'Policies',
+        dataIndex: 'policies',
+        key: 'policies',
+        width: 260,
+        render: (_, record) => (
+          <PolicyTag
+            key={`tag-${record.name}-policies`}
+            metadataObjectType='tag'
+            metadataObjectFullName={record.name}
+          />
+        )
+      },
       {
         title: 'Actions',
         key: 'action',
diff --git a/web-v2/web/src/app/metadataObjectsForPolicy/page.js 
b/web-v2/web/src/app/metadataObjectsForPolicy/page.js
deleted file mode 100644
index f5aa24dd3d..0000000000
--- a/web-v2/web/src/app/metadataObjectsForPolicy/page.js
+++ /dev/null
@@ -1,167 +0,0 @@
-/*
- * 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.
- */
-
-'use client'
-
-import { useMemo, useState, useEffect } from 'react'
-import { useRouter } from 'next/navigation'
-import { StopOutlined } from '@ant-design/icons'
-import { Flex, Input, Spin, Table, Tag, Tooltip, Typography, theme as 
antdTheme } from 'antd'
-import { useAntdColumnResize } from 'react-antd-column-resize'
-import Icons from '@/components/Icons'
-import SectionContainer from '@/components/SectionContainer'
-import { useSearchParams } from 'next/navigation'
-import { useAppSelector, useAppDispatch } from '@/lib/hooks/useStore'
-import { getPolicyDetails, associatePolicy } from '@/lib/store/policies'
-import { getMetadataObjectsForPolicy } from '@/lib/store/metalakes'
-
-const { Title, Paragraph } = Typography
-const { Search } = Input
-
-export default function MetadataObjectsForPolicyPage() {
-  const [search, setSearch] = useState('')
-  const searchParams = useSearchParams()
-  const currentMetalake = searchParams.get('metalake')
-  const policy = searchParams.get('policy') || ''
-  const router = useRouter()
-  const { token } = antdTheme.useToken()
-  const dispatch = useAppDispatch()
-  const [policyData, setPolicyData] = useState(null)
-  const [metaDatas, setMetaDatas] = useState([])
-  const [isLoading, setIsLoading] = useState(false)
-
-  useEffect(() => {
-    const initLoad = async () => {
-      setIsLoading(true)
-      const { payload: policyData } = await dispatch(getPolicyDetails({ 
metalake: currentMetalake, policy }))
-      const { payload: metaDatas } = await 
dispatch(getMetadataObjectsForPolicy({ metalake: currentMetalake, policy }))
-      setPolicyData(policyData)
-      setMetaDatas(metaDatas)
-      setIsLoading(false)
-    }
-    if (policy && currentMetalake) {
-      initLoad()
-    }
-  }, [policy, dispatch, currentMetalake])
-
-  const tableData = metaDatas
-    ?.filter(d => {
-      if (search === '') return true
-
-      return d.fullName.includes(search)
-    })
-    .map(metaData => {
-      return {
-        ...metaData,
-        key: metaData.fullName,
-        type: metaData.type
-      }
-    })
-
-  const onSearchTable = e => {
-    const { value } = e.target
-    setSearch(value)
-  }
-
-  const showDeleteConfirm = async object => {
-    await dispatch(
-      associatePolicy({
-        metalake: currentMetalake,
-        metadataObjectType: object.type,
-        metadataObjectFullName: object.fullName,
-        data: { policiesToRemove: [policy] }
-      })
-    )
-    const { payload: metaDatas } = await 
dispatch(getMetadataObjectsForPolicy({ metalake: currentMetalake, policy }))
-    setMetaDatas(metaDatas)
-  }
-
-  const columns = useMemo(
-    () => [
-      {
-        title: 'Metadata Object Name',
-        dataIndex: 'fullName',
-        key: 'fullName',
-        ellipsis: true,
-        sorter: (a, b) => 
a.fullName.toLowerCase().localeCompare(b.fullName.toLowerCase()),
-        width: 300,
-        render: (_, record) => <span>{record.fullName}</span>
-      },
-      {
-        title: 'Type',
-        dataIndex: 'type',
-        key: 'type'
-      },
-      {
-        title: 'Actions',
-        key: 'action',
-        width: 100,
-        render: (_, record) => {
-          return (
-            <div className='flex gap-2'>
-              <a>
-                <Tooltip title='Remove Associate'>
-                  <Icons.Delete className='size-4' onClick={() => 
showDeleteConfirm(record)} />
-                </Tooltip>
-              </a>
-            </div>
-          )
-        }
-      }
-    ],
-    [currentMetalake, isLoading]
-  )
-
-  const { resizableColumns, components, tableWidth } = useAntdColumnResize(() 
=> {
-    return { columns, minWidth: 100 }
-  }, [columns])
-
-  return (
-    <SectionContainer classProps='block'>
-      <div className='h-full bg-white p-6'>
-        <Title level={2} className='flex items-center gap-1'>
-          <Icons.Undo2 className='size-6 cursor-pointer' onClick={() => 
router.back()} />
-          Metadata Objects
-          <Tag
-            icon={!policyData?.enabled ? <StopOutlined style={{ color: 'white' 
}} /> : null}
-            color={policyData?.enabled ? token.colorPrimary : 
token.colorTextDisabled}
-          >
-            {policy}
-          </Tag>
-        </Title>
-        <Paragraph type='secondary'>This table lists the metadata objects 
associated with policy {policy}.</Paragraph>
-        <Flex justify='flex-end' className='mb-4'>
-          <div className='flex w-1/4 gap-4'>
-            <Search name='searchCatalogInput' placeholder='Search...' 
onChange={onSearchTable} />
-          </div>
-        </Flex>
-        <Spin spinning={isLoading}>
-          <Table
-            style={{ maxHeight: 'calc(100vh - 25rem)' }}
-            scroll={{ x: tableWidth, y: 'calc(100vh - 30rem)' }}
-            dataSource={tableData}
-            columns={resizableColumns}
-            components={components}
-            pagination={{ position: ['bottomCenter'], showSizeChanger: true }}
-          />
-        </Spin>
-      </div>
-    </SectionContainer>
-  )
-}
diff --git a/web-v2/web/src/components/PolicyTag.js 
b/web-v2/web/src/components/PolicyTag.js
index 8e59cb85cf..ab9f3a59cf 100644
--- a/web-v2/web/src/components/PolicyTag.js
+++ b/web-v2/web/src/components/PolicyTag.js
@@ -21,9 +21,8 @@ import React, { useEffect, useRef, useState } from 'react'
 import { useRouter } from 'next/navigation'
 import { LockOutlined, PlusOutlined } from '@ant-design/icons'
 import { Flex, Select, Space, Tag, Tooltip, theme } from 'antd'
-import { cn } from '@/lib/utils/tailwind'
 import { useAppSelector, useAppDispatch } from '@/lib/hooks/useStore'
-import { associatePolicy } from '@/lib/store/policies'
+import { addPolicyForTag, getPoliciesForTag, removePolicyFromTag } from 
'@/lib/store/policies'
 import { getCurrentEntityPolicies } from '@/lib/store/metalakes'
 import { useSearchParams } from 'next/navigation'
 
@@ -36,45 +35,65 @@ const tagInputStyle = {
 
 export default function PolicyTag({ ...props }) {
   const { readOnly, metadataObjectType, metadataObjectFullName } = props
+  const isTag = metadataObjectType === 'tag'
   const { token } = theme.useToken()
   const [inputVisible, setInputVisible] = useState(false)
   const [optionList, setOptionList] = useState([])
+  const containerRef = useRef(null)
   const inputRef = useRef(null)
   const router = useRouter()
   const store = useAppSelector(state => state.policies)
   const dispatch = useAppDispatch()
-  const [policiesForEntity, setPoliciesForEntity] = useState([])
+  const [policiesForObject, setPoliciesForObject] = useState([])
   const searchParams = useSearchParams()
   const currentMetalake = searchParams.get('metalake')
 
-  const getPoliciesForEntity = async () => {
-    const { payload } = await dispatch(
+  const getPolicies = async () => {
+    if (isTag) {
+      const result = await dispatch(getPoliciesForTag({ metalake: 
currentMetalake, tag: metadataObjectFullName }))
+
+      return result.meta.requestStatus === 'fulfilled' ? result.payload || [] 
: undefined
+    }
+
+    const result = await dispatch(
       getCurrentEntityPolicies({ metalake: currentMetalake, 
metadataObjectType, metadataObjectFullName, details: true })
     )
 
-    return payload?.policies || []
+    return result.meta.requestStatus === 'fulfilled' ? 
result.payload?.policies || [] : undefined
   }
 
   useEffect(() => {
     const initLoad = async () => {
-      const policies = await getPoliciesForEntity()
-      setPoliciesForEntity(policies)
+      const policies = await getPolicies()
+      if (policies) setPoliciesForObject(policies)
     }
     if (currentMetalake && metadataObjectType && metadataObjectFullName) {
-      initLoad()
+      if (!isTag || typeof IntersectionObserver === 'undefined') {
+        initLoad()
+      } else {
+        const observer = new IntersectionObserver(([entry]) => {
+          if (entry.isIntersecting) {
+            observer.disconnect()
+            initLoad()
+          }
+        })
+        if (containerRef.current) observer.observe(containerRef.current)
+
+        return () => observer.disconnect()
+      }
     }
-  }, [metadataObjectType, metadataObjectFullName])
+  }, [currentMetalake, metadataObjectType, metadataObjectFullName, isTag])
 
   useEffect(() => {
     if (inputVisible) {
       const options =
         store.policiesData?.filter(
-          policyOption => !policiesForEntity?.map(policy => 
policy.name)?.includes(policyOption.name)
+          policyOption => !policiesForObject?.map(policy => 
policy.name)?.includes(policyOption.name)
         ) || []
       setOptionList(options)
       inputRef.current?.focus()
     }
-  }, [inputVisible, policiesForEntity])
+  }, [inputVisible, policiesForObject, store.policiesData])
 
   const showInput = () => {
     setInputVisible(true)
@@ -102,32 +121,28 @@ export default function PolicyTag({ ...props }) {
   }
 
   const handleChange = async value => {
-    if (value && !policiesForEntity?.map(policy => 
policy.name)?.includes(value)) {
-      await dispatch(
-        associatePolicy({
-          metalake: currentMetalake,
-          metadataObjectType,
-          metadataObjectFullName,
-          data: { policiesToAdd: [value] }
-        })
+    if (value && !policiesForObject?.map(policy => 
policy.name)?.includes(value)) {
+      const result = await dispatch(
+        addPolicyForTag({ metalake: currentMetalake, tag: 
metadataObjectFullName, policy: value })
       )
-      const policies = await getPoliciesForEntity()
-      setPoliciesForEntity(policies)
+      if (result.meta.requestStatus === 'fulfilled') {
+        const policies = await getPolicies()
+        if (policies) setPoliciesForObject(policies)
+      }
     }
     setInputVisible(false)
   }
 
-  const handleClose = async removedPolicy => {
-    await dispatch(
-      associatePolicy({
-        metalake: currentMetalake,
-        metadataObjectType,
-        metadataObjectFullName,
-        data: { policiesToRemove: [removedPolicy] }
-      })
+  const handleClose = async (removedPolicy, event) => {
+    event.preventDefault()
+
+    const result = await dispatch(
+      removePolicyFromTag({ metalake: currentMetalake, tag: 
metadataObjectFullName, policy: removedPolicy })
     )
-    const policies = await getPoliciesForEntity()
-    setPoliciesForEntity(policies)
+    if (result.meta.requestStatus === 'fulfilled') {
+      const policies = await getPolicies()
+      if (policies) setPoliciesForObject(policies)
+    }
   }
 
   const handleBlur = () => {
@@ -145,8 +160,8 @@ export default function PolicyTag({ ...props }) {
   }
 
   return (
-    <Flex gap='4px 0' wrap>
-      {policiesForEntity?.map((policy, index) => {
+    <Flex ref={containerRef} gap='4px 0' wrap>
+      {policiesForObject?.map((policy, index) => {
         const isLongPolicy = policy.name.length > 20
         let color = policy.enabled ? token.colorPrimary : 
token.colorTextDisabled
 
@@ -154,12 +169,12 @@ export default function PolicyTag({ ...props }) {
           <Tag
             key={policy.name + index}
             color={color}
-            closable={!readOnly && !policy.inherited}
+            closable={isTag && !readOnly && !policy.inherited}
             icon={policy.inherited ? <LockOutlined /> : null}
             onClick={handleClick(policy.name)}
             className='cursor-pointer'
             style={{ userSelect: 'none' }}
-            onClose={() => handleClose(policy.name)}
+            onClose={event => handleClose(policy.name, event)}
           >
             <span>{isLongPolicy ? `${policy.name.slice(0, 20)}...` : 
policy.name}</span>
           </Tag>
@@ -173,8 +188,8 @@ export default function PolicyTag({ ...props }) {
           policyElem
         )
       })}
-      {policiesForEntity?.length === 0 && <span>No Policies</span>}
-      {inputVisible && !readOnly && (
+      {policiesForObject?.length === 0 && <span>No Policies</span>}
+      {inputVisible && isTag && !readOnly && (
         <Select
           size='small'
           tagRender={tagRender}
@@ -196,7 +211,7 @@ export default function PolicyTag({ ...props }) {
           ))}
         </Select>
       )}
-      {!inputVisible && !readOnly && (
+      {!inputVisible && isTag && !readOnly && (
         <Tag style={tagPlusStyle} icon={<PlusOutlined />} onClick={showInput}>
           Associate Policy
         </Tag>
diff --git a/web-v2/web/src/components/PolicyTag.test.jsx 
b/web-v2/web/src/components/PolicyTag.test.jsx
index a5760a2197..b4856eface 100644
--- a/web-v2/web/src/components/PolicyTag.test.jsx
+++ b/web-v2/web/src/components/PolicyTag.test.jsx
@@ -24,17 +24,31 @@ import { Provider } from 'react-redux'
 import { configureStore } from '@reduxjs/toolkit'
 import { defHttp } from '@/lib/utils/axios'
 import metalakes from '@/lib/store/metalakes'
-import policies from '@/lib/store/policies'
+import policies, { getPoliciesForTag } from '@/lib/store/policies'
 import PolicyTag from './PolicyTag'
 
 const navigation = vi.hoisted(() => ({ push: vi.fn() }))
+const tagPoliciesUrl = 
'/api/metalakes/demo/tags/classification.sensitive/policies'
 
-vi.mock('@/lib/utils/axios', () => ({ defHttp: { get: vi.fn(), post: vi.fn() } 
}))
+vi.mock('@/lib/utils/axios', () => ({ defHttp: { get: vi.fn(), post: vi.fn(), 
delete: vi.fn() } }))
 vi.mock('next/navigation', () => ({
   useRouter: () => navigation,
   useSearchParams: () => new URLSearchParams({ metalake: 'demo' })
 }))
 
+it('keeps tag selectors nested under their own key', async () => {
+  defHttp.get.mockResolvedValue({
+    associations: [{ policy: { name: 'masking', enabled: true }, selector: { 
type: 'ALL_VALUES', name: 'selector' } }]
+  })
+  const store = configureStore({ reducer: { policies } })
+
+  const result = await store.dispatch(getPoliciesForTag({ metalake: 'demo', 
tag: 'classification.sensitive' }))
+
+  expect(result.payload).toEqual([
+    { name: 'masking', enabled: true, selector: { type: 'ALL_VALUES', name: 
'selector' } }
+  ])
+})
+
 let root
 let container
 
@@ -68,26 +82,115 @@ it.each([true, false])('respects readOnly=%s while 
retaining policy navigation',
   expect(directTag.textContent).toBe('direct')
   expect(inheritedTag.textContent).toBe('inherited')
   expect(inheritedTag.querySelector('.ant-tag-close-icon')).toBeNull()
-  expect(container.textContent.includes('Associate Policy')).toBe(!readOnly)
+  expect(container.textContent.includes('Associate Policy')).toBe(false)
 
   const close = directTag.querySelector('.ant-tag-close-icon')
-  if (readOnly) {
-    expect(close).toBeNull()
-  } else {
-    expect(close).not.toBeNull()
-    defHttp.post.mockResolvedValue({ code: 0 })
-    defHttp.get.mockResolvedValue({ policies: [inheritedPolicy] })
-    await act(async () => close.click())
-    expect(defHttp.post).toHaveBeenCalledExactlyOnceWith({
-      url: '/api/metalakes/demo/objects/table/sales.mart.orders/policies',
-      data: { policiesToRemove: ['direct'] }
-    })
-    expect(container.textContent).not.toContain('direct')
-    expect(navigation.push).not.toHaveBeenCalled()
-  }
+  expect(close).toBeNull()
 
   const policyLink = [...container.querySelectorAll('.ant-tag')].find(tag => 
tag.textContent === 'inherited')
   await act(async () => policyLink.click())
   
expect(navigation.push).toHaveBeenCalledExactlyOnceWith('/metadataObjectsForPolicy?policy=inherited&metalake=demo')
   if (readOnly) expect(defHttp.post).not.toHaveBeenCalled()
 })
+
+const renderTagPolicies = async () => {
+  const store = configureStore({
+    reducer: { metalakes, policies },
+    preloadedState: {
+      policies: { policiesData: [{ name: 'masking', enabled: true }], 
policiesLoading: false, error: null }
+    }
+  })
+  await act(async () =>
+    root.render(
+      <Provider store={store}>
+        <PolicyTag metadataObjectType='tag' 
metadataObjectFullName='classification.sensitive' />
+      </Provider>
+    )
+  )
+}
+
+const selectPolicy = async name => {
+  await act(async () =>
+    container.querySelector('.ant-select-selector').dispatchEvent(new 
MouseEvent('mousedown', { bubbles: true }))
+  )
+  const option = 
[...document.body.querySelectorAll('.ant-select-item-option')].find(item => 
item.textContent === name)
+  await act(async () => option.click())
+}
+
+it('lists policies associated with a tag using the association response 
mapping', async () => {
+  defHttp.get.mockResolvedValue({
+    associations: [{ policy: { name: 'masking', enabled: true }, selector: { 
type: 'ALL_VALUES' } }]
+  })
+
+  await renderTagPolicies()
+
+  expect(defHttp.get).toHaveBeenCalledExactlyOnceWith({ url: tagPoliciesUrl, 
params: { details: true } })
+  expect(container.textContent).toContain('masking')
+  expect(container.textContent).not.toContain('No Policies')
+})
+
+it('adds a policy to a tag with the ALL_VALUES selector', async () => {
+  defHttp.get.mockResolvedValueOnce({ associations: [] 
}).mockResolvedValueOnce({
+    associations: [{ policy: { name: 'masking', enabled: true }, selector: { 
type: 'ALL_VALUES' } }]
+  })
+  defHttp.post.mockResolvedValue({})
+
+  await renderTagPolicies()
+  await act(async () =>
+    [...container.querySelectorAll('.ant-tag')].find(tag => tag.textContent 
=== 'Associate Policy').click()
+  )
+  await selectPolicy('masking')
+
+  expect(defHttp.post).toHaveBeenCalledExactlyOnceWith({
+    url: `${tagPoliciesUrl}/masking`,
+    data: { selector: { type: 'ALL_VALUES' } }
+  })
+  expect(container.textContent).toContain('masking')
+})
+
+it('removes a tag policy when DELETE returns an empty 204 response', async () 
=> {
+  defHttp.get
+    .mockResolvedValueOnce({
+      associations: [{ policy: { name: 'masking', enabled: true }, selector: { 
type: 'ALL_VALUES' } }]
+    })
+    .mockResolvedValueOnce({ associations: [] })
+  defHttp.delete.mockResolvedValue(undefined)
+
+  await renderTagPolicies()
+  const close = container.querySelector('.ant-tag-close-icon')
+  await act(async () => close.click())
+
+  expect(defHttp.delete).toHaveBeenCalledExactlyOnceWith({ url: 
`${tagPoliciesUrl}/masking` })
+  expect(container.textContent).toContain('No Policies')
+})
+
+it('handles a rejected tag policy add request', async () => {
+  const association = { policy: { name: 'existing', enabled: true }, selector: 
{ type: 'ALL_VALUES' } }
+  defHttp.get.mockResolvedValue({ associations: [association] })
+  defHttp.post.mockRejectedValue(new Error('add failed'))
+
+  await renderTagPolicies()
+  await act(async () =>
+    [...container.querySelectorAll('.ant-tag')].find(tag => tag.textContent 
=== 'Associate Policy').click()
+  )
+  await selectPolicy('masking')
+  expect(defHttp.post).toHaveBeenCalledExactlyOnceWith({
+    url: `${tagPoliciesUrl}/masking`,
+    data: { selector: { type: 'ALL_VALUES' } }
+  })
+  expect(container.textContent).toContain('existing')
+  expect(container.textContent).not.toContain('No Policies')
+})
+
+it('handles a rejected tag policy removal request', async () => {
+  const association = { policy: { name: 'masking', enabled: true }, selector: 
{ type: 'ALL_VALUES' } }
+  defHttp.get.mockResolvedValue({ associations: [association] })
+  defHttp.delete.mockRejectedValue(new Error('remove failed'))
+
+  await renderTagPolicies()
+
+  const close = container.querySelector('.ant-tag-close-icon')
+  await act(async () => close.click())
+  expect(defHttp.delete).toHaveBeenCalledExactlyOnceWith({ url: 
`${tagPoliciesUrl}/masking` })
+  expect(container.textContent).toContain('masking')
+})
diff --git a/web-v2/web/src/lib/api/policies/index.js 
b/web-v2/web/src/lib/api/policies/index.js
index ef1f0dffc5..619cd58ac6 100644
--- a/web-v2/web/src/lib/api/policies/index.js
+++ b/web-v2/web/src/lib/api/policies/index.js
@@ -28,8 +28,10 @@ const Apis = {
     
`/api/metalakes/${encodeURIComponent(metalake)}/policies/${encodeURIComponent(policy)}`,
   UPDATE: ({ metalake, policy }) =>
     
`/api/metalakes/${encodeURIComponent(metalake)}/policies/${encodeURIComponent(policy)}`,
-  ASSOCIATE: ({ metalake, metadataObjectType, metadataObjectFullName }) =>
-    
`/api/metalakes/${encodeURIComponent(metalake)}/objects/${encodeURIComponent(metadataObjectType)}/${encodeURIComponent(metadataObjectFullName)}/policies`
+  TAG_POLICIES: ({ metalake, tag }) =>
+    
`/api/metalakes/${encodeURIComponent(metalake)}/tags/${encodeURIComponent(tag)}/policies`,
+  TAG_POLICY: ({ metalake, tag, policy }) =>
+    
`/api/metalakes/${encodeURIComponent(metalake)}/tags/${encodeURIComponent(tag)}/policies/${encodeURIComponent(policy)}`
 }
 
 export const getPoliciesApi = ({ metalake, details }) => {
@@ -72,9 +74,22 @@ export const enableOrDisablePolicyApi = ({ metalake, policy, 
data }) => {
   })
 }
 
-export const associatePolicyApi = ({ metalake, metadataObjectType, 
metadataObjectFullName, data }) => {
+export const getPoliciesForTagApi = ({ metalake, tag }) => {
+  return defHttp.get({
+    url: Apis.TAG_POLICIES({ metalake, tag }),
+    params: { details: true }
+  })
+}
+
+export const addPolicyForTagApi = ({ metalake, tag, policy }) => {
   return defHttp.post({
-    url: Apis.ASSOCIATE({ metalake, metadataObjectType, metadataObjectFullName 
}),
-    data
+    url: Apis.TAG_POLICY({ metalake, tag, policy }),
+    data: { selector: { type: 'ALL_VALUES' } }
+  })
+}
+
+export const removePolicyFromTagApi = ({ metalake, tag, policy }) => {
+  return defHttp.delete({
+    url: Apis.TAG_POLICY({ metalake, tag, policy })
   })
 }
diff --git a/web-v2/web/src/lib/store/policies/index.js 
b/web-v2/web/src/lib/store/policies/index.js
index 850def46d3..c0cf9e5650 100644
--- a/web-v2/web/src/lib/store/policies/index.js
+++ b/web-v2/web/src/lib/store/policies/index.js
@@ -29,7 +29,9 @@ import {
   updatePolicyApi,
   enableOrDisablePolicyApi,
   getPolicyDetailsApi,
-  associatePolicyApi
+  getPoliciesForTagApi,
+  addPolicyForTagApi,
+  removePolicyFromTagApi
 } from '@/lib/api/policies'
 
 export const fetchPolicies = createAsyncThunk('policies/fetchPolicies', async 
({ metalake, details }) => {
@@ -106,12 +108,32 @@ export const deletePolicy = 
createAsyncThunk('policies/deletePolicy', async ({ m
   return res
 })
 
-export const associatePolicy = createAsyncThunk(
-  'policies/associatePolicy',
-  async ({ metalake, metadataObjectType, metadataObjectFullName, data }) => {
-    const [err, res] = await to(associatePolicyApi({ metalake, 
metadataObjectType, metadataObjectFullName, data }))
+export const getPoliciesForTag = 
createAsyncThunk('policies/getPoliciesForTag', async ({ metalake, tag }) => {
+  const [err, res] = await to(getPoliciesForTagApi({ metalake, tag }))
 
-    if (err || !res) {
+  if (err || !res) {
+    throw new Error(err)
+  }
+
+  return res.associations?.map(association => ({ ...association.policy, 
selector: association.selector })) || []
+})
+
+export const addPolicyForTag = createAsyncThunk('policies/addPolicyForTag', 
async ({ metalake, tag, policy }) => {
+  const [err, res] = await to(addPolicyForTagApi({ metalake, tag, policy }))
+
+  if (err || !res) {
+    throw new Error(err)
+  }
+
+  return res
+})
+
+export const removePolicyFromTag = createAsyncThunk(
+  'policies/removePolicyFromTag',
+  async ({ metalake, tag, policy }) => {
+    const [err, res] = await to(removePolicyFromTagApi({ metalake, tag, policy 
}))
+
+    if (err) {
       throw new Error(err)
     }
 
@@ -172,7 +194,17 @@ const policiesSlice = createSlice({
           toast.error(action.error.message)
         }
       })
-      .addCase(associatePolicy.rejected, (state, action) => {
+      .addCase(getPoliciesForTag.rejected, (state, action) => {
+        if (!action.error.message.includes('CanceledError')) {
+          toast.error(action.error.message)
+        }
+      })
+      .addCase(addPolicyForTag.rejected, (state, action) => {
+        if (!action.error.message.includes('CanceledError')) {
+          toast.error(action.error.message)
+        }
+      })
+      .addCase(removePolicyFromTag.rejected, (state, action) => {
         if (!action.error.message.includes('CanceledError')) {
           toast.error(action.error.message)
         }

Reply via email to