Skip to content

fix: lock before generating invoice number#1243

Merged
tarunnjoshi merged 5 commits intodevelopfrom
fix/inv-number-race-condition
May 30, 2025
Merged

fix: lock before generating invoice number#1243
tarunnjoshi merged 5 commits intodevelopfrom
fix/inv-number-race-condition

Conversation

@pokhiii
Copy link
Copy Markdown
Member

@pokhiii pokhiii commented May 30, 2025

Update logic for invoice number generation.

Why using transaction directly won't work

In our previous logic, we were asking MySQL:

Look across the whole table and tell me the biggest invoice number so far.

But even if we run this inside a transaction, there is nothing to lock, because:

  • We are not selecting one unique row.
  • We are not using FOR UPDATE on a known, specific row.
  • MySQL won’t prevent another query from reading the same max value in a concurrent transaction.

So two processes still get the same max invoice, both think “I’ll use 153”, and you get duplicates.

Why saving in option value Fixes This

  • Locks one specific row
  • Prevents any other transaction from accessing it until you’re done
  • Makes our increment + update atomic

Inside a transaction, this row is locked — no one else can increment until we finish.

Summary by CodeRabbit

  • Bug Fixes
    • Improved handling of missing or invalid data during campaign and invoice processing, reducing the chance of errors.
  • Refactor
    • Enhanced the process for generating invoice numbers to ensure greater reliability and accuracy.

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented May 30, 2025

Walkthrough

This change refactors invoice number generation in the CollectionCampService class to use a transactional sequence stored in the civicrm_option_value table, ensuring atomic updates. It also adds early return checks in the campaign update method to prevent unnecessary processing when required IDs are missing.

Changes

File(s) Change Summary
wp-content/civi-extensions/goonjcustom/Civi/CollectionCampService.php Refactored invoice number generation to use a transactional sequence in civicrm_option_value; added early return checks in campaign update method.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant CollectionCampService
    participant DB

    User->>CollectionCampService: generateInvoiceNumber(op, objectName, objectId, objectRef)
    CollectionCampService->>DB: Begin Transaction
    CollectionCampService->>DB: SELECT sequence row FOR UPDATE
    alt Sequence not initialized
        CollectionCampService->>User: Throw Exception
        DB-->>CollectionCampService: Rollback
    else
        CollectionCampService->>DB: Increment sequence value
        CollectionCampService->>DB: UPDATE sequence value
        CollectionCampService->>DB: UPDATE contribution with new invoice number
        CollectionCampService->>DB: Commit
        CollectionCampService->>User: Log assignment
    end
Loading

Possibly related PRs

Suggested labels

status : ready for review

Suggested reviewers

  • pokhiii

Poem

In the land where invoices grow,
A sequence now keeps the flow.
Transactions guard the sacred count,
No duplicate numbers to surmount.
Early exits, checks in place—
Clean and tidy, code with grace!
🎉


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 1cef00c and afd080a.

📒 Files selected for processing (1)
  • wp-content/civi-extensions/goonjcustom/Civi/CollectionCampService.php (2 hunks)
🔇 Additional comments (4)
wp-content/civi-extensions/goonjcustom/Civi/CollectionCampService.php (4)

1539-1546: LGTM! Good defensive programming practices.

The early return checks prevent unnecessary processing when required IDs are missing, improving code efficiency and clarity.


1687-1689: LGTM! Well-structured early return condition.

The consolidated condition efficiently handles all necessary checks in a single statement, improving code readability and following the early return pattern.


1693-1720: Excellent implementation of atomic invoice number generation!

The transaction with SELECT FOR UPDATE locking effectively prevents race conditions during invoice number generation. This directly addresses the PR objectives and ensures data consistency.


1727-1737: Robust transaction management and error handling.

The implementation properly commits successful transactions and rolls back on exceptions, with appropriate logging for both success and error scenarios. This ensures data consistency and provides good debugging visibility.

✨ 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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 generate sequence diagram to generate a sequence diagram of the changes in 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.

Comment on lines -1674 to -1676
if (!$contributionId) {
return;
}
Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

This was removed because this was already being ensured earlier in the method:

if ($objectName !== 'Contribution' || !$objectRef->id) {
  return;
}

@pokhiii pokhiii marked this pull request as ready for review May 30, 2025 12:36
Copy link
Copy Markdown

@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

🧹 Nitpick comments (2)
wp-content/civi-extensions/goonjcustom/Civi/CollectionCampService.php (2)

