main: add many things to app :)
Signed-off-by: nfel <nfilsaraee@gmail.com>
This commit is contained in:
+18
-18
@@ -68,14 +68,14 @@ export default function AdminAlbumsPage() {
|
||||
{/* Header */}
|
||||
<div className="flex items-center justify-between mb-8">
|
||||
<div>
|
||||
<h1 className="text-3xl font-bold text-white mb-2">Album Management</h1>
|
||||
<p className="text-gray-400">Manage your music catalog • {albums.length} albums</p>
|
||||
<h1 className="text-3xl font-bold text-paper-dark mb-2 border-b-4 border-paper-dark inline-block pb-1">Album Management</h1>
|
||||
<p className="text-paper-gray mt-4">Manage your music catalog • {albums.length} albums</p>
|
||||
</div>
|
||||
<motion.button
|
||||
whileHover={{ scale: 1.05 }}
|
||||
whileTap={{ scale: 0.95 }}
|
||||
onClick={() => setShowAddModal(true)}
|
||||
className="px-6 py-3 bg-gradient-to-r from-accent-cyan to-accent-cyan/80 hover:from-accent-cyan/90 hover:to-accent-cyan/70 rounded-lg font-semibold text-white transition-all glow-cyan flex items-center gap-2"
|
||||
className="px-6 py-3 bg-paper-brown hover:bg-paper-dark border-2 border-paper-dark font-semibold text-paper-light transition-all shadow-paper-lg flex items-center gap-2"
|
||||
>
|
||||
<FaPlus />
|
||||
Add New Album
|
||||
@@ -90,28 +90,28 @@ export default function AdminAlbumsPage() {
|
||||
initial={{ opacity: 0, y: 20 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ delay: index * 0.1 }}
|
||||
className="glass-effect rounded-xl p-6 border border-white/10"
|
||||
className="paper-card p-6 border-2 border-paper-brown shadow-paper"
|
||||
>
|
||||
<div className="flex gap-4">
|
||||
{/* Album Cover */}
|
||||
<div className="w-24 h-24 rounded-lg bg-gradient-to-br from-accent-cyan/20 to-accent-orange/20 flex items-center justify-center flex-shrink-0">
|
||||
<span className="text-xs text-white/50 font-bold text-center px-2">
|
||||
<div className="w-24 h-24 bg-paper-brown border-2 border-paper-dark flex items-center justify-center flex-shrink-0">
|
||||
<span className="text-xs text-paper-dark/50 font-bold text-center px-2">
|
||||
{album.title}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{/* Album Info */}
|
||||
<div className="flex-1">
|
||||
<h3 className="text-xl font-bold text-white mb-1">{album.title}</h3>
|
||||
<p className="text-sm text-gray-400 mb-2">
|
||||
<h3 className="text-xl font-bold text-paper-dark mb-1">{album.title}</h3>
|
||||
<p className="text-sm text-paper-gray mb-2">
|
||||
{album.year} • {album.genre}
|
||||
</p>
|
||||
<p className="text-sm text-gray-500 mb-3 line-clamp-2">
|
||||
<p className="text-sm text-paper-brown mb-3 line-clamp-2">
|
||||
{album.description}
|
||||
</p>
|
||||
<div className="flex items-center gap-4 text-sm text-gray-400">
|
||||
<div className="flex items-center gap-4 text-sm text-paper-gray">
|
||||
<span>{album.songs.length} tracks</span>
|
||||
<span className="text-accent-orange font-bold">{formatPrice(album.price)}</span>
|
||||
<span className="text-paper-brown font-bold">{formatPrice(album.price)}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -121,7 +121,7 @@ export default function AdminAlbumsPage() {
|
||||
whileHover={{ scale: 1.1 }}
|
||||
whileTap={{ scale: 0.9 }}
|
||||
onClick={() => openEditModal(album)}
|
||||
className="p-2 bg-accent-cyan/20 hover:bg-accent-cyan/30 rounded-lg text-accent-cyan transition-colors"
|
||||
className="p-2 bg-paper-light hover:bg-paper-sand border-2 border-paper-brown text-paper-brown transition-colors"
|
||||
aria-label="Edit album"
|
||||
>
|
||||
<FaEdit />
|
||||
@@ -130,7 +130,7 @@ export default function AdminAlbumsPage() {
|
||||
whileHover={{ scale: 1.1 }}
|
||||
whileTap={{ scale: 0.9 }}
|
||||
onClick={() => openDeleteModal(album)}
|
||||
className="p-2 bg-red-500/20 hover:bg-red-500/30 rounded-lg text-red-400 transition-colors"
|
||||
className="p-2 bg-red-100 hover:bg-red-200 border-2 border-red-400 text-red-700 transition-colors"
|
||||
aria-label="Delete album"
|
||||
>
|
||||
<FaTrash />
|
||||
@@ -139,19 +139,19 @@ export default function AdminAlbumsPage() {
|
||||
</div>
|
||||
|
||||
{/* Track List */}
|
||||
<div className="mt-4 pt-4 border-t border-white/10">
|
||||
<p className="text-sm font-semibold text-gray-400 mb-2">Tracks:</p>
|
||||
<div className="mt-4 pt-4 border-t-2 border-paper-brown">
|
||||
<p className="text-sm font-semibold text-paper-dark mb-2">Tracks:</p>
|
||||
<div className="space-y-1">
|
||||
{album.songs.slice(0, 3).map((song, idx) => (
|
||||
<div key={song.id} className="flex justify-between text-sm">
|
||||
<span className="text-gray-300">
|
||||
<span className="text-paper-dark">
|
||||
{idx + 1}. {song.title}
|
||||
</span>
|
||||
<span className="text-gray-500 font-mono">{song.duration}</span>
|
||||
<span className="text-paper-gray font-mono">{song.duration}</span>
|
||||
</div>
|
||||
))}
|
||||
{album.songs.length > 3 && (
|
||||
<p className="text-xs text-gray-500">+{album.songs.length - 3} more tracks</p>
|
||||
<p className="text-xs text-paper-gray">+{album.songs.length - 3} more tracks</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
+161
-21
@@ -2,7 +2,7 @@
|
||||
|
||||
import { useEffect, useState } from 'react';
|
||||
import { motion } from 'framer-motion';
|
||||
import { FaDownload, FaSearch } from 'react-icons/fa';
|
||||
import { FaDownload, FaSearch, FaCheck, FaTimes, FaClock } from 'react-icons/fa';
|
||||
import { useAlbums } from '@/lib/AlbumsContext';
|
||||
import { Purchase } from '@/lib/types';
|
||||
import { formatPrice } from '@/lib/utils';
|
||||
@@ -12,29 +12,79 @@ export default function AdminPurchasesPage() {
|
||||
const { albums } = useAlbums();
|
||||
const [purchases, setPurchases] = useState<Purchase[]>([]);
|
||||
const [searchTerm, setSearchTerm] = useState('');
|
||||
const [filterStatus, setFilterStatus] = useState<'all' | 'pending' | 'approved' | 'rejected'>('all');
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
const fetchPurchases = async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const response = await fetch('/api/purchases');
|
||||
if (response.ok) {
|
||||
const data = await response.json();
|
||||
setPurchases(data.reverse());
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error fetching purchases:', error);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
const savedPurchases = localStorage.getItem('purchases');
|
||||
if (savedPurchases) {
|
||||
setPurchases(JSON.parse(savedPurchases).reverse());
|
||||
}
|
||||
fetchPurchases();
|
||||
}, []);
|
||||
|
||||
const handleApprove = async (purchaseId: number) => {
|
||||
try {
|
||||
const response = await fetch(`/api/purchases/${purchaseId}/approve`, {
|
||||
method: 'PATCH',
|
||||
});
|
||||
if (response.ok) {
|
||||
fetchPurchases();
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error approving purchase:', error);
|
||||
alert('Failed to approve purchase');
|
||||
}
|
||||
};
|
||||
|
||||
const handleReject = async (purchaseId: number) => {
|
||||
try {
|
||||
const response = await fetch(`/api/purchases/${purchaseId}/reject`, {
|
||||
method: 'PATCH',
|
||||
});
|
||||
if (response.ok) {
|
||||
fetchPurchases();
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error rejecting purchase:', error);
|
||||
alert('Failed to reject purchase');
|
||||
}
|
||||
};
|
||||
|
||||
const filteredPurchases = purchases.filter((purchase) => {
|
||||
const album = albums.find((a) => a.id === purchase.albumId);
|
||||
return (
|
||||
const matchesSearch =
|
||||
album?.title.toLowerCase().includes(searchTerm.toLowerCase()) ||
|
||||
purchase.transactionId.toLowerCase().includes(searchTerm.toLowerCase())
|
||||
);
|
||||
purchase.transactionId.toLowerCase().includes(searchTerm.toLowerCase()) ||
|
||||
purchase.customerName?.toLowerCase().includes(searchTerm.toLowerCase()) ||
|
||||
purchase.email?.toLowerCase().includes(searchTerm.toLowerCase());
|
||||
|
||||
const matchesStatus = filterStatus === 'all' || purchase.approvalStatus === filterStatus;
|
||||
|
||||
return matchesSearch && matchesStatus;
|
||||
});
|
||||
|
||||
const totalRevenue = purchases.reduce((total, purchase) => {
|
||||
const pendingPurchases = purchases.filter(p => p.approvalStatus === 'pending');
|
||||
const approvedPurchases = purchases.filter(p => p.approvalStatus === 'approved');
|
||||
|
||||
const totalRevenue = approvedPurchases.reduce((total, purchase) => {
|
||||
const album = albums.find((a) => a.id === purchase.albumId);
|
||||
return total + (album?.price || 0);
|
||||
}, 0);
|
||||
|
||||
const exportToCSV = () => {
|
||||
const headers = ['Date', 'Time', 'Transaction ID', 'Album', 'Price'];
|
||||
const headers = ['Date', 'Time', 'Transaction ID', 'Album', 'Price', 'Customer', 'Email', 'Phone', 'Status', 'Payment Method'];
|
||||
const rows = purchases.map((purchase) => {
|
||||
const album = albums.find((a) => a.id === purchase.albumId);
|
||||
const date = new Date(purchase.purchaseDate);
|
||||
@@ -43,7 +93,12 @@ export default function AdminPurchasesPage() {
|
||||
date.toLocaleTimeString(),
|
||||
purchase.transactionId,
|
||||
album?.title || 'Unknown',
|
||||
formatPrice(album?.price || 0),
|
||||
album?.price || 0,
|
||||
purchase.customerName || '',
|
||||
purchase.email || '',
|
||||
purchase.phoneNumber || '',
|
||||
purchase.approvalStatus || 'pending',
|
||||
purchase.paymentMethod || 'card-to-card',
|
||||
];
|
||||
});
|
||||
|
||||
@@ -59,15 +114,40 @@ export default function AdminPurchasesPage() {
|
||||
URL.revokeObjectURL(url);
|
||||
};
|
||||
|
||||
const getStatusBadge = (status?: string) => {
|
||||
const statusLower = (status || 'pending').toLowerCase();
|
||||
if (statusLower === 'approved') {
|
||||
return (
|
||||
<span className="px-2 py-1 bg-green-100 border border-green-400 text-green-700 text-xs font-semibold">
|
||||
Approved
|
||||
</span>
|
||||
);
|
||||
} else if (statusLower === 'rejected') {
|
||||
return (
|
||||
<span className="px-2 py-1 bg-red-100 border border-red-400 text-red-700 text-xs font-semibold">
|
||||
Rejected
|
||||
</span>
|
||||
);
|
||||
} else {
|
||||
return (
|
||||
<span className="px-2 py-1 bg-orange-100 border border-orange-400 text-orange-700 text-xs font-semibold flex items-center gap-1">
|
||||
<FaClock className="text-xs" /> Pending
|
||||
</span>
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<AdminLayout>
|
||||
<div className="p-8">
|
||||
{/* Header */}
|
||||
<div className="flex items-center justify-between mb-8">
|
||||
<div>
|
||||
<h1 className="text-3xl font-bold text-paper-dark mb-2 border-b-4 border-paper-dark inline-block pb-1">Purchase History</h1>
|
||||
<h1 className="text-3xl font-bold text-paper-dark mb-2 border-b-4 border-paper-dark inline-block pb-1">
|
||||
Purchase Management
|
||||
</h1>
|
||||
<p className="text-paper-gray mt-4">
|
||||
{purchases.length} total purchases • {formatPrice(totalRevenue)} revenue
|
||||
{purchases.length} total • {pendingPurchases.length} pending • {formatPrice(totalRevenue)} revenue
|
||||
</p>
|
||||
</div>
|
||||
<motion.button
|
||||
@@ -81,15 +161,31 @@ export default function AdminPurchasesPage() {
|
||||
</motion.button>
|
||||
</div>
|
||||
|
||||
{/* Search */}
|
||||
<div className="mb-6">
|
||||
{/* Filters */}
|
||||
<div className="mb-6 space-y-4">
|
||||
<div className="flex gap-2">
|
||||
{(['all', 'pending', 'approved', 'rejected'] as const).map((status) => (
|
||||
<button
|
||||
key={status}
|
||||
onClick={() => setFilterStatus(status)}
|
||||
className={`px-4 py-2 border-2 font-medium transition-all ${
|
||||
filterStatus === status
|
||||
? 'bg-paper-brown text-paper-light border-paper-dark'
|
||||
: 'bg-paper-light text-paper-dark border-paper-brown hover:bg-paper-sand'
|
||||
}`}
|
||||
>
|
||||
{status.charAt(0).toUpperCase() + status.slice(1)}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="relative">
|
||||
<FaSearch className="absolute left-4 top-1/2 -translate-y-1/2 text-paper-gray" />
|
||||
<input
|
||||
type="text"
|
||||
value={searchTerm}
|
||||
onChange={(e) => setSearchTerm(e.target.value)}
|
||||
placeholder="Search by album name or transaction ID..."
|
||||
placeholder="Search by album, transaction ID, customer name, or email..."
|
||||
className="w-full pl-12 pr-4 py-3 bg-paper-light border-2 border-paper-brown focus:border-paper-dark focus:outline-none text-paper-dark placeholder-paper-gray shadow-paper"
|
||||
/>
|
||||
</div>
|
||||
@@ -101,16 +197,23 @@ export default function AdminPurchasesPage() {
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
className="paper-card border-2 border-paper-brown shadow-paper overflow-hidden"
|
||||
>
|
||||
{filteredPurchases.length > 0 ? (
|
||||
{loading ? (
|
||||
<div className="p-12 text-center">
|
||||
<p className="text-paper-gray">Loading purchases...</p>
|
||||
</div>
|
||||
) : filteredPurchases.length > 0 ? (
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full">
|
||||
<thead className="bg-paper-brown/20 border-b-2 border-paper-brown">
|
||||
<tr>
|
||||
<th className="text-left p-4 text-sm font-semibold text-paper-dark">Date & Time</th>
|
||||
<th className="text-left p-4 text-sm font-semibold text-paper-dark">Transaction ID</th>
|
||||
<th className="text-left p-4 text-sm font-semibold text-paper-dark">Customer</th>
|
||||
<th className="text-left p-4 text-sm font-semibold text-paper-dark">Album</th>
|
||||
<th className="text-left p-4 text-sm font-semibold text-paper-dark">Genre</th>
|
||||
<th className="text-center p-4 text-sm font-semibold text-paper-dark">Payment</th>
|
||||
<th className="text-center p-4 text-sm font-semibold text-paper-dark">Status</th>
|
||||
<th className="text-right p-4 text-sm font-semibold text-paper-dark">Price</th>
|
||||
<th className="text-center p-4 text-sm font-semibold text-paper-dark">Actions</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@@ -120,7 +223,7 @@ export default function AdminPurchasesPage() {
|
||||
|
||||
return (
|
||||
<motion.tr
|
||||
key={purchase.transactionId}
|
||||
key={purchase.id || purchase.transactionId}
|
||||
initial={{ opacity: 0, x: -20 }}
|
||||
animate={{ opacity: 1, x: 0 }}
|
||||
transition={{ delay: index * 0.05 }}
|
||||
@@ -134,15 +237,52 @@ export default function AdminPurchasesPage() {
|
||||
<code className="text-xs text-paper-brown bg-paper-brown/10 px-2 py-1 border border-paper-brown">
|
||||
{purchase.transactionId}
|
||||
</code>
|
||||
{purchase.txReceipt && (
|
||||
<div className="text-xs text-paper-gray mt-1">
|
||||
Receipt: {purchase.txReceipt}
|
||||
</div>
|
||||
)}
|
||||
</td>
|
||||
<td className="p-4">
|
||||
<div className="text-sm text-paper-dark">{purchase.customerName || 'N/A'}</div>
|
||||
<div className="text-xs text-paper-gray">{purchase.email}</div>
|
||||
<div className="text-xs text-paper-gray">{purchase.phoneNumber}</div>
|
||||
</td>
|
||||
<td className="p-4">
|
||||
<div className="text-paper-dark font-medium">{album?.title || 'Unknown'}</div>
|
||||
<div className="text-xs text-paper-gray">{album?.songs.length} tracks</div>
|
||||
</td>
|
||||
<td className="p-4 text-paper-gray text-sm">{album?.genre}</td>
|
||||
<td className="p-4 text-center">
|
||||
<span className="text-xs text-paper-brown bg-paper-brown/10 px-2 py-1 border border-paper-brown">
|
||||
{purchase.paymentMethod === 'ipg' ? 'IPG' : 'Card-to-Card'}
|
||||
</span>
|
||||
</td>
|
||||
<td className="p-4 text-center">
|
||||
{getStatusBadge(purchase.approvalStatus)}
|
||||
</td>
|
||||
<td className="p-4 text-right">
|
||||
<span className="text-paper-brown font-bold">{formatPrice(album?.price || 0)}</span>
|
||||
</td>
|
||||
<td className="p-4">
|
||||
{purchase.approvalStatus === 'pending' && (
|
||||
<div className="flex gap-2 justify-center">
|
||||
<button
|
||||
onClick={() => purchase.id && handleApprove(purchase.id)}
|
||||
className="p-2 bg-green-100 hover:bg-green-200 border-2 border-green-400 text-green-700 transition-colors"
|
||||
title="Approve"
|
||||
>
|
||||
<FaCheck />
|
||||
</button>
|
||||
<button
|
||||
onClick={() => purchase.id && handleReject(purchase.id)}
|
||||
className="p-2 bg-red-100 hover:bg-red-200 border-2 border-red-400 text-red-700 transition-colors"
|
||||
title="Reject"
|
||||
>
|
||||
<FaTimes />
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</td>
|
||||
</motion.tr>
|
||||
);
|
||||
})}
|
||||
@@ -152,7 +292,7 @@ export default function AdminPurchasesPage() {
|
||||
) : (
|
||||
<div className="p-12 text-center">
|
||||
<p className="text-paper-gray">
|
||||
{searchTerm ? 'No purchases found matching your search' : 'No purchases yet'}
|
||||
{searchTerm || filterStatus !== 'all' ? 'No purchases found matching your filters' : 'No purchases yet'}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
+21
-4
@@ -32,25 +32,42 @@ export default function AlbumDetailPage() {
|
||||
const foundAlbum = albums.find((a) => a.id === params.id);
|
||||
setAlbum(foundAlbum || null);
|
||||
|
||||
// Load purchases
|
||||
// Load purchases from localStorage (legacy)
|
||||
const savedPurchases = localStorage.getItem('purchases');
|
||||
if (savedPurchases) {
|
||||
const parsedPurchases = JSON.parse(savedPurchases);
|
||||
setPurchases(parsedPurchases);
|
||||
setPurchasedAlbums(parsedPurchases.map((p: Purchase) => p.albumId));
|
||||
}
|
||||
}, [params.id]);
|
||||
|
||||
// Fetch approved purchases from API
|
||||
const fetchPurchases = async () => {
|
||||
try {
|
||||
const response = await fetch('/api/purchases');
|
||||
if (response.ok) {
|
||||
const apiPurchases = await response.json();
|
||||
// Only include approved purchases for determining access
|
||||
const approvedPurchases = apiPurchases.filter((p: Purchase) => p.approvalStatus === 'approved');
|
||||
setPurchasedAlbums(approvedPurchases.map((p: Purchase) => p.albumId));
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error fetching purchases:', error);
|
||||
}
|
||||
};
|
||||
|
||||
fetchPurchases();
|
||||
}, [params.id, albums]);
|
||||
|
||||
const handlePurchaseSuccess = (albumId: string, transactionId: string) => {
|
||||
const purchase: Purchase = {
|
||||
albumId,
|
||||
transactionId,
|
||||
purchaseDate: new Date(),
|
||||
approvalStatus: 'pending',
|
||||
};
|
||||
|
||||
const updatedPurchases = [...purchases, purchase];
|
||||
setPurchases(updatedPurchases);
|
||||
setPurchasedAlbums([...purchasedAlbums, albumId]);
|
||||
// Don't add to purchasedAlbums yet - wait for approval
|
||||
setLatestPurchase(purchase);
|
||||
|
||||
localStorage.setItem('purchases', JSON.stringify(updatedPurchases));
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
""
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { albumDb } from '@/lib/db';
|
||||
import { Album } from '@/lib/types';
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { ZarinPal } from 'zarinpal-node-sdk';
|
||||
import { getDatabase } from '@/lib/db';
|
||||
|
||||
const zarinpal = new ZarinPal({
|
||||
merchantId: process.env.ZARINPAL_MERCHANT_ID || 'test-merchant-id',
|
||||
sandbox: process.env.NODE_ENV !== 'production',
|
||||
});
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
const body = await request.json();
|
||||
const { albumId, amount, customerName, email, phoneNumber } = body;
|
||||
|
||||
if (!albumId || !amount) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Album ID and amount are required' },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
// Clean phone number: remove +98, spaces, and any non-digits
|
||||
// ZarinPal expects format: 09XXXXXXXXX (11 digits starting with 0)
|
||||
const cleanPhone = phoneNumber.replace(/\D/g, ''); // Remove all non-digits
|
||||
const mobileNumber = cleanPhone.startsWith('98')
|
||||
? '0' + cleanPhone.slice(2) // +98 9390084053 -> 09390084053
|
||||
: cleanPhone.startsWith('9')
|
||||
? '0' + cleanPhone // 9390084053 -> 09390084053
|
||||
: cleanPhone; // Already in correct format
|
||||
|
||||
// Get the base URL for callback
|
||||
const protocol = request.headers.get('x-forwarded-proto') || 'http';
|
||||
const host = request.headers.get('host') || 'localhost:3000';
|
||||
const callback_url = `${protocol}://${host}/payment/callback`;
|
||||
|
||||
// Initiate payment with ZarinPal
|
||||
const response = await zarinpal.payments.create({
|
||||
amount: amount,
|
||||
callback_url: callback_url,
|
||||
description: `Purchase album: ${albumId}`,
|
||||
mobile: mobileNumber,
|
||||
email: email,
|
||||
});
|
||||
|
||||
if (response.data && response.data.code === 100) {
|
||||
const authority = response.data.authority;
|
||||
|
||||
// Store payment authority in database
|
||||
const db = getDatabase();
|
||||
db.prepare(`
|
||||
INSERT INTO payment_authorities (authority, albumId, amount, customerName, email, phoneNumber, status)
|
||||
VALUES (?, ?, ?, ?, ?, ?, 'pending')
|
||||
`).run(authority, albumId, amount, customerName, email, mobileNumber);
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
authority: authority,
|
||||
paymentUrl: `https://sandbox.zarinpal.com/pg/StartPay/${authority}`,
|
||||
});
|
||||
} else {
|
||||
return NextResponse.json(
|
||||
{ error: 'Failed to initiate payment', code: response.data?.code },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
} catch (error: any) {
|
||||
console.error('Payment initiation error:', error);
|
||||
return NextResponse.json(
|
||||
{ error: error.message || 'Failed to initiate payment' },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { ZarinPal } from 'zarinpal-node-sdk';
|
||||
import { getDatabase } from '@/lib/db';
|
||||
|
||||
const zarinpal = new ZarinPal({
|
||||
merchantId: process.env.ZARINPAL_MERCHANT_ID || 'test-merchant-id',
|
||||
sandbox: process.env.NODE_ENV !== 'production',
|
||||
});
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
const body = await request.json();
|
||||
const { authority } = body;
|
||||
|
||||
if (!authority) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Authority code is required' },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const db = getDatabase();
|
||||
|
||||
// Get payment details from database
|
||||
const paymentRecord = db.prepare(`
|
||||
SELECT * FROM payment_authorities WHERE authority = ?
|
||||
`).get(authority) as any;
|
||||
|
||||
if (!paymentRecord) {
|
||||
return NextResponse.json(
|
||||
{ error: 'No matching transaction found for this authority code' },
|
||||
{ status: 404 }
|
||||
);
|
||||
}
|
||||
|
||||
// Check if already verified
|
||||
if (paymentRecord.status === 'verified') {
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
refId: paymentRecord.refId,
|
||||
message: 'Payment already verified',
|
||||
});
|
||||
}
|
||||
|
||||
// Verify payment with ZarinPal
|
||||
const response = await zarinpal.verifications.verify({
|
||||
amount: paymentRecord.amount,
|
||||
authority: authority,
|
||||
});
|
||||
|
||||
if (response.data.code === 100 || response.data.code === 101) {
|
||||
const refId = response.data.ref_id;
|
||||
const cardPan = response.data.card_pan;
|
||||
const fee = response.data.fee;
|
||||
|
||||
// Update payment authority status
|
||||
db.prepare(`
|
||||
UPDATE payment_authorities
|
||||
SET status = 'verified', refId = ?, cardPan = ?, fee = ?, verifiedAt = ?
|
||||
WHERE authority = ?
|
||||
`).run(refId, cardPan, fee, Date.now(), authority);
|
||||
|
||||
// Create purchase record (auto-approved for IPG payments)
|
||||
db.prepare(`
|
||||
INSERT INTO purchases (albumId, transactionId, customerName, email, phoneNumber, txReceipt, purchaseDate, approvalStatus, paymentMethod)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, 'approved', 'ipg')
|
||||
`).run(
|
||||
paymentRecord.albumId,
|
||||
refId.toString(),
|
||||
paymentRecord.customerName,
|
||||
paymentRecord.email,
|
||||
paymentRecord.phoneNumber,
|
||||
`ZarinPal-${refId}`,
|
||||
Date.now()
|
||||
);
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
refId: refId,
|
||||
cardPan: cardPan,
|
||||
fee: fee,
|
||||
message: response.data.code === 101 ? 'Payment already verified' : 'Payment verified successfully',
|
||||
});
|
||||
} else {
|
||||
// Update payment authority status to failed
|
||||
db.prepare(`
|
||||
UPDATE payment_authorities
|
||||
SET status = 'failed'
|
||||
WHERE authority = ?
|
||||
`).run(authority);
|
||||
|
||||
return NextResponse.json(
|
||||
{ error: `Transaction failed with code: ${response.data.code}` },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
} catch (error: any) {
|
||||
console.error('Payment verification error:', error);
|
||||
return NextResponse.json(
|
||||
{ error: error.message || 'Failed to verify payment' },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { getDatabase } from '@/lib/db';
|
||||
|
||||
export async function PATCH(
|
||||
request: NextRequest,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
try {
|
||||
const { id } = await params;
|
||||
const purchaseId = parseInt(id);
|
||||
|
||||
if (isNaN(purchaseId)) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Invalid purchase ID' },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const db = getDatabase();
|
||||
|
||||
// Update purchase status to approved
|
||||
const result = db.prepare(`
|
||||
UPDATE purchases
|
||||
SET approvalStatus = 'approved'
|
||||
WHERE id = ?
|
||||
`).run(purchaseId);
|
||||
|
||||
if (result.changes === 0) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Purchase not found' },
|
||||
{ status: 404 }
|
||||
);
|
||||
}
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
message: 'Purchase approved successfully'
|
||||
});
|
||||
} catch (error: any) {
|
||||
console.error('Error approving purchase:', error);
|
||||
return NextResponse.json(
|
||||
{ error: error.message || 'Failed to approve purchase' },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { getDatabase } from '@/lib/db';
|
||||
|
||||
export async function PATCH(
|
||||
request: NextRequest,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
try {
|
||||
const { id } = await params;
|
||||
const purchaseId = parseInt(id);
|
||||
|
||||
if (isNaN(purchaseId)) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Invalid purchase ID' },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const db = getDatabase();
|
||||
|
||||
// Update purchase status to rejected
|
||||
const result = db.prepare(`
|
||||
UPDATE purchases
|
||||
SET approvalStatus = 'rejected'
|
||||
WHERE id = ?
|
||||
`).run(purchaseId);
|
||||
|
||||
if (result.changes === 0) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Purchase not found' },
|
||||
{ status: 404 }
|
||||
);
|
||||
}
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
message: 'Purchase rejected successfully'
|
||||
});
|
||||
} catch (error: any) {
|
||||
console.error('Error rejecting purchase:', error);
|
||||
return NextResponse.json(
|
||||
{ error: error.message || 'Failed to reject purchase' },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
+9
-6
@@ -1,16 +1,19 @@
|
||||
import type { Metadata } from 'next';
|
||||
import { Inter } from 'next/font/google';
|
||||
import { Vazirmatn } from 'next/font/google';
|
||||
import './globals.css';
|
||||
import { CartProvider } from '@/lib/CartContext';
|
||||
import { AdminProvider } from '@/lib/AdminContext';
|
||||
import { AlbumsProvider } from '@/lib/AlbumsContext';
|
||||
|
||||
const inter = Inter({ subsets: ['latin'] });
|
||||
const vazirmatn = Vazirmatn({
|
||||
subsets: ['latin', 'arabic'],
|
||||
display: 'swap',
|
||||
});
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: 'Parsa - Progressive Rock Composer',
|
||||
description: 'Explore progressive rock albums by composer and producer Parsa. Intricate compositions, powerful instrumentation, and sonic landscapes.',
|
||||
keywords: ['progressive rock', 'prog rock', 'music', 'composer', 'producer', 'albums'],
|
||||
title: 'Podzahr - Parsa Sadatie Music',
|
||||
description: 'Explore progressive rock albums by composer and producer Parsa Sadatie (@parsadat). Intricate compositions, powerful instrumentation, and sonic landscapes.',
|
||||
keywords: ['podzahr', 'parsa sadatie', 'progressive rock', 'prog rock', 'music', 'composer', 'producer', 'albums'],
|
||||
};
|
||||
|
||||
export default function RootLayout({
|
||||
@@ -20,7 +23,7 @@ export default function RootLayout({
|
||||
}>) {
|
||||
return (
|
||||
<html lang="en">
|
||||
<body className={inter.className}>
|
||||
<body className={vazirmatn.className}>
|
||||
<AdminProvider>
|
||||
<AlbumsProvider>
|
||||
<CartProvider>{children}</CartProvider>
|
||||
|
||||
+20
-3
@@ -19,14 +19,30 @@ export default function Home() {
|
||||
const [latestPurchase, setLatestPurchase] = useState<Purchase | null>(null);
|
||||
const [cartOpen, setCartOpen] = useState(false);
|
||||
|
||||
// Load purchases from localStorage on mount
|
||||
// Load purchases from localStorage and API on mount
|
||||
useEffect(() => {
|
||||
const savedPurchases = localStorage.getItem('purchases');
|
||||
if (savedPurchases) {
|
||||
const parsedPurchases = JSON.parse(savedPurchases);
|
||||
setPurchases(parsedPurchases);
|
||||
setPurchasedAlbums(parsedPurchases.map((p: Purchase) => p.albumId));
|
||||
}
|
||||
|
||||
// Fetch approved purchases from API
|
||||
const fetchPurchases = async () => {
|
||||
try {
|
||||
const response = await fetch('/api/purchases');
|
||||
if (response.ok) {
|
||||
const apiPurchases = await response.json();
|
||||
// Only include approved purchases for determining access
|
||||
const approvedPurchases = apiPurchases.filter((p: Purchase) => p.approvalStatus === 'approved');
|
||||
setPurchasedAlbums(approvedPurchases.map((p: Purchase) => p.albumId));
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error fetching purchases:', error);
|
||||
}
|
||||
};
|
||||
|
||||
fetchPurchases();
|
||||
}, []);
|
||||
|
||||
const handlePlayAlbum = (album: Album) => {
|
||||
@@ -42,11 +58,12 @@ export default function Home() {
|
||||
albumId,
|
||||
transactionId,
|
||||
purchaseDate: new Date(),
|
||||
approvalStatus: 'pending',
|
||||
};
|
||||
|
||||
const updatedPurchases = [...purchases, purchase];
|
||||
setPurchases(updatedPurchases);
|
||||
setPurchasedAlbums([...purchasedAlbums, albumId]);
|
||||
// Don't add to purchasedAlbums yet - wait for approval
|
||||
setLatestPurchase(purchase);
|
||||
|
||||
// Save to localStorage
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect, useState, Suspense } from 'react';
|
||||
import { useRouter, useSearchParams } from 'next/navigation';
|
||||
import { motion } from 'framer-motion';
|
||||
import { FaCheckCircle, FaTimesCircle, FaSpinner } from 'react-icons/fa';
|
||||
|
||||
function CallbackContent() {
|
||||
const router = useRouter();
|
||||
const searchParams = useSearchParams();
|
||||
const [status, setStatus] = useState<'verifying' | 'success' | 'failed'>('verifying');
|
||||
const [message, setMessage] = useState('Verifying your payment...');
|
||||
const [refId, setRefId] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const authority = searchParams.get('Authority');
|
||||
const statusParam = searchParams.get('Status');
|
||||
|
||||
if (!authority || !statusParam) {
|
||||
setStatus('failed');
|
||||
setMessage('Invalid payment callback');
|
||||
return;
|
||||
}
|
||||
|
||||
if (statusParam !== 'OK') {
|
||||
setStatus('failed');
|
||||
setMessage('Payment was cancelled or failed');
|
||||
return;
|
||||
}
|
||||
|
||||
// Verify the payment
|
||||
verifyPayment(authority);
|
||||
}, [searchParams]);
|
||||
|
||||
const verifyPayment = async (authority: string) => {
|
||||
try {
|
||||
const response = await fetch('/api/payment/verify', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ authority }),
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
if (response.ok && data.success) {
|
||||
setStatus('success');
|
||||
setMessage(`Payment verified successfully!`);
|
||||
setRefId(data.refId);
|
||||
|
||||
// Redirect to home after 3 seconds
|
||||
setTimeout(() => {
|
||||
router.push('/');
|
||||
}, 3000);
|
||||
} else {
|
||||
setStatus('failed');
|
||||
setMessage(data.error || 'Payment verification failed');
|
||||
}
|
||||
} catch (error: any) {
|
||||
setStatus('failed');
|
||||
setMessage('Failed to verify payment');
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-paper-light flex items-center justify-center p-4">
|
||||
<motion.div
|
||||
initial={{ opacity: 0, scale: 0.9 }}
|
||||
animate={{ opacity: 1, scale: 1 }}
|
||||
className="paper-card max-w-md w-full p-8 border-4 border-paper-dark shadow-paper-lg text-center"
|
||||
>
|
||||
{status === 'verifying' && (
|
||||
<>
|
||||
<FaSpinner className="text-6xl text-paper-brown mx-auto mb-4 animate-spin" />
|
||||
<h1 className="text-2xl font-bold text-paper-dark mb-2">Verifying Payment</h1>
|
||||
<p className="text-paper-gray">{message}</p>
|
||||
</>
|
||||
)}
|
||||
|
||||
{status === 'success' && (
|
||||
<>
|
||||
<motion.div
|
||||
initial={{ scale: 0 }}
|
||||
animate={{ scale: 1 }}
|
||||
transition={{ type: 'spring', stiffness: 200 }}
|
||||
>
|
||||
<FaCheckCircle className="text-6xl text-green-600 mx-auto mb-4" />
|
||||
</motion.div>
|
||||
<h1 className="text-2xl font-bold text-paper-dark mb-2 border-b-4 border-paper-dark inline-block pb-1">
|
||||
Payment Successful!
|
||||
</h1>
|
||||
<p className="text-paper-gray mt-4">{message}</p>
|
||||
{refId && (
|
||||
<div className="mt-4 p-3 bg-paper-light border-2 border-paper-brown">
|
||||
<p className="text-xs text-paper-gray">Reference ID:</p>
|
||||
<p className="text-sm font-mono text-paper-dark font-semibold">{refId}</p>
|
||||
</div>
|
||||
)}
|
||||
<p className="text-sm text-paper-gray mt-4">Redirecting you to the home page...</p>
|
||||
</>
|
||||
)}
|
||||
|
||||
{status === 'failed' && (
|
||||
<>
|
||||
<motion.div
|
||||
initial={{ scale: 0 }}
|
||||
animate={{ scale: 1 }}
|
||||
transition={{ type: 'spring', stiffness: 200 }}
|
||||
>
|
||||
<FaTimesCircle className="text-6xl text-red-600 mx-auto mb-4" />
|
||||
</motion.div>
|
||||
<h1 className="text-2xl font-bold text-paper-dark mb-2 border-b-4 border-paper-dark inline-block pb-1">
|
||||
Payment Failed
|
||||
</h1>
|
||||
<p className="text-paper-gray mt-4">{message}</p>
|
||||
<button
|
||||
onClick={() => router.push('/')}
|
||||
className="mt-6 px-6 py-3 bg-paper-brown hover:bg-paper-dark border-2 border-paper-dark text-paper-light font-semibold transition-all shadow-paper"
|
||||
>
|
||||
Return to Home
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
</motion.div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function PaymentCallback() {
|
||||
return (
|
||||
<Suspense fallback={
|
||||
<div className="min-h-screen bg-paper-light flex items-center justify-center">
|
||||
<FaSpinner className="text-6xl text-paper-brown animate-spin" />
|
||||
</div>
|
||||
}>
|
||||
<CallbackContent />
|
||||
</Suspense>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user