Skip to content

fix: Improve recurring invoicing due date calculation logic - #34

Merged
rodrigopavezi merged 1 commit into
mainfrom
fix/recurring-invoice-due-date
Mar 10, 2025
Merged

fix: Improve recurring invoicing due date calculation logic#34
rodrigopavezi merged 1 commit into
mainfrom
fix/recurring-invoice-due-date

Conversation

@rodrigopavezi

@rodrigopavezi rodrigopavezi commented Mar 10, 2025

Copy link
Copy Markdown
Contributor

Problem

Due date calculation was facing rounding issues so creating wrong due dates for the recurring invoices.

Changes

Use UTC dates to avoid rounding and timezones issues

Summary by CodeRabbit

  • Bug Fixes
    • Improved the scheduling of recurring due dates to ensure dates are set accurately regardless of time zone differences.
    • The update refines the underlying logic to provide more consistent and reliable timing for recurring tasks, reducing potential discrepancies.
    • Users will experience improved confidence in managing recurring task deadlines with these enhancements.

@coderabbitai

coderabbitai Bot commented Mar 10, 2025

Copy link
Copy Markdown
Contributor

Walkthrough

The change modifies the calculation logic for the new due date in the webhook route’s POST function. Instead of adding the original interval between the issued and due dates to the current date, the new approach sets the current date and the original dates to midnight UTC, computes the difference in days between the issued and due dates, and then adds this difference to the current date. This adjustment ensures that all date calculations are performed in UTC.

Changes

File Change Summary
src/.../webhook/route.ts Updated the POST function to convert the current, issued, and due dates to midnight UTC. Calculated the days difference instead of using the original interval, and computed the new due date by adding this days difference to the UTC-normalized current date.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant WebhookHandler
    participant DateUtils

    Client->>WebhookHandler: Send POST request for recurring request
    WebhookHandler->>DateUtils: Get current date (set to midnight UTC)
    DateUtils-->>WebhookHandler: Return current UTC date
    WebhookHandler->>DateUtils: Normalize issued and due dates to midnight UTC
    DateUtils-->>WebhookHandler: Return normalized dates
    WebhookHandler->>WebhookHandler: Calculate days difference between dates
    WebhookHandler->>DateUtils: Add days difference to current date
    DateUtils-->>WebhookHandler: Return new due date
    WebhookHandler->>Client: Respond with updated due date
Loading
✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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.
  • @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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

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 (1)
src/app/api/webhook/route.ts (1)

69-93: Consider using a date utility library

While the current implementation is correct, consider using a date utility library like date-fns or Luxon for more readable and maintainable date operations. These libraries provide dedicated functions for day-difference calculations and date manipulations that could simplify this code.

- // Calculate the difference in days between original issue and due dates
- const originalIssuedDate = new Date(issuedDate);
- originalIssuedDate.setUTCHours(0, 0, 0, 0); // Set to midnight UTC due to rounding
- 
- const originalDueDate = new Date(dueDate);
- originalDueDate.setUTCHours(0, 0, 0, 0); // Set to midnight UTC due to rounding
- 
- // Calculate days difference using UTC dates to avoid timezone issues
- const daysDifference = Math.max(
-   0,
-   Math.floor(
-     (originalDueDate.getTime() - originalIssuedDate.getTime()) /
-       (24 * 60 * 60 * 1000),
-   ),
- );
- 
- // Calculate new due date by adding the same number of days to the new issue date
- const newDueDate = new Date(now);
- newDueDate.setDate(now.getDate() + daysDifference);
+ // Calculate the difference in days between original issue and due dates using date-fns
+ import { differenceInDays, addDays, startOfDay, parseISO } from 'date-fns';
+ 
+ const originalIssuedDate = startOfDay(parseISO(issuedDate));
+ const originalDueDate = startOfDay(parseISO(dueDate));
+ 
+ // Calculate days difference (ensure it's not negative)
+ const daysDifference = Math.max(0, differenceInDays(originalDueDate, originalIssuedDate));
+ 
+ // Calculate new due date by adding the same number of days
+ const newDueDate = addDays(now, daysDifference);
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 4dd99bb and 9dcff88.

📒 Files selected for processing (1)
  • src/app/api/webhook/route.ts (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Build
🔇 Additional comments (4)
src/app/api/webhook/route.ts (4)

71-72: Good use of UTC standardization for date handling

Setting the current date to midnight UTC is a solid approach to eliminate timezone-related inconsistencies in the due date calculations. This ensures that regardless of where the server is located, the date calculation starts from a consistent reference point.


75-79: Proper normalization of reference dates

Setting both the original issued and due dates to midnight UTC is crucial for accurate day-difference calculation. This approach effectively eliminates any time-of-day variations that could cause rounding errors in the calculation.


82-88: Robust day-difference calculation

The implementation correctly:

  • Uses UTC timestamps to avoid timezone issues
  • Applies Math.floor to ensure whole day counting
  • Uses Math.max to prevent negative durations

This approach effectively addresses the rounding issues mentioned in the PR objectives.


91-92: Clean implementation of new due date calculation

Using the day difference to calculate the new due date ensures consistent intervals between issued and due dates across recurring invoices. This maintains the original payment terms while fixing the date calculation issues.

@rodrigopavezi rodrigopavezi self-assigned this Mar 10, 2025
@rodrigopavezi
rodrigopavezi merged commit 4283a13 into main Mar 10, 2025
@rodrigopavezi
rodrigopavezi deleted the fix/recurring-invoice-due-date branch March 10, 2025 12:25
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