feat(claim): quantity-aware claims via item_claims; per-guest unclaim
This commit is contained in:
@@ -1,89 +1,105 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { eq } from 'drizzle-orm';
|
||||
import { db, wishlistItems, wishlists } from '@/lib/db';
|
||||
import { createId } from '@paralleldrive/cuid2';
|
||||
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 { id } = await params;
|
||||
const body = await request.json();
|
||||
const { name, note } = body;
|
||||
|
||||
// Get the item
|
||||
const item = await db
|
||||
.select()
|
||||
.from(wishlistItems)
|
||||
.where(eq(wishlistItems.id, id))
|
||||
.limit(1);
|
||||
|
||||
if (item.length === 0) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Item not found' },
|
||||
{ status: 404 }
|
||||
);
|
||||
const guest = await getGuestFromRequest(request);
|
||||
if (!guest) {
|
||||
return NextResponse.json({ error: 'Convite necessário' }, { status: 401 });
|
||||
}
|
||||
|
||||
// Check if item is already claimed
|
||||
if (item[0].claimedByToken) {
|
||||
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 });
|
||||
|
||||
// Sum quantities reserved by OTHER guests
|
||||
const otherSumRow = await db
|
||||
.select({ total: sql<number>`COALESCE(SUM(${itemClaims.quantity}), 0)` })
|
||||
.from(itemClaims)
|
||||
.where(and(eq(itemClaims.itemId, id), ne(itemClaims.guestId, guest.id)));
|
||||
const otherSum = Number(otherSumRow[0]?.total ?? 0);
|
||||
|
||||
if (otherSum + requestedQty > item.quantity) {
|
||||
const remaining = Math.max(0, item.quantity - otherSum);
|
||||
return NextResponse.json(
|
||||
{ error: 'Item is already claimed' },
|
||||
{ error: `Apenas ${remaining} disponível(is)`, remaining },
|
||||
{ status: 409 }
|
||||
);
|
||||
}
|
||||
|
||||
// Check if wishlist is public
|
||||
const wishlist = await db
|
||||
// Upsert: replace existing claim for this (item, guest)
|
||||
const existing = await db
|
||||
.select()
|
||||
.from(wishlists)
|
||||
.where(eq(wishlists.id, item[0].wishlistId))
|
||||
.from(itemClaims)
|
||||
.where(and(eq(itemClaims.itemId, id), eq(itemClaims.guestId, guest.id)))
|
||||
.limit(1);
|
||||
|
||||
if (wishlist.length === 0) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Wishlist not found' },
|
||||
{ status: 404 }
|
||||
);
|
||||
if (existing.length > 0) {
|
||||
await db
|
||||
.update(itemClaims)
|
||||
.set({ quantity: requestedQty, note, updatedAt: new Date() })
|
||||
.where(eq(itemClaims.id, existing[0].id));
|
||||
} else {
|
||||
await db.insert(itemClaims).values({
|
||||
itemId: id,
|
||||
guestId: guest.id,
|
||||
quantity: requestedQty,
|
||||
note,
|
||||
});
|
||||
}
|
||||
|
||||
if (!wishlist[0].isPublic) {
|
||||
return NextResponse.json(
|
||||
{ error: 'This wishlist is private' },
|
||||
{ status: 403 }
|
||||
);
|
||||
}
|
||||
await db.update(wishlistItems).set({ updatedAt: new Date() }).where(eq(wishlistItems.id, id));
|
||||
|
||||
// Generate unique claim token
|
||||
const claimToken = createId();
|
||||
|
||||
// Update item with claim information
|
||||
const updatedItem = await db
|
||||
.update(wishlistItems)
|
||||
.set({
|
||||
claimedByName: name || null,
|
||||
claimedByNote: note || null,
|
||||
claimedByToken: claimToken,
|
||||
claimedAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
})
|
||||
.where(eq(wishlistItems.id, id))
|
||||
.returning();
|
||||
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: true,
|
||||
claimToken,
|
||||
item: updatedItem[0],
|
||||
},
|
||||
{ status: 201 }
|
||||
);
|
||||
} catch (error) {
|
||||
console.error('Error claiming item:', error);
|
||||
return NextResponse.json(
|
||||
{ error: 'Failed to claim item' },
|
||||
{ status: 500 }
|
||||
);
|
||||
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),
|
||||
};
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user