This commit is contained in:
root
2025-12-21 12:46:27 +01:00
parent 5e65144934
commit bb1c5b43d6
18 changed files with 1375 additions and 691 deletions

View File

@@ -6,7 +6,7 @@ import bcrypt from 'bcrypt'
export async function POST(request: NextRequest) {
try {
const body = await request.json()
const { username, password, email } = body
const { username, password, email, referral_id } = body
// Validate required fields
if (!username || !password || !email) {
@@ -84,6 +84,27 @@ export async function POST(request: NextRequest) {
const buyer = (rows as any[])[0]
// Handle referral if provided
if (referral_id) {
const referrerId = parseInt(referral_id, 10)
// Validate that referrer exists and is not the same as the new user
if (referrerId && referrerId !== buyer.id) {
const [referrerRows] = await pool.execute(
'SELECT id FROM buyers WHERE id = ?',
[referrerId]
)
if ((referrerRows as any[]).length > 0) {
// Create referral record
await pool.execute(
'INSERT INTO referrals (referrer, referree) VALUES (?, ?)',
[referrerId, buyer.id]
)
}
}
}
// Create session cookie
const response = NextResponse.json(
{

54
app/api/orders/route.ts Normal file
View File

@@ -0,0 +1,54 @@
import { NextRequest, NextResponse } from 'next/server'
import { cookies } from 'next/headers'
import pool from '@/lib/db'
// GET /api/orders - Get all orders (sales) for the current user
export async function GET(request: NextRequest) {
try {
// Get buyer_id from session cookie
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 all sales for this buyer with drop and buyer_data information
const [rows] = await pool.execute(
`SELECT
s.id,
s.drop_id,
s.buyer_id,
s.size,
s.payment_id,
s.created_at,
d.item as drop_item,
d.unit as drop_unit,
d.ppu as drop_ppu,
d.image_url as drop_image_url,
bd.fullname as buyer_fullname,
bd.address as buyer_address,
bd.phone as buyer_phone
FROM sales s
LEFT JOIN drops d ON s.drop_id = d.id
LEFT JOIN buyer_data bd ON s.buyer_data_id = bd.id
WHERE s.buyer_id = ?
ORDER BY s.created_at DESC`,
[buyer_id]
)
return NextResponse.json(rows)
} catch (error) {
console.error('Error fetching orders:', error)
return NextResponse.json(
{ error: 'Failed to fetch orders' },
{ status: 500 }
)
}
}

View File

@@ -119,18 +119,23 @@ export async function POST(request: NextRequest) {
)
}
// Check if user has unlocked wholesale prices
const [referralRows] = await pool.execute(
'SELECT COUNT(*) as count FROM referrals WHERE referrer = ?',
[buyer_id]
)
const referralCount = (referralRows as any[])[0]?.count || 0
const isWholesaleUnlocked = referralCount >= 3
// Calculate price
// ppu is stored as integer where 1000 = $1.00, so divide by 1000 to get actual price
const pricePerUnit = drop.ppu / 1000
let priceAmount = 0
if (drop.unit === 'kg') {
priceAmount = (size / 1000) * pricePerUnit
} else {
priceAmount = size * pricePerUnit
}
// Assuming ppu is per gram
const pricePerGram = drop.ppu / 1000
const priceToUse = isWholesaleUnlocked ? pricePerGram * 0.76 : pricePerGram
const priceAmount = size * priceToUse
// Round to 2 decimal places
priceAmount = Math.round(priceAmount * 100) / 100
const roundedPriceAmount = Math.round(priceAmount * 100) / 100
// Generate order ID
const orderId = `SALE-${Date.now()}-${drop_id}-${buyer_id}`
@@ -163,7 +168,7 @@ export async function POST(request: NextRequest) {
'Content-Type': 'application/json',
},
body: JSON.stringify({
price_amount: priceAmount,
price_amount: roundedPriceAmount,
price_currency: nowPaymentsConfig.currency,
pay_currency: payCurrency, // Required: crypto currency (btc, eth, etc)
order_id: orderId,
@@ -190,7 +195,7 @@ export async function POST(request: NextRequest) {
// 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, priceAmount, nowPaymentsConfig.currency, expiresAt]
[payment.payment_id, orderId, drop_id, buyer_id, buyer_data_id, size, roundedPriceAmount, nowPaymentsConfig.currency, expiresAt]
)
// Commit transaction - inventory is now reserved

View File

@@ -0,0 +1,39 @@
import { NextRequest, NextResponse } from 'next/server'
import { cookies } from 'next/headers'
// GET /api/referrals/link - Get referral link for current user
export async function GET(request: NextRequest) {
try {
const cookieStore = 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 base URL
const baseUrl = process.env.NEXT_PUBLIC_BASE_URL ||
request.headers.get('origin') ||
'http://localhost:3000'
// Create referral link with buyer_id as referral parameter
const referralLink = `${baseUrl}?ref=${buyer_id}`
return NextResponse.json({
referralLink,
referralId: buyer_id,
})
} catch (error) {
console.error('Error generating referral link:', error)
return NextResponse.json(
{ error: 'Failed to generate referral link' },
{ status: 500 }
)
}
}

View File

@@ -0,0 +1,50 @@
import { NextRequest, NextResponse } from 'next/server'
import { cookies } from 'next/headers'
import pool from '@/lib/db'
// GET /api/referrals/status - Get referral count and unlock status for current user
export async function GET(request: NextRequest) {
try {
const cookieStore = cookies()
const buyerIdCookie = cookieStore.get('buyer_id')?.value
if (!buyerIdCookie) {
return NextResponse.json(
{
referralCount: 0,
isUnlocked: false,
referralsNeeded: 3,
referralsRemaining: 3
},
{ status: 200 }
)
}
const buyer_id = parseInt(buyerIdCookie, 10)
// Count referrals for this user
const [referralRows] = await pool.execute(
'SELECT COUNT(*) as count FROM referrals WHERE referrer = ?',
[buyer_id]
)
const referralCount = (referralRows as any[])[0]?.count || 0
const isUnlocked = referralCount >= 3
const referralsNeeded = 3
const referralsRemaining = Math.max(0, referralsNeeded - referralCount)
return NextResponse.json({
referralCount,
isUnlocked,
referralsNeeded,
referralsRemaining,
})
} catch (error) {
console.error('Error fetching referral status:', error)
return NextResponse.json(
{ error: 'Failed to fetch referral status' },
{ status: 500 }
)
}
}