:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-catalog): add relationships and certifications tabs (#73983)
Thiago Salvatored5a09fad79e9
diff --git a/products/data_catalog/frontend/DataCatalogScene.tsx b/products/data_catalog/frontend/DataCatalogScene.tsxindex f7fe3cbea565..e3bc6f43aa3d 100644--- a/products/data_catalog/frontend/DataCatalogScene.tsx+++ b/products/data_catalog/frontend/DataCatalogScene.tsx@@ -3,6 +3,7 @@ import { BindLogic, useActions, useValues } from 'kea'import { IconPlusSmall } from '@posthog/icons'import { LemonButton } from '@posthog/lemon-ui'+import { LemonBadge } from 'lib/lemon-ui/LemonBadge'import { LemonTab, LemonTabs } from 'lib/lemon-ui/LemonTabs'import { SceneExport } from 'scenes/sceneTypes'import { urls } from 'scenes/urls'@@ -11,10 +12,14 @@ import { SceneContent } from '~/layout/scenes/components/SceneContent'import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'import { ProductKey } from '~/queries/schema/schema-general'+import { certificationsLogic } from './certificationsLogic'import { NewMetricModal } from './components/NewMetricModal'import { DataCatalogTab, dataCatalogSceneLogic } from './dataCatalogSceneLogic'import { metricsLogic } from './metricsLogic'+import { relationshipsLogic } from './relationshipsLogic'+import { CertificationsTab } from './tabs/CertificationsTab'import { MetricsTab } from './tabs/MetricsTab'+import { RelationshipsTab } from './tabs/RelationshipsTab'export const scene: SceneExport = {component: DataCatalogScene,@@ -22,32 +27,40 @@ export const scene: SceneExport = {productKey: ProductKey.DATA_CATALOG,}-function TabPlaceholder({ label }: { label: string }): JSX.Element {- return <p className="text-secondary">{label} are coming soon.</p>+function TabLabel({ label, count }: { label: string; count: number }): JSX.Element {+ return (+ <span className="flex items-center gap-1">+ {label}+ {count > 0 && <LemonBadge.Number count={count} status="primary" size="small" />}+ </span>+ )}export function DataCatalogScene(): JSX.Element {const { activeTab } = useValues(dataCatalogSceneLogic)const { setActiveTab } = useActions(dataCatalogSceneLogic)- const { openNewMetricModal } = useActions(metricsLogic)+ const { proposedCount: metricsPending } = useValues(metricsLogic)+ const { pendingCount: relationshipsPending } = useValues(relationshipsLogic)+ const { proposedCount: certificationsPending } = useValues(certificationsLogic)+ const { openNewMetricModal: openMetricModal } = useActions(metricsLogic)const tabs: LemonTab<DataCatalogTab>[] = [{key: 'metrics',- label: 'Metrics',+ label: <TabLabel label="Metrics" count={metricsPending} />,content: <MetricsTab />,link: urls.dataCatalog(),},{key: 'relationships',- label: 'Relationships',- content: <TabPlaceholder label="Relationships" />,+ label: <TabLabel label="Relationships" count={relationshipsPending} />,+ content: <RelationshipsTab />,link: urls.dataCatalog('relationships'),},{key: 'certifications',- label: 'Certifications',- content: <TabPlaceholder label="Certifications" />,+ label: <TabLabel label="Certifications" count={certificationsPending} />,+ content: <CertificationsTab />,link: urls.dataCatalog('certifications'),},]@@ -64,7 +77,7 @@ export function DataCatalogScene(): JSX.Element {type="primary"size="small"icon={<IconPlusSmall />}- onClick={openNewMetricModal}+ onClick={openMetricModal}data-attr="data-catalog-new-metric-button">New metricdiff --git a/products/data_catalog/frontend/certificationsLogic.test.ts b/products/data_catalog/frontend/certificationsLogic.test.tsnew file mode 100644index 000000000000..ff69fa08e0d7--- /dev/null+++ b/products/data_catalog/frontend/certificationsLogic.test.ts@@ -0,0 +1,99 @@+import { initKeaTests } from '~/test/init'+import { expectLogic } from '~/test/keaTestUtils'++import { certificationsLogic } from './certificationsLogic'+import {+ dataCatalogCertificationsCertifyCreate,+ dataCatalogCertificationsDestroy,+ dataCatalogCertificationsList,+} from './generated/api'+import type { DataCatalogCertificationApi } from './generated/api.schemas'++jest.mock('lib/api', () => {+ class ApiError extends Error {+ status?: number+ detail: string | null+ constructor(message?: string, status?: number, _headers?: unknown, data?: { detail?: string }) {+ super(message)+ this.status = status+ this.detail = data?.detail ?? null+ }+ }+ return {+ __esModule: true,+ default: {},+ ApiConfig: { getCurrentTeamId: jest.fn(() => 1) },+ ApiError,+ }+})++jest.mock('lib/lemon-ui/LemonToast/LemonToast', () => ({+ lemonToast: { success: jest.fn(), error: jest.fn(), info: jest.fn(), warning: jest.fn() },+}))++jest.mock('scenes/data-management/database/databaseTableListLogic', () => ({+ databaseTableListLogic: { loadDatabase: jest.fn(() => ({ type: 'load database (mock)' })) },+}))++jest.mock('./generated/api', () => ({+ dataCatalogCertificationsList: jest.fn(),+ dataCatalogCertificationsCreate: jest.fn(),+ dataCatalogCertificationsCertifyCreate: jest.fn(),+ dataCatalogCertificationsDeprecateCreate: jest.fn(),+ dataCatalogCertificationsDestroy: jest.fn(),+}))++function buildCertification(overrides: Partial<DataCatalogCertificationApi>): DataCatalogCertificationApi {+ return {+ id: 'cert-1',+ target_name: 'stripe_charges',+ target_type: 'table',+ status: 'proposed',+ notes: '',+ ...overrides,+ } as DataCatalogCertificationApi+}++describe('certificationsLogic', () => {+ let logic: ReturnType<typeof certificationsLogic.build>++ beforeEach(async () => {+ jest.clearAllMocks()+ ;(dataCatalogCertificationsList as jest.Mock).mockResolvedValue({+ results: [+ buildCertification({ id: 'cert-1', status: 'proposed' }),+ buildCertification({ id: 'cert-2', status: 'certified' }),+ ],+ })+ initKeaTests()+ logic = certificationsLogic()+ logic.mount()+ await expectLogic(logic).toDispatchActions(['loadCertificationsSuccess'])+ })++ it('counts only proposed certifications as pending', () => {+ expect(logic.values.proposedCount).toEqual(1)+ })++ it('replaces the row status from the response when certifying', async () => {+ ;(dataCatalogCertificationsCertifyCreate as jest.Mock).mockResolvedValue(+ buildCertification({ id: 'cert-1', status: 'certified' })+ )++ logic.actions.certifyCertification('cert-1')+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.certifications.find((certification) => certification.id === 'cert-1')?.status).toEqual(+ 'certified'+ )+ })++ it('removes the row when revoking', async () => {+ ;(dataCatalogCertificationsDestroy as jest.Mock).mockResolvedValue(undefined)++ logic.actions.revokeCertification('cert-1')+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.certifications.map((certification) => certification.id)).not.toContain('cert-1')+ })+})diff --git a/products/data_catalog/frontend/certificationsLogic.tsx b/products/data_catalog/frontend/certificationsLogic.tsxnew file mode 100644index 000000000000..9933698ff8e0--- /dev/null+++ b/products/data_catalog/frontend/certificationsLogic.tsx@@ -0,0 +1,267 @@+import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'+import { loaders } from 'kea-loaders'++import { ApiConfig, ApiError } from 'lib/api'+import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'+import { databaseTableListLogic } from 'scenes/data-management/database/databaseTableListLogic'++import {+ dataCatalogCertificationsCertifyCreate,+ dataCatalogCertificationsCreate,+ dataCatalogCertificationsDeprecateCreate,+ dataCatalogCertificationsDestroy,+ dataCatalogCertificationsList,+} from './generated/api'+import type { DataCatalogCertificationApi } from './generated/api.schemas'++export type CertificationTargetType = 'table' | 'view'++export interface NewCertificationForm {+ targetName: string+ targetType: CertificationTargetType+ notes: string+}++export const EMPTY_NEW_CERTIFICATION_FORM: NewCertificationForm = {+ targetName: '',+ targetType: 'table',+ notes: '',+}++function projectId(): string {+ return String(ApiConfig.getCurrentTeamId())+}++function apiErrorDetail(error: unknown): string | null {+ return error instanceof ApiError ? error.detail : null+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface certificationsLogicValues {+ actionsInFlight: Record<string, boolean>+ certifications: DataCatalogCertificationApi[]+ certificationsLoading: boolean+ isCreatingCertification: boolean+ newCertificationForm: NewCertificationForm+ newCertificationModalOpen: boolean+ proposedCount: number+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface certificationsLogicActions {+ loadDatabase: (+ args_0?:+ | {+ force?: boolean+ }+ | undefined+ ) => {+ force?: boolean+ } // databaseTableListLogic+ certifyCertification: (id: string) => {+ id: string+ }+ closeNewCertificationModal: () => {+ value: true+ }+ createCertification: () => {+ value: true+ }+ deprecateCertification: (id: string) => {+ id: string+ }+ loadCertifications: () => any+ loadCertificationsFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadCertificationsSuccess: (+ certifications: DataCatalogCertificationApi[],+ payload?: any+ ) => {+ certifications: DataCatalogCertificationApi[]+ payload?: any+ }+ openNewCertificationModal: () => {+ value: true+ }+ revokeCertification: (id: string) => {+ id: string+ }+ setActionInFlight: (+ id: string,+ inFlight: boolean+ ) => {+ id: string+ inFlight: boolean+ }+ setCreatingCertification: (creating: boolean) => {+ creating: boolean+ }+ setNewCertificationForm: (form: Partial<NewCertificationForm>) => {+ form: Partial<NewCertificationForm>+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface certificationsLogicMeta {+ __keaTypeGenInternalSelectorTypes: {+ proposedCount: (certifications: DataCatalogCertificationApi[]) => number+ }+}++export type certificationsLogicType = MakeLogicType<+ certificationsLogicValues,+ certificationsLogicActions,+ Record<string, any>,+ certificationsLogicMeta+>++export const certificationsLogic = kea<certificationsLogicType>([+ path(['products', 'data_catalog', 'frontend', 'certificationsLogic']),+ connect(() => ({+ actions: [databaseTableListLogic, ['loadDatabase']],+ })),+ actions({+ openNewCertificationModal: true,+ closeNewCertificationModal: true,+ setNewCertificationForm: (form: Partial<NewCertificationForm>) => ({ form }),+ createCertification: true,+ setCreatingCertification: (creating: boolean) => ({ creating }),+ certifyCertification: (id: string) => ({ id }),+ deprecateCertification: (id: string) => ({ id }),+ revokeCertification: (id: string) => ({ id }),+ setActionInFlight: (id: string, inFlight: boolean) => ({ id, inFlight }),+ }),+ loaders(() => ({+ certifications: [+ [] as DataCatalogCertificationApi[],+ {+ loadCertifications: async () => {+ const response = await dataCatalogCertificationsList(projectId())+ return response.results || []+ },+ },+ ],+ })),+ reducers({+ newCertificationModalOpen: [+ false,+ {+ openNewCertificationModal: () => true,+ closeNewCertificationModal: () => false,+ },+ ],+ newCertificationForm: [+ EMPTY_NEW_CERTIFICATION_FORM as NewCertificationForm,+ {+ setNewCertificationForm: (state, { form }) => ({ ...state, ...form }),+ openNewCertificationModal: () => EMPTY_NEW_CERTIFICATION_FORM,+ closeNewCertificationModal: () => EMPTY_NEW_CERTIFICATION_FORM,+ },+ ],+ isCreatingCertification: [+ false,+ {+ setCreatingCertification: (_, { creating }) => creating,+ },+ ],+ actionsInFlight: [+ {} as Record<string, boolean>,+ {+ setActionInFlight: (state, { id, inFlight }) => ({ ...state, [id]: inFlight }),+ },+ ],+ }),+ selectors({+ proposedCount: [+ (s) => [s.certifications],+ (certifications: DataCatalogCertificationApi[]) =>+ certifications.filter((certification) => certification.status === 'proposed').length,+ ],+ }),+ listeners(({ values, actions }) => {+ // certify and deprecate share a body: both replace the row in place from the response.+ const runReviewAction = async (+ id: string,+ request: () => Promise<DataCatalogCertificationApi>,+ failureMessage: string+ ): Promise<void> => {+ if (values.actionsInFlight[id]) {+ return+ }+ actions.setActionInFlight(id, true)+ try {+ const updated = await request()+ actions.loadCertificationsSuccess(+ values.certifications.map((certification) => (certification.id === id ? updated : certification))+ )+ } catch (error) {+ lemonToast.error(apiErrorDetail(error) || failureMessage)+ } finally {+ actions.setActionInFlight(id, false)+ }+ }++ return {+ openNewCertificationModal: () => actions.loadDatabase(),+ createCertification: async () => {+ if (values.isCreatingCertification) {+ return+ }+ actions.setCreatingCertification(true)+ const form = values.newCertificationForm+ try {+ const created = await dataCatalogCertificationsCreate(projectId(), {+ ...(form.targetType === 'view'+ ? { view_name: form.targetName }+ : { table_name: form.targetName }),+ notes: form.notes || undefined,+ })+ actions.loadCertificationsSuccess([created, ...values.certifications])+ actions.closeNewCertificationModal()+ lemonToast.success('Certification proposed')+ } catch (error) {+ lemonToast.error(apiErrorDetail(error) || 'Could not propose the certification. Try again.')+ } finally {+ actions.setCreatingCertification(false)+ }+ },+ certifyCertification: async ({ id }) =>+ runReviewAction(+ id,+ () => dataCatalogCertificationsCertifyCreate(projectId(), id),+ 'Could not certify. Try again.'+ ),+ deprecateCertification: async ({ id }) =>+ runReviewAction(+ id,+ () => dataCatalogCertificationsDeprecateCreate(projectId(), id),+ 'Could not deprecate. Try again.'+ ),+ revokeCertification: async ({ id }) => {+ if (values.actionsInFlight[id]) {+ return+ }+ actions.setActionInFlight(id, true)+ try {+ await dataCatalogCertificationsDestroy(projectId(), id)+ actions.loadCertificationsSuccess(+ values.certifications.filter((certification) => certification.id !== id)+ )+ lemonToast.success('Certification revoked')+ } catch (error) {+ lemonToast.error(apiErrorDetail(error) || 'Could not revoke the certification. Try again.')+ } finally {+ actions.setActionInFlight(id, false)+ }+ },+ }+ }),+ afterMount(({ actions }) => {+ actions.loadCertifications()+ }),+])diff --git a/products/data_catalog/frontend/components/NewCertificationModal.tsx b/products/data_catalog/frontend/components/NewCertificationModal.tsxnew file mode 100644index 000000000000..9a99808c097d--- /dev/null+++ b/products/data_catalog/frontend/components/NewCertificationModal.tsx@@ -0,0 +1,108 @@+import { useActions, useValues } from 'kea'++import { LemonButton } from 'lib/lemon-ui/LemonButton'+import { LemonField } from 'lib/lemon-ui/LemonField'+import { LemonModal } from 'lib/lemon-ui/LemonModal'+import { LemonSelect } from 'lib/lemon-ui/LemonSelect'+import { LemonTextArea } from 'lib/lemon-ui/LemonTextArea'+import { databaseTableListLogic } from 'scenes/data-management/database/databaseTableListLogic'++import { CertificationTargetType, certificationsLogic } from '../certificationsLogic'++const VIEW_TABLE_TYPES = new Set(['view', 'materialized_view', 'managed_view'])++function targetTypeForTable(tableType: string): CertificationTargetType | null {+ if (tableType === 'data_warehouse') {+ return 'table'+ }+ if (VIEW_TABLE_TYPES.has(tableType)) {+ return 'view'+ }+ return null+}++export function NewCertificationModal(): JSX.Element {+ const { newCertificationModalOpen, newCertificationForm, isCreatingCertification } = useValues(certificationsLogic)+ const { setNewCertificationForm, createCertification, closeNewCertificationModal } = useActions(certificationsLogic)+ const { allTables, databaseLoading } = useValues(databaseTableListLogic)++ // Certification targets are keyed by (type, name), so a warehouse table and a view sharing a+ // name are distinct targets. Encode the type into the option value so they don't collapse.+ const optionEntries = allTables+ .map((table) => ({ table, targetType: targetTypeForTable(table.type) }))+ .filter(+ (option): option is { table: (typeof allTables)[number]; targetType: CertificationTargetType } =>+ option.targetType !== null+ )+ .map(({ table, targetType }) => ({+ value: `${targetType}:${table.name}`,+ name: table.name,+ targetType,+ }))++ const options = optionEntries.map(({ value, name, targetType }) => ({+ value,+ label: name,+ labelInMenu: `${name} (${targetType})`,+ }))++ const selectedValue = newCertificationForm.targetName+ ? `${newCertificationForm.targetType}:${newCertificationForm.targetName}`+ : null++ const submitDisabledReason = !newCertificationForm.targetName ? 'Choose a table or view' : undefined++ return (+ <LemonModal+ isOpen={newCertificationModalOpen}+ onClose={closeNewCertificationModal}+ width={560}+ title="Propose a certification"+ >+ <LemonModal.Content>+ <div className="flex flex-col gap-4">+ <LemonField.Pure label="Table or view">+ <LemonSelect+ value={selectedValue}+ onChange={(value) => {+ const selected = optionEntries.find((entry) => entry.value === value)+ setNewCertificationForm({+ targetName: selected?.name ?? '',+ targetType: selected?.targetType ?? 'table',+ })+ }}+ options={options}+ loading={databaseLoading}+ placeholder="Select a warehouse table or view"+ data-attr="data-catalog-certification-target"+ />+ </LemonField.Pure>++ <LemonField.Pure label="Notes">+ <LemonTextArea+ value={newCertificationForm.notes}+ onChange={(notes) => setNewCertificationForm({ notes })}+ placeholder="Why should the team trust this source?"+ minRows={2}+ />+ </LemonField.Pure>+ </div>+ </LemonModal.Content>++ <LemonModal.Footer>+ <LemonButton type="secondary" onClick={closeNewCertificationModal} disabled={isCreatingCertification}>+ Cancel+ </LemonButton>+ <LemonButton+ type="primary"+ onClick={createCertification}+ loading={isCreatingCertification}+ disabledReason={submitDisabledReason}+ data-attr="data-catalog-create-certification-submit"+ >+ Propose certification+ </LemonButton>+ </LemonModal.Footer>+ </LemonModal>+ )+}diff --git a/products/data_catalog/frontend/relationshipsLogic.test.ts b/products/data_catalog/frontend/relationshipsLogic.test.tsnew file mode 100644index 000000000000..c87adafc7b05--- /dev/null+++ b/products/data_catalog/frontend/relationshipsLogic.test.ts@@ -0,0 +1,155 @@+import api from 'lib/api'+import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'++import { initKeaTests } from '~/test/init'+import { expectLogic } from '~/test/keaTestUtils'++import {+ dataCatalogRelationshipProposalsAcceptCreate,+ dataCatalogRelationshipProposalsList,+ dataCatalogRelationshipProposalsRejectCreate,+} from './generated/api'+import type { DataCatalogRelationshipProposalApi } from './generated/api.schemas'+import { relationshipsLogic } from './relationshipsLogic'++jest.mock('lib/api', () => {+ class ApiError extends Error {+ status?: number+ detail: string | null+ constructor(message?: string, status?: number, _headers?: unknown, data?: { detail?: string }) {+ super(message)+ this.status = status+ this.detail = data?.detail ?? null+ }+ }+ return {+ __esModule: true,+ default: { dataWarehouseViewLinks: { list: jest.fn() } },+ ApiConfig: { getCurrentTeamId: jest.fn(() => 1) },+ ApiError,+ }+})++jest.mock('lib/lemon-ui/LemonToast/LemonToast', () => ({+ lemonToast: { success: jest.fn(), error: jest.fn(), info: jest.fn(), warning: jest.fn() },+}))++jest.mock('./generated/api', () => ({+ dataCatalogRelationshipProposalsList: jest.fn(),+ dataCatalogRelationshipProposalsAcceptCreate: jest.fn(),+ dataCatalogRelationshipProposalsRejectCreate: jest.fn(),+}))++function buildProposal(overrides: Partial<DataCatalogRelationshipProposalApi>): DataCatalogRelationshipProposalApi {+ return {+ id: 'proposal-1',+ source_table_name: 'events',+ source_table_key: 'person_id',+ joining_table_name: 'persons',+ joining_table_key: 'id',+ field_name: 'person',+ status: 'proposed',+ confidence: 0.9,+ reasoning: 'high match rate',+ rejection_reason: '',+ created_join: null,+ ...overrides,+ } as DataCatalogRelationshipProposalApi+}++describe('relationshipsLogic', () => {+ let logic: ReturnType<typeof relationshipsLogic.build>++ async function mountWith(+ proposals: DataCatalogRelationshipProposalApi[],+ joins: { id: string; source_table_name?: string }[]+ ): Promise<void> {+ ;(dataCatalogRelationshipProposalsList as jest.Mock).mockResolvedValue({+ results: proposals,+ count: proposals.filter((proposal) => proposal.status === 'proposed').length,+ })+ ;(api.dataWarehouseViewLinks.list as jest.Mock).mockResolvedValue({ results: joins })+ initKeaTests()+ logic = relationshipsLogic()+ logic.mount()+ await expectLogic(logic).toDispatchActions(['loadPendingCountSuccess'])+ // The full proposal/join payloads load only when the Relationships tab is viewed.+ logic.actions.loadProposals()+ logic.actions.loadJoins()+ await expectLogic(logic).toDispatchActions(['loadProposalsSuccess', 'loadJoinsSuccess'])+ }++ beforeEach(() => {+ jest.clearAllMocks()+ })++ it('loads only the lightweight badge count on mount, not the full proposal payloads', async () => {+ ;(dataCatalogRelationshipProposalsList as jest.Mock).mockResolvedValue({ results: [], count: 3 })+ ;(api.dataWarehouseViewLinks.list as jest.Mock).mockResolvedValue({ results: [] })+ initKeaTests()+ logic = relationshipsLogic()+ logic.mount()++ await expectLogic(logic)+ .toDispatchActions(['loadPendingCountSuccess'])+ .toNotHaveDispatchedActions(['loadProposals', 'loadJoins'])+ expect(logic.values.pendingCount).toEqual(3)+ expect(dataCatalogRelationshipProposalsList).toHaveBeenCalledWith('1', { status: 'proposed', limit: 1 })+ })++ it('folds an accepted proposal into its created join and tags it via-catalog', async () => {+ await mountWith(+ [+ buildProposal({+ id: 'accepted',+ status: 'accepted',+ created_join: 'join-1',+ reviewed_by: { email: '[email protected]' } as any,+ }),+ buildProposal({ id: 'pending', status: 'proposed' }),+ ],+ [+ { id: 'join-1', source_table_name: 'events' },+ { id: 'join-2', source_table_name: 'manual' },+ ]+ )++ const rows = logic.values.rows+ expect(rows.find((row) => row.proposalId === 'accepted')).toBeUndefined()++ const viaCatalog = rows.find((row) => row.key === 'join-join-1')+ expect(viaCatalog?.viaCatalog).toEqual(true)+ expect(viaCatalog?.rowStatus).toEqual('active')++ const manual = rows.find((row) => row.key === 'join-join-2')+ expect(manual?.viaCatalog).toEqual(false)+ expect(manual?.rowStatus).toEqual('active')++ expect(rows.find((row) => row.proposalId === 'pending')?.rowStatus).toEqual('pending')+ })++ it('passes the rejection reason through when rejecting', async () => {+ await mountWith([buildProposal({ id: 'pending', status: 'proposed' })], [])+ ;(dataCatalogRelationshipProposalsRejectCreate as jest.Mock).mockResolvedValue(+ buildProposal({ status: 'rejected' })+ )++ logic.actions.rejectProposal('pending', 'wrong join')+ await expectLogic(logic).toFinishAllListeners()++ expect(dataCatalogRelationshipProposalsRejectCreate).toHaveBeenCalledWith('1', 'pending', {+ rejection_reason: 'wrong join',+ })+ })++ it('surfaces the error and clears loading when accept fails', async () => {+ await mountWith([buildProposal({ id: 'pending', status: 'proposed' })], [])+ ;(dataCatalogRelationshipProposalsAcceptCreate as jest.Mock).mockRejectedValue(new Error('probe failed'))++ logic.actions.acceptProposal('pending')+ await expectLogic(logic).toFinishAllListeners()++ expect(lemonToast.error).toHaveBeenCalled()+ expect(logic.values.actionsInFlight.pending).toEqual(false)+ })+})diff --git a/products/data_catalog/frontend/relationshipsLogic.tsx b/products/data_catalog/frontend/relationshipsLogic.tsxnew file mode 100644index 000000000000..9fbe1b84c0fa--- /dev/null+++ b/products/data_catalog/frontend/relationshipsLogic.tsx@@ -0,0 +1,333 @@+import { MakeLogicType, actions, afterMount, kea, listeners, path, reducers, selectors } from 'kea'+import { loaders } from 'kea-loaders'+import { urlToAction } from 'kea-router'++import api, { ApiConfig, ApiError } from 'lib/api'+import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'+import { urls } from 'scenes/urls'++import { DataWarehouseViewLink } from '~/types'++import {+ dataCatalogRelationshipProposalsAcceptCreate,+ dataCatalogRelationshipProposalsList,+ dataCatalogRelationshipProposalsRejectCreate,+} from './generated/api'+import type { DataCatalogRelationshipProposalApi } from './generated/api.schemas'++export type RelationshipStatusFilter = 'all' | 'pending' | 'active' | 'rejected'+export type RelationshipRowStatus = 'pending' | 'active' | 'rejected'++export interface RelationshipRow {+ key: string+ sourceTableName: string+ sourceTableKey: string+ joiningTableName: string+ joiningTableKey: string+ fieldName: string+ rowStatus: RelationshipRowStatus+ confidence: number | null+ reasoning: string+ evidence: unknown+ rejectionReason: string+ reviewedBy: string | null+ viaCatalog: boolean+ proposalId: string | null+}++function projectId(): string {+ return String(ApiConfig.getCurrentTeamId())+}++function apiErrorDetail(error: unknown): string | null {+ return error instanceof ApiError ? error.detail : null+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface relationshipsLogicValues {+ actionsInFlight: Record<string, boolean>+ filteredRows: RelationshipRow[]+ joins: DataWarehouseViewLink[]+ joinsLoading: boolean+ pendingCount: number+ pendingCountLoading: boolean+ proposals: DataCatalogRelationshipProposalApi[]+ proposalsLoading: boolean+ rows: RelationshipRow[]+ statusFilter: RelationshipStatusFilter+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface relationshipsLogicActions {+ acceptProposal: (id: string) => {+ id: string+ }+ loadJoins: () => any+ loadJoinsFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadJoinsSuccess: (+ joins: DataWarehouseViewLink[],+ payload?: any+ ) => {+ joins: DataWarehouseViewLink[]+ payload?: any+ }+ loadPendingCount: () => any+ loadPendingCountFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadPendingCountSuccess: (+ pendingCount: number,+ payload?: any+ ) => {+ pendingCount: number+ payload?: any+ }+ loadProposals: () => any+ loadProposalsFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadProposalsSuccess: (+ proposals: DataCatalogRelationshipProposalApi[],+ payload?: any+ ) => {+ proposals: DataCatalogRelationshipProposalApi[]+ payload?: any+ }+ rejectProposal: (+ id: string,+ rejectionReason: string+ ) => {+ id: string+ rejectionReason: string+ }+ setActionInFlight: (+ id: string,+ inFlight: boolean+ ) => {+ id: string+ inFlight: boolean+ }+ setStatusFilter: (statusFilter: RelationshipStatusFilter) => {+ statusFilter: RelationshipStatusFilter+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface relationshipsLogicMeta {+ __keaTypeGenInternalSelectorTypes: {+ rows: (proposals: DataCatalogRelationshipProposalApi[], joins: DataWarehouseViewLink[]) => RelationshipRow[]+ filteredRows: (rows: RelationshipRow[], statusFilter: RelationshipStatusFilter) => RelationshipRow[]+ }+}++export type relationshipsLogicType = MakeLogicType<+ relationshipsLogicValues,+ relationshipsLogicActions,+ Record<string, any>,+ relationshipsLogicMeta+>++export const relationshipsLogic = kea<relationshipsLogicType>([+ path(['products', 'data_catalog', 'frontend', 'relationshipsLogic']),+ actions({+ setStatusFilter: (statusFilter: RelationshipStatusFilter) => ({ statusFilter }),+ acceptProposal: (id: string) => ({ id }),+ rejectProposal: (id: string, rejectionReason: string) => ({ id, rejectionReason }),+ setActionInFlight: (id: string, inFlight: boolean) => ({ id, inFlight }),+ }),+ loaders(() => ({+ // Badge count only — never pull the full proposal payloads (unbounded reasoning/evidence)+ // just to render a number on a tab the user may never open.+ pendingCount: [+ 0,+ {+ loadPendingCount: async () => {+ const response = await dataCatalogRelationshipProposalsList(projectId(), {+ status: 'proposed',+ limit: 1,+ })+ return response.count ?? 0+ },+ },+ ],+ proposals: [+ [] as DataCatalogRelationshipProposalApi[],+ {+ loadProposals: async () => {+ const response = await dataCatalogRelationshipProposalsList(projectId())+ return response.results || []+ },+ },+ ],+ joins: [+ [] as DataWarehouseViewLink[],+ {+ loadJoins: async () => {+ const response = await api.dataWarehouseViewLinks.list()+ return response.results || []+ },+ },+ ],+ })),+ reducers({+ statusFilter: [+ 'all' as RelationshipStatusFilter,+ {+ setStatusFilter: (_, { statusFilter }) => statusFilter,+ },+ ],+ actionsInFlight: [+ {} as Record<string, boolean>,+ {+ setActionInFlight: (state, { id, inFlight }) => ({ ...state, [id]: inFlight }),+ },+ ],+ }),+ selectors({+ rows: [+ (s) => [s.proposals, s.joins],+ (proposals: DataCatalogRelationshipProposalApi[], joins: DataWarehouseViewLink[]): RelationshipRow[] => {+ const acceptedByJoinId = new Map<string, DataCatalogRelationshipProposalApi>()+ proposals+ .filter((proposal) => proposal.status === 'accepted' && proposal.created_join)+ .forEach((proposal) => acceptedByJoinId.set(proposal.created_join as string, proposal))++ const joinIds = new Set(joins.map((join) => join.id))++ const joinRows: RelationshipRow[] = joins.map((join) => {+ const proposal = acceptedByJoinId.get(join.id)+ return {+ key: `join-${join.id}`,+ sourceTableName: join.source_table_name || '',+ sourceTableKey: join.source_table_key || '',+ joiningTableName: join.joining_table_name || '',+ joiningTableKey: join.joining_table_key || '',+ fieldName: join.field_name || '',+ rowStatus: 'active',+ confidence: proposal?.confidence ?? null,+ reasoning: proposal?.reasoning ?? '',+ evidence: proposal?.evidence,+ rejectionReason: '',+ reviewedBy: proposal?.reviewed_by?.email ?? null,+ viaCatalog: !!proposal,+ proposalId: null,+ }+ })++ // Accepted proposals whose created join isn't in the loaded joins (null, soft-deleted,+ // or beyond the paginated response) would otherwise vanish — surface them as active rows.+ const orphanedAcceptedRows: RelationshipRow[] = proposals+ .filter(+ (proposal) =>+ proposal.status === 'accepted' &&+ !(proposal.created_join && joinIds.has(proposal.created_join))+ )+ .map((proposal) => ({+ key: `proposal-${proposal.id}`,+ sourceTableName: proposal.source_table_name,+ sourceTableKey: proposal.source_table_key,+ joiningTableName: proposal.joining_table_name,+ joiningTableKey: proposal.joining_table_key,+ fieldName: proposal.field_name,+ rowStatus: 'active',+ confidence: proposal.confidence ?? null,+ reasoning: proposal.reasoning ?? '',+ evidence: proposal.evidence,+ rejectionReason: '',+ reviewedBy: proposal.reviewed_by?.email ?? null,+ viaCatalog: true,+ proposalId: proposal.id,+ }))++ const proposalRows: RelationshipRow[] = proposals+ .filter((proposal) => proposal.status !== 'accepted')+ .map((proposal) => ({+ key: `proposal-${proposal.id}`,+ sourceTableName: proposal.source_table_name,+ sourceTableKey: proposal.source_table_key,+ joiningTableName: proposal.joining_table_name,+ joiningTableKey: proposal.joining_table_key,+ fieldName: proposal.field_name,+ rowStatus: proposal.status === 'rejected' ? 'rejected' : 'pending',+ confidence: proposal.confidence ?? null,+ reasoning: proposal.reasoning ?? '',+ evidence: proposal.evidence,+ rejectionReason: proposal.rejection_reason || '',+ reviewedBy: proposal.reviewed_by?.email ?? null,+ viaCatalog: false,+ proposalId: proposal.id,+ }))++ return [...joinRows, ...orphanedAcceptedRows, ...proposalRows]+ },+ ],+ filteredRows: [+ (s) => [s.rows, s.statusFilter],+ (rows: RelationshipRow[], statusFilter: RelationshipStatusFilter) =>+ statusFilter === 'all' ? rows : rows.filter((row) => row.rowStatus === statusFilter),+ ],+ }),+ listeners(({ values, actions }) => ({+ acceptProposal: async ({ id }) => {+ if (values.actionsInFlight[id]) {+ return+ }+ actions.setActionInFlight(id, true)+ try {+ await dataCatalogRelationshipProposalsAcceptCreate(projectId(), id)+ lemonToast.success('Relationship accepted and promoted to a warehouse join')+ actions.loadProposals()+ actions.loadJoins()+ actions.loadPendingCount()+ } catch (error) {+ lemonToast.error(apiErrorDetail(error) || 'Could not accept the relationship. Try again.')+ } finally {+ actions.setActionInFlight(id, false)+ }+ },+ rejectProposal: async ({ id, rejectionReason }) => {+ if (values.actionsInFlight[id]) {+ return+ }+ actions.setActionInFlight(id, true)+ try {+ await dataCatalogRelationshipProposalsRejectCreate(projectId(), id, {+ rejection_reason: rejectionReason || undefined,+ })+ lemonToast.success('Relationship rejected')+ actions.loadProposals()+ actions.loadPendingCount()+ } catch (error) {+ lemonToast.error(apiErrorDetail(error) || 'Could not reject the relationship. Try again.')+ } finally {+ actions.setActionInFlight(id, false)+ }+ },+ })),+ urlToAction(({ actions }) => ({+ // Load the full proposals and joins only when the Relationships tab is actually viewed.+ [urls.dataCatalog()]: (_, searchParams) => {+ if (searchParams.tab === 'relationships') {+ actions.loadProposals()+ actions.loadJoins()+ }+ },+ })),+ afterMount(({ actions }) => {+ actions.loadPendingCount()+ }),+])diff --git a/products/data_catalog/frontend/tabs/CertificationsTab.tsx b/products/data_catalog/frontend/tabs/CertificationsTab.tsxnew file mode 100644index 000000000000..4e9e42784637--- /dev/null+++ b/products/data_catalog/frontend/tabs/CertificationsTab.tsx@@ -0,0 +1,155 @@+import { useActions, useValues } from 'kea'++import { IconPlusSmall, IconRefresh } from '@posthog/icons'+import { LemonButton, LemonDialog } from '@posthog/lemon-ui'++import { More } from 'lib/lemon-ui/LemonButton/More'+import { LemonTable, LemonTableColumns } from 'lib/lemon-ui/LemonTable'+import { LemonTag } from 'lib/lemon-ui/LemonTag'++import { certificationsLogic } from '../certificationsLogic'+import { NewCertificationModal } from '../components/NewCertificationModal'+import type { DataCatalogCertificationApi } from '../generated/api.schemas'++const STATUS_TAG: Record<string, { label: string; type: 'warning' | 'success' | 'muted' }> = {+ proposed: { label: 'Proposed', type: 'warning' },+ certified: { label: 'Certified', type: 'success' },+ deprecated: { label: 'Deprecated', type: 'muted' },+}++export function CertificationsTab(): JSX.Element {+ const { certifications, certificationsLoading, actionsInFlight } = useValues(certificationsLogic)+ const {+ loadCertifications,+ openNewCertificationModal,+ certifyCertification,+ deprecateCertification,+ revokeCertification,+ } = useActions(certificationsLogic)++ const confirmRevoke = (certification: DataCatalogCertificationApi): void => {+ LemonDialog.open({+ title: 'Revoke this certification?',+ content: (+ <div className="text-sm text-secondary">+ Revoking deletes the trust mark on {certification.target_name}. This cannot be undone.+ </div>+ ),+ primaryButton: {+ children: 'Revoke',+ status: 'danger',+ onClick: () => revokeCertification(certification.id),+ },+ secondaryButton: { children: 'Cancel' },+ })+ }++ const columns: LemonTableColumns<DataCatalogCertificationApi> = [+ {+ title: 'Target',+ key: 'target_name',+ render: (_, certification) => certification.target_name,+ },+ {+ title: 'Type',+ key: 'target_type',+ render: (_, certification) => <LemonTag type="option">{certification.target_type}</LemonTag>,+ },+ {+ title: 'Status',+ key: 'status',+ render: (_, certification) => {+ const tag = STATUS_TAG[certification.status] ?? { label: certification.status, type: 'muted' as const }+ return <LemonTag type={tag.type}>{tag.label}</LemonTag>+ },+ },+ {+ title: 'Notes',+ key: 'notes',+ render: (_, certification) => certification.notes || <span className="text-secondary">-</span>,+ },+ {+ title: 'Certified by',+ key: 'certified_by',+ render: (_, certification) =>+ certification.certified_by?.email || <span className="text-secondary">-</span>,+ },+ {+ key: 'actions',+ width: 0,+ render: (_, certification) => {+ const inFlight = !!actionsInFlight[certification.id]+ return (+ <More+ overlay={+ <>+ {certification.status !== 'certified' && (+ <LemonButton+ fullWidth+ loading={inFlight}+ onClick={() => certifyCertification(certification.id)}+ >+ Certify+ </LemonButton>+ )}+ {certification.status === 'certified' && (+ <LemonButton+ fullWidth+ loading={inFlight}+ onClick={() => deprecateCertification(certification.id)}+ >+ Deprecate+ </LemonButton>+ )}+ <LemonButton+ fullWidth+ status="danger"+ disabledReason={inFlight ? 'Working' : undefined}+ onClick={() => confirmRevoke(certification)}+ >+ Revoke+ </LemonButton>+ </>+ }+ />+ )+ },+ },+ ]++ return (+ <div className="flex flex-col gap-4">+ <div className="flex justify-end gap-2 flex-wrap items-center">+ <LemonButton+ type="secondary"+ icon={<IconRefresh />}+ size="small"+ loading={certificationsLoading}+ onClick={() => loadCertifications()}+ >+ Reload+ </LemonButton>+ <LemonButton+ type="primary"+ icon={<IconPlusSmall />}+ size="small"+ onClick={openNewCertificationModal}+ data-attr="data-catalog-new-certification-button"+ >+ Propose certification+ </LemonButton>+ </div>+ <LemonTable+ data-attr="data-catalog-certifications-table"+ dataSource={certifications}+ rowKey="id"+ columns={columns}+ loading={certificationsLoading}+ pagination={{ pageSize: 20 }}+ emptyState="No certifications yet."+ nouns={['certification', 'certifications']}+ />+ <NewCertificationModal />+ </div>+ )+}diff --git a/products/data_catalog/frontend/tabs/RelationshipsTab.tsx b/products/data_catalog/frontend/tabs/RelationshipsTab.tsxnew file mode 100644index 000000000000..5877297906c8--- /dev/null+++ b/products/data_catalog/frontend/tabs/RelationshipsTab.tsx@@ -0,0 +1,194 @@+import { useActions, useValues } from 'kea'++import { IconRefresh } from '@posthog/icons'+import { LemonButton, LemonDialog } from '@posthog/lemon-ui'++import { CodeSnippet, Language } from 'lib/components/CodeSnippet/CodeSnippet'+import { LemonField } from 'lib/lemon-ui/LemonField'+import { LemonSegmentedButton } from 'lib/lemon-ui/LemonSegmentedButton'+import { LemonTable, LemonTableColumns } from 'lib/lemon-ui/LemonTable'+import { LemonTag } from 'lib/lemon-ui/LemonTag'+import { LemonTextArea } from 'lib/lemon-ui/LemonTextArea'+import { Tooltip } from 'lib/lemon-ui/Tooltip'++import { RelationshipRow, RelationshipStatusFilter, relationshipsLogic } from '../relationshipsLogic'++const STATUS_FILTER_OPTIONS: { value: RelationshipStatusFilter; label: string }[] = [+ { value: 'all', label: 'All' },+ { value: 'pending', label: 'Pending' },+ { value: 'active', label: 'Active' },+ { value: 'rejected', label: 'Rejected' },+]++const STATUS_TAG: Record<RelationshipRow['rowStatus'], { label: string; type: 'warning' | 'success' | 'danger' }> = {+ pending: { label: 'Pending', type: 'warning' },+ active: { label: 'Active', type: 'success' },+ rejected: { label: 'Rejected', type: 'danger' },+}++function tableRef(table: string, key: string): string {+ return key ? `${table}.${key}` : table+}++export function RelationshipsTab(): JSX.Element {+ const { filteredRows, proposalsLoading, joinsLoading, statusFilter, actionsInFlight } =+ useValues(relationshipsLogic)+ const { setStatusFilter, acceptProposal, rejectProposal, loadProposals, loadJoins } = useActions(relationshipsLogic)++ const confirmReject = (row: RelationshipRow): void => {+ if (!row.proposalId) {+ return+ }+ LemonDialog.openForm({+ title: 'Reject this relationship?',+ description: 'Rejecting is permanent: this table pair will not be proposed again.',+ initialValues: { rejectionReason: '' },+ content: (+ <LemonField name="rejectionReason" label="Reason (optional)">+ <LemonTextArea placeholder="Why is this join wrong?" />+ </LemonField>+ ),+ onSubmit: ({ rejectionReason }) => rejectProposal(row.proposalId as string, rejectionReason || ''),+ })+ }++ const columns: LemonTableColumns<RelationshipRow> = [+ {+ title: 'Source',+ key: 'source',+ render: (_, row) => (+ <span className="font-mono text-xs">{tableRef(row.sourceTableName, row.sourceTableKey)}</span>+ ),+ },+ {+ title: 'Joins to',+ key: 'joining',+ render: (_, row) => (+ <span className="font-mono text-xs">{tableRef(row.joiningTableName, row.joiningTableKey)}</span>+ ),+ },+ {+ title: (+ <Tooltip title="The field added to the source table to reach the joined rows, for example events.person">+ <span>Accessor</span>+ </Tooltip>+ ),+ key: 'field',+ render: (_, row) => row.fieldName,+ },+ {+ title: 'Confidence',+ key: 'confidence',+ render: (_, row) => (row.confidence != null ? `${Math.round(row.confidence * 100)}%` : ''),+ },+ {+ title: 'Status',+ key: 'status',+ render: (_, row) => (+ <div className="flex items-center gap-1">+ <LemonTag type={STATUS_TAG[row.rowStatus].type}>{STATUS_TAG[row.rowStatus].label}</LemonTag>+ {row.viaCatalog && <LemonTag type="completion">Via catalog</LemonTag>}+ </div>+ ),+ },+ {+ title: 'Reviewed by',+ key: 'reviewedBy',+ render: (_, row) => row.reviewedBy || <span className="text-secondary">-</span>,+ },+ {+ key: 'actions',+ width: 0,+ render: (_, row) => {+ if (row.rowStatus !== 'pending' || !row.proposalId) {+ return null+ }+ const inFlight = !!actionsInFlight[row.proposalId]+ return (+ <div className="flex gap-1">+ <LemonButton+ type="primary"+ size="small"+ loading={inFlight}+ onClick={() => acceptProposal(row.proposalId as string)}+ >+ Accept+ </LemonButton>+ <LemonButton+ type="secondary"+ size="small"+ disabled={inFlight}+ onClick={() => confirmReject(row)}+ >+ Reject+ </LemonButton>+ </div>+ )+ },+ },+ ]++ return (+ <div className="flex flex-col gap-4">+ <div className="flex justify-between gap-2 flex-wrap items-center">+ <LemonSegmentedButton+ value={statusFilter}+ onChange={setStatusFilter}+ options={STATUS_FILTER_OPTIONS}+ size="small"+ />+ <LemonButton+ type="secondary"+ icon={<IconRefresh />}+ size="small"+ loading={proposalsLoading || joinsLoading}+ onClick={() => {+ loadProposals()+ loadJoins()+ }}+ >+ Reload+ </LemonButton>+ </div>+ <LemonTable+ data-attr="data-catalog-relationships-table"+ dataSource={filteredRows}+ rowKey="key"+ columns={columns}+ loading={proposalsLoading || joinsLoading}+ pagination={{ pageSize: 20 }}+ emptyState="No relationships match your filters."+ nouns={['relationship', 'relationships']}+ expandable={{+ rowExpandable: (row) => !!row.reasoning || !!row.evidence || !!row.rejectionReason,+ expandedRowRender: (row) => <RelationshipDetail row={row} />,+ }}+ />+ </div>+ )+}++function RelationshipDetail({ row }: { row: RelationshipRow }): JSX.Element {+ return (+ <div className="flex flex-col gap-2 p-2">+ {row.reasoning && (+ <div>+ <span className="text-secondary">Reasoning</span>+ <p className="mb-0">{row.reasoning}</p>+ </div>+ )}+ {row.rejectionReason && (+ <div>+ <span className="text-secondary">Rejection reason</span>+ <p className="mb-0">{row.rejectionReason}</p>+ </div>+ )}+ {row.evidence != null && (+ <div>+ <span className="text-secondary">Evidence</span>+ <CodeSnippet language={Language.JSON}>{JSON.stringify(row.evidence, null, 2)}</CodeSnippet>+ </div>+ )}+ </div>+ )+}