Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion apps/api/src/lib/self-refund.ts
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,8 @@ function latestOf(rows: TransactionRow[]): TransactionRow | undefined {
/**
* Total credits ever consumed by the org, reconstructed from the pooled
* balance: every credit grant and drain besides gateway usage is recorded
* either as a transaction row (topups, gifts, refunds, end-user bonuses) or on
* either as a transaction row (topups, manual payments, gifts, refunds,
* end-user bonuses) or on
* the org row itself (referral earnings, which are only ever incremented), so
* usage = grants − balance. Referral-bonus reversals aren't reconstructed,
* which only over-counts usage — erring toward denying the refund.
Expand All @@ -160,6 +161,7 @@ function computeUsedCredits(
if (
t.type === "credit_topup" ||
t.type === "credit_gift" ||
t.type === "credit_manual_payment" ||
t.type === "credit_refund"
) {
// credit_refund rows carry a negative creditAmount, netting out the
Expand Down
137 changes: 137 additions & 0 deletions apps/api/src/routes/admin-manual-credits.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
import { afterEach, beforeEach, describe, expect, test } from "vitest";

import { app } from "@/index.js";
import { createTestUser, deleteAll } from "@/testing.js";

import { db, tables } from "@llmgateway/db";

const ORG_ID = "admin-manual-credits-org";

interface AdminMetricsResponse {
totalRevenue: number;
totalProcessed: number;
totalToppedUp: number;
totalGiftedCredits: number;
payingCustomers: number;
grossRevenue: number;
grossManualPaymentsRevenue: number;
}

describe("admin manual credits", () => {
let cookie: string;

beforeEach(async () => {
process.env.ADMIN_EMAILS = "admin@example.com";
cookie = await createTestUser();

await db.insert(tables.organization).values({
id: ORG_ID,
name: "Manual Credits Org",
billingEmail: "manual@example.com",
credits: "10",
});
});

afterEach(async () => {
await deleteAll();
});

test("credits the org and records a manual payment transaction", async () => {
const res = await app.request(
`/admin/organizations/${ORG_ID}/manual-credits`,
{
method: "POST",
headers: { Cookie: cookie, "Content-Type": "application/json" },
body: JSON.stringify({
creditAmount: 250,
paymentMethod: "wire",
comment: "Invoice INV-42",
}),
},
);
expect(res.status).toBe(200);
const body = (await res.json()) as { credits: string };
expect(Number(body.credits)).toBe(260);

const org = await db.query.organization.findFirst({
where: { id: { eq: ORG_ID } },
});
expect(Number(org!.credits)).toBe(260);

const transactions = await db.query.transaction.findMany({
where: { organizationId: { eq: ORG_ID } },
});
expect(transactions).toHaveLength(1);
const [txn] = transactions;
expect(txn.type).toBe("credit_manual_payment");
expect(txn.status).toBe("completed");
// Money really arrived, so both the payment and the credits are booked.
expect(Number(txn.amount)).toBe(250);
expect(Number(txn.creditAmount)).toBe(250);
expect(txn.paymentMethod).toBe("wire");
expect(txn.description).toContain("wire");
expect(txn.description).toContain("Invoice INV-42");
});

test("rejects an unknown payment method", async () => {
const res = await app.request(
`/admin/organizations/${ORG_ID}/manual-credits`,
{
method: "POST",
headers: { Cookie: cookie, "Content-Type": "application/json" },
body: JSON.stringify({ creditAmount: 10, paymentMethod: "cash" }),
},
);
expect(res.status).toBe(400);

const transactions = await db.query.transaction.findMany({
where: { organizationId: { eq: ORG_ID } },
});
expect(transactions).toHaveLength(0);
});

test("returns 404 for an unknown organization", async () => {
const res = await app.request("/admin/organizations/nope/manual-credits", {
method: "POST",
headers: { Cookie: cookie, "Content-Type": "application/json" },
body: JSON.stringify({ creditAmount: 10, paymentMethod: "crypto" }),
});
expect(res.status).toBe(404);
});

test("counts toward revenue, processed, and gross revenue — unlike a gift", async () => {
await db.insert(tables.transaction).values([
{
organizationId: ORG_ID,
type: "credit_manual_payment",
amount: "500",
creditAmount: "500",
paymentMethod: "crypto",
status: "completed",
},
// Gifts stay free credits: no revenue, no processed, no paying customer.
{
organizationId: ORG_ID,
type: "credit_gift",
amount: "7",
creditAmount: "7",
status: "completed",
},
]);

const res = await app.request("/admin/metrics", {
headers: { Cookie: cookie },
});
expect(res.status).toBe(200);
const body = (await res.json()) as AdminMetricsResponse;

expect(body.totalRevenue).toBe(500);
expect(body.totalProcessed).toBe(500);
// Credits economy: the manual payment plus the gift.
expect(body.totalToppedUp).toBe(507);
expect(body.totalGiftedCredits).toBe(7);
expect(body.payingCustomers).toBe(1);
expect(body.grossManualPaymentsRevenue).toBe(500);
expect(body.grossRevenue).toBe(500);
});
});
158 changes: 155 additions & 3 deletions apps/api/src/routes/admin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -312,6 +312,9 @@ const adminMetricsSchema = z.object({
grossResetPassRevenue: z.number(),
grossChatPlansRevenue: z.number(),
grossProSubscriptionsRevenue: z.number(),
// Credits paid for outside Stripe (wire, crypto, …) and credited manually by
// an administrator. Real revenue, just settled on another channel.
grossManualPaymentsRevenue: z.number(),
});

const timeseriesRangeSchema = z.enum(["7d", "30d", "90d", "365d", "all"]);
Expand Down Expand Up @@ -857,7 +860,8 @@ admin.openapi(getMetrics, async (c) => {

const payingCustomers = Number(payingRow?.count ?? 0);

// Total revenue: completed credit-purchase rows — org credit top-ups AND
// Total revenue: completed credit-purchase rows — org credit top-ups,
// manually credited off-Stripe payments (`credit_manual_payment`) AND
// end-user wallet top-ups (`end_user_topup`, reversed on refund) — using
// creditAmount to exclude Stripe fees. Excludes gifts, all plan rows
// (DevPass/legacy subscription/Chat Plan), and the non-revenue end-user rows
Expand Down Expand Up @@ -973,7 +977,8 @@ admin.openapi(getMetrics, async (c) => {
const totalApiKeysSpent = Number(spentRow?.apiKeysValue ?? 0);
const totalDebitedSpend = Number(spentRow?.debitedValue ?? 0);

// Total processed (gross Stripe amounts from completed non-gift, non-plan transactions)
// Total processed (gross payment amounts from completed non-gift, non-plan
// transactions — Stripe charges plus off-Stripe manual payments)
const [processedRow] = await db
.select({
value:
Expand Down Expand Up @@ -1236,13 +1241,37 @@ admin.openapi(getMetrics, async (c) => {

const grossProSubscriptionsRevenue = Number(grossProSubsRow?.value ?? 0);

// Manual payments: credits an administrator granted against money received
// outside Stripe (wire, crypto, …). `amount` is the real payment, so these
// belong in gross revenue like any other purchase — kept as their own split
// because they never appear in Stripe reporting.
const [grossManualPaymentsRow] = await db
.select({
value:
sql<number>`COALESCE(SUM(CAST(${tables.transaction.amount} AS NUMERIC)), 0)`.as(
"value",
),
})
.from(tables.transaction)
.where(
and(
eq(tables.transaction.status, "completed"),
eq(tables.transaction.type, "credit_manual_payment"),
sql`CAST(${tables.transaction.amount} AS NUMERIC) > 0`,
transactionDateFilter,
),
);

const grossManualPaymentsRevenue = Number(grossManualPaymentsRow?.value ?? 0);

const grossRevenue =
grossCreditsRevenue +
grossDevpassRevenue +
grossDevpassTopupsRevenue +
grossResetPassRevenue +
grossChatPlansRevenue +
grossProSubscriptionsRevenue;
grossProSubscriptionsRevenue +
grossManualPaymentsRevenue;

// Balance derivation must use debited spend, not blended cost: BYOK usage
// never drains purchased credits, so subtracting it would understate
Expand Down Expand Up @@ -1274,6 +1303,7 @@ admin.openapi(getMetrics, async (c) => {
grossResetPassRevenue,
grossChatPlansRevenue,
grossProSubscriptionsRevenue,
grossManualPaymentsRevenue,
});
});

Expand Down Expand Up @@ -6139,6 +6169,128 @@ admin.openapi(giftCreditsRoute, async (c) => {
});
});

// Manually credit an organization for a payment received outside Stripe
const manualPaymentMethods = ["wire", "crypto", "paypal", "other"] as const;

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"),
paymentMethod: z.enum(manualPaymentMethods),
comment: z.string().optional(),
}),
},
},
},
},
responses: {
200: {
content: {
"application/json": {
schema: z.object({
message: z.string(),
credits: z.string(),
}),
},
},
description: "Credits added successfully.",
},
404: {
content: {
"application/json": {
schema: z.object({
message: z.string(),
}),
},
},
description: "Organization not found.",
},
},
});

admin.openapi(manualCreditsRoute, async (c) => {
const user = c.get("user");
const { orgId } = c.req.valid("param");
const { creditAmount, paymentMethod, comment } = c.req.valid("json");

const org = await db.query.organization.findFirst({
where: {
id: { eq: orgId },
},
});

if (!org || org.status === "deleted") {
throw new HTTPException(404, {
message: "Organization not found",
});
}

const description = comment
? `Manual payment (${paymentMethod}) credited by Administrator: ${comment}`
: `Manual payment (${paymentMethod}) credited by Administrator`;

const { transactionId, updatedCredits } = await db.transaction(async (tx) => {
const [txn] = await tx
.insert(tables.transaction)
.values({
organizationId: orgId,
type: "credit_manual_payment",
// The money was actually received, so `amount` (gross payment) and
// `creditAmount` (credits granted) are the same figure: there are no
// Stripe fees to net out on an off-Stripe channel.
amount: creditAmount.toString(),
creditAmount: creditAmount.toString(),
currency: "USD",
status: "completed",
description,
paymentMethod,
})
.returning({ id: tables.transaction.id });

const [updatedOrg] = await tx
.update(tables.organization)
.set({
credits: sql`${tables.organization.credits} + ${creditAmount}`,
})
.where(eq(tables.organization.id, orgId))
.returning({ credits: tables.organization.credits });

return {
transactionId: txn.id,
updatedCredits: String(updatedOrg.credits),
};
});

await logAuditEvent({
organizationId: orgId,
userId: user!.id,
action: "credits.manual_payment",
resourceType: "organization",
resourceId: orgId,
metadata: {
creditAmount,
paymentMethod,
comment,
transactionId,
},
});

return c.json({
message: "Credits added successfully",
credits: updatedCredits,
});
});

// Configure the referral signup bonus for an organization
const updateReferralBonusRoute = createRoute({
method: "patch",
Expand Down
1 change: 1 addition & 0 deletions apps/api/src/routes/organization.ts
Original file line number Diff line number Diff line change
Expand Up @@ -278,6 +278,7 @@ const transactionSchema = z.object({
"credit_topup",
"credit_refund",
"credit_gift",
"credit_manual_payment",
"dev_plan_start",
"dev_plan_upgrade",
"dev_plan_downgrade",
Expand Down
10 changes: 6 additions & 4 deletions apps/api/src/utils/devpass-filter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -124,12 +124,14 @@ export function firstRowPerInvoiceFilter(dedupTypes: readonly string[]) {
}

// Transaction types that represent an actual customer payment: org credit
// purchases, dev/chat plan charges (start/upgrade/renewal — cancel, end and
// downgrade rows are bookkeeping, not payments), legacy subscriptions, and
// end-user wallet top-ups. Used to count "paid customers", so gifts, refunds
// and margin bookkeeping never qualify an org as paying.
// purchases (Stripe or manually credited off-Stripe payments), dev/chat plan
// charges (start/upgrade/renewal — cancel, end and downgrade rows are
// bookkeeping, not payments), legacy subscriptions, and end-user wallet
// top-ups. Used to count "paid customers", so gifts, refunds and margin
// bookkeeping never qualify an org as paying.
export const paidTransactionTypes = [
"credit_topup",
"credit_manual_payment",
"subscription_start",
"dev_plan_start",
"dev_plan_upgrade",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ const TYPE_LABELS: Partial<Record<Transaction["type"], string>> = {
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.

end_user_topup: "Credit top-up",
end_user_refund: "Credit refund",
};
Expand Down
Loading
Loading