final 0.9

This commit is contained in:
root
2025-12-31 07:49:35 +00:00
parent 312810bb56
commit 0d8c2ea3a3
13 changed files with 1195 additions and 41 deletions

View File

@@ -25,7 +25,7 @@ export async function POST(request: NextRequest) {
const buyer_id = parseInt(buyerIdCookie, 10)
const body = await request.json()
const { drop_id, size, pay_currency, buyer_data_id } = body
const { drop_id, size, pay_currency, buyer_data_id, points_to_use } = body
// Validate required fields
if (!drop_id || !size || !buyer_data_id) {
@@ -35,6 +35,15 @@ export async function POST(request: NextRequest) {
)
}
// Validate and parse points_to_use
const pointsToUse = points_to_use ? parseFloat(points_to_use) : 0
if (pointsToUse < 0) {
return NextResponse.json(
{ error: 'points_to_use must be non-negative' },
{ status: 400 }
)
}
// Validate pay_currency against allowed list
const normalizedPayCurrency = pay_currency ? String(pay_currency).trim().toLowerCase() : null
if (normalizedPayCurrency && !isAllowedCurrency(normalizedPayCurrency)) {
@@ -153,16 +162,102 @@ export async function POST(request: NextRequest) {
// Convert price to user's currency (CHF for Swiss, EUR for others)
const priceAmount = convertPriceForCountry(priceAmountEur, countryCode)
// Handle referral points discount if points are being used
let pointsDiscount = 0
let actualPointsUsed = 0
if (pointsToUse > 0) {
// Get buyer's current points balance and points_to_chf setting
const [buyerPointsRows] = await connection.execute(
'SELECT referral_points FROM buyers WHERE id = ?',
[buyer_id]
)
const buyerPointsData = buyerPointsRows as any[]
if (buyerPointsData.length === 0) {
await connection.rollback()
connection.release()
return NextResponse.json(
{ error: 'Buyer not found' },
{ status: 404 }
)
}
const availablePoints = parseFloat(buyerPointsData[0].referral_points) || 0
if (pointsToUse > availablePoints) {
await connection.rollback()
connection.release()
return NextResponse.json(
{ error: 'Insufficient referral points' },
{ status: 400 }
)
}
// Get points_to_chf setting
const [settingsRows] = await connection.execute(
'SELECT setting_value FROM referral_settings WHERE setting_key = ?',
['points_to_chf']
)
const settings = settingsRows as any[]
const pointsToChf = parseFloat(settings[0]?.setting_value || '100')
// Calculate discount in CHF, then convert to user's currency
const discountChf = pointsToUse / pointsToChf
// Convert discount based on user's currency
if (currency === 'CHF') {
pointsDiscount = discountChf
} else {
// Convert CHF to EUR (1 CHF ≈ 1.03 EUR)
pointsDiscount = discountChf * 1.03
}
// Don't allow discount to exceed the product price (before shipping)
pointsDiscount = Math.min(pointsDiscount, priceAmount)
actualPointsUsed = pointsToUse
// Deduct points directly (stored procedures can be tricky with transactions)
// Get current points balance
const [currentPointsRows] = await connection.execute(
'SELECT referral_points FROM buyers WHERE id = ? FOR UPDATE',
[buyer_id]
)
const currentPointsData = currentPointsRows as any[]
const currentPoints = parseFloat(currentPointsData[0]?.referral_points) || 0
if (currentPoints < actualPointsUsed) {
await connection.rollback()
connection.release()
return NextResponse.json(
{ error: 'Insufficient referral points' },
{ status: 400 }
)
}
// Deduct points
const newBalance = currentPoints - actualPointsUsed
await connection.execute(
'UPDATE buyers SET referral_points = ? WHERE id = ?',
[newBalance, buyer_id]
)
// Record the transaction (we'll update pending_order_id later when we have it)
// For now, we'll record it after creating the pending order
}
// Calculate final price after discount
const priceAfterDiscount = Math.max(0, priceAmount - pointsDiscount)
// Calculate shipping fee (already in correct currency: CHF for CH, EUR for others)
const shippingFee = calculateShippingFee(countryCode)
// Add shipping fee to total price
const totalPriceAmount = priceAmount + shippingFee
// Add shipping fee to total price (shipping is not discounted)
const totalPriceAmount = priceAfterDiscount + shippingFee
// Round to 2 decimal places
const roundedPriceAmount = Math.round(totalPriceAmount * 100) / 100
const roundedShippingFee = Math.round(shippingFee * 100) / 100
const roundedSubtotal = Math.round(priceAmount * 100) / 100
const roundedSubtotal = Math.round(priceAfterDiscount * 100) / 100
const roundedPointsDiscount = Math.round(pointsDiscount * 100) / 100
// Generate order ID
const orderId = `SALE-${Date.now()}-${drop_id}-${buyer_id}`
@@ -225,10 +320,25 @@ export async function POST(request: NextRequest) {
// Store pending order with expiration time (atomically reserves inventory)
// payment.payment_id is the NOWPayments payment ID
await connection.execute(
'INSERT INTO pending_orders (payment_id, order_id, drop_id, buyer_id, buyer_data_id, size, price_amount, price_currency, expires_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)',
[payment.payment_id, orderId, drop_id, buyer_id, buyer_data_id, size, roundedPriceAmount, priceCurrency, expiresAt]
const [pendingOrderResult] = await connection.execute(
'INSERT INTO pending_orders (payment_id, order_id, drop_id, buyer_id, buyer_data_id, size, price_amount, price_currency, points_used, expires_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)',
[payment.payment_id, orderId, drop_id, buyer_id, buyer_data_id, size, roundedPriceAmount, priceCurrency, actualPointsUsed, expiresAt]
)
const pendingOrderId = (pendingOrderResult as any).insertId
// Record referral point transaction if points were used
if (actualPointsUsed > 0) {
await connection.execute(
'INSERT INTO referral_point_transactions (buyer_id, points, type, pending_order_id, description) VALUES (?, ?, ?, ?, ?)',
[
buyer_id,
actualPointsUsed,
'spent',
pendingOrderId,
`Points spent for purchase (Pending Order #${pendingOrderId})`
]
)
}
// Commit transaction - inventory is now reserved
await connection.commit()
@@ -241,10 +351,12 @@ export async function POST(request: NextRequest) {
pay_address: payment.pay_address, // Address where customer sends payment
pay_amount: payment.pay_amount, // Amount in crypto to pay
pay_currency: payment.pay_currency, // Crypto currency
price_amount: payment.price_amount, // Total price in fiat (includes shipping)
price_amount: payment.price_amount, // Total price in fiat (includes shipping, after points discount)
price_currency: payment.price_currency, // Fiat currency (CHF or EUR)
shipping_fee: roundedShippingFee, // Shipping fee in user's currency
subtotal: roundedSubtotal, // Product price without shipping in user's currency
subtotal: roundedSubtotal, // Product price without shipping in user's currency (after discount)
points_used: actualPointsUsed, // Points used for discount
points_discount: roundedPointsDiscount, // Discount amount in user's currency
order_id: orderId,
payin_extra_id: payment.payin_extra_id, // Memo/tag for certain currencies (XRP, XLM, etc)
expiration_estimate_date: payment.expiration_estimate_date, // When payment expires