Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
cce279a60d | ||
|
|
a447222201 | ||
|
|
05262b7636 | ||
|
|
3c0098ceab | ||
|
|
62398fbf3d | ||
|
|
6c005783e0 | ||
|
|
a25fd73eea | ||
|
|
555e56c50a | ||
|
|
a186db08e2 | ||
|
|
958f29b685 | ||
|
|
6c52a020eb | ||
|
|
f80fdd61ca | ||
|
|
07c93ceb91 | ||
|
|
cdf6239496 | ||
|
|
754c1c3178 | ||
|
|
99d29bbce5 | ||
|
|
577d8afb53 | ||
|
|
d65b73a593 | ||
|
|
240e8f4c13 | ||
|
|
c2b55647aa | ||
|
|
dcc1d1e258 | ||
|
|
d056c8b96c | ||
|
|
f641409d8a | ||
|
|
74f2a82a0e | ||
|
|
9aff48019d |
@@ -0,0 +1,22 @@
|
||||
#!/usr/bin/env bash
|
||||
# Runs on `git push`. If a tag ref is among what's being pushed, build locally
|
||||
# and deploy to the server. Normal branch pushes are untouched.
|
||||
set -euo pipefail
|
||||
|
||||
deploy=0
|
||||
tag=""
|
||||
while read -r local_ref _local_sha _remote_ref _remote_sha; do
|
||||
case "$local_ref" in
|
||||
refs/tags/*)
|
||||
deploy=1
|
||||
tag="${local_ref#refs/tags/}"
|
||||
;;
|
||||
esac
|
||||
done
|
||||
|
||||
if [ "$deploy" = "1" ]; then
|
||||
echo "→ Tag '$tag' is being pushed — building locally and deploying to the server…"
|
||||
exec "$(git rev-parse --show-toplevel)/scripts/deploy.sh"
|
||||
fi
|
||||
|
||||
exit 0
|
||||
@@ -1 +1,35 @@
|
||||
node_modules/
|
||||
# Next.js build output
|
||||
.next/
|
||||
.next/**
|
||||
.next/dev/lock
|
||||
out
|
||||
appro-admin
|
||||
appro-admin.zip
|
||||
*.zip
|
||||
|
||||
# Dependencies
|
||||
node_modules/
|
||||
|
||||
# Environment files
|
||||
.env
|
||||
.env.local
|
||||
.env.development.local
|
||||
.env.test.local
|
||||
.env.production.local
|
||||
|
||||
# Debug logs
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
|
||||
# Editor directories and files
|
||||
.vscode/
|
||||
.idea/
|
||||
*.suo
|
||||
*.ntvs*
|
||||
*.njsproj
|
||||
*.sln
|
||||
*.sw?
|
||||
|
||||
# TypeScript
|
||||
tsconfig.tsbuildinfo
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
'use client';
|
||||
|
||||
import { useAuth } from '@/contexts/AuthContext';
|
||||
import Link from 'next/link';
|
||||
import { UsersIcon, CubeIcon, TagIcon, BellIcon, GiftIcon, ShoppingBagIcon } from '@heroicons/react/24/outline';
|
||||
import { MegaphoneIcon } from 'lucide-react';
|
||||
|
||||
export default function Dashboard() {
|
||||
const { user } = useAuth();
|
||||
|
||||
const cards = [
|
||||
{
|
||||
href: '/admin/users',
|
||||
title: 'مدیریت کاربران',
|
||||
desc: 'مشاهده و مدیریت کاربران، اشتراکها و تراکنشها',
|
||||
Icon: UsersIcon,
|
||||
iconBg: 'bg-indigo-100 dark:bg-indigo-500/15',
|
||||
iconColor: 'text-indigo-600 dark:text-indigo-400',
|
||||
hoverBorder: 'hover:border-indigo-300 dark:hover:border-indigo-700',
|
||||
},
|
||||
{
|
||||
href: '/admin/purchases',
|
||||
title: 'خریدهای اشتراک',
|
||||
desc: 'مشاهده و فیلتر خریدها بر اساس ایمیل، موبایل، پکیج و منبع پرداخت',
|
||||
Icon: ShoppingBagIcon,
|
||||
iconBg: 'bg-orange-100 dark:bg-orange-500/15',
|
||||
iconColor: 'text-orange-600 dark:text-orange-400',
|
||||
hoverBorder: 'hover:border-orange-300 dark:hover:border-orange-700',
|
||||
},
|
||||
{
|
||||
href: '/admin/packages',
|
||||
title: 'مدیریت پکیجها',
|
||||
desc: 'ایجاد و مدیریت پکیجهای نرمافزار',
|
||||
Icon: CubeIcon,
|
||||
iconBg: 'bg-green-100 dark:bg-green-500/15',
|
||||
iconColor: 'text-green-600 dark:text-green-400',
|
||||
hoverBorder: 'hover:border-green-300 dark:hover:border-green-700',
|
||||
},
|
||||
{
|
||||
href: '/admin/products',
|
||||
title: 'مدیریت محصولات',
|
||||
desc: 'ایجاد و مدیریت محصولات و اشتراکها',
|
||||
Icon: TagIcon,
|
||||
iconBg: 'bg-purple-100 dark:bg-purple-500/15',
|
||||
iconColor: 'text-purple-600 dark:text-purple-400',
|
||||
hoverBorder: 'hover:border-purple-300 dark:hover:border-purple-700',
|
||||
},
|
||||
{
|
||||
href: '/admin/reminders',
|
||||
title: 'مدیریت یادآوریها',
|
||||
desc: 'ایجاد و مدیریت یادآوریها و پیامهای انگیزشی',
|
||||
Icon: BellIcon,
|
||||
iconBg: 'bg-yellow-100 dark:bg-yellow-500/15',
|
||||
iconColor: 'text-yellow-600 dark:text-yellow-400',
|
||||
hoverBorder: 'hover:border-yellow-300 dark:hover:border-yellow-700',
|
||||
},
|
||||
{
|
||||
href: '/admin/promotions',
|
||||
title: 'مدیریت تبلیغات',
|
||||
desc: 'ایجاد و مدیریت تبلیغات، بنرها و اسلایدرها',
|
||||
Icon: MegaphoneIcon,
|
||||
iconBg: 'bg-pink-100 dark:bg-pink-500/15',
|
||||
iconColor: 'text-pink-600 dark:text-pink-400',
|
||||
hoverBorder: 'hover:border-pink-300 dark:hover:border-pink-700',
|
||||
},
|
||||
{
|
||||
href: '/admin/referral-rewards',
|
||||
title: 'پاداشهای معرفی',
|
||||
desc: 'اعطای اشتراک رایگان به کاربران واجد شرایط دعوت',
|
||||
Icon: GiftIcon,
|
||||
iconBg: 'bg-emerald-100 dark:bg-emerald-500/15',
|
||||
iconColor: 'text-emerald-600 dark:text-emerald-400',
|
||||
hoverBorder: 'hover:border-emerald-300 dark:hover:border-emerald-700',
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<div className="p-4 sm:p-8">
|
||||
<div className="max-w-7xl mx-auto">
|
||||
{/* Welcome Section */}
|
||||
<div className="mb-8">
|
||||
<div className="bg-gradient-to-l from-indigo-600 to-indigo-700 rounded-2xl p-6 sm:p-8 text-white shadow-lg shadow-indigo-500/20">
|
||||
<h1 className="text-2xl sm:text-3xl font-bold">
|
||||
خوش آمدید
|
||||
</h1>
|
||||
<p className="mt-1 text-indigo-100 text-sm sm:text-base">
|
||||
{user?.email}
|
||||
</p>
|
||||
<p className="mt-3 text-indigo-200 text-sm">
|
||||
یکی از بخشهای زیر را برای مدیریت انتخاب کنید
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Dashboard Cards */}
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
|
||||
{cards.map(({ href, title, desc, Icon, iconBg, iconColor, hoverBorder }) => (
|
||||
<Link key={href} href={href} className="block group">
|
||||
<div className={`h-full bg-white dark:bg-gray-900 rounded-2xl p-5 ring-1 ring-gray-200 dark:ring-gray-800 shadow-sm hover:shadow-md ${hoverBorder} hover:-translate-y-0.5 transition-all duration-200`}>
|
||||
<div className={`inline-flex h-11 w-11 items-center justify-center rounded-xl mb-3 ${iconBg}`}>
|
||||
<Icon className={`h-5.5 w-5.5 ${iconColor}`} />
|
||||
</div>
|
||||
<h3 className="text-base font-semibold text-gray-900 dark:text-gray-100">{title}</h3>
|
||||
<p className="text-sm text-gray-500 dark:text-gray-400 mt-1.5 leading-relaxed">
|
||||
{desc}
|
||||
</p>
|
||||
<div className="mt-4 flex items-center text-xs font-medium text-indigo-600 dark:text-indigo-400 opacity-0 group-hover:opacity-100 transition-opacity">
|
||||
ورود به بخش
|
||||
<svg className="h-4 w-4 mr-1 rotate-180" fill="none" viewBox="0 0 24 24" strokeWidth={2} stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" d="M13.5 4.5 21 12m0 0-7.5 7.5M21 12H3" />
|
||||
</svg>
|
||||
</div>
|
||||
</div>
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
'use client';
|
||||
|
||||
import { AuthProvider } from '@/contexts/AuthContext';
|
||||
import AuthGuard from '@/components/AuthGuard';
|
||||
import Sidebar from '@/components/admin/Sidebar';
|
||||
import ToastContainer from '@/components/Toast';
|
||||
import { usePathname } from 'next/navigation';
|
||||
|
||||
export default function AdminLayout({
|
||||
children,
|
||||
}: {
|
||||
children: React.ReactNode;
|
||||
}) {
|
||||
const pathname = usePathname();
|
||||
const isLogin = pathname === '/admin/login' || pathname === '/admin/login/';
|
||||
|
||||
return (
|
||||
<AuthProvider>
|
||||
<div className="min-h-screen bg-gray-50 dark:bg-gray-950">
|
||||
<ToastContainer />
|
||||
{isLogin ? (
|
||||
children
|
||||
) : (
|
||||
<AuthGuard>
|
||||
<Sidebar />
|
||||
<main className="lg:pr-64 min-h-screen">
|
||||
{children}
|
||||
</main>
|
||||
</AuthGuard>
|
||||
)}
|
||||
</div>
|
||||
</AuthProvider>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useAuth } from '@/contexts/AuthContext';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { LockClosedIcon } from '@heroicons/react/24/outline';
|
||||
|
||||
export default function LoginPage() {
|
||||
const [auth, setAuth] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [localError, setLocalError] = useState('');
|
||||
|
||||
const { login, isLoading, error, token } = useAuth();
|
||||
const router = useRouter();
|
||||
|
||||
useEffect(() => {
|
||||
if (token) {
|
||||
router.push('/admin/dashboard');
|
||||
}
|
||||
}, [token, router]);
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setLocalError('');
|
||||
|
||||
if (!auth || !password) {
|
||||
setLocalError('لطفاً همه فیلدها را پر کنید');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await login({ auth, password });
|
||||
} catch (err) {
|
||||
// Error is handled by context
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-gray-50 via-indigo-50/30 to-gray-100 dark:from-gray-950 dark:via-indigo-950/20 dark:to-gray-950 py-12 px-4 sm:px-6 lg:px-8">
|
||||
{/* Decorative background */}
|
||||
<div className="absolute inset-0 overflow-hidden pointer-events-none">
|
||||
<div className="absolute -top-40 -right-40 w-80 h-80 bg-indigo-100 dark:bg-indigo-500/10 rounded-full blur-3xl opacity-60" />
|
||||
<div className="absolute -bottom-40 -left-40 w-80 h-80 bg-indigo-100 dark:bg-indigo-500/10 rounded-full blur-3xl opacity-40" />
|
||||
</div>
|
||||
|
||||
<div className="relative max-w-md w-full">
|
||||
<div className="bg-white/80 dark:bg-gray-900/80 backdrop-blur-xl rounded-3xl shadow-xl shadow-gray-200/50 dark:shadow-black/30 ring-1 ring-gray-200/60 dark:ring-gray-800/60 p-8 space-y-8">
|
||||
<div>
|
||||
<div className="mx-auto h-16 w-16 rounded-2xl bg-gradient-to-br from-indigo-500 to-indigo-700 flex items-center justify-center mb-5 shadow-lg shadow-indigo-500/30">
|
||||
<LockClosedIcon className="h-8 w-8 text-white" />
|
||||
</div>
|
||||
<h2 className="text-center text-2xl font-bold text-gray-900 dark:text-gray-100">
|
||||
پنل ادمین
|
||||
</h2>
|
||||
<p className="mt-2 text-center text-sm text-gray-500 dark:text-gray-400">
|
||||
اپروایجنسی
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<form className="space-y-5" onSubmit={handleSubmit}>
|
||||
<div className="space-y-4">
|
||||
<div>
|
||||
<label htmlFor="auth" className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5">
|
||||
ایمیل یا نام کاربری
|
||||
</label>
|
||||
<input
|
||||
id="auth"
|
||||
name="auth"
|
||||
type="text"
|
||||
required
|
||||
className="block w-full px-4 py-3 border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800/80 placeholder-gray-400 dark:placeholder-gray-500 text-gray-900 dark:text-gray-100 rounded-xl focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-transparent sm:text-sm transition-all duration-150 shadow-sm"
|
||||
placeholder="example@email.com"
|
||||
value={auth}
|
||||
onChange={(e) => setAuth(e.target.value)}
|
||||
disabled={isLoading}
|
||||
dir="ltr"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label htmlFor="password" className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5">
|
||||
رمز عبور
|
||||
</label>
|
||||
<input
|
||||
id="password"
|
||||
name="password"
|
||||
type="password"
|
||||
required
|
||||
className="block w-full px-4 py-3 border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800/80 placeholder-gray-400 dark:placeholder-gray-500 text-gray-900 dark:text-gray-100 rounded-xl focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-transparent sm:text-sm transition-all duration-150 shadow-sm"
|
||||
placeholder="••••••••"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
disabled={isLoading}
|
||||
dir="ltr"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{(error || localError) && (
|
||||
<div className="rounded-xl bg-red-50 dark:bg-red-950/40 ring-1 ring-red-200 dark:ring-red-800/60 p-4">
|
||||
<p className="text-sm font-medium text-red-700 dark:text-red-300 text-center">
|
||||
{localError || error}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={isLoading}
|
||||
className="relative w-full flex justify-center items-center py-3 px-4 border border-transparent text-sm font-semibold rounded-xl text-white bg-gradient-to-l from-indigo-600 to-indigo-700 hover:from-indigo-700 hover:to-indigo-800 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 dark:focus:ring-offset-gray-900 disabled:opacity-50 disabled:cursor-not-allowed shadow-lg shadow-indigo-500/25 hover:shadow-xl hover:shadow-indigo-500/30 transition-all duration-150"
|
||||
>
|
||||
{isLoading ? (
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="h-4 w-4 border-2 border-white/30 border-t-white rounded-full animate-spin" />
|
||||
کمی صبر کنید...
|
||||
</div>
|
||||
) : (
|
||||
'ورود'
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useAuth } from '@/contexts/AuthContext';
|
||||
import { packagesApi } from '@/lib/api/packages';
|
||||
import PackageList from '@/components/admin/packages/PackageList';
|
||||
import PackageForm from '@/components/admin/packages/PackageForm';
|
||||
import PageHeader from '@/components/admin/PageHeader';
|
||||
import { showToast } from '@/components/Toast';
|
||||
import { PackageName, CreatePackageData, UpdatePackageData } from '@/types/package';
|
||||
import { PlusIcon } from '@heroicons/react/24/outline';
|
||||
|
||||
export default function PackagesPage() {
|
||||
const { token } = useAuth();
|
||||
const [packages, setPackages] = useState<PackageName[]>([]);
|
||||
const [selectedPackage, setSelectedPackage] = useState<PackageName | null>(null);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [isFormVisible, setIsFormVisible] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (token) {
|
||||
loadPackages();
|
||||
}
|
||||
}, [token]);
|
||||
|
||||
const loadPackages = async () => {
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const data = await packagesApi.getAllPackages(token!);
|
||||
setPackages(data);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'خطا در دریافت لیست پکیجها');
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleCreate = () => {
|
||||
setSelectedPackage(null);
|
||||
setIsFormVisible(true);
|
||||
};
|
||||
|
||||
const handleEdit = (pkg: PackageName) => {
|
||||
setSelectedPackage(pkg);
|
||||
setIsFormVisible(true);
|
||||
};
|
||||
|
||||
const handleDelete = async (pkg: PackageName) => {
|
||||
if (!confirm(`آیا از حذف پکیج "${pkg.title}" اطمینان دارید؟`)) {
|
||||
return;
|
||||
}
|
||||
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
await packagesApi.deletePackage(pkg.name!, token!);
|
||||
showToast('success', 'پکیج با موفقیت حذف شد');
|
||||
await loadPackages();
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'خطا در حذف پکیج');
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleSubmit = async (data: CreatePackageData | UpdatePackageData) => {
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
if (selectedPackage) {
|
||||
await packagesApi.updatePackage(selectedPackage.name!, data, token!);
|
||||
showToast('success', 'پکیج با موفقیت بهروزرسانی شد');
|
||||
} else {
|
||||
await packagesApi.createPackage(data as CreatePackageData, token!);
|
||||
showToast('success', 'پکیج با موفقیت ایجاد شد');
|
||||
}
|
||||
|
||||
await loadPackages();
|
||||
setIsFormVisible(false);
|
||||
setSelectedPackage(null);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'خطا در ذخیره پکیج');
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleCancel = () => {
|
||||
setIsFormVisible(false);
|
||||
setSelectedPackage(null);
|
||||
setError(null);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="p-4 sm:p-8">
|
||||
<div className="max-w-7xl mx-auto">
|
||||
<PageHeader
|
||||
title="مدیریت پکیجها"
|
||||
action={
|
||||
!isFormVisible ? (
|
||||
<button
|
||||
onClick={handleCreate}
|
||||
className="inline-flex items-center gap-2 px-4 py-2.5 bg-indigo-600 text-white rounded-xl text-sm font-medium hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 dark:focus:ring-offset-gray-900 transition-colors shadow-sm shadow-indigo-500/20"
|
||||
>
|
||||
<PlusIcon className="h-4 w-4" />
|
||||
پکیج جدید
|
||||
</button>
|
||||
) : undefined
|
||||
}
|
||||
/>
|
||||
|
||||
{error && (
|
||||
<div className="mb-4 rounded-xl bg-red-50 dark:bg-red-950/40 ring-1 ring-red-200 dark:ring-red-800/60 p-4 flex items-center gap-3">
|
||||
<p className="text-sm text-red-700 dark:text-red-300">{error}</p>
|
||||
<button onClick={() => setError(null)} className="mr-auto text-red-400 hover:text-red-600">
|
||||
<svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" strokeWidth={2} stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" d="M6 18 18 6M6 6l12 12" />
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{isFormVisible ? (
|
||||
<PackageForm
|
||||
package={selectedPackage}
|
||||
onSubmit={handleSubmit}
|
||||
onCancel={handleCancel}
|
||||
isLoading={isLoading}
|
||||
/>
|
||||
) : (
|
||||
<PackageList
|
||||
packages={packages}
|
||||
onEdit={handleEdit}
|
||||
onDelete={handleDelete}
|
||||
isLoading={isLoading}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,232 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useEffect, useCallback, useRef } from 'react';
|
||||
import { useAuth } from '@/contexts/AuthContext';
|
||||
import { packagesApi } from '@/lib/api/packages';
|
||||
import { productsApi } from '@/lib/api/products';
|
||||
import ProductList from '@/components/admin/products/ProductList';
|
||||
import ProductForm from '@/components/admin/products/ProductForm';
|
||||
import PageHeader from '@/components/admin/PageHeader';
|
||||
import { showToast } from '@/components/Toast';
|
||||
import { PackageName } from '@/types/package';
|
||||
import { Product, CreateProductData, UpdateProductData } from '@/types/product';
|
||||
import { PlusIcon } from '@heroicons/react/24/outline';
|
||||
|
||||
export default function ProductsPage() {
|
||||
const { token } = useAuth();
|
||||
const [packages, setPackages] = useState<PackageName[]>([]);
|
||||
const [selectedPackage, setSelectedPackage] = useState<PackageName | null>(null);
|
||||
const [products, setProducts] = useState<Product[]>([]);
|
||||
const [selectedProduct, setSelectedProduct] = useState<Product | null>(null);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [isLoadingPackages, setIsLoadingPackages] = useState(false);
|
||||
const [isFormVisible, setIsFormVisible] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const initialLoadRef = useRef(false);
|
||||
const prevPackageRef = useRef<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (token && !initialLoadRef.current) {
|
||||
initialLoadRef.current = true;
|
||||
loadPackages();
|
||||
}
|
||||
}, [token]);
|
||||
|
||||
const loadPackages = async () => {
|
||||
setIsLoadingPackages(true);
|
||||
setError(null);
|
||||
try {
|
||||
const data = await packagesApi.getAllPackages(token!);
|
||||
setPackages(data);
|
||||
if (data.length > 0 && !selectedPackage) {
|
||||
setSelectedPackage(data[0]);
|
||||
}
|
||||
} catch (err) {
|
||||
setError('خطا در دریافت لیست پکیجها');
|
||||
} finally {
|
||||
setIsLoadingPackages(false);
|
||||
}
|
||||
};
|
||||
|
||||
const loadProducts = useCallback(async (packageName: string, force = false) => {
|
||||
if (!force && prevPackageRef.current === packageName) {
|
||||
return;
|
||||
}
|
||||
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
prevPackageRef.current = packageName;
|
||||
|
||||
try {
|
||||
const data = await productsApi.getProducts(packageName, token!);
|
||||
setProducts(data);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'خطا در دریافت محصولات');
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, [token]);
|
||||
|
||||
useEffect(() => {
|
||||
if (selectedPackage?.name && token) {
|
||||
loadProducts(selectedPackage.name);
|
||||
} else {
|
||||
setProducts([]);
|
||||
}
|
||||
}, [selectedPackage?.name, token, loadProducts]);
|
||||
|
||||
const handlePackageChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
|
||||
const pkg = packages.find(p => p.name === e.target.value);
|
||||
setSelectedPackage(pkg || null);
|
||||
setIsFormVisible(false);
|
||||
setSelectedProduct(null);
|
||||
setError(null);
|
||||
};
|
||||
|
||||
const handleCreate = () => {
|
||||
setSelectedProduct(null);
|
||||
setIsFormVisible(true);
|
||||
};
|
||||
|
||||
const handleEdit = (product: Product) => {
|
||||
setSelectedProduct(product);
|
||||
setIsFormVisible(true);
|
||||
};
|
||||
|
||||
const handleDelete = async (product: Product) => {
|
||||
if (!selectedPackage) return;
|
||||
if (!confirm(`آیا از حذف محصول "${product.title}" اطمینان دارید؟`)) {
|
||||
return;
|
||||
}
|
||||
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
await productsApi.deleteProduct(selectedPackage.name!, product.id, token!);
|
||||
showToast('success', 'محصول با موفقیت حذف شد');
|
||||
if (selectedPackage.name) {
|
||||
prevPackageRef.current = null;
|
||||
await loadProducts(selectedPackage.name, true);
|
||||
}
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'خطا در حذف محصول');
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleSubmit = async (data: CreateProductData | UpdateProductData) => {
|
||||
if (!selectedPackage) return;
|
||||
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
if (selectedProduct) {
|
||||
await productsApi.updateProduct(selectedPackage.name!, selectedProduct.id, data, token!);
|
||||
showToast('success', 'محصول با موفقیت بهروزرسانی شد');
|
||||
} else {
|
||||
await productsApi.createProduct(selectedPackage.name!, data as CreateProductData, token!);
|
||||
showToast('success', 'محصول با موفقیت ایجاد شد');
|
||||
}
|
||||
|
||||
if (selectedPackage.name) {
|
||||
prevPackageRef.current = null;
|
||||
await loadProducts(selectedPackage.name, true);
|
||||
}
|
||||
|
||||
setIsFormVisible(false);
|
||||
setSelectedProduct(null);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'خطا در ذخیره محصول');
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleCancel = () => {
|
||||
setIsFormVisible(false);
|
||||
setSelectedProduct(null);
|
||||
setError(null);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="p-4 sm:p-8">
|
||||
<div className="max-w-7xl mx-auto">
|
||||
<PageHeader title="مدیریت محصولات" />
|
||||
|
||||
{/* Package Selector */}
|
||||
<div className="bg-white dark:bg-gray-900 p-4 rounded-2xl ring-1 ring-gray-200 dark:ring-gray-800 shadow-sm mb-6">
|
||||
<label htmlFor="package" className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
|
||||
انتخاب پکیج
|
||||
</label>
|
||||
<select
|
||||
id="package"
|
||||
value={selectedPackage?.name || ''}
|
||||
onChange={handlePackageChange}
|
||||
disabled={isLoadingPackages}
|
||||
className="block w-full px-3 py-2.5 text-gray-900 dark:text-gray-100 border border-gray-200 dark:border-gray-700 rounded-xl shadow-sm focus:ring-2 focus:ring-indigo-500 focus:border-transparent sm:text-sm disabled:opacity-50 dark:bg-gray-800/80 transition-colors"
|
||||
>
|
||||
{isLoadingPackages ? (
|
||||
<option>در حال بارگذاری پکیجها...</option>
|
||||
) : (
|
||||
packages.map((pkg) => (
|
||||
<option key={pkg.id} value={pkg.name || ''}>
|
||||
{pkg.title} ({pkg.name})
|
||||
</option>
|
||||
))
|
||||
)}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<div className="mb-4 rounded-xl bg-red-50 dark:bg-red-950/40 ring-1 ring-red-200 dark:ring-red-800/60 p-4 flex items-center gap-3">
|
||||
<p className="text-sm text-red-700 dark:text-red-300">{error}</p>
|
||||
<button onClick={() => setError(null)} className="mr-auto text-red-400 hover:text-red-600">
|
||||
<svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" strokeWidth={2} stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" d="M6 18 18 6M6 6l12 12" />
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{selectedPackage && (
|
||||
<>
|
||||
{!isFormVisible && (
|
||||
<div className="mb-4 flex justify-end">
|
||||
<button
|
||||
onClick={handleCreate}
|
||||
disabled={isLoading}
|
||||
className="inline-flex items-center gap-2 px-4 py-2.5 bg-indigo-600 text-white rounded-xl text-sm font-medium hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 dark:focus:ring-offset-gray-900 focus:ring-indigo-500 disabled:opacity-50 transition-colors shadow-sm shadow-indigo-500/20"
|
||||
>
|
||||
<PlusIcon className="h-4 w-4" />
|
||||
محصول جدید
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{isFormVisible ? (
|
||||
<ProductForm
|
||||
product={selectedProduct}
|
||||
packageName={selectedPackage.name!}
|
||||
onSubmit={handleSubmit}
|
||||
onCancel={handleCancel}
|
||||
isLoading={isLoading}
|
||||
/>
|
||||
) : (
|
||||
<ProductList
|
||||
products={products}
|
||||
packageName={selectedPackage.name!}
|
||||
onEdit={handleEdit}
|
||||
onDelete={handleDelete}
|
||||
isLoading={isLoading}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useEffect, useCallback, useRef } from 'react';
|
||||
import { useAuth } from '@/contexts/AuthContext';
|
||||
import { promotionsApi } from '@/lib/api/promotions';
|
||||
import PromotionList from '@/components/admin/promotions/PromotionList';
|
||||
import PromotionForm from '@/components/admin/promotions/PromotionForm';
|
||||
import PageHeader from '@/components/admin/PageHeader';
|
||||
import { showToast } from '@/components/Toast';
|
||||
import { Promotion, CreatePromotionData, UpdatePromotionData } from '@/types/promotion';
|
||||
import { PlusIcon } from '@heroicons/react/24/outline';
|
||||
|
||||
export default function PromotionsPage() {
|
||||
const { token } = useAuth();
|
||||
const [promotions, setPromotions] = useState<Promotion[]>([]);
|
||||
const [selectedPromotion, setSelectedPromotion] = useState<Promotion | null>(null);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [isFormVisible, setIsFormVisible] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const initialLoadRef = useRef(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (token && !initialLoadRef.current) {
|
||||
initialLoadRef.current = true;
|
||||
loadPromotions();
|
||||
}
|
||||
}, [token]);
|
||||
|
||||
const loadPromotions = async () => {
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const data = await promotionsApi.getPromotions(token!);
|
||||
setPromotions(data);
|
||||
} catch (err) {
|
||||
setError('خطا در دریافت لیست تبلیغات');
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleCreate = () => {
|
||||
setSelectedPromotion(null);
|
||||
setIsFormVisible(true);
|
||||
};
|
||||
|
||||
const handleEdit = (promotion: Promotion) => {
|
||||
setSelectedPromotion(promotion);
|
||||
setIsFormVisible(true);
|
||||
};
|
||||
|
||||
const handleDelete = async (promotion: Promotion) => {
|
||||
if (!confirm(`آیا از حذف تبلیغ "${promotion.title || 'بدون عنوان'}" اطمینان دارید؟`)) {
|
||||
return;
|
||||
}
|
||||
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
await promotionsApi.deletePromotion(promotion.id, token!);
|
||||
showToast('success', 'تبلیغ با موفقیت حذف شد');
|
||||
await loadPromotions();
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'خطا در حذف تبلیغ');
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleToggleActive = async (promotion: Promotion) => {
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
await promotionsApi.toggleActive(promotion.id, !promotion.is_active, token!);
|
||||
showToast('success', `تبلیغ با موفقیت ${!promotion.is_active ? 'فعال' : 'غیرفعال'} شد`);
|
||||
await loadPromotions();
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'خطا در تغییر وضعیت تبلیغ');
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleSubmit = async (data: CreatePromotionData | UpdatePromotionData) => {
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
if (selectedPromotion) {
|
||||
await promotionsApi.updatePromotion(selectedPromotion.id, data, token!);
|
||||
showToast('success', 'تبلیغ با موفقیت بهروزرسانی شد');
|
||||
} else {
|
||||
await promotionsApi.createPromotion(data as CreatePromotionData, token!);
|
||||
showToast('success', 'تبلیغ با موفقیت ایجاد شد');
|
||||
}
|
||||
|
||||
await loadPromotions();
|
||||
setIsFormVisible(false);
|
||||
setSelectedPromotion(null);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'خطا در ذخیره تبلیغ');
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleCancel = () => {
|
||||
setIsFormVisible(false);
|
||||
setSelectedPromotion(null);
|
||||
setError(null);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="p-4 sm:p-8">
|
||||
<div className="max-w-7xl mx-auto">
|
||||
<PageHeader
|
||||
title="مدیریت تبلیغات"
|
||||
action={
|
||||
!isFormVisible ? (
|
||||
<button
|
||||
onClick={handleCreate}
|
||||
disabled={isLoading}
|
||||
className="inline-flex items-center gap-2 px-4 py-2.5 bg-indigo-600 text-white rounded-xl text-sm font-medium hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 dark:focus:ring-offset-gray-900 focus:ring-indigo-500 disabled:opacity-50 transition-colors shadow-sm shadow-indigo-500/20"
|
||||
>
|
||||
<PlusIcon className="h-4 w-4" />
|
||||
تبلیغ جدید
|
||||
</button>
|
||||
) : undefined
|
||||
}
|
||||
/>
|
||||
|
||||
{error && (
|
||||
<div className="mb-4 rounded-xl bg-red-50 dark:bg-red-950/40 ring-1 ring-red-200 dark:ring-red-800/60 p-4 flex items-center gap-3">
|
||||
<p className="text-sm text-red-700 dark:text-red-300">{error}</p>
|
||||
<button onClick={() => setError(null)} className="mr-auto text-red-400 hover:text-red-600">
|
||||
<svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" strokeWidth={2} stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" d="M6 18 18 6M6 6l12 12" />
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{isFormVisible ? (
|
||||
<PromotionForm
|
||||
promotion={selectedPromotion}
|
||||
onSubmit={handleSubmit}
|
||||
onCancel={handleCancel}
|
||||
isLoading={isLoading}
|
||||
/>
|
||||
) : (
|
||||
<PromotionList
|
||||
promotions={promotions}
|
||||
onEdit={handleEdit}
|
||||
onDelete={handleDelete}
|
||||
onToggleActive={handleToggleActive}
|
||||
isLoading={isLoading}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,312 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { useAuth } from '@/contexts/AuthContext';
|
||||
import { purchasesApi } from '@/lib/api/purchases';
|
||||
import { packagesApi } from '@/lib/api/packages';
|
||||
import PageHeader from '@/components/admin/PageHeader';
|
||||
import {
|
||||
Purchase,
|
||||
Paginated,
|
||||
PurchaseFilters,
|
||||
PAYMENT_GATEWAYS,
|
||||
PURCHASE_STATUSES,
|
||||
getGatewayLabel,
|
||||
getPurchaseStatusLabel,
|
||||
} from '@/types/purchase';
|
||||
import { PackageName } from '@/types/package';
|
||||
import { formatPrice, formatDate, getProductTypeLabel } from '@/lib/utils';
|
||||
import { MagnifyingGlassIcon, ArrowPathIcon } from '@heroicons/react/24/outline';
|
||||
|
||||
const statusBadgeClass = (status: number): string => {
|
||||
switch (status) {
|
||||
case 2:
|
||||
return 'bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-300';
|
||||
case 3:
|
||||
return 'bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-300';
|
||||
default:
|
||||
return 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900/30 dark:text-yellow-300';
|
||||
}
|
||||
};
|
||||
|
||||
const emptyFilters: PurchaseFilters = {
|
||||
email: '',
|
||||
mobile: '',
|
||||
package_name: '',
|
||||
gateway: '',
|
||||
status: undefined,
|
||||
};
|
||||
|
||||
// قیمت نهایی خرید (مبلغ قابلنمایش در جدول).
|
||||
// وقتی محصول تخفیف دارد، مقدار نهایی همان «قیمت کلی تخفیفخورده» است؛
|
||||
// اما در پکیجهایی که تخفیف ندارند، «قیمت» خود محصول مقدار نهایی است.
|
||||
const getPurchaseFinalPrice = (purchase: Purchase): number => {
|
||||
const product = purchase.product;
|
||||
|
||||
// اگر محصول تخفیف دارد، قیمت نهایی همان قیمت تخفیفخورده است
|
||||
const discountedPrice = product?.discounted_price;
|
||||
if (discountedPrice) {
|
||||
const parsed = parseInt(discountedPrice.replace(/[^\d]/g, ''), 10);
|
||||
if (!Number.isNaN(parsed) && parsed > 0) return parsed;
|
||||
}
|
||||
|
||||
// بدون تخفیف → قیمت اصلی محصول (فقط وقتی discount نداشته باشد)
|
||||
if (product?.price) return product.price;
|
||||
|
||||
// برگشت به مبلغ ثبتشدهٔ تراکنش وقتی محصول در دسترس نیست
|
||||
return purchase.amount || 0;
|
||||
};
|
||||
|
||||
export default function PurchasesPage() {
|
||||
const { token } = useAuth();
|
||||
const [packages, setPackages] = useState<PackageName[]>([]);
|
||||
const [filters, setFilters] = useState<PurchaseFilters>(emptyFilters);
|
||||
const [result, setResult] = useState<Paginated<Purchase> | null>(null);
|
||||
const [page, setPage] = useState(1);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const loadPurchases = useCallback(async (targetPage: number, activeFilters: PurchaseFilters) => {
|
||||
if (!token) return;
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const data = await purchasesApi.getPurchases(
|
||||
{ ...activeFilters, page: targetPage, per_page: 30 },
|
||||
token
|
||||
);
|
||||
setResult(data);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'خطا در دریافت لیست خریدها');
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, [token]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!token) return;
|
||||
packagesApi.getAllPackages(token).then(setPackages).catch(() => setPackages([]));
|
||||
loadPurchases(1, emptyFilters);
|
||||
}, [token, loadPurchases]);
|
||||
|
||||
const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) => {
|
||||
const { name, value } = e.target;
|
||||
setFilters((prev) => ({
|
||||
...prev,
|
||||
[name]: name === 'status' ? (value === '' ? undefined : parseInt(value)) : value,
|
||||
}));
|
||||
};
|
||||
|
||||
const handleSearch = (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setPage(1);
|
||||
loadPurchases(1, filters);
|
||||
};
|
||||
|
||||
const handleReset = () => {
|
||||
setFilters(emptyFilters);
|
||||
setPage(1);
|
||||
loadPurchases(1, emptyFilters);
|
||||
};
|
||||
|
||||
const goToPage = (targetPage: number) => {
|
||||
setPage(targetPage);
|
||||
loadPurchases(targetPage, filters);
|
||||
};
|
||||
|
||||
const inputClass =
|
||||
'block w-full px-3 py-2.5 text-gray-900 dark:text-gray-100 border border-gray-200 dark:border-gray-700 rounded-xl shadow-sm focus:ring-2 focus:ring-indigo-500 focus:border-transparent sm:text-sm dark:bg-gray-800/80 transition-colors';
|
||||
const labelClass = 'block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5';
|
||||
|
||||
return (
|
||||
<div className="p-4 sm:p-8">
|
||||
<div className="max-w-7xl mx-auto">
|
||||
<PageHeader title="خریدهای اشتراک" />
|
||||
|
||||
{/* Filters */}
|
||||
<form
|
||||
onSubmit={handleSearch}
|
||||
className="bg-white dark:bg-gray-900 ring-1 ring-gray-200 dark:ring-gray-800 rounded-2xl p-5 sm:p-6 mb-6 shadow-sm"
|
||||
>
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-5">
|
||||
<div>
|
||||
<label htmlFor="email" className={labelClass}>ایمیل</label>
|
||||
<input type="text" id="email" name="email" value={filters.email || ''} onChange={handleInputChange} className={inputClass} placeholder="example@mail.com" dir="ltr" />
|
||||
</div>
|
||||
<div>
|
||||
<label htmlFor="mobile" className={labelClass}>شماره موبایل</label>
|
||||
<input type="text" id="mobile" name="mobile" value={filters.mobile || ''} onChange={handleInputChange} className={inputClass} placeholder="0912xxxxxxx" dir="ltr" />
|
||||
</div>
|
||||
<div>
|
||||
<label htmlFor="package_name" className={labelClass}>پکیج</label>
|
||||
<select id="package_name" name="package_name" value={filters.package_name || ''} onChange={handleInputChange} className={inputClass}>
|
||||
<option value="">همه پکیجها</option>
|
||||
{packages.map((pkg) => (
|
||||
<option key={pkg.id} value={pkg.name || ''}>
|
||||
{pkg.title || pkg.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label htmlFor="gateway" className={labelClass}>منبع پرداخت</label>
|
||||
<select id="gateway" name="gateway" value={filters.gateway || ''} onChange={handleInputChange} className={inputClass}>
|
||||
<option value="">همه درگاهها</option>
|
||||
{Object.entries(PAYMENT_GATEWAYS).map(([key, g]) => (
|
||||
<option key={key} value={key}>{g.label}</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label htmlFor="status" className={labelClass}>وضعیت</label>
|
||||
<select id="status" name="status" value={filters.status ?? ''} onChange={handleInputChange} className={inputClass}>
|
||||
<option value="">همه وضعیتها</option>
|
||||
{Object.entries(PURCHASE_STATUSES).map(([code, label]) => (
|
||||
<option key={code} value={code}>{label}</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-3 mt-5">
|
||||
<button
|
||||
type="submit"
|
||||
disabled={isLoading}
|
||||
className="inline-flex items-center gap-2 px-5 py-2.5 bg-indigo-600 text-white rounded-xl text-sm font-medium hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 dark:focus:ring-offset-gray-900 focus:ring-indigo-500 disabled:opacity-50 transition-colors shadow-sm shadow-indigo-500/20"
|
||||
>
|
||||
<MagnifyingGlassIcon className="h-4 w-4" />
|
||||
جستجو
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleReset}
|
||||
disabled={isLoading}
|
||||
className="inline-flex items-center gap-2 px-5 py-2.5 border border-gray-200 dark:border-gray-700 rounded-xl text-sm font-medium text-gray-700 dark:text-gray-200 bg-white dark:bg-gray-800 hover:bg-gray-50 dark:hover:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-offset-2 dark:focus:ring-offset-gray-900 focus:ring-indigo-500 disabled:opacity-50 transition-colors shadow-sm"
|
||||
>
|
||||
<ArrowPathIcon className="h-4 w-4" />
|
||||
پاک کردن فیلترها
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
{error && (
|
||||
<div className="mb-4 rounded-xl bg-red-50 dark:bg-red-950/40 ring-1 ring-red-200 dark:ring-red-800/60 p-4 flex items-center gap-3">
|
||||
<p className="text-sm text-red-700 dark:text-red-300">{error}</p>
|
||||
<button onClick={() => setError(null)} className="mr-auto text-red-400 hover:text-red-600">
|
||||
<svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" strokeWidth={2} stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" d="M6 18 18 6M6 6l12 12" />
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Results */}
|
||||
<div className="bg-white dark:bg-gray-900 ring-1 ring-gray-200 dark:ring-gray-800 rounded-2xl overflow-hidden shadow-sm">
|
||||
<div className="px-5 py-4 flex items-center justify-between border-b border-gray-200 dark:border-gray-800">
|
||||
<h3 className="text-sm font-medium text-gray-900 dark:text-gray-100">
|
||||
{result ? `${formatPrice(result.total)} خرید یافت شد` : 'در حال بارگذاری...'}
|
||||
</h3>
|
||||
</div>
|
||||
|
||||
{isLoading ? (
|
||||
<div className="flex justify-center items-center py-16">
|
||||
<div className="h-10 w-10 border-4 border-indigo-200 dark:border-indigo-800 border-t-indigo-600 rounded-full animate-spin" />
|
||||
</div>
|
||||
) : !result || result.data.length === 0 ? (
|
||||
<div className="text-center py-16">
|
||||
<div className="mx-auto h-12 w-12 rounded-xl bg-gray-100 dark:bg-gray-800 flex items-center justify-center mb-3">
|
||||
<svg className="h-6 w-6 text-gray-400" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" d="M2.25 3h1.386c.51 0 .955.343 1.087.835l.383 1.437M7.5 14.25a3 3 0 0 0-3 3h15.75m-12.75-3h11.218c1.121 0 2.09-.773 2.34-1.872l1.836-8.046A1.125 1.125 0 0 0 18.054 3H5.106m2.394 11.25-1.5-6h13.5" />
|
||||
</svg>
|
||||
</div>
|
||||
<p className="text-gray-500 dark:text-gray-400 text-sm">هیچ خریدی با این فیلترها یافت نشد</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="overflow-x-auto">
|
||||
<table className="min-w-full divide-y divide-gray-200 dark:divide-gray-800">
|
||||
<thead className="bg-gray-50 dark:bg-gray-800/60">
|
||||
<tr className="text-right text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
|
||||
<th className="px-4 py-3">کاربر</th>
|
||||
<th className="px-4 py-3">پکیج</th>
|
||||
<th className="px-4 py-3">محصول</th>
|
||||
<th className="px-4 py-3">قیمت نهایی</th>
|
||||
<th className="px-4 py-3">منبع پرداخت</th>
|
||||
<th className="px-4 py-3">وضعیت</th>
|
||||
<th className="px-4 py-3">تاریخ</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-gray-200 dark:divide-gray-800">
|
||||
{result.data.map((purchase) => (
|
||||
<tr key={purchase.id} className="hover:bg-gray-50 dark:hover:bg-gray-800/40 transition-colors">
|
||||
<td className="px-4 py-3.5">
|
||||
<div className="text-sm font-medium text-gray-900 dark:text-gray-100">
|
||||
{purchase.user?.full_name?.trim() || 'بدون نام'}
|
||||
</div>
|
||||
<div className="text-xs text-gray-500 dark:text-gray-400" dir="ltr">
|
||||
{purchase.user?.email || '—'}
|
||||
</div>
|
||||
<div className="text-xs text-gray-500 dark:text-gray-400" dir="ltr">
|
||||
{purchase.user?.mobile || '—'}
|
||||
</div>
|
||||
</td>
|
||||
<td className="px-4 py-3.5 text-sm text-gray-700 dark:text-gray-300 whitespace-nowrap">
|
||||
{purchase.product?.package_name?.title || purchase.product?.package_name?.name || '—'}
|
||||
</td>
|
||||
<td className="px-4 py-3.5 whitespace-nowrap">
|
||||
<div className="text-sm text-gray-900 dark:text-gray-100">
|
||||
{purchase.product?.title || '—'}
|
||||
</div>
|
||||
<div className="text-xs text-gray-500 dark:text-gray-400">
|
||||
{purchase.product ? getProductTypeLabel(purchase.product.type) : ''}
|
||||
</div>
|
||||
</td>
|
||||
<td className="px-4 py-3.5 text-sm text-gray-900 dark:text-gray-100 whitespace-nowrap font-medium">
|
||||
{formatPrice(getPurchaseFinalPrice(purchase))} تومان
|
||||
</td>
|
||||
<td className="px-4 py-3.5 whitespace-nowrap">
|
||||
<span className="px-2.5 py-1 inline-flex text-xs leading-5 font-semibold rounded-lg bg-gray-100 text-gray-700 dark:bg-gray-800 dark:text-gray-300">
|
||||
{getGatewayLabel(purchase.gateway)}
|
||||
</span>
|
||||
</td>
|
||||
<td className="px-4 py-3.5 whitespace-nowrap">
|
||||
<span className={`px-2.5 py-1 inline-flex text-xs leading-5 font-semibold rounded-lg ${statusBadgeClass(purchase.status)}`}>
|
||||
{getPurchaseStatusLabel(purchase.status)}
|
||||
</span>
|
||||
</td>
|
||||
<td className="px-4 py-3.5 text-xs text-gray-500 dark:text-gray-400 whitespace-nowrap">
|
||||
{formatDate(purchase.created_at)}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Pagination */}
|
||||
{result && result.last_page > 1 && (
|
||||
<div className="flex items-center justify-between px-5 py-3.5 border-t border-gray-200 dark:border-gray-800">
|
||||
<button
|
||||
onClick={() => goToPage(page - 1)}
|
||||
disabled={page <= 1 || isLoading}
|
||||
className="px-4 py-2 text-sm border border-gray-200 dark:border-gray-700 rounded-xl text-gray-700 dark:text-gray-200 bg-white dark:bg-gray-800 hover:bg-gray-50 dark:hover:bg-gray-700 disabled:opacity-40 disabled:cursor-not-allowed transition-colors"
|
||||
>
|
||||
قبلی
|
||||
</button>
|
||||
<span className="text-sm text-gray-600 dark:text-gray-400">
|
||||
صفحه {result.current_page} از {result.last_page}
|
||||
</span>
|
||||
<button
|
||||
onClick={() => goToPage(page + 1)}
|
||||
disabled={page >= result.last_page || isLoading}
|
||||
className="px-4 py-2 text-sm border border-gray-200 dark:border-gray-700 rounded-xl text-gray-700 dark:text-gray-200 bg-white dark:bg-gray-800 hover:bg-gray-50 dark:hover:bg-gray-700 disabled:opacity-40 disabled:cursor-not-allowed transition-colors"
|
||||
>
|
||||
بعدی
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useEffect, useRef } from 'react';
|
||||
import { useAuth } from '@/contexts/AuthContext';
|
||||
import { referralApi } from '@/lib/api/referral';
|
||||
import ReferralList from '@/components/admin/referral/ReferralList';
|
||||
import PageHeader from '@/components/admin/PageHeader';
|
||||
import { showToast } from '@/components/Toast';
|
||||
import { ReferralRewardUser } from '@/types/referral';
|
||||
import { ArrowPathIcon } from '@heroicons/react/24/outline';
|
||||
|
||||
export default function ReferralRewardsPage() {
|
||||
const { token } = useAuth();
|
||||
const [users, setUsers] = useState<ReferralRewardUser[]>([]);
|
||||
const [subscriptionTarget, setSubscriptionTarget] = useState(0);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [fulfillingId, setFulfillingId] = useState<number | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const initialLoadRef = useRef(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (token && !initialLoadRef.current) {
|
||||
initialLoadRef.current = true;
|
||||
loadRewards();
|
||||
}
|
||||
}, [token]);
|
||||
|
||||
const loadRewards = async () => {
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const data = await referralApi.getPendingRewards(token!);
|
||||
setUsers(data.data || []);
|
||||
setSubscriptionTarget(data.subscription_target || 0);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'خطا در دریافت لیست پاداشهای معرفی');
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleFulfill = async (user: ReferralRewardUser) => {
|
||||
if (!confirm(`آیا از اعطای یک ماه اشتراک رایگان به «${user.name || user.mobile || user.email}» اطمینان دارید؟`)) {
|
||||
return;
|
||||
}
|
||||
|
||||
setFulfillingId(user.id);
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
await referralApi.fulfillReward(user.id, token!);
|
||||
showToast('success', `اشتراک رایگان با موفقیت به «${user.name || user.mobile || user.email}» اعطا شد`);
|
||||
setUsers((prev) => prev.filter((u) => u.id !== user.id));
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'خطا در اعطای اشتراک رایگان');
|
||||
} finally {
|
||||
setFulfillingId(null);
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="p-4 sm:p-8">
|
||||
<div className="max-w-7xl mx-auto">
|
||||
<PageHeader
|
||||
title="پاداشهای معرفی"
|
||||
subtitle="کاربرانی که به حد نصاب دعوت موفق رسیدهاند و هنوز اشتراک رایگان دریافت نکردهاند."
|
||||
action={
|
||||
<button
|
||||
onClick={loadRewards}
|
||||
disabled={isLoading}
|
||||
className="inline-flex items-center gap-2 px-4 py-2.5 border border-gray-200 dark:border-gray-700 rounded-xl text-sm font-medium text-gray-700 dark:text-gray-200 bg-white dark:bg-gray-800 hover:bg-gray-50 dark:hover:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 dark:focus:ring-offset-gray-900 disabled:opacity-50 transition-colors shadow-sm"
|
||||
>
|
||||
<ArrowPathIcon className={`h-4 w-4 ${isLoading ? 'animate-spin' : ''}`} />
|
||||
بروزرسانی
|
||||
</button>
|
||||
}
|
||||
/>
|
||||
|
||||
{error && (
|
||||
<div className="mb-4 rounded-xl bg-red-50 dark:bg-red-950/40 ring-1 ring-red-200 dark:ring-red-800/60 p-4 flex items-center gap-3">
|
||||
<p className="text-sm text-red-700 dark:text-red-300">{error}</p>
|
||||
<button onClick={() => setError(null)} className="mr-auto text-red-400 hover:text-red-600">
|
||||
<svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" strokeWidth={2} stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" d="M6 18 18 6M6 6l12 12" />
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{isLoading && users.length === 0 ? (
|
||||
<div className="text-center py-16 bg-white dark:bg-gray-900 rounded-2xl ring-1 ring-gray-200 dark:ring-gray-800 shadow-sm">
|
||||
<div className="mx-auto h-10 w-10 border-4 border-indigo-200 dark:border-indigo-800 border-t-indigo-600 rounded-full animate-spin" />
|
||||
<p className="mt-3 text-gray-500 dark:text-gray-400 text-sm">در حال بارگذاری...</p>
|
||||
</div>
|
||||
) : (
|
||||
<ReferralList
|
||||
users={users}
|
||||
subscriptionTarget={subscriptionTarget}
|
||||
onFulfill={handleFulfill}
|
||||
isLoading={isLoading}
|
||||
fulfillingId={fulfillingId}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,232 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useEffect, useCallback, useRef } from 'react';
|
||||
import { useAuth } from '@/contexts/AuthContext';
|
||||
import { packagesApi } from '@/lib/api/packages';
|
||||
import { remindersApi } from '@/lib/api/reminders';
|
||||
import ReminderList from '@/components/admin/reminders/ReminderList';
|
||||
import ReminderForm from '@/components/admin/reminders/ReminderForm';
|
||||
import PageHeader from '@/components/admin/PageHeader';
|
||||
import { showToast } from '@/components/Toast';
|
||||
import { PackageName } from '@/types/package';
|
||||
import { Reminder, CreateReminderData, UpdateReminderData } from '@/types/reminder';
|
||||
import { PlusIcon } from '@heroicons/react/24/outline';
|
||||
|
||||
export default function RemindersPage() {
|
||||
const { token } = useAuth();
|
||||
const [packages, setPackages] = useState<PackageName[]>([]);
|
||||
const [selectedPackage, setSelectedPackage] = useState<PackageName | null>(null);
|
||||
const [reminders, setReminders] = useState<Reminder[]>([]);
|
||||
const [selectedReminder, setSelectedReminder] = useState<Reminder | null>(null);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [isLoadingPackages, setIsLoadingPackages] = useState(false);
|
||||
const [isFormVisible, setIsFormVisible] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const initialLoadRef = useRef(false);
|
||||
const prevPackageRef = useRef<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (token && !initialLoadRef.current) {
|
||||
initialLoadRef.current = true;
|
||||
loadPackages();
|
||||
}
|
||||
}, [token]);
|
||||
|
||||
const loadPackages = async () => {
|
||||
setIsLoadingPackages(true);
|
||||
setError(null);
|
||||
try {
|
||||
const data = await packagesApi.getAllPackages(token!);
|
||||
setPackages(data);
|
||||
if (data.length > 0 && !selectedPackage) {
|
||||
setSelectedPackage(data[0]);
|
||||
}
|
||||
} catch (err) {
|
||||
setError('خطا در دریافت لیست پکیجها');
|
||||
} finally {
|
||||
setIsLoadingPackages(false);
|
||||
}
|
||||
};
|
||||
|
||||
const loadReminders = useCallback(async (packageName: string, force = false) => {
|
||||
if (!force && prevPackageRef.current === packageName) {
|
||||
return;
|
||||
}
|
||||
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
prevPackageRef.current = packageName;
|
||||
|
||||
try {
|
||||
const data = await remindersApi.getReminders(packageName, token!);
|
||||
setReminders(data);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'خطا در دریافت یادآوریها');
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, [token]);
|
||||
|
||||
useEffect(() => {
|
||||
if (selectedPackage?.name && token) {
|
||||
loadReminders(selectedPackage.name);
|
||||
} else {
|
||||
setReminders([]);
|
||||
}
|
||||
}, [selectedPackage?.name, token, loadReminders]);
|
||||
|
||||
const handlePackageChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
|
||||
const pkg = packages.find(p => p.name === e.target.value);
|
||||
setSelectedPackage(pkg || null);
|
||||
setIsFormVisible(false);
|
||||
setSelectedReminder(null);
|
||||
setError(null);
|
||||
};
|
||||
|
||||
const handleCreate = () => {
|
||||
setSelectedReminder(null);
|
||||
setIsFormVisible(true);
|
||||
};
|
||||
|
||||
const handleEdit = (reminder: Reminder) => {
|
||||
setSelectedReminder(reminder);
|
||||
setIsFormVisible(true);
|
||||
};
|
||||
|
||||
const handleDelete = async (reminder: Reminder) => {
|
||||
if (!selectedPackage) return;
|
||||
if (!confirm(`آیا از حذف یادآوری "${reminder.title}" اطمینان دارید؟`)) {
|
||||
return;
|
||||
}
|
||||
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
await remindersApi.deleteReminder(selectedPackage.name!, reminder.id, token!);
|
||||
showToast('success', 'یادآوری با موفقیت حذف شد');
|
||||
if (selectedPackage.name) {
|
||||
prevPackageRef.current = null;
|
||||
await loadReminders(selectedPackage.name, true);
|
||||
}
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'خطا در حذف یادآوری');
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleSubmit = async (data: CreateReminderData | UpdateReminderData) => {
|
||||
if (!selectedPackage) return;
|
||||
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
if (selectedReminder) {
|
||||
await remindersApi.updateReminder(selectedPackage.name!, selectedReminder.id, data, token!);
|
||||
showToast('success', 'یادآوری با موفقیت بهروزرسانی شد');
|
||||
} else {
|
||||
await remindersApi.createReminder(selectedPackage.name!, data as CreateReminderData, token!);
|
||||
showToast('success', 'یادآوری با موفقیت ایجاد شد');
|
||||
}
|
||||
|
||||
if (selectedPackage.name) {
|
||||
prevPackageRef.current = null;
|
||||
await loadReminders(selectedPackage.name, true);
|
||||
}
|
||||
|
||||
setIsFormVisible(false);
|
||||
setSelectedReminder(null);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'خطا در ذخیره یادآوری');
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleCancel = () => {
|
||||
setIsFormVisible(false);
|
||||
setSelectedReminder(null);
|
||||
setError(null);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="p-4 sm:p-8">
|
||||
<div className="max-w-7xl mx-auto">
|
||||
<PageHeader title="مدیریت یادآوریها" />
|
||||
|
||||
{/* Package Selector */}
|
||||
<div className="bg-white dark:bg-gray-900 p-4 rounded-2xl ring-1 ring-gray-200 dark:ring-gray-800 shadow-sm mb-6">
|
||||
<label htmlFor="package" className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
|
||||
انتخاب پکیج
|
||||
</label>
|
||||
<select
|
||||
id="package"
|
||||
value={selectedPackage?.name || ''}
|
||||
onChange={handlePackageChange}
|
||||
disabled={isLoadingPackages}
|
||||
className="block w-full px-3 py-2.5 text-gray-900 dark:text-gray-100 border border-gray-200 dark:border-gray-700 rounded-xl shadow-sm focus:ring-2 focus:ring-indigo-500 focus:border-transparent sm:text-sm disabled:opacity-50 dark:bg-gray-800/80 transition-colors"
|
||||
>
|
||||
{isLoadingPackages ? (
|
||||
<option>در حال بارگذاری پکیجها...</option>
|
||||
) : (
|
||||
packages.map((pkg) => (
|
||||
<option key={pkg.id} value={pkg.name || ''}>
|
||||
{pkg.title} ({pkg.name})
|
||||
</option>
|
||||
))
|
||||
)}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<div className="mb-4 rounded-xl bg-red-50 dark:bg-red-950/40 ring-1 ring-red-200 dark:ring-red-800/60 p-4 flex items-center gap-3">
|
||||
<p className="text-sm text-red-700 dark:text-red-300">{error}</p>
|
||||
<button onClick={() => setError(null)} className="mr-auto text-red-400 hover:text-red-600">
|
||||
<svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" strokeWidth={2} stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" d="M6 18 18 6M6 6l12 12" />
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{selectedPackage && (
|
||||
<>
|
||||
{!isFormVisible && (
|
||||
<div className="mb-4 flex justify-end">
|
||||
<button
|
||||
onClick={handleCreate}
|
||||
disabled={isLoading}
|
||||
className="inline-flex items-center gap-2 px-4 py-2.5 bg-indigo-600 text-white rounded-xl text-sm font-medium hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 dark:focus:ring-offset-gray-900 focus:ring-indigo-500 disabled:opacity-50 transition-colors shadow-sm shadow-indigo-500/20"
|
||||
>
|
||||
<PlusIcon className="h-4 w-4" />
|
||||
یادآوری جدید
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{isFormVisible ? (
|
||||
<ReminderForm
|
||||
reminder={selectedReminder}
|
||||
packageName={selectedPackage.name!}
|
||||
onSubmit={handleSubmit}
|
||||
onCancel={handleCancel}
|
||||
isLoading={isLoading}
|
||||
/>
|
||||
) : (
|
||||
<ReminderList
|
||||
reminders={reminders}
|
||||
packageName={selectedPackage.name!}
|
||||
onEdit={handleEdit}
|
||||
onDelete={handleDelete}
|
||||
isLoading={isLoading}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,330 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useAuth } from '@/contexts/AuthContext';
|
||||
import { usersApi } from '@/lib/api/users';
|
||||
import { packagesApi } from '@/lib/api/packages';
|
||||
import UserSearch from '@/components/admin/users/UserSearch';
|
||||
import UserInfo from '@/components/admin/users/UserInfo';
|
||||
import UserProducts from '@/components/admin/users/UserProducts';
|
||||
import UserEditForm from '@/components/admin/users/UserEditForm';
|
||||
import PackageSelector from '@/components/admin/users/PackageSelector';
|
||||
import PageHeader from '@/components/admin/PageHeader';
|
||||
import StepIndicator from '@/components/admin/StepIndicator';
|
||||
import { showToast } from '@/components/Toast';
|
||||
import { User, Product, UpdateUserProfileData } from '@/types/user';
|
||||
import { PackageName } from '@/types/package';
|
||||
import { formatPrice, getProductTypeLabel } from '@/lib/utils';
|
||||
import { PencilSquareIcon, TrashIcon } from '@heroicons/react/24/outline';
|
||||
|
||||
export default function UsersPage() {
|
||||
const { token } = useAuth();
|
||||
const [user, setUser] = useState<User | null>(null);
|
||||
const [products, setProducts] = useState<Product[]>([]);
|
||||
const [packages, setPackages] = useState<PackageName[]>([]);
|
||||
const [selectedPackage, setSelectedPackage] = useState<string | null>(null);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [isEditing, setIsEditing] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (token) {
|
||||
loadPackages();
|
||||
}
|
||||
}, [token]);
|
||||
|
||||
useEffect(() => {
|
||||
if (token && selectedPackage) {
|
||||
loadProducts(selectedPackage);
|
||||
}
|
||||
}, [selectedPackage, token]);
|
||||
|
||||
const loadPackages = async () => {
|
||||
try {
|
||||
const data = await packagesApi.getAllPackages(token!);
|
||||
setPackages(data);
|
||||
if (data.length > 0 && !selectedPackage) {
|
||||
setSelectedPackage(data[0].name!);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Failed to load packages:', err);
|
||||
setError('خطا در دریافت لیست پکیجها');
|
||||
}
|
||||
};
|
||||
|
||||
const loadProducts = async (packageName: string) => {
|
||||
try {
|
||||
const data = await usersApi.getProductsByPackage(packageName, token!);
|
||||
setProducts(data);
|
||||
} catch (err) {
|
||||
console.error('Failed to load products:', err);
|
||||
setError('خطا در دریافت محصولات');
|
||||
}
|
||||
};
|
||||
|
||||
const handleSearch = async (searchTerm: string) => {
|
||||
if (!selectedPackage) {
|
||||
setError('لطفا ابتدا یک پکیج انتخاب کنید');
|
||||
return;
|
||||
}
|
||||
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
setUser(null);
|
||||
|
||||
try {
|
||||
const userData = await usersApi.getUserStatus(searchTerm, selectedPackage, token!);
|
||||
setUser(userData);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'خطا در دریافت اطلاعات کاربر');
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleSubscribe = async (productId: number) => {
|
||||
if (!user) return;
|
||||
const identifier = user.email || user.mobile;
|
||||
if (!identifier) {
|
||||
setError('کاربر فاقد ایمیل یا شماره موبایل است');
|
||||
return;
|
||||
}
|
||||
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
await usersApi.subscribeUser(identifier, productId, token!);
|
||||
showToast('success', 'اشتراک با موفقیت اضافه شد');
|
||||
if (selectedPackage) {
|
||||
const userData = await usersApi.getUserStatus(identifier, selectedPackage, token!);
|
||||
setUser(userData);
|
||||
}
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'خطا در افزودن اشتراک');
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleUnsubscribe = async (productId: number) => {
|
||||
if (!user) return;
|
||||
const identifier = user.email || user.mobile;
|
||||
if (!identifier) {
|
||||
setError('کاربر فاقد ایمیل یا شماره موبایل است');
|
||||
return;
|
||||
}
|
||||
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
await usersApi.unsubscribeUser(identifier, productId, token!);
|
||||
showToast('success', 'اشتراک با موفقیت لغو شد');
|
||||
if (selectedPackage) {
|
||||
const userData = await usersApi.getUserStatus(identifier, selectedPackage, token!);
|
||||
setUser(userData);
|
||||
}
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'خطا در لغو اشتراک');
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleEditSubmit = async (data: UpdateUserProfileData) => {
|
||||
if (!user) return;
|
||||
const identifier = user.email || user.mobile;
|
||||
if (!identifier) {
|
||||
setError('کاربر فاقد ایمیل یا شماره موبایل است');
|
||||
return;
|
||||
}
|
||||
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
await usersApi.updateUserProfile(identifier, data, token!);
|
||||
showToast('success', 'اطلاعات کاربر با موفقیت بهروزرسانی شد');
|
||||
setIsEditing(false);
|
||||
const newIdentifier = data.email || data.mobile || identifier;
|
||||
if (selectedPackage) {
|
||||
const userData = await usersApi.getUserStatus(newIdentifier, selectedPackage, token!);
|
||||
setUser(userData);
|
||||
}
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'خطا در بهروزرسانی اطلاعات کاربر');
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleDeleteUser = async () => {
|
||||
if (!user) return;
|
||||
const identifier = user.email || user.mobile;
|
||||
if (!identifier) {
|
||||
setError('کاربر فاقد ایمیل یا شماره موبایل است');
|
||||
return;
|
||||
}
|
||||
|
||||
if (!confirm('آیا از حذف این کاربر اطمینان دارید؟ این عملیات قابل بازگشت نیست.')) {
|
||||
return;
|
||||
}
|
||||
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
await usersApi.deleteUser(identifier, token!);
|
||||
showToast('success', 'کاربر با موفقیت حذف شد');
|
||||
setUser(null);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'خطا در حذف کاربر');
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handlePackageChange = (packageName: string) => {
|
||||
setSelectedPackage(packageName);
|
||||
setUser(null);
|
||||
setError(null);
|
||||
};
|
||||
|
||||
const availableProducts = products;
|
||||
|
||||
// Compute step indicator state
|
||||
const steps = [
|
||||
{ label: 'انتخاب پکیج', isCompleted: !!selectedPackage, isCurrent: !selectedPackage },
|
||||
{ label: 'جستجوی کاربر', isCompleted: !!user, isCurrent: !!selectedPackage && !user },
|
||||
{ label: 'پروفایل کاربر', isCompleted: false, isCurrent: !!user },
|
||||
];
|
||||
|
||||
return (
|
||||
<div className="p-4 sm:p-8">
|
||||
<div className="max-w-7xl mx-auto">
|
||||
<PageHeader title="مدیریت کاربران" subtitle="پکیج را انتخاب کنید، کاربر را جستجو کنید و مدیریت کنید" />
|
||||
|
||||
{/* Step Indicator */}
|
||||
<div className="mb-6 bg-white dark:bg-gray-900 rounded-2xl ring-1 ring-gray-200 dark:ring-gray-800 shadow-sm p-5">
|
||||
<StepIndicator steps={steps} />
|
||||
</div>
|
||||
|
||||
{token && (
|
||||
<PackageSelector
|
||||
token={token}
|
||||
selectedPackage={selectedPackage}
|
||||
onPackageChange={handlePackageChange}
|
||||
isLoading={isLoading}
|
||||
/>
|
||||
)}
|
||||
|
||||
{selectedPackage && (
|
||||
<UserSearch onSearch={handleSearch} isLoading={isLoading} />
|
||||
)}
|
||||
|
||||
{error && (
|
||||
<div className="mb-4 rounded-xl bg-red-50 dark:bg-red-950/40 ring-1 ring-red-200 dark:ring-red-800/60 p-4 flex items-center gap-3">
|
||||
<svg className="h-5 w-5 text-red-500 dark:text-red-400 flex-shrink-0" viewBox="0 0 20 20" fill="currentColor">
|
||||
<path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clipRule="evenodd" />
|
||||
</svg>
|
||||
<p className="text-sm text-red-700 dark:text-red-300">{error}</p>
|
||||
<button onClick={() => setError(null)} className="mr-auto text-red-400 hover:text-red-600 dark:hover:text-red-300">
|
||||
<svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" strokeWidth={2} stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" d="M6 18 18 6M6 6l12 12" />
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!selectedPackage && packages.length === 0 && (
|
||||
<div className="text-center py-16 bg-white dark:bg-gray-900 rounded-2xl ring-1 ring-gray-200 dark:ring-gray-800">
|
||||
<div className="mx-auto h-12 w-12 rounded-xl bg-gray-100 dark:bg-gray-800 flex items-center justify-center mb-3">
|
||||
<svg className="h-6 w-6 text-gray-400" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" d="m21 7.5-9-5.25L3 7.5m18 0-9 5.25m9-5.25v9l-9 5.25M3 7.5l9 5.25M3 7.5v9l9 5.25m0-9v9" />
|
||||
</svg>
|
||||
</div>
|
||||
<p className="text-gray-500 dark:text-gray-400 text-sm">هیچ پکیجی یافت نشد. ابتدا یک پکیج ایجاد کنید.</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{selectedPackage && products.length > 0 && !user && (
|
||||
<div className="bg-white dark:bg-gray-900 rounded-2xl ring-1 ring-gray-200 dark:ring-gray-800 overflow-hidden">
|
||||
<div className="px-5 py-4 border-b border-gray-200 dark:border-gray-800">
|
||||
<h3 className="text-base font-semibold text-gray-900 dark:text-gray-100">
|
||||
محصولات موجود در پکیج {selectedPackage}
|
||||
</h3>
|
||||
</div>
|
||||
<div className="p-5">
|
||||
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-3">
|
||||
{products.map((product) => (
|
||||
<div
|
||||
key={product.id}
|
||||
className="border border-gray-200 dark:border-gray-800 rounded-xl p-4 bg-gray-50 dark:bg-gray-800/60 hover:bg-white dark:hover:bg-gray-800 transition-colors"
|
||||
>
|
||||
<p className="text-sm font-medium text-gray-900 dark:text-gray-100">
|
||||
{product.title || 'محصول'}
|
||||
</p>
|
||||
<p className="mt-1 text-xs text-gray-500 dark:text-gray-400">
|
||||
قیمت: {formatPrice(product.price)} تومان
|
||||
</p>
|
||||
<p className="text-xs text-gray-500 dark:text-gray-400">
|
||||
نوع: {getProductTypeLabel(product.type)}
|
||||
</p>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<p className="mt-4 text-sm text-gray-400 dark:text-gray-500 text-center">
|
||||
برای افزودن اشتراک به کاربر، ابتدا یک کاربر جستجو کنید
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{user && (
|
||||
<>
|
||||
<UserInfo user={user} />
|
||||
<div className="flex justify-end gap-2 mb-6 -mt-2">
|
||||
<button
|
||||
onClick={() => setIsEditing(true)}
|
||||
disabled={isLoading}
|
||||
className="inline-flex items-center gap-2 px-4 py-2.5 border border-gray-200 dark:border-gray-700 rounded-xl text-sm font-medium text-gray-700 dark:text-gray-200 bg-white dark:bg-gray-800 hover:bg-gray-50 dark:hover:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 dark:focus:ring-offset-gray-900 disabled:opacity-50 transition-colors shadow-sm"
|
||||
>
|
||||
<PencilSquareIcon className="h-4 w-4" />
|
||||
ویرایش اطلاعات
|
||||
</button>
|
||||
<button
|
||||
onClick={handleDeleteUser}
|
||||
disabled={isLoading}
|
||||
className="inline-flex items-center gap-2 px-4 py-2.5 rounded-xl text-sm font-medium text-white bg-red-600 hover:bg-red-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-red-500 dark:focus:ring-offset-gray-900 disabled:opacity-50 transition-colors shadow-sm"
|
||||
>
|
||||
<TrashIcon className="h-4 w-4" />
|
||||
حذف کاربر
|
||||
</button>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
{user && selectedPackage && (
|
||||
<UserProducts
|
||||
products={user.products || []}
|
||||
availableProducts={availableProducts}
|
||||
onSubscribe={handleSubscribe}
|
||||
onUnsubscribe={handleUnsubscribe}
|
||||
isLoading={isLoading}
|
||||
selectedPackage={selectedPackage}
|
||||
/>
|
||||
)}
|
||||
|
||||
{user && isEditing && (
|
||||
<UserEditForm
|
||||
user={user}
|
||||
onSubmit={handleEditSubmit}
|
||||
onCancel={() => setIsEditing(false)}
|
||||
isLoading={isLoading}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
@import "tailwindcss";
|
||||
|
||||
/* Class-based dark mode (Tailwind v4): toggled by a `.dark` class on <html> */
|
||||
@custom-variant dark (&:where(.dark, .dark *));
|
||||
|
||||
@theme {
|
||||
--color-primary-50: #f0f1ff;
|
||||
--color-primary-100: #e4e6ff;
|
||||
--color-primary-200: #c3c7ff;
|
||||
--color-primary-300: #a8b1ff;
|
||||
--color-primary-400: #8d9aff;
|
||||
--color-primary-500: #727dfd;
|
||||
--color-primary-600: #5d68e0;
|
||||
--color-primary-700: #4853c4;
|
||||
--color-primary-800: #343ea8;
|
||||
--color-primary-900: #2a318c;
|
||||
}
|
||||
|
||||
/* Dana Font Faces */
|
||||
@font-face {
|
||||
font-family: 'Dana';
|
||||
src: url('/fonts/dana_regular.ttf') format('truetype');
|
||||
font-weight: 400;
|
||||
font-style: normal;
|
||||
font-display: swap;
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: 'Dana';
|
||||
src: url('/fonts/dana_medium.ttf') format('truetype');
|
||||
font-weight: 500;
|
||||
font-style: normal;
|
||||
font-display: swap;
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: 'Dana';
|
||||
src: url('/fonts/dana_bold.ttf') format('truetype');
|
||||
font-weight: 700;
|
||||
font-style: normal;
|
||||
font-display: swap;
|
||||
}
|
||||
|
||||
:root {
|
||||
--background: #f9fafb;
|
||||
--foreground: #111827;
|
||||
}
|
||||
|
||||
.dark {
|
||||
--background: #030712;
|
||||
--foreground: #f9fafb;
|
||||
}
|
||||
|
||||
@theme inline {
|
||||
--color-background: var(--background);
|
||||
--color-foreground: var(--foreground);
|
||||
--font-sans: 'Dana', 'Inter', var(--font-geist-sans);
|
||||
--font-mono: var(--font-geist-mono);
|
||||
}
|
||||
|
||||
body {
|
||||
background: var(--background);
|
||||
color: var(--foreground);
|
||||
font-family: 'Dana', 'Inter', Arial, Helvetica, sans-serif;
|
||||
font-weight: 400;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
-moz-osx-font-smoothing: grayscale;
|
||||
}
|
||||
|
||||
/* Smooth theme transition for surfaces, borders and text */
|
||||
*,
|
||||
*::before,
|
||||
*::after {
|
||||
transition-property: background-color, border-color, color, fill, stroke;
|
||||
transition-duration: 150ms;
|
||||
transition-timing-function: ease;
|
||||
}
|
||||
|
||||
/* Custom scrollbar that adapts to the theme */
|
||||
* {
|
||||
scrollbar-width: thin;
|
||||
scrollbar-color: #cbd5e1 transparent;
|
||||
}
|
||||
.dark * {
|
||||
scrollbar-color: #374151 transparent;
|
||||
}
|
||||
*::-webkit-scrollbar {
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
}
|
||||
*::-webkit-scrollbar-track {
|
||||
background: transparent;
|
||||
}
|
||||
*::-webkit-scrollbar-thumb {
|
||||
background-color: #cbd5e1;
|
||||
border-radius: 9999px;
|
||||
border: 2px solid transparent;
|
||||
background-clip: content-box;
|
||||
}
|
||||
.dark *::-webkit-scrollbar-thumb {
|
||||
background-color: #374151;
|
||||
}
|
||||
|
||||
::selection {
|
||||
background-color: #c3c7ff;
|
||||
color: #1f2937;
|
||||
}
|
||||
.dark ::selection {
|
||||
background-color: #4853c4;
|
||||
color: #f9fafb;
|
||||
}
|
||||
|
||||
/* Toast animations */
|
||||
@keyframes fade-in {
|
||||
from { opacity: 0; }
|
||||
to { opacity: 1; }
|
||||
}
|
||||
@keyframes slide-in-from-top-4 {
|
||||
from { transform: translateY(-1rem); }
|
||||
to { transform: translateY(0); }
|
||||
}
|
||||
.animate-in {
|
||||
animation-duration: 300ms;
|
||||
animation-timing-function: ease-out;
|
||||
animation-fill-mode: both;
|
||||
}
|
||||
.fade-in {
|
||||
animation-name: fade-in;
|
||||
}
|
||||
.slide-in-from-top-4 {
|
||||
animation-name: slide-in-from-top-4;
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
import type { Metadata } from 'next';
|
||||
import './globals.css';
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: 'پنل ادمین',
|
||||
|
||||
alternates: {
|
||||
canonical: '/',
|
||||
languages: {
|
||||
'fa-IR': '/',
|
||||
},
|
||||
},
|
||||
|
||||
|
||||
|
||||
};
|
||||
|
||||
export default function RootLayout({
|
||||
children,
|
||||
}: {
|
||||
children: React.ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<html lang="fa" dir="rtl" suppressHydrationWarning>
|
||||
<head>
|
||||
{/* Apply the saved/system theme before paint to avoid a flash of the wrong theme */}
|
||||
<script
|
||||
dangerouslySetInnerHTML={{
|
||||
__html: `(function(){try{var t=localStorage.getItem('theme');var d=t?t==='dark':window.matchMedia('(prefers-color-scheme: dark)').matches;if(d)document.documentElement.classList.add('dark');}catch(e){}})();`,
|
||||
}}
|
||||
/>
|
||||
<meta
|
||||
name="google-site-verification"
|
||||
content="HIKgdf_siYdPxbJ2P1792opMprpxci_QjE-quk9kyi8"
|
||||
/>
|
||||
{/* Favicon */}
|
||||
<link rel="icon" href="/favicon.ico" sizes="any" />
|
||||
<link rel="icon" href="/icon?<generated>" type="image/<generated>" sizes="<generated>" />
|
||||
<link rel="apple-touch-icon" href="/apple-touch-icon.png" />
|
||||
|
||||
{/* Preload critical resources */}
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com" />
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossOrigin="anonymous" />
|
||||
|
||||
{/* Structured Data for SEO */}
|
||||
|
||||
</head>
|
||||
<body className="antialiased">
|
||||
{children}
|
||||
</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
|
||||
export default function Home() {
|
||||
const router = useRouter();
|
||||
|
||||
useEffect(() => {
|
||||
router.push('/admin/login');
|
||||
}, [router]);
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { useAuth } from '@/contexts/AuthContext';
|
||||
|
||||
export default function AuthGuard({ children }: { children: React.ReactNode }) {
|
||||
const { token, isLoading } = useAuth();
|
||||
const router = useRouter();
|
||||
|
||||
useEffect(() => {
|
||||
if (!isLoading && !token) {
|
||||
router.replace('/admin/login');
|
||||
}
|
||||
}, [token, isLoading, router]);
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center bg-gray-50 dark:bg-gray-950">
|
||||
<div className="flex flex-col items-center gap-3">
|
||||
<div className="h-10 w-10 border-4 border-indigo-200 dark:border-indigo-800 border-t-indigo-600 rounded-full animate-spin" />
|
||||
<p className="text-sm text-gray-500 dark:text-gray-400">در حال بررسی دسترسی...</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (!token) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return <>{children}</>;
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect, useState } from 'react';
|
||||
import { SunIcon, MoonIcon } from '@heroicons/react/24/outline';
|
||||
|
||||
type Theme = 'light' | 'dark';
|
||||
|
||||
interface ThemeToggleProps {
|
||||
/** When true, renders as a fixed floating pill (used on the app shell). */
|
||||
floating?: boolean;
|
||||
/** When true, shows a Persian text label next to the icon. */
|
||||
withLabel?: boolean;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export default function ThemeToggle({ floating = false, withLabel, className = '' }: ThemeToggleProps) {
|
||||
const [theme, setTheme] = useState<Theme>('light');
|
||||
const [mounted, setMounted] = useState(false);
|
||||
|
||||
// Floating variant shows a label by default; inline variant is icon-only unless asked.
|
||||
const showLabel = withLabel ?? floating;
|
||||
|
||||
useEffect(() => {
|
||||
setMounted(true);
|
||||
setTheme(document.documentElement.classList.contains('dark') ? 'dark' : 'light');
|
||||
}, []);
|
||||
|
||||
const toggle = () => {
|
||||
const next: Theme = theme === 'dark' ? 'light' : 'dark';
|
||||
const root = document.documentElement;
|
||||
if (next === 'dark') {
|
||||
root.classList.add('dark');
|
||||
} else {
|
||||
root.classList.remove('dark');
|
||||
}
|
||||
try {
|
||||
localStorage.setItem('theme', next);
|
||||
} catch {
|
||||
// ignore storage errors
|
||||
}
|
||||
setTheme(next);
|
||||
};
|
||||
|
||||
const base =
|
||||
'inline-flex items-center gap-2 border border-gray-200 bg-white text-gray-700 shadow-sm hover:bg-gray-50 hover:text-gray-900 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 dark:border-gray-700 dark:bg-gray-800 dark:text-gray-200 dark:hover:bg-gray-700 dark:hover:text-white dark:focus:ring-offset-gray-900 transition-colors';
|
||||
|
||||
const shape = showLabel
|
||||
? 'rounded-full px-4 py-2 text-sm font-medium'
|
||||
: 'rounded-full justify-center h-10 w-10';
|
||||
|
||||
const floatingCls = floating ? 'fixed bottom-5 left-5 z-50' : '';
|
||||
|
||||
const isDark = theme === 'dark';
|
||||
const label = isDark ? 'حالت روشن' : 'حالت تیره';
|
||||
|
||||
// Avoid hydration mismatch: render a neutral placeholder until mounted
|
||||
if (!mounted) {
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
aria-label="تغییر تم"
|
||||
className={`${base} ${shape} ${floatingCls} ${className}`}
|
||||
>
|
||||
<SunIcon className="h-5 w-5" />
|
||||
{showLabel && <span>تم</span>}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
onClick={toggle}
|
||||
aria-label={label}
|
||||
title={label}
|
||||
className={`${base} ${shape} ${floatingCls} ${className}`}
|
||||
>
|
||||
{isDark ? <SunIcon className="h-5 w-5" /> : <MoonIcon className="h-5 w-5" />}
|
||||
{showLabel && <span>{label}</span>}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect, useState, useCallback } from 'react';
|
||||
import { CheckCircleIcon, ExclamationCircleIcon, XMarkIcon } from '@heroicons/react/24/outline';
|
||||
|
||||
export interface Toast {
|
||||
id: string;
|
||||
type: 'success' | 'error';
|
||||
message: string;
|
||||
}
|
||||
|
||||
let toastListeners: ((toast: Toast) => void)[] = [];
|
||||
|
||||
export function showToast(type: 'success' | 'error', message: string) {
|
||||
const toast: Toast = {
|
||||
id: Math.random().toString(36).slice(2),
|
||||
type,
|
||||
message,
|
||||
};
|
||||
toastListeners.forEach((fn) => fn(toast));
|
||||
}
|
||||
|
||||
export default function ToastContainer() {
|
||||
const [toasts, setToasts] = useState<Toast[]>([]);
|
||||
|
||||
const addToast = useCallback((toast: Toast) => {
|
||||
setToasts((prev) => [...prev, toast]);
|
||||
setTimeout(() => {
|
||||
setToasts((prev) => prev.filter((t) => t.id !== toast.id));
|
||||
}, 4000);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
toastListeners.push(addToast);
|
||||
return () => {
|
||||
toastListeners = toastListeners.filter((fn) => fn !== addToast);
|
||||
};
|
||||
}, [addToast]);
|
||||
|
||||
if (toasts.length === 0) return null;
|
||||
|
||||
return (
|
||||
<div className="fixed top-4 left-1/2 -translate-x-1/2 z-[100] flex flex-col gap-2 w-full max-w-md pointer-events-none">
|
||||
{toasts.map((toast) => (
|
||||
<div
|
||||
key={toast.id}
|
||||
className={`pointer-events-auto flex items-center gap-3 px-4 py-3 rounded-xl shadow-xl ring-1 animate-in fade-in slide-in-from-top-4 duration-300 ${
|
||||
toast.type === 'success'
|
||||
? 'bg-green-50 dark:bg-green-950/80 ring-green-200 dark:ring-green-800 text-green-800 dark:text-green-200'
|
||||
: 'bg-red-50 dark:bg-red-950/80 ring-red-200 dark:ring-red-800 text-red-800 dark:text-red-200'
|
||||
}`}
|
||||
>
|
||||
{toast.type === 'success' ? (
|
||||
<CheckCircleIcon className="h-5 w-5 text-green-500 dark:text-green-400 flex-shrink-0" />
|
||||
) : (
|
||||
<ExclamationCircleIcon className="h-5 w-5 text-red-500 dark:text-red-400 flex-shrink-0" />
|
||||
)}
|
||||
<p className="flex-1 text-sm font-medium">{toast.message}</p>
|
||||
<button
|
||||
onClick={() => setToasts((prev) => prev.filter((t) => t.id !== toast.id))}
|
||||
className="flex-shrink-0 p-0.5 rounded-lg hover:bg-black/5 dark:hover:bg-white/5 transition-colors"
|
||||
>
|
||||
<XMarkIcon className="h-4 w-4" />
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
'use client';
|
||||
|
||||
interface PageHeaderProps {
|
||||
title: string;
|
||||
subtitle?: string;
|
||||
action?: React.ReactNode;
|
||||
}
|
||||
|
||||
export default function PageHeader({ title, subtitle, action }: PageHeaderProps) {
|
||||
return (
|
||||
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 mb-6">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-gray-900 dark:text-gray-100">
|
||||
{title}
|
||||
</h1>
|
||||
{subtitle && (
|
||||
<p className="mt-1 text-sm text-gray-500 dark:text-gray-400">
|
||||
{subtitle}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
{action && <div>{action}</div>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
'use client';
|
||||
|
||||
import Link from 'next/link';
|
||||
import { usePathname } from 'next/navigation';
|
||||
import { useAuth } from '@/contexts/AuthContext';
|
||||
import { useState } from 'react';
|
||||
import {
|
||||
UsersIcon,
|
||||
CubeIcon,
|
||||
TagIcon,
|
||||
BellIcon,
|
||||
GiftIcon,
|
||||
PowerIcon,
|
||||
ShoppingBagIcon,
|
||||
HomeIcon,
|
||||
Bars3Icon,
|
||||
XMarkIcon,
|
||||
} from '@heroicons/react/24/outline';
|
||||
import { MegaphoneIcon } from 'lucide-react';
|
||||
import ThemeToggle from '@/components/ThemeToggle';
|
||||
|
||||
const navItems = [
|
||||
{ href: '/admin/dashboard', label: 'داشبورد', Icon: HomeIcon },
|
||||
{ href: '/admin/users', label: 'کاربران', Icon: UsersIcon },
|
||||
{ href: '/admin/purchases', label: 'خریدها', Icon: ShoppingBagIcon },
|
||||
{ href: '/admin/packages', label: 'پکیجها', Icon: CubeIcon },
|
||||
{ href: '/admin/products', label: 'محصولات', Icon: TagIcon },
|
||||
{ href: '/admin/reminders', label: 'یادآوریها', Icon: BellIcon },
|
||||
{ href: '/admin/promotions', label: 'تبلیغات', Icon: MegaphoneIcon },
|
||||
{ href: '/admin/referral-rewards', label: 'پاداش معرفی', Icon: GiftIcon },
|
||||
];
|
||||
|
||||
export default function Sidebar() {
|
||||
const pathname = usePathname();
|
||||
const { logout, user } = useAuth();
|
||||
const [mobileOpen, setMobileOpen] = useState(false);
|
||||
|
||||
const isActive = (href: string) => {
|
||||
if (href === '/admin/dashboard') return pathname === href;
|
||||
return pathname.startsWith(href);
|
||||
};
|
||||
|
||||
const navContent = (
|
||||
<div className="flex flex-col h-full">
|
||||
{/* Logo / Brand */}
|
||||
<div className="flex items-center gap-3 px-5 py-5 border-b border-gray-200 dark:border-gray-800">
|
||||
<div className="flex-shrink-0 h-9 w-9 rounded-xl bg-indigo-600 flex items-center justify-center shadow-sm shadow-indigo-500/20">
|
||||
<span className="text-white font-bold text-sm">A</span>
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
<p className="text-sm font-bold text-gray-900 dark:text-gray-100 truncate">اپروایجنسی</p>
|
||||
<p className="text-xs text-gray-500 dark:text-gray-400 truncate">پنل مدیریت</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Navigation */}
|
||||
<nav className="flex-1 px-3 py-4 space-y-1 overflow-y-auto">
|
||||
{navItems.map(({ href, label, Icon }) => {
|
||||
const active = isActive(href);
|
||||
return (
|
||||
<Link
|
||||
key={href}
|
||||
href={href}
|
||||
onClick={() => setMobileOpen(false)}
|
||||
className={`flex items-center gap-3 px-3 py-2.5 rounded-xl text-sm font-medium transition-all duration-150 ${
|
||||
active
|
||||
? 'bg-indigo-50 text-indigo-700 dark:bg-indigo-500/10 dark:text-indigo-400 shadow-sm'
|
||||
: 'text-gray-600 hover:bg-gray-100 hover:text-gray-900 dark:text-gray-400 dark:hover:bg-gray-800 dark:hover:text-gray-200'
|
||||
}`}
|
||||
>
|
||||
<Icon className={`h-5 w-5 flex-shrink-0 ${active ? 'text-indigo-600 dark:text-indigo-400' : ''}`} />
|
||||
{label}
|
||||
</Link>
|
||||
);
|
||||
})}
|
||||
</nav>
|
||||
|
||||
{/* User, Theme & Logout */}
|
||||
<div className="border-t border-gray-200 dark:border-gray-800 px-3 py-4 space-y-1">
|
||||
<ThemeToggle withLabel className="w-full justify-start px-3 py-2.5 rounded-xl text-sm font-medium" />
|
||||
{user && (
|
||||
<div className="px-3 py-2">
|
||||
<p className="text-xs text-gray-500 dark:text-gray-400 truncate" dir="ltr">{user.email}</p>
|
||||
</div>
|
||||
)}
|
||||
<button
|
||||
onClick={logout}
|
||||
className="flex items-center gap-3 w-full px-3 py-2.5 rounded-xl text-sm font-medium text-red-600 hover:bg-red-50 dark:text-red-400 dark:hover:bg-red-500/10 transition-colors"
|
||||
>
|
||||
<PowerIcon className="h-5 w-5" />
|
||||
خروج
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
{/* Mobile hamburger */}
|
||||
<button
|
||||
onClick={() => setMobileOpen(true)}
|
||||
className="lg:hidden fixed top-4 right-4 z-50 p-2 rounded-xl bg-white dark:bg-gray-900 shadow-lg ring-1 ring-gray-200 dark:ring-gray-800 text-gray-600 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors"
|
||||
>
|
||||
<Bars3Icon className="h-6 w-6" />
|
||||
</button>
|
||||
|
||||
{/* Mobile overlay */}
|
||||
{mobileOpen && (
|
||||
<div className="lg:hidden fixed inset-0 z-40">
|
||||
<div
|
||||
className="absolute inset-0 bg-black/40 dark:bg-black/60 backdrop-blur-sm"
|
||||
onClick={() => setMobileOpen(false)}
|
||||
/>
|
||||
<div className="absolute inset-y-0 right-0 w-72 bg-white dark:bg-gray-950 shadow-2xl">
|
||||
<button
|
||||
onClick={() => setMobileOpen(false)}
|
||||
className="absolute top-4 left-4 p-1 rounded-lg text-gray-400 hover:text-gray-600 dark:hover:text-gray-200"
|
||||
>
|
||||
<XMarkIcon className="h-5 w-5" />
|
||||
</button>
|
||||
{navContent}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Desktop sidebar */}
|
||||
<aside className="hidden lg:flex lg:fixed lg:inset-y-0 lg:right-0 lg:z-30 lg:w-64 lg:flex-col bg-white dark:bg-gray-950 border-l border-gray-200 dark:border-gray-800">
|
||||
{navContent}
|
||||
</aside>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
'use client';
|
||||
|
||||
interface Step {
|
||||
label: string;
|
||||
isCompleted: boolean;
|
||||
isCurrent: boolean;
|
||||
}
|
||||
|
||||
interface StepIndicatorProps {
|
||||
steps: Step[];
|
||||
}
|
||||
|
||||
export default function StepIndicator({ steps }: StepIndicatorProps) {
|
||||
return (
|
||||
<div className="flex items-center gap-0 w-full max-w-2xl">
|
||||
{steps.map((step, index) => (
|
||||
<div key={index} className="flex items-center flex-1 last:flex-none">
|
||||
<div className="flex flex-col items-center">
|
||||
<div
|
||||
className={`flex items-center justify-center w-8 h-8 rounded-full text-xs font-bold transition-all duration-200 ${
|
||||
step.isCompleted
|
||||
? 'bg-indigo-600 text-white shadow-sm shadow-indigo-500/30'
|
||||
: step.isCurrent
|
||||
? 'bg-indigo-100 dark:bg-indigo-500/15 text-indigo-700 dark:text-indigo-400 ring-2 ring-indigo-600 dark:ring-indigo-400'
|
||||
: 'bg-gray-100 dark:bg-gray-800 text-gray-400 dark:text-gray-500'
|
||||
}`}
|
||||
>
|
||||
{step.isCompleted ? (
|
||||
<svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" strokeWidth={2.5} stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" d="m4.5 12.75 6 6 9-13.5" />
|
||||
</svg>
|
||||
) : (
|
||||
index + 1
|
||||
)}
|
||||
</div>
|
||||
<span
|
||||
className={`mt-1.5 text-xs font-medium whitespace-nowrap ${
|
||||
step.isCurrent
|
||||
? 'text-indigo-700 dark:text-indigo-400'
|
||||
: step.isCompleted
|
||||
? 'text-gray-600 dark:text-gray-300'
|
||||
: 'text-gray-400 dark:text-gray-500'
|
||||
}`}
|
||||
>
|
||||
{step.label}
|
||||
</span>
|
||||
</div>
|
||||
{index < steps.length - 1 && (
|
||||
<div
|
||||
className={`flex-1 h-0.5 mx-2 mb-5 rounded-full transition-colors ${
|
||||
step.isCompleted
|
||||
? 'bg-indigo-600'
|
||||
: 'bg-gray-200 dark:bg-gray-800'
|
||||
}`}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useEffect } from 'react';
|
||||
import { PackageName, CreatePackageData, UpdatePackageData } from '@/types/package';
|
||||
import { XMarkIcon, PhotoIcon, DocumentTextIcon } from '@heroicons/react/24/outline';
|
||||
|
||||
interface PackageFormProps {
|
||||
package?: PackageName | null;
|
||||
onSubmit: (data: CreatePackageData | UpdatePackageData) => Promise<void>;
|
||||
onCancel: () => void;
|
||||
isLoading: boolean;
|
||||
}
|
||||
|
||||
export default function PackageForm({ package: pkg, onSubmit, onCancel, isLoading }: PackageFormProps) {
|
||||
const [formData, setFormData] = useState<CreatePackageData | UpdatePackageData>({
|
||||
name: '',
|
||||
title: '',
|
||||
v1_identifier: '',
|
||||
myket_access_token: '',
|
||||
cafe_config_id: null,
|
||||
web_app_url: '',
|
||||
tries: 0,
|
||||
});
|
||||
|
||||
const [avatarFile, setAvatarFile] = useState<File | null>(null);
|
||||
const [firebaseFile, setFirebaseFile] = useState<File | null>(null);
|
||||
const [avatarPreview, setAvatarPreview] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (pkg) {
|
||||
setFormData({
|
||||
name: pkg.name || '',
|
||||
title: pkg.title || '',
|
||||
v1_identifier: pkg.v1_identifier || '',
|
||||
myket_access_token: pkg.myket_access_token || '',
|
||||
cafe_config_id: pkg.cafe_config_id,
|
||||
web_app_url: pkg.web_app_url || '',
|
||||
tries: pkg.tries || 0,
|
||||
});
|
||||
if (pkg.image && typeof pkg.image === 'string') {
|
||||
setAvatarPreview(pkg.image);
|
||||
}
|
||||
}
|
||||
}, [pkg]);
|
||||
|
||||
const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
|
||||
const { name, value } = e.target;
|
||||
setFormData(prev => ({ ...prev, [name]: value === '' ? null : value }));
|
||||
};
|
||||
|
||||
const handleNumberChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const { name, value } = e.target;
|
||||
setFormData(prev => ({ ...prev, [name]: value === '' ? null : parseInt(value, 10) }));
|
||||
};
|
||||
|
||||
const handleAvatarChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = e.target.files?.[0];
|
||||
if (file) {
|
||||
setAvatarFile(file);
|
||||
setFormData(prev => ({ ...prev, avatar: file }));
|
||||
const reader = new FileReader();
|
||||
reader.onloadend = () => setAvatarPreview(reader.result as string);
|
||||
reader.readAsDataURL(file);
|
||||
}
|
||||
};
|
||||
|
||||
const handleFirebaseChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = e.target.files?.[0];
|
||||
if (file) {
|
||||
setFirebaseFile(file);
|
||||
setFormData(prev => ({ ...prev, firebase_json: file }));
|
||||
}
|
||||
};
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
await onSubmit(formData);
|
||||
};
|
||||
|
||||
const removeAvatar = () => {
|
||||
setAvatarFile(null);
|
||||
setAvatarPreview(null);
|
||||
setFormData(prev => ({ ...prev, avatar: null }));
|
||||
};
|
||||
|
||||
const inputClass = 'block w-full px-4 py-2.5 text-sm text-gray-900 dark:text-gray-100 border border-gray-200 dark:border-gray-700 rounded-xl bg-gray-50 dark:bg-gray-800/60 placeholder-gray-400 dark:placeholder-gray-500 focus:ring-2 focus:ring-indigo-500/20 focus:border-indigo-500 dark:focus:border-indigo-400 transition-colors';
|
||||
const labelClass = 'block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5';
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit} className="space-y-6 bg-white dark:bg-gray-900 p-6 rounded-2xl ring-1 ring-gray-200 dark:ring-gray-800 shadow-sm">
|
||||
<div className="pb-4 border-b border-gray-100 dark:border-gray-800">
|
||||
<h3 className="text-lg font-semibold text-gray-900 dark:text-gray-100">
|
||||
{pkg ? 'ویرایش پکیج' : 'ایجاد پکیج جدید'}
|
||||
</h3>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 gap-5 md:grid-cols-2">
|
||||
<div>
|
||||
<label htmlFor="name" className={labelClass}>نام پکیج <span className="text-red-500">*</span></label>
|
||||
<input type="text" id="name" name="name" required value={formData.name || ''} onChange={handleInputChange} className={inputClass} placeholder="مثال: com.approagency.meditation" dir="ltr" />
|
||||
</div>
|
||||
<div>
|
||||
<label htmlFor="title" className={labelClass}>عنوان <span className="text-red-500">*</span></label>
|
||||
<input type="text" id="title" name="title" required value={formData.title || ''} onChange={handleInputChange} className={inputClass} placeholder="مثال: آرام لند" />
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className={labelClass}>تصویر</label>
|
||||
<div className="flex items-center gap-3">
|
||||
<label className="cursor-pointer inline-flex items-center gap-2 px-4 py-2.5 rounded-xl border border-gray-200 dark:border-gray-700 text-sm font-medium text-gray-700 dark:text-gray-200 bg-gray-50 dark:bg-gray-800/60 hover:bg-gray-100 dark:hover:bg-gray-800 transition-colors">
|
||||
<PhotoIcon className="h-4 w-4 text-gray-400" />
|
||||
انتخاب تصویر
|
||||
<input type="file" accept="image/*" onChange={handleAvatarChange} className="hidden" />
|
||||
</label>
|
||||
{avatarPreview && (
|
||||
<button type="button" onClick={removeAvatar} className="text-red-500 hover:text-red-700 transition-colors">
|
||||
<XMarkIcon className="h-5 w-5" />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
{avatarPreview && (
|
||||
<div className="mt-3">
|
||||
<img src={avatarPreview} alt="Preview" className="h-20 w-20 object-cover rounded-xl ring-1 ring-gray-200 dark:ring-gray-800" />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label htmlFor="v1_identifier" className={labelClass}>شناسه V1</label>
|
||||
<input type="text" id="v1_identifier" name="v1_identifier" value={formData.v1_identifier || ''} onChange={handleInputChange} className={inputClass} />
|
||||
</div>
|
||||
<div>
|
||||
<label htmlFor="myket_access_token" className={labelClass}>توکن دسترسی Myket</label>
|
||||
<input type="text" id="myket_access_token" name="myket_access_token" value={formData.myket_access_token || ''} onChange={handleInputChange} className={inputClass} />
|
||||
</div>
|
||||
<div>
|
||||
<label htmlFor="cafe_config_id" className={labelClass}>شناسه کافه بازار</label>
|
||||
<input type="number" id="cafe_config_id" name="cafe_config_id" value={formData.cafe_config_id || ''} onChange={handleNumberChange} className={inputClass} />
|
||||
</div>
|
||||
<div>
|
||||
<label htmlFor="web_app_url" className={labelClass}>آدرس وب اپلیکیشن</label>
|
||||
<input type="url" id="web_app_url" name="web_app_url" value={formData.web_app_url || ''} onChange={handleInputChange} className={inputClass} placeholder="https://example.com" dir="ltr" />
|
||||
</div>
|
||||
<div>
|
||||
<label htmlFor="tries" className={labelClass}>تعداد تلاشها</label>
|
||||
<input type="number" id="tries" name="tries" value={formData.tries || 0} onChange={handleNumberChange} className={inputClass} />
|
||||
</div>
|
||||
<div className="md:col-span-2 pt-2 border-t border-gray-100 dark:border-gray-800">
|
||||
<label className={labelClass}>فایل Firebase JSON</label>
|
||||
<label className="cursor-pointer inline-flex items-center gap-2 px-4 py-2.5 rounded-xl border border-gray-200 dark:border-gray-700 text-sm font-medium text-gray-700 dark:text-gray-200 bg-gray-50 dark:bg-gray-800/60 hover:bg-gray-100 dark:hover:bg-gray-800 transition-colors">
|
||||
<DocumentTextIcon className="h-4 w-4 text-gray-400" />
|
||||
انتخاب فایل
|
||||
<input type="file" accept=".json,application/json" onChange={handleFirebaseChange} className="hidden" />
|
||||
</label>
|
||||
{firebaseFile && (
|
||||
<p className="mt-2 text-xs text-gray-500 dark:text-gray-400">{firebaseFile.name}</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end gap-3 pt-4 border-t border-gray-100 dark:border-gray-800">
|
||||
<button type="button" onClick={onCancel} className="px-5 py-2.5 rounded-xl border border-gray-200 dark:border-gray-700 text-sm font-medium text-gray-700 dark:text-gray-200 bg-white dark:bg-gray-800 hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors">
|
||||
انصراف
|
||||
</button>
|
||||
<button type="submit" disabled={isLoading} className="px-5 py-2.5 rounded-xl bg-indigo-600 text-white text-sm font-medium hover:bg-indigo-700 focus:ring-2 focus:ring-indigo-500/30 disabled:opacity-50 transition-colors shadow-sm shadow-indigo-500/20">
|
||||
{isLoading ? 'در حال ذخیره...' : pkg ? 'بهروزرسانی' : 'ایجاد'}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
'use client';
|
||||
|
||||
import { PackageName } from '@/types/package';
|
||||
import { PencilIcon, TrashIcon } from '@heroicons/react/24/outline';
|
||||
import { formatDate } from '@/lib/utils';
|
||||
import Image from 'next/image';
|
||||
|
||||
interface PackageListProps {
|
||||
packages: PackageName[];
|
||||
onEdit: (pkg: PackageName) => void;
|
||||
onDelete: (pkg: PackageName) => void;
|
||||
isLoading: boolean;
|
||||
}
|
||||
|
||||
export default function PackageList({ packages, onEdit, onDelete, isLoading }: PackageListProps) {
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="flex justify-center items-center py-16">
|
||||
<div className="h-10 w-10 border-4 border-indigo-200 dark:border-indigo-800 border-t-indigo-600 rounded-full animate-spin" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (!packages || packages.length === 0) {
|
||||
return (
|
||||
<div className="text-center py-16 bg-white dark:bg-gray-900 rounded-2xl ring-1 ring-gray-200 dark:ring-gray-800 shadow-sm">
|
||||
<div className="mx-auto h-12 w-12 rounded-xl bg-gray-100 dark:bg-gray-800 flex items-center justify-center mb-3">
|
||||
<svg className="h-6 w-6 text-gray-400" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" d="M21 7.5l-2.25-1.313M21 7.5v2.25m0-2.25l-2.25 1.313M3 7.5l2.25-1.313M3 7.5l2.25 1.313M3 7.5v2.25m9 3l2.25-1.313M12 12.75l-2.25-1.313M12 12.75V15m0 6.75l2.25-1.313M12 21.75V19.5m0 2.25l-2.25-1.313m0-16.875L12 2.25l2.25 1.313M21 14.25v2.25l-2.25 1.313m-13.5 0L3 16.5v-2.25" />
|
||||
</svg>
|
||||
</div>
|
||||
<p className="text-gray-500 dark:text-gray-400 text-sm">هیچ پکیجی یافت نشد</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="bg-white dark:bg-gray-900 ring-1 ring-gray-200 dark:ring-gray-800 rounded-2xl overflow-hidden shadow-sm">
|
||||
<div className="px-5 py-4 border-b border-gray-200 dark:border-gray-800">
|
||||
<h3 className="text-base font-semibold text-gray-900 dark:text-gray-100">لیست پکیجها</h3>
|
||||
</div>
|
||||
<ul className="divide-y divide-gray-200 dark:divide-gray-800">
|
||||
{packages.map((pkg) => (
|
||||
<li key={pkg.id} className="px-5 py-4 hover:bg-gray-50 dark:hover:bg-gray-800/40 transition-colors">
|
||||
<div className="flex items-center justify-between gap-4">
|
||||
<div className="flex items-center gap-4 flex-1 min-w-0">
|
||||
{pkg.image && typeof pkg.image === 'string' ? (
|
||||
<div className="relative h-12 w-12 rounded-xl overflow-hidden ring-1 ring-gray-200 dark:ring-gray-800 flex-shrink-0">
|
||||
<Image src={pkg.image} alt={pkg.title || ''} fill className="object-cover" unoptimized />
|
||||
</div>
|
||||
) : (
|
||||
<div className="h-12 w-12 rounded-xl bg-indigo-100 dark:bg-indigo-500/10 flex items-center justify-center flex-shrink-0">
|
||||
<span className="text-lg font-bold text-indigo-600 dark:text-indigo-400">{(pkg.title || pkg.name || '?')[0]}</span>
|
||||
</div>
|
||||
)}
|
||||
<div className="min-w-0">
|
||||
<p className="text-sm font-semibold text-indigo-600 dark:text-indigo-400 truncate">{pkg.title || 'بدون عنوان'}</p>
|
||||
<p className="text-xs text-gray-500 dark:text-gray-400 truncate" dir="ltr">{pkg.name || 'بدون نام'}</p>
|
||||
<p className="text-xs text-gray-400 dark:text-gray-500 mt-1">{formatDate(pkg.updated_at)}</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-1 flex-shrink-0">
|
||||
<button
|
||||
onClick={() => onEdit(pkg)}
|
||||
className="p-2 rounded-lg text-indigo-600 dark:text-indigo-400 hover:bg-indigo-50 dark:hover:bg-indigo-500/10 transition-colors"
|
||||
>
|
||||
<PencilIcon className="h-4 w-4" />
|
||||
</button>
|
||||
<button
|
||||
onClick={() => onDelete(pkg)}
|
||||
className="p-2 rounded-lg text-red-600 dark:text-red-400 hover:bg-red-50 dark:hover:bg-red-500/10 transition-colors"
|
||||
>
|
||||
<TrashIcon className="h-4 w-4" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useEffect } from 'react';
|
||||
import { Product, CreateProductData, UpdateProductData, PRODUCT_TYPES } from '@/types/product';
|
||||
import { PlusIcon, XMarkIcon } from '@heroicons/react/24/outline';
|
||||
|
||||
interface ProductFormProps {
|
||||
product?: Product | null;
|
||||
packageName: string;
|
||||
onSubmit: (data: CreateProductData | UpdateProductData) => Promise<void>;
|
||||
onCancel: () => void;
|
||||
isLoading: boolean;
|
||||
}
|
||||
|
||||
export default function ProductForm({ product, packageName, onSubmit, onCancel, isLoading }: ProductFormProps) {
|
||||
const [formData, setFormData] = useState<CreateProductData | UpdateProductData>({
|
||||
title: '',
|
||||
price: 0,
|
||||
type: 4,
|
||||
discounted_price: '',
|
||||
daily_price: '',
|
||||
discount: '',
|
||||
is_best_seller: false,
|
||||
sort_order: 0,
|
||||
});
|
||||
|
||||
const [descriptions, setDescriptions] = useState<string[]>([]);
|
||||
const [newDescription, setNewDescription] = useState('');
|
||||
|
||||
useEffect(() => {
|
||||
if (product) {
|
||||
setFormData({
|
||||
title: product.title || '',
|
||||
price: product.price || 0,
|
||||
type: product.type || 4,
|
||||
discounted_price: product.discounted_price || '',
|
||||
daily_price: product.daily_price || '',
|
||||
discount: product.discount || '',
|
||||
is_best_seller: product.is_best_seller || false,
|
||||
sort_order: product.sort_order || 0,
|
||||
});
|
||||
setDescriptions(product.descriptions || []);
|
||||
}
|
||||
}, [product]);
|
||||
|
||||
const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) => {
|
||||
const { name, value, type } = e.target;
|
||||
if (type === 'checkbox') {
|
||||
const { checked } = e.target as HTMLInputElement;
|
||||
setFormData(prev => ({ ...prev, [name]: checked }));
|
||||
return;
|
||||
}
|
||||
setFormData(prev => ({
|
||||
...prev,
|
||||
[name]: name === 'price' || name === 'sort_order' ? parseInt(value) || 0 : value,
|
||||
}));
|
||||
};
|
||||
|
||||
const handleAddDescription = () => {
|
||||
if (newDescription.trim()) {
|
||||
setDescriptions([...descriptions, newDescription.trim()]);
|
||||
setNewDescription('');
|
||||
}
|
||||
};
|
||||
|
||||
const handleRemoveDescription = (index: number) => {
|
||||
setDescriptions(descriptions.filter((_, i) => i !== index));
|
||||
};
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
const submitData = {
|
||||
...formData,
|
||||
...(descriptions.length > 0 && { descriptions }),
|
||||
};
|
||||
await onSubmit(submitData);
|
||||
};
|
||||
|
||||
const inputClass = 'block w-full px-4 py-2.5 text-sm text-gray-900 dark:text-gray-100 border border-gray-200 dark:border-gray-700 rounded-xl bg-gray-50 dark:bg-gray-800/60 placeholder-gray-400 dark:placeholder-gray-500 focus:ring-2 focus:ring-indigo-500/20 focus:border-indigo-500 dark:focus:border-indigo-400 transition-colors';
|
||||
const labelClass = 'block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5';
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit} className="space-y-6 bg-white dark:bg-gray-900 p-6 rounded-2xl ring-1 ring-gray-200 dark:ring-gray-800 shadow-sm">
|
||||
<div className="pb-4 border-b border-gray-100 dark:border-gray-800">
|
||||
<h3 className="text-lg font-semibold text-gray-900 dark:text-gray-100">
|
||||
{product ? 'ویرایش محصول' : 'ایجاد محصول جدید'} برای پکیج {packageName}
|
||||
</h3>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 gap-5 md:grid-cols-2">
|
||||
<div>
|
||||
<label htmlFor="title" className={labelClass}>عنوان <span className="text-red-500">*</span></label>
|
||||
<input type="text" id="title" name="title" required value={formData.title || ''} onChange={handleInputChange} className={inputClass} placeholder="مثال: اشتراک ماهانه" />
|
||||
</div>
|
||||
<div>
|
||||
<label htmlFor="price" className={labelClass}>قیمت (تومان) <span className="text-red-500">*</span></label>
|
||||
<input type="number" id="price" name="price" required min="0" value={formData.price || ''} onChange={handleInputChange} className={inputClass} placeholder="مثال: 60000" />
|
||||
</div>
|
||||
<div>
|
||||
<label htmlFor="type" className={labelClass}>نوع اشتراک <span className="text-red-500">*</span></label>
|
||||
<select id="type" name="type" required value={formData.type || 4} onChange={handleInputChange} className={inputClass}>
|
||||
{Object.entries(PRODUCT_TYPES).map(([value, label]) => (
|
||||
<option key={value} value={value}>{label}</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label htmlFor="discounted_price" className={labelClass}>قیمت کلی تخفیف خورده <span className="text-xs text-gray-400">(فقط نمایشی)</span></label>
|
||||
<input type="text" id="discounted_price" name="discounted_price" value={formData.discounted_price || ''} onChange={handleInputChange} dir="rtl" className={inputClass} placeholder="مثال: ۱٬۴۶۰٬۰۰۰" />
|
||||
</div>
|
||||
<div>
|
||||
<label htmlFor="daily_price" className={labelClass}>قیمت روزانه <span className="text-xs text-gray-400">(فقط نمایشی)</span></label>
|
||||
<input type="text" id="daily_price" name="daily_price" value={formData.daily_price || ''} onChange={handleInputChange} dir="rtl" className={inputClass} placeholder="مثال: معادل روزانه ۴٬۰۰۰ تومان" />
|
||||
</div>
|
||||
<div>
|
||||
<label htmlFor="discount" className={labelClass}>تخفیف <span className="text-xs text-gray-400">(فقط نمایشی)</span></label>
|
||||
<input type="text" id="discount" name="discount" value={formData.discount || ''} onChange={handleInputChange} dir="rtl" className={inputClass} placeholder="مثال: ۵۵٪ تخفیف" />
|
||||
</div>
|
||||
<div>
|
||||
<label htmlFor="sort_order" className={labelClass}>ترتیب نمایش <span className="text-xs text-gray-400">(۰ بالاترین)</span></label>
|
||||
<input type="number" id="sort_order" name="sort_order" min="0" value={formData.sort_order ?? 0} onChange={handleInputChange} className={inputClass} placeholder="0" />
|
||||
</div>
|
||||
<div className="md:col-span-2">
|
||||
<label className="flex items-center gap-3 cursor-pointer p-3 rounded-xl bg-gray-50 dark:bg-gray-800/60 hover:bg-gray-100 dark:hover:bg-gray-800 transition-colors">
|
||||
<input type="checkbox" name="is_best_seller" checked={!!formData.is_best_seller} onChange={handleInputChange} className="h-4 w-4 text-indigo-600 border-gray-300 dark:border-gray-600 rounded-lg focus:ring-indigo-500 dark:bg-gray-800" />
|
||||
<div>
|
||||
<span className="text-sm font-medium text-gray-700 dark:text-gray-300">پرفروشترین اشتراک</span>
|
||||
<span className="text-xs text-gray-400 mr-2">(فقط برای یک محصول فعال میشود)</span>
|
||||
</div>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="pt-4 border-t border-gray-100 dark:border-gray-800">
|
||||
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">ویژگیها</label>
|
||||
<div className="flex gap-2">
|
||||
<input
|
||||
type="text"
|
||||
value={newDescription}
|
||||
onChange={(e) => setNewDescription(e.target.value)}
|
||||
className={`flex-1 ${inputClass}`}
|
||||
placeholder="ویژگی جدید را وارد کنید"
|
||||
onKeyDown={(e) => { if (e.key === 'Enter') { e.preventDefault(); handleAddDescription(); } }}
|
||||
/>
|
||||
<button type="button" onClick={handleAddDescription} className="inline-flex items-center px-4 py-2.5 rounded-xl bg-indigo-600 text-white text-sm font-medium hover:bg-indigo-700 focus:ring-2 focus:ring-indigo-500/30 transition-colors shadow-sm shadow-indigo-500/20">
|
||||
<PlusIcon className="h-5 w-5" />
|
||||
</button>
|
||||
</div>
|
||||
{descriptions.length > 0 && (
|
||||
<ul className="mt-3 space-y-2">
|
||||
{descriptions.map((desc, index) => (
|
||||
<li key={index} className="flex items-center justify-between px-4 py-2.5 rounded-xl bg-gray-50 dark:bg-gray-800/60 ring-1 ring-gray-100 dark:ring-gray-800">
|
||||
<span className="text-sm text-gray-700 dark:text-gray-300">{desc}</span>
|
||||
<button type="button" onClick={() => handleRemoveDescription(index)} className="text-red-500 hover:text-red-700 dark:text-red-400 transition-colors">
|
||||
<XMarkIcon className="h-4 w-4" />
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end gap-3 pt-4 border-t border-gray-100 dark:border-gray-800">
|
||||
<button type="button" onClick={onCancel} className="px-5 py-2.5 rounded-xl border border-gray-200 dark:border-gray-700 text-sm font-medium text-gray-700 dark:text-gray-200 bg-white dark:bg-gray-800 hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors">
|
||||
انصراف
|
||||
</button>
|
||||
<button type="submit" disabled={isLoading} className="px-5 py-2.5 rounded-xl bg-indigo-600 text-white text-sm font-medium hover:bg-indigo-700 focus:ring-2 focus:ring-indigo-500/30 disabled:opacity-50 transition-colors shadow-sm shadow-indigo-500/20">
|
||||
{isLoading ? 'در حال ذخیره...' : product ? 'بهروزرسانی' : 'ایجاد'}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
'use client';
|
||||
|
||||
import { Product } from '@/types/product';
|
||||
import { getProductTypeLabel, PRODUCT_TYPES } from '@/types/product';
|
||||
import { PencilIcon, TrashIcon } from '@heroicons/react/24/outline';
|
||||
import { formatDate, formatPrice } from '@/lib/utils';
|
||||
|
||||
interface ProductListProps {
|
||||
products: Product[];
|
||||
packageName: string;
|
||||
onEdit: (product: Product) => void;
|
||||
onDelete: (product: Product) => void;
|
||||
isLoading: boolean;
|
||||
}
|
||||
|
||||
export default function ProductList({ products, packageName, onEdit, onDelete, isLoading }: ProductListProps) {
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="flex justify-center items-center py-16">
|
||||
<div className="h-10 w-10 border-4 border-indigo-200 dark:border-indigo-800 border-t-indigo-600 rounded-full animate-spin" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (!products || products.length === 0) {
|
||||
return (
|
||||
<div className="text-center py-16 bg-white dark:bg-gray-900 rounded-2xl ring-1 ring-gray-200 dark:ring-gray-800 shadow-sm">
|
||||
<div className="mx-auto h-12 w-12 rounded-xl bg-gray-100 dark:bg-gray-800 flex items-center justify-center mb-3">
|
||||
<svg className="h-6 w-6 text-gray-400" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" d="M15.75 10.5V6a3.75 3.75 0 1 0-7.5 0v4.5m11.356-1.993 1.263 12c.07.665-.45 1.243-1.119 1.243H4.25a1.125 1.125 0 0 1-1.12-1.243l1.264-12A1.125 1.125 0 0 1 5.513 7.5h12.974c.576 0 1.059.435 1.119 1.007ZM8.625 10.5a.375.375 0 1 1-.75 0 .375.375 0 0 1 .75 0Zm7.5 0a.375.375 0 1 1-.75 0 .375.375 0 0 1 .75 0Z" />
|
||||
</svg>
|
||||
</div>
|
||||
<p className="text-gray-500 dark:text-gray-400 text-sm">هیچ محصولی برای پکیج {packageName} یافت نشد</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="bg-white dark:bg-gray-900 ring-1 ring-gray-200 dark:ring-gray-800 rounded-2xl overflow-hidden shadow-sm">
|
||||
<div className="px-5 py-4 border-b border-gray-200 dark:border-gray-800">
|
||||
<h3 className="text-base font-semibold text-gray-900 dark:text-gray-100">
|
||||
محصولات پکیج {packageName}
|
||||
</h3>
|
||||
</div>
|
||||
<ul className="divide-y divide-gray-200 dark:divide-gray-800">
|
||||
{products.map((product) => (
|
||||
<li key={product.id} className="px-5 py-4 hover:bg-gray-50 dark:hover:bg-gray-800/40 transition-colors">
|
||||
<div className="flex items-start justify-between gap-4">
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
<p className="text-sm font-semibold text-indigo-600 dark:text-indigo-400">
|
||||
{product.title || 'بدون عنوان'}
|
||||
</p>
|
||||
{product.is_best_seller && (
|
||||
<span className="px-2 py-0.5 text-xs font-semibold rounded-lg bg-amber-100 text-amber-800 dark:bg-amber-900/30 dark:text-amber-300">
|
||||
پرفروش
|
||||
</span>
|
||||
)}
|
||||
<span className="px-2 py-0.5 text-xs font-semibold rounded-lg bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-300">
|
||||
{getProductTypeLabel(product.type)}
|
||||
</span>
|
||||
<span className="px-2 py-0.5 text-xs font-medium rounded-lg bg-gray-100 text-gray-600 dark:bg-gray-800 dark:text-gray-400">
|
||||
#{product.sort_order ?? 0}
|
||||
</span>
|
||||
</div>
|
||||
<div className="mt-2 flex flex-wrap gap-x-5 gap-y-1 text-xs text-gray-500 dark:text-gray-400">
|
||||
<span className="font-medium text-gray-900 dark:text-gray-100">{formatPrice(product.price)} تومان</span>
|
||||
{product.discounted_price && <span>تخفیف: {product.discounted_price}</span>}
|
||||
{product.daily_price && <span>روزانه: {product.daily_price}</span>}
|
||||
{product.discount && <span>{product.discount}</span>}
|
||||
</div>
|
||||
{product.descriptions && product.descriptions.length > 0 && (
|
||||
<div className="mt-2 flex flex-wrap gap-1.5">
|
||||
{product.descriptions.map((desc, index) => (
|
||||
<span key={index} className="px-2 py-0.5 text-xs bg-gray-100 dark:bg-gray-800 text-gray-600 dark:text-gray-400 rounded-md">
|
||||
{desc}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
<p className="mt-2 text-xs text-gray-400 dark:text-gray-500">
|
||||
{formatDate(product.updated_at)}
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex items-center gap-1 flex-shrink-0">
|
||||
<button
|
||||
onClick={() => onEdit(product)}
|
||||
className="p-2 rounded-lg text-indigo-600 dark:text-indigo-400 hover:bg-indigo-50 dark:hover:bg-indigo-500/10 transition-colors"
|
||||
>
|
||||
<PencilIcon className="h-4 w-4" />
|
||||
</button>
|
||||
<button
|
||||
onClick={() => onDelete(product)}
|
||||
className="p-2 rounded-lg text-red-600 dark:text-red-400 hover:bg-red-50 dark:hover:bg-red-500/10 transition-colors"
|
||||
>
|
||||
<TrashIcon className="h-4 w-4" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,202 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useEffect } from 'react';
|
||||
import { Promotion, CreatePromotionData, UpdatePromotionData, PROMOTION_TYPES } from '@/types/promotion';
|
||||
import { PhotoIcon, XMarkIcon } from '@heroicons/react/24/outline';
|
||||
|
||||
interface PromotionFormProps {
|
||||
promotion?: Promotion | null;
|
||||
onSubmit: (data: CreatePromotionData | UpdatePromotionData) => Promise<void>;
|
||||
onCancel: () => void;
|
||||
isLoading: boolean;
|
||||
}
|
||||
|
||||
export default function PromotionForm({ promotion, onSubmit, onCancel, isLoading }: PromotionFormProps) {
|
||||
const [formData, setFormData] = useState<CreatePromotionData | UpdatePromotionData>({
|
||||
type: 'slider',
|
||||
title: '',
|
||||
subtitle: '',
|
||||
action_text: '',
|
||||
url_myket: '',
|
||||
url_bazzar: '',
|
||||
url_google_play: '',
|
||||
url_site: '',
|
||||
priority: 0,
|
||||
start_at: '',
|
||||
end_at: '',
|
||||
});
|
||||
|
||||
const [imageFile, setImageFile] = useState<File | null>(null);
|
||||
const [imagePreview, setImagePreview] = useState<string | null>(null);
|
||||
const [isActive, setIsActive] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
if (promotion) {
|
||||
const startAt = promotion.start_at ? promotion.start_at.slice(0, 16) : '';
|
||||
const endAt = promotion.end_at ? promotion.end_at.slice(0, 16) : '';
|
||||
setFormData({
|
||||
type: promotion.type || 'slider',
|
||||
title: promotion.title || '',
|
||||
subtitle: promotion.subtitle || '',
|
||||
action_text: promotion.action_text || '',
|
||||
url_myket: promotion.url_myket || '',
|
||||
url_bazzar: promotion.url_bazzar || '',
|
||||
url_google_play: promotion.url_google_play || '',
|
||||
url_site: promotion.url_site || '',
|
||||
priority: promotion.priority || 0,
|
||||
start_at: startAt,
|
||||
end_at: endAt,
|
||||
});
|
||||
setIsActive(promotion.is_active);
|
||||
if (promotion.image_url) setImagePreview(promotion.image_url);
|
||||
} else {
|
||||
setFormData(prev => ({ ...prev, priority: 0 }));
|
||||
}
|
||||
}, [promotion]);
|
||||
|
||||
const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) => {
|
||||
const { name, value } = e.target;
|
||||
setFormData(prev => ({ ...prev, [name]: value === '' ? null : value }));
|
||||
};
|
||||
|
||||
const handleNumberChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const { name, value } = e.target;
|
||||
setFormData(prev => ({ ...prev, [name]: value === '' ? null : parseInt(value, 10) }));
|
||||
};
|
||||
|
||||
const handleImageChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = e.target.files?.[0];
|
||||
if (file) {
|
||||
setImageFile(file);
|
||||
setFormData(prev => ({ ...prev, image: file }));
|
||||
const reader = new FileReader();
|
||||
reader.onloadend = () => setImagePreview(reader.result as string);
|
||||
reader.readAsDataURL(file);
|
||||
}
|
||||
};
|
||||
|
||||
const removeImage = () => {
|
||||
setImageFile(null);
|
||||
setImagePreview(null);
|
||||
setFormData(prev => ({ ...prev, image: null }));
|
||||
};
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
let submitData: any = { ...formData };
|
||||
if (submitData.start_at) submitData.start_at = submitData.start_at.replace('T', ' ') + ':00';
|
||||
if (submitData.end_at) submitData.end_at = submitData.end_at.replace('T', ' ') + ':00';
|
||||
if (promotion) submitData.is_active = isActive;
|
||||
await onSubmit(submitData);
|
||||
};
|
||||
|
||||
const inputClass = 'block w-full px-4 py-2.5 text-sm text-gray-900 dark:text-gray-100 border border-gray-200 dark:border-gray-700 rounded-xl bg-gray-50 dark:bg-gray-800/60 placeholder-gray-400 dark:placeholder-gray-500 focus:ring-2 focus:ring-indigo-500/20 focus:border-indigo-500 dark:focus:border-indigo-400 transition-colors';
|
||||
const labelClass = 'block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5';
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit} className="space-y-6 bg-white dark:bg-gray-900 p-6 rounded-2xl ring-1 ring-gray-200 dark:ring-gray-800 shadow-sm">
|
||||
<div className="pb-4 border-b border-gray-100 dark:border-gray-800">
|
||||
<h3 className="text-lg font-semibold text-gray-900 dark:text-gray-100">
|
||||
{promotion ? 'ویرایش تبلیغ' : 'ایجاد تبلیغ جدید'}
|
||||
</h3>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 gap-5 md:grid-cols-2">
|
||||
<div>
|
||||
<label htmlFor="type" className={labelClass}>نوع <span className="text-red-500">*</span></label>
|
||||
<select id="type" name="type" required value={formData.type || 'slider'} onChange={handleInputChange} className={inputClass}>
|
||||
{Object.entries(PROMOTION_TYPES).map(([value, label]) => (
|
||||
<option key={value} value={value}>{label}</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label htmlFor="title" className={labelClass}>عنوان</label>
|
||||
<input type="text" id="title" name="title" value={formData.title || ''} onChange={handleInputChange} className={inputClass} placeholder="عنوان تبلیغ" />
|
||||
</div>
|
||||
<div className="md:col-span-2">
|
||||
<label htmlFor="subtitle" className={labelClass}>زیرعنوان</label>
|
||||
<input type="text" id="subtitle" name="subtitle" value={formData.subtitle || ''} onChange={handleInputChange} className={inputClass} placeholder="زیرعنوان تبلیغ" />
|
||||
</div>
|
||||
<div>
|
||||
<label htmlFor="action_text" className={labelClass}>متن دکمه</label>
|
||||
<input type="text" id="action_text" name="action_text" value={formData.action_text || ''} onChange={handleInputChange} className={inputClass} placeholder="مثال: همین حالا نصب کن" />
|
||||
</div>
|
||||
<div>
|
||||
<label htmlFor="priority" className={labelClass}>اولویت</label>
|
||||
<input type="number" id="priority" name="priority" min="0" value={formData.priority || 0} onChange={handleNumberChange} className={inputClass} placeholder="عدد بالاتر = اولویت بیشتر" />
|
||||
</div>
|
||||
<div>
|
||||
<label htmlFor="start_at" className={labelClass}>تاریخ شروع</label>
|
||||
<input type="datetime-local" id="start_at" name="start_at" value={formData.start_at || ''} onChange={handleInputChange} className={inputClass} />
|
||||
</div>
|
||||
<div>
|
||||
<label htmlFor="end_at" className={labelClass}>تاریخ پایان</label>
|
||||
<input type="datetime-local" id="end_at" name="end_at" value={formData.end_at || ''} onChange={handleInputChange} className={inputClass} />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="pt-4 border-t border-gray-100 dark:border-gray-800">
|
||||
<h4 className="text-sm font-semibold text-gray-900 dark:text-gray-100 mb-3">لینکها</h4>
|
||||
<div className="grid grid-cols-1 gap-4 md:grid-cols-2">
|
||||
<div>
|
||||
<label htmlFor="url_myket" className={labelClass}>لینک مایکت</label>
|
||||
<input type="url" id="url_myket" name="url_myket" value={formData.url_myket || ''} onChange={handleInputChange} className={inputClass} placeholder="https://myket.ir/app/..." dir="ltr" />
|
||||
</div>
|
||||
<div>
|
||||
<label htmlFor="url_bazzar" className={labelClass}>لینک بازار</label>
|
||||
<input type="url" id="url_bazzar" name="url_bazzar" value={formData.url_bazzar || ''} onChange={handleInputChange} className={inputClass} placeholder="https://cafebazaar.ir/app/..." dir="ltr" />
|
||||
</div>
|
||||
<div>
|
||||
<label htmlFor="url_google_play" className={labelClass}>لینک گوگلپلی</label>
|
||||
<input type="url" id="url_google_play" name="url_google_play" value={formData.url_google_play || ''} onChange={handleInputChange} className={inputClass} placeholder="https://play.google.com/store/apps/..." dir="ltr" />
|
||||
</div>
|
||||
<div>
|
||||
<label htmlFor="url_site" className={labelClass}>لینک وبسایت</label>
|
||||
<input type="url" id="url_site" name="url_site" value={formData.url_site || ''} onChange={handleInputChange} className={inputClass} placeholder="https://example.com" dir="ltr" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="pt-2 border-t border-gray-100 dark:border-gray-800">
|
||||
<label className={labelClass}>تصویر</label>
|
||||
<div className="flex items-center gap-3">
|
||||
<label className="cursor-pointer inline-flex items-center gap-2 px-4 py-2.5 rounded-xl border border-gray-200 dark:border-gray-700 text-sm font-medium text-gray-700 dark:text-gray-200 bg-gray-50 dark:bg-gray-800/60 hover:bg-gray-100 dark:hover:bg-gray-800 transition-colors">
|
||||
<PhotoIcon className="h-4 w-4 text-gray-400" />
|
||||
انتخاب تصویر
|
||||
<input type="file" accept="image/*" onChange={handleImageChange} className="hidden" />
|
||||
</label>
|
||||
{imagePreview && (
|
||||
<button type="button" onClick={removeImage} className="text-red-500 hover:text-red-700 transition-colors">
|
||||
<XMarkIcon className="h-5 w-5" />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
{imagePreview && (
|
||||
<div className="mt-3 relative h-32 w-32 rounded-xl overflow-hidden ring-1 ring-gray-200 dark:ring-gray-800">
|
||||
<img src={imagePreview} alt="Preview" className="w-full h-full object-cover" />
|
||||
</div>
|
||||
)}
|
||||
<p className="mt-1.5 text-xs text-gray-400 dark:text-gray-500">حداکثر حجم: ۲ مگابایت</p>
|
||||
</div>
|
||||
|
||||
{promotion && (
|
||||
<div className="pt-2 border-t border-gray-100 dark:border-gray-800">
|
||||
<label className="flex items-center gap-3 p-3 rounded-xl bg-gray-50 dark:bg-gray-800/60 hover:bg-gray-100 dark:hover:bg-gray-800 transition-colors cursor-pointer">
|
||||
<input type="checkbox" id="is_active" checked={isActive} onChange={(e) => setIsActive(e.target.checked)} className="h-4 w-4 text-indigo-600 border-gray-300 dark:border-gray-600 dark:bg-gray-800 rounded-lg focus:ring-indigo-500" />
|
||||
<span className="text-sm font-medium text-gray-700 dark:text-gray-300">فعال</span>
|
||||
</label>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex justify-end gap-3 pt-4 border-t border-gray-100 dark:border-gray-800">
|
||||
<button type="button" onClick={onCancel} className="px-5 py-2.5 rounded-xl border border-gray-200 dark:border-gray-700 text-sm font-medium text-gray-700 dark:text-gray-200 bg-white dark:bg-gray-800 hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors">
|
||||
انصراف
|
||||
</button>
|
||||
<button type="submit" disabled={isLoading} className="px-5 py-2.5 rounded-xl bg-indigo-600 text-white text-sm font-medium hover:bg-indigo-700 focus:ring-2 focus:ring-indigo-500/30 disabled:opacity-50 transition-colors shadow-sm shadow-indigo-500/20">
|
||||
{isLoading ? 'در حال ذخیره...' : promotion ? 'بهروزرسانی' : 'ایجاد'}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
'use client';
|
||||
|
||||
import { Promotion } from '@/types/promotion';
|
||||
import { getPromotionTypeLabel } from '@/types/promotion';
|
||||
import { PencilIcon, TrashIcon, EyeIcon, EyeSlashIcon } from '@heroicons/react/24/outline';
|
||||
import { formatDate } from '@/lib/utils';
|
||||
import Image from 'next/image';
|
||||
import { useState } from 'react';
|
||||
|
||||
interface PromotionListProps {
|
||||
promotions: Promotion[];
|
||||
onEdit: (promotion: Promotion) => void;
|
||||
onDelete: (promotion: Promotion) => void;
|
||||
onToggleActive: (promotion: Promotion) => void;
|
||||
isLoading: boolean;
|
||||
}
|
||||
|
||||
export default function PromotionList({ promotions, onEdit, onDelete, onToggleActive, isLoading }: PromotionListProps) {
|
||||
const [imageErrors, setImageErrors] = useState<Record<number, boolean>>({});
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="flex justify-center items-center py-16">
|
||||
<div className="h-10 w-10 border-4 border-indigo-200 dark:border-indigo-800 border-t-indigo-600 rounded-full animate-spin" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (!promotions || promotions.length === 0) {
|
||||
return (
|
||||
<div className="text-center py-16 bg-white dark:bg-gray-900 rounded-2xl ring-1 ring-gray-200 dark:ring-gray-800 shadow-sm">
|
||||
<div className="mx-auto h-12 w-12 rounded-xl bg-gray-100 dark:bg-gray-800 flex items-center justify-center mb-3">
|
||||
<svg className="h-6 w-6 text-gray-400" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" d="M10.34 15.84c-.688-.06-1.386-.09-2.09-.09H7.5a4.5 4.5 0 1 1 0-9h.75c.704 0 1.402-.03 2.09-.09m0 9.18c.253.962.584 1.892.985 2.783.247.55.06 1.21-.463 1.511l-.657.38c-.551.318-1.26.117-1.527-.461a20.845 20.845 0 0 1-1.44-4.282m3.102.069a18.03 18.03 0 0 1-.59-4.59c0-1.586.205-3.124.59-4.59m0 9.18a23.848 23.848 0 0 1-8.635 2.517m0 0a23.848 23.848 0 0 1-8.635-2.517m8.635 2.517a23.848 23.848 0 0 0 8.635 2.517m0 0a23.848 23.848 0 0 0 8.635-2.517M12 13.5a2.25 2.25 0 1 1-4.5 0 2.25 2.25 0 0 1 4.5 0Z" />
|
||||
</svg>
|
||||
</div>
|
||||
<p className="text-gray-500 dark:text-gray-400 text-sm">هیچ تبلیغاتی یافت نشد</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const sortedPromotions = [...promotions].sort((a, b) => {
|
||||
if (a.priority && b.priority) return b.priority - a.priority;
|
||||
if (a.priority) return -1;
|
||||
if (b.priority) return 1;
|
||||
return new Date(b.created_at).getTime() - new Date(a.created_at).getTime();
|
||||
});
|
||||
|
||||
const handleImageError = (id: number) => {
|
||||
setImageErrors(prev => ({ ...prev, [id]: true }));
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="bg-white dark:bg-gray-900 ring-1 ring-gray-200 dark:ring-gray-800 rounded-2xl overflow-hidden shadow-sm">
|
||||
<div className="px-5 py-4 border-b border-gray-200 dark:border-gray-800">
|
||||
<h3 className="text-base font-semibold text-gray-900 dark:text-gray-100">
|
||||
لیست تبلیغات
|
||||
</h3>
|
||||
</div>
|
||||
<ul className="divide-y divide-gray-200 dark:divide-gray-800">
|
||||
{sortedPromotions.map((promotion) => (
|
||||
<li key={promotion.id} className="px-5 py-4 hover:bg-gray-50 dark:hover:bg-gray-800/40 transition-colors">
|
||||
<div className="flex items-start gap-4">
|
||||
{promotion.image_url && !imageErrors[promotion.id] && (
|
||||
<div className="flex-shrink-0">
|
||||
<div className="relative h-16 w-16 rounded-xl overflow-hidden ring-1 ring-gray-200 dark:ring-gray-800">
|
||||
<Image
|
||||
src={promotion.image_url}
|
||||
alt={promotion.title || 'Promotion'}
|
||||
fill
|
||||
className="object-cover"
|
||||
onError={() => handleImageError(promotion.id)}
|
||||
unoptimized
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
<p className="text-sm font-semibold text-indigo-600 dark:text-indigo-400">
|
||||
{promotion.title || 'بدون عنوان'}
|
||||
</p>
|
||||
<span className="px-2 py-0.5 text-xs font-semibold rounded-lg bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-300">
|
||||
{getPromotionTypeLabel(promotion.type)}
|
||||
</span>
|
||||
{promotion.is_active ? (
|
||||
<span className="inline-flex items-center gap-1 px-2 py-0.5 text-xs font-semibold rounded-lg bg-green-50 text-green-700 dark:bg-green-500/10 dark:text-green-400">
|
||||
<span className="h-1.5 w-1.5 rounded-full bg-green-500" />
|
||||
فعال
|
||||
</span>
|
||||
) : (
|
||||
<span className="inline-flex items-center gap-1 px-2 py-0.5 text-xs font-semibold rounded-lg bg-gray-100 text-gray-600 dark:bg-gray-800 dark:text-gray-400">
|
||||
<span className="h-1.5 w-1.5 rounded-full bg-gray-400" />
|
||||
غیرفعال
|
||||
</span>
|
||||
)}
|
||||
{promotion.priority && (
|
||||
<span className="px-2 py-0.5 text-xs font-medium rounded-lg bg-purple-100 text-purple-700 dark:bg-purple-900/30 dark:text-purple-300">
|
||||
اولویت: {promotion.priority}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{promotion.subtitle && (
|
||||
<p className="mt-1 text-sm text-gray-600 dark:text-gray-400">{promotion.subtitle}</p>
|
||||
)}
|
||||
|
||||
<div className="mt-2 flex flex-wrap gap-x-5 gap-y-1 text-xs text-gray-500 dark:text-gray-400">
|
||||
{promotion.action_text && <span>دکمه: {promotion.action_text}</span>}
|
||||
{promotion.start_at && <span>شروع: {formatDate(promotion.start_at)}</span>}
|
||||
{promotion.end_at && <span>پایان: {formatDate(promotion.end_at)}</span>}
|
||||
</div>
|
||||
|
||||
<div className="mt-1.5 flex flex-wrap gap-1.5">
|
||||
{promotion.url_site && (
|
||||
<span className="px-2 py-0.5 text-xs bg-gray-100 dark:bg-gray-800 text-gray-600 dark:text-gray-400 rounded-md">وبسایت</span>
|
||||
)}
|
||||
{promotion.url_myket && (
|
||||
<span className="px-2 py-0.5 text-xs bg-gray-100 dark:bg-gray-800 text-gray-600 dark:text-gray-400 rounded-md">مایکت</span>
|
||||
)}
|
||||
{promotion.url_bazzar && (
|
||||
<span className="px-2 py-0.5 text-xs bg-gray-100 dark:bg-gray-800 text-gray-600 dark:text-gray-400 rounded-md">بازار</span>
|
||||
)}
|
||||
{promotion.url_google_play && (
|
||||
<span className="px-2 py-0.5 text-xs bg-gray-100 dark:bg-gray-800 text-gray-600 dark:text-gray-400 rounded-md">گوگلپلی</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-1 flex-shrink-0">
|
||||
<button
|
||||
onClick={() => onToggleActive(promotion)}
|
||||
className={`p-2 rounded-lg transition-colors ${
|
||||
promotion.is_active
|
||||
? 'text-green-600 dark:text-green-400 hover:bg-green-50 dark:hover:bg-green-500/10'
|
||||
: 'text-gray-400 dark:text-gray-500 hover:bg-gray-100 dark:hover:bg-gray-800'
|
||||
}`}
|
||||
title={promotion.is_active ? 'غیرفعال کردن' : 'فعال کردن'}
|
||||
>
|
||||
{promotion.is_active ? <EyeIcon className="h-4 w-4" /> : <EyeSlashIcon className="h-4 w-4" />}
|
||||
</button>
|
||||
<button
|
||||
onClick={() => onEdit(promotion)}
|
||||
className="p-2 rounded-lg text-indigo-600 dark:text-indigo-400 hover:bg-indigo-50 dark:hover:bg-indigo-500/10 transition-colors"
|
||||
>
|
||||
<PencilIcon className="h-4 w-4" />
|
||||
</button>
|
||||
<button
|
||||
onClick={() => onDelete(promotion)}
|
||||
className="p-2 rounded-lg text-red-600 dark:text-red-400 hover:bg-red-50 dark:hover:bg-red-500/10 transition-colors"
|
||||
>
|
||||
<TrashIcon className="h-4 w-4" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
'use client';
|
||||
|
||||
import { ReferralRewardUser } from '@/types/referral';
|
||||
import { GiftIcon, EnvelopeIcon, PhoneIcon, TicketIcon, UserIcon } from '@heroicons/react/24/outline';
|
||||
|
||||
interface ReferralListProps {
|
||||
users: ReferralRewardUser[];
|
||||
subscriptionTarget: number;
|
||||
onFulfill: (user: ReferralRewardUser) => void;
|
||||
isLoading: boolean;
|
||||
fulfillingId: number | null;
|
||||
}
|
||||
|
||||
export default function ReferralList({
|
||||
users,
|
||||
subscriptionTarget,
|
||||
onFulfill,
|
||||
isLoading,
|
||||
fulfillingId
|
||||
}: ReferralListProps) {
|
||||
if (users.length === 0) {
|
||||
return (
|
||||
<div className="text-center py-16 bg-white dark:bg-gray-900 rounded-2xl ring-1 ring-gray-200 dark:ring-gray-800 shadow-sm">
|
||||
<div className="mx-auto h-12 w-12 rounded-xl bg-gray-100 dark:bg-gray-800 flex items-center justify-center mb-3">
|
||||
<GiftIcon className="h-6 w-6 text-gray-400" />
|
||||
</div>
|
||||
<p className="text-gray-500 dark:text-gray-400 text-sm">
|
||||
در حال حاضر هیچ کاربری واجد شرایط نیست
|
||||
</p>
|
||||
<p className="text-xs text-gray-400 dark:text-gray-500 mt-1">
|
||||
کاربران پس از {subscriptionTarget} دعوت موفق در این لیست نمایش داده میشوند
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="bg-white dark:bg-gray-900 ring-1 ring-gray-200 dark:ring-gray-800 rounded-2xl overflow-hidden shadow-sm">
|
||||
<div className="px-5 py-4 border-b border-gray-200 dark:border-gray-800 flex items-center justify-between">
|
||||
<h3 className="text-base font-semibold text-gray-900 dark:text-gray-100">
|
||||
کاربران واجد شرایط
|
||||
</h3>
|
||||
<span className="px-3 py-1 text-xs font-semibold rounded-lg bg-indigo-100 text-indigo-700 dark:bg-indigo-500/15 dark:text-indigo-400">
|
||||
هدف: {subscriptionTarget} دعوت
|
||||
</span>
|
||||
</div>
|
||||
<ul className="divide-y divide-gray-200 dark:divide-gray-800">
|
||||
{users.map((user) => (
|
||||
<li key={user.id} className="px-5 py-4 hover:bg-gray-50 dark:hover:bg-gray-800/40 transition-colors">
|
||||
<div className="flex items-start justify-between gap-4 flex-wrap">
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
<div className="h-8 w-8 rounded-lg bg-indigo-100 dark:bg-indigo-500/10 flex items-center justify-center flex-shrink-0">
|
||||
<UserIcon className="h-4 w-4 text-indigo-600 dark:text-indigo-400" />
|
||||
</div>
|
||||
<p className="text-sm font-semibold text-gray-900 dark:text-gray-100">
|
||||
{user.name || 'بدون نام'}
|
||||
</p>
|
||||
<span className="inline-flex items-center gap-1 px-2 py-0.5 text-xs font-semibold rounded-lg bg-green-50 text-green-700 dark:bg-green-500/10 dark:text-green-400">
|
||||
<span className="h-1.5 w-1.5 rounded-full bg-green-500" />
|
||||
{user.successful_invites} دعوت موفق
|
||||
</span>
|
||||
</div>
|
||||
<div className="mt-2 flex flex-wrap gap-x-5 gap-y-1 text-xs text-gray-500 dark:text-gray-400">
|
||||
{user.email && (
|
||||
<span className="flex items-center gap-1" dir="ltr">
|
||||
<EnvelopeIcon className="h-3.5 w-3.5" />
|
||||
{user.email}
|
||||
</span>
|
||||
)}
|
||||
{user.mobile && (
|
||||
<span className="flex items-center gap-1" dir="ltr">
|
||||
<PhoneIcon className="h-3.5 w-3.5" />
|
||||
{user.mobile}
|
||||
</span>
|
||||
)}
|
||||
{user.referral_code && (
|
||||
<span className="flex items-center gap-1">
|
||||
<TicketIcon className="h-3.5 w-3.5" />
|
||||
{user.referral_code}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
onClick={() => onFulfill(user)}
|
||||
disabled={isLoading}
|
||||
className="flex-shrink-0 inline-flex items-center gap-2 px-4 py-2 bg-green-600 text-white rounded-xl text-sm font-medium hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500 dark:focus:ring-offset-gray-900 disabled:opacity-50 disabled:cursor-not-allowed transition-colors shadow-sm shadow-green-500/20"
|
||||
>
|
||||
<GiftIcon className="h-4 w-4" />
|
||||
{fulfillingId === user.id ? 'در حال اعطا...' : 'اعطای اشتراک'}
|
||||
</button>
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useEffect } from 'react';
|
||||
import { Reminder, CreateReminderData, UpdateReminderData, REMINDER_TYPES } from '@/types/reminder';
|
||||
|
||||
interface ReminderFormProps {
|
||||
reminder?: Reminder | null;
|
||||
packageName: string;
|
||||
onSubmit: (data: CreateReminderData | UpdateReminderData) => Promise<void>;
|
||||
onCancel: () => void;
|
||||
isLoading: boolean;
|
||||
}
|
||||
|
||||
export default function ReminderForm({ reminder, packageName, onSubmit, onCancel, isLoading }: ReminderFormProps) {
|
||||
const [formData, setFormData] = useState<CreateReminderData | UpdateReminderData>({
|
||||
title: '',
|
||||
description: '',
|
||||
time: '',
|
||||
repeatable: false,
|
||||
repeat_days: null,
|
||||
type: 'reminder',
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (reminder) {
|
||||
const formattedTime = reminder.time ? reminder.time.replace(/\.\d+/, '').slice(0, 16) : '';
|
||||
setFormData({
|
||||
title: reminder.title || '',
|
||||
description: reminder.description || '',
|
||||
time: formattedTime,
|
||||
repeatable: reminder.repeatable || false,
|
||||
repeat_days: reminder.repeat_days,
|
||||
type: reminder.type || 'reminder',
|
||||
});
|
||||
} else {
|
||||
const defaultTime = new Date();
|
||||
defaultTime.setHours(defaultTime.getHours() + 1);
|
||||
const year = defaultTime.getFullYear();
|
||||
const month = String(defaultTime.getMonth() + 1).padStart(2, '0');
|
||||
const day = String(defaultTime.getDate()).padStart(2, '0');
|
||||
const hours = String(defaultTime.getHours()).padStart(2, '0');
|
||||
const minutes = String(defaultTime.getMinutes()).padStart(2, '0');
|
||||
setFormData({
|
||||
title: '',
|
||||
description: '',
|
||||
time: `${year}-${month}-${day}T${hours}:${minutes}`,
|
||||
repeatable: false,
|
||||
repeat_days: null,
|
||||
type: 'reminder',
|
||||
});
|
||||
}
|
||||
}, [reminder]);
|
||||
|
||||
const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) => {
|
||||
const { name, value, type } = e.target;
|
||||
if (type === 'checkbox') {
|
||||
const checked = (e.target as HTMLInputElement).checked;
|
||||
setFormData(prev => ({ ...prev, [name]: checked }));
|
||||
} else {
|
||||
setFormData(prev => ({ ...prev, [name]: value }));
|
||||
}
|
||||
};
|
||||
|
||||
const handleNumberChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const { name, value } = e.target;
|
||||
setFormData(prev => ({ ...prev, [name]: value ? parseInt(value, 10) : null }));
|
||||
};
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
let formattedTime = '';
|
||||
if (formData.time) {
|
||||
formattedTime = formData.time.replace('T', ' ') + ':00.000';
|
||||
}
|
||||
await onSubmit({ ...formData, time: formattedTime });
|
||||
};
|
||||
|
||||
const inputClass = 'block w-full px-4 py-2.5 text-sm text-gray-900 dark:text-gray-100 border border-gray-200 dark:border-gray-700 rounded-xl bg-gray-50 dark:bg-gray-800/60 placeholder-gray-400 dark:placeholder-gray-500 focus:ring-2 focus:ring-indigo-500/20 focus:border-indigo-500 dark:focus:border-indigo-400 transition-colors';
|
||||
const labelClass = 'block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5';
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit} className="space-y-6 bg-white dark:bg-gray-900 p-6 rounded-2xl ring-1 ring-gray-200 dark:ring-gray-800 shadow-sm">
|
||||
<div className="pb-4 border-b border-gray-100 dark:border-gray-800">
|
||||
<h3 className="text-lg font-semibold text-gray-900 dark:text-gray-100">
|
||||
{reminder ? 'ویرایش یادآوری' : 'ایجاد یادآوری جدید'} برای پکیج {packageName}
|
||||
</h3>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 gap-5 md:grid-cols-2">
|
||||
<div className="md:col-span-2">
|
||||
<label htmlFor="title" className={labelClass}>عنوان <span className="text-red-500">*</span></label>
|
||||
<input type="text" id="title" name="title" required value={formData.title || ''} onChange={handleInputChange} className={inputClass} placeholder="مثال: یادآوری روزانه" />
|
||||
</div>
|
||||
<div>
|
||||
<label htmlFor="type" className={labelClass}>نوع <span className="text-red-500">*</span></label>
|
||||
<select id="type" name="type" required value={formData.type || 'reminder'} onChange={handleInputChange} className={inputClass}>
|
||||
{Object.entries(REMINDER_TYPES).map(([value, label]) => (
|
||||
<option key={value} value={value}>{label}</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label htmlFor="time" className={labelClass}>زمان <span className="text-red-500">*</span></label>
|
||||
<input type="datetime-local" id="time" name="time" required value={formData.time || ''} onChange={handleInputChange} className={inputClass} />
|
||||
</div>
|
||||
<div>
|
||||
<label className={`${labelClass} invisible`}>تکرار</label>
|
||||
<label className="flex items-center gap-3 p-3 rounded-xl bg-gray-50 dark:bg-gray-800/60 hover:bg-gray-100 dark:hover:bg-gray-800 transition-colors cursor-pointer">
|
||||
<input type="checkbox" id="repeatable" name="repeatable" checked={formData.repeatable || false} onChange={handleInputChange} className="h-4 w-4 text-indigo-600 border-gray-300 dark:border-gray-600 dark:bg-gray-800 rounded-lg focus:ring-indigo-500" />
|
||||
<span className="text-sm font-medium text-gray-700 dark:text-gray-300">قابل تکرار</span>
|
||||
</label>
|
||||
</div>
|
||||
{formData.repeatable && (
|
||||
<div>
|
||||
<label htmlFor="repeat_days" className={labelClass}>فاصله تکرار (روز)</label>
|
||||
<input type="number" id="repeat_days" name="repeat_days" min="1" value={formData.repeat_days || ''} onChange={handleNumberChange} className={inputClass} placeholder="مثال: 7" />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="pt-2 border-t border-gray-100 dark:border-gray-800">
|
||||
<label htmlFor="description" className={labelClass}>توضیحات</label>
|
||||
<textarea id="description" name="description" rows={3} value={formData.description || ''} onChange={handleInputChange} className={inputClass} placeholder="توضیحات یادآوری را وارد کنید..." />
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end gap-3 pt-4 border-t border-gray-100 dark:border-gray-800">
|
||||
<button type="button" onClick={onCancel} className="px-5 py-2.5 rounded-xl border border-gray-200 dark:border-gray-700 text-sm font-medium text-gray-700 dark:text-gray-200 bg-white dark:bg-gray-800 hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors">
|
||||
انصراف
|
||||
</button>
|
||||
<button type="submit" disabled={isLoading} className="px-5 py-2.5 rounded-xl bg-indigo-600 text-white text-sm font-medium hover:bg-indigo-700 focus:ring-2 focus:ring-indigo-500/30 disabled:opacity-50 transition-colors shadow-sm shadow-indigo-500/20">
|
||||
{isLoading ? 'در حال ذخیره...' : reminder ? 'بهروزرسانی' : 'ایجاد'}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
'use client';
|
||||
|
||||
import { Reminder } from '@/types/reminder';
|
||||
import { getReminderTypeLabel } from '@/types/reminder';
|
||||
import { PencilIcon, TrashIcon, BellIcon, SparklesIcon } from '@heroicons/react/24/outline';
|
||||
import { formatDate, formatTime } from '@/lib/utils';
|
||||
|
||||
interface ReminderListProps {
|
||||
reminders: Reminder[];
|
||||
packageName: string;
|
||||
onEdit: (reminder: Reminder) => void;
|
||||
onDelete: (reminder: Reminder) => void;
|
||||
isLoading: boolean;
|
||||
}
|
||||
|
||||
export default function ReminderList({ reminders, packageName, onEdit, onDelete, isLoading }: ReminderListProps) {
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="flex justify-center items-center py-16">
|
||||
<div className="h-10 w-10 border-4 border-indigo-200 dark:border-indigo-800 border-t-indigo-600 rounded-full animate-spin" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (!reminders || reminders.length === 0) {
|
||||
return (
|
||||
<div className="text-center py-16 bg-white dark:bg-gray-900 rounded-2xl ring-1 ring-gray-200 dark:ring-gray-800 shadow-sm">
|
||||
<div className="mx-auto h-12 w-12 rounded-xl bg-gray-100 dark:bg-gray-800 flex items-center justify-center mb-3">
|
||||
<BellIcon className="h-6 w-6 text-gray-400" />
|
||||
</div>
|
||||
<p className="text-gray-500 dark:text-gray-400 text-sm">هیچ یادآوری برای پکیج {packageName} یافت نشد</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const sortedReminders = [...reminders].sort((a, b) =>
|
||||
new Date(a.time).getTime() - new Date(b.time).getTime()
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="bg-white dark:bg-gray-900 ring-1 ring-gray-200 dark:ring-gray-800 rounded-2xl overflow-hidden shadow-sm">
|
||||
<div className="px-5 py-4 border-b border-gray-200 dark:border-gray-800">
|
||||
<h3 className="text-base font-semibold text-gray-900 dark:text-gray-100">
|
||||
یادآوریهای پکیج {packageName}
|
||||
</h3>
|
||||
</div>
|
||||
<ul className="divide-y divide-gray-200 dark:divide-gray-800">
|
||||
{sortedReminders.map((reminder) => (
|
||||
<li key={reminder.id} className="px-5 py-4 hover:bg-gray-50 dark:hover:bg-gray-800/40 transition-colors">
|
||||
<div className="flex items-start justify-between gap-4">
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-center gap-2">
|
||||
<div className={`h-8 w-8 rounded-lg flex items-center justify-center flex-shrink-0 ${
|
||||
reminder.type === 'motivate'
|
||||
? 'bg-yellow-100 dark:bg-yellow-500/10'
|
||||
: 'bg-indigo-100 dark:bg-indigo-500/10'
|
||||
}`}>
|
||||
{reminder.type === 'motivate' ? (
|
||||
<SparklesIcon className="h-4 w-4 text-yellow-600 dark:text-yellow-400" />
|
||||
) : (
|
||||
<BellIcon className="h-4 w-4 text-indigo-600 dark:text-indigo-400" />
|
||||
)}
|
||||
</div>
|
||||
<p className="text-sm font-semibold text-gray-900 dark:text-gray-100">
|
||||
{reminder.title}
|
||||
</p>
|
||||
<span className="px-2 py-0.5 text-xs font-semibold rounded-lg bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-300">
|
||||
{getReminderTypeLabel(reminder.type)}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{reminder.description && (
|
||||
<p className="mt-2 text-sm text-gray-600 dark:text-gray-400 line-clamp-2">
|
||||
{reminder.description}
|
||||
</p>
|
||||
)}
|
||||
|
||||
<div className="mt-2 flex flex-wrap gap-x-5 gap-y-1 text-xs text-gray-500 dark:text-gray-400">
|
||||
<span>زمان: {formatDate(reminder.time)} {formatTime(reminder.time)}</span>
|
||||
<span>تکرار: {reminder.repeatable ? 'فعال' : 'غیرفعال'}</span>
|
||||
{reminder.repeatable && reminder.repeat_days && (
|
||||
<span>هر {reminder.repeat_days} روز</span>
|
||||
)}
|
||||
</div>
|
||||
<p className="mt-2 text-xs text-gray-400 dark:text-gray-500">
|
||||
{formatDate(reminder.updated_at)}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-1 flex-shrink-0">
|
||||
<button
|
||||
onClick={() => onEdit(reminder)}
|
||||
className="p-2 rounded-lg text-indigo-600 dark:text-indigo-400 hover:bg-indigo-50 dark:hover:bg-indigo-500/10 transition-colors"
|
||||
>
|
||||
<PencilIcon className="h-4 w-4" />
|
||||
</button>
|
||||
<button
|
||||
onClick={() => onDelete(reminder)}
|
||||
className="p-2 rounded-lg text-red-600 dark:text-red-400 hover:bg-red-50 dark:hover:bg-red-500/10 transition-colors"
|
||||
>
|
||||
<TrashIcon className="h-4 w-4" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
'use client';
|
||||
|
||||
import { PackageName } from '@/types/package';
|
||||
import { useState, useEffect } from 'react';
|
||||
import { packagesApi } from '@/lib/api/packages';
|
||||
import { CubeIcon } from '@heroicons/react/24/outline';
|
||||
|
||||
interface PackageSelectorProps {
|
||||
token: string;
|
||||
selectedPackage: string | null;
|
||||
onPackageChange: (packageName: string) => void;
|
||||
isLoading?: boolean;
|
||||
}
|
||||
|
||||
export default function PackageSelector({ token, selectedPackage, onPackageChange, isLoading }: PackageSelectorProps) {
|
||||
const [packages, setPackages] = useState<PackageName[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
loadPackages();
|
||||
}, [token]);
|
||||
|
||||
const loadPackages = async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const data = await packagesApi.getAllPackages(token);
|
||||
setPackages(data);
|
||||
|
||||
if (data.length > 0 && !selectedPackage) {
|
||||
onPackageChange(data[0].name!);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to load packages:', error);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="bg-white dark:bg-gray-900 p-4 rounded-2xl ring-1 ring-gray-200 dark:ring-gray-800 shadow-sm mb-6">
|
||||
<div className="animate-pulse flex items-center gap-3">
|
||||
<div className="h-10 w-10 bg-gray-200 dark:bg-gray-800 rounded-xl" />
|
||||
<div className="flex-1">
|
||||
<div className="h-3 w-24 bg-gray-200 dark:bg-gray-800 rounded mb-2" />
|
||||
<div className="h-4 w-48 bg-gray-200 dark:bg-gray-800 rounded" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="mb-6">
|
||||
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
|
||||
پکیج را انتخاب کنید
|
||||
</label>
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3">
|
||||
{packages.map((pkg) => {
|
||||
const isSelected = selectedPackage === pkg.name;
|
||||
return (
|
||||
<button
|
||||
key={pkg.id}
|
||||
onClick={() => onPackageChange(pkg.name!)}
|
||||
disabled={isLoading}
|
||||
className={`flex items-center gap-3 p-4 rounded-2xl text-right transition-all duration-150 ${
|
||||
isSelected
|
||||
? 'bg-indigo-50 dark:bg-indigo-500/10 ring-2 ring-indigo-600 dark:ring-indigo-400 shadow-sm'
|
||||
: 'bg-white dark:bg-gray-900 ring-1 ring-gray-200 dark:ring-gray-800 hover:ring-gray-300 dark:hover:ring-gray-700 hover:shadow-sm'
|
||||
} disabled:opacity-50`}
|
||||
>
|
||||
{pkg.image && typeof pkg.image === 'string' ? (
|
||||
<img src={pkg.image} alt={pkg.title || ''} className="h-10 w-10 rounded-xl object-cover flex-shrink-0" />
|
||||
) : (
|
||||
<div className={`h-10 w-10 rounded-xl flex items-center justify-center flex-shrink-0 ${
|
||||
isSelected
|
||||
? 'bg-indigo-100 dark:bg-indigo-500/15'
|
||||
: 'bg-gray-100 dark:bg-gray-800'
|
||||
}`}>
|
||||
<CubeIcon className={`h-5 w-5 ${isSelected ? 'text-indigo-600 dark:text-indigo-400' : 'text-gray-400 dark:text-gray-500'}`} />
|
||||
</div>
|
||||
)}
|
||||
<div className="min-w-0">
|
||||
<p className={`text-sm font-semibold truncate ${
|
||||
isSelected ? 'text-indigo-700 dark:text-indigo-400' : 'text-gray-900 dark:text-gray-100'
|
||||
}`}>
|
||||
{pkg.title || 'بدون عنوان'}
|
||||
</p>
|
||||
<p className="text-xs text-gray-500 dark:text-gray-400 truncate" dir="ltr">
|
||||
{pkg.name}
|
||||
</p>
|
||||
</div>
|
||||
{isSelected && (
|
||||
<div className="mr-auto flex-shrink-0">
|
||||
<div className="h-5 w-5 rounded-full bg-indigo-600 dark:bg-indigo-400 flex items-center justify-center">
|
||||
<svg className="h-3 w-3 text-white" fill="none" viewBox="0 0 24 24" strokeWidth={3} stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" d="m4.5 12.75 6 6 9-13.5" />
|
||||
</svg>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
import { User, UpdateUserProfileData } from '@/types/user';
|
||||
import { XMarkIcon } from '@heroicons/react/24/outline';
|
||||
|
||||
interface UserEditFormProps {
|
||||
user: User;
|
||||
onSubmit: (data: UpdateUserProfileData) => void;
|
||||
onCancel: () => void;
|
||||
isLoading: boolean;
|
||||
}
|
||||
|
||||
export default function UserEditForm({ user, onSubmit, onCancel, isLoading }: UserEditFormProps) {
|
||||
const [formData, setFormData] = useState<UpdateUserProfileData>({
|
||||
first_name: user.first_name || '',
|
||||
last_name: user.last_name || '',
|
||||
email: user.email || '',
|
||||
mobile: user.mobile || '',
|
||||
avatar: null,
|
||||
});
|
||||
|
||||
const handleSubmit = (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
const payload: UpdateUserProfileData = {};
|
||||
if (formData.first_name !== (user.first_name || '')) payload.first_name = formData.first_name;
|
||||
if (formData.last_name !== (user.last_name || '')) payload.last_name = formData.last_name;
|
||||
if (formData.email !== (user.email || '')) payload.email = formData.email;
|
||||
if (formData.mobile !== (user.mobile || '')) payload.mobile = formData.mobile;
|
||||
if (formData.avatar) payload.avatar = formData.avatar;
|
||||
onSubmit(payload);
|
||||
};
|
||||
|
||||
const inputClass = 'block w-full px-4 py-2.5 text-sm text-gray-900 dark:text-gray-100 border border-gray-200 dark:border-gray-700 rounded-xl bg-gray-50 dark:bg-gray-800/60 placeholder-gray-400 dark:placeholder-gray-500 focus:ring-2 focus:ring-indigo-500/20 focus:border-indigo-500 dark:focus:border-indigo-400 transition-colors';
|
||||
const labelClass = 'block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5';
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 dark:bg-black/60 p-4">
|
||||
<div className="bg-white dark:bg-gray-900 rounded-2xl shadow-xl ring-1 ring-gray-200 dark:ring-gray-800 w-full max-w-lg" dir="rtl">
|
||||
<div className="flex items-center justify-between px-6 py-4 border-b border-gray-200 dark:border-gray-800">
|
||||
<h3 className="text-lg font-semibold text-gray-900 dark:text-gray-100">ویرایش اطلاعات کاربر</h3>
|
||||
<button onClick={onCancel} className="p-2 rounded-lg text-gray-400 hover:text-gray-600 dark:text-gray-500 dark:hover:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-800 transition-colors" type="button">
|
||||
<XMarkIcon className="h-5 w-5" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<form onSubmit={handleSubmit} className="px-6 py-5 space-y-4">
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
|
||||
<div>
|
||||
<label className={labelClass}>نام</label>
|
||||
<input type="text" className={inputClass} value={formData.first_name || ''} onChange={(e) => setFormData({ ...formData, first_name: e.target.value })} />
|
||||
</div>
|
||||
<div>
|
||||
<label className={labelClass}>نام خانوادگی</label>
|
||||
<input type="text" className={inputClass} value={formData.last_name || ''} onChange={(e) => setFormData({ ...formData, last_name: e.target.value })} />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className={labelClass}>ایمیل</label>
|
||||
<input type="email" dir="ltr" className={inputClass} value={formData.email || ''} onChange={(e) => setFormData({ ...formData, email: e.target.value })} />
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className={labelClass}>شماره موبایل</label>
|
||||
<input type="text" dir="ltr" placeholder="09xxxxxxxxx" className={inputClass} value={formData.mobile || ''} onChange={(e) => setFormData({ ...formData, mobile: e.target.value })} />
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className={labelClass}>آواتار</label>
|
||||
<input
|
||||
type="file"
|
||||
accept="image/*"
|
||||
className="block w-full text-sm text-gray-600 dark:text-gray-400 file:ml-0 file:py-2 file:px-4 file:rounded-xl file:border-0 file:text-sm file:font-medium file:bg-indigo-50 file:text-indigo-700 hover:file:bg-indigo-100 dark:file:bg-indigo-500/10 dark:file:text-indigo-400 dark:hover:file:bg-indigo-500/15 transition-colors"
|
||||
onChange={(e) => setFormData({ ...formData, avatar: e.target.files?.[0] || null })}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end gap-3 pt-3 border-t border-gray-100 dark:border-gray-800">
|
||||
<button type="button" onClick={onCancel} disabled={isLoading} className="px-5 py-2.5 rounded-xl border border-gray-200 dark:border-gray-700 text-sm font-medium text-gray-700 dark:text-gray-200 bg-white dark:bg-gray-800 hover:bg-gray-50 dark:hover:bg-gray-700 disabled:opacity-50 transition-colors">
|
||||
انصراف
|
||||
</button>
|
||||
<button type="submit" disabled={isLoading} className="px-5 py-2.5 rounded-xl bg-indigo-600 text-white text-sm font-medium hover:bg-indigo-700 focus:ring-2 focus:ring-indigo-500/30 disabled:opacity-50 transition-colors shadow-sm shadow-indigo-500/20">
|
||||
{isLoading ? 'در حال ذخیره...' : 'ذخیره تغییرات'}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
'use client';
|
||||
|
||||
import { User } from '@/types/user';
|
||||
import { formatDate, formatPrice, getFullName, getEmail, getMobile } from '@/lib/utils';
|
||||
import { CalendarIcon, EnvelopeIcon, PhoneIcon, WalletIcon, UserIcon } from '@heroicons/react/24/outline';
|
||||
|
||||
interface UserInfoProps {
|
||||
user: User;
|
||||
}
|
||||
|
||||
export default function UserInfo({ user }: UserInfoProps) {
|
||||
const fullName = getFullName(user);
|
||||
const initials = fullName
|
||||
.split(' ')
|
||||
.map((w) => w[0])
|
||||
.slice(0, 2)
|
||||
.join('')
|
||||
.toUpperCase();
|
||||
|
||||
const stats = [
|
||||
{
|
||||
label: 'کیف پول',
|
||||
value: `${formatPrice(user.wallet)} تومان`,
|
||||
icon: WalletIcon,
|
||||
color: 'bg-emerald-50 dark:bg-emerald-500/10 text-emerald-600 dark:text-emerald-400',
|
||||
},
|
||||
{
|
||||
label: 'عضویت',
|
||||
value: formatDate(user.created_at),
|
||||
icon: CalendarIcon,
|
||||
color: 'bg-blue-50 dark:bg-blue-500/10 text-blue-600 dark:text-blue-400',
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<div className="bg-white dark:bg-gray-900 rounded-2xl ring-1 ring-gray-200 dark:ring-gray-800 shadow-sm overflow-hidden mb-6">
|
||||
{/* Profile Header */}
|
||||
<div className="bg-gradient-to-l from-indigo-600 to-indigo-700 px-6 py-5">
|
||||
<div className="flex items-center gap-4">
|
||||
<div className="h-14 w-14 rounded-2xl bg-white/20 backdrop-blur-sm flex items-center justify-center text-white font-bold text-lg flex-shrink-0">
|
||||
{initials || <UserIcon className="h-6 w-6" />}
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
<h3 className="text-lg font-bold text-white truncate">
|
||||
{fullName || 'کاربر بدون نام'}
|
||||
</h3>
|
||||
<div className="flex items-center gap-3 mt-1">
|
||||
{user.email && (
|
||||
<span className="text-sm text-indigo-100 flex items-center gap-1" dir="ltr">
|
||||
<EnvelopeIcon className="h-3.5 w-3.5" />
|
||||
{user.email}
|
||||
</span>
|
||||
)}
|
||||
{user.mobile && (
|
||||
<span className="text-sm text-indigo-100 flex items-center gap-1" dir="ltr">
|
||||
<PhoneIcon className="h-3.5 w-3.5" />
|
||||
{user.mobile}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Stats Row */}
|
||||
<div className="grid grid-cols-2 divide-x divide-gray-200 dark:divide-gray-800 border-b border-gray-200 dark:border-gray-800">
|
||||
{stats.map((stat) => (
|
||||
<div key={stat.label} className="px-5 py-4">
|
||||
<div className="flex items-center gap-2 mb-1">
|
||||
<div className={`h-7 w-7 rounded-lg flex items-center justify-center ${stat.color}`}>
|
||||
<stat.icon className="h-3.5 w-3.5" />
|
||||
</div>
|
||||
<span className="text-xs text-gray-500 dark:text-gray-400">{stat.label}</span>
|
||||
</div>
|
||||
<p className="text-sm font-semibold text-gray-900 dark:text-gray-100" dir="ltr">{stat.value}</p>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Details Grid */}
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-px bg-gray-200 dark:bg-gray-800">
|
||||
<InfoRow icon={UserIcon} label="نام کامل" value={getFullName(user)} />
|
||||
<InfoRow icon={EnvelopeIcon} label="ایمیل" value={getEmail(user.email)} dir="ltr" />
|
||||
<InfoRow icon={PhoneIcon} label="شماره موبایل" value={getMobile(user.mobile)} dir="ltr" />
|
||||
<InfoRow icon={WalletIcon} label="موجودی کیف پول" value={`${formatPrice(user.wallet)} تومان`} />
|
||||
{user.birthday && (
|
||||
<InfoRow icon={CalendarIcon} label="تاریخ تولد" value={formatDate(user.birthday)} />
|
||||
)}
|
||||
{user.gender && (
|
||||
<InfoRow
|
||||
icon={UserIcon}
|
||||
label="جنسیت"
|
||||
value={user.gender === 'male' ? 'مرد' : user.gender === 'female' ? 'زن' : user.gender}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function InfoRow({ icon: Icon, label, value, dir }: { icon: React.ElementType; label: string; value: string; dir?: string }) {
|
||||
return (
|
||||
<div className="bg-white dark:bg-gray-900 px-5 py-3.5 flex items-center gap-3">
|
||||
<div className="h-7 w-7 rounded-lg bg-gray-100 dark:bg-gray-800 flex items-center justify-center flex-shrink-0">
|
||||
<Icon className="h-3.5 w-3.5 text-gray-400 dark:text-gray-500" />
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
<p className="text-xs text-gray-500 dark:text-gray-400">{label}</p>
|
||||
<p className="text-sm font-medium text-gray-900 dark:text-gray-100 truncate" dir={dir}>{value}</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
'use client';
|
||||
|
||||
import { UserProduct } from '@/types/user';
|
||||
import { formatDate, formatPrice, getProductTypeLabel } from '@/lib/utils';
|
||||
import { CheckCircleIcon, XCircleIcon, PlusCircleIcon } from '@heroicons/react/24/outline';
|
||||
import { useState } from 'react';
|
||||
|
||||
interface UserProductsProps {
|
||||
products: UserProduct[];
|
||||
onSubscribe: (productId: number) => void;
|
||||
onUnsubscribe: (productId: number) => void;
|
||||
isLoading: boolean;
|
||||
availableProducts: { id: number; title: string | null; packageName?: string }[];
|
||||
selectedPackage?: string | null;
|
||||
}
|
||||
|
||||
export default function UserProducts({
|
||||
products,
|
||||
onSubscribe,
|
||||
onUnsubscribe,
|
||||
isLoading,
|
||||
availableProducts,
|
||||
selectedPackage
|
||||
}: UserProductsProps) {
|
||||
const [selectedProductId, setSelectedProductId] = useState<number | null>(null);
|
||||
|
||||
const getSubscriptionStatus = (product: UserProduct) => {
|
||||
if (!product.pivot?.expire_at) {
|
||||
return {
|
||||
isActive: false,
|
||||
text: 'نامشخص',
|
||||
color: 'bg-gray-100 dark:bg-gray-800 text-gray-600 dark:text-gray-400',
|
||||
dotColor: 'bg-gray-400',
|
||||
};
|
||||
}
|
||||
|
||||
const expireDate = new Date(product.pivot.expire_at);
|
||||
const now = new Date();
|
||||
const isActive = expireDate > now;
|
||||
|
||||
return {
|
||||
isActive,
|
||||
text: isActive ? 'فعال' : 'منقضی شده',
|
||||
color: isActive
|
||||
? 'bg-green-50 dark:bg-green-500/10 text-green-700 dark:text-green-400'
|
||||
: 'bg-red-50 dark:bg-red-500/10 text-red-700 dark:text-red-400',
|
||||
dotColor: isActive ? 'bg-green-500' : 'bg-red-500',
|
||||
};
|
||||
};
|
||||
|
||||
const getSubscriptionCount = (productId: number): number => {
|
||||
return products.filter(p => p.id === productId).length;
|
||||
};
|
||||
|
||||
const productsByPackage = products.reduce((acc, product) => {
|
||||
const packageName = product.package_name?.name || 'نامشخص';
|
||||
if (!acc[packageName]) {
|
||||
acc[packageName] = [];
|
||||
}
|
||||
acc[packageName].push(product);
|
||||
return acc;
|
||||
}, {} as Record<string, UserProduct[]>);
|
||||
|
||||
const handleSubscribeClick = (productId: number) => {
|
||||
setSelectedProductId(productId);
|
||||
onSubscribe(productId);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="bg-white dark:bg-gray-900 rounded-2xl ring-1 ring-gray-200 dark:ring-gray-800 shadow-sm overflow-hidden">
|
||||
<div className="px-5 py-4 border-b border-gray-200 dark:border-gray-800">
|
||||
<h3 className="text-base font-semibold text-gray-900 dark:text-gray-100">
|
||||
اشتراکهای کاربر
|
||||
</h3>
|
||||
</div>
|
||||
|
||||
{/* Current Subscriptions */}
|
||||
<div className="divide-y divide-gray-200 dark:divide-gray-800">
|
||||
{Object.keys(productsByPackage).length > 0 ? (
|
||||
Object.entries(productsByPackage).map(([packageName, packageProducts]) => (
|
||||
<div key={packageName}>
|
||||
<div className="px-5 py-2.5 bg-gray-50 dark:bg-gray-800/60">
|
||||
<span className="text-xs font-medium text-gray-500 dark:text-gray-400">
|
||||
پکیج: {packageName}
|
||||
</span>
|
||||
</div>
|
||||
<ul className="divide-y divide-gray-100 dark:divide-gray-800/60">
|
||||
{packageProducts.map((product) => {
|
||||
const status = getSubscriptionStatus(product);
|
||||
const subscriptionCount = getSubscriptionCount(product.id);
|
||||
|
||||
return (
|
||||
<li key={`${product.id}-${product.pivot?.purchase_token || Math.random()}`} className="px-5 py-4">
|
||||
<div className="flex items-start justify-between gap-4">
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
<p className="text-sm font-semibold text-indigo-600 dark:text-indigo-400">
|
||||
{product.title || 'محصول'}
|
||||
</p>
|
||||
{subscriptionCount > 1 && (
|
||||
<span className="px-2 py-0.5 text-xs font-medium bg-gray-100 dark:bg-gray-800 text-gray-600 dark:text-gray-400 rounded-lg">
|
||||
×{subscriptionCount}
|
||||
</span>
|
||||
)}
|
||||
<span className={`inline-flex items-center gap-1.5 px-2.5 py-0.5 text-xs font-medium rounded-lg ${status.color}`}>
|
||||
<span className={`h-1.5 w-1.5 rounded-full ${status.dotColor}`} />
|
||||
{status.text}
|
||||
</span>
|
||||
</div>
|
||||
<div className="mt-2 flex flex-wrap gap-x-5 gap-y-1 text-xs text-gray-500 dark:text-gray-400">
|
||||
<span>قیمت: {formatPrice(product.price)} تومان</span>
|
||||
<span>نوع: {getProductTypeLabel(product.type)}</span>
|
||||
{product.pivot?.expire_at && (
|
||||
<span>انقضا: {formatDate(product.pivot.expire_at)}</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
onClick={() => onUnsubscribe(product.id)}
|
||||
disabled={isLoading}
|
||||
className="flex-shrink-0 px-3 py-1.5 text-xs font-medium text-red-600 dark:text-red-400 bg-red-50 dark:bg-red-500/10 hover:bg-red-100 dark:hover:bg-red-500/20 rounded-lg disabled:opacity-50 transition-colors"
|
||||
>
|
||||
لغو اشتراک
|
||||
</button>
|
||||
</div>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
</div>
|
||||
))
|
||||
) : (
|
||||
<div className="px-5 py-10 text-center">
|
||||
<div className="mx-auto h-10 w-10 rounded-xl bg-gray-100 dark:bg-gray-800 flex items-center justify-center mb-2">
|
||||
<XCircleIcon className="h-5 w-5 text-gray-400" />
|
||||
</div>
|
||||
<p className="text-sm text-gray-500 dark:text-gray-400">کاربر هیچ اشتراکی ندارد</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Available Products for Subscription */}
|
||||
{availableProducts && availableProducts.length > 0 && selectedPackage && (
|
||||
<div className="border-t border-gray-200 dark:border-gray-800 px-5 py-5">
|
||||
<h4 className="text-sm font-semibold text-gray-900 dark:text-gray-100 mb-3">
|
||||
افزودن اشتراک جدید
|
||||
</h4>
|
||||
<div className="grid grid-cols-1 gap-2 sm:grid-cols-2 lg:grid-cols-3">
|
||||
{availableProducts.map((product) => {
|
||||
const subscriptionCount = getSubscriptionCount(product.id);
|
||||
|
||||
return (
|
||||
<button
|
||||
key={product.id}
|
||||
onClick={() => handleSubscribeClick(product.id)}
|
||||
disabled={isLoading}
|
||||
className="flex items-center gap-3 p-3.5 border border-dashed border-indigo-200 dark:border-indigo-800/60 rounded-xl text-right hover:border-indigo-400 hover:bg-indigo-50 dark:hover:border-indigo-600 dark:hover:bg-indigo-500/5 disabled:opacity-50 disabled:cursor-not-allowed transition-all duration-150 group"
|
||||
>
|
||||
<div className="h-8 w-8 rounded-lg bg-indigo-100 dark:bg-indigo-500/15 flex items-center justify-center flex-shrink-0 group-hover:bg-indigo-200 dark:group-hover:bg-indigo-500/25 transition-colors">
|
||||
<PlusCircleIcon className="h-4 w-4 text-indigo-600 dark:text-indigo-400" />
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
<p className="text-sm font-medium text-gray-900 dark:text-gray-100 truncate">
|
||||
{product.title || 'محصول'}
|
||||
</p>
|
||||
{subscriptionCount > 0 && (
|
||||
<p className="text-xs text-amber-600 dark:text-amber-400">
|
||||
{subscriptionCount} اشتراک فعال
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
import { MagnifyingGlassIcon } from '@heroicons/react/24/outline';
|
||||
|
||||
interface UserSearchProps {
|
||||
onSearch: (searchTerm: string) => void;
|
||||
isLoading: boolean;
|
||||
}
|
||||
|
||||
export default function UserSearch({ onSearch, isLoading }: UserSearchProps) {
|
||||
const [searchTerm, setSearchTerm] = useState('');
|
||||
|
||||
const handleSubmit = (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (searchTerm.trim()) {
|
||||
onSearch(searchTerm.trim());
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="bg-white dark:bg-gray-900 rounded-2xl ring-1 ring-gray-200 dark:ring-gray-800 shadow-sm p-4 mb-6">
|
||||
<form onSubmit={handleSubmit}>
|
||||
<label htmlFor="user-search" className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
|
||||
جستجوی کاربر
|
||||
</label>
|
||||
<div className="flex gap-2">
|
||||
<div className="flex-1 relative">
|
||||
<div className="absolute inset-y-0 right-0 flex items-center pr-4 pointer-events-none">
|
||||
<MagnifyingGlassIcon className="h-5 w-5 text-gray-400 dark:text-gray-500" />
|
||||
</div>
|
||||
<input
|
||||
type="text"
|
||||
id="user-search"
|
||||
className="block w-full pr-11 pl-4 py-3 border border-gray-200 dark:border-gray-700 rounded-xl bg-gray-50 dark:bg-gray-800/60 placeholder-gray-400 dark:placeholder-gray-500 text-gray-900 dark:text-gray-100 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-transparent focus:bg-white dark:focus:bg-gray-800 sm:text-sm transition-all duration-150"
|
||||
placeholder="ایمیل یا شماره موبایل کاربر را وارد کنید..."
|
||||
value={searchTerm}
|
||||
onChange={(e) => setSearchTerm(e.target.value)}
|
||||
dir="rtl"
|
||||
/>
|
||||
</div>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={isLoading || !searchTerm.trim()}
|
||||
className="inline-flex items-center gap-2 px-6 py-3 bg-indigo-600 text-white rounded-xl text-sm font-medium hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 dark:focus:ring-offset-gray-900 disabled:opacity-50 disabled:cursor-not-allowed transition-all duration-150 shadow-sm shadow-indigo-500/20 whitespace-nowrap"
|
||||
>
|
||||
{isLoading ? (
|
||||
<>
|
||||
<div className="h-4 w-4 border-2 border-white/30 border-t-white rounded-full animate-spin" />
|
||||
در حال جستجو
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<MagnifyingGlassIcon className="h-4 w-4" />
|
||||
جستجو
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
'use client';
|
||||
|
||||
import React, { createContext, useContext, useState, useEffect } from 'react';
|
||||
import { AuthState, LoginCredentials, User } from '@/types/auth';
|
||||
import { authApi } from '@/lib/api/auth';
|
||||
import { useRouter } from 'next/navigation';
|
||||
|
||||
interface AuthContextType extends AuthState {
|
||||
login: (credentials: { auth: string; password: string }) => Promise<void>;
|
||||
logout: () => Promise<void>;
|
||||
}
|
||||
|
||||
const AuthContext = createContext<AuthContextType | undefined>(undefined);
|
||||
|
||||
const PACKAGE_NAME = 'com.approagency.meditation';
|
||||
|
||||
export function AuthProvider({ children }: { children: React.ReactNode }) {
|
||||
const [state, setState] = useState<AuthState>({
|
||||
user: null,
|
||||
token: null,
|
||||
isLoading: true,
|
||||
error: null,
|
||||
});
|
||||
|
||||
const router = useRouter();
|
||||
|
||||
useEffect(() => {
|
||||
// Check for stored token on mount
|
||||
const storedToken = localStorage.getItem('auth_token');
|
||||
const storedUser = localStorage.getItem('auth_user');
|
||||
|
||||
if (storedToken && storedUser) {
|
||||
setState({
|
||||
user: JSON.parse(storedUser),
|
||||
token: storedToken,
|
||||
isLoading: false,
|
||||
error: null,
|
||||
});
|
||||
} else {
|
||||
setState(prev => ({ ...prev, isLoading: false }));
|
||||
}
|
||||
}, []);
|
||||
|
||||
// contexts/AuthContext.tsx - Update the login function
|
||||
const login = async (credentials: { auth: string; password: string }) => {
|
||||
setState(prev => ({ ...prev, isLoading: true, error: null }));
|
||||
|
||||
try {
|
||||
const fullCredentials: LoginCredentials = {
|
||||
auth: credentials.auth,
|
||||
password: credentials.password,
|
||||
package_name: PACKAGE_NAME,
|
||||
};
|
||||
|
||||
const response = await authApi.login(fullCredentials);
|
||||
|
||||
// Extract user data from response
|
||||
const user: User = {
|
||||
id: response.user?.id || '1',
|
||||
email: credentials.auth,
|
||||
name: response.user?.name,
|
||||
};
|
||||
|
||||
// Store in localStorage
|
||||
localStorage.setItem('auth_token', response.token);
|
||||
localStorage.setItem('auth_user', JSON.stringify(user));
|
||||
|
||||
// Set cookie for middleware
|
||||
document.cookie = `auth_token=${response.token}; path=/; max-age=86400; SameSite=Strict`;
|
||||
|
||||
setState({
|
||||
user,
|
||||
token: response.token,
|
||||
isLoading: false,
|
||||
error: null,
|
||||
});
|
||||
|
||||
router.push('/admin/dashboard');
|
||||
} catch (error) {
|
||||
setState({
|
||||
user: null,
|
||||
token: null,
|
||||
isLoading: false,
|
||||
error: error instanceof Error ? error.message : 'Login failed',
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
// Update logout function
|
||||
|
||||
|
||||
const logout = async () => {
|
||||
if (state.token) {
|
||||
try {
|
||||
await authApi.logout(state.token);
|
||||
} catch (error) {
|
||||
console.error('Logout error:', error);
|
||||
}
|
||||
}
|
||||
|
||||
// Clear localStorage
|
||||
localStorage.removeItem('auth_token');
|
||||
localStorage.removeItem('auth_user');
|
||||
|
||||
// Clear cookie - multiple methods to ensure it's removed
|
||||
document.cookie = 'auth_token=; path=/; expires=Thu, 01 Jan 1970 00:00:01 GMT; SameSite=Strict';
|
||||
document.cookie = 'auth_token=; path=/admin; expires=Thu, 01 Jan 1970 00:00:01 GMT; SameSite=Strict';
|
||||
|
||||
// Alternative: Clear all cookies
|
||||
document.cookie.split(";").forEach(function (c) {
|
||||
document.cookie = c.replace(/^ +/, "").replace(/=.*/, "=; path=/; expires=" + new Date().toUTCString() + ";");
|
||||
});
|
||||
|
||||
setState({
|
||||
user: null,
|
||||
token: null,
|
||||
isLoading: false,
|
||||
error: null,
|
||||
});
|
||||
|
||||
// Force hard navigation instead of router.push
|
||||
window.location.href = '/admin/login';
|
||||
// router.push('/admin/login');
|
||||
};
|
||||
|
||||
return (
|
||||
<AuthContext.Provider value={{ ...state, login, logout }}>
|
||||
{children}
|
||||
</AuthContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
export function useAuth() {
|
||||
const context = useContext(AuthContext);
|
||||
if (context === undefined) {
|
||||
throw new Error('useAuth must be used within an AuthProvider');
|
||||
}
|
||||
return context;
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import { apiClient } from './client';
|
||||
import { LoginCredentials, LoginResponse } from '@/types/auth';
|
||||
|
||||
export const authApi = {
|
||||
login: async (credentials: LoginCredentials): Promise<LoginResponse> => {
|
||||
const formData = new FormData();
|
||||
formData.append('auth', credentials.auth);
|
||||
formData.append('password', credentials.password);
|
||||
formData.append('package_name', credentials.package_name);
|
||||
|
||||
return apiClient.post<LoginResponse>('/auth/login', formData);
|
||||
},
|
||||
|
||||
logout: async (token: string): Promise<void> => {
|
||||
return apiClient.put('/auth/logout', {}, token);
|
||||
},
|
||||
|
||||
getProfile: async (token: string): Promise<any> => {
|
||||
return apiClient.get('/auth/profile', token);
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,124 @@
|
||||
const API_BASE_URL = process.env.NEXT_PUBLIC_API_URL || 'https://api.approagency.ir/api';
|
||||
|
||||
interface ApiOptions extends RequestInit {
|
||||
token?: string;
|
||||
}
|
||||
|
||||
// Simple in-memory cache for ongoing requests
|
||||
const pendingRequests = new Map();
|
||||
|
||||
class ApiClient {
|
||||
private async request<T>(
|
||||
endpoint: string,
|
||||
options: ApiOptions = {}
|
||||
): Promise<T> {
|
||||
const { token, ...fetchOptions } = options;
|
||||
|
||||
const headers: Record<string, string> = {
|
||||
// Always ask for JSON so Laravel returns 401 JSON on auth failure
|
||||
// instead of a 302 redirect to the login page.
|
||||
Accept: 'application/json',
|
||||
...(options.headers as Record<string, string> || {}),
|
||||
};
|
||||
|
||||
// Don't set Content-Type for FormData (browser will set it automatically with boundary)
|
||||
if (!(options.body instanceof FormData)) {
|
||||
headers['Content-Type'] = 'application/json';
|
||||
}
|
||||
|
||||
if (token) {
|
||||
headers['Authorization'] = `Bearer ${token}`;
|
||||
}
|
||||
|
||||
// Create a unique key for this request
|
||||
const requestKey = `${fetchOptions.method || 'GET'}-${endpoint}-${JSON.stringify(options.body)}`;
|
||||
|
||||
// Check if there's already a pending request with the same key
|
||||
if (pendingRequests.has(requestKey)) {
|
||||
console.log('Deduplicating request:', endpoint);
|
||||
return pendingRequests.get(requestKey);
|
||||
}
|
||||
|
||||
// Make the request
|
||||
const promise = fetch(`${API_BASE_URL}${endpoint}`, {
|
||||
...fetchOptions,
|
||||
headers,
|
||||
}).then(async (response) => {
|
||||
if (!response.ok) {
|
||||
const error = await response.json().catch(() => ({}));
|
||||
throw new Error(error.message || 'API request failed');
|
||||
}
|
||||
return response.json();
|
||||
}).finally(() => {
|
||||
// Clean up after request completes
|
||||
pendingRequests.delete(requestKey);
|
||||
});
|
||||
|
||||
// Store the promise
|
||||
pendingRequests.set(requestKey, promise);
|
||||
|
||||
return promise;
|
||||
}
|
||||
|
||||
async post<T>(endpoint: string, data: any, token?: string): Promise<T> {
|
||||
const body = data instanceof FormData ? data : JSON.stringify(data);
|
||||
|
||||
return this.request<T>(endpoint, {
|
||||
method: 'POST',
|
||||
body,
|
||||
token,
|
||||
});
|
||||
}
|
||||
|
||||
async get<T>(endpoint: string, token?: string): Promise<T> {
|
||||
return this.request<T>(endpoint, {
|
||||
method: 'GET',
|
||||
token,
|
||||
});
|
||||
}
|
||||
|
||||
async put<T>(endpoint: string, data: any, token?: string): Promise<T> {
|
||||
const body = data instanceof FormData ? data : JSON.stringify(data);
|
||||
|
||||
return this.request<T>(endpoint, {
|
||||
method: 'PUT',
|
||||
body,
|
||||
token,
|
||||
});
|
||||
}
|
||||
|
||||
async patch<T>(endpoint: string, data: any, token?: string): Promise<T> {
|
||||
const body = data instanceof FormData ? data : JSON.stringify(data);
|
||||
|
||||
return this.request<T>(endpoint, {
|
||||
method: 'PATCH',
|
||||
body,
|
||||
token,
|
||||
});
|
||||
}
|
||||
|
||||
async delete<T>(endpoint: string, data?: any, token?: string): Promise<T> {
|
||||
const options: ApiOptions = {
|
||||
method: 'DELETE',
|
||||
token,
|
||||
};
|
||||
|
||||
if (data) {
|
||||
options.body = data instanceof FormData ? data : JSON.stringify(data);
|
||||
|
||||
if (!(data instanceof FormData)) {
|
||||
options.headers = {
|
||||
'Content-Type': 'application/json',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
return this.request<T>(endpoint, options);
|
||||
}
|
||||
|
||||
async deleteWithBody<T>(endpoint: string, data: any, token?: string): Promise<T> {
|
||||
return this.delete<T>(endpoint, data, token);
|
||||
}
|
||||
}
|
||||
|
||||
export const apiClient = new ApiClient();
|
||||
@@ -0,0 +1,77 @@
|
||||
import { apiClient } from './client';
|
||||
import { PackageName, CreatePackageData, UpdatePackageData, ApiResponse } from '@/types/package';
|
||||
|
||||
export const packagesApi = {
|
||||
// Get all package names
|
||||
getAllPackages: async (token: string): Promise<PackageName[]> => {
|
||||
return apiClient.get<PackageName[]>('/package-names', token);
|
||||
},
|
||||
|
||||
// Get single package by name
|
||||
getPackageByName: async (name: string, token: string): Promise<PackageName> => {
|
||||
return apiClient.get<PackageName>(`/package-names/${name}`, token);
|
||||
},
|
||||
|
||||
// Create new package
|
||||
createPackage: async (data: CreatePackageData, token: string): Promise<ApiResponse<PackageName>> => {
|
||||
const formData = new FormData();
|
||||
|
||||
// Append all fields to FormData
|
||||
Object.entries(data).forEach(([key, value]) => {
|
||||
if (value !== null && value !== undefined) {
|
||||
if (key === 'avatar' && value instanceof File) {
|
||||
formData.append('avatar', value);
|
||||
} else if (key === 'firebase_json' && value instanceof File) {
|
||||
formData.append('firebase_json', value);
|
||||
} else {
|
||||
formData.append(key, String(value));
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return apiClient.post<ApiResponse<PackageName>>('/package-names', formData, token);
|
||||
},
|
||||
|
||||
// Update package
|
||||
updatePackage: async (name: string, data: UpdatePackageData, token: string): Promise<ApiResponse<PackageName>> => {
|
||||
const formData = new FormData();
|
||||
|
||||
// Add method spoofing for Laravel
|
||||
|
||||
// Append all fields to FormData
|
||||
Object.entries(data).forEach(([key, value]) => {
|
||||
if (value !== null && value !== undefined) {
|
||||
if (key === 'avatar' && value instanceof File) {
|
||||
formData.append('avatar', value);
|
||||
} else if (key === 'firebase_json' && value instanceof File) {
|
||||
formData.append('firebase_json', value);
|
||||
} else {
|
||||
formData.append(key, String(value));
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return apiClient.post<ApiResponse<PackageName>>(`/package-names/${name}`, formData, token);
|
||||
},
|
||||
|
||||
// Delete package
|
||||
deletePackage: async (name: string, token: string): Promise<ApiResponse<any>> => {
|
||||
return apiClient.delete<ApiResponse<any>>(`/package-names/${name}`, undefined, token);
|
||||
},
|
||||
|
||||
// Upload avatar separately if needed
|
||||
uploadAvatar: async (name: string, avatarFile: File, token: string): Promise<ApiResponse<any>> => {
|
||||
const formData = new FormData();
|
||||
formData.append('avatar', avatarFile);
|
||||
|
||||
return apiClient.post<ApiResponse<any>>(`/package-names/${name}/avatar`, formData, token);
|
||||
},
|
||||
|
||||
// Upload firebase config separately if needed
|
||||
uploadFirebaseConfig: async (name: string, firebaseFile: File, token: string): Promise<ApiResponse<any>> => {
|
||||
const formData = new FormData();
|
||||
formData.append('firebase_json', firebaseFile);
|
||||
|
||||
return apiClient.post<ApiResponse<any>>(`/package-names/${name}/firebase`, formData, token);
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,75 @@
|
||||
import { apiClient } from './client';
|
||||
import { Product, CreateProductData, UpdateProductData, ApiResponse } from '@/types/product';
|
||||
|
||||
export const productsApi = {
|
||||
// Get all products for a package
|
||||
getProducts: async (packageName: string, token: string): Promise<Product[]> => {
|
||||
return apiClient.get<Product[]>(`/package-names/${packageName}/products`, token);
|
||||
},
|
||||
|
||||
// Get single product
|
||||
getProduct: async (packageName: string, productId: number, token: string): Promise<Product> => {
|
||||
return apiClient.get<Product>(`/package-names/${packageName}/products/${productId}`, token);
|
||||
},
|
||||
|
||||
// Create new product
|
||||
createProduct: async (packageName: string, data: CreateProductData, token: string): Promise<ApiResponse<Product>> => {
|
||||
const formData = new FormData();
|
||||
|
||||
// Append all fields to FormData
|
||||
Object.entries(data).forEach(([key, value]) => {
|
||||
if (value !== null && value !== undefined) {
|
||||
if (key === 'descriptions' && Array.isArray(value)) {
|
||||
// Handle descriptions array
|
||||
value.forEach((desc, index) => {
|
||||
formData.append(`descriptions[${index}]`, desc);
|
||||
});
|
||||
} else if (typeof value === 'boolean') {
|
||||
// Laravel's boolean rule accepts "1"/"0", not "true"/"false"
|
||||
formData.append(key, value ? '1' : '0');
|
||||
} else {
|
||||
formData.append(key, String(value));
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return apiClient.post<ApiResponse<Product>>(`/package-names/${packageName}/products`, formData, token);
|
||||
},
|
||||
|
||||
// Update product (using PATCH)
|
||||
updateProduct: async (packageName: string, productId: number, data: UpdateProductData, token: string): Promise<ApiResponse<Product>> => {
|
||||
return apiClient.patch<ApiResponse<Product>>(
|
||||
`/package-names/${packageName}/products/${productId}`,
|
||||
data,
|
||||
token
|
||||
);
|
||||
},
|
||||
|
||||
// Delete product
|
||||
deleteProduct: async (packageName: string, productId: number, token: string): Promise<ApiResponse<any>> => {
|
||||
return apiClient.delete<ApiResponse<any>>(`/package-names/${packageName}/products/${productId}`, undefined, token);
|
||||
},
|
||||
|
||||
// Alternative update method using POST with _method spoofing (if PATCH is not supported)
|
||||
updateProductWithSpoof: async (packageName: string, productId: number, data: UpdateProductData, token: string): Promise<ApiResponse<Product>> => {
|
||||
const formData = new FormData();
|
||||
formData.append('_method', 'PATCH');
|
||||
|
||||
Object.entries(data).forEach(([key, value]) => {
|
||||
if (value !== null && value !== undefined) {
|
||||
if (key === 'descriptions' && Array.isArray(value)) {
|
||||
value.forEach((desc, index) => {
|
||||
formData.append(`descriptions[${index}]`, desc);
|
||||
});
|
||||
} else if (typeof value === 'boolean') {
|
||||
// Laravel's boolean rule accepts "1"/"0", not "true"/"false"
|
||||
formData.append(key, value ? '1' : '0');
|
||||
} else {
|
||||
formData.append(key, String(value));
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return apiClient.post<ApiResponse<Product>>(`/package-names/${packageName}/products/${productId}`, formData, token);
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,65 @@
|
||||
import { apiClient } from './client';
|
||||
import { Promotion, CreatePromotionData, UpdatePromotionData, ApiResponse } from '@/types/promotion';
|
||||
|
||||
export const promotionsApi = {
|
||||
// Get all promotions for admin (includes inactive/expired ones)
|
||||
getPromotions: async (token: string): Promise<Promotion[]> => {
|
||||
return apiClient.get<Promotion[]>('/admin/promotions', token);
|
||||
},
|
||||
|
||||
// Get single promotion
|
||||
getPromotion: async (id: number, token: string): Promise<Promotion> => {
|
||||
return apiClient.get<Promotion>(`/promotions/${id}`, token);
|
||||
},
|
||||
|
||||
// Create new promotion
|
||||
createPromotion: async (data: CreatePromotionData, token: string): Promise<ApiResponse<Promotion>> => {
|
||||
const formData = new FormData();
|
||||
|
||||
// Append all fields to FormData
|
||||
Object.entries(data).forEach(([key, value]) => {
|
||||
if (value !== null && value !== undefined) {
|
||||
if (key === 'image' && value instanceof File) {
|
||||
formData.append('image', value);
|
||||
} else {
|
||||
formData.append(key, String(value));
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return apiClient.post<ApiResponse<Promotion>>('/promotions', formData, token);
|
||||
},
|
||||
|
||||
// Update promotion
|
||||
updatePromotion: async (id: number, data: UpdatePromotionData, token: string): Promise<ApiResponse<Promotion>> => {
|
||||
const formData = new FormData();
|
||||
|
||||
// Add method spoofing for Laravel
|
||||
// formData.append('_method', 'PUT');
|
||||
|
||||
// Append all fields to FormData
|
||||
Object.entries(data).forEach(([key, value]) => {
|
||||
if (value !== null && value !== undefined) {
|
||||
if (key === 'image' && value instanceof File) {
|
||||
formData.append('image', value);
|
||||
} else if (key === 'is_active') {
|
||||
formData.append(key, value ? '1' : '0');
|
||||
} else {
|
||||
formData.append(key, String(value));
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return apiClient.post<ApiResponse<Promotion>>(`/promotions/${id}`, formData, token);
|
||||
},
|
||||
|
||||
// Delete promotion
|
||||
deletePromotion: async (id: number, token: string): Promise<ApiResponse<any>> => {
|
||||
return apiClient.delete<ApiResponse<any>>(`/promotions/${id}`, undefined, token);
|
||||
},
|
||||
|
||||
// Toggle promotion active status
|
||||
toggleActive: async (id: number, isActive: boolean, token: string): Promise<ApiResponse<Promotion>> => {
|
||||
return apiClient.put<ApiResponse<Promotion>>(`/promotions/${id}`, { is_active: isActive }, token);
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,22 @@
|
||||
import { apiClient } from './client';
|
||||
import { Purchase, Paginated, PurchaseFilters } from '@/types/purchase';
|
||||
|
||||
export const purchasesApi = {
|
||||
// List all subscription purchases with optional filters
|
||||
getPurchases: async (filters: PurchaseFilters, token: string): Promise<Paginated<Purchase>> => {
|
||||
const params = new URLSearchParams();
|
||||
|
||||
if (filters.email) params.append('email', filters.email);
|
||||
if (filters.mobile) params.append('mobile', filters.mobile);
|
||||
if (filters.package_name) params.append('package_name', filters.package_name);
|
||||
if (filters.gateway) params.append('gateway', filters.gateway);
|
||||
if (filters.status !== undefined && filters.status !== null) {
|
||||
params.append('status', String(filters.status));
|
||||
}
|
||||
if (filters.per_page) params.append('per_page', String(filters.per_page));
|
||||
if (filters.page) params.append('page', String(filters.page));
|
||||
|
||||
const qs = params.toString();
|
||||
return apiClient.get<Paginated<Purchase>>(`/admin/purchases${qs ? `?${qs}` : ''}`, token);
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,26 @@
|
||||
import { apiClient } from './client';
|
||||
import { PendingReferralRewardsResponse, FulfillReferralRewardResponse } from '@/types/referral';
|
||||
|
||||
export const referralApi = {
|
||||
// List users who reached the invite target and have not been granted the free month yet
|
||||
getPendingRewards: async (token: string): Promise<PendingReferralRewardsResponse> => {
|
||||
return apiClient.get<PendingReferralRewardsResponse>('/admin/referral-rewards', token);
|
||||
},
|
||||
|
||||
// Grant the free month to a user. product_id is optional: omit it to
|
||||
// auto-grant the meditation package's monthly product.
|
||||
fulfillReward: async (
|
||||
userId: number,
|
||||
token: string,
|
||||
productId?: number
|
||||
): Promise<FulfillReferralRewardResponse> => {
|
||||
const data = productId ? { product_id: productId } : {};
|
||||
|
||||
return apiClient.post<FulfillReferralRewardResponse>(
|
||||
`/admin/referral-rewards/${userId}/fulfill`,
|
||||
data,
|
||||
token
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
import { apiClient } from './client';
|
||||
import { Reminder, CreateReminderData, UpdateReminderData, ApiResponse } from '@/types/reminder';
|
||||
|
||||
export const remindersApi = {
|
||||
// Get all reminders for a package
|
||||
getReminders: async (packageName: string, token: string): Promise<Reminder[]> => {
|
||||
return apiClient.get<Reminder[]>(`/package-names/${packageName}/reminders`, token);
|
||||
},
|
||||
|
||||
// Get single reminder
|
||||
getReminder: async (packageName: string, reminderId: number, token: string): Promise<Reminder> => {
|
||||
return apiClient.get<Reminder>(`/package-names/${packageName}/reminders/${reminderId}`, token);
|
||||
},
|
||||
|
||||
// Create new reminder
|
||||
createReminder: async (packageName: string, data: CreateReminderData, token: string): Promise<ApiResponse<Reminder>> => {
|
||||
const formData = new FormData();
|
||||
|
||||
// Append all fields to FormData
|
||||
Object.entries(data).forEach(([key, value]) => {
|
||||
if (value !== null && value !== undefined) {
|
||||
if (key === 'data' && typeof value === 'object') {
|
||||
formData.append(key, JSON.stringify(value));
|
||||
} else if (typeof value === 'boolean') {
|
||||
// Laravel's `boolean` rule rejects the strings "true"/"false"; send 1/0
|
||||
formData.append(key, value ? '1' : '0');
|
||||
} else {
|
||||
formData.append(key, String(value));
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return apiClient.post<ApiResponse<Reminder>>(`/package-names/${packageName}/reminders`, formData, token);
|
||||
},
|
||||
|
||||
// Update reminder (using PUT)
|
||||
updateReminder: async (packageName: string, reminderId: number, data: UpdateReminderData, token: string): Promise<ApiResponse<Reminder>> => {
|
||||
return apiClient.put<ApiResponse<Reminder>>(
|
||||
`/package-names/${packageName}/reminders/${reminderId}`,
|
||||
data,
|
||||
token
|
||||
);
|
||||
},
|
||||
|
||||
// Delete reminder
|
||||
deleteReminder: async (packageName: string, reminderId: number, token: string): Promise<ApiResponse<any>> => {
|
||||
return apiClient.delete<ApiResponse<any>>(`/package-names/${packageName}/reminders/${reminderId}`, undefined, token);
|
||||
},
|
||||
|
||||
// Alternative update method using POST with _method spoofing (if PUT is not supported)
|
||||
updateReminderWithSpoof: async (packageName: string, reminderId: number, data: UpdateReminderData, token: string): Promise<ApiResponse<Reminder>> => {
|
||||
const formData = new FormData();
|
||||
formData.append('_method', 'PUT');
|
||||
|
||||
Object.entries(data).forEach(([key, value]) => {
|
||||
if (value !== null && value !== undefined) {
|
||||
if (key === 'data' && typeof value === 'object') {
|
||||
formData.append(key, JSON.stringify(value));
|
||||
} else if (typeof value === 'boolean') {
|
||||
// Laravel's `boolean` rule rejects the strings "true"/"false"; send 1/0
|
||||
formData.append(key, value ? '1' : '0');
|
||||
} else {
|
||||
formData.append(key, String(value));
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return apiClient.post<ApiResponse<Reminder>>(`/package-names/${packageName}/reminders/${reminderId}`, formData, token);
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,77 @@
|
||||
import { apiClient } from './client';
|
||||
import { User, Product, ApiResponse, UpdateUserProfileData } from '@/types/user';
|
||||
|
||||
export const usersApi = {
|
||||
// Get user status by email or mobile - package name is now a parameter
|
||||
getUserStatus: async (identifier: string, packageName: string, token: string): Promise<User> => {
|
||||
// Check if identifier is email or mobile
|
||||
const isEmail = identifier.includes('@');
|
||||
const endpoint = isEmail
|
||||
? `/admin/users/${identifier}/status?package_name=${packageName}`
|
||||
: `/admin/users/${identifier}/status?package_name=${packageName}`;
|
||||
|
||||
return apiClient.get<User>(endpoint, token);
|
||||
},
|
||||
|
||||
// Subscribe user to a product
|
||||
subscribeUser: async (identifier: string, productId: number, token: string): Promise<ApiResponse<any>> => {
|
||||
const data = {
|
||||
product_id: productId
|
||||
};
|
||||
|
||||
return apiClient.put<ApiResponse<any>>(
|
||||
`/admin/users/${identifier}/status`,
|
||||
data,
|
||||
token
|
||||
);
|
||||
},
|
||||
|
||||
// Unsubscribe user from a product
|
||||
unsubscribeUser: async (identifier: string, productId: number, token: string): Promise<ApiResponse<any>> => {
|
||||
const data = {
|
||||
product_id: productId
|
||||
};
|
||||
|
||||
return apiClient.delete<ApiResponse<any>>(
|
||||
`/admin/users/${identifier}/status`,
|
||||
data,
|
||||
token
|
||||
);
|
||||
},
|
||||
|
||||
// Get user transactions
|
||||
getUserTransactions: async (userId: number, packageName: string, token: string): Promise<any> => {
|
||||
return apiClient.get(`/admin/users/${userId}/transactions?package_name=${packageName}`, token);
|
||||
},
|
||||
|
||||
// Get products for a specific package
|
||||
getProductsByPackage: async (packageName: string, token: string): Promise<Product[]> => {
|
||||
return apiClient.get<Product[]>(`/package-names/${packageName}/products`, token);
|
||||
},
|
||||
|
||||
// Update a user's profile (admin). Uses FormData because avatar may be an image file.
|
||||
updateUserProfile: async (
|
||||
identifier: string,
|
||||
data: UpdateUserProfileData,
|
||||
token: string
|
||||
): Promise<ApiResponse<any>> => {
|
||||
const formData = new FormData();
|
||||
|
||||
Object.entries(data).forEach(([key, value]) => {
|
||||
if (value !== null && value !== undefined && value !== '') {
|
||||
if (key === 'avatar' && value instanceof File) {
|
||||
formData.append('avatar', value);
|
||||
} else if (key !== 'avatar') {
|
||||
formData.append(key, String(value));
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return apiClient.post<ApiResponse<any>>(`/admin/users/${identifier}/profile`, formData, token);
|
||||
},
|
||||
|
||||
// Delete a user (admin)
|
||||
deleteUser: async (identifier: string, token: string): Promise<ApiResponse<any>> => {
|
||||
return apiClient.delete<ApiResponse<any>>(`/admin/users/${identifier}`, undefined, token);
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,61 @@
|
||||
import { User } from "@/types/user";
|
||||
|
||||
// Single source of truth for product type labels lives in types/product.ts
|
||||
// (kept in sync with the backend Product::TYPES). Re-exported here so existing
|
||||
// `@/lib/utils` imports keep working without a divergent (previously wrong) map.
|
||||
export { getProductTypeLabel } from "@/types/product";
|
||||
|
||||
export const formatDate = (dateString: string | null): string => {
|
||||
if (!dateString) return 'نامشخص';
|
||||
|
||||
try {
|
||||
const date = new Date(dateString);
|
||||
return new Intl.DateTimeFormat('fa-IR', {
|
||||
year: 'numeric',
|
||||
month: 'long',
|
||||
day: 'numeric',
|
||||
}).format(date);
|
||||
} catch {
|
||||
return 'نامشخص';
|
||||
}
|
||||
};
|
||||
|
||||
export const formatPrice = (price: number | null): string => {
|
||||
if (price === null || price === undefined) return '0';
|
||||
return new Intl.NumberFormat('fa-IR').format(price);
|
||||
};
|
||||
|
||||
export const getFullName = (user: User): string => {
|
||||
if (user.full_name) return user.full_name;
|
||||
|
||||
const firstName = user.first_name || '';
|
||||
const lastName = user.last_name || '';
|
||||
|
||||
if (firstName || lastName) {
|
||||
return `${firstName} ${lastName}`.trim();
|
||||
}
|
||||
|
||||
return 'نامشخص';
|
||||
};
|
||||
|
||||
export const getEmail = (email: string | null): string => {
|
||||
return email || 'ایمیل ثبت نشده';
|
||||
};
|
||||
|
||||
export const getMobile = (mobile: string | null): string => {
|
||||
return mobile || 'شماره موبایل ثبت نشده';
|
||||
};
|
||||
|
||||
export const formatTime = (dateString: string | null): string => {
|
||||
if (!dateString) return '';
|
||||
|
||||
try {
|
||||
const date = new Date(dateString);
|
||||
return new Intl.DateTimeFormat('fa-IR', {
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
}).format(date);
|
||||
} catch {
|
||||
return '';
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,6 @@
|
||||
/// <reference types="next" />
|
||||
/// <reference types="next/image-types/global" />
|
||||
import "./.next/types/routes.d.ts";
|
||||
|
||||
// NOTE: This file should not be edited
|
||||
// see https://nextjs.org/docs/app/api-reference/config/typescript for more information.
|
||||
@@ -0,0 +1,9 @@
|
||||
import type { NextConfig } from "next";
|
||||
|
||||
const nextConfig: NextConfig = {
|
||||
output: 'export',
|
||||
// Emit each route as a folder with index.html (e.g. admin/login/index.html)
|
||||
// so static hosts (nginx) can serve clean URLs without custom rewrite rules.
|
||||
trailingSlash: true,
|
||||
};
|
||||
export default nextConfig;
|
||||
@@ -0,0 +1,32 @@
|
||||
{
|
||||
"name": "approagency admin pannel",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "next dev",
|
||||
"build": "next build",
|
||||
"start": "next start",
|
||||
"lint": "eslint",
|
||||
"prepare": "git config core.hooksPath .githooks || true"
|
||||
},
|
||||
"dependencies": {
|
||||
"@heroicons/react": "^2.2.0",
|
||||
"framer-motion": "^12.23.24",
|
||||
"lucide-react": "^0.552.0",
|
||||
"next": "16.0.1",
|
||||
"react": "19.2.0",
|
||||
"react-dom": "19.2.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@tailwindcss/postcss": "^4",
|
||||
"@types/node": "^20",
|
||||
"@types/react": "^19",
|
||||
"@types/react-dom": "^19",
|
||||
"autoprefixer": "^10.4.24",
|
||||
"eslint": "^9",
|
||||
"eslint-config-next": "16.0.1",
|
||||
"postcss": "^8.5.6",
|
||||
"tailwindcss": "^4.2.0",
|
||||
"typescript": "^5"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
// postcss.config.mjs
|
||||
const config = {
|
||||
plugins: {
|
||||
"@tailwindcss/postcss": {}, // ✅ correct for Tailwind 4
|
||||
autoprefixer: {},
|
||||
},
|
||||
};
|
||||
|
||||
export default config;
|
||||
|
After Width: | Height: | Size: 4.2 KiB |
|
After Width: | Height: | Size: 677 KiB |
@@ -0,0 +1 @@
|
||||
<svg fill="none" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path d="M14.5 13.5V5.41a1 1 0 0 0-.3-.7L9.8.29A1 1 0 0 0 9.08 0H1.5v13.5A2.5 2.5 0 0 0 4 16h8a2.5 2.5 0 0 0 2.5-2.5m-1.5 0v-7H8v-5H3v12a1 1 0 0 0 1 1h8a1 1 0 0 0 1-1M9.5 5V2.12L12.38 5zM5.13 5h-.62v1.25h2.12V5zm-.62 3h7.12v1.25H4.5zm.62 3h-.62v1.25h7.12V11z" clip-rule="evenodd" fill="#666" fill-rule="evenodd"/></svg>
|
||||
|
After Width: | Height: | Size: 391 B |
@@ -0,0 +1 @@
|
||||
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><g clip-path="url(#a)"><path fill-rule="evenodd" clip-rule="evenodd" d="M10.27 14.1a6.5 6.5 0 0 0 3.67-3.45q-1.24.21-2.7.34-.31 1.83-.97 3.1M8 16A8 8 0 1 0 8 0a8 8 0 0 0 0 16m.48-1.52a7 7 0 0 1-.96 0H7.5a4 4 0 0 1-.84-1.32q-.38-.89-.63-2.08a40 40 0 0 0 3.92 0q-.25 1.2-.63 2.08a4 4 0 0 1-.84 1.31zm2.94-4.76q1.66-.15 2.95-.43a7 7 0 0 0 0-2.58q-1.3-.27-2.95-.43a18 18 0 0 1 0 3.44m-1.27-3.54a17 17 0 0 1 0 3.64 39 39 0 0 1-4.3 0 17 17 0 0 1 0-3.64 39 39 0 0 1 4.3 0m1.1-1.17q1.45.13 2.69.34a6.5 6.5 0 0 0-3.67-3.44q.65 1.26.98 3.1M8.48 1.5l.01.02q.41.37.84 1.31.38.89.63 2.08a40 40 0 0 0-3.92 0q.25-1.2.63-2.08a4 4 0 0 1 .85-1.32 7 7 0 0 1 .96 0m-2.75.4a6.5 6.5 0 0 0-3.67 3.44 29 29 0 0 1 2.7-.34q.31-1.83.97-3.1M4.58 6.28q-1.66.16-2.95.43a7 7 0 0 0 0 2.58q1.3.27 2.95.43a18 18 0 0 1 0-3.44m.17 4.71q-1.45-.12-2.69-.34a6.5 6.5 0 0 0 3.67 3.44q-.65-1.27-.98-3.1" fill="#666"/></g><defs><clipPath id="a"><path fill="#fff" d="M0 0h16v16H0z"/></clipPath></defs></svg>
|
||||
|
After Width: | Height: | Size: 1.0 KiB |
|
After Width: | Height: | Size: 676 KiB |
|
After Width: | Height: | Size: 68 KiB |
|
After Width: | Height: | Size: 16 KiB |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 394 80"><path fill="#000" d="M262 0h68.5v12.7h-27.2v66.6h-13.6V12.7H262V0ZM149 0v12.7H94v20.4h44.3v12.6H94v21h55v12.6H80.5V0h68.7zm34.3 0h-17.8l63.8 79.4h17.9l-32-39.7 32-39.6h-17.9l-23 28.6-23-28.6zm18.3 56.7-9-11-27.1 33.7h17.8l18.3-22.7z"/><path fill="#000" d="M81 79.3 17 0H0v79.3h13.6V17l50.2 62.3H81Zm252.6-.4c-1 0-1.8-.4-2.5-1s-1.1-1.6-1.1-2.6.3-1.8 1-2.5 1.6-1 2.6-1 1.8.3 2.5 1a3.4 3.4 0 0 1 .6 4.3 3.7 3.7 0 0 1-3 1.8zm23.2-33.5h6v23.3c0 2.1-.4 4-1.3 5.5a9.1 9.1 0 0 1-3.8 3.5c-1.6.8-3.5 1.3-5.7 1.3-2 0-3.7-.4-5.3-1s-2.8-1.8-3.7-3.2c-.9-1.3-1.4-3-1.4-5h6c.1.8.3 1.6.7 2.2s1 1.2 1.6 1.5c.7.4 1.5.5 2.4.5 1 0 1.8-.2 2.4-.6a4 4 0 0 0 1.6-1.8c.3-.8.5-1.8.5-3V45.5zm30.9 9.1a4.4 4.4 0 0 0-2-3.3 7.5 7.5 0 0 0-4.3-1.1c-1.3 0-2.4.2-3.3.5-.9.4-1.6 1-2 1.6a3.5 3.5 0 0 0-.3 4c.3.5.7.9 1.3 1.2l1.8 1 2 .5 3.2.8c1.3.3 2.5.7 3.7 1.2a13 13 0 0 1 3.2 1.8 8.1 8.1 0 0 1 3 6.5c0 2-.5 3.7-1.5 5.1a10 10 0 0 1-4.4 3.5c-1.8.8-4.1 1.2-6.8 1.2-2.6 0-4.9-.4-6.8-1.2-2-.8-3.4-2-4.5-3.5a10 10 0 0 1-1.7-5.6h6a5 5 0 0 0 3.5 4.6c1 .4 2.2.6 3.4.6 1.3 0 2.5-.2 3.5-.6 1-.4 1.8-1 2.4-1.7a4 4 0 0 0 .8-2.4c0-.9-.2-1.6-.7-2.2a11 11 0 0 0-2.1-1.4l-3.2-1-3.8-1c-2.8-.7-5-1.7-6.6-3.2a7.2 7.2 0 0 1-2.4-5.7 8 8 0 0 1 1.7-5 10 10 0 0 1 4.3-3.5c2-.8 4-1.2 6.4-1.2 2.3 0 4.4.4 6.2 1.2 1.8.8 3.2 2 4.3 3.4 1 1.4 1.5 3 1.5 5h-5.8z"/></svg>
|
||||
|
After Width: | Height: | Size: 1.3 KiB |
|
After Width: | Height: | Size: 1.4 MiB |
@@ -0,0 +1 @@
|
||||
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1155 1000"><path d="m577.3 0 577.4 1000H0z" fill="#fff"/></svg>
|
||||
|
After Width: | Height: | Size: 128 B |
@@ -0,0 +1 @@
|
||||
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path fill-rule="evenodd" clip-rule="evenodd" d="M1.5 2.5h13v10a1 1 0 0 1-1 1h-11a1 1 0 0 1-1-1zM0 1h16v11.5a2.5 2.5 0 0 1-2.5 2.5h-11A2.5 2.5 0 0 1 0 12.5zm3.75 4.5a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5M7 4.75a.75.75 0 1 1-1.5 0 .75.75 0 0 1 1.5 0m1.75.75a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5" fill="#666"/></svg>
|
||||
|
After Width: | Height: | Size: 385 B |
@@ -0,0 +1,46 @@
|
||||
#!/usr/bin/env bash
|
||||
# Build the static site locally, then replace the server directory with it.
|
||||
#
|
||||
# - Builds on THIS machine (npm run build -> ./out).
|
||||
# - Streams out/ over a single SSH connection (tar pipe) and swaps the
|
||||
# contents of the target dir on the server. No rsync/sshpass required.
|
||||
#
|
||||
# Password handling:
|
||||
# - If `sshpass` is installed AND DEPLOY_PASSWORD is set (env or .env.deploy),
|
||||
# the deploy is fully unattended.
|
||||
# - Otherwise SSH prompts for the password once (interactive).
|
||||
#
|
||||
# Config (override via env or .env.deploy):
|
||||
set -euo pipefail
|
||||
cd "$(git rev-parse --show-toplevel 2>/dev/null || dirname "$(dirname "$0")")"
|
||||
|
||||
# Optional local secrets file (gitignored).
|
||||
[ -f .env.deploy ] && . ./.env.deploy
|
||||
|
||||
DEPLOY_HOST="${DEPLOY_HOST:-185.226.116.88}"
|
||||
DEPLOY_USER="${DEPLOY_USER:-ubuntu}"
|
||||
DEPLOY_PATH="${DEPLOY_PATH:-/var/www/appro-admin}"
|
||||
DEPLOY_PASSWORD="${DEPLOY_PASSWORD:-}"
|
||||
|
||||
echo "▸ Building locally…"
|
||||
npm run build
|
||||
|
||||
if [ ! -d out ]; then
|
||||
echo "✗ Build did not produce ./out" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Pick the SSH command: unattended with sshpass, else interactive prompt.
|
||||
ssh_cmd=(ssh -o StrictHostKeyChecking=no "$DEPLOY_USER@$DEPLOY_HOST")
|
||||
if command -v sshpass >/dev/null 2>&1 && [ -n "$DEPLOY_PASSWORD" ]; then
|
||||
ssh_cmd=(sshpass -p "$DEPLOY_PASSWORD" "${ssh_cmd[@]}")
|
||||
else
|
||||
echo "ℹ sshpass/password not available — SSH will prompt for the password."
|
||||
fi
|
||||
|
||||
echo "▸ Uploading to $DEPLOY_USER@$DEPLOY_HOST:$DEPLOY_PATH …"
|
||||
# Replace the directory contents (incl. dotfiles) then extract the new build.
|
||||
tar -C out -czf - . | "${ssh_cmd[@]}" \
|
||||
"set -e; mkdir -p '$DEPLOY_PATH'; find '$DEPLOY_PATH' -mindepth 1 -delete; tar -C '$DEPLOY_PATH' -xzf -"
|
||||
|
||||
echo "✓ Deployed to $DEPLOY_HOST:$DEPLOY_PATH"
|
||||
@@ -0,0 +1,35 @@
|
||||
import type { Config } from "tailwindcss";
|
||||
|
||||
const config: Config = {
|
||||
content: [
|
||||
"./pages/**/*.{js,ts,jsx,tsx,mdx}",
|
||||
"./components/**/*.{js,ts,jsx,tsx,mdx}",
|
||||
"./app/**/*.{js,ts,jsx,tsx,mdx}",
|
||||
],
|
||||
theme: {
|
||||
extend: {
|
||||
// fontFamily: {
|
||||
// sans: [
|
||||
// "Dana",
|
||||
// "Inter",
|
||||
// "var(--font-geist-sans)",
|
||||
// "system-ui",
|
||||
// "sans-serif",
|
||||
// ],
|
||||
// },
|
||||
|
||||
// animation: {
|
||||
// fadeInUp: "fadeInUp 0.6s ease-out",
|
||||
// },
|
||||
// keyframes: {
|
||||
// fadeInUp: {
|
||||
// "0%": { opacity: "0", transform: "translateY(30px)" },
|
||||
// "100%": { opacity: "1", transform: "translateY(0)" },
|
||||
// },
|
||||
// },
|
||||
},
|
||||
},
|
||||
plugins: [],
|
||||
};
|
||||
|
||||
export default config;
|
||||
@@ -0,0 +1,42 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "es5",
|
||||
"lib": [
|
||||
"dom",
|
||||
"dom.iterable",
|
||||
"esnext"
|
||||
],
|
||||
"allowJs": true,
|
||||
"skipLibCheck": true,
|
||||
"strict": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"noEmit": true,
|
||||
"esModuleInterop": true,
|
||||
"module": "esnext",
|
||||
"moduleResolution": "bundler",
|
||||
"resolveJsonModule": true,
|
||||
"isolatedModules": true,
|
||||
"jsx": "react-jsx",
|
||||
"incremental": true,
|
||||
"plugins": [
|
||||
{
|
||||
"name": "next"
|
||||
}
|
||||
],
|
||||
"paths": {
|
||||
"@/*": [
|
||||
"./*"
|
||||
]
|
||||
}
|
||||
},
|
||||
"include": [
|
||||
"next-env.d.ts",
|
||||
"**/*.ts",
|
||||
"**/*.tsx",
|
||||
".next/types/**/*.ts",
|
||||
".next/dev/types/**/*.ts"
|
||||
],
|
||||
"exclude": [
|
||||
"node_modules"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
export interface LoginCredentials {
|
||||
auth: string;
|
||||
password: string;
|
||||
package_name: string;
|
||||
}
|
||||
|
||||
export interface LoginResponse {
|
||||
token: string;
|
||||
user?: User;
|
||||
message?: string;
|
||||
}
|
||||
|
||||
export interface User {
|
||||
id: string;
|
||||
email: string;
|
||||
name?: string;
|
||||
role?: string;
|
||||
is_admin?: String;
|
||||
}
|
||||
|
||||
export interface AuthState {
|
||||
user: User | null;
|
||||
token: string | null;
|
||||
isLoading: boolean;
|
||||
error: string | null;
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
export interface PackageName {
|
||||
id: number;
|
||||
name: string | null;
|
||||
title: string | null;
|
||||
image: string | null | File | any;
|
||||
v1_identifier: string | null;
|
||||
uuid: string;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
cafe_config_id: number | null;
|
||||
myket_access_token: string | null;
|
||||
web_app_url: string | null;
|
||||
tries: number | null;
|
||||
}
|
||||
|
||||
export interface CreatePackageData {
|
||||
name: string;
|
||||
title: string;
|
||||
avatar?: File | null;
|
||||
v1_identifier?: string | null;
|
||||
myket_access_token?: string | null;
|
||||
cafe_config_id?: number | null;
|
||||
web_app_url?: string | null;
|
||||
tries?: number;
|
||||
firebase_json?: File | null;
|
||||
}
|
||||
|
||||
export interface UpdatePackageData {
|
||||
name?: string;
|
||||
title?: string;
|
||||
avatar?: File | null;
|
||||
v1_identifier?: string | null;
|
||||
myket_access_token?: string | null;
|
||||
cafe_config_id?: number | null;
|
||||
web_app_url?: string | null;
|
||||
tries?: number;
|
||||
firebase_json?: File | null;
|
||||
_method?: string; // For Laravel method spoofing
|
||||
}
|
||||
|
||||
export interface ApiResponse<T> {
|
||||
data: T;
|
||||
message?: string;
|
||||
status?: number;
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
export interface Product {
|
||||
id: number;
|
||||
package_name_id: number;
|
||||
title: string | null;
|
||||
price: number | null;
|
||||
type: number | null;
|
||||
uuid: string;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
descriptions: string[] | null;
|
||||
// Display-only text fields (no calculation)
|
||||
discounted_price: string | null; // قیمت کلی تخفیف خورده
|
||||
daily_price: string | null; // قیمت روزانه
|
||||
discount: string | null; // تخفیف
|
||||
is_best_seller: boolean; // پرفروشترین
|
||||
sort_order: number; // ترتیب (۰ بالاترین)
|
||||
}
|
||||
|
||||
export interface CreateProductData {
|
||||
title: string;
|
||||
price: number;
|
||||
type: number;
|
||||
descriptions?: string[];
|
||||
discounted_price?: string;
|
||||
daily_price?: string;
|
||||
discount?: string;
|
||||
is_best_seller?: boolean;
|
||||
sort_order?: number;
|
||||
}
|
||||
|
||||
export interface UpdateProductData {
|
||||
title?: string;
|
||||
price?: number;
|
||||
type?: number;
|
||||
descriptions?: string[];
|
||||
discounted_price?: string;
|
||||
daily_price?: string;
|
||||
discount?: string;
|
||||
is_best_seller?: boolean;
|
||||
sort_order?: number;
|
||||
}
|
||||
|
||||
export interface ApiResponse<T> {
|
||||
data: T;
|
||||
message?: string;
|
||||
status?: number;
|
||||
}
|
||||
|
||||
// Product types mapping
|
||||
export const PRODUCT_TYPES = {
|
||||
1: 'دائمی',
|
||||
2: 'سالیانه',
|
||||
3: '۶ ماهه',
|
||||
4: 'ماهیانه',
|
||||
5: 'سه ماهه'
|
||||
} as const;
|
||||
|
||||
export type ProductType = keyof typeof PRODUCT_TYPES;
|
||||
|
||||
export const getProductTypeLabel = (type: number | null): string => {
|
||||
if (!type) return 'نامشخص';
|
||||
return PRODUCT_TYPES[type as ProductType] || 'نامشخص';
|
||||
};
|
||||
@@ -0,0 +1,69 @@
|
||||
export type PromotionType = 'slider' | 'action' | 'paid_app' | 'banner';
|
||||
|
||||
export const PROMOTION_TYPES = {
|
||||
slider: 'اسلایدر',
|
||||
action: 'اکشن',
|
||||
paid_app: 'اپلیکیشن پولی',
|
||||
banner: 'بنر'
|
||||
} as const;
|
||||
|
||||
export interface Promotion {
|
||||
id: number;
|
||||
type: PromotionType;
|
||||
title: string | null;
|
||||
image_url:string | null;
|
||||
subtitle: string | null;
|
||||
image: string | null;
|
||||
action_text: string | null;
|
||||
url_myket: string | null;
|
||||
url_bazzar: string | null;
|
||||
url_google_play: string | null;
|
||||
url_site: string | null;
|
||||
is_active: boolean;
|
||||
priority: number | null;
|
||||
start_at: string | null;
|
||||
end_at: string | null;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
export interface CreatePromotionData {
|
||||
type: PromotionType;
|
||||
title?: string | null;
|
||||
subtitle?: string | null;
|
||||
image?: File | null;
|
||||
action_text?: string | null;
|
||||
url_myket?: string | null;
|
||||
url_bazzar?: string | null;
|
||||
url_google_play?: string | null;
|
||||
url_site?: string | null;
|
||||
priority?: number | null;
|
||||
start_at?: string | null;
|
||||
end_at?: string | null;
|
||||
}
|
||||
|
||||
export interface UpdatePromotionData {
|
||||
type?: PromotionType;
|
||||
title?: string | null;
|
||||
subtitle?: string | null;
|
||||
image?: File | null;
|
||||
action_text?: string | null;
|
||||
url_myket?: string | null;
|
||||
url_bazzar?: string | null;
|
||||
url_google_play?: string | null;
|
||||
url_site?: string | null;
|
||||
is_active?: boolean;
|
||||
priority?: number | null;
|
||||
start_at?: string | null;
|
||||
end_at?: string | null;
|
||||
}
|
||||
|
||||
export interface ApiResponse<T> {
|
||||
data: T;
|
||||
message?: string;
|
||||
status?: number;
|
||||
}
|
||||
|
||||
export const getPromotionTypeLabel = (type: PromotionType): string => {
|
||||
return PROMOTION_TYPES[type] || type;
|
||||
};
|
||||
@@ -0,0 +1,94 @@
|
||||
import { PackageName } from './user';
|
||||
|
||||
// Nested user on a purchase (subset of the full User model)
|
||||
export interface PurchaseUser {
|
||||
id: number;
|
||||
uuid: string;
|
||||
first_name: string | null;
|
||||
last_name: string | null;
|
||||
full_name: string | null;
|
||||
email: string | null;
|
||||
mobile: string | null;
|
||||
}
|
||||
|
||||
// Nested product on a purchase, with its package
|
||||
export interface PurchaseProduct {
|
||||
id: number;
|
||||
title: string | null;
|
||||
price: number | null;
|
||||
type: number | null;
|
||||
package_name_id: number;
|
||||
package_name: PackageName | null;
|
||||
// Display-only pricing (متن نمایشی — بدون محاسبه)
|
||||
discounted_price: string | null; // قیمت کلی تخفیفخورده
|
||||
discount: string | null; // تخفیف
|
||||
}
|
||||
|
||||
// A purchase = a subscription transaction
|
||||
export interface Purchase {
|
||||
id: number;
|
||||
user_id: number;
|
||||
product_id: number | null;
|
||||
amount: number;
|
||||
uuid: string;
|
||||
status: number;
|
||||
authority: string | null;
|
||||
ref_id: string | null;
|
||||
gateway: number;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
user: PurchaseUser | null;
|
||||
product: PurchaseProduct | null;
|
||||
}
|
||||
|
||||
// Laravel length-aware paginator envelope
|
||||
export interface Paginated<T> {
|
||||
current_page: number;
|
||||
data: T[];
|
||||
last_page: number;
|
||||
per_page: number;
|
||||
total: number;
|
||||
from: number | null;
|
||||
to: number | null;
|
||||
next_page_url: string | null;
|
||||
prev_page_url: string | null;
|
||||
}
|
||||
|
||||
// Payment source (gateway) — matches backend Transaction::GATEWAYS
|
||||
export const PAYMENT_GATEWAYS = {
|
||||
asanpardakht: { code: 1, label: 'آسانپرداخت' },
|
||||
zarinpal: { code: 2, label: 'زرینپال' },
|
||||
digipay: { code: 3, label: 'دیجیپی' },
|
||||
cafe: { code: 4, label: 'کافه بازار' },
|
||||
myket: { code: 5, label: 'مایکت' },
|
||||
} as const;
|
||||
|
||||
export type PaymentGatewayKey = keyof typeof PAYMENT_GATEWAYS;
|
||||
|
||||
export const getGatewayLabel = (gateway: number | null): string => {
|
||||
const found = Object.values(PAYMENT_GATEWAYS).find((g) => g.code === gateway);
|
||||
return found ? found.label : 'نامشخص';
|
||||
};
|
||||
|
||||
// Purchase status — matches backend Transaction::STATUSES
|
||||
export const PURCHASE_STATUSES: Record<number, string> = {
|
||||
1: 'در انتظار پرداخت',
|
||||
2: 'موفق',
|
||||
3: 'مصرفشده',
|
||||
};
|
||||
|
||||
export const getPurchaseStatusLabel = (status: number | null): string => {
|
||||
if (status === null || status === undefined) return 'نامشخص';
|
||||
return PURCHASE_STATUSES[status] || 'نامشخص';
|
||||
};
|
||||
|
||||
// Filters sent to the purchases endpoint
|
||||
export interface PurchaseFilters {
|
||||
email?: string;
|
||||
mobile?: string;
|
||||
package_name?: string;
|
||||
gateway?: string; // gateway name key (e.g. "zarinpal")
|
||||
status?: number;
|
||||
per_page?: number;
|
||||
page?: number;
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
export interface ReferralRewardUser {
|
||||
id: number;
|
||||
uuid: string;
|
||||
name: string;
|
||||
email: string | null;
|
||||
mobile: string | null;
|
||||
referral_code: string | null;
|
||||
successful_invites: number;
|
||||
}
|
||||
|
||||
export interface PendingReferralRewardsResponse {
|
||||
subscription_target: number;
|
||||
data: ReferralRewardUser[];
|
||||
}
|
||||
|
||||
export interface FulfillReferralRewardResponse {
|
||||
message: string;
|
||||
user_id?: number;
|
||||
product_id?: number;
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
export type ReminderType = 'reminder' | 'motivate';
|
||||
|
||||
export const REMINDER_TYPES = {
|
||||
reminder: 'یادآوری',
|
||||
motivate: 'انگیزشی'
|
||||
} as const;
|
||||
|
||||
export interface Reminder {
|
||||
id: number;
|
||||
title: string;
|
||||
description: string | null;
|
||||
time: string;
|
||||
repeatable: boolean;
|
||||
repeat_days: number | null;
|
||||
data: any | null;
|
||||
type: ReminderType;
|
||||
package_name?: string;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
export interface CreateReminderData {
|
||||
title: string;
|
||||
description?: string | null;
|
||||
time: string;
|
||||
repeatable?: boolean;
|
||||
repeat_days?: number | null;
|
||||
data?: any | null;
|
||||
type: ReminderType;
|
||||
}
|
||||
|
||||
export interface UpdateReminderData {
|
||||
title?: string;
|
||||
description?: string | null;
|
||||
time?: string;
|
||||
repeatable?: boolean;
|
||||
repeat_days?: number | null;
|
||||
data?: any | null;
|
||||
type?: ReminderType;
|
||||
}
|
||||
|
||||
export interface ApiResponse<T> {
|
||||
data: T;
|
||||
message?: string;
|
||||
status?: number;
|
||||
}
|
||||
|
||||
export const getReminderTypeLabel = (type: ReminderType): string => {
|
||||
return REMINDER_TYPES[type] || type;
|
||||
};
|
||||
@@ -0,0 +1,85 @@
|
||||
export interface User {
|
||||
id: number;
|
||||
first_name: string | null;
|
||||
last_name: string | null;
|
||||
email: string | null;
|
||||
mobile: string | null;
|
||||
avatar: string | null;
|
||||
uuid: string;
|
||||
is_admin: boolean;
|
||||
wallet: number;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
birthday: string | null;
|
||||
gender: string | null;
|
||||
email_verified_at: string | null;
|
||||
remember_token: string | null;
|
||||
full_name: string | null;
|
||||
products: UserProduct[];
|
||||
}
|
||||
|
||||
export interface UserProduct {
|
||||
id: number;
|
||||
package_name_id: number;
|
||||
title: string | null;
|
||||
price: number | null;
|
||||
type: number | null;
|
||||
uuid: string;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
descriptions: string[] | null;
|
||||
pivot: ProductPivot;
|
||||
package_name: PackageName | null;
|
||||
}
|
||||
|
||||
export interface ProductPivot {
|
||||
user_id: number;
|
||||
product_id: number;
|
||||
expire_at: string | null;
|
||||
purchase_token: string | null;
|
||||
gateway: string | null;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
export interface PackageName {
|
||||
id: number;
|
||||
name: string | null;
|
||||
title: string | null;
|
||||
image: string | null;
|
||||
v1_identifier: string | null;
|
||||
uuid: string;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
cafe_config_id: string | null;
|
||||
myket_access_token: string | null;
|
||||
web_app_url: string | null;
|
||||
tries: number | null;
|
||||
}
|
||||
|
||||
export interface Product {
|
||||
id: number;
|
||||
title: string | null;
|
||||
price: number | null;
|
||||
type: number | null;
|
||||
descriptions: string[] | null;
|
||||
}
|
||||
|
||||
export interface UserSearchParams {
|
||||
searchTerm: string;
|
||||
package_name: string;
|
||||
}
|
||||
|
||||
export interface UpdateUserProfileData {
|
||||
first_name?: string | null;
|
||||
last_name?: string | null;
|
||||
email?: string | null;
|
||||
mobile?: string | null;
|
||||
avatar?: File | null;
|
||||
}
|
||||
|
||||
export interface ApiResponse<T> {
|
||||
data: T;
|
||||
message?: string | null;
|
||||
status?: number | null;
|
||||
}
|
||||