Skip to content

fix: credit purchase adapter issues - #4068

Merged
turip merged 1 commit into
mainfrom
fix/credit-purchase-flow
Apr 2, 2026
Merged

turip merged 1 commit into
mainfrom
fix/credit-purchase-flow

Conversation

@turip

@turip turip commented Apr 2, 2026 •

Copy link
Copy Markdown
Member

Overview

Fixes two bugs:

  • no credit realization for negative credit was done on promotional credits
  • add support for invoice settlement type (and simplify type handling)

Notes for reviewer

Summary by CodeRabbit

  • Refactor

    • Consolidated credit-purchase billing logic to reduce duplication and ensure consistent handling across payment flows.
    • Unified cost-basis usage so issuance, authorization, and settlement steps all derive and apply the same value.
  • Bug Fixes

    • Improved validation and error handling for settlement cost-basis lookups to avoid silent failures during billing and settlement.

@turip
turip requested a review from a team as a code owner April 2, 2026 14:54
@coderabbitai

coderabbitai Bot commented Apr 2, 2026 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

Adds Settlement.GetCostBasis() to return a settlement's cost basis by type. Consolidates credit-purchase logic into a shared issueCreditPurchase helper and updates handlers (initiated, promotional, payment-authorized, payment-settled) to use the new getter and unified issuance/settlement flows.

Changes

Cohort / File(s) Summary
Settlement Enhancement
openmeter/billing/charges/creditpurchase/settlement.go
Added GetCostBasis() method that returns an alpacadecimal.Decimal cost basis based on SettlementType, with nil checks and error returns for invoice/external types and zero for promotional/unknown types.
Handler Consolidation
openmeter/ledger/chargeadapter/creditpurchase.go
Introduced issueCreditPurchase helper and OnCreditPurchaseInitiated; refactored OnPromotionalCreditPurchase, OnCreditPurchasePaymentAuthorized, and added/updated OnCreditPurchasePaymentSettled to derive cost basis via Settlement.GetCostBasis() and use unified templates (AttributeCustomerAdvanceReceivableCostBasisTemplate, TranslateCustomerAccruedCostBasisTemplate, IssueCustomerReceivableTemplate, FundCustomerReceivableTemplate, SettleCustomerReceivablePaymentTemplate) and commit transaction groups. Removed duplicated prior logic.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant Handler as CreditPurchaseHandler
    participant Charge as Charge (credit purchase)
    participant Settlement
    participant Templates
    participant Transactions
    participant Ledger

    Client->>Handler: Trigger credit-purchase event (initiated/authorized/settled)
    Handler->>Charge: read charge, intent, settlement
    Charge->>Settlement: GetCostBasis()
    Settlement-->>Handler: costBasis (or error)
    Handler->>Templates: fill attribution/translation/issue/fund/settle templates with costBasis
    Templates-->>Transactions: build transaction(s)
    Transactions->>Ledger: commit transaction group
    Ledger-->>Handler: GroupReference / result
    Handler-->>Client: return GroupReference / error
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

🚥 Pre-merge checks | ✅ 1 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Title check ❓ Inconclusive The title 'fix: credit purchase adapter issues' is vague and doesn't clearly convey the specific changes—it could refer to many different types of fixes without indicating whether it involves new getters, settlement types, or realization logic. Consider a more specific title like 'fix: add settlement cost basis getter and consolidate credit purchase issuance' that better describes the main changes and bug fixes.
✅ Passed checks (1 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/credit-purchase-flow

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

Comment @coderabbitai help to get the list of available commands and usage tips.

@turip
turip requested a review from GAlexIHU April 2, 2026 16:11
@turip turip added release-note/bug-fix Release note: Bug Fixes area/billing labels Apr 2, 2026
GAlexIHU
GAlexIHU previously approved these changes Apr 2, 2026
Fixes two bugs:

- no credit realization for negative credit was done on promotional credits
- add support for invoice settlement type (and simplify type handling)
@turip
turip force-pushed the fix/credit-purchase-flow branch from 09d90d6 to 740e44a Compare April 2, 2026 16:26
@turip
turip enabled auto-merge (squash) April 2, 2026 16:26
@turip
turip requested a review from GAlexIHU April 2, 2026 16:27

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

🧹 Nitpick comments (1)
openmeter/ledger/chargeadapter/creditpurchase.go (1)

191-194: Consider adding a brief comment explaining why accrued attribution is bounded by advance attribution.

The calculation accruedAttributionAmount := advanceAttributionAmount creates a coupling where accrued attribution can never exceed advance attribution. This might be intentional accounting logic, but it's not immediately obvious from reading the code. A short comment here would help future readers understand the business reasoning.

+	// Accrued attribution is bounded by advance attribution because [explain domain reason]
 	accruedAttributionAmount := advanceAttributionAmount
 	if accruedAttributionAmount.GreaterThan(unattributedAccrued) {
 		accruedAttributionAmount = unattributedAccrued
 	}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@openmeter/ledger/chargeadapter/creditpurchase.go` around lines 191 - 194, Add
a short clarifying comment above the bounding logic for accruedAttributionAmount
that explains the business/accounting reason why accrued attribution is capped
by advanceAttributionAmount (i.e., to prevent attributing more than was
advanced) and mention the role of unattributedAccrued in the cap; update the
block around accruedAttributionAmount, advanceAttributionAmount and
unattributedAccrued to include that comment so future readers understand the
intent.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@openmeter/ledger/chargeadapter/creditpurchase.go`:
- Around line 191-194: Add a short clarifying comment above the bounding logic
for accruedAttributionAmount that explains the business/accounting reason why
accrued attribution is capped by advanceAttributionAmount (i.e., to prevent
attributing more than was advanced) and mention the role of unattributedAccrued
in the cap; update the block around accruedAttributionAmount,
advanceAttributionAmount and unattributedAccrued to include that comment so
future readers understand the intent.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: e8cdbf9d-c100-4eb4-99ae-e3e8d635a864

📥 Commits

Reviewing files that changed from the base of the PR and between 09d90d6 and 740e44a.

📒 Files selected for processing (2)
  • openmeter/billing/charges/creditpurchase/settlement.go
  • openmeter/ledger/chargeadapter/creditpurchase.go

@turip
turip merged commit fe83424 into main Apr 2, 2026
24 checks passed
@turip
turip deleted the fix/credit-purchase-flow branch April 2, 2026 16:55
This was referenced May 17, 2026

This branch was previously deployed

1 inactive deployment
dev — 740e44a4 Deployed Apr 2, 2026 by turip via Migration Checks #13181
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants