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: Add support for skip expense post import of expenses #712

Open
wants to merge 6 commits into
base: master
Choose a base branch
from

Conversation

ashwin1111
Copy link
Contributor

@ashwin1111 ashwin1111 commented Jan 2, 2025

Description

Please add PR description here, add screenshots if needed

Clickup

https://app.clickup.com/

Summary by CodeRabbit

  • New Features

    • Added functionality to skip expenses before export based on specific filters.
    • Introduced a new method to mark expenses as skipped with enhanced return capabilities.
  • Tests

    • Added a new test case to validate expense skipping functionality.
  • Improvements

    • Enhanced expense management workflow by adding pre-export expense filtering.
    • Improved task chain creation with additional filtering logic based on workspace ID.

Copy link

coderabbitai bot commented Jan 2, 2025

Walkthrough

This pull request modifies the Fyle application by updating the mark_expenses_as_skipped function to return a list of skipped expenses instead of None. It introduces a new function, skip_expenses_pre_export, for handling expense skipping prior to export, and updates the QuickBooks Online queue to incorporate filtering based on expense groups. Additionally, a new test case is added to validate the new functionality, enhancing the overall expense management process.

Changes

File Change Summary
apps/fyle/actions.py Modified mark_expenses_as_skipped to return List[Expense] instead of None.
apps/fyle/tasks.py Added skip_expenses_pre_export function to handle pre-export expense skipping and imported Error.
apps/quickbooks_online/queue.py Added ExpenseFilter import and logic to filter expense groups before export.
tests/test_fyle/test_tasks.py Added test_skip_expenses_pre_export test case and updated imports for ExpenseFilter.

Possibly related PRs

  • fix: re structure direct export #717: The changes in this PR also modify the mark_expenses_as_skipped function in apps/fyle/actions.py, enhancing its return type and functionality, which directly relates to the changes made in the main PR.

Suggested labels

deploy

Suggested reviewers

  • ashwin1111

Poem

🐰 Hopping through expenses with glee,
Skipping filters, setting data free!
Pre-export magic, clean and bright,
Expense management taking flight!
A rabbit's code, precise and neat 🚀

Finishing Touches

  • 📝 Generate Docstrings (Beta)

🪧 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.

@github-actions github-actions bot added the size/M Medium PR label Jan 2, 2025
Copy link

github-actions bot commented Jan 2, 2025

Tests Skipped Failures Errors Time
269 0 💤 0 ❌ 0 🔥 49.099s ⏱️

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

🔭 Outside diff range comments (1)
apps/fyle/actions.py (1)

Line range hint 127-161: Update the docstring to reflect the return value.

The docstring currently states “:return: None” but the method returns a list of skipped expenses. Keeping the docstring accurate helps maintain code clarity.

- :return: None
+ :return: List[Expense]
🧹 Nitpick comments (1)
tests/test_fyle/test_tasks.py (1)

214-239: Consider verifying skipped outcomes in your new test.

This test successfully demonstrates the workflow for filtering and attempting to skip expenses. However, there are no final assertions confirming that the skipped expenses are indeed marked as skipped or removed from their groups.

You might add simple post-call assertions similar to:

assert Expense.objects.filter(is_skipped=True).exists()

to confirm the result.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between d9c69ca and ac47631.

📒 Files selected for processing (4)
  • apps/fyle/actions.py (2 hunks)
  • apps/fyle/tasks.py (2 hunks)
  • apps/quickbooks_online/queue.py (2 hunks)
  • tests/test_fyle/test_tasks.py (2 hunks)
🔇 Additional comments (6)
tests/test_fyle/test_tasks.py (2)

11-11: Import for ExpenseFilter looks good.

This addition is aligned with the new test scenario for skipping expenses. The usage here appears consistent with the rest of the file.


17-18: Newly imported skip_expenses_pre_export is consistent with usage.

It's logical to include this in the import list because the new test function will verify its behavior.

apps/fyle/tasks.py (2)

21-21: Import of Error is suitably placed.

The new import aligns with the usage in the skip_expenses_pre_export function.


