Skip to content

Conversation

kushagrasarathe
Copy link
Contributor

@kushagrasarathe kushagrasarathe commented Feb 11, 2025

fixes TASK-7699

Summary by CodeRabbit

  • Bug Fixes

    • Enhanced error notifications during account creation and linking to provide clear, actionable feedback for issues like missing or invalid data.
    • Improved handling of duplicate account errors and streamlined response processing for account creation.
  • New Features

    • Introduced a direct verification link during account linking that guides users through additional KYC requirements when needed.
    • Expanded response structure to include additional details about errors and requirements.

Copy link

vercel bot commented Feb 11, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
peanut-ui ✅ Ready (Inspect) Visit Preview 💬 Add feedback Feb 12, 2025 10:28am

Copy link

Copy link
Contributor

coderabbitai bot commented Feb 11, 2025

Walkthrough

This pull request refines error handling and response formatting across both backend and frontend components. The external account creation API now returns structured JSON responses with proper HTTP status codes instead of throwing exceptions. Simultaneously, the cashout utility function streamlines duplicate account checks and error responses. On the frontend, a new state variable manages re-KYC verification URLs and conditionally displays user prompts. Additionally, the response interface is expanded with an optional property to include detailed error data.

Changes

File(s) Change Summary
src/app/api/bridge/.../create-external-account/route.ts & src/utils/cashout.utils.ts Updated error handling to replace thrown exceptions with structured JSON responses and proper HTTP status codes; refined duplicate account and endorsement error processing; removed extraneous logging.
src/components/Global/LinkAccountComponent/index.tsx Introduced reKYCUrl state for managing re-KYC flows; enhanced error handling to conditionally render verification links based on endorsement requirements.
src/interfaces/interfaces.ts Extended the IResponse interface with an optional details property (including code, message, and requirements) for more granular error information.

Possibly related PRs

Suggested Reviewers

  • Hugo0

Poem

Hop along, my coding friend,
Bugs and errors find their end.
JSON flows with graceful might,
KYC links shine ever bright.
A rabbit's cheer—code pure and light! 🐇✨


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 generate docstrings to generate docstrings for this PR. (Beta)
  • @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 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
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: 0

🧹 Nitpick comments (5)
src/app/api/bridge/external-account/create-external-account/route.ts (2)

79-97: Enhance error logging for better debugging.

While the error handling is good, consider adding more context to the error logs.

-console.error('Bridge API request failed:', response.status, response.statusText, responseData)
+console.error('Bridge API request failed:', {
+  status: response.status,
+  statusText: response.statusText,
+  endpoint: 'create-external-account',
+  responseData,
+  customerId
+})

112-157: Consider optimizing duplicate account detection.

The duplicate account detection logic could be moved to a separate function for better maintainability.

+async function findMatchingExistingAccount(
+  accounts: interfaces.IBridgeAccount[],
+  accountType: string,
+  accountDetails: any
+): Promise<interfaces.IBridgeAccount | undefined> {
+  return accounts.find((account: interfaces.IBridgeAccount) => {
+    if (accountType === 'iban') {
+      return (
+        account.account_details.type === 'iban' &&
+        account.account_details.last_4 === accountDetails.accountNumber.slice(-4)
+      )
+    } else {
+      return (
+        account.account_details.type === 'us' &&
+        account.account_details.last_4 === accountDetails.accountNumber.slice(-4) &&
+        account.account_details.routing_number === accountDetails.routingNumber
+      )
+    }
+  })
+}

Then use it in the route:

-const existingAccount = accounts.find((account: interfaces.IBridgeAccount) => {
-  if (accountType === 'iban') {
-    return (
-      account.account_details.type === 'iban' &&
-      account.account_details.last_4 === accountDetails.accountNumber.slice(-4)
-    )
-  } else {
-    return (
-      account.account_details.type === 'us' &&
-      account.account_details.last_4 === accountDetails.accountNumber.slice(-4) &&
-      account.account_details.routing_number === accountDetails.routingNumber
-    )
-  }
-})
+const existingAccount = await findMatchingExistingAccount(accounts, accountType, accountDetails)
src/utils/cashout.utils.ts (1)

224-276: Improve error handling and response type safety.

The error handling could be more robust with type guards and explicit error types.

+interface BridgeApiError {
+  code: string;
+  message: string;
+  details?: {
+    code?: string;
+    message?: string;
+    requirements?: {
+      [key: string]: string;
+    };
+  };
+}

