Skip to content

Conversation

@sstefdev
Copy link
Contributor

@sstefdev sstefdev commented Nov 21, 2024

Fixes #177
Fixes #162

Problem

The Invoice Dashboard lacks clarity in distinguishing canceled invoices based on whether the Payee or the Payer initiated the cancellation. Additionally, the previous approach to loading statuses was slower and less efficient.

Changes

  • Status Indicators:
    • Added better logic to differentiate the statuses.
    • Added logic for the Overdue, Rejected and Canceled
  • Performance Enhancements:
    • Optimized the status-loading mechanism for faster performance in the Invoice View and Dashboard.

These updates improve clarity in status representation while enhancing performance, providing a more intuitive and responsive user experience.

Summary by CodeRabbit

Summary by CodeRabbit

  • New Features

    • Enhanced invoice payment status evaluation providing more detailed statuses such as "Paid," "Partially Paid," "Rejected," "Overdue," and "Canceled."
    • Updated display logic for invoice statuses to reflect the latest evaluations.
    • Introduced a new utility function for checking payment status, improving overall reliability.
    • Added a new utility function for capitalizing strings.
  • Bug Fixes

    • Improved accuracy in determining and displaying the payment status based on the latest request data.

@sstefdev sstefdev self-assigned this Nov 21, 2024
@sstefdev sstefdev linked an issue Nov 21, 2024 that may be closed by this pull request
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Nov 21, 2024

Walkthrough

The changes introduce a new function, checkStatus, in the invoice-view.svelte file that evaluates the payment status of requests based on their balance and associated events. The display logic for the invoice status is updated to utilize this new function, replacing the previous isPaid boolean. In the view-requests.svelte file, the local checkStatus implementation is removed and replaced with an import from @requestnetwork/shared-utils/checkStatus. Additionally, a new capitalize function is added to handle string formatting.

Changes

File Path Change Summary
packages/invoice-dashboard/src/lib/dashboard/invoice-view.svelte Introduced checkStatus function to evaluate payment status and updated invoice status display logic.
packages/invoice-dashboard/src/lib/view-requests.svelte Removed local checkStatus implementation; replaced with import from @requestnetwork/shared-utils/checkStatus.
shared/utils/capitalize.ts Added capitalize function for string formatting.
shared/utils/checkStatus.ts Introduced checkStatus function to evaluate payment status based on balance, due date, and events.

Assessment against linked issues