322-356: Overall logic for skipping expenses is solid.

The function persistently marks matching expenses as skipped, manages associated logs/errors, and removes empty groups. This appears coherent for the intended workflow.

apps/quickbooks_online/queue.py (2)

9-9: Import of ExpenseFilter is consistent with usage.

This import is needed to detect and skip qualified expense groups before export.


95-99: Pre-export skip in chain tasks is correctly placed.

Calling skip_expenses_pre_export before running the main export tasks ensures that only valid, unskipped expenses proceed. This placement is logical and should not disrupt existing flows.

Copy link

github-actions bot commented Jan 3, 2025

Tests Skipped Failures Errors Time
269 0 💤 0 ❌ 0 🔥 55.238s ⏱️

Copy link

github-actions bot commented Jan 8, 2025

Tests Skipped Failures Errors Time
269 0 💤 0 ❌ 0 🔥 59.722s ⏱️

Copy link

github-actions bot commented Jan 8, 2025

Tests Skipped Failures Errors Time
269 0 💤 1 ❌ 0 🔥 1m 9s ⏱️

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

🧹 Nitpick comments (2)
apps/fyle/tasks.py (2)

322-356: Add transaction handling and optimize bulk operations.

Consider the following improvements to ensure data consistency and better performance:

  1. Wrap operations in a transaction to ensure atomicity
  2. Use bulk operations for removing expenses from groups
 def skip_expenses_pre_export(workspace_id: int, expense_group_ids: List[int]) -> None:
+    from django.db import transaction
+
     expense_filters = ExpenseFilter.objects.filter(workspace_id=workspace_id).order_by('rank')
     if expense_filters:
-        workspace = Workspace.objects.get(pk=workspace_id)
-        expense_ids_queued = Expense.objects.filter(expensegroup__id__in=expense_group_ids).values_list('id', flat=True)
-        filtered_expense_query = construct_expense_filter_query(expense_filters)
-        skipped_expenses = mark_expenses_as_skipped(filtered_expense_query, expense_ids_queued, workspace)
+        with transaction.atomic():
+            workspace = Workspace.objects.get(pk=workspace_id)
+            expense_ids_queued = Expense.objects.filter(expensegroup__id__in=expense_group_ids).values_list('id', flat=True)
+            filtered_expense_query = construct_expense_filter_query(expense_filters)
+            skipped_expenses = mark_expenses_as_skipped(filtered_expense_query, expense_ids_queued, workspace)

             if skipped_expenses:
                 skipped_expense_ids = [expense.id for expense in skipped_expenses]
                 logger.info('Skipping expenses before export %s', skipped_expense_ids)

-                expense_groups = ExpenseGroup.objects.filter(expenses__id__in=skipped_expense_ids)
+                # Bulk delete related records
+                TaskLog.objects.filter(
+                    workspace_id=workspace_id,
+                    expense_group_id__in=ExpenseGroup.objects.filter(
+                        expenses__id__in=skipped_expense_ids
+                    ).values_list('id', flat=True)
+                ).delete()
+
+                Error.objects.filter(
+                    workspace_id=workspace_id,
+                    expense_group_id__in=ExpenseGroup.objects.filter(
+                        expenses__id__in=skipped_expense_ids
+                    ).values_list('id', flat=True)
+                ).delete()

336-338: Consider adding post-skip notification.

The function logs skipped expense IDs but doesn't notify the user. Consider adding a notification mechanism to inform users about skipped expenses.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between ac47631 and 4dc9d7e.

