Aditya-fix: resolve tool stoppage reason data loading error with comprehensive improvements#1903
Open
Aditya-gam wants to merge 13 commits intodevelopmentfrom
Open
Aditya-fix: resolve tool stoppage reason data loading error with comprehensive improvements#1903Aditya-gam wants to merge 13 commits intodevelopmentfrom
Aditya-gam wants to merge 13 commits intodevelopmentfrom
Conversation
…ntal_bar_graph_for_tools_stoppage_reason
…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.
Contributor
RitzzzZ2021
approved these changes
Nov 23, 2025
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.













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

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
console.errorwithLogger.logException()for Sentry integrationparseYmdUtc()andparseDateFlexibleUTC()supporting YYYY-MM-DD and ISO 8601 formatsbuildDateFilter()helper to eliminate code duplication{ success, data, count, message, executionTimeMs, cached? }retry: true) from query failures (500)GET /api/bm/projects/:id/tools-stoppage-reason?startDate&endDate- Tool stoppage data with optional date filteringGET /api/bm/tools-stoppage-reason/projects- Cached project list (5-min TTL)src/routes/bmdashboard/bmToolStoppageReasonRouter.js
{ success: false, errors: [...], message: "Validation failed" }src/models/bmdashboard/buildingToolsStoppage.js
projectId(ObjectId ref),toolName,usedForLifetime,damaged,lost,datetoolStoppageReason{ projectId: 1, date: 1 }for efficient querying{ toolName: 1 }for sorting optimizationHow to test:
Check into current branch:
Aditya-fix/tool-stoppage-reason-improvementsReinstall dependencies and clean cache using
rm -rf node_modules package-lock.json && npm cache clean --forceRun
npm installto install dependencies, then start the backend locally (npm startornpm run dev)Test endpoints (using Postman/curl with JWT token in Authorization header):
GET /api/bm/projects/<projectId>/tools-stoppage-reason→ Returns all tool stoppage data for projectGET /api/bm/projects/<projectId>/tools-stoppage-reason?startDate=2024-01-01&endDate=2024-12-31→ Filters by date rangeGET /api/bm/projects/invalid-id/tools-stoppage-reason→ Returns 400 validation errorGET /api/bm/projects/<nonExistentId>/tools-stoppage-reason→ Returns 404 not foundGET /api/bm/projects/<projectId>/tools-stoppage-reason?startDate=2024-12-31&endDate=2024-01-01→ Returns 400 invalid date range errorGET /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)Verify:
{ success, data, count, message, executionTimeMs, cached? }retry: trueFrontend Integration (coordinate with PR #):
/projectsendpointScreenshots or videos of changes:
TestVideo.mov
See frontend PR for:
Note:
[{projectId, projectName}, ...]{ success, data: [{projectId, projectName}, ...], count, message, executionTimeMs, cached? }response.datainstead ofresponsedirectly{ projectId: 1, date: 1 }- 50-80% query performance improvement{ toolName: 1 }- optimizes sorting