phase 1-6 implemented
This commit is contained in:
1 parent
22c274bb83
commit
2c4927478a
73 files changed
+9702
-2354
No files matched your search
@@ -1,6 +1,7 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { auth } from "@clerk/nextjs/server";
|
||||
import { db, users as usersTable, eq, sql } from "@fitai/database";
|
||||
import log from "@/lib/logger";
|
||||
|
||||
/**
|
||||
* PATCH /api/users/gym
|
||||
@@ -12,7 +13,7 @@ import { db, users as usersTable, eq, sql } from "@fitai/database";
|
||||
export async function PATCH(req: Request) {
|
||||
try {
|
||||
const { userId } = await auth();
|
||||
console.log("PATCH /api/users/gym auth userId:", userId);
|
||||
log.debug("Updating user gym assignment", { userId });
|
||||
if (!userId) return new NextResponse("Unauthorized", { status: 401 });
|
||||
|
||||
const body = await req.json().catch(() => null);
|
||||
@@ -24,32 +25,32 @@ export async function PATCH(req: Request) {
|
||||
}
|
||||
|
||||
const gymId = body.gymId === null ? null : String(body.gymId);
|
||||
console.log("PATCH /api/users/gym parsed gymId from body:", gymId);
|
||||
log.debug("Parsed gym ID from request body", { gymId });
|
||||
|
||||
// Ensure user exists
|
||||
console.log("PATCH /api/users/gym fetching user by id:", userId);
|
||||
log.debug("Fetching user by ID", { userId });
|
||||
const user = await db
|
||||
.select()
|
||||
.from(usersTable)
|
||||
.where(eq(usersTable.id, userId))
|
||||
.get();
|
||||
console.log("PATCH /api/users/gym fetched user:", user);
|
||||
log.debug("User fetched", { user: user ? { id: user.id } : null });
|
||||
if (!user) return new NextResponse("User not found", { status: 404 });
|
||||
|
||||
// Validate gym when provided
|
||||
if (gymId) {
|
||||
console.log("PATCH /api/users/gym validating gym:", gymId);
|
||||
log.debug("Validating gym", { gymId });
|
||||
const rows = await db.all(
|
||||
sql`SELECT status FROM gyms WHERE id = ${gymId} LIMIT 1`,
|
||||
);
|
||||
console.log("PATCH /api/users/gym validation query result rows:", rows);
|
||||
log.debug("Gym validation query result", { rowCount: rows?.length });
|
||||
const gym = rows?.[0] as { status?: string } | undefined;
|
||||
if (!gym) {
|
||||
console.log("PATCH /api/users/gym validation: gym not found");
|
||||
log.warn("Gym not found during validation", { gymId });
|
||||
return NextResponse.json({ error: "Gym not found" }, { status: 404 });
|
||||
}
|
||||
if (gym.status !== "active") {
|
||||
console.log("PATCH /api/users/gym validation: gym not active", gym);
|
||||
log.warn("Gym is not active", { gymId, status: gym.status });
|
||||
return NextResponse.json(
|
||||
{ error: "Gym is not active" },
|
||||
{ status: 400 },
|
||||
@@ -58,24 +59,21 @@ export async function PATCH(req: Request) {
|
||||
}
|
||||
|
||||
// Update user's gym selection
|
||||
console.log("PATCH /api/users/gym updating user gym_id:", {
|
||||
userId,
|
||||
gymId,
|
||||
});
|
||||
log.debug("Updating user gym assignment in database", { userId, gymId });
|
||||
await db.run(
|
||||
sql`UPDATE users SET gym_id = ${gymId ?? null}, updated_at = ${Date.now()} WHERE id = ${userId}`,
|
||||
);
|
||||
console.log("PATCH /api/users/gym update completed");
|
||||
log.debug("User gym assignment updated");
|
||||
|
||||
const updated = await db
|
||||
.select()
|
||||
.from(usersTable)
|
||||
.where(eq(usersTable.id, userId))
|
||||
.get();
|
||||
console.log("PATCH /api/users/gym returning updated user:", updated);
|
||||
log.debug("Returning updated user", { userId });
|
||||
return NextResponse.json(updated);
|
||||
} catch (error) {
|
||||
console.error("PATCH /users/gym error:", error);
|
||||
log.error("Failed to update user gym assignment", error);
|
||||
return new NextResponse("Internal Server Error", { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@ import { getDatabase } from "../../../lib/database/index";
|
||||
import bcrypt from "bcryptjs";
|
||||
import { auth, clerkClient } from "@clerk/nextjs/server";
|
||||
import { db as rawDb, sql } from "@fitai/database";
|
||||
import log from "@/lib/logger";
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
try {
|
||||
@@ -31,28 +32,25 @@ export async function GET(request: NextRequest) {
|
||||
(g.name as string) || (g.id as string),
|
||||
]),
|
||||
);
|
||||
console.log(
|
||||
"GET /api/users: total users fetched from DB:",
|
||||
Array.isArray(users) ? users.length : 0,
|
||||
);
|
||||
log.debug("Fetched users from database", {
|
||||
totalUsers: Array.isArray(users) ? users.length : 0,
|
||||
});
|
||||
|
||||
if (role) {
|
||||
users = users.filter((user) => user.role === role);
|
||||
}
|
||||
console.log(
|
||||
"GET /api/users: role filter:",
|
||||
log.debug("Applied role filter", {
|
||||
role,
|
||||
"users after filter:",
|
||||
Array.isArray(users) ? users.length : 0,
|
||||
"sample:",
|
||||
users && users[0]
|
||||
? {
|
||||
id: users[0].id,
|
||||
role: users[0].role,
|
||||
gymId: (users as any)[0].gymId,
|
||||
}
|
||||
: null,
|
||||
);
|
||||
usersAfterFilter: Array.isArray(users) ? users.length : 0,
|
||||
sample:
|
||||
users && users[0]
|
||||
? {
|
||||
id: users[0].id,
|
||||
role: users[0].role,
|
||||
gymId: (users as any)[0].gymId,
|
||||
}
|
||||
: null,
|
||||
});
|
||||
|
||||
const usersWithClients = await Promise.all(
|
||||
users.map(async (user) => {
|
||||
@@ -116,21 +114,20 @@ export async function GET(request: NextRequest) {
|
||||
}),
|
||||
);
|
||||
|
||||
console.log(
|
||||
"GET /api/users: responding users count:",
|
||||
Array.isArray(usersWithClients) ? usersWithClients.length : 0,
|
||||
"sample:",
|
||||
usersWithClients && usersWithClients[0]
|
||||
? {
|
||||
id: usersWithClients[0].id,
|
||||
role: usersWithClients[0].role,
|
||||
gymId: (usersWithClients as any)[0].gymId,
|
||||
}
|
||||
: null,
|
||||
);
|
||||
log.debug("Prepared response with user details", {
|
||||
usersCount: Array.isArray(usersWithClients) ? usersWithClients.length : 0,
|
||||
sample:
|
||||
usersWithClients && usersWithClients[0]
|
||||
? {
|
||||
id: usersWithClients[0].id,
|
||||
role: usersWithClients[0].role,
|
||||
gymId: (usersWithClients as any)[0].gymId,
|
||||
}
|
||||
: null,
|
||||
});
|
||||
return NextResponse.json({ users: usersWithClients });
|
||||
} catch (error) {
|
||||
console.error("Get users error:", error);
|
||||
log.error("Failed to get users", error);
|
||||
return NextResponse.json(
|
||||
{ error: "Internal server error" },
|
||||
{ status: 500 },
|
||||
@@ -218,7 +215,11 @@ export async function POST(request: NextRequest) {
|
||||
ignoreExisting: true, // Don't fail if invite exists
|
||||
});
|
||||
} catch (clerkError: any) {
|
||||
console.error("Clerk invitation error:", clerkError);
|
||||
log.error("Clerk invitation failed", clerkError, {
|
||||
email,
|
||||
role,
|
||||
errorCode: clerkError.errors?.[0]?.code,
|
||||
});
|
||||
// If user already exists in Clerk, we might want to handle it.
|
||||
// But for now, let's proceed to create local record if invite sent or if they exist.
|
||||
if (clerkError.errors?.[0]?.code === "form_identifier_exists") {
|
||||
@@ -263,7 +264,7 @@ export async function POST(request: NextRequest) {
|
||||
{ status: 201 },
|
||||
);
|
||||
} catch (error) {
|
||||
console.error("Create user error:", error);
|
||||
log.error("Failed to create user", error);
|
||||
return NextResponse.json(
|
||||
{ error: "Internal server error" },
|
||||
{ status: 500 },
|
||||
@@ -276,7 +277,7 @@ export async function PUT(request: NextRequest) {
|
||||
const db = await getDatabase();
|
||||
const body = await request.json();
|
||||
const { id, email, firstName, lastName, role, phone, gymId } = body;
|
||||
console.log("PUT /api/users received body:", {
|
||||
log.debug("Updating user", {
|
||||
id,
|
||||
email,
|
||||
firstName,
|
||||
@@ -346,7 +347,7 @@ export async function PUT(request: NextRequest) {
|
||||
try {
|
||||
const client = await clerkClient();
|
||||
const publicMetadata: Record<string, unknown> = {};
|
||||
console.log("PUT /api/users preparing Clerk metadata update:", {
|
||||
log.debug("Preparing Clerk metadata update", {
|
||||
targetUserId: id,
|
||||
role,
|
||||
gymId,
|
||||
@@ -360,23 +361,20 @@ export async function PUT(request: NextRequest) {
|
||||
}
|
||||
|
||||
if (Object.keys(publicMetadata).length > 0) {
|
||||
console.log(
|
||||
"PUT /api/users calling Clerk updateUser with metadata:",
|
||||
publicMetadata,
|
||||
);
|
||||
log.debug("Updating Clerk user metadata", { publicMetadata });
|
||||
const clerkResult = await client.users.updateUser(id, {
|
||||
publicMetadata,
|
||||
});
|
||||
console.log("PUT /api/users Clerk updateUser result:", {
|
||||
log.debug("Clerk user updated successfully", {
|
||||
id: clerkResult.id,
|
||||
role: clerkResult.publicMetadata?.role,
|
||||
gymId: clerkResult.publicMetadata?.gymId,
|
||||
});
|
||||
} else {
|
||||
console.log("PUT /api/users no Clerk metadata changes requested");
|
||||
log.debug("No Clerk metadata changes requested");
|
||||
}
|
||||
} catch (clerkErr: any) {
|
||||
console.error("Clerk metadata update error:", clerkErr);
|
||||
log.error("Clerk metadata update failed", clerkErr, { userId: id });
|
||||
return NextResponse.json(
|
||||
{ error: "Failed to update role/gym in identity provider" },
|
||||
{ status: 500 },
|
||||
@@ -384,9 +382,7 @@ export async function PUT(request: NextRequest) {
|
||||
}
|
||||
|
||||
// Update local DB for immediate UI feedback (webhook will also sync)
|
||||
console.log(
|
||||
"PUT /api/users raw SQL updating local DB user gym_id and fields",
|
||||
);
|
||||
log.debug("Updating local database user");
|
||||
await rawDb.run(
|
||||
sql`UPDATE users
|
||||
SET email = ${email ?? existingUser.email},
|
||||
@@ -402,7 +398,7 @@ export async function PUT(request: NextRequest) {
|
||||
const updatedRow = await rawDb.get(
|
||||
sql`SELECT id, email, first_name, last_name, role, phone, gym_id, created_at, updated_at FROM users WHERE id = ${id}`,
|
||||
);
|
||||
console.log("PUT /api/users raw DB row after update:", updatedRow);
|
||||
log.debug("User updated in database", { updatedRow });
|
||||
|
||||
const updatedUser = {
|
||||
...existingUser,
|
||||
@@ -418,11 +414,11 @@ export async function PUT(request: NextRequest) {
|
||||
? gymId
|
||||
: existingUser.gymId,
|
||||
};
|
||||
console.log("PUT /api/users responding with updated user:", updatedUser);
|
||||
log.debug("Sending updated user response", { updatedUser });
|
||||
|
||||
return NextResponse.json({ user: updatedUser });
|
||||
} catch (error) {
|
||||
console.error("Update user error:", error);
|
||||
log.error("Failed to update user", error);
|
||||
return NextResponse.json(
|
||||
{ error: "Internal server error" },
|
||||
{ status: 500 },
|
||||
@@ -457,7 +453,7 @@ export async function DELETE(request: NextRequest) {
|
||||
);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Delete user error:", error);
|
||||
log.error("Failed to delete user(s)", error);
|
||||
return NextResponse.json(
|
||||
{ error: "Internal server error" },
|
||||
{ status: 500 },
|
||||
|
||||
Reference in new issue
Block a user