Repository navigation
feat(admin): credit off-Stripe payments manually - #3526
Conversation
Adds an "Add Paid Credits" action next to Gift Credits in the admin org detail page for money received outside Stripe (wire, crypto, PayPal). Unlike a gift this is real revenue: the new credit_manual_payment transaction type stores both the dollars received (amount) and the credits granted (creditAmount), plus the payment channel in the new transaction.payment_method column. It therefore counts toward total revenue, processed, topped-up credits and paying customers, and gets its own "Manual payments" split in the admin gross revenue breakdown. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
WalkthroughAdmins can record off-Stripe payments as organization credits. The API stores payment metadata, updates balances, logs audit events, and includes manual payments in metrics. Admin pages and billing histories display the new transaction type. ChangesManual payment credits
Estimated code review effort: 4 (Complex) | ~45 minutes Sequence Diagram(s)sequenceDiagram
participant Admin
participant ManualCreditsDialog
participant AdminServerAction
participant AdminAPI
participant Database
participant RevenueMetrics
Admin->>ManualCreditsDialog: enter amount and payment details
ManualCreditsDialog->>AdminServerAction: submit manual credit payload
AdminServerAction->>AdminAPI: POST manual-credit request
AdminAPI->>Database: update credits and record transaction
AdminAPI->>Database: write audit event
AdminAPI-->>AdminServerAction: return updated balance
AdminServerAction-->>ManualCreditsDialog: return success or error
AdminAPI->>RevenueMetrics: include completed manual payments
Possibly related PRs
Suggested reviewers: 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
apps/api/src/routes/admin.ts (1)
6172-6293: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick winAdd an upper bound on
creditAmount.
manualCreditsRoutevalidatescreditAmountwithmin(0.01)but no maximum. This transaction is booked directly as revenue and cannot be refunded. A data-entry mistake by an admin (an extra digit) inflatestotalRevenue,grossRevenue, andpayingCustomerson the admin dashboard with no easy correction path.Compare this to
autoTopUpAmountinapps/api/src/routes/organization.ts, which caps atCREDIT_TOP_UP_MAX_AMOUNT. Add a similar cap here.♻️ Proposed fix
+import { CREDIT_TOP_UP_MAX_AMOUNT } from "`@llmgateway/shared`"; + const manualCreditsRoute = createRoute({ method: "post", path: "/organizations/{orgId}/manual-credits", request: { params: z.object({ orgId: z.string(), }), body: { content: { "application/json": { schema: z.object({ creditAmount: z .number() - .min(0.01, "Credit amount must be positive"), + .min(0.01, "Credit amount must be positive") + .max(CREDIT_TOP_UP_MAX_AMOUNT, "Credit amount is too large"), paymentMethod: z.enum(manualPaymentMethods), comment: z.string().optional(), }), }, }, }, },🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@apps/api/src/routes/admin.ts` around lines 6172 - 6293, Update the creditAmount validation in manualCreditsRoute to enforce the existing CREDIT_TOP_UP_MAX_AMOUNT upper bound, while preserving the current 0.01 minimum and validation message behavior. Reuse that shared constant rather than introducing a new limit.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@apps/playground/src/components/pricing/chat-billing-history.tsx`:
- Line 50: Update the credit_manual_payment transaction label in the billing
history component from “Credits added” to “Credits Added” so it matches the
capitalization used by transactions-client.tsx.
---
Nitpick comments:
In `@apps/api/src/routes/admin.ts`:
- Around line 6172-6293: Update the creditAmount validation in
manualCreditsRoute to enforce the existing CREDIT_TOP_UP_MAX_AMOUNT upper bound,
while preserving the current 0.01 minimum and validation message behavior. Reuse
that shared constant rather than introducing a new limit.
🪄 Autofix
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 707d3dc8-afbd-4329-864d-4cd8dab88f57
📒 Files selected for processing (15)
apps/api/src/lib/self-refund.tsapps/api/src/routes/admin-manual-credits.spec.tsapps/api/src/routes/admin.tsapps/api/src/routes/organization.tsapps/api/src/utils/devpass-filter.tsapps/playground/src/components/pricing/chat-billing-history.tsxapps/ui/src/components/billing/transactions-client.tsxee/admin/src/app/organizations/[orgId]/page.tsxee/admin/src/app/page.tsxee/admin/src/components/manual-credits-dialog.tsxee/admin/src/lib/admin-organizations.tspackages/db/migrations/1786396140_eminent_madame_masque.sqlpackages/db/migrations/meta/1786396140_snapshot.jsonpackages/db/migrations/meta/_journal.jsonpackages/db/src/schema.ts
| credit_topup: "Credit top-up", | ||
| credit_refund: "Credit refund", | ||
| credit_gift: "Credit gift", | ||
| credit_manual_payment: "Credits added", |
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win
Use consistent capitalization for the transaction label.
apps/ui/src/components/billing/transactions-client.tsx uses Credits Added at Lines 371-372 and 537-538. This file uses Credits added. Use the same label in both clients.
Proposed fix
- credit_manual_payment: "Credits added",
+ credit_manual_payment: "Credits Added",📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| credit_manual_payment: "Credits added", | |
| credit_manual_payment: "Credits Added", |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@apps/playground/src/components/pricing/chat-billing-history.tsx` at line 50,
Update the credit_manual_payment transaction label in the billing history
component from “Credits added” to “Credits Added” so it matches the
capitalization used by transactions-client.tsx.
Adds an optional Transaction ID / Reference field to the Add Paid Credits dialog, stored in a new transaction.external_reference column (bank wire reference, on-chain tx hash, PayPal transaction id). It is a column rather than free text in the description so a credit can be reconciled against the payment that funded it. The admin org transactions table gains a Reference column, and the two migrations from this branch are squashed into one. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
ee/admin/src/components/manual-credits-dialog.tsx (1)
68-89: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick winAlways clear the loading state when
onCreditrejects.If the server action or network request rejects, execution stops before
setLoading(false). The dialog then remains disabled and the user receives no error message. Wrap the call intry/catch/finallyand set a safe error in thecatchblock.Proposed error handling
setLoading(true); setError(null); - const result = await onCredit({ - creditAmount: amount, - paymentMethod, - externalReference: externalReference.trim() || undefined, - comment: comment.trim() || undefined, - }); - - setLoading(false); - - if (result.success) { - setOpen(false); - setCreditAmount(""); - setPaymentMethod("wire"); - setExternalReference(""); - setComment(""); - router.refresh(); - } else { - setError(result.error ?? "Failed to add credits"); + try { + const result = await onCredit({ + creditAmount: amount, + paymentMethod, + externalReference: externalReference.trim() || undefined, + comment: comment.trim() || undefined, + }); + + if (result.success) { + setOpen(false); + setCreditAmount(""); + setPaymentMethod("wire"); + setExternalReference(""); + setComment(""); + router.refresh(); + } else { + setError(result.error ?? "Failed to add credits"); + } + } catch { + setError("Failed to add credits"); + } finally { + setLoading(false); }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@ee/admin/src/components/manual-credits-dialog.tsx` around lines 68 - 89, The manual credit submission flow around onCredit must handle rejected requests. Wrap the onCredit call and result handling in try/catch/finally, set a safe error message in catch, and move setLoading(false) into finally so loading always clears while preserving the existing success and result-error behavior.packages/db/src/schema.ts (1)
502-512: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick winEnforce manual payment idempotency
The route inserts
externalReferenceand credits the organization without a duplicate check. Repeating a manual payment request creates duplicate credits. Define the uniqueness scope, enforce it atomically for non-null references, and add a duplicate-reference test. If references may be reused, document that rule.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/db/src/schema.ts` around lines 502 - 512, Enforce idempotency for manual payments by defining the allowed uniqueness scope for non-null externalReference values and applying it atomically in the manual payment creation flow, rather than relying on a pre-check. Update the relevant manual-payment route and schema symbols to reject duplicate references without creating another credit, and add a test covering repeated requests with the same reference; document reuse behavior if references are intentionally scoped or reusable.
🧹 Nitpick comments (2)
apps/api/src/routes/admin-manual-credits.spec.ts (2)
39-76: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick winAdd an assertion for the audit record.
The success test verifies the balance and transaction row, but it does not verify the required
credits.manual_paymentaudit entry. A regression can remove or mislabel the audit event while this test remains green. Assert the audit action and its organization or transaction target.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@apps/api/src/routes/admin-manual-credits.spec.ts` around lines 39 - 76, Add an assertion in the “credits the org and records a manual payment transaction” test that queries the audit records created by the request and verifies a credits.manual_payment entry with the expected organization or transaction target.
96-111: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick winAssert that rejected requests leave credits unchanged.
The test verifies only that no transaction row exists. It would still pass if the handler updated
organization.creditsbefore returning HTTP 400. Reload the organization and assert that its balance remains10.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@apps/api/src/routes/admin-manual-credits.spec.ts` around lines 96 - 111, Extend the “rejects an unknown payment method” test to reload the organization after the request and assert its credits balance remains 10. Keep the existing transaction-count assertion, using the organization lookup established in the test suite.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Outside diff comments:
In `@ee/admin/src/components/manual-credits-dialog.tsx`:
- Around line 68-89: The manual credit submission flow around onCredit must
handle rejected requests. Wrap the onCredit call and result handling in
try/catch/finally, set a safe error message in catch, and move setLoading(false)
into finally so loading always clears while preserving the existing success and
result-error behavior.
In `@packages/db/src/schema.ts`:
- Around line 502-512: Enforce idempotency for manual payments by defining the
allowed uniqueness scope for non-null externalReference values and applying it
atomically in the manual payment creation flow, rather than relying on a
pre-check. Update the relevant manual-payment route and schema symbols to reject
duplicate references without creating another credit, and add a test covering
repeated requests with the same reference; document reuse behavior if references
are intentionally scoped or reusable.
---
Nitpick comments:
In `@apps/api/src/routes/admin-manual-credits.spec.ts`:
- Around line 39-76: Add an assertion in the “credits the org and records a
manual payment transaction” test that queries the audit records created by the
request and verifies a credits.manual_payment entry with the expected
organization or transaction target.
- Around line 96-111: Extend the “rejects an unknown payment method” test to
reload the organization after the request and assert its credits balance remains
10. Keep the existing transaction-count assertion, using the organization lookup
established in the test suite.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 947e15e7-0b45-44f3-a73a-37ffa5afb63a
📒 Files selected for processing (9)
apps/api/src/routes/admin-manual-credits.spec.tsapps/api/src/routes/admin.tsee/admin/src/app/organizations/[orgId]/page.tsxee/admin/src/components/manual-credits-dialog.tsxee/admin/src/lib/admin-organizations.tspackages/db/migrations/1786398375_pretty_hedge_knight.sqlpackages/db/migrations/meta/1786398375_snapshot.jsonpackages/db/migrations/meta/_journal.jsonpackages/db/src/schema.ts
🚧 Files skipped from review as they are similar to previous changes (2)
- apps/api/src/routes/admin.ts
- ee/admin/src/lib/admin-organizations.ts
Problem
Gifting credits is the only way an admin can move credits into an org, and a gift is deliberately excluded from every revenue metric. When a customer pays us on another channel — wire transfer, crypto, PayPal — there was no way to record that: gifting them the credits silently understated revenue, and nothing in the database distinguished "free credits we gave away" from "credits someone actually paid for".
Approach
Adds an Add Paid Credits action next to Gift Credits on the admin org detail page, backed by a new
credit_manual_paymenttransaction type.It behaves like a gift operationally (admin enters an amount, credits land on the org balance) but is accounted for as a real purchase:
amount(dollars received) andcreditAmount(credits granted) are set to the entered figure — there are no Stripe fees to net out on an off-Stripe channel, so processed − revenue stays 0 for these rows.transaction.payment_methodcolumn (wire/crypto/paypal/other), and the payment's own identifier — bank wire reference, on-chain tx hash, PayPal transaction id — into a new optionaltransaction.external_referencecolumn. Both are columns rather than free text so manual revenue can be reconciled per channel and each credit traced back to the money that funded it. The optional comment still goes intodescription.credits.manual_payment.Accounting fallout, all in
/admin/metrics:totalRevenue,totalProcessedandtotalToppedUp(it was already inside those filters, which exclude by type — only gifts and plan rows are subtracted).paidTransactionTypes, so the org counts as a paying customer.grossRevenue, since these rows never show up in Stripe reporting.computeUsedCreditsin the self-refund path now counts it as a grant, so manually credited balances can't be burned and then refunded against an earlier Stripe top-up. The type itself is not self-refundable — there's no PaymentIntent to refund.The admin org transactions table gains a Reference column so the identifier is visible where the payments are reviewed.
The button sits on the org detail page only (not the DevPass subscriber page): the DevPass revenue reports are Stripe-invoice shaped, and a manual credit on a devpass org would read inconsistently there.
Verification
apps/api/src/routes/admin-manual-credits.spec.tscovers the endpoint (credits applied, transaction fields, reference stored / left null, rejected payment method, unknown org) and the metrics accounting vs. a gift.apps/apiunit suite: 909 tests pass.pnpm format+pnpm buildclean.Screenshots
Add Paid Credits dialog
Org transactions table with the new Reference column
Admin dashboard — new "Manual payments" revenue split
Customer dashboard — transaction history label
🤖 Generated with Claude Code
Summary by CodeRabbit