feat: initial admin panel

This commit is contained in:
2026-02-19 22:13:11 +03:30
parent 70efff0dfd
commit 9aff48019d
50 changed files with 9604 additions and 1 deletions
+29 -1
View File
@@ -1 +1,29 @@
node_modules/ # Create or edit .gitignore
echo "# Next.js build output
.next/
.next/**
.next/dev/lock
# 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?" >> .gitignore
+66
View File
@@ -0,0 +1,66 @@
'use client';
import { useAuth } from '@/contexts/AuthContext';
import Link from 'next/link';
import { UsersIcon, CubeIcon, TagIcon } from '@heroicons/react/24/outline';
export default function Dashboard() {
const { user, logout } = useAuth();
return (
<div className="p-8">
<div className="max-w-7xl mx-auto">
<div className="bg-white rounded-lg shadow-lg p-6">
<div className="flex justify-between items-center mb-6">
<h1 className="text-2xl font-bold text-gray-900">
داشبورد
</h1>
<button
onClick={logout}
className="px-4 py-2 bg-red-600 text-white rounded-md hover:bg-red-700 transition-colors"
>
خروج
</button>
</div>
<div className="border-t pt-6">
<h2 className="text-lg font-semibold mb-4">خوش آمدید، {user?.email}</h2>
{/* Dashboard Cards */}
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 mt-6">
<Link href="/admin/users" className="block">
<div className="bg-indigo-50 hover:bg-indigo-100 rounded-lg p-6 transition-colors">
<UsersIcon className="h-8 w-8 text-indigo-600 mb-3" />
<h3 className="text-lg font-medium text-gray-900">مدیریت کاربران</h3>
<p className="text-sm text-gray-600 mt-1">
مشاهده و مدیریت کاربران، اشتراکها و تراکنشها
</p>
</div>
</Link>
<Link href="/admin/packages" className="block">
<div className="bg-green-50 hover:bg-green-100 rounded-lg p-6 transition-colors">
<CubeIcon className="h-8 w-8 text-green-600 mb-3" />
<h3 className="text-lg font-medium text-gray-900">مدیریت پکیجها</h3>
<p className="text-sm text-gray-600 mt-1">
ایجاد و مدیریت پکیجهای نرمافزار
</p>
</div>
</Link>
<Link href="/admin/products" className="block">
<div className="bg-purple-50 hover:bg-purple-100 rounded-lg p-6 transition-colors">
<TagIcon className="h-8 w-8 text-purple-600 mb-3" />
<h3 className="text-lg font-medium text-gray-900">مدیریت محصولات</h3>
<p className="text-sm text-gray-600 mt-1">
ایجاد و مدیریت محصولات و اشتراکها
</p>
</div>
</Link>
</div>
</div>
</div>
</div>
</div>
);
}
+17
View File
@@ -0,0 +1,17 @@
'use client';
import { AuthProvider } from '@/contexts/AuthContext';
export default function AdminLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<AuthProvider>
<div className="min-h-screen bg-gray-100">
{children}
</div>
</AuthProvider>
);
}
+111
View File
@@ -0,0 +1,111 @@
'use client';
import { useState } from 'react';
import { useAuth } from '@/contexts/AuthContext';
import { useRouter } from 'next/navigation';
import { useEffect } from 'react';
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('Please fill in all fields');
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-gray-50 py-12 px-4 sm:px-6 lg:px-8">
<div className="max-w-md w-full space-y-8">
<div>
<h2 className="mt-6 text-center text-3xl font-extrabold text-gray-900">
Admin Login
</h2>
<p className="mt-2 text-center text-sm text-gray-600">
Meditation App Admin Panel
</p>
</div>
<form className="mt-8 space-y-6" onSubmit={handleSubmit}>
<div className="rounded-md shadow-sm -space-y-px">
<div>
<label htmlFor="auth" className="sr-only">
Email
</label>
<input
id="auth"
name="auth"
type="text"
required
className="appearance-none rounded-none relative block w-full px-3 py-2 border border-gray-300 placeholder-gray-500 text-gray-900 rounded-t-md focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 focus:z-10 sm:text-sm"
placeholder="Email"
value={auth}
onChange={(e) => setAuth(e.target.value)}
disabled={isLoading}
/>
</div>
<div>
<label htmlFor="password" className="sr-only">
Password
</label>
<input
id="password"
name="password"
type="password"
required
className="appearance-none rounded-none relative block w-full px-3 py-2 border border-gray-300 placeholder-gray-500 text-gray-900 rounded-b-md focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 focus:z-10 sm:text-sm"
placeholder="Password"
value={password}
onChange={(e) => setPassword(e.target.value)}
disabled={isLoading}
/>
</div>
</div>
{(error || localError) && (
<div className="rounded-md bg-red-50 p-4">
<div className="flex">
<div className="ml-3">
<h3 className="text-sm font-medium text-red-800">
{localError || error}
</h3>
</div>
</div>
</div>
)}
<div>
<button
type="submit"
disabled={isLoading}
className="group relative w-full flex justify-center py-2 px-4 border border-transparent text-sm font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 disabled:opacity-50 disabled:cursor-not-allowed"
>
{isLoading ? 'Logging in...' : 'Sign in'}
</button>
</div>
</form>
</div>
</div>
);
}
+153
View File
@@ -0,0 +1,153 @@
'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 { 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);
const [success, setSuccess] = useState<string | null>(null);
// Load packages on mount
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);
setSuccess(null);
try {
await packagesApi.deletePackage(pkg.name!, token!);
setSuccess('پکیج با موفقیت حذف شد');
await loadPackages();
} catch (err) {
setError(err instanceof Error ? err.message : 'خطا در حذف پکیج');
} finally {
setIsLoading(false);
}
};
const handleSubmit = async (data: CreatePackageData | UpdatePackageData) => {
setIsLoading(true);
setError(null);
setSuccess(null);
try {
if (selectedPackage) {
// Update existing package
await packagesApi.updatePackage(selectedPackage.name!, data, token!);
setSuccess('پکیج با موفقیت به‌روزرسانی شد');
} else {
// Create new package
await packagesApi.createPackage(data as CreatePackageData, token!);
setSuccess('پکیج با موفقیت ایجاد شد');
}
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);
setSuccess(null);
};
return (
<div className="p-6">
<div className="max-w-7xl mx-auto">
<div className="flex justify-between items-center mb-6">
<h1 className="text-2xl font-bold text-gray-900">
مدیریت پکیجها
</h1>
{!isFormVisible && (
<button
onClick={handleCreate}
className="inline-flex items-center px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
>
<PlusIcon className="h-5 w-5 ml-2" />
پکیج جدید
</button>
)}
</div>
{/* Messages */}
{error && (
<div className="mb-4 rounded-md bg-red-50 p-4">
<p className="text-sm text-red-800">{error}</p>
</div>
)}
{success && (
<div className="mb-4 rounded-md bg-green-50 p-4">
<p className="text-sm text-green-800">{success}</p>
</div>
)}
{/* Form or List */}
{isFormVisible ? (
<PackageForm
package={selectedPackage}
onSubmit={handleSubmit}
onCancel={handleCancel}
isLoading={isLoading}
/>
) : (
<PackageList
packages={packages}
onEdit={handleEdit}
onDelete={handleDelete}
isLoading={isLoading}
/>
)}
</div>
</div>
);
}
+217
View File
@@ -0,0 +1,217 @@
'use client';
import { useState, useEffect } 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 { 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 [isFormVisible, setIsFormVisible] = useState(false);
const [error, setError] = useState<string | null>(null);
const [success, setSuccess] = useState<string | null>(null);
// Load packages on mount
useEffect(() => {
if (token) {
loadPackages();
}
}, [token]);
// Load products when package is selected
useEffect(() => {
if (selectedPackage && token) {
loadProducts(selectedPackage.name!);
} else {
setProducts([]);
}
}, [selectedPackage, token]);
const loadPackages = async () => {
try {
const data = await packagesApi.getAllPackages(token!);
setPackages(data);
if (data.length > 0 && !selectedPackage) {
setSelectedPackage(data[0]);
}
} catch (err) {
setError('خطا در دریافت لیست پکیج‌ها');
}
};
const loadProducts = async (packageName: string) => {
setIsLoading(true);
setError(null);
try {
const data = await productsApi.getProducts(packageName, token!);
setProducts(data);
} catch (err) {
setError(err instanceof Error ? err.message : 'خطا در دریافت محصولات');
} finally {
setIsLoading(false);
}
};
const handlePackageChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
const pkg = packages.find(p => p.name === e.target.value);
setSelectedPackage(pkg || null);
setIsFormVisible(false);
setSelectedProduct(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);
setSuccess(null);
try {
await productsApi.deleteProduct(selectedPackage.name!, product.id, token!);
setSuccess('محصول با موفقیت حذف شد');
await loadProducts(selectedPackage.name!);
} catch (err) {
setError(err instanceof Error ? err.message : 'خطا در حذف محصول');
} finally {
setIsLoading(false);
}
};
const handleSubmit = async (data: CreateProductData | UpdateProductData) => {
if (!selectedPackage) return;
setIsLoading(true);
setError(null);
setSuccess(null);
try {
if (selectedProduct) {
// Update existing product
await productsApi.updateProduct(selectedPackage.name!, selectedProduct.id, data, token!);
setSuccess('محصول با موفقیت به‌روزرسانی شد');
} else {
// Create new product
await productsApi.createProduct(selectedPackage.name!, data as CreateProductData, token!);
setSuccess('محصول با موفقیت ایجاد شد');
}
await loadProducts(selectedPackage.name!);
setIsFormVisible(false);
setSelectedProduct(null);
} catch (err) {
setError(err instanceof Error ? err.message : 'خطا در ذخیره محصول');
} finally {
setIsLoading(false);
}
};
const handleCancel = () => {
setIsFormVisible(false);
setSelectedProduct(null);
setError(null);
setSuccess(null);
};
return (
<div className="p-6">
<div className="max-w-7xl mx-auto">
<div className="flex justify-between items-center mb-6">
<h1 className="text-2xl font-bold text-gray-900">
مدیریت محصولات
</h1>
</div>
{/* Package Selector */}
<div className="bg-white p-4 rounded-lg shadow mb-6">
<label htmlFor="package" className="block text-sm font-medium text-gray-700 mb-2">
انتخاب پکیج
</label>
<select
id="package"
value={selectedPackage?.name || ''}
onChange={handlePackageChange}
className="block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
>
{packages.map((pkg) => (
<option key={pkg.id} value={pkg.name || ''}>
{pkg.title} ({pkg.name})
</option>
))}
</select>
</div>
{/* Messages */}
{error && (
<div className="mb-4 rounded-md bg-red-50 p-4">
<p className="text-sm text-red-800">{error}</p>
</div>
)}
{success && (
<div className="mb-4 rounded-md bg-green-50 p-4">
<p className="text-sm text-green-800">{success}</p>
</div>
)}
{/* Form or List */}
{selectedPackage && (
<>
{!isFormVisible && (
<div className="mb-4 flex justify-end">
<button
onClick={handleCreate}
className="inline-flex items-center px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
>
<PlusIcon className="h-5 w-5 ml-2" />
محصول جدید
</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>
);
}
+280
View File
@@ -0,0 +1,280 @@
'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 PackageSelector from '@/components/admin/users/PackageSelector';
import { User, Product } from '@/types/user';
import { PackageName } from '@/types/package';
import { formatPrice, getProductTypeLabel } from '@/lib/utils';
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 [success, setSuccess] = useState<string | null>(null);
// Load packages on mount
useEffect(() => {
if (token) {
loadPackages();
}
}, [token]);
// Load products when package changes
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 {
console.log('Loading products for package:', packageName);
const data = await usersApi.getProductsByPackage(packageName, token!);
console.log('Products loaded:', data);
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 {
console.log('Searching for user:', searchTerm, 'in package:', selectedPackage);
const userData = await usersApi.getUserStatus(searchTerm, selectedPackage, token!);
console.log('User data:', userData);
setUser(userData);
} catch (err) {
setError(err instanceof Error ? err.message : 'خطا در دریافت اطلاعات کاربر');
} finally {
setIsLoading(false);
}
};
const handleSubscribe = async (productId: number) => {
if (!user) return;
// Get identifier (email or mobile) with null check
const identifier = user.email || user.mobile;
if (!identifier) {
setError('کاربر فاقد ایمیل یا شماره موبایل است');
return;
}
setIsLoading(true);
setError(null);
setSuccess(null);
try {
console.log('Subscribing user:', identifier, 'to product:', productId);
await usersApi.subscribeUser(identifier, productId, token!);
setSuccess('اشتراک با موفقیت اضافه شد');
// Refresh user data with current selected package
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;
// Get identifier (email or mobile) with null check
const identifier = user.email || user.mobile;
if (!identifier) {
setError('کاربر فاقد ایمیل یا شماره موبایل است');
return;
}
setIsLoading(true);
setError(null);
setSuccess(null);
try {
console.log('Unsubscribing user:', identifier, 'from product:', productId);
await usersApi.unsubscribeUser(identifier, productId, token!);
setSuccess('اشتراک با موفقیت لغو شد');
// Refresh user data with current selected package
if (selectedPackage) {
const userData = await usersApi.getUserStatus(identifier, selectedPackage, token!);
setUser(userData);
}
} catch (err) {
setError(err instanceof Error ? err.message : 'خطا در لغو اشتراک');
} finally {
setIsLoading(false);
}
};
const handlePackageChange = (packageName: string) => {
console.log('Package changed to:', packageName);
setSelectedPackage(packageName);
// Clear user when package changes to avoid showing wrong data
setUser(null);
setError(null);
setSuccess(null);
};
// Filter available products (show ALL products, don't filter out ones user already has)
const availableProducts = products;
console.log('Current state:', {
selectedPackage,
productsCount: products.length,
userProductsCount: user?.products?.length,
availableProductsCount: availableProducts.length
});
return (
<div className="p-6">
<div className="max-w-7xl mx-auto">
<h1 className="text-2xl font-bold text-gray-900 mb-6">
مدیریت کاربران
</h1>
{/* Package Selector */}
{token && (
<PackageSelector
token={token}
selectedPackage={selectedPackage}
onPackageChange={handlePackageChange}
isLoading={isLoading}
/>
)}
{/* Search Section - Only show if package is selected */}
{selectedPackage && (
<UserSearch onSearch={handleSearch} isLoading={isLoading} />
)}
{/* Messages */}
{error && (
<div className="mb-4 rounded-md bg-red-50 p-4">
<div className="flex">
<div className="flex-shrink-0">
<svg className="h-5 w-5 text-red-400" 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>
</div>
<div className="mr-3">
<p className="text-sm text-red-800">{error}</p>
</div>
</div>
</div>
)}
{success && (
<div className="mb-4 rounded-md bg-green-50 p-4">
<div className="flex">
<div className="flex-shrink-0">
<svg className="h-5 w-5 text-green-400" viewBox="0 0 20 20" fill="currentColor">
<path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clipRule="evenodd" />
</svg>
</div>
<div className="mr-3">
<p className="text-sm text-green-800">{success}</p>
</div>
</div>
</div>
)}
{/* No Package Selected Message */}
{!selectedPackage && packages.length === 0 && (
<div className="text-center py-12 bg-white rounded-lg shadow">
<p className="text-gray-500">هیچ پکیجی یافت نشد. ابتدا یک پکیج ایجاد کنید.</p>
</div>
)}
{/* Show products list even without user */}
{selectedPackage && products.length > 0 && !user && (
<div className="mb-6">
<div className="bg-white shadow overflow-hidden sm:rounded-lg">
<div className="px-4 py-5 sm:px-6">
<h3 className="text-lg leading-6 font-medium text-gray-900">
محصولات موجود در پکیج {selectedPackage}
</h3>
</div>
<div className="border-t border-gray-200 px-4 py-5 sm:px-6">
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-3">
{products.map((product) => (
<div
key={product.id}
className="relative block w-full border border-gray-200 rounded-lg p-4 text-right bg-gray-50"
>
<p className="text-sm font-medium text-gray-900">
{product.title || 'محصول'}
</p>
<p className="mt-1 text-xs text-gray-500">
قیمت: {formatPrice(product.price)} تومان
</p>
<p className="text-xs text-gray-500">
نوع: {getProductTypeLabel(product.type)}
</p>
</div>
))}
</div>
<p className="mt-4 text-sm text-gray-500 text-center">
برای افزودن اشتراک به کاربر، ابتدا یک کاربر جستجو کنید
</p>
</div>
</div>
</div>
)}
{/* User Info */}
{user && <UserInfo user={user} />}
{/* User Products */}
{user && selectedPackage && (
<UserProducts
products={user.products || []}
availableProducts={availableProducts}
onSubscribe={handleSubscribe}
onUnsubscribe={handleUnsubscribe}
isLoading={isLoading}
selectedPackage={selectedPackage}
/>
)}
</div>
</div>
);
}
+69
View File
@@ -0,0 +1,69 @@
@import "tailwindcss";
@tailwind utilities;
/* @import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap'); */
@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: #1f298;
}
/* 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: #ffffff;
--foreground: #171717;
}
@theme inline {
--color-background: var(--background);
--color-foreground: var(--foreground);
--font-sans: 'Dana', 'Inter', var(--font-geist-sans);
--font-mono: var(--font-geist-mono);
}
@media (prefers-color-scheme: dark) {
:root {
--background: #0a0a0a;
--foreground: #ededed;
}
}
body {
background: var(--background);
color: var(--foreground);
font-family: 'Dana', 'Inter', Arial, Helvetica, sans-serif;
font-weight: 400;
}
+47
View File
@@ -0,0 +1,47 @@
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">
<head>
<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>
);
}
+14
View File
@@ -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]);
}
+290
View File
@@ -0,0 +1,290 @@
'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 }));
// Create preview
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 }));
};
return (
<form onSubmit={handleSubmit} className="space-y-6 bg-white p-6 rounded-lg shadow">
<div className="grid grid-cols-1 gap-6 md:grid-cols-2">
{/* Name */}
<div>
<label htmlFor="name" className="block text-sm font-medium text-gray-700 mb-1">
نام پکیج <span className="text-red-500">*</span>
</label>
<input
type="text"
id="name"
name="name"
required
value={formData.name || ''}
onChange={handleInputChange}
className="block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
placeholder="مثال: com.approagency.meditation"
dir="ltr"
/>
</div>
{/* Title */}
<div>
<label htmlFor="title" className="block text-sm font-medium text-gray-700 mb-1">
عنوان <span className="text-red-500">*</span>
</label>
<input
type="text"
id="title"
name="title"
required
value={formData.title || ''}
onChange={handleInputChange}
className="block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
placeholder="مثال: آرام لند"
/>
</div>
{/* Avatar */}
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">
تصویر
</label>
<div className="flex items-center space-x-3 space-x-reverse">
<label className="cursor-pointer flex items-center px-4 py-2 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50">
<PhotoIcon className="h-5 w-5 ml-2 text-gray-400" />
انتخاب تصویر
<input
type="file"
accept="image/*"
onChange={handleAvatarChange}
className="hidden"
/>
</label>
{avatarPreview && (
<button
type="button"
onClick={removeAvatar}
className="text-red-600 hover:text-red-900"
>
<XMarkIcon className="h-5 w-5" />
</button>
)}
</div>
{avatarPreview && (
<div className="mt-2">
<img
src={avatarPreview}
alt="Preview"
className="h-20 w-20 object-cover rounded-lg border border-gray-200"
/>
</div>
)}
</div>
{/* V1 Identifier */}
<div>
<label htmlFor="v1_identifier" className="block text-sm font-medium text-gray-700 mb-1">
شناسه V1
</label>
<input
type="text"
id="v1_identifier"
name="v1_identifier"
value={formData.v1_identifier || ''}
onChange={handleInputChange}
className="block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
/>
</div>
{/* Myket Access Token */}
<div>
<label htmlFor="myket_access_token" className="block text-sm font-medium text-gray-700 mb-1">
توکن دسترسی Myket
</label>
<input
type="text"
id="myket_access_token"
name="myket_access_token"
value={formData.myket_access_token || ''}
onChange={handleInputChange}
className="block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
/>
</div>
{/* Cafe Config ID */}
<div>
<label htmlFor="cafe_config_id" className="block text-sm font-medium text-gray-700 mb-1">
شناسه کافه بازار
</label>
<input
type="number"
id="cafe_config_id"
name="cafe_config_id"
value={formData.cafe_config_id || ''}
onChange={handleNumberChange}
className="block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
/>
</div>
{/* Web App URL */}
<div>
<label htmlFor="web_app_url" className="block text-sm font-medium text-gray-700 mb-1">
آدرس وب اپلیکیشن
</label>
<input
type="url"
id="web_app_url"
name="web_app_url"
value={formData.web_app_url || ''}
onChange={handleInputChange}
className="block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
placeholder="https://example.com"
/>
</div>
{/* Tries */}
<div>
<label htmlFor="tries" className="block text-sm font-medium text-gray-700 mb-1">
تعداد تلاشها
</label>
<input
type="number"
id="tries"
name="tries"
value={formData.tries || 0}
onChange={handleNumberChange}
className="block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
/>
</div>
{/* Firebase JSON */}
<div className="md:col-span-2">
<label className="block text-sm font-medium text-gray-700 mb-1">
فایل Firebase JSON
</label>
<label className="cursor-pointer inline-flex items-center px-4 py-2 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50">
<DocumentTextIcon className="h-5 w-5 ml-2 text-gray-400" />
انتخاب فایل
<input
type="file"
accept=".json,application/json"
onChange={handleFirebaseChange}
className="hidden"
/>
</label>
{firebaseFile && (
<p className="mt-2 text-sm text-gray-600">
فایل انتخاب شده: {firebaseFile.name}
</p>
)}
</div>
</div>
{/* Form Actions */}
<div className="flex justify-end space-x-3 space-x-reverse pt-4 border-t">
<button
type="button"
onClick={onCancel}
className="px-4 py-2 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
>
انصراف
</button>
<button
type="submit"
disabled={isLoading}
className="px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 disabled:opacity-50"
>
{isLoading ? 'در حال ذخیره...' : pkg ? 'به‌روزرسانی' : 'ایجاد'}
</button>
</div>
</form>
);
}
+89
View File
@@ -0,0 +1,89 @@
'use client';
import { PackageName } from '@/types/package';
import { PencilIcon, TrashIcon } from '@heroicons/react/24/outline';
import { formatDate } from '@/lib/utils';
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-12">
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-indigo-600"></div>
</div>
);
}
if (!packages || packages.length === 0) {
return (
<div className="text-center py-12 bg-white rounded-lg shadow">
<p className="text-gray-500">هیچ پکیجی یافت نشد</p>
</div>
);
}
return (
<div className="bg-white shadow overflow-hidden sm:rounded-lg">
<ul className="divide-y divide-gray-200">
{packages.map((pkg) => (
<li key={pkg.id} className="px-6 py-4 hover:bg-gray-50">
<div className="flex items-center justify-between">
<div className="flex-1 min-w-0">
<div className="flex items-center space-x-3 space-x-reverse">
{pkg.image && typeof pkg.image === 'string' && (
<img
src={pkg.image}
alt={pkg.title || ''}
className="h-10 w-10 rounded-full object-cover"
/>
)}
<div>
<p className="text-sm font-medium text-indigo-600 truncate">
{pkg.title || 'بدون عنوان'}
</p>
<p className="text-sm text-gray-500">
{pkg.name || 'بدون نام'}
</p>
</div>
</div>
<div className="mt-2 sm:flex sm:justify-between">
<div className="sm:flex sm:space-x-4 sm:space-x-reverse">
<p className="text-xs text-gray-500">
شناسه: {pkg.uuid?.substring(0, 8)}...
</p>
<p className="text-xs text-gray-500 mt-1 sm:mt-0">
تلاشها: {pkg.tries || 0}
</p>
</div>
<p className="text-xs text-gray-500 mt-1 sm:mt-0">
آخرین بهروزرسانی: {formatDate(pkg.updated_at)}
</p>
</div>
</div>
<div className="mr-4 flex-shrink-0 flex space-x-2 space-x-reverse">
<button
onClick={() => onEdit(pkg)}
className="text-indigo-600 hover:text-indigo-900 p-2 rounded-full hover:bg-indigo-50"
>
<PencilIcon className="h-5 w-5" />
</button>
<button
onClick={() => onDelete(pkg)}
className="text-red-600 hover:text-red-900 p-2 rounded-full hover:bg-red-50"
>
<TrashIcon className="h-5 w-5" />
</button>
</div>
</div>
</li>
))}
</ul>
</div>
);
}
+198
View File
@@ -0,0 +1,198 @@
'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, // Default to monthly
});
const [descriptions, setDescriptions] = useState<string[]>([]);
const [newDescription, setNewDescription] = useState('');
useEffect(() => {
if (product) {
setFormData({
title: product.title || '',
price: product.price || 0,
type: product.type || 4,
});
setDescriptions(product.descriptions || []);
}
}, [product]);
const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) => {
const { name, value } = e.target;
setFormData(prev => ({
...prev,
[name]: name === 'price' ? 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);
};
return (
<form onSubmit={handleSubmit} className="space-y-6 bg-white p-6 rounded-lg shadow">
<div>
<h3 className="text-lg font-medium text-gray-900 mb-4">
{product ? 'ویرایش محصول' : 'ایجاد محصول جدید'} برای پکیج {packageName}
</h3>
</div>
<div className="grid grid-cols-1 gap-6 md:grid-cols-2">
{/* Title */}
<div>
<label htmlFor="title" className="block text-sm font-medium text-gray-700 mb-1">
عنوان <span className="text-red-500">*</span>
</label>
<input
type="text"
id="title"
name="title"
required
value={formData.title || ''}
onChange={handleInputChange}
className="block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
placeholder="مثال: اشتراک ماهانه"
/>
</div>
{/* Price */}
<div>
<label htmlFor="price" className="block text-sm font-medium text-gray-700 mb-1">
قیمت (تومان) <span className="text-red-500">*</span>
</label>
<input
type="number"
id="price"
name="price"
required
min="0"
value={formData.price || ''}
onChange={handleInputChange}
className="block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
placeholder="مثال: 60000"
/>
</div>
{/* Type */}
<div>
<label htmlFor="type" className="block text-sm font-medium text-gray-700 mb-1">
نوع اشتراک <span className="text-red-500">*</span>
</label>
<select
id="type"
name="type"
required
value={formData.type || 4}
onChange={handleInputChange}
className="block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
>
{Object.entries(PRODUCT_TYPES).map(([value, label]) => (
<option key={value} value={value}>
{label}
</option>
))}
</select>
</div>
</div>
{/* Descriptions */}
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">
ویژگیها
</label>
<div className="flex space-x-2 space-x-reverse">
<input
type="text"
value={newDescription}
onChange={(e) => setNewDescription(e.target.value)}
className="flex-1 px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
placeholder="ویژگی جدید را وارد کنید"
onKeyPress={(e) => {
if (e.key === 'Enter') {
e.preventDefault();
handleAddDescription();
}
}}
/>
<button
type="button"
onClick={handleAddDescription}
className="inline-flex items-center px-3 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
>
<PlusIcon className="h-5 w-5" />
</button>
</div>
{/* Descriptions List */}
{descriptions.length > 0 && (
<ul className="mt-3 space-y-2">
{descriptions.map((desc, index) => (
<li key={index} className="flex items-center justify-between bg-gray-50 px-3 py-2 rounded-md">
<span className="text-sm text-gray-700">{desc}</span>
<button
type="button"
onClick={() => handleRemoveDescription(index)}
className="text-red-600 hover:text-red-900"
>
<XMarkIcon className="h-5 w-5" />
</button>
</li>
))}
</ul>
)}
</div>
{/* Form Actions */}
<div className="flex justify-end space-x-3 space-x-reverse pt-4 border-t">
<button
type="button"
onClick={onCancel}
className="px-4 py-2 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
>
انصراف
</button>
<button
type="submit"
disabled={isLoading}
className="px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 disabled:opacity-50"
>
{isLoading ? 'در حال ذخیره...' : product ? 'به‌روزرسانی' : 'ایجاد'}
</button>
</div>
</form>
);
}
+92
View File
@@ -0,0 +1,92 @@
'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-12">
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-indigo-600"></div>
</div>
);
}
if (!products || products.length === 0) {
return (
<div className="text-center py-12 bg-white rounded-lg shadow">
<p className="text-gray-500">هیچ محصولی برای این پکیج یافت نشد</p>
</div>
);
}
return (
<div className="bg-white shadow overflow-hidden sm:rounded-lg">
<div className="px-4 py-5 sm:px-6">
<h3 className="text-lg leading-6 font-medium text-gray-900">
محصولات پکیج {packageName}
</h3>
</div>
<ul className="divide-y divide-gray-200">
{products.map((product) => (
<li key={product.id} className="px-6 py-4 hover:bg-gray-50">
<div className="flex items-center justify-between">
<div className="flex-1 min-w-0">
<div className="flex items-center justify-between">
<p className="text-sm font-medium text-indigo-600 truncate">
{product.title || 'بدون عنوان'}
</p>
<span className="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-blue-100 text-blue-800">
{getProductTypeLabel(product.type)}
</span>
</div>
<div className="mt-2">
<p className="text-sm text-gray-900">
قیمت: {formatPrice(product.price)} تومان
</p>
{product.descriptions && product.descriptions.length > 0 && (
<div className="mt-2">
<p className="text-xs text-gray-500 mb-1">ویژگیها:</p>
<ul className="list-disc list-inside text-xs text-gray-600 pr-4">
{product.descriptions.map((desc, index) => (
<li key={index}>{desc}</li>
))}
</ul>
</div>
)}
</div>
<div className="mt-2 text-xs text-gray-500">
آخرین بهروزرسانی: {formatDate(product.updated_at)}
</div>
</div>
<div className="mr-4 flex-shrink-0 flex space-x-2 space-x-reverse">
<button
onClick={() => onEdit(product)}
className="text-indigo-600 hover:text-indigo-900 p-2 rounded-full hover:bg-indigo-50"
>
<PencilIcon className="h-5 w-5" />
</button>
<button
onClick={() => onDelete(product)}
className="text-red-600 hover:text-red-900 p-2 rounded-full hover:bg-red-50"
>
<TrashIcon className="h-5 w-5" />
</button>
</div>
</div>
</li>
))}
</ul>
</div>
);
}
@@ -0,0 +1,67 @@
'use client';
import { PackageName } from '@/types/package';
import { useState, useEffect } from 'react';
import { packagesApi } from '@/lib/api/packages';
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);
// Select first package if none selected
if (data.length > 0 && !selectedPackage) {
onPackageChange(data[0].name!);
}
} catch (error) {
console.error('Failed to load packages:', error);
} finally {
setLoading(false);
}
};
const handleChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
onPackageChange(e.target.value);
};
return (
<div className="bg-white p-4 rounded-lg shadow mb-6">
<label htmlFor="package-select" className="block text-sm font-medium text-gray-700 mb-2">
انتخاب پکیج
</label>
<select
id="package-select"
value={selectedPackage || ''}
onChange={handleChange}
disabled={loading || isLoading}
className="block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm disabled:opacity-50"
>
{loading ? (
<option>در حال بارگذاری...</option>
) : (
packages.map((pkg) => (
<option key={pkg.id} value={pkg.name || ''}>
{pkg.title} ({pkg.name})
</option>
))
)}
</select>
</div>
);
}
+76
View File
@@ -0,0 +1,76 @@
'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) {
return (
<div className="bg-white shadow overflow-hidden sm:rounded-lg mb-6">
<div className="px-4 py-5 sm:px-6">
<h3 className="text-lg leading-6 font-medium text-gray-900">
اطلاعات کاربر
</h3>
</div>
<div className="border-t border-gray-200">
<dl>
<div className="bg-gray-50 px-4 py-5 sm:grid sm:grid-cols-3 sm:gap-4 sm:px-6">
<dt className="text-sm font-medium text-gray-500">نام کامل</dt>
<dd className="mt-1 text-sm text-gray-900 sm:mt-0 sm:col-span-2 flex items-center">
<UserIcon className="h-4 w-4 ml-1 text-gray-400" />
{getFullName(user)}
</dd>
</div>
<div className="bg-white px-4 py-5 sm:grid sm:grid-cols-3 sm:gap-4 sm:px-6">
<dt className="text-sm font-medium text-gray-500">ایمیل</dt>
<dd className="mt-1 text-sm text-gray-900 sm:mt-0 sm:col-span-2 flex items-center">
<EnvelopeIcon className="h-4 w-4 ml-1 text-gray-400" />
{getEmail(user.email)}
</dd>
</div>
<div className="bg-gray-50 px-4 py-5 sm:grid sm:grid-cols-3 sm:gap-4 sm:px-6">
<dt className="text-sm font-medium text-gray-500">شماره موبایل</dt>
<dd className="mt-1 text-sm text-gray-900 sm:mt-0 sm:col-span-2 flex items-center">
<PhoneIcon className="h-4 w-4 ml-1 text-gray-400" />
{getMobile(user.mobile)}
</dd>
</div>
<div className="bg-white px-4 py-5 sm:grid sm:grid-cols-3 sm:gap-4 sm:px-6">
<dt className="text-sm font-medium text-gray-500">کیف پول</dt>
<dd className="mt-1 text-sm text-gray-900 sm:mt-0 sm:col-span-2 flex items-center">
<WalletIcon className="h-4 w-4 ml-1 text-gray-400" />
{formatPrice(user.wallet)} تومان
</dd>
</div>
<div className="bg-gray-50 px-4 py-5 sm:grid sm:grid-cols-3 sm:gap-4 sm:px-6">
<dt className="text-sm font-medium text-gray-500">تاریخ عضویت</dt>
<dd className="mt-1 text-sm text-gray-900 sm:mt-0 sm:col-span-2 flex items-center">
<CalendarIcon className="h-4 w-4 ml-1 text-gray-400" />
{formatDate(user.created_at)}
</dd>
</div>
{user.birthday && (
<div className="bg-white px-4 py-5 sm:grid sm:grid-cols-3 sm:gap-4 sm:px-6">
<dt className="text-sm font-medium text-gray-500">تاریخ تولد</dt>
<dd className="mt-1 text-sm text-gray-900 sm:mt-0 sm:col-span-2">
{formatDate(user.birthday)}
</dd>
</div>
)}
{user.gender && (
<div className="bg-gray-50 px-4 py-5 sm:grid sm:grid-cols-3 sm:gap-4 sm:px-6">
<dt className="text-sm font-medium text-gray-500">جنسیت</dt>
<dd className="mt-1 text-sm text-gray-900 sm:mt-0 sm:col-span-2">
{user.gender === 'male' ? 'مرد' : user.gender === 'female' ? 'زن' : user.gender}
</dd>
</div>
)}
</dl>
</div>
</div>
);
}
+195
View File
@@ -0,0 +1,195 @@
'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: 'text-gray-600',
icon: XCircleIcon
};
}
const expireDate = new Date(product.pivot.expire_at);
const now = new Date();
const isActive = expireDate > now;
return {
isActive,
text: isActive ? 'فعال' : 'منقضی شده',
color: isActive ? 'text-green-600' : 'text-red-600',
icon: isActive ? CheckCircleIcon : XCircleIcon
};
};
// Get count of subscriptions for a specific product
const getSubscriptionCount = (productId: number): number => {
return products.filter(p => p.id === productId).length;
};
// Group products by package
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 shadow overflow-hidden sm:rounded-lg">
<div className="px-4 py-5 sm:px-6">
<h3 className="text-lg leading-6 font-medium text-gray-900">
اشتراکهای کاربر
</h3>
</div>
{/* Current Subscriptions grouped by package */}
<div className="border-t border-gray-200">
{Object.keys(productsByPackage).length > 0 ? (
Object.entries(productsByPackage).map(([packageName, packageProducts]) => (
<div key={packageName} className="border-b border-gray-200 last:border-b-0">
<div className="bg-gray-50 px-4 py-2">
<h4 className="text-sm font-medium text-gray-700">
پکیج: {packageName}
</h4>
</div>
<ul className="divide-y divide-gray-200">
{packageProducts.map((product) => {
const status = getSubscriptionStatus(product);
const StatusIcon = status.icon;
const subscriptionCount = getSubscriptionCount(product.id);
return (
<li key={`${product.id}-${product.pivot?.purchase_token || Math.random()}`} className="px-4 py-4 sm:px-6">
<div className="flex items-center justify-between">
<div className="flex-1">
<div className="flex items-center justify-between">
<div className="flex items-center space-x-2 space-x-reverse">
<p className="text-sm font-medium text-indigo-600 truncate">
{product.title || 'محصول'}
</p>
{subscriptionCount > 1 && (
<span className="px-2 py-1 text-xs bg-gray-100 text-gray-600 rounded-full">
{subscriptionCount} اشتراک
</span>
)}
</div>
<div className="mr-2 flex-shrink-0 flex">
<p className={`px-2 inline-flex text-xs leading-5 font-semibold rounded-full ${status.isActive ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'}`}>
<StatusIcon className={`h-4 w-4 ml-1 ${status.color}`} />
{status.text}
</p>
</div>
</div>
<div className="mt-2 sm:flex sm:justify-between">
<div className="sm:flex">
<p className="flex items-center text-sm text-gray-500">
قیمت: {formatPrice(product.price)} تومان
</p>
<p className="mt-2 flex items-center text-sm text-gray-500 sm:mt-0 sm:mr-6">
نوع: {getProductTypeLabel(product.type)}
</p>
{product.pivot?.expire_at && (
<p className="mt-2 flex items-center text-sm text-gray-500 sm:mt-0 sm:mr-6">
تاریخ انقضا: {formatDate(product.pivot.expire_at)}
</p>
)}
</div>
<div className="mt-2 flex items-center text-sm text-gray-500 sm:mt-0">
<button
onClick={() => onUnsubscribe(product.id)}
disabled={isLoading}
className="text-red-600 hover:text-red-900 disabled:opacity-50"
>
لغو اشتراک
</button>
</div>
</div>
</div>
</div>
</li>
);
})}
</ul>
</div>
))
) : (
<div className="px-4 py-5 sm:px-6 text-center text-gray-500">
کاربر هیچ اشتراکی ندارد
</div>
)}
</div>
{/* Available Products for Subscription */}
{availableProducts && availableProducts.length > 0 && selectedPackage && (
<div className="border-t border-gray-200 px-4 py-5 sm:px-6">
<h4 className="text-md font-medium text-gray-900 mb-3">
افزودن اشتراک جدید برای پکیج {selectedPackage}
</h4>
<div className="grid grid-cols-1 gap-3 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="relative block w-full border-2 border-indigo-200 rounded-lg p-4 text-right hover:border-indigo-500 hover:bg-indigo-50 disabled:opacity-50 disabled:cursor-not-allowed transition-all"
>
<div className="flex items-start justify-between">
<div>
<p className="text-sm font-medium text-gray-900">
{product.title || 'محصول'}
</p>
{subscriptionCount > 0 && (
<p className="mt-1 text-xs text-amber-600">
{subscriptionCount} اشتراک فعال دارد
</p>
)}
</div>
<PlusCircleIcon className="h-5 w-5 text-indigo-600" />
</div>
<p className="mt-2 text-xs text-gray-500">
برای افزودن اشتراک جدید کلیک کنید
</p>
</button>
);
})}
</div>
</div>
)}
</div>
);
}
+53
View File
@@ -0,0 +1,53 @@
'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 (
<form onSubmit={handleSubmit} className="mb-6">
<div className="flex gap-2">
<div className="flex-1">
<label htmlFor="search" className="sr-only">
جستجو با ایمیل یا شماره موبایل
</label>
<div className="relative">
<div className="absolute inset-y-0 right-0 flex items-center pr-3 pointer-events-none">
<MagnifyingGlassIcon className="h-5 w-5 text-gray-400" />
</div>
<input
type="text"
id="search"
className="block w-full pr-10 pl-3 py-2 border border-gray-300 rounded-md leading-5 bg-white placeholder-gray-500 focus:outline-none focus:placeholder-gray-400 focus:ring-1 focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
placeholder="جستجو با ایمیل یا شماره موبایل..."
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
dir="rtl"
/>
</div>
</div>
<button
type="submit"
disabled={isLoading || !searchTerm.trim()}
className="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 disabled:opacity-50 disabled:cursor-not-allowed"
>
{isLoading ? 'در حال جستجو...' : 'جستجو'}
</button>
</div>
</form>
);
}
+127
View File
@@ -0,0 +1,127 @@
'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);
}
}
localStorage.removeItem('auth_token');
localStorage.removeItem('auth_user');
setState({
user: null,
token: null,
isLoading: false,
error: null,
});
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;
}
+21
View File
@@ -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.post('/auth/logout', {}, token);
},
getProfile: async (token: string): Promise<any> => {
return apiClient.get('/auth/profile', token);
},
};
+104
View File
@@ -0,0 +1,104 @@
const API_BASE_URL = process.env.NEXT_PUBLIC_API_URL || 'https://api.approagency.ir/api';
interface ApiOptions extends RequestInit {
token?: string;
}
class ApiClient {
private async request<T>(
endpoint: string,
options: ApiOptions = {}
): Promise<T> {
const { token, ...fetchOptions } = options;
const headers: Record<string, string> = {
...(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}`;
}
const response = await fetch(`${API_BASE_URL}${endpoint}`, {
...fetchOptions,
headers,
});
if (!response.ok) {
const error = await response.json().catch(() => ({}));
throw new Error(error.message || 'API request failed');
}
return response.json();
}
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 delete<T>(endpoint: string, data?: any, token?: string): Promise<T> {
const options: ApiOptions = {
method: 'DELETE',
token,
};
// Handle DELETE with body if data is provided
if (data) {
options.body = data instanceof FormData ? data : JSON.stringify(data);
// Don't set Content-Type for FormData
if (!(data instanceof FormData)) {
options.headers = {
'Content-Type': 'application/json',
};
}
}
return this.request<T>(endpoint, options);
}
// Convenience method for DELETE with JSON body
async deleteWithBody<T>(endpoint: string, data: any, token?: string): Promise<T> {
return this.delete<T>(endpoint, data, 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,
});
}
}
export const apiClient = new ApiClient();
+78
View File
@@ -0,0 +1,78 @@
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
formData.append('_method', 'PUT');
// 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);
}
};
+69
View File
@@ -0,0 +1,69 @@
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 {
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 {
formData.append(key, String(value));
}
}
});
return apiClient.post<ApiResponse<Product>>(`/package-names/${packageName}/products/${productId}`, formData, token);
}
};
+51
View File
@@ -0,0 +1,51 @@
import { apiClient } from './client';
import { User, Product, ApiResponse } 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);
}
};
+52
View File
@@ -0,0 +1,52 @@
import { User } from "@/types/user";
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 getProductTypeLabel = (type: number | null): string => {
const types: Record<number, string> = {
1: 'ماهیانه',
2: 'سه ماهه',
3: 'شش ماهه',
4: 'سالیانه',
};
return type && types[type] ? types[type] : 'نامشخص';
};
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 || 'شماره موبایل ثبت نشده';
};
+30
View File
@@ -0,0 +1,30 @@
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
export function middleware(request: NextRequest) {
const token = request.cookies.get('auth_token')?.value ||
request.headers.get('authorization')?.replace('Bearer ', '');
const isAdminRoute = request.nextUrl.pathname.startsWith('/admin');
const isLoginRoute = request.nextUrl.pathname === '/admin/login';
// Allow access to login page without token
if (isLoginRoute) {
// If already logged in, redirect to dashboard
if (token) {
return NextResponse.redirect(new URL('/admin/dashboard', request.url));
}
return NextResponse.next();
}
// Protect admin routes
if (isAdminRoute && !token) {
return NextResponse.redirect(new URL('/admin/login', request.url));
}
return NextResponse.next();
}
export const config = {
matcher: '/admin/:path*',
};
+6
View File
@@ -0,0 +1,6 @@
/// <reference types="next" />
/// <reference types="next/image-types/global" />
import "./.next/dev/types/routes.d.ts";
// NOTE: This file should not be edited
// see https://nextjs.org/docs/app/api-reference/config/typescript for more information.
+6687
View File
File diff suppressed because it is too large Load Diff
+31
View File
@@ -0,0 +1,31 @@
{
"name": "approagency admin pannel",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "eslint"
},
"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"
}
}
+9
View File
@@ -0,0 +1,9 @@
// postcss.config.mjs
const config = {
plugins: {
"@tailwindcss/postcss": {}, // ✅ correct for Tailwind 4
autoprefixer: {},
},
};
export default config;
Binary file not shown.

After

Width:  |  Height:  |  Size: 4.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 677 KiB

+1
View File
@@ -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

Binary file not shown.
Binary file not shown.
Binary file not shown.
+1
View File
@@ -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

Binary file not shown.

After

Width:  |  Height:  |  Size: 676 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 68 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

+1
View File
@@ -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

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 MiB

+1
View File
@@ -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

+1
View File
@@ -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

+35
View File
@@ -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;
+42
View File
@@ -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"
]
}
+26
View File
@@ -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;
}
+45
View File
@@ -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;
}
+46
View File
@@ -0,0 +1,46 @@
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;
}
export interface CreateProductData {
title: string;
price: number;
type: number;
descriptions?: string[];
}
export interface UpdateProductData {
title?: string;
price?: number;
type?: number;
descriptions?: string[];
}
export interface ApiResponse<T> {
data: T;
message?: string;
status?: number;
}
// Product types mapping
export const PRODUCT_TYPES = {
1: 'دائمی',
2: 'سالیانه',
3: '۶ ماهه',
4: 'ماهیانه'
} 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] || 'نامشخص';
};
+77
View File
@@ -0,0 +1,77 @@
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 ApiResponse<T> {
data: T;
message?: string | null;
status?: number | null;
}