Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Analytics] Added maintenance banner #2296

Merged
merged 7 commits into from
Dec 4, 2024
Merged

Conversation

Codebmk
Copy link
Member

@Codebmk Codebmk commented Dec 4, 2024

Summary of Changes (What does this PR do?)

This pull request introduces a new feature to display a maintenance banner on the platform. The changes include adding a new MaintenanceBanner component, creating a hook to fetch maintenance status, and updating relevant files to incorporate these changes.

New Feature: Maintenance Banner

API Integration

Hook for Maintenance Status

Status of maturity (all need to be checked before merging):

  • I've tested this locally
  • I consider this code done
  • This change ready to hit production in its current state

How should this be manually tested?

  • Please include the steps to be done inorder to setup and test this PR.

What are the relevant tickets?

Screenshots (optional)

image

Summary by CodeRabbit

  • New Features

    • Introduced a MaintenanceBanner component to display maintenance notifications.
    • Added a custom hook, useMaintenanceStatus, to manage and retrieve maintenance status.
    • Implemented a new API function, getMaintenanceStatus, to fetch maintenance status from the server.
    • Added a new URL constant for maintenance status retrieval.
  • Bug Fixes

    • Enhanced error handling for maintenance status retrieval.
  • Documentation

    • Updated documentation to reflect the new maintenance-related features and components.

@Codebmk Codebmk self-assigned this Dec 4, 2024
Copy link

coderabbitai bot commented Dec 4, 2024

Warning

Rate limit exceeded

@Codebmk has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 12 minutes and 57 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between d27cd8e and 5b332d0.

📝 Walkthrough
📝 Walkthrough
📝 Walkthrough
📝 Walkthrough

Walkthrough

This pull request introduces several updates to the application's layout and maintenance status handling. A new MaintenanceBanner component is added to display maintenance notifications, utilizing a custom hook, useMaintenanceStatus, to fetch and manage the maintenance status. Additionally, a new API function, getMaintenanceStatus, is implemented to retrieve maintenance data from the server. The changes enhance the user interface by prominently showing maintenance information while keeping existing functionalities intact.

Changes

File Path Change Summary
platform/src/common/components/Layout/index.jsx Added import for MaintenanceBanner and useMaintenanceStatus. Integrated MaintenanceBanner to display maintenance status.
platform/src/common/components/MaintenanceBanner/index.jsx Introduced MaintenanceBanner component to show maintenance notifications with formatted times.
platform/src/core/apis/Account.js Added getMaintenanceStatus function to fetch maintenance status from the server. Imported MAINTENANCE_STATUS_URL.
platform/src/core/hooks/useMaintenanceStatus.js Created useMaintenanceStatus hook to manage and provide maintenance status with loading and error states.
platform/src/core/urls/authentication.js Added MAINTENANCE_STATUS_URL constant and removed import for NEXT_PUBLIC_API_TOKEN.

Possibly related PRs

Suggested labels

ready for review

Suggested reviewers

  • Baalmart

🎉 In the layout, a banner now shines,
With maintenance updates, it brightly aligns.
Fetching the status, it stands so tall,
A friendly reminder for one and for all.
With hooks and APIs, the code flows with grace,
Keeping users informed in this digital space! 🌟


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai or @coderabbitai title anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 5

🧹 Outside diff range and nitpick comments (2)
platform/src/core/hooks/useMaintenanceStatus.js (1)

4-4: Consider making the polling interval configurable

The polling interval is hardcoded. Consider making it configurable through props or environment variables for flexibility across different environments.

-const POLLING_INTERVAL = 5 * 60 * 1000; // 5 minutes
+const POLLING_INTERVAL = process.env.NEXT_PUBLIC_MAINTENANCE_POLLING_INTERVAL || 5 * 60 * 1000;
platform/src/common/components/MaintenanceBanner/index.jsx (1)

1-35: Add unit tests for the component

The component needs test coverage for various scenarios.

