DataSets MFE Documentation
MFE Name: DataSets
Date: 19-03-2024
1. Overview
The Data Sets MFE is responsible for displaying Adverse Media and AML Checks datasets. It consists of different folders for better organization, including views, components, apis, store, graphql, and icons.
Folder Structure:
/dart-datasets/src/
│── views/ # Contains main pages or screens
│── components/ # UI components for Adverse Media & AML Checks
│── apis/ # API calls using GraphQL queries
│── store/ # State management (if applicable)
│── graphql/ # GraphQL queries & auto-generated files
│── icons/ # Stores all icon assets
1. DataSetsDashboard Component
- File: DataSetsDashboard.tsx
- Purpose:
- Displays Adverse Media and AML Checks data.
- Uses @mantine/core for UI.
- Implements tabs for switching between datasets.
Code Breakdown
- Uses useState to manage the active tab.
- Uses Mantine Tabs to switch between Adverse Media & AML Checks.
- Loads respective components inside Tabs.Panel.
2. AdverseMedia.tsx Component
The AdverseMedia component is a comprehensive dashboard for tracking, filtering, and managing entities with adverse media hits. It provides a tabbed interface to navigate between different entity types and displays their associated media mentions.
Component Structure
Props
- currentTab: string - Indicates the currently active tab in the parent component
State Management
- Uses Jotai atoms for pagination state:
- paginationCompanyAtomAdverse
- paginationDirectorAtomAdverse
- paginationIndividualAtomAdverse
- paginationNonCompanyAtomAdverse
- paginationForeignCompanyAtomAdverse
- Local state variables:
- search: string - For entity name filtering
- activeTab: string - Current tab selection
- shouldFetchData: boolean - Controls when to fetch data
- filterImportant: boolean - Controls filtering to show only important entities
- shouldFetchCsvData: boolean - Controls when to fetch data for CSV export
- csvEntities: AdverseProps[] - Stores data for CSV export
- isDownloading: boolean - Loading state for CSV download
API Integration
GraphQL Queries
- GetEntityHitsCountQuery - Fetches the count of hits for each entity
- Entity listing queries for different entity types:
- ListCompaniesByOrgIdQuery
- ListDirectorsByOrgIdQuery
- ListIndividualByOrgIdQuery
- ListNonCompaniesByOrgIDQuery
- ListForeignCompaniesByOrgIDQuery
GraphQL Mutations
- Entity importance toggle mutations:
- ChangeCompanyAsImportantMutation
- ChangeDirectorAsImportantMutation
- ChangeIndividualAsImportantMutation
- ChangeNonCompanyAsImportantMutation
- ChangeForeignCompanyAsImportantQuery
Key Functions
Entity Importance Handlers
- handleCompanyIsImportant(companyID: string)
- handleDirectorIsImportant(director: string)
- handleIndividualIsImportant(individual: string)
- handleNonCompanyIsImportant(noncompany: string)
- handleForeignCompanyIsImportant(foreigncompany: string)
Filtering Functions
- getFilteredCompanies()
- getFilteredDirectors()
- getFilteredIndividuals()
- getFilteredNonCompanies()
- getFilteredForeignCompanies()
Data Export
- handleCsvDownload() - Initiates CSV data gathering
- CSV processing useEffect - Processes and downloads data when available
UI Components
Dashboard Statistics Cards
4. UI Components
- Built with Mantine UI components (Table, Card, Modal, etc.)
- Implements a sticky header table with custom styling
- Uses visual indicators (red dots) for entities with high default counts
- Provides modal dialogs for detailed entity information
5. User Interactions
- Row click navigation to entity details
- Search functionality with debounced input
- CSV export capability with dynamic data fetching
- Tab-based navigation in the detail modal
6. Modal Implementation
- Detailed view with tabbed interface showing NPA and Wilful Defaults
- Dynamically filters and formats default records
- Handles empty state with appropriate messaging
- Formats currency values using Intl.NumberFormat
7. CSV Export Logic
- Fetches complete dataset when export is requested
- Processes and transforms data for CSV format
- Creates downloadable file using Blob API
- Implements loading states and error prevention
Component Structure
The component follows a clean organization:
- State definitions and hooks
- Data fetching logic
- Data transformation
- Row rendering and event handlers
- CSV export implementation
Performance Considerations
- Implements conditional data fetching to minimize API calls
- Uses deferred values for search to prevent rendering thrashing
- Implements virtualized scrolling with fixed height container
- Optimizes modal rendering with filtered data
3. MCACharges Component
Component Overview
The MCACharges component displays financial charge records registered with the MCA for companies, presenting data in a tabular format with summary metrics and detailed modal views.
Key Technical Elements
1. State Management
- Uses local React state for search, filtering, and download operations
- Employs Jotai atoms for persistent pagination state
- Implements conditional data fetching through the shouldFetchData flag
- Uses useDeferredValue for optimized search performance
2. Data Retrieval
- Fetches data using custom GraphQL queries:
- GetOverallMCAChargesDataQuery: Main tabular data with pagination
- GetMcaChargesQuery: Summary statistics
- useSearchCharges/useSearchDirectors: Detail data for modal views
- Implements conditional fetching based on active tab
3. Data Presentation
- Organizes complex charge data across multiple columns
- Implements proper number formatting using toLocaleString('en-IN')
- Converts financial values from raw amounts to lakhs (dividing by 100,000)
- Handles missing data with fallback displays
4. User Interactions
- Row click navigates to entity details
- Action button click opens detailed modal with event propagation prevention
- Search functionality with optimized input
- CSV export with dynamic data fetching
5. CSV Export Implementation
- On-demand data retrieval for full dataset
- Formats data for CSV structure
- Creates downloadable file using Blob API
- Manages loading states and error prevention
4. Litigations and Modal Components
These components work together to display corporate litigation data with a detailed modal view for case inspection.
Litigations Component
Component Overview
The Litigations component displays legal cases associated with entities in a tabular format with summary metrics. It features visual risk indicators, filtering options, and detailed modal views.
Key Technical Elements
1. State Management
- Uses local state for UI controls and search
- Leverages Jotai atoms for pagination state (paginationAtomLitigation)
- Implements conditional data fetching based on the active tab
- Uses useDeferredValue for optimized search performance
2. Data Retrieval
- Fetches data using GraphQL queries:
- SearchLitigationCasesByNameQuery: Main table data with pagination
- useSearchLitigations: Detailed litigation data for the modal view
- Implements conditional data loading based on component visibility
3. Visual Risk Indicators
- Uses red dots to highlight entities with more than 5 litigation cases
- Separate indicators for total, high court, and other court cases
- Displays properly formatted numeric values with Indian locale
4. Modal Integration
- Passes selected entity data to the LitigationModal component
- Prevents event propagation when clicking the action button
- Maintains entity name and CIN for context in the modal
5. CSV Export Logic
- Implements on-demand data retrieval for full dataset export
- Formats data consistently for CSV structure
- Creates downloadable file using Blob API
- Handles loading states and prevents multiple simultaneous downloads
LitigationModal Component
Component Overview
This modal presents detailed case information for a specific entity with tabbed navigation and case filtering capabilities.
Key Technical Elements
1. Tab Navigation
- Provides three views: All, Tribunal, and Court Cases
- Each tab filters the litigation data appropriately
- Maintains consistent styling with active tab highlighting
2. Case Filtering
- Allows filtering by case status (All, PENDING, DISPOSED)
- Implements custom filtering logic based on selection
- Handles empty or null data gracefully
3. Case Display Logic
- Renders individual case cards with formatted information
- Displays different case numbers based on forum type
- Shows tribunal appeal numbers or CNR numbers as appropriate
- Includes color-coded status indicators (yellow for pending, blue for disposed)
4. Document Links
- Detects and displays document links when available
- Renders file icons for case orders
- Opens documents in new tabs when clicked
5. Loading States
- Displays appropriate loading indicators during data fetching
- Maintains consistent UI during state transitions
Component Interaction
The components interact through these mechanisms:
- The main component passes entity data and case information to the modal
- The modal presents detailed case records with appropriate filtering
- When closed, focus returns to the main table view
These components effectively manage legal risk data with appropriate visualizations, search capabilities, and case details, maintaining a consistent user experience throughout.
5. PEPMentions and Modal Components
These components work together to display Politically Exposed Person (PEP) mentions for corporate entities, providing both a summary table view and detailed modal analysis.
PEPMentions Component
Component Overview
The PEPMentions component displays corporate entities with PEP associations, showing summary counts in a tabular format with visual risk indicators and detailed modal views for individual entities.
Key Technical Elements
1. State Management
- Uses a multi-layered approach combining local state and global Jotai atoms
- Implements conditional data fetching based on active tab visibility
- Uses useDeferredValue for optimized search performance
- Manages modal state with useDisclosure from Mantine hooks
2. Data Fetching
- Retrieves data using multiple GraphQL queries:
- GetOverallPepMentionsDataQuery: Main table data with pagination
- useSearchPepMentions: Detailed PEP data for the modal view
- GetCumulativePepQuery: Summary statistics for dashboard cards
- GetAllEntitiesCountQuery: Total entity count for comparison metrics
3. Visual Risk Indicators
- Implements red dot indicators for entities with more than 5 PEP mentions
- Uses Grid component for structured layout of indicators and counts
- Ensures proper alignment with right-justified text for numeric values
4. CSV Export Logic
- Uses on-demand data fetching for full dataset export
- Implements proper type safety with TypeScript interfaces
- Creates and triggers download using Blob API
- Manages loading states and prevents multiple simultaneous downloads
PEPModal Component
Component Overview
The PEPModal presents detailed information about politically exposed persons associated with a particular entity, displaying relationships and evidence links.
Key Technical Elements
1. Data Structure
- Handles complex nested data with directors and their PEP matches
- Processes links to evidence documents
- Organizes information hierarchically for clear presentation
2. UI Components
- Displays entity name prominently with styled header
- Shows director information with PEP tier classification
- Includes external links to source documents as anchors
- Implements appropriate loading states during data fetching
3. Layout Management
- Uses card components for individual PEP matches
- Organizes director information with hierarchical text styles
- Handles multiple matches per director with nested mapping
Component Interaction
The components work together through these key mechanisms:
- The main component selects and passes entity data to the modal
- The modal displays PEP associations for the selected entity
- The user can navigate back to the main view to select different entities
Technical Considerations
- Both components implement proper loading states during data fetching
- The table implements fixed height scrolling for performance with large datasets
- The components handle missing or empty data gracefully
- Visual risk indicators highlight entities requiring additional scrutiny
- Export functionality provides data in standard CSV format for offline analysis
This implementation effectively manages and presents politically exposed person associations, an important component in financial compliance and risk assessment systems.
6. AdverseMedia and Modal Components
These components work together to display adverse media mentions for corporate entities, showing potential reputational risks in a tabular format with detailed modal views.
AdverseMedia Component
Component Overview
The AdverseMedia component presents news and media mentions that may negatively impact a company's reputation. It features summary statistics, a searchable data table with risk indicators, and detailed modal views.
Key Technical Elements
1. State Management
- Uses a combination of local React state and global Jotai atoms
- Implements conditional data fetching based on tab visibility
- Uses useDeferredValue for optimized search performance
- Tracks selected entity data for modal context
2. Data Retrieval
- Fetches data using custom GraphQL queries:
- GetAdverseMediaCountQuery: Summary statistics
- GetOverallAdverseMediaDataQuery: Main table data
- useSearchAdverseMedia: Detailed view data for modal
- Implements conditional data loading with pause parameter
3. Media Category Processing
- Implements complex category filtering logic in the table view:
- Prioritizes specific important categories from a predefined list
- Limits displayed categories to prevent overflow
- Handles null values with appropriate fallbacks
4. Visual Risk Indicators
- Displays red dot indicators for entities with more than 5 adverse media hits
- Uses Grid component for consistent layout of numbers and indicators
AdverseMediaModal Component
Component Overview
This modal component presents detailed news articles and media mentions associated with a specific entity, focusing on potentially negative information.
Key Technical Elements
1. Data Display
- Shows article titles, publication dates, and descriptions
- Handles missing data gracefully with appropriate fallbacks
- Includes links to original sources when available
- Implements proper scrolling with fixed height container
2. Content Formatting
- Limits text length for readability (uses first 200 characters when needed)
- Formats dates and text with consistent styling
- Provides clear empty state message when no data is available
3. UI Composition
- Uses Card components for individual media mentions
- Implements appropriate spacing and typography
- Provides external links to source articles
Component Interaction
The components work together through these mechanisms:
- The main component passes entity information and adverse media data to the modal
- The modal displays article details when triggered by action button
- Focus returns to the main table view after modal close
Technical Considerations
- Both components implement proper loading states during data fetching
- The table view uses fixed height with scrolling for performance
- The modal view implements scrolling with maximum height to handle varying content lengths
- Visual risk indicators highlight entities requiring additional scrutiny
- CSV export preserves categories and hit counts for offline analysis
This implementation provides an effective way to monitor and analyze potentially negative media coverage that could impact corporate reputation or indicate underlying financial or operational issues.
7. EPFO Compliance Dashboard:
The EPFO Compliance Dashboard is a React-based frontend module that displays Employee Provident Fund compliance data for various entities. The application enables users to view compliance metrics, search for specific entities, analyze workforce trends, and export data for further analysis. The dashboard presents key statistics in summary cards and provides detailed entity-level information in an interactive table with sorting, filtering, and pagination capabilities.
Key Components
DataSetsDashboard
A tab-based dashboard displaying different dataset views.
| Prop | Type | Description |
|---|---|---|
| currentTab | string | Represents the currently active tab. |
| GetUpdatedDate | string | Displays the last updated date of the selected dataset. |
<DataSetsDashboard />
GSTCompliance, EpfoCompliance, AnnualTurnover, MCACarges, CIBILData, Litigations, AdverseMedia, PEPMentions
Each component represents a different dataset displayed under corresponding tabs.
| Component | Prop | Type | Description |
|---|---|---|---|
| GSTCompliance | currentTab | string | Identifies the selected dataset. |
| GSTCompliance | GetUpdatedDate | string | Last updated date fetched from API. |
Example:
<GSTCompliance currentTab="gstCompliance" GetUpdatedDate="2024-03-10" />
EPFO Component:
| Prop | Type | Description |
|---|---|---|
| currentTab | string | Determines if this component should be active and fetch data |
| GetUpdatedDate | string | Last updated date for the displayed data |
Example:
<EpfoCompliance currentTab="epfoCompliance" GetUpdatedDate="2025-03-15" />
API Integration
Endpoints:
- GetUpdatedDateQuery({ type: dateType })
- Fetches the last updated date for the selected dataset.
- The type is derived from the activeTab state.
AnnualTurnover Component
This code represents the core business logic for the AnnualTurnover component. Let me walk you through exactly what each section does:
State Management
const [pagination, setPagination] = useAtom(paginationAtomAnnual);
const [searchTerm, setSearchTerm] = useState('')
const deferredValue = useDeferredValue(searchTerm)
- pagination: Global state for controlling what page is shown and how many items per page
- searchTerm: Local state to track what the user types in the search box
- deferredValue: Performance optimization that delays processing of search input to prevent UI lag
Conditional Data Fetching
const [shouldFetchData, setShouldFetchData] = useState(false);
useEffect(() => {
if (currentTab === 'annualTurnover') {
setShouldFetchData(true);
} else {
setShouldFetchData(false);
}
}, [currentTab]);
- Only fetches data when this tab is active (prevents unnecessary API calls)
- Tracks the active state with shouldFetchData boolean
Data Retrieval
const { TurnoverPositiveNegativeEntities } = TurnoverPositiveNegativeEntitiesQuery({
yearRange: '2022-2023',
pause: !shouldFetchData
});
const { OverallTurnOver, isFetchingOverallTurnOver } = OverallTurnOverQuery({
...pagination,
entityName: deferredValue,
pause: !shouldFetchData
});
- Fetches summary statistics (positive/negative counts)
- Fetches main table data with pagination and search filtering
- Both queries are paused when the tab is inactive
Data Transformation
useEffect(() => {
const transformed = OverallTurnOver?.compliances?.map(item => {
return {
cin: item.meta.cin,
name: item.meta.entityName,
turnover_2020_21: item.data[0]?.turnOverData[0]?.count || 0,
turnover_2021_22: item.data[1]?.turnOverData[0]?.count || 0,
turnover_2022_23: item.data[2]?.turnOverData[0]?.count || 0
}
});
setTransformedData(transformed || []);
}, [OverallTurnOver?.compliances, searchTerm]);
- Converts the API response into a flat structure for easier rendering
- Uses optional chaining and fallbacks to handle missing data
- Re-processes when either the data source or search term changes
Row Click Handler
const navigate = useNavigate();
const [, setSelectedRow] = useAtom(selectedRowAtom)
const handleRowClick = (cin: string) => {
navigate(`/data-terminal/entity/${cin}`);
setSelectedRow(cin);
};
- When a row is clicked, it:
- Updates global state with the selected company identifier
- Navigates to a detailed view for that company
Table Row Rendering
The rows variable maps the transformed data into React components:
- Each row shows company name with icons
- Displays three years of turnover data
- Adds up/down arrows to visually indicate growth/decline
- Formats numbers with Indian locale (e.g., "1,00,000")
- Shows "N/A" for missing data
CSV Export Logic
const handleCsvDownload = () => {
if (isDownloading) return;
setShouldFetchCsvData(true);
setIsDownloading(true);
};
useEffect(() => {
if (shouldFetchCsvData && csvData && !isLoadingCsv) {
setShouldFetchCsvData(false); // Stop fetching
if (csvData.compliances && csvData.compliances.length > 0) {
const processedData: AnnualTurnoverProps[] = csvData.compliances.map((element) => ({
cin: element?.meta?.cin || '',
name: element?.meta?.entityName || '',
turnover_2020_21: element?.data[0]?.turnOverData[0]?.count || 0,
turnover_2021_22: element?.data[1]?.turnOverData[0]?.count || 0,
turnover_2022_23: element?.data[2]?.turnOverData[0]?.count || 0
}));
setCsvDataFunc(processedData); // Store processed data
const csvDownloader = document.createElement('a');
const blob = new Blob(
[
[
columns.map((col) => col.displayName).join(','),
...processedData.map((row) =>
columns.map((col) => row[col.id as keyof AnnualTurnoverProps]).join(',')
),
].join('\n'),
],
{ type: 'text/csv' }
);
const url = URL.createObjectURL(blob);
csvDownloader.href = url;
csvDownloader.download = `Annual-Turnover-${new Date()
.toISOString()
.split('T')[0]}.csv`;
csvDownloader.click();
URL.revokeObjectURL(url); // Clean up
}
// Reset download state after handling the file
setIsDownloading(false);
}
}, [shouldFetchCsvData, csvData, isLoadingCsv]);
- Creates CSV data with headers and formatted rows
- Generates a downloadable file using Blob API
- Programmatically triggers the download
- Cleans up resources and resets state after completion
CIBILData Component
State Management
const [opened, { open, close }] = useDisclosure(false);
const [pagination, setPagination] = useAtom(paginationAtomCibil);
const [searchQuery, setSearchQuery] = useState('');
const [activeTab, setActiveTab] = useState<string | null>('npaDefault');
const deferredValue = useDeferredValue(searchQuery)
const [cibil, setCibil] = useState<any>([]);
- opened + open/close: Controls the detail modal visibility
- pagination: Global state for table pagination
- searchQuery/deferredValue: Manages search input with performance optimization
- activeTab: Controls which tab is active in the detail modal
- cibil: Holds the transformed data ready for display
Conditional Data Fetching
const [shouldFetchData, setShouldFetchData] = useState(false);
useEffect(() => {
if (currentTab === 'cibil') {
setShouldFetchData(true);
} else {
setShouldFetchData(false);
}
}, [currentTab]);
- Only loads data when this tab is visible to the user
- Prevents unnecessary API calls when on other tabs
Data Retrieval & Transformation
const { OverallEntitiesCibilDataCount } = GetOverallEntitiesCibilDataCountQuery({ pause: !shouldFetchData });
const { OverallEntitiesCibilDefaults, isFetchingOverallEntitiesCibilDefaults } = OverallEntitiesCibilDefaultsQuery({
...pagination,
entityName: deferredValue,
pause: !shouldFetchData
});
useEffect(() => {
const cibilData = OverallEntitiesCibilDefaults?.entities?.map((element) => {
const npaCount = element?.data?.filter(item =>
item?.npa_amount !== null)?.length;
// Count willful defaults (excluding null values)
const willfulCount = element?.data?.filter(item =>
item.willful_amount !== null
).length;
return {
cin: element?.meta?.cin,
name: element?.meta?.entityName,
turnOver: element?.meta?.turnOver,
npaHits: npaCount,
wilfulDefaultHits: willfulCount,
originalData: element,
}
});
setCibil(cibilData || []);
}, [OverallEntitiesCibilDefaults?.entities]);
- Fetches summary statistics and detailed entity data
- Processes raw data by calculating:
- NPA (Non-Performing Asset) hit counts
- Wilful Default hit counts
- Shapes data into a flat, display-ready structure
- Preserves original data for use in the modal
Row Click & Modal Management
const [selectedEntity, setSelectedEntity] = useState<CibilEntity | null>(null);
const navigate = useNavigate();
const [, setSelectedRow] = useAtom(selectedRowAtom)
const handleRowClick = (cin: string) => {
navigate(`/data-terminal/entity/${cin}`);
setSelectedRow(cin);
};
- Stores currently selected entity for detail view
- Navigates to entity details page when row is clicked
- Updates global selected row state
Table Row Rendering
The rows variable maps transformed data into table rows with:
- Entity name with icons
- Formatted turnover value
- NPA hit count with visual indicator (red dot) if over 5 hits
- Wilful Default hit count with visual indicator if over 5 hits
- Action button that opens a detail modal (stops event propagation to prevent row click)
CSV Export Implementation
const handleCsvDownload = () => {
if (isDownloading) return; // Prevent multiple triggers while downloading
setShouldFetchCsvData(true); // Trigger data fetch
setIsDownloading(true); // Start the download process
};
useEffect(() => {
if (shouldFetchCsvData && csvData && !isLoadingCsv) {
// Process download...
}
}, [shouldFetchCsvData, csvData, isLoadingCsv]);
- Initiates CSV export with safeguards against multiple clicks
- Fetches complete dataset (not just current page)
- Processes data with the same transformation logic
- Creates downloadable CSV file using Blob API
- Handles cleanup to prevent memory leaks
MCACharges Component
State Management
const [opened, { open, close }] = useDisclosure(false);
const [pagination, setPagination] = useAtom(paginationAtomMca);
const [searchTerm, setSearchTerm] = useState('')
const deferredValue = useDeferredValue(searchTerm)
- opened/open/close: Controls the detail modal visibility
- pagination: Global state for table pagination (using Jotai)
- searchTerm/deferredValue: Search input with performance optimization
Conditional Data Fetching
const [shouldFetchData, setShouldFetchData] = useState(false);
useEffect(() => {
if (currentTab === 'mcaCharges') {
setShouldFetchData(true);
} else {
setShouldFetchData(false);
}
}, [currentTab]);
- Only loads data when this tab is active
- Prevents unnecessary API calls
Data Loading and Modal Management
const { OverallMCAChargesData, isFetchingOverallMCAChargesData } = GetOverallMCAChargesDataQuery({
...pagination,
entityName: deferredValue,
pause: !shouldFetchData
});
const { GetMcaCharges } = GetMcaChargesQuery({
pause: !shouldFetchData
});
const [cin, setCin] = useState('')
const [entityName, setEntityName] = useState('')
const { charges } = useSearchCharges({ cin, pause: !shouldFetchData });
const { directors } = useSearchDirectors({ cin, pause: !shouldFetchData });
- Loads main table data with pagination and filtering
- Retrieves summary statistics
- Manages state for the selected entity (for modal)
- Loads detailed charges and directors data for the modal view
Navigation and Modal Handlers
const handleRowClick = (cin: string, name: string) => {
setCin(cin)
setEntityName(name)
open()
}
const navigate = useNavigate();
const [, setSelectedRow] = useAtom(selectedRowAtom)
const handleRowClickNav = (cin: string) => {
navigate(`/data-terminal/entity/${cin}`);
setSelectedRow(cin);
};
- handleRowClick: Opens the modal with charge details
- handleRowClickNav: Navigates to entity details page
Table Row Rendering
- Renders each entity as a row with formatted data
- Shows financial values with Indian number formatting
- Converts charge amounts from raw values to lakhs (dividing by 100,000)
- Includes an action button that stops event propagation to open modal
CSV Export Implementation
const handleCsvDownload = () => {
if (isDownloading) return;
setShouldFetchCsvData(true);
setIsDownloading(true);
};
- Initiates download process when button is clicked
- Prevents multiple simultaneous downloads
- Fetches all data (not just current page)
- Processes data into CSV format
- Creates and triggers download using the Blob API
- Properly cleans up to prevent memory leaks
Litigations Component - Logic Breakdown
This snippet represents the core business logic of the Litigations component, a sophisticated data display system that shows legal case information for corporate entities. Here's a technical analysis:
State Management Architecture
const [opened, { open, close }] = useDisclosure(false);
const [pagination, setPagination] = useAtom(paginationAtomLitigation);
const [cin, setCin] = useState('')
const [entityName, setEntityName] = useState('')
const [searchTerm, setSearchTerm] = useState('')
const [shouldFetchData, setShouldFetchData] = useState(false);
const deferredValue = useDeferredValue(searchTerm)
This implements a multi-layered state management approach:
- Modal visibility controlled via useDisclosure hook
- Pagination persisted with Jotai's global atom store
- Context-specific entity data in local component state
- Search optimization with React 18's useDeferredValue for debounced input.
Conditional Data Fetching
useEffect(() => {
if (currentTab === 'litigations') {
setShouldFetchData(true);
} else {
setShouldFetchData(false);
}
}, [currentTab]);
const {
SearchLitigationCasesByName,
isFetchingSearchLitigationCasesByName,
} = SearchLitigationCasesByNameQuery({
...pagination,
name: deferredValue,
pause: !shouldFetchData
});
const { litigations, isFetchingLitigations } = useSearchLitigations({
cin,
pause: !shouldFetchData
});
- Uses a tab-based conditional fetching strategy
- Prevents unnecessary API calls when component is not visible
- Leverages the pause parameter to stop GraphQL queries
- Separates main table data and detailed modal data queries
- handleRowClick: Opens the modal with detailed case information
- handleRowClickNav: Navigates to a full entity details page
- Uses event propagation control in the action button to prevent navigation when viewing details
- Displays formatted financial values with Indian locale
- Implements visual risk indicators (red dots) for high case counts
- Uses Grid component for structured layout of indicators
- Prevents event bubbling in action button via e.stopPropagation()
PEPMentions Component - Logic Breakdown
This code represents the core business logic for the PEPMentions component, which tracks and displays politically exposed person (PEP) mentions associated with corporate entities. Here's a detailed explanation:
State Management
const [opened, { open, close }] = useDisclosure(false);
const [pagination, setPagination] = useAtom(paginationAtomPep);
const [searchTerm, setSearchTerm] = useState('')
const deferredValue = useDeferredValue(searchTerm)
const [cin, setCinData] = useState('')
const [entityName, setEntityName] = useState('')
const [shouldFetchData, setShouldFetchData] = useState(false);
- Modal visibility control with Mantine's useDisclosure hook
- Global pagination state using Jotai's useAtom
- Search term state with performance optimization via useDeferredValue
- Selected entity tracking for modal context
**Conditional Data Fetching**
const [shouldFetchData, setShouldFetchData] = useState(false);
useEffect(() => {
if (currentTab === 'pepMentions') {
setShouldFetchData(true);
} else {
setShouldFetchData(false);
}
}, [currentTab]);
- Only fetches data when the PEP Mentions tab is active
- Prevents unnecessary API calls when component is not visible
**Data Retrieval**
**const**** { ****GetAllEntities**** } ****=**** ****GetAllEntitiesCountQuery****({**
** ****pageNo:**** ****1****,**
** ****pageSize:**** ****10****,**
** ****name:**** ****""****,**
** ****pause:**** ****!****shouldFetchData**
**});**
** ****const**** { ****GetCumulativePep**** } ****=**** ****GetCumulativePepQuery****({**
** ****pause:**** ****!****shouldFetchData**
**});**
** ****const**** { ****OverallPepMentionsData****, ****isFetchingOverallPepMentionsData**** } ****=**** ****GetOverallPepMentionsDataQuery****({ ****...****pagination****, ****entityName:**** ****deferredValue****, ****pause:**** ****!****shouldFetchData**** })**
** ****const**** { ****pepMentions****, ****isFetchingPepMentions**** } ****=**** ****useSearchPepMentions****({ ****cin****, ****pause:**** ****!****shouldFetchData**** })**
Multiple data sources are queried with appropriate controls:
- Total entity count (for comparison metrics)
- Cumulative PEP statistics (for summary cards)
- Main table data with pagination and search
- Detailed PEP mentions for the selected entity
**Table Row Rendering:**
Renders entity rows with formatted data
Uses visual indicators (red dots) for high-risk entities
Formats numbers with Indian locale
Prevents event bubbling for action button clicks.
**CSV Export Implementation:**
Fetches complete dataset when export is requested
Transforms data into a consistent format for CSV
Creates and triggers download via Blob API
Implements safeguards against multiple simultaneous exports
Properly cleans up resources after download
# 6. AdverseMedia Component - Logic Breakdown
This code represents the core business logic for the AdverseMedia component, which tracks and displays negative news mentions for corporate entities. Here's a detailed explanation of its functionality:
## **State Management**
const [opened, { open, close }] = useDisclosure(false);
const [pagination, setPagination] = useAtom(paginationAtomAdverse);
const [cin, setCinData] = useState('')
const [entityName, setEntityName] = useState('')
const [searchTerm, setSearchTerm] = useState('')
const deferredValue = useDeferredValue(searchTerm)
- Modal visibility control with Mantine's useDisclosure hook
- Pagination state management with Jotai's global atom store
- Entity identifier and name tracking for modal context
- Search optimization with React 18's useDeferredValue.
**Conditional Data Fetching**
const [shouldFetchData, setShouldFetchData] = useState(false);
useEffect(() => {
if (currentTab === 'adverseMedia') {
setShouldFetchData(true);
} else {
setShouldFetchData(false);
}
}, [currentTab]);
- Only loads data when the Adverse Media tab is active
- Prevents unnecessary API calls when component is not visible
**Data Retrieval:**
** ****const**** { ****GetAdverseMedia**** } ****=**** ****GetAdverseMediaCountQuery****({**
** ****pause:**** ****!****shouldFetchData**
**});**
** ****const**** { ****OverallAdverseMediaData****, ****isFetchingOverallAdverseMediaData**** } ****=**** ****GetOverallAdverseMediaDataQuery****({**
** ****...****pagination****,**
** ****entityName:**** ****deferredValue****,**
** ****pause:**** ****!****shouldFetchData**
**});**
** ****const**** { ****adverseMedia**** } ****=**** ****useSearchAdverseMedia****({ ****cin****, ****pause:**** ****!****shouldFetchData**** });**
- Fetches summary statistics for dashboard cards
- Retrieves paginated table data with search filtering
- Loads detailed media mentions for the selected entity
## **Table Row Rendering**
The most sophisticated part of this component is the table row rendering, particularly the media category display:
- Complex category prioritization logic using IIFE pattern
- Limiting displayed categories to prevent overflow
- Visual risk indicators for entities with many mentions
- Event propagation control for action buttons
**CSV Export Implementation**
const handleCsvDownload = () => {
if (isDownloading) return; // Prevent multiple triggers while downloading
setShouldFetchCsvData(true); // Trigger data fetch
setIsDownloading(true); // Start the download process
};
- Fetches full dataset when export is requested
- Processes data with type conversion for consistency
- Creates downloadable CSV using Blob API
- Implements safeguards against multiple downloads
- Properly cleans up resources with URL revocation
This component effectively manages adverse media data with sophisticated filtering, risk indication, and export capabilities - all crucial for corporate risk assessment and due diligence processes.
**8. EPFO Compliences**
### **Endpoints:**
const { GetOverallEPFOComplianceData, GetOverallEPFOComplianceDataFetching } = GetOverallEPFOComplianceDataQuery({ ...pagination, entityName: deferredValue, pause: !shouldFetchData });
const { GetCumulativeEpfo } = GetCumulativeEpfoQuery({
pause: !shouldFetchData
});
- **GetOverallEPFOComplianceData**: Fetches paginated entity compliance data
- Parameters: pageNo, pageSize, entityName (search filter)
- Implementation: GetOverallEPFOComplianceDataQuery
- **GetCumulativeEpfo**: Retrieves summary statistics for the dashboard cards
- Implementation: GetCumulativeEpfoQuery
### **API Hooks:**
- **GetOverallEPFOComplianceDataQuery**: Custom hook that manages fetching and state for the compliance data table
- **GetCumulativeEpfoQuery**: Custom hook that manages fetching and state for the summary statistics
## **4. State Management**
### **Local State:**
- **searchTerm**: Controls the entity name search input
- **shouldFetchData**: Determines if data fetching should occur based on active tab
- **shouldFetchCsvData**: Manages the CSV download process
- **isDownloading**: Tracks download status for UI feedback
### **Global State (Jotai):**
- **paginationAtomEPFO**: Manages pagination state (pageNo, pageSize)
- **selectedRowAtom**: Tracks selected entity when navigating to details.
## **5. Deployment \
****Tools:** Docker,nginx.conf. \
*"Each MFE has its own Dockerfile and NGINX configuration, so they need to be built and deployed separately."*
FROM nginx:alpine
Remove the default Nginx configuration file
RUN rm /etc/nginx/conf.d/default.conf
Copy the custom Nginx configuration file
COPY nginx.conf /etc/nginx/conf.d
Copy the build output from the previous stage
COPY dist /usr/share/nginx/html
Expose port 80
EXPOSE 80
Start Nginx
CMD ["nginx", "-g", "daemon off;"]
We're using **Google Cloud Platform (GCP)** to deploy the **Risk Terminal Project** in two environments: \
✅ **Dev (Development) \
** ✅ **Staging**
Each **Micro Frontend (MFE)** has its **own Dockerfile and Nginx config**, meaning they need to be deployed separately.
### **2. Commands**
#### ✅ Development Environment (Dev)
- pnpm build
- docker build --no-cache -t risk-terminal-fe/risk-datasets:latest .
- docker tag risk-terminal-fe/risk-datasets:latest us-west1-docker.pkg.dev/test-genai-422809/risk-terminal-fe/risk-terminal-fe/risk-datasets:latest
- docker push us-west1-docker.pkg.dev/test-genai-422809/risk-terminal-fe/risk-terminal-fe/risk-datasets:latest
overview:
- **pnpm build** → Builds the project.
- **docker build** → Creates a Docker image from your project.
- **docker tag** → Tags the image for GCP Artifact Registry.
- **docker push** → Pushes the image to Artifact Registry.
### **3. What is Artifact Registry?**
📌 **Artifact Registry** is GCP’s container registry where you store Docker images.
- Instead of using DockerHub, you push images to **us-west1-docker.pkg.dev/test-genai-422809/risk-terminal-fe/
- Each environment (**Dev**, **Staging**) has its own **separate image repository**.
### **4. What is Cloud Run?**
📌 **Cloud Run** is a serverless platform to run Docker containers.
- After pushing the image to **Artifact Registry**, you deploy it to **Cloud Run**.
- Cloud Run automatically **scales** your container based on traffic.
### **5. What is Cloud DNS?**
📌 **Cloud DNS** helps map domain names (e.g.,risk-terminal.example.com) to your Cloud Run service.
- Instead of accessing your app via **long Cloud Run URLs**, you set up a **custom domain**.
- Steps:
- **Reserve a domain** in Google Domains or another provider.
- **Create a DNS Zone** in Cloud DNS.
- **Add an A or CNAME record** pointing to your Cloud Run service.
- **Verify and apply SSL (if needed)**.
### **6. Deployment Flow**
1️⃣ **Build the MFE using pnpm \
** 2️⃣ **Create a Docker image and push it to Artifact Registry \
** 3️⃣ **Deploy the image to Cloud Run \
** 4️⃣ **Map a custom domain using Cloud DNS**