Skip to content

feat(admin): credit off-Stripe payments manually - #3526

Merged
steebchen merged 2 commits into
mainfrom
admin-manual-credit-button
Aug 10, 2026
Merged

steebchen merged 2 commits into
mainfrom
admin-manual-credit-button

Conversation

@steebchen

@steebchen steebchen commented Aug 10, 2026 •

Copy link
Copy Markdown
Member

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_payment transaction 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:

  • Both amount (dollars received) and creditAmount (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.
  • The channel goes into a new transaction.payment_method column (wire / crypto / paypal / other), and the payment's own identifier — bank wire reference, on-chain tx hash, PayPal transaction id — into a new optional transaction.external_reference column. 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 into description.
  • Audited as credits.manual_payment.

Accounting fallout, all in /admin/metrics:

  • Counts toward totalRevenue, totalProcessed and totalToppedUp (it was already inside those filters, which exclude by type — only gifts and plan rows are subtracted).
  • Added to paidTransactionTypes, so the org counts as a paying customer.
  • Gets its own Manual payments split in the gross revenue breakdown and is added into grossRevenue, since these rows never show up in Stripe reporting.
  • computeUsedCredits in 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

  • New apps/api/src/routes/admin-manual-credits.spec.ts covers the endpoint (credits applied, transaction fields, reference stored / left null, rejected payment method, unknown org) and the metrics accounting vs. a gift.
  • Full apps/api unit suite: 909 tests pass. pnpm format + pnpm build clean.
  • Exercised end to end against a local stack — screenshots below are that run ($500 wire on the test org, balance $5 → $505, reference round-tripped into the transactions table).

Screenshots

Add Paid Credits dialog

Add Paid Credits dialog, light

Add Paid Credits dialog, dark

Org transactions table with the new Reference column

Admin org transactions, light

Admin org transactions, dark

Admin dashboard — new "Manual payments" revenue split

Admin dashboard revenue split, light

Admin dashboard revenue split, dark

Customer dashboard — transaction history label

Org transactions, light

Org transactions, dark

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features
    • Administrators can add organization credits for payments received by wire, crypto, PayPal, or other methods.
    • Optional payment references and comments are recorded for reconciliation.
    • Admin dashboards show manual payment revenue and transaction details.
    • Billing history displays manually added credits as “Credits Added.”
  • Bug Fixes
    • Manual payment credits are now included when calculating credit usage and paid activity.

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>
Copilot AI lite review requested due to automatic review settings August 10, 2026 21:36
@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@coderabbitai

coderabbitai Bot commented Aug 10, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Walkthrough

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

Changes

Manual payment credits

Layer / File(s) Summary
Payment transaction contracts and persistence
packages/db/src/schema.ts, packages/db/migrations/..., apps/api/src/routes/organization.ts
Transactions support credit_manual_payment, payment methods, external references, and the credits.manual_payment audit action.
Backend manual-credit flow
apps/api/src/routes/admin.ts, apps/api/src/routes/admin-manual-credits.spec.ts
The admin endpoint validates requests, updates credits transactionally, records completed transactions, logs audit events, exposes metadata, and updates revenue metrics. Tests cover success, validation, organization errors, and metrics.
Admin manual-credit interface
ee/admin/src/components/manual-credits-dialog.tsx, ee/admin/src/lib/admin-organizations.ts, ee/admin/src/app/organizations/[orgId]/page.tsx, ee/admin/src/app/page.tsx
The admin UI collects payment details, submits manual credits, displays external references, and shows manual-payment revenue.
Credit accounting and transaction display
apps/api/src/lib/self-refund.ts, apps/api/src/utils/devpass-filter.ts, apps/playground/src/components/pricing/chat-billing-history.tsx, apps/ui/src/components/billing/transactions-client.tsx
Manual payments count toward used and paid credits and display as “Credits added” or “Credits Added” in billing histories.

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
Loading

Possibly related PRs

Suggested reviewers: smakosh

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 20.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the main change: enabling admins to record off-Stripe payments as credits.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch admin-manual-credit-button

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.

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

🧹 Nitpick comments (1)
apps/api/src/routes/admin.ts (1)

6172-6293: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick win

Add an upper bound on creditAmount.

manualCreditsRoute validates creditAmount with min(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) inflates totalRevenue, grossRevenue, and payingCustomers on the admin dashboard with no easy correction path.

Compare this to autoTopUpAmount in apps/api/src/routes/organization.ts, which caps at CREDIT_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

📥 Commits

Reviewing files that changed from the base of the PR and between 31ecab5 and afd780b.

📒 Files selected for processing (15)
  • apps/api/src/lib/self-refund.ts
  • apps/api/src/routes/admin-manual-credits.spec.ts
  • apps/api/src/routes/admin.ts
  • apps/api/src/routes/organization.ts
  • apps/api/src/utils/devpass-filter.ts
  • apps/playground/src/components/pricing/chat-billing-history.tsx
  • apps/ui/src/components/billing/transactions-client.tsx
  • ee/admin/src/app/organizations/[orgId]/page.tsx
  • ee/admin/src/app/page.tsx
  • ee/admin/src/components/manual-credits-dialog.tsx
  • ee/admin/src/lib/admin-organizations.ts
  • packages/db/migrations/1786396140_eminent_madame_masque.sql
  • packages/db/migrations/meta/1786396140_snapshot.json
  • packages/db/migrations/meta/_journal.json
  • packages/db/src/schema.ts

credit_topup: "Credit top-up",
credit_refund: "Credit refund",
credit_gift: "Credit gift",
credit_manual_payment: "Credits added",

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.

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

Suggested change
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>
@steebchen
steebchen enabled auto-merge (squash) August 10, 2026 22:16

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

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 win

Always clear the loading state when onCredit rejects.

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 in try/catch/finally and set a safe error in the catch block.

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 win

Enforce manual payment idempotency

The route inserts externalReference and 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 win

Add an assertion for the audit record.

The success test verifies the balance and transaction row, but it does not verify the required credits.manual_payment audit 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 win

Assert that rejected requests leave credits unchanged.

The test verifies only that no transaction row exists. It would still pass if the handler updated organization.credits before returning HTTP 400. Reload the organization and assert that its balance remains 10.

🤖 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

📥 Commits

Reviewing files that changed from the base of the PR and between afd780b and d4efaf3.

📒 Files selected for processing (9)
  • apps/api/src/routes/admin-manual-credits.spec.ts
  • apps/api/src/routes/admin.ts
  • ee/admin/src/app/organizations/[orgId]/page.tsx
  • ee/admin/src/components/manual-credits-dialog.tsx
  • ee/admin/src/lib/admin-organizations.ts
  • packages/db/migrations/1786398375_pretty_hedge_knight.sql
  • packages/db/migrations/meta/1786398375_snapshot.json
  • packages/db/migrations/meta/_journal.json
  • packages/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

@steebchen
steebchen merged commit b57c103 into main Aug 10, 2026
13 checks passed
@steebchen
steebchen deleted the admin-manual-credit-button branch August 10, 2026 22:31
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