Would you like me to generate unit tests covering:

  • Rendering with valid maintenance data
  • Not rendering when maintenance is inactive
  • Handling invalid dates
  • Accessibility checks
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 9e15412 and 1e9b10f.

📒 Files selected for processing (5)
  • platform/src/common/components/Layout/index.jsx (3 hunks)
  • platform/src/common/components/MaintenanceBanner/index.jsx (1 hunks)
  • platform/src/core/apis/Account.js (2 hunks)
  • platform/src/core/hooks/useMaintenanceStatus.js (1 hunks)
  • platform/src/core/urls/authentication.js (2 hunks)
🔇 Additional comments (5)
platform/src/core/urls/authentication.js (1)

42-42: Consider generalizing the maintenance endpoint

The endpoint /maintenances/analytics seems specific to analytics. Consider whether this maintenance status should be platform-wide rather than analytics-specific.

platform/src/common/components/Layout/index.jsx (3)

12-12: LGTM! Clean import additions

The new imports follow the established path conventions and are logically grouped with similar imports.

Also applies to: 19-19


41-42: LGTM! Proper hook implementation

The maintenance status hook is correctly implemented at the component level, following React hooks best practices.


55-57: Verify banner's visibility across all layout scenarios

The MaintenanceBanner placement looks good, but let's ensure it remains visible across all layout scenarios.

✅ Verification successful

Banner implementation looks good with no visibility concerns

The MaintenanceBanner component uses a simple div structure with Tailwind CSS classes for styling. The implementation:

  • Uses fixed positioning relative to its parent container
  • Has proper z-index hierarchy through natural DOM order
  • Includes clear visual hierarchy with background color and border
  • Maintains visibility through contrasting colors (yellow-50 bg with yellow-700 text)
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for potential z-index conflicts and visibility issues

# Search for z-index values in stylesheets and components
rg -n "z-index|zIndex" --type css --type jsx

# Look for other absolute/fixed positioned elements that might overlap
rg -n "position:\s*(fixed|absolute)" --type css --type jsx

Length of output: 163


Script:

#!/bin/bash
# Let's try a different approach to find z-index and positioning styles
# Search in all files since the file extension detection seems problematic
rg -n "z-index|zIndex" 

# Search for MaintenanceBanner component definition to check its styling
fd -e js -e jsx -e tsx "MaintenanceBanner" --exec cat {}

# Search for position styles
rg -n "position:\s*(fixed|absolute)"

# Look for styled-components usage with position or z-index
rg -n "styled\." -A 3 

Length of output: 100352


Script:

#!/bin/bash
# Let's search for the MaintenanceBanner component definition and its styles
ast-grep --pattern 'const MaintenanceBanner = $$$'

# Search for any styled components related to MaintenanceBanner
rg -l "MaintenanceBanner"

# Look for any CSS modules or style files related to maintenance banner
fd -e css -e scss "maintenance|banner" --exec cat {}

Length of output: 3596

platform/src/core/apis/Account.js (1)

15-15: LGTM! Consistent URL import

The MAINTENANCE_STATUS_URL import follows the established pattern for authentication-related URLs.

Comment on lines +11 to +26
const fetchMaintenanceStatus = async () => {
try {
const response = await getMaintenanceStatus();
if (response.success && response.maintenance?.length > 0) {
setMaintenance(response.maintenance[0]);
} else {
setMaintenance(null);
}
setError(null);
} catch (err) {
setError(err);
console.error('Error fetching maintenance status:', err);
} finally {
setLoading(false);
}
};
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Enhance error handling and add type validation

The error handling could be more robust:

  1. No specific error types are being handled
  2. No validation of response data structure
  3. Console error in production code

