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

feat(web): email-updateable-at-info #1729

Merged
merged 3 commits into from
Oct 29, 2024
Merged

Conversation

Harman-singh-waraich
Copy link
Contributor

@Harman-singh-waraich Harman-singh-waraich commented Oct 29, 2024

Screenshot 2024-10-29 at 3 18 18 PM

PR-Codex overview

This PR introduces enhancements to the user settings functionality, including the ability to determine when a user's email can be updated and a new utility function to calculate the time left until a specified date.

Detailed summary

  • Added align-self: center to the Settings component.
  • Updated User type to include emailUpdateableAt.
  • Introduced timeLeftUntil function for calculating remaining time until a date.
  • Integrated timeLeftUntil in FormContactDetails to show when email can be updated.
  • Styled InfoCard to display email update information.

✨ Ask PR-Codex anything about this PR by commenting with /codex {your question}

Summary by CodeRabbit

  • New Features

    • Enhanced email update process with eligibility checks and user feedback through a new info card.
    • Introduced a new function to calculate time remaining until a specified date.
  • Bug Fixes

    • Improved error handling in email update submission to prevent execution on missing addresses.
  • Style

    • Adjusted alignment of tabs in the Settings component for better visual presentation.

Copy link
Contributor

coderabbitai bot commented Oct 29, 2024

Walkthrough

The changes in this pull request enhance the email update functionality within the FormContactDetails component by introducing a new utility function, isEmailUpdateable, which determines if the user's email can be updated based on a timestamp. The error handling in the submission process has been refined to prevent execution on missing addresses. Additionally, a new styled component, StyledInfoCard, provides user feedback regarding email update eligibility. Other modifications include updates to the StyledTabs component's alignment and the structure of user data retrieval in the fetchUser function to accommodate the new emailUpdateableAt property.

Changes

File Change Summary
web/src/layout/Header/navbar/Menu/Settings/Notifications/FormContactDetails/index.tsx Introduced isEmailUpdateable function for email update eligibility, modified error handling in handleSubmit, added StyledInfoCard for user feedback, updated button's disabled state.
web/src/layout/Header/navbar/Menu/Settings/index.tsx Modified StyledTabs component to include align-self: center; CSS property.
web/src/utils/atlas/fetchUser.ts Updated User type to include emailUpdateableAt, redefined GetUserResponse type, modified GraphQL query to include new user property.
web/src/utils/date.ts Added timeLeftUntil function to calculate remaining time until a specified date.

Possibly related PRs

  • fix(web): error-handling-in-submit-evidence-modal #1724: The changes in the SubmitEvidenceModal.tsx file enhance error handling in a way that is conceptually similar to the modifications made in the handleSubmit function of the FormContactDetails component, where error handling was also improved to prevent throwing errors when the address is missing.

Suggested labels

Type: Feature🗿, Package: Web

Suggested reviewers

  • alcercu
  • kemuru

Poem

🐇 In the meadow, changes bloom,
A new function to lift the gloom.
Email updates, now a breeze,
With styled cards that aim to please.
Tabs aligned, all set to go,
Time left until the next email flow! 🌼


🪧 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

netlify bot commented Oct 29, 2024

Deploy Preview for kleros-v2-neo ready!

Name Link
🔨 Latest commit 3869072
🔍 Latest deploy log https://app.netlify.com/sites/kleros-v2-neo/deploys/6720ba35a01fc50008ac4198
😎 Deploy Preview https://deploy-preview-1729--kleros-v2-neo.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 site configuration.

Copy link

netlify bot commented Oct 29, 2024

Deploy Preview for kleros-v2-university ready!

Name Link
🔨 Latest commit 3869072
🔍 Latest deploy log https://app.netlify.com/sites/kleros-v2-university/deploys/6720ba35215ab40008182cc8
😎 Deploy Preview https://deploy-preview-1729--kleros-v2-university.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 site configuration.

Copy link

netlify bot commented Oct 29, 2024

Deploy Preview for kleros-v2-testnet-devtools ready!

Name Link
🔨 Latest commit 3869072
🔍 Latest deploy log https://app.netlify.com/sites/kleros-v2-testnet-devtools/deploys/6720ba35237b06000838ad1d
😎 Deploy Preview https://deploy-preview-1729--kleros-v2-testnet-devtools.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 site configuration.