1708-1712: Add validation for the invoice number components

The code assumes the database values are valid but doesn't validate the prefix format or check for integer overflow.

Consider adding validation:

       $last = (int) $dao->value;
       $prefix = $dao->label;
+      
+      // Validate prefix format
+      if (!preg_match('/^[A-Z0-9_\/-]+$/', $prefix)) {
+        throw new \Exception("Invalid invoice prefix format");
+      }
+      
+      // Check for potential overflow
+      if ($last >= PHP_INT_MAX - 1) {
+        throw new \Exception("Invoice sequence number overflow");
+      }
+      
       $next = $last + 1;
       $newInvoice = $prefix . $next;

1695-1720: Consider using CiviCRM's API for consistency

The method uses direct SQL queries for option value operations while using the API for contribution updates. This inconsistency makes the code harder to maintain.

While the current implementation works correctly for ensuring atomicity, consider investigating if CiviCRM's API supports the necessary locking mechanisms. If not, document why direct SQL is necessary here for future maintainers.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 7296ce5 and 1cef00c.

📒 Files selected for processing (1)
  • wp-content/civi-extensions/goonjcustom/Civi/CollectionCampService.php (2 hunks)
🔇 Additional comments (3)
wp-content/civi-extensions/goonjcustom/Civi/CollectionCampService.php (3)

1539-1542: Good defensive programming practice!

Adding this early return check prevents unnecessary processing when sourceID is falsy, improving code efficiency and preventing potential null reference issues downstream.


1544-1547: Excellent null check addition!

This early return prevents further processing when contributionCampaignId is falsy, maintaining consistency with the defensive programming approach used throughout the method.


1693-1720: Excellent implementation of atomic invoice number generation!

The use of database transactions with SELECT ... FOR UPDATE properly addresses the race condition issue mentioned in the PR title. This ensures that concurrent requests won't generate duplicate invoice numbers. The transaction management with proper rollback on failure is a best practice for maintaining data integrity.

Comment on lines +1705 to 1706
throw new \Exception("Invoice sequence not initialized for prefix $invoiceSeqName");
}
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue

Security consideration: Avoid exposing internal implementation details

The exception message reveals the internal naming convention of your invoice sequences, which could be useful information for attackers.

Consider using a more generic error message:

-        throw new \Exception("Invoice sequence not initialized for prefix $invoiceSeqName");
+        throw new \Exception("Invoice sequence not properly initialized");

Log the detailed error internally for debugging purposes while keeping the exception message generic.

🤖 Prompt for AI Agents
In wp-content/civi-extensions/goonjcustom/Civi/CollectionCampService.php at
lines 1705-1706, the exception message exposes internal invoice sequence naming
details. Replace the detailed message with a generic error message like "Invoice
sequence initialization error." Log the original detailed message internally for
debugging without exposing it in the exception thrown.

$params = [
1 => [$invoicePrefix . '%', 'String'],
];
$invoiceSeqName = 'GNJCRM_25_26';
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider making the invoice sequence name configurable

The hardcoded value 'GNJCRM_25_26' appears to be fiscal year specific. This will require code changes every fiscal year, which violates the DRY principle and creates a maintenance burden.

Consider these alternatives:

  1. Make it a class constant that can be easily updated
  2. Retrieve it from a configuration setting
  3. Calculate it dynamically based on the current fiscal year

Example implementation for option 3:

-      $invoiceSeqName = 'GNJCRM_25_26';
+      $currentYear = date('y');
+      $nextYear = ($currentYear + 1) % 100;
+      $invoiceSeqName = sprintf('GNJCRM_%02d_%02d', $currentYear, $nextYear);
🤖 Prompt for AI Agents
In wp-content/civi-extensions/goonjcustom/Civi/CollectionCampService.php at line
1691, the invoice sequence name is hardcoded as 'GNJCRM_25_26', which is fiscal
year specific and requires manual updates each year. To fix this, refactor the
code to avoid hardcoding by either defining the sequence name as a class
constant, fetching it from a configuration setting, or dynamically generating it
based on the current fiscal year. This will reduce maintenance overhead and
adhere to the DRY principle.

@tarunnjoshi tarunnjoshi merged commit 4aa3e0c into develop May 30, 2025
1 check was pending
@tarunnjoshi tarunnjoshi deleted the fix/inv-number-race-condition branch May 30, 2025 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.

2 participants