Consider this enhanced implementation:

 const fetchMaintenanceStatus = async () => {
   try {
     const response = await getMaintenanceStatus();
+    // Validate response structure
+    if (!response || typeof response.success !== 'boolean') {
+      throw new Error('Invalid response format');
+    }
     if (response.success && response.maintenance?.length > 0) {
+      // Validate maintenance object structure
+      const maintenance = response.maintenance[0];
+      if (!maintenance.startDate || !maintenance.endDate || typeof maintenance.isActive !== 'boolean') {
+        throw new Error('Invalid maintenance data format');
+      }
       setMaintenance(response.maintenance[0]);
     } else {
       setMaintenance(null);
     }
     setError(null);
   } catch (err) {
     setError(err);
-    console.error('Error fetching maintenance status:', err);
+    // Use a proper logging service in production
+    if (process.env.NODE_ENV === 'development') {
+      console.error('Error fetching maintenance status:', err);
+    }
   } finally {
     setLoading(false);
   }
 };
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const fetchMaintenanceStatus = async () => {
try {
const response = await getMaintenanceStatus();
if (response.success && response.maintenance?.length > 0) {
setMaintenance(response.maintenance[0]);
} else {
setMaintenance(null);
}
setError(null);
} catch (err) {
setError(err);
console.error('Error fetching maintenance status:', err);
} finally {
setLoading(false);
}
};
const fetchMaintenanceStatus = async () => {
try {
const response = await getMaintenanceStatus();
// Validate response structure
if (!response || typeof response.success !== 'boolean') {
throw new Error('Invalid response format');
}
if (response.success && response.maintenance?.length > 0) {
// Validate maintenance object structure
const maintenance = response.maintenance[0];
if (!maintenance.startDate || !maintenance.endDate || typeof maintenance.isActive !== 'boolean') {
throw new Error('Invalid maintenance data format');
}
setMaintenance(response.maintenance[0]);
} else {
setMaintenance(null);
}
setError(null);
} catch (err) {
setError(err);
// Use a proper logging service in production
if (process.env.NODE_ENV === 'development') {
console.error('Error fetching maintenance status:', err);
}
} finally {
setLoading(false);
}
};

Comment on lines +28 to +33
useEffect(() => {
fetchMaintenanceStatus();
const interval = setInterval(fetchMaintenanceStatus, POLLING_INTERVAL);

return () => clearInterval(interval);
}, []);
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add cleanup for in-flight requests

