Skip to content

Conversation

@Aditya-gam
Copy link
Contributor

@Aditya-gam Aditya-gam commented Dec 19, 2025

Description

Implements a new Material Usage vs Cost Correlation chart component for the BM Dashboard. The chart visualizes material quantity used vs total material cost per project using a combined bar/line chart (Recharts ComposedChart). Features include filtering (projects, material types, date ranges), dark mode support, responsive design, and error handling. Integrated into the Weekly Project Summary → Material Consumption section.

IssueDescription1 IssueDescription2 ExpectedGraph

Related PRs (if any):

  • This PR is the Frontend PR for the backend PR #1957.

Main changes explained:

Created Files:

  • src/constants/bmdashboard/materialCostCorrelationConstants.js

    • Redux action type constants
  • src/reducers/bmdashboard/materialCostCorrelationReducer.js

    • Redux reducer for loading, data, error, and filter state management
  • src/actions/bmdashboard/materialCostCorrelationActions.js

    • Thunk action with client-side validation (date ranges, ObjectId format)
    • Error handling (401→login redirect after 2s, 403→permission error, network→retry button)
    • Query params: projectId (comma-separated), materialType (comma-separated), startDate (YYYY-MM-DD), endDate (YYYY-MM-DD)
    • Toast notifications for validation errors and API errors
  • src/components/BMDashboard/MaterialCostCorrelation/MaterialCostCorrelationChart.jsx

    • Main chart component (Recharts ComposedChart with dual Y-axes)
    • Bar chart: totalCostK (blue #0088FE) on left Y-axis, Line chart: quantityUsed (orange #FF8042) on right Y-axis
    • X-axis: project names rotated -45° with truncation (>15 chars)
    • Responsive margins/heights: mobile (450px) to desktop (600px)
    • Loading, error, and no-data states with custom tooltip (project name, cost in dollars, quantity)
  • src/components/BMDashboard/MaterialCostCorrelation/FilterPanel.jsx

    • Multi-select filters (projects, material types) with react-select
    • Fetches from Redux state: state.bmProjects and state.bmInvTypes.list
    • Date range picker with preset buttons: Last Week, Last Month, Last 3 Months, All Time
    • "All Projects/Materials" options and Reset button clear filters (empty array = all items)
  • src/components/BMDashboard/MaterialCostCorrelation/MaterialCostCorrelationChart.module.css

  • src/components/BMDashboard/MaterialCostCorrelation/FilterPanel.module.css

    • CSS modules with dark mode support via CSS custom properties
    • Responsive breakpoints, animations, and styling for React-Select components in both themes
  • src/components/BMDashboard/MaterialCostCorrelation/index.jsx

    • Barrel export

Modified Files:

  • src/utils/URL.js - Added BM_MATERIAL_COST_CORRELATION endpoint constant
  • src/reducers/index.js - Added materialCostCorrelation reducer to root reducer
  • src/components/BMDashboard/WeeklyProjectSummary/WeeklyProjectSummary.jsx - Integrated chart into Material Consumption section (index 0)

Key Implementation Details:

  • API: /api/bm/materials/cost-correlation (GET) - Response: { meta, data: [{ projectId, projectName, totals: { totalCostK, quantityUsed } }] }. Cost in USD, totalCostK pre-calculated. Empty filter arrays = fetch all items.
  • Chart: Recharts ComposedChart - Bar (blue #0088FE, cost ×1000$) + Line (orange #FF8042, quantity) with dual Y-axes. X-axis: projects rotated -45°, truncated >15 chars. Data transformation via useMemo.
  • State: Redux slice materialCostCorrelation manages loading, data, error, filters. Filter changes trigger auto-refetch via useEffect.
  • Responsive: Dynamic margins/heights: mobile ≤480px (40px/70px, 450px) to desktop >1024px (60px/80px, 600px). Window resize listener with cleanup.
  • Errors: Client-side validation (date range, ObjectId format). Categorized errors: 401→login redirect (2s), 403→permission, network→retry, validation→toast. Logger service replaces console statements.
  • Dark Mode: CSS custom properties with conditional classes based on state.theme.darkMode

How to test:

  1. Checkout branch: Aditya-feat/material-cost-correlation-chart
  2. Reinstall dependencies and clear cache: rm -rf node_modules && yarn cache clean
  3. Run yarn install and start the app: yarn start:local
  4. Clear browser cache/site data
  5. Log in as an admin user
  6. Navigate to BM Dashboard → Weekly Project Summary → Material Consumption section
  7. Test filters: Projects/Material Types (multi-select with "All" options), Date Range (preset buttons + manual), Reset button
  8. Test chart: Hover for tooltip (project name, cost in dollars, quantity), verify Y-axis labels and X-axis project names (-45° rotation, truncated >15 chars)
  9. Test responsive: Resize browser (mobile ≤480px, tablet ≤768px, desktop >1024px) - verify margins/heights adjust
  10. Test dark mode: Toggle theme - verify chart, filters, tooltips adapt correctly
  11. Test error states: Network error (retry button), validation error (date range toast), no data state, authentication (401 redirect after 2s)
  12. Verify integration: Chart appears as the first card (index 0) in the Material Consumption section

Screenshots:

  1. Light Mode:
LightModeChart
  1. Dark Mode:
DarkModeChart
  1. Test Video:
TestVideo.mov

Notes:

  • Performance: Uses useMemo for data transformation, API calls triggered on filter changes, and window resize listener cleaned up. Consider pagination for >100 projects.
  • Validation: Client-side (date range, ObjectId format), server-side handled by backend API. Invalid inputs show toast notifications.
  • Logging: Uses logger service with [MaterialCostCorrelation] prefix (replaces console statements)

- Create materialCostCorrelationConstants.js with Redux action type constants
- Add BM_MATERIAL_COST_CORRELATION endpoint to URL utilities
- Define constants for fetch requests, filter updates, and reset actions
- Create materialCostCorrelationConstants.js with Redux action type constants
- Add BM_MATERIAL_COST_CORRELATION endpoint to URL utilities
- Define constants for fetch requests, filter updates, and reset actions
- Create materialCostCorrelationActions.js with action creators and thunk
- Implement fetchMaterialCostCorrelation thunk with query parameter handling
- Add date formatting helper for YYYY-MM-DD format
- Create materialCostCorrelationReducer with initial state and switch cases
- Register reducer in root reducer as materialCostCorrelation
- Include error handling with toast notifications
- Create main MaterialCostCorrelationChart component with scatter and bar chart views
- Implement FilterPanel with project, material type, and date range filters
- Add ChartTypeToggle component for switching between chart types
- Transform API data for Recharts consumption with proper data flattening
- Implement custom tooltip with project, material, cost, and quantity details
- Add color mapping for material types in scatter chart
- Include loading, error, and empty state handling
- Create barrel export for component directory
…st correlation

- Implement CSS variables for theming with light and dark mode support
- Style main chart component with responsive layout and proper spacing
- Add comprehensive FilterPanel styling with react-select and datepicker support
- Style ChartTypeToggle with active states and transitions
- Add responsive media queries for tablet and mobile devices
- Include focus-visible states for accessibility compliance
- Style loading, error, and empty states with appropriate colors
- Add proper tooltip and legend styling for both chart types
…ummary

- Add MaterialCostCorrelationChart import to WeeklyProjectSummary component
- Replace placeholder content at index 0 in Material Consumption section
- Chart now appears as first card in Material Consumption section
- Maintains existing card styling with weeklyProjectSummaryCard and normalCard classes
- Add comprehensive error handling in actions with validation, network, auth, and permission error detection
- Implement date range and ObjectId validation before API calls
- Add detailed console logging for debugging with timestamps and context
- Enhance error display in component with error types, icons, and contextual hints
- Add retry functionality for recoverable errors
- Handle malformed responses with graceful fallbacks
- Add optional chaining and fallback values for data transformation
- Implement sessionStorage retry mechanism for authentication errors
- Add reset filters button for empty state
- Improve toast notification configuration with appropriate auto-close settings
- Remove all console.log, console.error, and console.warn statements
- Replace with logger.logError for error logging
- Replace with logger.logInfo for validation warnings
- Remove debug console.log statements that are not needed in production
- Ensure all logging goes through the logger service for proper error tracking
- Remove unused imports (BMError) and unused variables (meta, containerWidth)
- Remove unused resize handler that was not being utilized
- Add JSDoc comments to document component props and functionality
- Add documentation for CustomTooltip, MaterialCostCorrelationChart, FilterPanel, and ChartTypeToggle components
- Improve code maintainability by documenting complex logic sections
- Replace dual chart types (scatter and bar) with single ComposedChart
- Add Line component for quantity data with dual Y-axes
- Remove scatter chart functionality and toggle component
- Update tooltip to show both cost and quantity values
- Remove unused state, data transformations, and imports
- Update chart information section to reflect combined visualization
- Configure left Y-axis for cost and right Y-axis for quantity
- Delete ChartTypeToggle.jsx and ChartTypeToggle.module.css
- No longer needed after converting to single combined chart
- Chart type toggle functionality was removed in favor of combined bar+line visualization
- Remove chart information legend section from bottom of chart
- Increase chart margins to accommodate axis labels (left: 80, right: 80, bottom: 100)
- Add explicit width to Y-axes for proper label spacing
- Truncate long project names on X-axis to prevent overflow
- Remove X-axis label and adjust tick formatting
- Set consistent font sizes for axis ticks (12px)
- Add offsets to Y-axis labels for better positioning
- Reduce container padding from 20px to 12px
- Reduce header margin-bottom from 24px to 12px
- Reduce chart container padding from 24px to 12px
- Reduce filter panel padding from 24px to 16px and margin-bottom from 24px to 12px
- Reduce chart margins (top: 10px, sides: 60px, bottom: 80px)
- Increase chart height from 500px to 600px to utilize freed space
- Maintains UI integrity while maximizing chart visualization area
- Add responsive padding for tablets (1024px) and mobile devices
- Reduce container padding progressively: 8px (1024px), 6px (768px), 4px (480px)
- Reduce chart container padding for smaller screens
- Reduce filter panel padding and margins for mobile devices
- Add dynamic chart margins based on screen width
- Add responsive chart height: 450px (mobile), 500px (tablet), 550px (small laptop), 600px (desktop)
- Add window resize listener to update chart margins dynamically
- Optimize spacing for iPhone XR, iPad, and other smaller screens
@netlify
Copy link

netlify bot commented Dec 19, 2025

Deploy Preview for highestgoodnetwork-dev ready!

Name Link
🔨 Latest commit 71ee921
🔍 Latest deploy log https://app.netlify.com/projects/highestgoodnetwork-dev/deploys/6945e6bebc4e7c00088bf80e
😎 Deploy Preview https://deploy-preview-4587--highestgoodnetwork-dev.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify project configuration.

Remove unnecessary if/else block where both branches executed identical toast.error calls. SonarQube issue resolved.
@sonarqubecloud
Copy link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants