feat: add refferal feature

This commit is contained in:
2026-06-06 13:50:06 +03:30
parent 577d8afb53
commit 754c1c3178
10 changed files with 526 additions and 4 deletions
+10 -1
View File
@@ -2,7 +2,7 @@
import { useAuth } from '@/contexts/AuthContext';
import Link from 'next/link';
import { UsersIcon, CubeIcon, TagIcon , BellIcon } from '@heroicons/react/24/outline';
import { UsersIcon, CubeIcon, TagIcon , BellIcon, GiftIcon } from '@heroicons/react/24/outline';
import { MegaphoneIcon } from 'lucide-react';
// import { BellIcon } from 'lucide-react';
@@ -77,6 +77,15 @@ export default function Dashboard() {
</p>
</div>
</Link>
<Link href="/admin/referral-rewards" className="block">
<div className="bg-emerald-50 hover:bg-emerald-100 rounded-lg p-6 transition-colors">
<GiftIcon className="h-8 w-8 text-emerald-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>
+116
View File
@@ -0,0 +1,116 @@
'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 { 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 [success, setSuccess] = 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);
setSuccess(null);
try {
await referralApi.fulfillReward(user.id, token!);
setSuccess(`اشتراک رایگان با موفقیت به «${user.name || user.mobile || user.email}» اعطا شد`);
// Remove the fulfilled user from the list and refresh
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-6">
<div className="max-w-7xl mx-auto">
<div className="flex justify-between items-center mb-6">
<div>
<h1 className="text-2xl font-bold text-gray-900">
پاداشهای معرفی
</h1>
<p className="text-sm text-gray-500 mt-1">
کاربرانی که به حد نصاب دعوت موفق رسیدهاند و هنوز اشتراک رایگان دریافت نکردهاند.
</p>
</div>
<button
onClick={loadRewards}
disabled={isLoading}
className="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 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 disabled:opacity-50"
>
<ArrowPathIcon className={`h-5 w-5 ml-2 ${isLoading ? 'animate-spin' : ''}`} />
بروزرسانی
</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>
)}
{isLoading && users.length === 0 ? (
<div className="text-center py-12 bg-white rounded-lg shadow">
<p className="text-gray-500">در حال بارگذاری...</p>
</div>
) : (
<ReferralList
users={users}
subscriptionTarget={subscriptionTarget}
onFulfill={handleFulfill}
isLoading={isLoading}
fulfillingId={fulfillingId}
/>
)}
</div>
</div>
);
}
+97 -2
View File
@@ -7,10 +7,12 @@ 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 { User, Product } from '@/types/user';
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();
@@ -21,6 +23,7 @@ export default function UsersPage() {
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [success, setSuccess] = useState<string | null>(null);
const [isEditing, setIsEditing] = useState(false);
// Load packages on mount
useEffect(() => {
@@ -145,6 +148,66 @@ export default function UsersPage() {
}
};
const handleEditSubmit = async (data: UpdateUserProfileData) => {
if (!user) return;
const identifier = user.email || user.mobile;
if (!identifier) {
setError('کاربر فاقد ایمیل یا شماره موبایل است');
return;
}
setIsLoading(true);
setError(null);
setSuccess(null);
try {
await usersApi.updateUserProfile(identifier, data, token!);
setSuccess('اطلاعات کاربر با موفقیت به‌روزرسانی شد');
setIsEditing(false);
// Refresh user data using the (possibly) new identifier
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);
setSuccess(null);
try {
await usersApi.deleteUser(identifier, token!);
setSuccess('کاربر با موفقیت حذف شد');
setUser(null);
} catch (err) {
setError(err instanceof Error ? err.message : 'خطا در حذف کاربر');
} finally {
setIsLoading(false);
}
};
const handlePackageChange = (packageName: string) => {
console.log('Package changed to:', packageName);
setSelectedPackage(packageName);
@@ -261,7 +324,29 @@ export default function UsersPage() {
)}
{/* User Info */}
{user && <UserInfo user={user} />}
{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 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 disabled:opacity-50"
>
<PencilSquareIcon className="h-5 w-5 ml-2" />
ویرایش اطلاعات
</button>
<button
onClick={handleDeleteUser}
disabled={isLoading}
className="inline-flex items-center px-4 py-2 border border-transparent rounded-md shadow-sm 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 disabled:opacity-50"
>
<TrashIcon className="h-5 w-5 ml-2" />
حذف کاربر
</button>
</div>
</>
)}
{/* User Products */}
{user && selectedPackage && (
@@ -274,6 +359,16 @@ export default function UsersPage() {
selectedPackage={selectedPackage}
/>
)}
{/* Edit User Modal */}
{user && isEditing && (
<UserEditForm
user={user}
onSubmit={handleEditSubmit}
onCancel={() => setIsEditing(false)}
isLoading={isLoading}
/>
)}
</div>
</div>
);
@@ -0,0 +1,90 @@
'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-12 bg-white rounded-lg shadow">
<GiftIcon className="h-10 w-10 text-gray-300 mx-auto mb-3" />
<p className="text-gray-500">
در حال حاضر هیچ کاربری واجد شرایط دریافت پاداش معرفی نیست.
</p>
<p className="text-sm text-gray-400 mt-1">
کاربران پس از {subscriptionTarget} دعوت موفق در این لیست نمایش داده میشوند.
</p>
</div>
);
}
return (
<div className="bg-white shadow overflow-hidden sm:rounded-lg">
<div className="px-4 py-5 sm:px-6 flex items-center justify-between">
<h3 className="text-lg leading-6 font-medium text-gray-900">
کاربران واجد شرایط پاداش
</h3>
<span className="px-3 py-1 text-xs font-medium rounded-full bg-indigo-100 text-indigo-800">
هدف: {subscriptionTarget} دعوت موفق
</span>
</div>
<ul className="divide-y divide-gray-200 border-t border-gray-200">
{users.map((user) => (
<li key={user.id} className="px-4 py-4 sm:px-6">
<div className="flex items-center justify-between flex-wrap gap-3">
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2">
<UserIcon className="h-4 w-4 text-gray-400" />
<p className="text-sm font-medium text-gray-900 truncate">
{user.name || 'بدون نام'}
</p>
<span className="px-2 py-0.5 text-xs font-semibold rounded-full bg-green-100 text-green-800">
{user.successful_invites} دعوت موفق
</span>
</div>
<div className="mt-2 flex flex-wrap gap-x-6 gap-y-1 text-sm text-gray-500">
<span className="flex items-center">
<EnvelopeIcon className="h-4 w-4 ml-1 text-gray-400" />
{user.email || 'ایمیل ثبت نشده'}
</span>
<span className="flex items-center">
<PhoneIcon className="h-4 w-4 ml-1 text-gray-400" />
{user.mobile || 'شماره ثبت نشده'}
</span>
{user.referral_code && (
<span className="flex items-center">
<TicketIcon className="h-4 w-4 ml-1 text-gray-400" />
کد معرف: {user.referral_code}
</span>
)}
</div>
</div>
<button
onClick={() => onFulfill(user)}
disabled={isLoading}
className="inline-flex items-center px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-green-600 hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500 disabled:opacity-50 disabled:cursor-not-allowed"
>
<GiftIcon className="h-5 w-5 ml-2" />
{fulfillingId === user.id ? 'در حال اعطا...' : 'اعطای اشتراک رایگان'}
</button>
</div>
</li>
))}
</ul>
</div>
);
}
+132
View File
@@ -0,0 +1,132 @@
'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();
// Only send changed fields so we never overwrite values with empty ones
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-3 py-2 border text-slate-900 border-gray-300 rounded-md leading-5 bg-white focus:outline-none focus:ring-1 focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm';
return (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-4">
<div className="bg-white rounded-lg shadow-xl w-full max-w-lg" dir="rtl">
<div className="flex items-center justify-between px-6 py-4 border-b border-gray-200">
<h3 className="text-lg font-medium text-gray-900">ویرایش اطلاعات کاربر</h3>
<button
onClick={onCancel}
className="text-gray-400 hover:text-gray-600"
type="button"
>
<XMarkIcon className="h-5 w-5" />
</button>
</div>
<form onSubmit={handleSubmit} className="px-6 py-4 space-y-4">
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">نام</label>
<input
type="text"
className={inputClass}
value={formData.first_name || ''}
onChange={(e) => setFormData({ ...formData, first_name: e.target.value })}
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">نام خانوادگی</label>
<input
type="text"
className={inputClass}
value={formData.last_name || ''}
onChange={(e) => setFormData({ ...formData, last_name: e.target.value })}
/>
</div>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">ایمیل</label>
<input
type="email"
dir="ltr"
className={inputClass}
value={formData.email || ''}
onChange={(e) => setFormData({ ...formData, email: e.target.value })}
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">شماره موبایل</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="block text-sm font-medium text-gray-700 mb-1">آواتار</label>
<input
type="file"
accept="image/*"
className="block w-full text-sm text-gray-700 file:ml-4 file:py-2 file:px-4 file:rounded-md file:border-0 file:text-sm file:font-medium file:bg-indigo-50 file:text-indigo-700 hover:file:bg-indigo-100"
onChange={(e) =>
setFormData({ ...formData, avatar: e.target.files?.[0] || null })
}
/>
</div>
<div className="flex justify-end gap-2 pt-2">
<button
type="button"
onClick={onCancel}
disabled={isLoading}
className="px-4 py-2 border border-gray-300 rounded-md text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 disabled:opacity-50"
>
انصراف
</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 ? 'در حال ذخیره...' : 'ذخیره تغییرات'}
</button>
</div>
</form>
</div>
</div>
);
}
+25
View File
@@ -0,0 +1,25 @@
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
);
}
};
+27 -1
View File
@@ -1,5 +1,5 @@
import { apiClient } from './client';
import { User, Product, ApiResponse } from '@/types/user';
import { User, Product, ApiResponse, UpdateUserProfileData } from '@/types/user';
export const usersApi = {
// Get user status by email or mobile - package name is now a parameter
@@ -47,5 +47,31 @@ export const usersApi = {
// 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);
}
};
File diff suppressed because one or more lines are too long
+20
View File
@@ -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;
}
+8
View File
@@ -70,6 +70,14 @@ export interface UserSearchParams {
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;