Use AbortController to clean up pending requests when the component unmounts.

 useEffect(() => {
+  const abortController = new AbortController();
+
-  fetchMaintenanceStatus();
+  const fetchWithAbort = async () => {
+    try {
+      await fetchMaintenanceStatus({ signal: abortController.signal });
+    } catch (error) {
+      if (!error.name === 'AbortError') {
+        throw error;
+      }
+    }
+  };
+
+  fetchWithAbort();
   const interval = setInterval(fetchMaintenanceStatus, POLLING_INTERVAL);

-  return () => clearInterval(interval);
+  return () => {
+    clearInterval(interval);
+    abortController.abort();
+  };
 }, []);

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines +5 to +7
const MaintenanceBanner = ({ maintenance }) => {
if (!maintenance?.isActive) return null;

Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add PropTypes and handle invalid maintenance object

The component lacks prop type validation and could crash with invalid date values.

+import PropTypes from 'prop-types';
+import { isValid } from 'date-fns';

 const MaintenanceBanner = ({ maintenance }) => {
-  if (!maintenance?.isActive) return null;
+  if (!maintenance?.isActive || !maintenance?.startDate || !maintenance?.endDate) return null;
+
+  const startDate = new Date(maintenance.startDate);
+  const endDate = new Date(maintenance.endDate);
+
+  if (!isValid(startDate) || !isValid(endDate)) {
+    console.warn('Invalid maintenance dates provided');
+    return null;
+  }

+MaintenanceBanner.propTypes = {
+  maintenance: PropTypes.shape({
+    isActive: PropTypes.bool.isRequired,
+    startDate: PropTypes.string.isRequired,
+    endDate: PropTypes.string.isRequired,
+    message: PropTypes.string.isRequired,
+  }),
+};
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const MaintenanceBanner = ({ maintenance }) => {
if (!maintenance?.isActive) return null;
import PropTypes from 'prop-types';
import { isValid } from 'date-fns';
const MaintenanceBanner = ({ maintenance }) => {
if (!maintenance?.isActive || !maintenance?.startDate || !maintenance?.endDate) return null;
const startDate = new Date(maintenance.startDate);
const endDate = new Date(maintenance.endDate);
if (!isValid(startDate) || !isValid(endDate)) {
console.warn('Invalid maintenance dates provided');
return null;
}
MaintenanceBanner.propTypes = {
maintenance: PropTypes.shape({
isActive: PropTypes.bool.isRequired,
startDate: PropTypes.string.isRequired,
endDate: PropTypes.string.isRequired,
message: PropTypes.string.isRequired,
}),
};

Comment on lines 11 to 32
return (
<div className="bg-yellow-50 border-b border-yellow-200">
<div className="max-w-7xl mx-auto py-3 px-3 sm:px-6 lg:px-8">
<div className="flex items-center justify-center">
<div className="flex items-center">
<span className="flex">
<IoWarningOutline
className="h-6 w-6 text-yellow-600"
aria-hidden="true"
/>
</span>
<p className="ml-3 font-medium text-yellow-700">
{maintenance.message}
<span className="ml-2 text-yellow-600">
({startTime} - {endTime})
</span>
</p>
</div>
</div>
</div>
</div>
);
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Enhance accessibility and user experience

The banner needs better accessibility support and could benefit from additional UX features.

 return (
-  <div className="bg-yellow-50 border-b border-yellow-200">
+  <div 
+    role="alert"
+    aria-live="polite"
+    className="bg-yellow-50 border-b border-yellow-200"
+  >
     <div className="max-w-7xl mx-auto py-3 px-3 sm:px-6 lg:px-8">
       <div className="flex items-center justify-center">
         <div className="flex items-center">
           <span className="flex">
             <IoWarningOutline
               className="h-6 w-6 text-yellow-600"
-              aria-hidden="true"
+              aria-label="Warning"
             />
           </span>
-          <p className="ml-3 font-medium text-yellow-700">
+          <p className="ml-3 font-medium text-yellow-700" id="maintenance-message">
             {maintenance.message}
             <span className="ml-2 text-yellow-600">
               ({startTime} - {endTime})
             </span>
           </p>
         </div>
       </div>
     </div>
   </div>
 );
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
return (
<div className="bg-yellow-50 border-b border-yellow-200">
<div className="max-w-7xl mx-auto py-3 px-3 sm:px-6 lg:px-8">
<div className="flex items-center justify-center">
<div className="flex items-center">
<span className="flex">
<IoWarningOutline
className="h-6 w-6 text-yellow-600"
aria-hidden="true"
/>
</span>
<p className="ml-3 font-medium text-yellow-700">
{maintenance.message}
<span className="ml-2 text-yellow-600">
({startTime} - {endTime})
</span>
</p>
</div>
</div>
</div>
</div>
);
return (
<div
role="alert"
aria-live="polite"
className="bg-yellow-50 border-b border-yellow-200"
>
<div className="max-w-7xl mx-auto py-3 px-3 sm:px-6 lg:px-8">
<div className="flex items-center justify-center">
<div className="flex items-center">
<span className="flex">
<IoWarningOutline
className="h-6 w-6 text-yellow-600"
aria-label="Warning"
/>
</span>
<p className="ml-3 font-medium text-yellow-700" id="maintenance-message">
{maintenance.message}
<span className="ml-2 text-yellow-600">
({startTime} - {endTime})
</span>
</p>
</div>
</div>
</div>
</div>
);

Comment on lines +226 to +234
export const getMaintenanceStatus = async () => {
try {
const response = await createAxiosInstance().get(MAINTENANCE_STATUS_URL);
return response.data;
} catch (error) {
console.error('Error fetching maintenance status:', error);
throw error;
}
};
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Enhance error handling and reliability

While the basic implementation is functional, consider these improvements:

  1. Add specific error handling for different failure scenarios
  2. Implement a retry mechanism for transient failures
  3. Specify response type for better type safety
 export const getMaintenanceStatus = async () => {
   try {
-    const response = await createAxiosInstance().get(MAINTENANCE_STATUS_URL);
+    const response = await createAxiosInstance().get<MaintenanceStatusResponse>(
+      MAINTENANCE_STATUS_URL,
+      {
+        retry: 3,
+        retryDelay: 1000,
+      }
+    );
     return response.data;
   } catch (error) {
-    console.error('Error fetching maintenance status:', error);
+    if (axios.isAxiosError(error)) {
+      if (error.response?.status === 404) {
+        console.error('Maintenance status endpoint not found');
+      } else if (error.response?.status >= 500) {
+        console.error('Server error while fetching maintenance status');
+      } else {
+        console.error('Network error:', error.message);
+      }
+    }
     throw error;
   }
 };

Also, consider defining a type for the maintenance status response:

interface MaintenanceStatusResponse {
  active: boolean;
  message?: string;
  startTime?: string;
  endTime?: string;
}

Copy link
Contributor

github-actions bot commented Dec 4, 2024

New next-platform changes available for preview here

Copy link
Contributor

github-actions bot commented Dec 4, 2024

New next-platform changes available for preview here

Copy link
Contributor

github-actions bot commented Dec 4, 2024

New next-platform changes available for preview here

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🧹 Outside diff range and nitpick comments (1)
platform/src/common/components/MaintenanceBanner/index.jsx (1)

12-34: Add loading and error states

The component currently doesn't handle loading or error states, which could lead to a poor user experience during API calls or when errors occur.

Consider adding loading and error states:

 const MaintenanceBanner = ({ maintenance }) => {
+  if (maintenance === undefined) {
+    return (
+      <div className="bg-gray-50 border-b border-gray-200 mb-2">
+        <div className="py-3 px-3 text-center">
+          Loading maintenance status...
+        </div>
+      </div>
+    );
+  }
+
+  if (maintenance === null) {
+    return (
+      <div className="bg-red-50 border-b border-red-200 mb-2">
+        <div className="py-3 px-3 text-center text-red-700">
+          Error loading maintenance status
+        </div>
+      </div>
+    );
+  }

   if (!maintenance?.isActive) return null;
   // ... rest of the component
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between d97584a and bdda6b6.

📒 Files selected for processing (2)
  • platform/src/common/components/Layout/index.jsx (3 hunks)
  • platform/src/common/components/MaintenanceBanner/index.jsx (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • platform/src/common/components/Layout/index.jsx
🔇 Additional comments (1)
platform/src/common/components/MaintenanceBanner/index.jsx (1)

6-8: Enhance input validation

The current null check is insufficient and could lead to runtime errors if the date fields are invalid.

The previous review comment about adding PropTypes and handling invalid maintenance object is still applicable here.

Comment on lines 9 to 10
const startTime = format(new Date(maintenance.startDate), 'HH:mm');
const endTime = format(new Date(maintenance.endDate), 'HH:mm');
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Implement robust date handling

The current date handling has several potential issues:

  1. No validation for invalid date strings
  2. No explicit timezone handling
  3. No error boundaries for date parsing failures

Consider implementing this more robust approach:

-  const startTime = format(new Date(maintenance.startDate), 'HH:mm');
-  const endTime = format(new Date(maintenance.endDate), 'HH:mm');
+  const formatMaintenanceTime = (dateString) => {
+    try {
+      const date = new Date(dateString);
+      if (isNaN(date.getTime())) {
+        console.error('Invalid date string:', dateString);
+        return 'Invalid date';
+      }
+      return format(date, 'HH:mm');
+    } catch (error) {
+      console.error('Error formatting date:', error);
+      return 'Invalid date';
+    }
+  };
+
+  const startTime = formatMaintenanceTime(maintenance.startDate);
+  const endTime = formatMaintenanceTime(maintenance.endDate);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const startTime = format(new Date(maintenance.startDate), 'HH:mm');
const endTime = format(new Date(maintenance.endDate), 'HH:mm');
const formatMaintenanceTime = (dateString) => {
try {
const date = new Date(dateString);
if (isNaN(date.getTime())) {
console.error('Invalid date string:', dateString);
return 'Invalid date';
}
return format(date, 'HH:mm');
} catch (error) {
console.error('Error formatting date:', error);
return 'Invalid date';
}
};
const startTime = formatMaintenanceTime(maintenance.startDate);
const endTime = formatMaintenanceTime(maintenance.endDate);

Comment on lines 1 to 5
import React from 'react';
import { IoWarningOutline } from 'react-icons/io5';
import { format } from 'date-fns';
import dayjs from 'dayjs';

Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider consolidating date manipulation libraries

The component currently uses both date-fns and dayjs for date formatting. This is redundant and increases the bundle size unnecessarily. Consider standardizing on one library, preferably date-fns since it's already being used for the basic time formatting.

 import React from 'react';
 import { IoWarningOutline } from 'react-icons/io5';
 import { format } from 'date-fns';
-import dayjs from 'dayjs';

Committable suggestion skipped: line range outside the PR's diff.

);
};

export default MaintenanceBanner;
Copy link

Choose a reason for hiding this comment

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

💡 Codebase verification

Add test coverage for MaintenanceBanner component

The component is currently used in the Layout component and serves a clear purpose, but lacks test coverage. A test file should be added to ensure the component's reliability, especially since it handles maintenance state display.

  • Add test file at platform/src/common/components/MaintenanceBanner/MaintenanceBanner.test.jsx
  • Include test cases for:
    • Rendering with maintenance prop
    • Proper display of maintenance message
    • Component behavior when maintenance prop is empty/false
🔗 Analysis chain

Verify component usage and add tests

Let's ensure the component is properly integrated and tested:

  1. Verify all usage locations
  2. Add unit tests for the component
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for MaintenanceBanner usage
echo "Searching for MaintenanceBanner usage..."
rg "MaintenanceBanner" --type jsx --type tsx

# Check for existing test file
echo "Checking for test file..."
fd "MaintenanceBanner.test" --type file

Length of output: 264


Script:

#!/bin/bash
# Search for MaintenanceBanner usage with correct file extensions
echo "Searching for MaintenanceBanner usage..."
rg "MaintenanceBanner" -g "*.js" -g "*.jsx" -g "*.ts" -g "*.tsx"

# Check for test files in a more comprehensive way
echo "Checking for test files..."
fd -e test.js -e test.jsx -e spec.js -e spec.jsx "MaintenanceBanner"

# Look for the component definition to understand its location
echo "Finding component definition..."
rg "class MaintenanceBanner|function MaintenanceBanner|const MaintenanceBanner" -g "*.js" -g "*.jsx" -g "*.ts" -g "*.tsx"

Length of output: 1001

Copy link
Contributor

github-actions bot commented Dec 4, 2024

New next-platform changes available for preview here

Copy link
Contributor

github-actions bot commented Dec 4, 2024

New next-platform changes available for preview here

Copy link
Contributor

github-actions bot commented Dec 4, 2024

New next-platform changes available for preview here

Copy link
Contributor

github-actions bot commented Dec 4, 2024

New next-platform changes available for preview here

@Baalmart Baalmart merged commit 32e129f into staging Dec 4, 2024
30 of 31 checks passed
@Baalmart Baalmart deleted the ft-maintenance-banner branch December 4, 2024 14:44
@Codebmk Codebmk mentioned this pull request Dec 4, 2024
1 task
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants