Skip to content

Aditya-fix: resolve tool stoppage reason data loading error with comprehensive improvements#1903

Open
Aditya-gam wants to merge 13 commits intodevelopmentfrom
Aditya-fix/tool-stoppage-reason-improvements
Open

Aditya-fix: resolve tool stoppage reason data loading error with comprehensive improvements#1903
Aditya-gam wants to merge 13 commits intodevelopmentfrom
Aditya-fix/tool-stoppage-reason-improvements

Conversation

@Aditya-gam
Copy link
Contributor

@Aditya-gam Aditya-gam commented Nov 15, 2025

Description

This PR Fixes - BM Dashboard "Reason of Stoppage of Tools" data loading error
IssueDescription

This PR implements comprehensive improvements to the BM Dashboard 'Reason of Stoppage of Tools' feature to fix critical data loading errors and enhance overall robustness, performance, and maintainability. The implementation addresses the high-priority issue where the section fails to load data and displays "Failed to load projects. Please try again."

The changes include error tracking with Sentry integration, comprehensive input validation, database indexing for performance optimization, intelligent response caching to reduce server load, structured API responses with metadata and timing information, MongoDB connection error handling with appropriate HTTP status codes, and consistent error response formatting across all endpoints.


Related PRs (if any):


Main changes explained:

Updated Files:

src/controllers/bmdashboard/bmToolStoppageReasonController.js

  • Core Functionality:
    • Replaced console.error with Logger.logException() for Sentry integration
    • Implemented date parsing helpers: parseYmdUtc() and parseDateFlexibleUTC() supporting YYYY-MM-DD and ISO 8601 formats
    • Added buildDateFilter() helper to eliminate code duplication
    • Integrated nodeCache with 5-minute TTL for project list endpoint
    • Returns structured responses: { success, data, count, message, executionTimeMs, cached? }
    • Logs slow queries (>1000ms) to Sentry for optimization
    • Distinguishes MongoDB connection errors (503 with retry: true) from query failures (500)
  • Validation:
    • Date format and range validation (endDate >= startDate)
    • Project existence check (returns 404 for non-existent projects)
    • Note: ObjectId format validation handled by express-validator in router
  • Endpoints:
    1. GET /api/bm/projects/:id/tools-stoppage-reason?startDate&endDate - Tool stoppage data with optional date filtering
    2. GET /api/bm/tools-stoppage-reason/projects - Cached project list (5-min TTL)

src/routes/bmdashboard/bmToolStoppageReasonRouter.js

  • Validation Middleware:
    • Uses express-validator for type-safe validation
    • Validates projectId as MongoDB ObjectId
    • Validates optional date parameters (YYYY-MM-DD or ISO 8601 format)
    • Returns structured 400 errors: { success: false, errors: [...], message: "Validation failed" }

src/models/bmdashboard/buildingToolsStoppage.js

  • Schema:
    • Fields: projectId (ObjectId ref), toolName, usedForLifetime, damaged, lost, date
    • Collection: toolStoppageReason
  • Indexes:
    • Compound index: { projectId: 1, date: 1 } for efficient querying
    • Single index: { toolName: 1 } for sorting optimization

How to test:

  1. Check into current branch: Aditya-fix/tool-stoppage-reason-improvements

  2. Reinstall dependencies and clean cache using rm -rf node_modules package-lock.json && npm cache clean --force

  3. Run npm install to install dependencies, then start the backend locally (npm start or npm run dev)

  4. Test endpoints (using Postman/curl with JWT token in Authorization header):

    • Tool Stoppage Data:
      • GET /api/bm/projects/<projectId>/tools-stoppage-reason → Returns all tool stoppage data for project
      • GET /api/bm/projects/<projectId>/tools-stoppage-reason?startDate=2024-01-01&endDate=2024-12-31 → Filters by date range
      • GET /api/bm/projects/invalid-id/tools-stoppage-reason → Returns 400 validation error
      • GET /api/bm/projects/<nonExistentId>/tools-stoppage-reason → Returns 404 not found
      • GET /api/bm/projects/<projectId>/tools-stoppage-reason?startDate=2024-12-31&endDate=2024-01-01 → Returns 400 invalid date range error
    • Project List:
      • GET /api/bm/tools-stoppage-reason/projects → Returns all projects with tool stoppage data (first call: cached=false, ~120ms)
      • GET /api/bm/tools-stoppage-reason/projects → Second call within 5 minutes (cached=true, ~2-5ms)
  5. Verify:

    • Response format: { success, data, count, message, executionTimeMs, cached? }
    • Data sorted by date (ascending), then toolName (alphabetically)
    • Invalid inputs return 400 with structured error messages
    • Non-existent projects return 404
    • Empty results include a helpful message
    • Cache hit shows dramatically faster executionTimeMs
    • MongoDB connection errors return 503 with retry: true
    • executionTimeMs included in all responses (success and error)
  6. Frontend Integration (coordinate with PR #):

    • Navigate to BM Dashboard → "Reason of Stoppage of Tools"
    • Verify project dropdown populates from /projects endpoint
    • Test chart loading with date filters
    • Verify error handling and dark mode compatibility

Screenshots or videos of changes:

  • Light Mode:
LightMode
  • Dark Mode:
DarkMode
  • Test Video:
TestVideo.mov

See frontend PR for:

  • Chart component consuming structured data
  • Error message displays
  • Loading states and cache indicators

Note:

  • Response format changed from raw array to structured object.
    • Old: [{projectId, projectName}, ...]
    • New: { success, data: [{projectId, projectName}, ...], count, message, executionTimeMs, cached? }
    • Frontend must access response.data instead of response directly
  • Database Changes:
    • Compound: { projectId: 1, date: 1 } - 50-80% query performance improvement
    • Single: { toolName: 1 } - optimizes sorting

vamsikrishna1704 and others added 12 commits June 13, 2025 18:57
…ppageReasonController

- Replace console.error with Logger.logException() for Sentry integration
- Add detailed request context (projectId, dates, URL) to error logs
- Improve error messages with specific details and actionable guidance
- Enhance invalid projectId error to include actual value and format requirements
- Add transaction names to all error logs for better tracking

This provides centralized error tracking in production, generates tracking IDs
for debugging, and improves user experience with clearer error messages.
…geReasonController

- Add date format validation using parseDateFlexibleUTC helper (YYYY-MM-DD or ISO 8601)
- Add date range logical validation to ensure endDate >= startDate
- Add project existence validation to return 404 for non-existent projects
- Implement parseYmdUtc and parseDateFlexibleUTC helpers consistent with injuryCategoryController
- Replace new Date() calls with validated parsed dates to prevent silent failures

This prevents invalid queries from reaching the database, returns appropriate
HTTP status codes (400 for validation errors, 404 for missing projects),
and provides clear error messages to guide users.
- Add compound index on projectId and date for efficient querying
- Add index on toolName to optimize sorting operations
- Add sorting to aggregation pipeline: date (ascending), then toolName (alphabetically)
- Update comment to correctly reference 'tool stoppage reason data'

This improves query performance, reduces database load, ensures consistent
predictable result ordering, and enhances scalability as data grows.
- Add nodeCache utility for caching getUniqueProjectIds response
- Use 5-minute TTL (300s default) for project list cache
- Check cache before database query to reduce load
- Cache formatted results after successful database query

This significantly reduces database load especially with chart auto-refreshes,
improves response time, and enhances user experience. Slightly stale data
(max 5 minutes) is acceptable trade-off for project list.
- Fix incorrect comments in router (tools-availability -> tools-stoppage-reason)
- Add comprehensive JSDoc comments to all functions with param and return types
- Extract buildDateFilter helper function to eliminate code duplication
- Define error message constants (ERROR_MESSAGES) for consistency and maintainability
- Define cache key constants (CACHE_KEYS) for better organization
- Replace all hardcoded error strings with constants

This improves code documentation for better IDE autocomplete, makes error
messages easier to update, follows DRY principle, and enhances developer
onboarding experience.
- Return structured response format with success, data, count, and message fields
- Add executionTimeMs to all responses for performance monitoring
- Log slow queries (>1000ms) for identification and optimization
- Include cached flag in getUniqueProjectIds to indicate cache hits
- Add informative messages for empty result sets
- Include execution time in error responses and logging context
- Add express-validator middleware for query parameter validation (projectId, dates)
- Implement isMongoConnectionError helper to detect connection failures
- Return 503 Service Unavailable for MongoDB connection errors vs 500 for other errors
- Add retry flag to 503 responses to signal frontend can retry
- Include errorType in logging context for better debugging
- Add validation error responses with structured format

This improves HTTP semantics for different error types, enables appropriate
frontend retry behavior, and provides type-safe query parameter validation.
…dation

- Add success field (false) to all 400/404 error responses for consistency
- Add executionTimeMs to all validation and not-found error responses
- Remove redundant ObjectId validation from controller (already handled by express-validator in router)
- Remove unused INVALID_PROJECT_ID_FORMAT error constant
- Add clarifying comment about router-level validation

This ensures all error responses follow the same structured format:
{ success, error, executionTimeMs, retry? } regardless of error type.
@RitzzzZ2021
Copy link
Contributor

Tested APIs locally using Postman and the results are as expected. Correct data is returned when sending valid requests. The error messages are clear when requests are invalid.

GET /api/bm/projects//tools-stoppage-reason
image

GET /api/bm/projects//tools-stoppage-reason?startDate=2024-01-01&endDate=2024-12-31
image

GET /api/bm/projects/invalid-id/tools-stoppage-reason
image

GET /api/bm/projects//tools-stoppage-reason?startDate=2024-12-31&endDate=2024-01-01
image

Also, the cache greatly reducing the data fetching time.

GET /api/bm/tools-stoppage-reason/projects
first call: 28ms
image

second call: 4ms
image

Copy link

@Anusha-Gali Anusha-Gali left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi Aditya,

I have reviewed your PR locally and the backend works as per requirement.
Screenshot 2025-12-05 at 7 24 48 PM
Screenshot 2025-12-05 at 7 26 00 PM
Screenshot 2025-12-05 at 7 26 14 PM
Screenshot 2025-12-05 at 7 27 47 PM
Screenshot 2025-12-05 at 7 28 04 PM
Screenshot 2025-12-05 at 7 30 11 PM
Screenshot 2025-12-05 at 7 31 18 PM

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

Labels

High Priority - Please Review First This is an important PR we'd like to get merged as soon as possible

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants

Comments