Copy link

netlify bot commented Oct 29, 2024

Deploy Preview for kleros-v2-testnet ready!

Name Link
🔨 Latest commit 3869072
🔍 Latest deploy log https://app.netlify.com/sites/kleros-v2-testnet/deploys/6720ba35a2868b0008c209af
😎 Deploy Preview https://deploy-preview-1729--kleros-v2-testnet.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 site configuration.

Copy link
Contributor

@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 (3)
web/src/utils/date.ts (1)

39-48: Enhance function documentation for completeness.

The JSDoc documentation could be more comprehensive by including all possible return values.

Consider updating the documentation:

 /**
  * Calculates the time left until a specified date and formats it.
  *
  * @param {string} isoString - An ISO 8601 formatted date string (e.g., "2024-10-29T09:52:08.580Z").
  * @returns {string} A human-readable string indicating the time left until the specified date.
  * @example
  * console.log(timeLeftUntil("2024-10-29T09:52:08.580Z"));
- * // Outputs: "in x secs", "in x mins", "in x hrs", or "after October 29, 2024"
+ * // Possible outputs:
+ * // - "The date has already passed."
+ * // - "in x secs"
+ * // - "in x mins"
+ * // - "in x hrs"
+ * // - "in x days"
+ * // - "after October 29, 2024"
  */
web/src/layout/Header/navbar/Menu/Settings/Notifications/FormContactDetails/index.tsx (2)

41-45: Consider using consistent spacing values

The margin-bottom: 8px in StyledInfoCard is inconsistent with the gap: 16px used in FormContainer. Consider using 16px for consistency.

 const StyledInfoCard = styled(InfoCard)`
   width: fit-content;
   font-size: 14px;
-  margin-bottom: 8px;
+  margin-bottom: 16px;
   word-wrap: break-word;
 `;

Line range hint 47-138: Consider splitting component responsibilities

The FormContactDetails component handles multiple responsibilities:

  1. User creation
  2. Email updates
  3. Update restriction management
  4. Form validation

Consider splitting these into smaller, more focused components for better maintainability and testing.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between d1a6020 and 5ec36e5.

📒 Files selected for processing (4)
  • web/src/layout/Header/navbar/Menu/Settings/Notifications/FormContactDetails/index.tsx (5 hunks)
  • web/src/layout/Header/navbar/Menu/Settings/index.tsx (1 hunks)
  • web/src/utils/atlas/fetchUser.ts (1 hunks)
  • web/src/utils/date.ts (1 hunks)
🔇 Additional comments (5)
web/src/utils/atlas/fetchUser.ts (2)

9-9: LGTM! Well-structured type definitions.

The type definitions are well-organized and follow TypeScript best practices:

  • emailUpdateableAt is properly typed as string | null
  • GetUserResponse type improves maintainability by referencing the User type

Also applies to: 12-14


20-20: Verify GraphQL schema compatibility.

The addition of emailUpdateableAt field looks correct, but we should verify it matches the backend schema to prevent runtime errors.

web/src/layout/Header/navbar/Menu/Settings/index.tsx (1)

55-55: LGTM! Clean styling improvement.

The addition of align-self: center to StyledTabs improves UI consistency by properly centering the tabs, matching the centered settings text above.

web/src/utils/date.ts (1)

49-74: ⚠️ Potential issue

Several improvements needed for robustness and consistency.

The implementation has a few areas that could be enhanced:

  1. Missing input validation for invalid date strings
  2. Time calculations could leverage existing utility functions
  3. Singular/plural handling needs improvement
  4. Inconsistent time formatting with other functions in the file