Objective Addressed Explanation
Add "Rejected" status to the Invoice Dashboard (#162)
Indicate who canceled the invoice (#162)

Possibly related PRs

  • fix: added payment check when invoice is paid #83: The changes in this PR involve the introduction of a boolean variable isRequestPayed and updates to the logic for determining if a request is paid, which relates to the overall payment status logic being enhanced in the main PR.
  • feat: handle all request status #138: This PR modifies the logic for determining the payment status of requests, aligning closely with the new checkStatus function introduced in the main PR that also evaluates payment statuses.
  • Add IN/OUT Indicator Column to Invoice Dashboard #204: The updates in this PR include modifications to the view-requests.svelte file, which is relevant as it also deals with the display and handling of request statuses, complementing the changes made in the main PR.

Suggested reviewers

  • MantisClone
  • aimensahnoun
  • rodrigopavezi

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

🧹 Outside diff range and nitpick comments (2)
packages/invoice-dashboard/src/lib/dashboard/invoice-view.svelte (1)

102-102: Consider making status reactive.

The status should be updated whenever requestData or request changes.

Apply this diff to make the status reactive:

-  let status = checkStatus(requestData || request);
+  $: status = checkStatus(requestData || request);
packages/invoice-dashboard/src/lib/view-requests.svelte (1)

386-408: LGTM! Consider these optimizations for better performance and type safety.

The implementation correctly handles all required statuses (Paid, Partially Paid, Rejected, Overdue, Canceled) as per PR objectives. However, here are some suggestions for optimization:

  1. Move the event status mapping outside the function to avoid recreation on each call:
+const EVENT_STATUS = {
+  reject: "Rejected",
+  overdue: "Overdue",
+  cancel: "Canceled",
+} as const;

 const checkStatus = (request: any) => {
   if (request?.balance?.balance > 0) {
     return request.balance.balance >= request.expectedAmount
       ? "Paid"
       : "Partially Paid";
   }

-  const eventStatus = {
-    reject: "Rejected",
-    overdue: "Overdue",
-    cancel: "Canceled",
-  };

-  for (const [event, status] of Object.entries(eventStatus)) {
+  for (const [event, status] of Object.entries(EVENT_STATUS)) {
     if (
       request?.events?.some(
         (e: { name?: string }) => e?.name?.toLowerCase() === event
       )
     ) {
       return status;
     }
   }

   return capitalize(request?.state);
 };
  1. Add TypeScript types for better type safety:
type RequestStatus = "Paid" | "Partially Paid" | "Rejected" | "Overdue" | "Canceled" | string;
type RequestEvent = { name?: string };
type Request = {
  balance?: { balance: number };
  expectedAmount: number;
  events?: RequestEvent[];
  state?: string;
};

const checkStatus = (request: Request): RequestStatus => {
  // ... rest of the implementation
};
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between dc6b506 and 1d67532.

📒 Files selected for processing (2)
  • packages/invoice-dashboard/src/lib/dashboard/invoice-view.svelte (3 hunks)
  • packages/invoice-dashboard/src/lib/view-requests.svelte (1 hunks)
🧰 Additional context used
📓 Learnings (1)
packages/invoice-dashboard/src/lib/dashboard/invoice-view.svelte (1)
Learnt from: MantisClone
PR: RequestNetwork/web-components#141
File: packages/invoice-dashboard/src/lib/dashboard/invoice-view.svelte:0-0
Timestamp: 2024-11-12T14:52:33.204Z
Learning: In `packages/invoice-dashboard/src/lib/dashboard/invoice-view.svelte`, mapping payment network IDs to their respective approval functions in the `checkApproval` function is acceptable and can improve readability and maintainability.
🔇 Additional comments (1)
packages/invoice-dashboard/src/lib/dashboard/invoice-view.svelte (1)

400-400: 🛠️ Refactor suggestion

Improve status display styling.

The status styling currently only differentiates between paid and unpaid states using the isPaid boolean. With the new status system, the styling should reflect all possible states.

Apply this diff to improve the status display:

-    <p class={`invoice-status ${isPaid ? "bg-green" : "bg-zinc"}`}>
+    <p class={`invoice-status ${
+      status === "Paid" ? "bg-green" : 
+      status === "Partially Paid" ? "bg-yellow" : 
+      status === "Rejected" ? "bg-red" : 
+      status === "Overdue" ? "bg-orange" : 
+      status === "Canceled" ? "bg-purple" : 
+      "bg-zinc"
+    }`}>

Also add the new status colors to the style section:

   .bg-green {
     background-color: #0bb489;
   }
+  .bg-yellow {
+    background-color: #f59e0b;
+  }
+  .bg-red {
+    background-color: #ef4444;
+  }
+  .bg-orange {
+    background-color: #f97316;
+  }
+  .bg-purple {
+    background-color: #8b5cf6;
+  }
   .bg-zinc {
     background-color: #a1a1aa;
   }

Likely invalid or redundant comment.

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: 2

🧹 Outside diff range and nitpick comments (3)
packages/invoice-dashboard/src/lib/dashboard/invoice-view.svelte (1)

76-101: Consider improving documentation and maintainability.

The checkStatus function implementation looks good, but could benefit from these improvements:

  1. Add JSDoc documentation to describe the function's purpose and return values
  2. Move the event status mapping to a constant outside the function
  3. Add explicit null check for the events array
+const EVENT_STATUS_MAP = {
+  create: "Created",
+  reject: "Rejected",
+  overdue: "Overdue",
+  cancel: "Canceled",
+} as const;
+
+/**
+ * Determines the status of a request based on its balance and events.
+ * @param request - The request data with events
+ * @returns The current status of the request
+ */
 const checkStatus = (request: Types.IRequestDataWithEvents | null) => {
   if (Number(request?.balance?.balance)! > 0) {
     return request?.balance?.balance! >= request?.expectedAmount!
       ? "Paid"
       : "Partially Paid";
   }

-  const eventStatus = {
-    create: "Created",
-    reject: "Rejected",
-    overdue: "Overdue",
-    cancel: "Canceled",
-  };

-  for (const [event, reqStatus] of Object.entries(eventStatus)) {
+  if (!request?.events) return "Created";
+
+  for (const [event, reqStatus] of Object.entries(EVENT_STATUS_MAP)) {
     if (
-      request?.events?.some(
+      request.events.some(
         (e: { name?: string }) => e?.name?.toLowerCase() === event
       )
     ) {
       return reqStatus;
     }
   }

   return "Created";
 };
packages/invoice-dashboard/src/lib/view-requests.svelte (2)

Line range hint 679-679: Add visual distinction for different status types

According to the PR objectives, different statuses should have distinct visual representations (e.g., red for Canceled, orange for Rejected). Consider adding status-specific styling to improve clarity.

Add a status indicator component or apply status-specific classes:

-  <td> {checkStatus(request)}</td>
+  <td>
+    <span class="status-indicator {checkStatus(request).toLowerCase()}">
+      {checkStatus(request)}
+    </span>
+  </td>

Add these styles to the <style> section:

.status-indicator {
  padding: 4px 8px;
  border-radius: 4px;
  font-weight: 500;
}

.status-indicator.canceled {
  background-color: #fee2e2;
  color: #dc2626;
}

.status-indicator.rejected {
  background-color: #ffedd5;
  color: #ea580c;
}

.status-indicator.overdue {
  background-color: #fef3c7;
  color: #d97706;
}

.status-indicator.paid {
  background-color: #dcfce7;
  color: #16a34a;
}

.status-indicator.partially.paid {
  background-color: #e0f2fe;
  color: #0284c7;
}

385-408: Optimize status checking performance

The checkStatus function is called for each row on every render. Consider these optimizations:

  1. Memoize the status calculations
  2. Pre-compute statuses when requests are loaded
  3. Use a derived store for filtered and processed requests

Here's how to implement these optimizations:

+ const requestStatusCache = new Map<string, string>();

+ const getRequestStatus = (request: Types.IRequestDataWithEvents | null) => {
+   if (!request) return "Unknown";
+   
+   const cacheKey = `${request.requestId}-${request.state}-${request.balance?.balance}`;
+   if (requestStatusCache.has(cacheKey)) {
+     return requestStatusCache.get(cacheKey)!;
+   }
+   
+   const status = checkStatus(request);
+   requestStatusCache.set(cacheKey, status);
+   return status;
+ };

  const processedRequests = (filteredRequests ?? []).map(
    (request): Types.IRequestDataWithEvents & {
      formattedAmount: string;
      currencySymbol: string;
      paymentCurrencies: (CurrencyTypes.ERC20Currency | CurrencyTypes.NativeCurrency | undefined)[];
+     status: string;
    } => {
      // ... existing processing ...
+     const status = getRequestStatus(request);
      
      return {
        ...request,
        formattedAmount,
        currencySymbol,
        paymentCurrencies,
+       status,
      };
    }
  );

Then update the table to use the pre-computed status:

- <td> {checkStatus(request)}</td>
+ <td>
+   <span class="status-indicator {request.status.toLowerCase()}">
+     {request.status}
+   </span>
+ </td>
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 1d67532 and 8a60e3a.

📒 Files selected for processing (2)
  • packages/invoice-dashboard/src/lib/dashboard/invoice-view.svelte (3 hunks)
  • packages/invoice-dashboard/src/lib/view-requests.svelte (1 hunks)
🧰 Additional context used
📓 Learnings (1)
packages/invoice-dashboard/src/lib/dashboard/invoice-view.svelte (1)
Learnt from: MantisClone
PR: RequestNetwork/web-components#141
File: packages/invoice-dashboard/src/lib/dashboard/invoice-view.svelte:0-0
Timestamp: 2024-11-12T14:52:33.204Z
Learning: In `packages/invoice-dashboard/src/lib/dashboard/invoice-view.svelte`, mapping payment network IDs to their respective approval functions in the `checkApproval` function is acceptable and can improve readability and maintainability.
🔇 Additional comments (1)
packages/invoice-dashboard/src/lib/dashboard/invoice-view.svelte (1)

103-103: LGTM: Status initialization is correct.

The status initialization properly uses the new checkStatus function with appropriate fallback handling.

Copy link
Member

@MantisClone MantisClone left a comment

Choose a reason for hiding this comment

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

Thanks @sstefdev It's not quite ready - please see comments 👇

@sstefdev sstefdev requested a review from MantisClone November 22, 2024 18:40
@MantisClone MantisClone changed the title Add Overdue, Rejected and Canceled statuses feat: Add Overdue, Rejected and Canceled statuses Nov 22, 2024
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: 4

🧹 Outside diff range and nitpick comments (8)
shared/utils/checkStatus.ts (3)

5-10: Consider handling additional edge cases in the balance check.

While the current implementation handles the basic cases well, consider adding validation for:

  • Negative balances
  • Invalid number conversions
  • Zero expected amount
 export const checkStatus = (request: Types.IRequestDataWithEvents | null) => {
   const balance = Number(request?.balance?.balance ?? 0);
   const expectedAmount = Number(request?.expectedAmount ?? 0);
 
+  if (expectedAmount <= 0) {
+    return "Invalid Amount";
+  }
+
+  if (balance < 0) {
+    return "Error";
+  }
+
   if (balance > 0) {
     return balance >= expectedAmount ? "Paid" : "Partially Paid";
   }

12-15: Consider moving event status mapping to a constant.

The event status mapping could be moved to a constant or enum to improve maintainability and reusability across the codebase.

+export const EVENT_STATUS = {
+  reject: "Rejected",
+  cancel: "Canceled",
+} as const;
+
 export const checkStatus = (request: Types.IRequestDataWithEvents | null) => {
   // ...
-  const eventStatus = {
-    reject: "Rejected",
-    cancel: "Canceled",
-  };
+  const eventStatus = EVENT_STATUS;

4-33: Add unit tests for comprehensive status checking.

The implementation successfully adds all required statuses, but would benefit from comprehensive unit tests to verify:

  1. All status transitions
  2. Edge cases
  3. Date handling
  4. Event processing

Would you like me to help generate a test suite for this utility function?

packages/invoice-dashboard/src/lib/dashboard/invoice-view.svelte (2)

77-77: Consider simplifying the initial status assignment.

The fallback to request might be unnecessary since requestData is initially null. Consider using just request for the initial status.

-let status = checkStatus(requestData || request);
+let status = checkStatus(request);

192-193: Add error handling for status updates.

The status update in checkInvoice should handle errors explicitly to prevent undefined states.

-      status = checkStatus(requestData || request);
+      status = checkStatus(requestData || request);
+    } catch (err: any) {
+      console.error("Error while checking status: ", err);
+      status = "Error";
+      throw err;
packages/invoice-dashboard/src/lib/view-requests.svelte (3)

Line range hint 42-141: Consider breaking down the component for better maintainability.

The component handles multiple responsibilities including wallet connection, request fetching, pagination, and sorting. Consider extracting these into separate components or composables:

  • RequestManager: Handle request fetching and processing
  • PaginationManager: Handle pagination logic
  • SortingManager: Handle sorting logic

This would improve:

  • Code organization
  • Testing
  • Reusability
  • Maintenance

Line range hint 516-524: Optimize table rendering performance.

The table implementation processes and sorts data on every change. Consider implementing:

  1. Virtual scrolling for large datasets
  2. Memoization of sorted and filtered results
  3. Debounced sorting and filtering operations

This would improve performance especially with large datasets by:

  • Reducing unnecessary re-renders
  • Minimizing DOM updates
  • Improving scroll performance

Line range hint 642-658: Enhance error handling and user feedback.

The PDF export error handling could be more informative and provide better recovery options:

  1. Add specific error messages for common failure scenarios
  2. Provide retry functionality
  3. Log errors for debugging

Consider this enhancement:

 onClick={async () => {
   try {
     await exportToPDF(
       request,
       getCurrencyFromManager(
         request.currencyInfo,
         currencyManager
       ),
       request.paymentCurrencies,
       config.logo
     );
   } catch (error) {
+    const errorMessage = error instanceof Error ? error.message : 'Unknown error';
+    const actionType = errorMessage.includes('network') ? 'Retry' : 'Close';
     toast.error(`Failed to export PDF`, {
-      description: `${error}`,
+      description: `Error: ${errorMessage}. Please try again later.`,
       action: {
-        label: "X",
-        onClick: () => console.info("Close"),
+        label: actionType,
+        onClick: () => actionType === 'Retry' ? 
+          exportToPDF(request, getCurrencyFromManager(request.currencyInfo, currencyManager), request.paymentCurrencies, config.logo) : 
+          console.info("Close"),
       },
     });
-    console.error("Failed to export PDF:", error);
+    console.error("Failed to export PDF:", { error, request: request.requestId });
   }
 }}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 6f45844 and 005e558.

📒 Files selected for processing (4)
  • packages/invoice-dashboard/src/lib/dashboard/invoice-view.svelte (4 hunks)
  • packages/invoice-dashboard/src/lib/view-requests.svelte (1 hunks)
  • shared/utils/capitalize.ts (1 hunks)
  • shared/utils/checkStatus.ts (1 hunks)
🧰 Additional context used
📓 Learnings (1)
packages/invoice-dashboard/src/lib/dashboard/invoice-view.svelte (1)
Learnt from: MantisClone
PR: RequestNetwork/web-components#141
File: packages/invoice-dashboard/src/lib/dashboard/invoice-view.svelte:0-0
Timestamp: 2024-11-12T14:52:33.204Z
Learning: In `packages/invoice-dashboard/src/lib/dashboard/invoice-view.svelte`, mapping payment network IDs to their respective approval functions in the `checkApproval` function is acceptable and can improve readability and maintainability.
🔇 Additional comments (5)
shared/utils/capitalize.ts (1)

1-2: Verify usage in status text handling

Since this utility is used for status text capitalization, let's verify that all status values are properly handled.

✅ Verification successful

The capitalize utility is safely handling all status values

Based on the analysis:

  1. The capitalize function is only used in checkStatus.ts for handling request states
  2. The function has proper null checks with the && operator and returns an empty string as fallback
  3. The state is only capitalized as a last resort after checking for:
    • Payment status (Paid/Partially Paid)
    • Special event statuses (Rejected/Canceled)
    • Due date status (Overdue)

The implementation safely handles all edge cases:

  • Null/undefined inputs return empty string
  • Non-empty strings are properly capitalized
  • The function is used in a controlled context where state values come from the Request Network SDK
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Find all status text usage to ensure proper string inputs

# Search for status-related code that might use this function
echo "Searching for status-related code..."
rg -l 'status|state' --type ts --type svelte

# Search for direct usage of capitalize
echo -e "\nSearching for capitalize usage..."
rg -A 2 'capitalize\(' --type ts --type svelte

Length of output: 323


Script:

#!/bin/bash
# Let's try a different approach without specifying file types
# First, find all files that might contain status-related code
echo "Searching for status-related code..."
rg -l 'status|state'

# Then search for direct usage of capitalize function
echo -e "\nSearching for capitalize usage..."
rg -A 2 'capitalize\('

# Also search for imports of capitalize to track its usage
echo -e "\nSearching for capitalize imports..."
rg "import.*capitalize.*from"

Length of output: 926


Script:

#!/bin/bash
# Let's examine the checkStatus.ts file to understand how state values are handled
echo "Content of checkStatus.ts:"
cat shared/utils/checkStatus.ts

# Let's also check what possible state values might be by looking at related files
echo -e "\nChecking state values in components:"
rg -A 3 'state=' shared/components/status.svelte
rg -A 3 'state:' packages/invoice-dashboard/src/lib/dashboard/invoice-view.svelte

Length of output: 1211


Script:

#!/bin/bash
# Let's check the Request Network types to understand possible state values
echo "Searching for Request Network type definitions:"
rg -A 5 "enum.*State" 

# Also check for any state-related constants or type definitions in our codebase
echo -e "\nSearching for state-related type definitions:"
rg -A 5 "type.*State|interface.*State|enum.*State" --type ts

# Look for actual state values being used
echo -e "\nSearching for state value assignments:"
rg "state.*=.*['\"](\w+)['\"]" --type ts

Length of output: 1424

shared/utils/checkStatus.ts (1)

1-4: LGTM! Well-structured function signature with proper typing.

The function signature and imports are well-defined, with appropriate handling of the nullable parameter.

packages/invoice-dashboard/src/lib/dashboard/invoice-view.svelte (2)

26-26: LGTM! Good refactoring of status checking logic.

Moving the status checking logic to a shared utility improves code reuse and maintainability.


375-375: ⚠️ Potential issue

Update status styling to support new status types.

The current styling only differentiates between paid and unpaid states. With the new status types (Overdue, Rejected, Canceled), the styling should be updated to reflect these states appropriately.

-<p class={`invoice-status ${isPaid ? "bg-green" : "bg-zinc"}`}>
+<p class={`invoice-status ${getStatusStyle(status)}`}>
   {status}
 </p>

+<script>
+function getStatusStyle(status: string): string {
+  switch (status) {
+    case "Paid":
+      return "bg-green";
+    case "Rejected":
+    case "Canceled":
+      return "bg-red";
+    case "Overdue":
+      return "bg-orange";
+    default:
+      return "bg-zinc";
+  }
+}
+</script>

+<style>
+.bg-red {
+  background-color: #ef4444;
+}
+.bg-orange {
+  background-color: #f97316;
+}
+</style>

Note: This was previously suggested in a past review comment. Please coordinate with the team regarding the styling implementation timeline.

packages/invoice-dashboard/src/lib/view-requests.svelte (1)

34-34: LGTM! Good refactoring of status check logic.

Moving the checkStatus function to a shared utility follows the DRY principle and promotes code reuse across components.

…162-add-the-rejected-status-to-the-invoice-dashboard
…f github.com:RequestNetwork/web-components into 162-add-the-rejected-status-to-the-invoice-dashboard
@sstefdev sstefdev requested a review from MantisClone November 22, 2024 22:56
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

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 2f524c7 and 8e984de.

📒 Files selected for processing (1)
  • shared/utils/checkStatus.ts (1 hunks)
🔇 Additional comments (1)
shared/utils/checkStatus.ts (1)

1-2: LGTM!

The imports are appropriate and necessary for the functionality.

@rodrigopavezi
Copy link
Member

@sstefdev It needs to fix merging conflicts.

sstefdev and others added 4 commits November 26, 2024 12:25
…162-add-the-rejected-status-to-the-invoice-dashboard
…f github.com:RequestNetwork/web-components into 162-add-the-rejected-status-to-the-invoice-dashboard
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

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 91d6d0d and 543bee1.

📒 Files selected for processing (1)
  • shared/utils/checkStatus.ts (1 hunks)
🧰 Additional context used
📓 Learnings (1)
shared/utils/checkStatus.ts (1)
Learnt from: MantisClone
PR: RequestNetwork/web-components#205
File: shared/utils/checkStatus.ts:11-24
Timestamp: 2024-11-25T22:26:01.581Z
Learning: When determining the status of a request, use `some()` to check for "cancel" or "reject" events, as they may not be the last events in the sequence.
🪛 Biome (1.9.4)
shared/utils/checkStatus.ts

[error] 15-15: isNaN is unsafe. It attempts a type coercion. Use Number.isNaN instead.

See the MDN documentation for more details.
Unsafe fix: Use Number.isNaN instead.

(lint/suspicious/noGlobalIsNan)

🔇 Additional comments (2)
shared/utils/checkStatus.ts (2)

1-4: LGTM!

The imports and function signature are well-defined and appropriate for the task.


9-9: 🛠️ Refactor suggestion

Move isPaid declaration after date validation.

The isPaid status is currently determined before date validation, which could lead to incorrect status precedence. Consider moving this after the date validation to ensure proper status handling.

-  const isPaid = balance >= expectedAmount ? "Paid" : "Partially Paid";
+  const getPaymentStatus = () => balance >= expectedAmount ? "Paid" : "Partially Paid";

Likely invalid or redundant comment.

@rodrigopavezi rodrigopavezi self-requested a review November 26, 2024 12:42
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.

Add the "Overdue" Status to the Invoice Dashboard Add the "Rejected" status to the Invoice Dashboard

4 participants