Some checks failed
Build and Push Docker Image / build-and-push (push) Has been cancelled
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
131 lines
4.6 KiB
TypeScript
131 lines
4.6 KiB
TypeScript
import { NextRequest, NextResponse } from 'next/server';
|
|
import { and, eq, ne, sql } from 'drizzle-orm';
|
|
import { db, wishlistItems, wishlists, itemClaims, guests } from '@/lib/db';
|
|
import { getGuestFromRequest } from '@/lib/auth/tokens';
|
|
|
|
export async function POST(
|
|
request: NextRequest,
|
|
{ params }: { params: Promise<{ id: string }> }
|
|
) {
|
|
try {
|
|
const guest = await getGuestFromRequest(request);
|
|
if (!guest) {
|
|
return NextResponse.json({ error: 'Convite necessário' }, { status: 401 });
|
|
}
|
|
|
|
const { id } = await params;
|
|
const body = await request.json().catch(() => ({}));
|
|
const requestedQty = Math.max(1, Math.floor(Number(body?.quantity ?? 1)));
|
|
const note = (body?.note ?? '').toString().trim() || null;
|
|
|
|
const itemRows = await db.select().from(wishlistItems).where(eq(wishlistItems.id, id)).limit(1);
|
|
if (itemRows.length === 0) return NextResponse.json({ error: 'Item not found' }, { status: 404 });
|
|
const item = itemRows[0];
|
|
|
|
const wl = await db.select().from(wishlists).where(eq(wishlists.id, item.wishlistId)).limit(1);
|
|
if (wl.length === 0) return NextResponse.json({ error: 'Wishlist not found' }, { status: 404 });
|
|
if (!wl[0].isPublic) return NextResponse.json({ error: 'This wishlist is private' }, { status: 403 });
|
|
|
|
// Atomically check remaining quantity and upsert the claim inside a synchronous
|
|
// transaction to prevent race conditions (better-sqlite3 is synchronous).
|
|
type TxResult = { ok: true } | { ok: false; remaining: number };
|
|
|
|
const txResult: TxResult = db.transaction((tx) => {
|
|
// Re-read item quantity inside the transaction for an accurate snapshot
|
|
const itemSnap = tx
|
|
.select({ quantity: wishlistItems.quantity })
|
|
.from(wishlistItems)
|
|
.where(eq(wishlistItems.id, id))
|
|
.limit(1)
|
|
.all();
|
|
|
|
if (itemSnap.length === 0) return { ok: false, remaining: 0 };
|
|
const itemQty = itemSnap[0].quantity;
|
|
|
|
// Sum quantities reserved by OTHER guests
|
|
const otherSumRow = tx
|
|
.select({ total: sql<number>`COALESCE(SUM(${itemClaims.quantity}), 0)` })
|
|
.from(itemClaims)
|
|
.where(and(eq(itemClaims.itemId, id), ne(itemClaims.guestId, guest.id)))
|
|
.all();
|
|
const otherSum = Number(otherSumRow[0]?.total ?? 0);
|
|
|
|
if (otherSum + requestedQty > itemQty) {
|
|
const remaining = Math.max(0, itemQty - otherSum);
|
|
return { ok: false, remaining };
|
|
}
|
|
|
|
// Upsert: replace existing claim for this (item, guest)
|
|
const existing = tx
|
|
.select({ id: itemClaims.id })
|
|
.from(itemClaims)
|
|
.where(and(eq(itemClaims.itemId, id), eq(itemClaims.guestId, guest.id)))
|
|
.limit(1)
|
|
.all();
|
|
|
|
if (existing.length > 0) {
|
|
tx.update(itemClaims)
|
|
.set({ quantity: requestedQty, note, updatedAt: new Date() })
|
|
.where(eq(itemClaims.id, existing[0].id))
|
|
.run();
|
|
} else {
|
|
tx.insert(itemClaims)
|
|
.values({ itemId: id, guestId: guest.id, quantity: requestedQty, note })
|
|
.run();
|
|
}
|
|
|
|
tx.update(wishlistItems)
|
|
.set({ updatedAt: new Date() })
|
|
.where(eq(wishlistItems.id, id))
|
|
.run();
|
|
|
|
return { ok: true };
|
|
});
|
|
|
|
if (!txResult.ok) {
|
|
return NextResponse.json(
|
|
{ error: `Apenas ${txResult.remaining} disponível(is)`, remaining: txResult.remaining },
|
|
{ status: 409 }
|
|
);
|
|
}
|
|
|
|
const updated = await fetchItemWithClaims(id);
|
|
return NextResponse.json({ success: true, item: updated }, { status: 201 });
|
|
} catch (err) {
|
|
console.error('Error claiming item:', err);
|
|
return NextResponse.json({ error: 'Failed to claim item' }, { status: 500 });
|
|
}
|
|
}
|
|
|
|
async function fetchItemWithClaims(itemId: string) {
|
|
const itemRows = await db.select().from(wishlistItems).where(eq(wishlistItems.id, itemId)).limit(1);
|
|
if (itemRows.length === 0) return null;
|
|
const claims = await db
|
|
.select({
|
|
id: itemClaims.id,
|
|
quantity: itemClaims.quantity,
|
|
note: itemClaims.note,
|
|
isPurchased: itemClaims.isPurchased,
|
|
claimedAt: itemClaims.claimedAt,
|
|
guestId: guests.id,
|
|
guestName: guests.name,
|
|
})
|
|
.from(itemClaims)
|
|
.innerJoin(guests, eq(itemClaims.guestId, guests.id))
|
|
.where(eq(itemClaims.itemId, itemId));
|
|
const claimedQuantity = claims.reduce((s, c) => s + c.quantity, 0);
|
|
return {
|
|
...itemRows[0],
|
|
claims: claims.map((c) => ({
|
|
id: c.id,
|
|
quantity: c.quantity,
|
|
note: c.note,
|
|
isPurchased: c.isPurchased,
|
|
claimedAt: c.claimedAt,
|
|
guest: { id: c.guestId, name: c.guestName },
|
|
})),
|
|
claimedQuantity,
|
|
remainingQuantity: Math.max(0, itemRows[0].quantity - claimedQuantity),
|
|
};
|
|
}
|