📒 Files selected for processing (4)
  • apps/fyle/actions.py (2 hunks)
  • apps/fyle/tasks.py (2 hunks)
  • apps/quickbooks_online/queue.py (2 hunks)
  • tests/test_fyle/test_tasks.py (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/quickbooks_online/queue.py
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: pytest
🔇 Additional comments (2)
apps/fyle/actions.py (1)

Line range hint 124-159: LGTM! Return type change improves function reusability.

The modification to return skipped expenses and removal of the expensegroup__isnull=True condition makes the function more versatile, allowing it to be used in both pre-export and post-import scenarios.

apps/fyle/tasks.py (1)

322-356: Verify integration with existing export workflow.

Please ensure that this new pre-export skipping functionality integrates properly with the existing export workflow, particularly in:

  1. QuickBooks Online queue processing
  2. Export status tracking
  3. Error handling and reporting
✅ Verification successful

Integration with export workflow verified successfully

The skip_expenses_pre_export function is properly integrated into the QuickBooks Online export workflow:

  • Correctly placed in the task chain before expense updates
  • Followed by appropriate sync operations
  • Covered by test cases
  • Protected by the chain task system's error handling
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for proper integration with export workflow

# Look for export workflow integration points
rg -A 5 "skip_expenses_pre_export" --type python

# Check for proper error handling in export workflow
ast-grep --pattern 'try {
  $$$
  skip_expenses_pre_export($_, $_)
  $$$
} catch ($err) {
  $$$
}'

Length of output: 180


Script:

#!/bin/bash
# Find all occurrences and usages of skip_expenses_pre_export
rg "skip_expenses_pre_export" -B 2 -A 5

# Look for try-except blocks around this function
ast-grep --pattern 'try:
  $$$
  skip_expenses_pre_export($$$)
  $$$
except $$$:
  $$$'

# Find related export workflow files
rg "export.*workflow|export.*queue" -B 2 -A 2

Length of output: 2459

tests/test_fyle/test_tasks.py Outdated Show resolved Hide resolved
Copy link

Tests Skipped Failures Errors Time
271 0 💤 1 ❌ 0 🔥 1m 18s ⏱️

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

🔭 Outside diff range comments (1)
tests/test_fyle/test_tasks.py (1)

Line range hint 1-211: Add missing test function for skip_expenses_pre_export.

The AI summary indicates that a new test function test_skip_expenses_pre_export should be present to test the new functionality, but it's missing from the code.

Would you like me to help you generate the test function? Based on the past review comments, I can help create a comprehensive test that:

  1. Sets up expense filters
  2. Creates test expenses
  3. Verifies the initial state
  4. Calls skip_expenses_pre_export
  5. Verifies the final state
🧰 Tools
🪛 Ruff (0.8.2)

12-12: apps.fyle.models.ExpenseFilter imported but unused

Remove unused import: apps.fyle.models.ExpenseFilter

(F401)


19-19: apps.fyle.tasks.skip_expenses_pre_export imported but unused

Remove unused import: apps.fyle.tasks.skip_expenses_pre_export

(F401)

🪛 GitHub Actions: Continuous Integration

[error] 12-12: Import 'apps.fyle.models.ExpenseFilter' is unused


[error] 13-13: Import 'apps.fyle.tasks.skip_expenses_pre_export' is unused

🧹 Nitpick comments (1)
tests/test_fyle/test_tasks.py (1)

211-211: Remove extra blank line at the end of file.

Remove the extra blank line at the end of the file.

🧰 Tools
🪛 GitHub Actions: Continuous Integration

[warning] 211-211: Blank line found at end of file

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 4dc9d7e and 7597d85.

📒 Files selected for processing (1)
  • tests/test_fyle/test_tasks.py (2 hunks)
🧰 Additional context used
🪛 Ruff (0.8.2)
tests/test_fyle/test_tasks.py

12-12: apps.fyle.models.ExpenseFilter imported but unused

Remove unused import: apps.fyle.models.ExpenseFilter

(F401)


19-19: apps.fyle.tasks.skip_expenses_pre_export imported but unused

Remove unused import: apps.fyle.tasks.skip_expenses_pre_export

(F401)

🪛 GitHub Actions: Continuous Integration
tests/test_fyle/test_tasks.py

[error] 12-12: Import 'apps.fyle.models.ExpenseFilter' is unused


[error] 13-13: Import 'apps.fyle.tasks.skip_expenses_pre_export' is unused


[warning] 211-211: Blank line found at end of file

tests/test_fyle/test_tasks.py Show resolved Hide resolved
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
size/M Medium PR
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants