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

View File

@@ -0,0 +1,65 @@
import { NextRequest, NextResponse } from 'next/server'
import { cookies } from 'next/headers'
import pool from '@/lib/db'
// GET /api/referral-points - Get current user's referral points and settings
export async function GET(request: NextRequest) {
try {
const cookieStore = await cookies()
const buyerIdCookie = cookieStore.get('buyer_id')?.value
if (!buyerIdCookie) {
return NextResponse.json(
{ error: 'Authentication required' },
{ status: 401 }
)
}
const buyer_id = parseInt(buyerIdCookie, 10)
// Get buyer's referral points
const [buyerRows] = await pool.execute(
'SELECT referral_points FROM buyers WHERE id = ?',
[buyer_id]
)
const buyers = buyerRows as any[]
if (buyers.length === 0) {
return NextResponse.json(
{ error: 'Buyer not found' },
{ status: 404 }
)
}
const referralPoints = parseFloat(buyers[0].referral_points) || 0
// Get referral settings
const [settingsRows] = await pool.execute(
'SELECT setting_key, setting_value FROM referral_settings'
)
const settings = settingsRows as any[]
const pointsToChf = parseFloat(
settings.find(s => s.setting_key === 'points_to_chf')?.setting_value || '100'
)
const pointsPerChf = parseFloat(
settings.find(s => s.setting_key === 'points_per_chf')?.setting_value || '10'
)
// Calculate maximum discount available
const maxDiscountChf = referralPoints / pointsToChf
return NextResponse.json({
referral_points: referralPoints,
points_to_chf: pointsToChf,
points_per_chf: pointsPerChf,
max_discount_chf: maxDiscountChf,
})
} catch (error) {
console.error('Error fetching referral points:', error)
return NextResponse.json(
{ error: 'Failed to fetch referral points' },
{ status: 500 }
)
}
}

View File

@@ -0,0 +1,109 @@
import { NextRequest, NextResponse } from 'next/server'
import pool from '@/lib/db'
// POST /api/sales/from-pending-order - Create a sale from a pending order (for IPN handlers)
// This endpoint should be called by your IPN/webhook handler when payment is confirmed
// It creates the sale and awards referral points
export async function POST(request: NextRequest) {
try {
const body = await request.json()
const { payment_id } = body
if (!payment_id) {
return NextResponse.json(
{ error: 'Missing required field: payment_id' },
{ status: 400 }
)
}
const connection = await pool.getConnection()
await connection.beginTransaction()
try {
// Find the pending order
const [pendingRows] = await connection.execute(
'SELECT * FROM pending_orders WHERE payment_id = ?',
[payment_id]
)
const pendingOrders = pendingRows as any[]
if (pendingOrders.length === 0) {
await connection.rollback()
connection.release()
return NextResponse.json(
{ error: 'Pending order not found' },
{ status: 404 }
)
}
const pendingOrder = pendingOrders[0]
// Check if sale already exists
const [existingSalesRows] = await connection.execute(
'SELECT id FROM sales WHERE payment_id = ?',
[payment_id]
)
const existingSales = existingSalesRows as any[]
if (existingSales.length > 0) {
// Sale already exists, return it
await connection.commit()
connection.release()
return NextResponse.json({
sale_id: existingSales[0].id,
message: 'Sale already exists',
})
}
// Create the sale from pending order data
const [result] = await connection.execute(
'INSERT INTO sales (drop_id, buyer_id, buyer_data_id, size, payment_id, price_amount, price_currency, points_used) VALUES (?, ?, ?, ?, ?, ?, ?, ?)',
[
pendingOrder.drop_id,
pendingOrder.buyer_id,
pendingOrder.buyer_data_id,
pendingOrder.size,
payment_id,
pendingOrder.price_amount,
pendingOrder.price_currency,
pendingOrder.points_used || 0,
]
)
const saleId = (result as any).insertId
// Award referral points to the referrer (if any)
// The stored procedure will:
// 1. Check if the buyer has a referrer
// 2. Calculate points based on purchase amount and points_per_chf setting
// 3. Update the referrer's referral_points balance
// 4. Record the transaction in referral_point_transactions
await connection.execute('CALL award_referral_points(?)', [saleId])
// Delete the pending order (it's now converted to a sale)
await connection.execute(
'DELETE FROM pending_orders WHERE payment_id = ?',
[payment_id]
)
await connection.commit()
connection.release()
return NextResponse.json({
sale_id: saleId,
message: 'Sale created successfully',
}, { status: 201 })
} catch (error) {
await connection.rollback()
connection.release()
throw error
}
} catch (error) {
console.error('Error creating sale from pending order:', error)
return NextResponse.json(
{ error: 'Failed to create sale from pending order' },
{ status: 500 }
)
}
}