96 lines
2.8 KiB
TypeScript
96 lines
2.8 KiB
TypeScript
import { NextResponse } from "next/server";
|
|
import { eq } from "drizzle-orm";
|
|
import { auth } from "@/app/(auth)/auth";
|
|
import { db } from "@/lib/db";
|
|
import { systemSettings } from "@/lib/db/schema";
|
|
import {
|
|
checkUserImageQuota,
|
|
getPointsSystemConfig,
|
|
getUserById,
|
|
getUserMonthlyImageCount,
|
|
} from "@/lib/db/queries";
|
|
import {
|
|
defaultMembershipConfig,
|
|
defaultMembershipUserOverrides,
|
|
getMembershipPlanById,
|
|
normalizeMembershipConfig,
|
|
normalizeMembershipUserOverrides,
|
|
resolveMembershipPlanIdForUser,
|
|
} from "@/lib/membership/config";
|
|
|
|
const MEMBERSHIP_CONFIG_KEY = "membership_config";
|
|
const MEMBERSHIP_USER_OVERRIDES_KEY = "membership_user_plan_overrides";
|
|
|
|
export async function GET() {
|
|
try {
|
|
const session = await auth();
|
|
|
|
if (!session?.user?.id) {
|
|
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
|
}
|
|
|
|
const [configSetting, overridesSetting, quota, totalImages, pointsConfig, dbUser] = await Promise.all([
|
|
db
|
|
.select()
|
|
.from(systemSettings)
|
|
.where(eq(systemSettings.key, MEMBERSHIP_CONFIG_KEY))
|
|
.limit(1)
|
|
.then((rows) => rows[0]),
|
|
db
|
|
.select()
|
|
.from(systemSettings)
|
|
.where(eq(systemSettings.key, MEMBERSHIP_USER_OVERRIDES_KEY))
|
|
.limit(1)
|
|
.then((rows) => rows[0]),
|
|
checkUserImageQuota(session.user.id),
|
|
getUserMonthlyImageCount(session.user.id),
|
|
getPointsSystemConfig(),
|
|
getUserById({ id: session.user.id }),
|
|
]);
|
|
|
|
const config = configSetting?.value
|
|
? normalizeMembershipConfig(configSetting.value)
|
|
: defaultMembershipConfig;
|
|
const overrides = overridesSetting?.value
|
|
? normalizeMembershipUserOverrides(overridesSetting.value)
|
|
: defaultMembershipUserOverrides;
|
|
|
|
const currentPlanId = resolveMembershipPlanIdForUser(
|
|
session.user.id,
|
|
session.user.email,
|
|
config,
|
|
overrides
|
|
);
|
|
const currentPlan = getMembershipPlanById(config, currentPlanId);
|
|
|
|
const currentCredits = pointsConfig.enabled
|
|
? Math.max(0, Number(dbUser?.pointsBalance || 0))
|
|
: quota.remaining !== null
|
|
? Math.max(0, quota.remaining)
|
|
: currentPlan.monthlyCredits;
|
|
|
|
return NextResponse.json({
|
|
config,
|
|
pointsSystemConfig: pointsConfig,
|
|
isHighVip: Boolean(dbUser?.isHighVip),
|
|
currentPlanId,
|
|
currentPlan,
|
|
summary: {
|
|
currentCredits,
|
|
dailyFreeCredits: currentPlan.dailyFreeCredits,
|
|
usedThisMonth: quota.used,
|
|
monthlyLimit: quota.limit,
|
|
remainingThisMonth: quota.remaining,
|
|
totalImages,
|
|
},
|
|
updatedAt: new Date().toISOString(),
|
|
});
|
|
} catch (error) {
|
|
console.error("[Membership Summary API] Error:", error);
|
|
return NextResponse.json(
|
|
{ error: "Failed to fetch membership summary" },
|
|
{ status: 500 }
|
|
);
|
|
}
|
|
}
|