final 0.9
This commit is contained in:
@@ -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
|
||||
|
||||
65
app/api/referral-points/route.ts
Normal file
65
app/api/referral-points/route.ts
Normal 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 }
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
109
app/api/sales/from-pending-order/route.ts
Normal file
109
app/api/sales/from-pending-order/route.ts
Normal 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 }
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -26,6 +26,7 @@ interface User {
|
||||
id: number
|
||||
username: string
|
||||
email: string
|
||||
referral_points?: number
|
||||
}
|
||||
|
||||
export default function Drop() {
|
||||
@@ -57,12 +58,17 @@ export default function Drop() {
|
||||
const [shippingFee, setShippingFee] = useState<number | null>(null)
|
||||
const [loadingShippingFee, setLoadingShippingFee] = useState(false)
|
||||
const [currency, setCurrency] = useState<'CHF' | 'EUR'>('EUR') // Default to EUR
|
||||
const [referralPoints, setReferralPoints] = useState<number>(0)
|
||||
const [pointsToChf, setPointsToChf] = useState<number>(100)
|
||||
const [pointsToUse, setPointsToUse] = useState<number>(0)
|
||||
const [loadingPoints, setLoadingPoints] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
fetchActiveDrop()
|
||||
checkAuth()
|
||||
checkWholesaleStatus()
|
||||
fetchShippingFee() // Fetch currency info on mount
|
||||
fetchReferralPoints()
|
||||
|
||||
// Poll active drop every 30 seconds
|
||||
const interval = setInterval(() => {
|
||||
@@ -72,6 +78,16 @@ export default function Drop() {
|
||||
return () => clearInterval(interval)
|
||||
}, [])
|
||||
|
||||
// Fetch referral points when user is authenticated
|
||||
useEffect(() => {
|
||||
if (user) {
|
||||
fetchReferralPoints()
|
||||
} else {
|
||||
setReferralPoints(0)
|
||||
setPointsToUse(0)
|
||||
}
|
||||
}, [user])
|
||||
|
||||
const checkWholesaleStatus = async () => {
|
||||
try {
|
||||
const response = await fetch('/api/referrals/status', {
|
||||
@@ -86,6 +102,30 @@ export default function Drop() {
|
||||
}
|
||||
}
|
||||
|
||||
const fetchReferralPoints = async () => {
|
||||
if (!user) {
|
||||
setReferralPoints(0)
|
||||
setPointsToUse(0)
|
||||
return
|
||||
}
|
||||
|
||||
setLoadingPoints(true)
|
||||
try {
|
||||
const response = await fetch('/api/referral-points', {
|
||||
credentials: 'include',
|
||||
})
|
||||
if (response.ok) {
|
||||
const data = await response.json()
|
||||
setReferralPoints(data.referral_points || 0)
|
||||
setPointsToChf(data.points_to_chf || 100)
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error fetching referral points:', error)
|
||||
} finally {
|
||||
setLoadingPoints(false)
|
||||
}
|
||||
}
|
||||
|
||||
// Poll payment status when payment modal is open
|
||||
useEffect(() => {
|
||||
if (!showPaymentModal || !paymentData?.payment_id) return
|
||||
@@ -429,6 +469,7 @@ export default function Drop() {
|
||||
size: selectedSize, // Size in grams
|
||||
pay_currency: selectedCurrency, // Selected payment currency
|
||||
buyer_data_id: buyerData.buyer_data_id, // Buyer delivery data ID
|
||||
points_to_use: pointsToUse, // Points to use for discount
|
||||
}),
|
||||
})
|
||||
|
||||
@@ -451,6 +492,12 @@ export default function Drop() {
|
||||
|
||||
const data = await response.json()
|
||||
|
||||
// Refresh referral points if any were used
|
||||
if (pointsToUse > 0) {
|
||||
fetchReferralPoints()
|
||||
setPointsToUse(0) // Reset points used
|
||||
}
|
||||
|
||||
// Close confirmation modal
|
||||
setShowConfirmModal(false)
|
||||
setProcessing(false)
|
||||
@@ -474,6 +521,39 @@ export default function Drop() {
|
||||
|
||||
const handleCancelPurchase = () => {
|
||||
setShowConfirmModal(false)
|
||||
setPointsToUse(0) // Reset points when canceling
|
||||
}
|
||||
|
||||
const handlePointsToUseChange = (value: string) => {
|
||||
const numValue = parseFloat(value) || 0
|
||||
const maxPoints = Math.min(referralPoints, calculatePriceBeforeDiscount() * pointsToChf)
|
||||
setPointsToUse(Math.max(0, Math.min(numValue, maxPoints)))
|
||||
}
|
||||
|
||||
const calculatePriceBeforeDiscount = () => {
|
||||
if (!drop) return 0
|
||||
const pricePerGramEur = drop.ppu / 1000
|
||||
const priceToUseEur = isWholesaleUnlocked ? pricePerGramEur * 0.76 : pricePerGramEur
|
||||
const priceEur = selectedSize * priceToUseEur
|
||||
return convertPrice(priceEur)
|
||||
}
|
||||
|
||||
const getMaxDiscountFromPoints = () => {
|
||||
if (pointsToChf === 0) return 0
|
||||
return referralPoints / pointsToChf
|
||||
}
|
||||
|
||||
const calculateDiscountFromPoints = () => {
|
||||
if (pointsToUse === 0 || pointsToChf === 0) return 0
|
||||
// Calculate discount in CHF, then convert to user's currency
|
||||
const discountChf = pointsToUse / pointsToChf
|
||||
// Convert CHF discount to user's currency
|
||||
if (currency === 'CHF') {
|
||||
return discountChf
|
||||
} else {
|
||||
// Convert CHF to EUR (1 CHF ≈ 1.03 EUR)
|
||||
return discountChf * 1.03
|
||||
}
|
||||
}
|
||||
|
||||
const calculatePrice = () => {
|
||||
@@ -484,7 +564,10 @@ export default function Drop() {
|
||||
const priceToUseEur = isWholesaleUnlocked ? pricePerGramEur * 0.76 : pricePerGramEur
|
||||
const priceEur = selectedSize * priceToUseEur
|
||||
// Convert to user's currency
|
||||
return convertPrice(priceEur)
|
||||
const price = convertPrice(priceEur)
|
||||
// Apply points discount
|
||||
const discount = calculateDiscountFromPoints()
|
||||
return Math.max(0, price - discount)
|
||||
}
|
||||
|
||||
const calculateStandardPrice = () => {
|
||||
@@ -587,6 +670,11 @@ export default function Drop() {
|
||||
}
|
||||
|
||||
const progressPercentage = getProgressPercentage(drop.fill, drop.size)
|
||||
// Calculate separate percentages for sales and pending
|
||||
const salesFill = Number(drop.sales_fill) || 0
|
||||
const pendingFill = Number(drop.pending_fill) || 0
|
||||
const salesPercentage = getProgressPercentage(salesFill, drop.size)
|
||||
const pendingPercentage = getProgressPercentage(pendingFill, drop.size)
|
||||
const availableSizes = getAvailableSizes()
|
||||
const timeUntilStart = getTimeUntilStart()
|
||||
const isUpcoming = drop.is_upcoming && timeUntilStart
|
||||
@@ -716,7 +804,24 @@ export default function Drop() {
|
||||
) : (
|
||||
<>
|
||||
<div className="progress">
|
||||
<span style={{ width: `${progressPercentage}%` }}></span>
|
||||
<div style={{ display: 'flex', height: '100%', width: '100%' }}>
|
||||
{salesPercentage > 0 && (
|
||||
<span style={{
|
||||
width: `${salesPercentage}%`,
|
||||
height: '100%',
|
||||
background: 'linear-gradient(90deg, var(--accent), #1fa463)',
|
||||
display: 'block'
|
||||
}}></span>
|
||||
)}
|
||||
{pendingPercentage > 0 && (
|
||||
<span style={{
|
||||
width: `${pendingPercentage}%`,
|
||||
height: '100%',
|
||||
background: '#808080',
|
||||
display: 'block'
|
||||
}}></span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="meta">
|
||||
{(() => {
|
||||
@@ -1001,6 +1106,62 @@ export default function Drop() {
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Referral Points Usage */}
|
||||
{user && referralPoints > 0 && (
|
||||
<div style={{ marginTop: '24px', marginBottom: '16px' }}>
|
||||
<label style={{ display: 'block', marginBottom: '8px', fontSize: '14px', color: 'var(--muted)' }}>
|
||||
<strong>⭐ {t('drop.useReferralPoints')}</strong>
|
||||
<span style={{ marginLeft: '8px', fontSize: '12px', color: 'var(--muted)' }}>
|
||||
({referralPoints.toFixed(0)} {t('drop.available')})
|
||||
</span>
|
||||
</label>
|
||||
<div style={{ display: 'flex', gap: '8px', alignItems: 'center' }}>
|
||||
<input
|
||||
type="number"
|
||||
min="0"
|
||||
max={referralPoints}
|
||||
step="1"
|
||||
value={pointsToUse}
|
||||
onChange={(e) => handlePointsToUseChange(e.target.value)}
|
||||
style={{
|
||||
flex: 1,
|
||||
padding: '12px',
|
||||
background: 'var(--bg-soft)',
|
||||
border: '1px solid var(--border)',
|
||||
borderRadius: '8px',
|
||||
fontSize: '14px',
|
||||
color: 'var(--text)',
|
||||
}}
|
||||
placeholder="0"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
const maxPoints = Math.min(referralPoints, calculatePriceBeforeDiscount() * pointsToChf)
|
||||
setPointsToUse(maxPoints)
|
||||
}}
|
||||
style={{
|
||||
padding: '12px 16px',
|
||||
background: 'var(--bg-soft)',
|
||||
border: '1px solid var(--border)',
|
||||
borderRadius: '8px',
|
||||
fontSize: '12px',
|
||||
color: 'var(--text)',
|
||||
cursor: 'pointer',
|
||||
whiteSpace: 'nowrap',
|
||||
}}
|
||||
>
|
||||
{t('drop.useMax')}
|
||||
</button>
|
||||
</div>
|
||||
{pointsToUse > 0 && (
|
||||
<div style={{ marginTop: '8px', fontSize: '12px', color: '#0a7931' }}>
|
||||
{t('drop.pointsDiscount')}: {(pointsToUse / pointsToChf).toFixed(2)} {currency === 'CHF' ? 'CHF' : 'EUR'}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div
|
||||
style={{
|
||||
padding: '16px',
|
||||
@@ -1013,9 +1174,19 @@ export default function Drop() {
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '8px' }}>
|
||||
<span style={{ color: 'var(--muted)', fontSize: '14px' }}>{t('drop.subtotal')}:</span>
|
||||
<span style={{ fontWeight: 500, fontSize: '14px' }}>
|
||||
{calculatePrice().toFixed(2)} {currency}
|
||||
{calculatePriceBeforeDiscount().toFixed(2)} {currency}
|
||||
</span>
|
||||
</div>
|
||||
{pointsToUse > 0 && (
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '8px' }}>
|
||||
<span style={{ color: '#0a7931', fontSize: '14px' }}>
|
||||
⭐ {t('drop.pointsDiscount')}:
|
||||
</span>
|
||||
<span style={{ fontWeight: 500, fontSize: '14px', color: '#0a7931' }}>
|
||||
-{calculateDiscountFromPoints().toFixed(2)} {currency}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '4px' }}>
|
||||
<span style={{ color: 'var(--muted)', fontSize: '14px' }}>{t('drop.shippingFee')}:</span>
|
||||
<span style={{ fontWeight: 500, fontSize: '14px' }}>
|
||||
@@ -1039,6 +1210,11 @@ export default function Drop() {
|
||||
{loadingShippingFee ? '...' : ((calculatePrice() + (shippingFee || 40)).toFixed(2))} {currency}
|
||||
</span>
|
||||
</div>
|
||||
{pointsToUse > 0 && (
|
||||
<div style={{ marginTop: '8px', fontSize: '12px', color: '#0a7931', fontStyle: 'italic' }}>
|
||||
{t('drop.pointsWillBeDeducted')}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<p
|
||||
style={{
|
||||
|
||||
@@ -1,25 +1,54 @@
|
||||
'use client'
|
||||
|
||||
import { useState } from 'react'
|
||||
import { useI18n } from '@/lib/i18n'
|
||||
import UnlockModal from './UnlockModal'
|
||||
|
||||
export default function InfoBox() {
|
||||
const { t } = useI18n()
|
||||
const [showUnlockModal, setShowUnlockModal] = useState(false)
|
||||
|
||||
// Process the text to make "referral link" clickable
|
||||
const processTaxesLegalText = () => {
|
||||
const text = t('infoBox.taxesLegalText')
|
||||
|
||||
// Replace "referral link" or "Referral-Link" with a clickable link
|
||||
// Preserve the original case of the matched text
|
||||
const processed = text.replace(
|
||||
/(referral link|Referral-Link)/gi,
|
||||
(match) => `<a href="#" class="referral-link-clickable" style="cursor:pointer;text-decoration:underline;color:inherit;">${match}</a>`
|
||||
)
|
||||
|
||||
return processed
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="info-box">
|
||||
<div>
|
||||
<h3>{t('infoBox.whyCheap')}</h3>
|
||||
<p>{t('infoBox.whyCheapText')}</p>
|
||||
<>
|
||||
<div className="info-box">
|
||||
<div>
|
||||
<h3>{t('infoBox.whyCheap')}</h3>
|
||||
<p>{t('infoBox.whyCheapText')}</p>
|
||||
</div>
|
||||
<div>
|
||||
<h3>{t('infoBox.taxesLegal')}</h3>
|
||||
<p
|
||||
dangerouslySetInnerHTML={{ __html: processTaxesLegalText() }}
|
||||
onClick={(e) => {
|
||||
const target = e.target as HTMLElement
|
||||
if (target.classList.contains('referral-link-clickable')) {
|
||||
e.preventDefault()
|
||||
setShowUnlockModal(true)
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<h3>{t('infoBox.dropModel')}</h3>
|
||||
<p>{t('infoBox.dropModelText')}</p>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<h3>{t('infoBox.taxesLegal')}</h3>
|
||||
<p>{t('infoBox.taxesLegalText')}</p>
|
||||
</div>
|
||||
<div>
|
||||
<h3>{t('infoBox.dropModel')}</h3>
|
||||
<p>{t('infoBox.dropModelText')}</p>
|
||||
</div>
|
||||
</div>
|
||||
<UnlockModal isOpen={showUnlockModal} onClose={() => setShowUnlockModal(false)} />
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -9,6 +9,7 @@ interface User {
|
||||
id: number
|
||||
username: string
|
||||
email: string
|
||||
referral_points?: number
|
||||
}
|
||||
|
||||
export default function Nav() {
|
||||
@@ -29,7 +30,24 @@ export default function Nav() {
|
||||
})
|
||||
if (response.ok) {
|
||||
const data = await response.json()
|
||||
setUser(data.user)
|
||||
const userData = data.user
|
||||
|
||||
// If user is logged in, fetch referral points
|
||||
if (userData) {
|
||||
try {
|
||||
const pointsResponse = await fetch('/api/referral-points', {
|
||||
credentials: 'include',
|
||||
})
|
||||
if (pointsResponse.ok) {
|
||||
const pointsData = await pointsResponse.json()
|
||||
userData.referral_points = pointsData.referral_points
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error fetching referral points:', error)
|
||||
}
|
||||
}
|
||||
|
||||
setUser(userData)
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error checking auth:', error)
|
||||
@@ -85,6 +103,16 @@ export default function Nav() {
|
||||
<span style={{ color: 'var(--muted)', fontSize: '14px', marginLeft: '48px' }}>
|
||||
{user.username}
|
||||
</span>
|
||||
{user.referral_points !== undefined && user.referral_points > 0 && (
|
||||
<span style={{
|
||||
color: '#0a7931',
|
||||
fontSize: '14px',
|
||||
marginLeft: '12px',
|
||||
fontWeight: 500,
|
||||
}}>
|
||||
⭐ {user.referral_points.toFixed(0)} pts
|
||||
</span>
|
||||
)}
|
||||
<a
|
||||
href="/orders"
|
||||
onClick={() => setMobileMenuOpen(false)}
|
||||
|
||||
@@ -15,11 +15,19 @@ interface User {
|
||||
email: string
|
||||
}
|
||||
|
||||
interface ReferralTier {
|
||||
referralsNeeded: number
|
||||
referralsRemaining: number
|
||||
isUnlocked: boolean
|
||||
}
|
||||
|
||||
interface ReferralStatus {
|
||||
referralCount: number
|
||||
isUnlocked: boolean
|
||||
referralsNeeded: number
|
||||
referralsRemaining: number
|
||||
wholesaleTier?: ReferralTier
|
||||
innerCircleTier?: ReferralTier
|
||||
}
|
||||
|
||||
export default function UnlockModal({ isOpen, onClose }: UnlockModalProps) {
|
||||
@@ -86,8 +94,35 @@ export default function UnlockModal({ isOpen, onClose }: UnlockModalProps) {
|
||||
isUnlocked: false,
|
||||
referralsNeeded: 3,
|
||||
referralsRemaining: 3,
|
||||
wholesaleTier: {
|
||||
referralsNeeded: 3,
|
||||
referralsRemaining: 3,
|
||||
isUnlocked: false
|
||||
},
|
||||
innerCircleTier: {
|
||||
referralsNeeded: 10,
|
||||
referralsRemaining: 10,
|
||||
isUnlocked: false
|
||||
}
|
||||
}
|
||||
|
||||
const wholesaleTier = status.wholesaleTier || {
|
||||
referralsNeeded: 3,
|
||||
referralsRemaining: Math.max(0, 3 - status.referralCount),
|
||||
isUnlocked: status.isUnlocked
|
||||
}
|
||||
|
||||
const innerCircleTier = status.innerCircleTier || {
|
||||
referralsNeeded: 10,
|
||||
referralsRemaining: Math.max(0, 10 - status.referralCount),
|
||||
isUnlocked: status.referralCount >= 10
|
||||
}
|
||||
|
||||
// Determine which tier to show and which title to use
|
||||
const isShowingInnerCircle = wholesaleTier.isUnlocked && !innerCircleTier.isUnlocked
|
||||
const currentTier = isShowingInnerCircle ? innerCircleTier : wholesaleTier
|
||||
const modalTitle = isShowingInnerCircle ? t('unlockModal.innerCircleTitle') : t('unlockModal.title')
|
||||
|
||||
return (
|
||||
<div
|
||||
style={{
|
||||
@@ -117,7 +152,7 @@ export default function UnlockModal({ isOpen, onClose }: UnlockModalProps) {
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '24px' }}>
|
||||
<h2 style={{ margin: 0 }}>{t('unlockModal.title')}</h2>
|
||||
<h2 style={{ margin: 0 }}>{modalTitle}</h2>
|
||||
<button
|
||||
onClick={onClose}
|
||||
style={{
|
||||
@@ -144,12 +179,12 @@ export default function UnlockModal({ isOpen, onClose }: UnlockModalProps) {
|
||||
<>
|
||||
<div style={{ marginBottom: '24px', textAlign: 'center' }}>
|
||||
<div style={{ fontSize: '18px', marginBottom: '8px' }}>
|
||||
🔒 {t('unlockModal.referralsCompleted', { count: status.referralCount, needed: status.referralsNeeded })}
|
||||
🔒 {t('unlockModal.referralsCompleted', { count: status.referralCount, needed: currentTier.referralsNeeded })}
|
||||
</div>
|
||||
<p style={{ color: 'var(--muted)', fontSize: '14px', margin: '8px 0' }}>
|
||||
{t('unlockModal.inviteFriends', { needed: status.referralsNeeded })}
|
||||
{t('unlockModal.inviteFriends', { needed: currentTier.referralsNeeded })}
|
||||
<br />
|
||||
{t('unlockModal.unlockForever')}
|
||||
{isShowingInnerCircle ? t('unlockModal.innerCircleUnlockForever') : t('unlockModal.unlockForever')}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
@@ -254,9 +289,9 @@ export default function UnlockModal({ isOpen, onClose }: UnlockModalProps) {
|
||||
marginBottom: '24px',
|
||||
}}
|
||||
>
|
||||
{status.referralsRemaining === 1
|
||||
? t('unlockModal.referralsToGoSingular', { remaining: status.referralsRemaining })
|
||||
: t('unlockModal.referralsToGoPlural', { remaining: status.referralsRemaining })
|
||||
{currentTier.referralsRemaining === 1
|
||||
? t('unlockModal.referralsToGoSingular', { remaining: currentTier.referralsRemaining })
|
||||
: t('unlockModal.referralsToGoPlural', { remaining: currentTier.referralsRemaining })
|
||||
}
|
||||
</div>
|
||||
|
||||
|
||||
Reference in New Issue
Block a user