48 lines
1.5 KiB
TypeScript
48 lines
1.5 KiB
TypeScript
import { prisma } from "@/lib/db";
|
|
import { periodKey } from "@/lib/utils";
|
|
import type { UsageMetric } from "@/lib/billing/plans";
|
|
|
|
export type OwnerType = "user" | "organization";
|
|
|
|
/** Increment a monthly usage counter for a billing subject. */
|
|
export async function incrementUsage(
|
|
ownerId: string,
|
|
ownerType: OwnerType,
|
|
metric: UsageMetric,
|
|
by = 1
|
|
): Promise<void> {
|
|
const key = periodKey(new Date());
|
|
await prisma.usageRecord.upsert({
|
|
where: { ownerId_periodKey_metric: { ownerId, periodKey: key, metric } },
|
|
create: { ownerId, ownerType, periodKey: key, metric, count: by },
|
|
update: { count: { increment: by } },
|
|
});
|
|
}
|
|
|
|
/** Current-period count for a single metric. */
|
|
export async function getUsage(
|
|
ownerId: string,
|
|
metric: UsageMetric,
|
|
date = new Date()
|
|
): Promise<number> {
|
|
const rec = await prisma.usageRecord.findUnique({
|
|
where: { ownerId_periodKey_metric: { ownerId, periodKey: periodKey(date), metric } },
|
|
});
|
|
return rec?.count ?? 0;
|
|
}
|
|
|
|
/** Current-period counts for all metrics. */
|
|
export async function getUsageSummary(
|
|
ownerId: string,
|
|
date = new Date()
|
|
): Promise<Record<UsageMetric, number>> {
|
|
const rows = await prisma.usageRecord.findMany({
|
|
where: { ownerId, periodKey: periodKey(date) },
|
|
});
|
|
const summary: Record<UsageMetric, number> = { script: 0, audio: 0, art: 0, repurpose: 0 };
|
|
for (const row of rows) {
|
|
if (row.metric in summary) summary[row.metric as UsageMetric] = row.count;
|
|
}
|
|
return summary;
|
|
}
|