payment on hold

This commit is contained in:
root
2025-12-21 08:43:43 +01:00
parent 872e5a1a6a
commit 6741f5ed72
9 changed files with 977 additions and 217 deletions

View File

@@ -45,31 +45,65 @@ export async function POST(request: NextRequest) {
const drop = drops[0]
// Check inventory availability (but don't reserve yet - will reserve when payment confirmed)
const [salesRows] = await pool.execute(
'SELECT COALESCE(SUM(size), 0) as total_fill FROM sales WHERE drop_id = ?',
[drop_id]
)
const salesData = salesRows as any[]
const currentFill = salesData[0]?.total_fill || 0
// Convert fill to the drop's unit for comparison
let currentFillInDropUnit = currentFill
let sizeInDropUnit = size
if (drop.unit === 'kg') {
currentFillInDropUnit = currentFill / 1000
sizeInDropUnit = size / 1000
}
// Check if there's enough remaining inventory
const remaining = drop.size - currentFillInDropUnit
if (sizeInDropUnit > remaining) {
// Get IPN callback URL from environment variable (IPN is handled by external service)
// This URL is still required for NOWPayments to know where to send payment notifications
const ipnCallbackUrl = process.env.IPN_CALLBACK_URL
if (!ipnCallbackUrl) {
return NextResponse.json(
{ error: 'Not enough inventory remaining' },
{ status: 400 }
{ error: 'IPN_CALLBACK_URL environment variable is required. This should point to your external IPN handler service.' },
{ status: 500 }
)
}
// Use transaction to atomically check and reserve inventory
const connection = await pool.getConnection()
await connection.beginTransaction()
try {
// Check inventory availability including non-expired pending orders
// First, clean up expired pending orders
await connection.execute(
'DELETE FROM pending_orders WHERE expires_at < NOW()',
)
// Calculate current fill from sales
const [salesRows] = await connection.execute(
'SELECT COALESCE(SUM(size), 0) as total_fill FROM sales WHERE drop_id = ?',
[drop_id]
)
const salesData = salesRows as any[]
const currentFill = salesData[0]?.total_fill || 0
// Calculate pending orders (non-expired) that are holding inventory
const [pendingRows] = await connection.execute(
'SELECT COALESCE(SUM(size), 0) as total_pending FROM pending_orders WHERE drop_id = ? AND expires_at > NOW()',
[drop_id]
)
const pendingData = pendingRows as any[]
const pendingFill = pendingData[0]?.total_pending || 0
console.log(`total fill : ${currentFill} + ${pendingFill} = ${Number(currentFill) + Number(pendingFill)}`)
// Total reserved = sales + pending orders, ensure both are numbers
const totalReserved = Number(currentFill) + Number(pendingFill)
// Convert fill to the drop's unit for comparison
let totalReservedInDropUnit = totalReserved
let sizeInDropUnit = size
if (drop.unit === 'kg') {
totalReservedInDropUnit = totalReserved / 1000
sizeInDropUnit = size / 1000
}
// Check if there's enough remaining inventory
const remaining = drop.size - totalReservedInDropUnit
if (sizeInDropUnit > remaining) {
await connection.rollback()
connection.release()
return NextResponse.json(
{ error: 'Not enough inventory remaining. Item may be on hold by another buyer.' },
{ status: 400 }
)
}
// Calculate price
// ppu is stored as integer where 1000 = $1.00, so divide by 1000 to get actual price
const pricePerUnit = drop.ppu / 1000
@@ -86,64 +120,72 @@ export async function POST(request: NextRequest) {
// Generate order ID
const orderId = `SALE-${Date.now()}-${drop_id}-${buyer_id}`
// Get base URL for success/cancel redirects
const baseUrl = process.env.NEXT_PUBLIC_BASE_URL ||
request.headers.get('origin') ||
'http://localhost:3420'
// Get base URL for success/cancel redirects
const baseUrl = process.env.NEXT_PUBLIC_BASE_URL ||
request.headers.get('origin') ||
'http://localhost:3420'
// Get IPN callback URL from environment variable
const ipnCallbackUrl = process.env.IPN_CALLBACK_URL
if (!ipnCallbackUrl) {
return NextResponse.json(
{ error: 'IPN_CALLBACK_URL environment variable is required' },
{ status: 500 }
// Get NOWPayments config (testnet or production)
const nowPaymentsConfig = getNowPaymentsConfig()
// Calculate expiration time (10 minutes from now)
const expiresAt = new Date()
expiresAt.setMinutes(expiresAt.getMinutes() + 10)
// Create NOWPayments invoice
// Note: NOWPayments doesn't support invoice_timeout parameter
// Expiration is handled by our pending_orders table (10 minutes)
const nowPaymentsResponse = await fetch(`${nowPaymentsConfig.baseUrl}/v1/invoice`, {
method: 'POST',
headers: {
'x-api-key': nowPaymentsConfig.apiKey,
'Content-Type': 'application/json',
},
body: JSON.stringify({
price_amount: priceAmount,
price_currency: nowPaymentsConfig.currency,
order_id: orderId,
order_description: `${drop.item} - ${size}g`,
ipn_callback_url: ipnCallbackUrl,
success_url: `${baseUrl}/?payment=success&order_id=${orderId}`,
cancel_url: `${baseUrl}/?payment=cancelled&order_id=${orderId}`,
}),
})
if (!nowPaymentsResponse.ok) {
const error = await nowPaymentsResponse.json()
console.error('NOWPayments error:', error)
await connection.rollback()
connection.release()
return NextResponse.json(
{ error: 'Failed to create payment invoice', details: error },
{ status: 500 }
)
}
const invoice = await nowPaymentsResponse.json()
// Store pending order with expiration time (atomically reserves inventory)
await connection.execute(
'INSERT INTO pending_orders (payment_id, order_id, drop_id, buyer_id, size, price_amount, price_currency, expires_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)',
[invoice.id, orderId, drop_id, buyer_id, size, priceAmount, nowPaymentsConfig.currency, expiresAt]
)
}
// Get NOWPayments config (testnet or production)
const nowPaymentsConfig = getNowPaymentsConfig()
// Commit transaction - inventory is now reserved
await connection.commit()
connection.release()
// Create NOWPayments invoice
const nowPaymentsResponse = await fetch(`${nowPaymentsConfig.baseUrl}/v1/invoice`, {
method: 'POST',
headers: {
'x-api-key': nowPaymentsConfig.apiKey,
'Content-Type': 'application/json',
},
body: JSON.stringify({
price_amount: priceAmount,
price_currency: nowPaymentsConfig.currency,
// Return invoice URL - sale will be created by external IPN handler when payment is confirmed
return NextResponse.json({
invoice_url: invoice.invoice_url,
payment_id: invoice.id,
order_id: orderId,
order_description: `${drop.item} - ${size}g`,
ipn_callback_url: ipnCallbackUrl,
success_url: `${baseUrl}/?payment=success&order_id=${orderId}`,
cancel_url: `${baseUrl}/?payment=cancelled&order_id=${orderId}`,
}),
})
if (!nowPaymentsResponse.ok) {
const error = await nowPaymentsResponse.json()
console.error('NOWPayments error:', error)
return NextResponse.json(
{ error: 'Failed to create payment invoice', details: error },
{ status: 500 }
)
}, { status: 201 })
} catch (error) {
await connection.rollback()
connection.release()
throw error
}
const invoice = await nowPaymentsResponse.json()
// Store pending order (will create sale when payment is confirmed)
const [result] = await pool.execute(
'INSERT INTO pending_orders (payment_id, order_id, drop_id, buyer_id, size, price_amount, price_currency) VALUES (?, ?, ?, ?, ?, ?, ?)',
[invoice.id, orderId, drop_id, buyer_id, size, priceAmount, nowPaymentsConfig.currency]
)
// Return invoice URL - sale will be created when payment is confirmed via IPN
return NextResponse.json({
invoice_url: invoice.invoice_url,
payment_id: invoice.id,
order_id: orderId,
}, { status: 201 })
} catch (error) {
console.error('Error creating invoice:', error)
return NextResponse.json(