55 lines
1.5 KiB
TypeScript
55 lines
1.5 KiB
TypeScript
import { NextRequest, NextResponse } from 'next/server';
|
|
import { purchaseDb } from '@/lib/db';
|
|
import { notifyCustomerOfDecision } from '@/lib/telegram';
|
|
|
|
export async function PATCH(
|
|
request: NextRequest,
|
|
{ params }: { params: Promise<{ id: string }> }
|
|
) {
|
|
try {
|
|
const { id } = await params;
|
|
const purchaseId = parseInt(id);
|
|
|
|
if (isNaN(purchaseId)) {
|
|
return NextResponse.json(
|
|
{ error: 'Invalid purchase ID' },
|
|
{ status: 400 }
|
|
);
|
|
}
|
|
|
|
const existing = purchaseDb.getById(purchaseId);
|
|
if (!existing) {
|
|
return NextResponse.json(
|
|
{ error: 'Purchase not found' },
|
|
{ status: 404 }
|
|
);
|
|
}
|
|
if (existing.approvalStatus !== 'pending') {
|
|
return NextResponse.json(
|
|
{ error: `Purchase is already ${existing.approvalStatus}` },
|
|
{ status: 409 }
|
|
);
|
|
}
|
|
|
|
const purchase = purchaseDb.setStatus(purchaseId, 'approved');
|
|
if (!purchase) {
|
|
return NextResponse.json({ error: 'Purchase was reviewed concurrently' }, { status: 409 });
|
|
}
|
|
void notifyCustomerOfDecision(purchase).catch((error) => {
|
|
console.error('Failed to notify Telegram customer:', error);
|
|
});
|
|
|
|
return NextResponse.json({
|
|
success: true,
|
|
message: 'Purchase approved successfully',
|
|
purchase,
|
|
});
|
|
} catch (error: any) {
|
|
console.error('Error approving purchase:', error);
|
|
return NextResponse.json(
|
|
{ error: error.message || 'Failed to approve purchase' },
|
|
{ status: 500 }
|
|
);
|
|
}
|
|
}
|