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

@@ -6,6 +6,11 @@ export async function GET() {
try {
const now = new Date()
// Clean up expired pending orders first to ensure accurate calculations
await pool.execute(
'DELETE FROM pending_orders WHERE expires_at < NOW()',
)
// Get all drops ordered by start_time (or created_at if start_time is null)
const [rows] = await pool.execute(
'SELECT * FROM drops ORDER BY COALESCE(start_time, created_at) ASC'
@@ -14,33 +19,50 @@ export async function GET() {
const drops = rows as any[]
// Find the first drop that's not fully sold out and has started
console.log(`Checking ${drops.length} drops for active drop`)
for (const drop of drops) {
// Check if drop has started (start_time is in the past or null)
const startTime = drop.start_time ? new Date(drop.start_time) : new Date(drop.created_at)
console.log(`Checking drop ${drop.id} (${drop.item}): startTime=${startTime.toISOString()}, now=${now.toISOString()}, started=${startTime <= now}`)
if (startTime > now) {
// Drop hasn't started yet - return it with a flag indicating it's upcoming
// Calculate fill (will be 0 for upcoming drops)
// Calculate fill (will be 0 for upcoming drops, but include pending for consistency)
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 totalFillInGrams = salesData[0]?.total_fill || 0
// Include non-expired pending orders in fill calculation
const [pendingRows] = await pool.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 pendingFillInGrams = pendingData[0]?.total_pending || 0
let fill = totalFillInGrams
const totalReservedInGrams = totalFillInGrams + pendingFillInGrams
let salesFill = totalFillInGrams
let pendingFill = pendingFillInGrams
if (drop.unit === 'kg') {
fill = totalFillInGrams / 1000
salesFill = totalFillInGrams / 1000
pendingFill = pendingFillInGrams / 1000
}
const totalFill = salesFill + pendingFill
console.log(`Returning upcoming drop ${drop.id} (${drop.item}): fill=${totalFill}, size=${drop.size}, starts at ${startTime.toISOString()}`)
return NextResponse.json({
...drop,
fill: fill,
fill: totalFill,
sales_fill: salesFill,
pending_fill: pendingFill,
is_upcoming: true,
start_time: drop.start_time || drop.created_at,
})
}
// Calculate fill from sales records
// Calculate fill from sales records and pending orders
// Sales are stored in grams, so we need to convert based on drop unit
const [salesRows] = await pool.execute(
'SELECT COALESCE(SUM(size), 0) as total_fill FROM sales WHERE drop_id = ?',
@@ -48,22 +70,65 @@ export async function GET() {
)
const salesData = salesRows as any[]
const totalFillInGrams = salesData[0]?.total_fill || 0
// Include non-expired pending orders in fill calculation (shows "on hold" inventory)
const [pendingRows] = await pool.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[]
// Ensure we get a number, handle null/undefined cases
// When table is empty, SUM returns NULL, COALESCE converts it to 0
let pendingFillInGrams = 0
if (pendingData && pendingData.length > 0 && pendingData[0]) {
const rawValue = pendingData[0].total_pending
// Handle both null (from empty result) and actual 0 values
if (rawValue !== null && rawValue !== undefined) {
pendingFillInGrams = Number(rawValue) || 0
}
}
// Explicitly ensure it's 0 if we got here with no valid data
pendingFillInGrams = Number(pendingFillInGrams) || 0
// Ensure totalFillInGrams and pendingFillInGrams are numbers, not strings
const totalFillNum = Number(totalFillInGrams) || 0
const pendingFillNum = Number(pendingFillInGrams) || 0
const totalReservedInGrams = totalFillNum + pendingFillNum
// Convert fill to drop's unit for comparison
let fill = totalFillInGrams
// Convert to drop's unit for display
let salesFill = totalFillNum
let pendingFill = pendingFillNum
if (drop.unit === 'kg') {
fill = totalFillInGrams / 1000
salesFill = totalFillNum / 1000
pendingFill = pendingFillNum / 1000
}
const totalFill = salesFill + pendingFill
// Ensure drop.size is a number for comparison
const dropSize = typeof drop.size === 'string' ? parseFloat(drop.size) : Number(drop.size)
const fillNum = Number(totalFill)
// Check if drop is not fully sold out
if (fill < drop.size) {
// Return drop with calculated fill
// Use a small epsilon for floating point comparison to handle precision issues
// Consider sold out if fill is within epsilon of size (to handle rounding)
const epsilon = drop.unit === 'kg' ? 0.00001 : 0.01
const remaining = dropSize - fillNum
if (remaining > epsilon) {
// Ensure pending_fill is explicitly 0 if no pending orders
const finalPendingFill = Number(pendingFill) || 0
console.log(`Returning active drop ${drop.id} with fill ${fillNum} < size ${dropSize}, pending_fill=${finalPendingFill} (raw: ${pendingFill})`)
return NextResponse.json({
...drop,
fill: fill,
fill: fillNum,
sales_fill: Number(salesFill) || 0, // Only confirmed sales
pending_fill: finalPendingFill, // Items on hold (explicitly 0 if no pending orders)
is_upcoming: false,
start_time: drop.start_time || drop.created_at,
})
} else {
console.log(`Drop ${drop.id} is sold out: fill=${fillNum} >= size=${dropSize} (remaining=${remaining})`)
}
}

View File

@@ -0,0 +1,115 @@
import { NextRequest, NextResponse } from 'next/server'
import pool from '@/lib/db'
import { getNowPaymentsConfig } from '@/lib/nowpayments'
// POST /api/payments/cleanup-expired - Clean up expired pending orders
// This endpoint should be called periodically (e.g., via cron job every minute)
export async function POST(request: NextRequest) {
try {
// Optional: Add authentication/authorization check here
// For security, you might want to require an API key or admin authentication
const authHeader = request.headers.get('authorization')
const expectedToken = process.env.CLEANUP_API_TOKEN
if (expectedToken && authHeader !== `Bearer ${expectedToken}`) {
return NextResponse.json(
{ error: 'Unauthorized' },
{ status: 401 }
)
}
// Find all expired pending orders
const [expiredRows] = await pool.execute(
'SELECT * FROM pending_orders WHERE expires_at < NOW()',
)
const expiredOrders = expiredRows as any[]
if (expiredOrders.length === 0) {
return NextResponse.json({
message: 'No expired orders to clean up',
cleaned: 0,
})
}
const nowPaymentsConfig = getNowPaymentsConfig()
let cleanedCount = 0
const errors: string[] = []
// Process each expired order
for (const order of expiredOrders) {
try {
// Try to cancel the NOWPayments invoice if it still exists
// Note: NOWPayments may not have a direct cancel endpoint, but we can try
// to check the status and handle accordingly
try {
const statusResponse = await fetch(
`${nowPaymentsConfig.baseUrl}/v1/payment/${order.payment_id}`,
{
method: 'GET',
headers: {
'x-api-key': nowPaymentsConfig.apiKey,
'Content-Type': 'application/json',
},
}
)
if (statusResponse.ok) {
const paymentStatus = await statusResponse.json()
// If payment is still pending/waiting, we can consider it expired
// NOWPayments will handle the expiration on their end based on invoice_timeout
console.log(`Payment ${order.payment_id} status:`, paymentStatus.payment_status)
}
} catch (apiError) {
// Invoice might already be expired/cancelled on NOWPayments side
console.log(`Could not check status for payment ${order.payment_id}:`, apiError)
}
// Delete the expired pending order
await pool.execute('DELETE FROM pending_orders WHERE id = ?', [order.id])
cleanedCount++
console.log(`Cleaned up expired pending order ${order.id} (payment_id: ${order.payment_id})`)
} catch (error) {
const errorMsg = `Error cleaning up order ${order.id}: ${error}`
console.error(errorMsg)
errors.push(errorMsg)
}
}
return NextResponse.json({
message: `Cleaned up ${cleanedCount} expired pending orders`,
cleaned: cleanedCount,
total: expiredOrders.length,
errors: errors.length > 0 ? errors : undefined,
})
} catch (error) {
console.error('Error in cleanup endpoint:', error)
return NextResponse.json(
{ error: 'Failed to clean up expired orders' },
{ status: 500 }
)
}
}
// GET /api/payments/cleanup-expired - Get status of expired orders (for monitoring)
export async function GET() {
try {
const [expiredRows] = await pool.execute(
'SELECT COUNT(*) as count FROM pending_orders WHERE expires_at < NOW()',
)
const result = expiredRows as any[]
const expiredCount = result[0]?.count || 0
return NextResponse.json({
expired_orders_count: expiredCount,
message: expiredCount > 0
? `There are ${expiredCount} expired pending orders that need cleanup`
: 'No expired orders',
})
} catch (error) {
console.error('Error checking expired orders:', error)
return NextResponse.json(
{ error: 'Failed to check expired orders' },
{ status: 500 }
)
}
}

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(

View File

@@ -1,132 +0,0 @@
import { NextRequest, NextResponse } from 'next/server'
import pool from '@/lib/db'
// POST /api/payments/ipn-callback - Handle NOWPayments IPN callbacks
export async function POST(request: NextRequest) {
try {
const body = await request.json()
// NOWPayments IPN callback structure
// You may need to adjust based on actual NOWPayments IPN format
const {
payment_id,
invoice_id,
order_id,
payment_status,
pay_amount,
pay_currency,
price_amount,
price_currency,
} = body
console.log('IPN Callback received:', {
payment_id,
invoice_id,
order_id,
payment_status,
})
// Find pending order by payment_id or invoice_id
const paymentIdToFind = invoice_id || payment_id
const [pendingRows] = await pool.execute(
'SELECT * FROM pending_orders WHERE payment_id = ?',
[paymentIdToFind]
)
const pendingOrders = pendingRows as any[]
if (pendingOrders.length === 0) {
// Check if sale already exists (idempotency)
const [existingSales] = await pool.execute(
'SELECT * FROM sales WHERE payment_id = ?',
[paymentIdToFind]
)
const existing = existingSales as any[]
if (existing.length > 0) {
// Sale already created, just return success
console.log('Sale already exists for payment_id:', paymentIdToFind)
return NextResponse.json({ status: 'ok' }, { status: 200 })
}
console.error('Pending order not found for payment_id:', paymentIdToFind)
return NextResponse.json(
{ error: 'Pending order not found' },
{ status: 404 }
)
}
const pendingOrder = pendingOrders[0]
// Update payment status based on payment_status
// NOWPayments statuses: waiting, confirming, confirmed, sending, partially_paid, finished, failed, refunded, expired
if (payment_status === 'finished' || payment_status === 'confirmed') {
// Payment successful - create sale record
try {
// Check inventory again before creating sale
const [dropRows] = await pool.execute(
'SELECT * FROM drops WHERE id = ?',
[pendingOrder.drop_id]
)
const drops = dropRows as any[]
if (drops.length === 0) {
console.error('Drop not found for pending order:', pendingOrder.id)
return NextResponse.json({ status: 'error', message: 'Drop not found' }, { status: 200 })
}
const drop = drops[0]
// Calculate current fill from sales
const [salesRows] = await pool.execute(
'SELECT COALESCE(SUM(size), 0) as total_fill FROM sales WHERE drop_id = ?',
[pendingOrder.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 = pendingOrder.size
if (drop.unit === 'kg') {
currentFillInDropUnit = currentFill / 1000
sizeInDropUnit = pendingOrder.size / 1000
}
// Check if there's still enough inventory
const remaining = drop.size - currentFillInDropUnit
if (sizeInDropUnit > remaining) {
console.error('Not enough inventory for pending order:', pendingOrder.id)
// Delete pending order since inventory is no longer available
await pool.execute('DELETE FROM pending_orders WHERE id = ?', [pendingOrder.id])
return NextResponse.json({ status: 'error', message: 'Inventory no longer available' }, { status: 200 })
}
// Create sale record
const [result] = await pool.execute(
'INSERT INTO sales (drop_id, buyer_id, size, payment_id) VALUES (?, ?, ?, ?)',
[pendingOrder.drop_id, pendingOrder.buyer_id, pendingOrder.size, pendingOrder.payment_id]
)
const saleId = (result as any).insertId
// Delete pending order since sale is created
await pool.execute('DELETE FROM pending_orders WHERE id = ?', [pendingOrder.id])
console.log(`Payment confirmed - Sale ${saleId} created from pending order ${pendingOrder.id}`)
} catch (error) {
console.error('Error creating sale from pending order:', error)
return NextResponse.json({ status: 'error' }, { status: 200 })
}
} else if (payment_status === 'failed' || payment_status === 'expired') {
// Payment failed - delete pending order
await pool.execute('DELETE FROM pending_orders WHERE id = ?', [pendingOrder.id])
console.log(`Payment failed - Pending order ${pendingOrder.id} deleted`)
}
// Return success to NOWPayments
return NextResponse.json({ status: 'ok' }, { status: 200 })
} catch (error) {
console.error('Error processing IPN callback:', error)
// Still return 200 to prevent NOWPayments from retrying
return NextResponse.json({ status: 'error' }, { status: 200 })
}
}

View File

@@ -15,6 +15,8 @@ interface DropData {
created_at: string
start_time: string | null
is_upcoming?: boolean
sales_fill?: number // Only confirmed sales
pending_fill?: number // Items on hold (pending orders)
}
interface User {
@@ -59,10 +61,17 @@ export default function Drop() {
const response = await fetch('/api/drops/active')
if (response.ok) {
const data = await response.json()
setDrop(data)
// Handle both null response and actual drop data
setDrop(data) // data can be null if no active drop
} else {
// If response is not ok, log the error
const errorData = await response.json().catch(() => ({ error: 'Unknown error' }))
console.error('Error fetching active drop:', errorData)
setDrop(null)
}
} catch (error) {
console.error('Error fetching active drop:', error)
setDrop(null)
} finally {
setLoading(false)
}
@@ -285,6 +294,16 @@ export default function Drop() {
{drop.unit} of {drop.size}
{drop.unit} reserved
</div>
{(() => {
const pendingFill = Number(drop.pending_fill) || 0;
console.log(`pending fill:${pendingFill}`)
return pendingFill > 0 && (
<div className="meta" style={{ fontSize: '12px', color: 'var(--muted)', marginTop: '4px' }}>
{drop.unit === 'kg' ? pendingFill.toFixed(2) : Math.round(pendingFill)}
{drop.unit} on hold (10 min checkout window)
</div>
)
})()}
</>
)}