+function isBridgeApiError(error: any): error is BridgeApiError {
+  return (
+    typeof error === 'object' &&
+    error !== null &&
+    'code' in error &&
+    typeof error.code === 'string'
+  );
+}

 if (!response.ok) {
-  if (responseData.code === 'duplicate_external_account') {
+  if (isBridgeApiError(responseData) && responseData.code === 'duplicate_external_account') {
src/components/Global/LinkAccountComponent/index.tsx (2)

422-440: Extract duplicated error display into a reusable component.

The error display logic is duplicated. Consider extracting it into a separate component.

+interface ErrorDisplayProps {
+  errorMessage: string;
+  reKYCUrl?: string;
+}

+const ErrorDisplay: React.FC<ErrorDisplayProps> = ({ errorMessage, reKYCUrl }) => (
+  <div className="text-start">
+    {reKYCUrl ? (
+      <div className="flex flex-col gap-2">
+        <label className="whitespace-normal text-h8 font-normal text-red">
+          {errorMessage}{' '}
+          <a
+            href={reKYCUrl}
+            target="_blank"
+            rel="noopener noreferrer"
+            className="underline"
+            aria-label="Complete additional KYC verification"
+          >
+            Click here to complete additional KYC verification.
+          </a>
+        </label>
+      </div>
+    ) : (
+      <label className="text-h8 font-normal text-red">{errorMessage}</label>
+    )}
+  </div>
+)

-{errorState.showError && (
-  <div className="text-start">
-    {reKYCUrl ? (
-      <div className="flex flex-col gap-2">
-        <label className="whitespace-normal text-h8 font-normal text-red">
-          {errorState.errorMessage}{' '}
-          <a href={reKYCUrl} target="_blank" rel="noopener noreferrer" className="underline">
-            Click here to complete additional KYC verification.
-          </a>
-        </label>
-      </div>
-    ) : (
-      <label className="text-h8 font-normal text-red">{errorState.errorMessage}</label>
-    )}
-  </div>
-)}
+{errorState.showError && (
+  <ErrorDisplay errorMessage={errorState.errorMessage} reKYCUrl={reKYCUrl} />
+)}

Also applies to: 597-615


49-49: Consider adding a loading state for the KYC URL.

The reKYCUrl state could benefit from a loading state to handle the transition period.

-const [reKYCUrl, setReKYCUrl] = useState<string | undefined>(undefined)
+const [reKYCUrl, setReKYCUrl] = useState<{ url?: string; isLoading: boolean }>({ isLoading: false })
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 5216e94 and aeda84b.

📒 Files selected for processing (4)
  • src/app/api/bridge/external-account/create-external-account/route.ts (4 hunks)
  • src/components/Global/LinkAccountComponent/index.tsx (5 hunks)
  • src/interfaces/interfaces.ts (1 hunks)
  • src/utils/cashout.utils.ts (1 hunks)
🔇 Additional comments (2)
src/interfaces/interfaces.ts (1)

10-16: LGTM! Well-structured interface extension.

The addition of the optional details property with typed fields enhances the response interface while maintaining backward compatibility.

src/app/api/bridge/external-account/create-external-account/route.ts (1)

11-14: LGTM! Consistent error response formatting.

The error responses are well-structured with proper HTTP status codes and content type headers.

Also applies to: 21-24, 62-65

Copy link
Contributor

@Hugo0 Hugo0 left a comment

Choose a reason for hiding this comment

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

No blocking issues

Comment on lines +11 to +14
return new NextResponse(JSON.stringify({ success: false, message: 'Customer ID is required' }), {
status: 400,
headers: { 'Content-Type': 'application/json' },
})
Copy link
Contributor

Choose a reason for hiding this comment

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

Q: why do we have a success: bool field? seems like a bad idea

Copy link
Contributor Author

Choose a reason for hiding this comment

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

following the bridge api response format here, they return a success field, also the success field is being used to track a few errors in the create account flow

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

🧹 Nitpick comments (2)
src/components/Global/LinkAccountComponent/index.tsx (2)

49-49: Enhance the state variable comment.

The comment could be more descriptive about when and why re-KYC might be required.

-    const [reKYCUrl, setReKYCUrl] = useState<string | undefined>(undefined) // state to set KYC url, if re-kyc verification is required
+    const [reKYCUrl, setReKYCUrl] = useState<string | undefined>(undefined) // Stores the URL for additional KYC verification when account creation fails due to insufficient verification level

315-330: Define error codes as constants.

Consider defining the error code as a constant to improve maintainability and prevent typos.

+const ERROR_CODES = {
+  ENDORSEMENT_REQUIREMENTS_NOT_MET: 'endorsement_requirements_not_met'
+} as const;

// Later in the code:
-                if (response.details?.code === 'endorsement_requirements_not_met') {
+                if (response.details?.code === ERROR_CODES.ENDORSEMENT_REQUIREMENTS_NOT_MET) {
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between aeda84b and e795e12.

📒 Files selected for processing (2)
  • src/app/api/bridge/external-account/create-external-account/route.ts (3 hunks)
  • src/components/Global/LinkAccountComponent/index.tsx (5 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/app/api/bridge/external-account/create-external-account/route.ts
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Deploy-Preview

Comment on lines +423 to +439
{reKYCUrl ? (
<div className="flex flex-col gap-2">
<label className="whitespace-normal text-h8 font-normal text-red">
{errorState.errorMessage}{' '}
<a
href={reKYCUrl}
target="_blank"
rel="noopener noreferrer"
className="underline"
>
Click here to complete additional KYC verification.
</a>
</label>
</div>
) : (
<label className="text-h8 font-normal text-red">{errorState.errorMessage}</label>
)}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Extract duplicated KYC link rendering into a reusable component.

The KYC link rendering logic is duplicated in two places. Consider extracting it into a reusable component to improve maintainability.

+const KYCLinkError: React.FC<{ errorMessage: string; reKYCUrl: string }> = ({ errorMessage, reKYCUrl }) => (
+  <div className="flex flex-col gap-2">
+    <label className="whitespace-normal text-h8 font-normal text-red">
+      {errorMessage}{' '}
+      <a href={reKYCUrl} target="_blank" rel="noopener noreferrer" className="underline">
+        Click here to complete additional KYC verification.
+      </a>
+    </label>
+  </div>
+);

// Replace both instances with:
{reKYCUrl ? (
  <KYCLinkError errorMessage={errorState.errorMessage} reKYCUrl={reKYCUrl} />
) : (
  <label className="text-h8 font-normal text-red">{errorState.errorMessage}</label>
)}

Also applies to: 598-614

@kushagrasarathe kushagrasarathe merged commit 3ae32a5 into peanut-wallet-dev Feb 12, 2025
5 checks passed
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