feat(transfer): implement transfer functionality with user selection and balance validation
This commit is contained in:
@@ -0,0 +1,75 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { auth } from "~/server/auth";
|
||||
import { db } from "~/server/db";
|
||||
|
||||
export async function POST(request: Request) {
|
||||
const session = await auth();
|
||||
|
||||
if (!session?.user?.id) {
|
||||
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
||||
}
|
||||
|
||||
const { toUserId, amount } = (await request.json()) as {
|
||||
toUserId: string;
|
||||
amount: number;
|
||||
};
|
||||
|
||||
if (!toUserId || typeof toUserId !== "string") {
|
||||
return NextResponse.json({ error: "Invalid recipient" }, { status: 400 });
|
||||
}
|
||||
|
||||
if (typeof amount !== "number" || isNaN(amount) || amount <= 0) {
|
||||
return NextResponse.json(
|
||||
{ error: "Amount must be a positive number" },
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
|
||||
const fromUserId = session.user.id;
|
||||
|
||||
if (fromUserId === toUserId) {
|
||||
return NextResponse.json(
|
||||
{ error: "Cannot transfer to yourself" },
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
|
||||
const [sender, recipient] = await Promise.all([
|
||||
db.user.findUnique({
|
||||
where: { id: fromUserId },
|
||||
select: { id: true, balance: true },
|
||||
}),
|
||||
db.user.findUnique({
|
||||
where: { id: toUserId },
|
||||
select: { id: true, name: true },
|
||||
}),
|
||||
]);
|
||||
|
||||
if (!sender) {
|
||||
return NextResponse.json({ error: "Sender not found" }, { status: 404 });
|
||||
}
|
||||
|
||||
if (!recipient) {
|
||||
return NextResponse.json({ error: "Recipient not found" }, { status: 404 });
|
||||
}
|
||||
|
||||
if (sender.balance < amount) {
|
||||
return NextResponse.json(
|
||||
{ error: "Insufficient balance" },
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
|
||||
await db.$transaction([
|
||||
db.user.update({
|
||||
where: { id: fromUserId },
|
||||
data: { balance: { decrement: amount } },
|
||||
}),
|
||||
db.user.update({
|
||||
where: { id: toUserId },
|
||||
data: { balance: { increment: amount } },
|
||||
}),
|
||||
]);
|
||||
|
||||
return NextResponse.json({ success: true, amount, to: recipient.name });
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { auth } from "~/server/auth";
|
||||
import { db } from "~/server/db";
|
||||
|
||||
export async function GET() {
|
||||
const session = await auth();
|
||||
|
||||
if (!session?.user?.id) {
|
||||
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
||||
}
|
||||
|
||||
const users = await db.user.findMany({
|
||||
where: { id: { not: session.user.id } },
|
||||
select: { id: true, name: true },
|
||||
orderBy: { name: "asc" },
|
||||
});
|
||||
|
||||
return NextResponse.json(users);
|
||||
}
|
||||
Reference in New Issue
Block a user