Consider applying these improvements:

 export function timeLeftUntil(isoString: string): string {
+  // Validate input
+  const parsedDate = new Date(isoString);
+  if (isNaN(parsedDate.getTime())) {
+    throw new Error('Invalid date string provided');
+  }
+
   const targetDate = new Date(isoString);
   const now = new Date();
-  const timeDifference = targetDate.getTime() - now.getTime();
+  const secondsLeft = Math.floor((targetDate.getTime() - now.getTime()) / 1000);
 
-  if (timeDifference <= 0) {
+  if (secondsLeft <= 0) {
     return "The date has already passed.";
   }
 
-  const secondsLeft = Math.floor(timeDifference / 1000);
   const minutesLeft = Math.floor(secondsLeft / 60);
   const hoursLeft = Math.floor(minutesLeft / 60);
   const daysLeft = Math.floor(hoursLeft / 24);
 
   if (secondsLeft < 60) {
-    return `in ${secondsLeft} secs`;
+    return `in ${secondsLeft} ${secondsLeft === 1 ? 'sec' : 'secs'}`;
   } else if (minutesLeft < 60) {
-    return `in ${minutesLeft} mins`;
+    return `in ${minutesLeft} ${minutesLeft === 1 ? 'min' : 'mins'}`;
   } else if (hoursLeft < 24) {
-    return `in ${hoursLeft} hrs`;
+    return `in ${hoursLeft} ${hoursLeft === 1 ? 'hr' : 'hrs'}`;
   } else if (daysLeft < 2) {
-    return `in ${daysLeft} days`;
+    return `in ${daysLeft} day`;
   } else {
-    const options: Intl.DateTimeFormatOptions = { year: "numeric", month: "long", day: "numeric" };
-    return `after ${targetDate.toLocaleDateString("en-US", options)}`;
+    return `after ${formatDate(Math.floor(targetDate.getTime() / 1000))}`;
   }
 }

This implementation:

  • Validates the input date string
  • Uses proper singular/plural forms
  • Leverages the existing formatDate function for consistency
  • Improves the readability of time calculations

Let's verify the usage context:

web/src/layout/Header/navbar/Menu/Settings/Notifications/FormContactDetails/index.tsx (1)

56-58: 🛠️ Refactor suggestion

Verify type safety and date handling

While the logic is functional, consider these improvements:

  1. Add type safety for emailUpdateableAt
  2. Use consistent date handling to avoid timezone issues

Consider this more robust implementation:

   const isEmailUpdateable = user?.email
-    ? !isUndefined(user?.emailUpdateableAt) && new Date(user.emailUpdateableAt).getTime() < new Date().getTime()
+    ? !isUndefined(user?.emailUpdateableAt) && 
+      Date.now() > new Date(user.emailUpdateableAt).getTime()
     : true;

Copy link
Contributor

@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: 1

🧹 Outside diff range and nitpick comments (1)
web/src/utils/date.ts (1)

39-48: LGTM! Well-documented function signature.

The JSDoc documentation is thorough and clear. The TypeScript types are properly defined.

Consider adding more examples to cover edge cases (e.g., past dates, different time ranges).

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 5ec36e5 and 074d7ca.

📒 Files selected for processing (1)
  • web/src/utils/date.ts (1 hunks)
🔇 Additional comments (1)
web/src/utils/date.ts (1)

49-61: 🛠️ Refactor suggestion

Consider adding input validation and time zone handling.

While the core logic is sound, there are a few potential improvements:

Consider these improvements:

  1. Add input validation to handle invalid ISO strings:
 export function timeLeftUntil(isoString: string): string {
+  if (!isoString || isNaN(Date.parse(isoString))) {
+    throw new Error('Invalid date format. Expected ISO 8601 string.');
+  }
   const targetDate = new Date(isoString);
  1. Consider using UTC methods to ensure consistent time zone handling:
-  const targetDate = new Date(isoString);
-  const now = new Date();
+  const targetDate = new Date(isoString).getTime();
+  const now = Date.now();
-  const timeDifference = targetDate.getTime() - now.getTime();
+  const timeDifference = targetDate - now;

Copy link
Contributor

@alcercu alcercu left a comment

Choose a reason for hiding this comment

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

lgtm

@alcercu alcercu enabled auto-merge October 29, 2024 10:34
Copy link

codeclimate bot commented Oct 29, 2024

Code Climate has analyzed commit 3869072 and detected 5 issues on this pull request.

Here's the issue category breakdown:

Category Count
Complexity 3
Duplication 2

View more on Code Climate.

Copy link

@alcercu alcercu added this pull request to the merge queue Oct 29, 2024
Merged via the queue into dev with commit 6e71e9d Oct 29, 2024
25 of 27 checks passed
This was referenced Nov 20, 2024
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