Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1409290353 | ||
|
|
390e4b3f1b | ||
|
|
90a66031bd | ||
|
|
e3071b8692 | ||
|
|
ba7147ff59 |
+357
-92
@@ -1,6 +1,7 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import type { ComponentType } from 'react';
|
||||
import { useAuth } from '@/contexts/AuthContext';
|
||||
import { purchasesApi } from '@/lib/api/purchases';
|
||||
import { packagesApi } from '@/lib/api/packages';
|
||||
@@ -10,7 +11,7 @@ import PersianDatePicker from '@/components/admin/PersianDatePicker';
|
||||
import { Purchase, PAYMENT_GATEWAYS } from '@/types/purchase';
|
||||
import { PackageName } from '@/types/package';
|
||||
import { Product } from '@/types/product';
|
||||
import { formatPrice, getPurchaseFinalPrice, parseStoreRate } from '@/lib/utils';
|
||||
import { formatPrice, getPurchaseFinalPrice, parseStoreRate, parseFee } from '@/lib/utils';
|
||||
import {
|
||||
MagnifyingGlassIcon,
|
||||
ArrowPathIcon,
|
||||
@@ -25,11 +26,56 @@ import {
|
||||
// بنابراین هر دو وضعیت باید بهعنوان فروش محسوب شوند.
|
||||
const PAID_STATUSES = [2, 3];
|
||||
|
||||
// Local-time Gregorian helpers. The "YYYY-MM-DD" format matches what
|
||||
// PersianDatePicker exchanges and what the created_at comparison expects.
|
||||
const toGregorianValue = (date: Date): string => {
|
||||
const year = date.getFullYear();
|
||||
const month = String(date.getMonth() + 1).padStart(2, '0');
|
||||
const day = String(date.getDate()).padStart(2, '0');
|
||||
return `${year}-${month}-${day}`;
|
||||
};
|
||||
|
||||
const addDays = (date: Date, days: number): Date => {
|
||||
const copy = new Date(date);
|
||||
copy.setDate(copy.getDate() + days);
|
||||
return copy;
|
||||
};
|
||||
|
||||
const todayValue = (): string => toGregorianValue(new Date());
|
||||
|
||||
type DatePreset = 'today' | 'yesterday' | 'last7' | 'thisMonth';
|
||||
|
||||
const presetRange = (preset: DatePreset): { from: string; to: string } => {
|
||||
const now = new Date();
|
||||
switch (preset) {
|
||||
case 'today':
|
||||
return { from: toGregorianValue(now), to: toGregorianValue(now) };
|
||||
case 'yesterday': {
|
||||
const yesterday = addDays(now, -1);
|
||||
return { from: toGregorianValue(yesterday), to: toGregorianValue(yesterday) };
|
||||
}
|
||||
case 'last7':
|
||||
return { from: toGregorianValue(addDays(now, -6)), to: toGregorianValue(now) };
|
||||
case 'thisMonth':
|
||||
return {
|
||||
from: toGregorianValue(new Date(now.getFullYear(), now.getMonth(), 1)),
|
||||
to: toGregorianValue(now),
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
const PRESET_LABELS: { key: DatePreset; label: string }[] = [
|
||||
{ key: 'today', label: 'امروز' },
|
||||
{ key: 'yesterday', label: 'دیروز' },
|
||||
{ key: 'last7', label: '۷ روز اخیر' },
|
||||
{ key: 'thisMonth', label: 'این ماه' },
|
||||
];
|
||||
|
||||
interface StoreSummary {
|
||||
count: number;
|
||||
gross: number;
|
||||
rate: number;
|
||||
commission: number;
|
||||
fee: number;
|
||||
net: number;
|
||||
}
|
||||
|
||||
@@ -55,24 +101,42 @@ interface AccountingResult {
|
||||
const computeAccounting = (
|
||||
purchases: Purchase[],
|
||||
myketRate: number,
|
||||
cafeRate: number
|
||||
cafeRate: number,
|
||||
transactionFee: number,
|
||||
): AccountingResult => {
|
||||
const rows = new Map<number, ProductRow>();
|
||||
let totalCount = 0;
|
||||
let totalGross = 0;
|
||||
let totalCommission = 0;
|
||||
|
||||
const makeStore = (rate: number): StoreSummary => ({ count: 0, gross: 0, rate, commission: 0, net: 0 });
|
||||
// درصد سهم توسعهدهنده بهصورت کسر (0.85) و کارمزد تراکنش به ریال
|
||||
const makeStore = (rate: number): StoreSummary => ({ count: 0, gross: 0, rate, fee: 0, net: 0 });
|
||||
const myket: StoreSummary = makeStore(myketRate);
|
||||
const cafe: StoreSummary = makeStore(cafeRate);
|
||||
const other: StoreSummary = makeStore(0);
|
||||
|
||||
const collect = (store: StoreSummary, price: number, rate: number) => {
|
||||
const commission = (price * rate) / 100;
|
||||
// سهم توسعهدهنده برای مایکت/کافهبازار:
|
||||
// (P / 1.1 - T) × R
|
||||
// P = قیمت فروش (با احتساب ۱۰٪ مالیات بر ارزش افزوده)
|
||||
// /1.1 = حذف ارزش افزوده، T = کارمزد تراکنش به ریال، R = درصد سهم
|
||||
const developerShare = (price: number, rate: number, feePerTransaction: number) => {
|
||||
const beforeVat = price / 1.1;
|
||||
const afterVatAndFee = beforeVat - feePerTransaction;
|
||||
if (afterVatAndFee <= 0) return 0;
|
||||
return afterVatAndFee * (rate / 100);
|
||||
};
|
||||
|
||||
const collect = (store: StoreSummary, price: number, rate: number, feePerTransaction: number) => {
|
||||
let net: number;
|
||||
if (rate > 0) {
|
||||
net = developerShare(price, rate, feePerTransaction);
|
||||
} else {
|
||||
net = price; // سایر درگاهها: بدون کارمزد فروشگاه
|
||||
}
|
||||
store.count += 1;
|
||||
store.gross += price;
|
||||
store.commission += commission;
|
||||
store.net += price - commission;
|
||||
store.fee += price - net;
|
||||
store.net += net;
|
||||
};
|
||||
|
||||
for (const purchase of purchases) {
|
||||
@@ -81,22 +145,26 @@ const computeAccounting = (
|
||||
|
||||
let store: StoreSummary;
|
||||
let rate: number;
|
||||
let feePerTransaction: number;
|
||||
if (gateway === PAYMENT_GATEWAYS.cafe.code) {
|
||||
store = cafe;
|
||||
rate = cafeRate;
|
||||
feePerTransaction = transactionFee;
|
||||
} else if (gateway === PAYMENT_GATEWAYS.myket.code) {
|
||||
store = myket;
|
||||
rate = myketRate;
|
||||
feePerTransaction = transactionFee;
|
||||
} else {
|
||||
store = other;
|
||||
rate = 0;
|
||||
feePerTransaction = 0;
|
||||
}
|
||||
|
||||
collect(store, price, rate);
|
||||
collect(store, price, rate, feePerTransaction);
|
||||
|
||||
totalCount += 1;
|
||||
totalGross += price;
|
||||
totalCommission += (price * rate) / 100;
|
||||
totalCommission += price - developerShare(price, rate, feePerTransaction);
|
||||
|
||||
const productId = purchase.product_id ?? purchase.product?.id ?? -1;
|
||||
let row = rows.get(productId);
|
||||
@@ -117,8 +185,8 @@ const computeAccounting = (
|
||||
}
|
||||
row.count += 1;
|
||||
row.gross += price;
|
||||
row.commission += (price * rate) / 100;
|
||||
row.net += price - (price * rate) / 100;
|
||||
row.commission += price - developerShare(price, rate, feePerTransaction);
|
||||
row.net += developerShare(price, rate, feePerTransaction);
|
||||
}
|
||||
|
||||
return {
|
||||
@@ -144,35 +212,42 @@ export default function AccountingPage() {
|
||||
const [products, setProducts] = useState<Product[]>([]);
|
||||
const [selectedProductId, setSelectedProductId] = useState<string>('');
|
||||
|
||||
// Date range
|
||||
const [dateFrom, setDateFrom] = useState<string>('');
|
||||
const [dateTo, setDateTo] = useState<string>('');
|
||||
// Date range — defaults to today so the daily account is the first thing shown
|
||||
const [dateFrom, setDateFrom] = useState<string>(todayValue);
|
||||
const [dateTo, setDateTo] = useState<string>(todayValue);
|
||||
const [preset, setPreset] = useState<DatePreset | null>('today');
|
||||
|
||||
// Time range
|
||||
const [timeFrom, setTimeFrom] = useState<string>('');
|
||||
const [timeTo, setTimeTo] = useState<string>('');
|
||||
|
||||
// Status filter — both paid statuses selected by default
|
||||
const [statuses, setStatuses] = useState<number[]>([...PAID_STATUSES]);
|
||||
|
||||
// Store commission rates (editable percentages)
|
||||
const [myketRate, setMyketRate] = useState<string>('15');
|
||||
const [cafeRate, setCafeRate] = useState<string>('15');
|
||||
// درصد سهم توسعهدهنده (R در فرمول) — مایکت و کافهبازار بهطور پیشفرض ۸۵٪
|
||||
const [myketRate, setMyketRate] = useState<string>('85');
|
||||
const [cafeRate, setCafeRate] = useState<string>('85');
|
||||
// کارمزد تراکنش به ریال (T در فرمول سهم توسعهدهنده)
|
||||
const [transactionFee, setTransactionFee] = useState<string>('1200');
|
||||
|
||||
const [allPurchases, setAllPurchases] = useState<Purchase[] | null>(null);
|
||||
const [result, setResult] = useState<AccountingResult | null>(null);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
// Bumped by the «تحلیل» button / «بارگذاری مجدد» to force a refetch
|
||||
const [refreshTick, setRefreshTick] = useState(0);
|
||||
|
||||
const inputClass =
|
||||
'block w-full px-3 py-2.5 text-gray-900 dark:text-gray-100 border border-gray-200 dark:border-gray-700 rounded-xl shadow-sm focus:ring-2 focus:ring-indigo-500 focus:border-transparent sm:text-sm dark:bg-gray-800/80 transition-colors';
|
||||
const labelClass = 'block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5';
|
||||
|
||||
// Load packages once on mount
|
||||
// Load packages once on mount — "همه پکیجها" stays selected by default so
|
||||
// the initial view covers the whole business.
|
||||
useEffect(() => {
|
||||
if (!token) return;
|
||||
packagesApi
|
||||
.getAllPackages(token)
|
||||
.then((data) => {
|
||||
setPackages(data);
|
||||
if (data.length > 0) setSelectedPackageName(data[0].name || '');
|
||||
})
|
||||
.then(setPackages)
|
||||
.catch(() => setError('خطا در دریافت لیست پکیجها'));
|
||||
}, [token]);
|
||||
|
||||
@@ -190,27 +265,68 @@ export default function AccountingPage() {
|
||||
.catch(() => setProducts([]));
|
||||
}, [selectedPackageName, token]);
|
||||
|
||||
const handleAnalyze = useCallback(async () => {
|
||||
// The server-side query window. Fetching only the selected window keeps the
|
||||
// payload small; the backend filters created_at by these dates. Runs
|
||||
// automatically on mount (today's account) and whenever the window,
|
||||
// package or product selection changes.
|
||||
const windowKey = [dateFrom, dateTo, timeFrom, timeTo, selectedPackageName, selectedProductId].join('|');
|
||||
|
||||
useEffect(() => {
|
||||
if (!token) return;
|
||||
let cancelled = false;
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
// Fetch all purchases once, then filter/aggregate in-memory.
|
||||
const purchases = await purchasesApi.getAllPurchases({ per_page: 500 }, token);
|
||||
|
||||
purchasesApi
|
||||
.getAllPurchases(
|
||||
{
|
||||
per_page: 500,
|
||||
...(dateFrom && { date_from: dateFrom }),
|
||||
...(dateTo && { date_to: dateTo }),
|
||||
...(timeFrom && { time_from: timeFrom }),
|
||||
...(timeTo && { time_to: timeTo }),
|
||||
...(selectedPackageName && { package_name: selectedPackageName }),
|
||||
...(selectedProductId && { product_id: Number(selectedProductId) }),
|
||||
},
|
||||
token
|
||||
)
|
||||
.then((purchases) => {
|
||||
if (cancelled) return;
|
||||
setAllPurchases(purchases);
|
||||
setResult(computeAccounting(purchases, parseStoreRate(myketRate), parseStoreRate(cafeRate)));
|
||||
} catch (err) {
|
||||
setResult(
|
||||
computeAccounting(
|
||||
purchases,
|
||||
parseStoreRate(myketRate),
|
||||
parseStoreRate(cafeRate),
|
||||
parseFee(transactionFee)
|
||||
)
|
||||
);
|
||||
})
|
||||
.catch((err) => {
|
||||
if (!cancelled) {
|
||||
setError(err instanceof Error ? err.message : 'خطا در دریافت دادهها');
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, [token, myketRate, cafeRate]);
|
||||
})
|
||||
.finally(() => {
|
||||
if (!cancelled) setIsLoading(false);
|
||||
});
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
// Commission rates are read at fetch time only; changing them recomputes
|
||||
// locally (see runAnalysis) without refetching.
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [token, windowKey, refreshTick]);
|
||||
|
||||
const handleAnalyze = () => setRefreshTick((t) => t + 1);
|
||||
|
||||
// Recompute whenever filters or commission rates change (uses cached data)
|
||||
const runAnalysis = useCallback(() => {
|
||||
if (!allPurchases) return;
|
||||
const myket = parseStoreRate(myketRate);
|
||||
const cafe = parseStoreRate(cafeRate);
|
||||
const fee = parseFee(transactionFee);
|
||||
|
||||
const filtered = allPurchases.filter((p) => {
|
||||
// Status
|
||||
@@ -227,28 +343,61 @@ export default function AccountingPage() {
|
||||
}
|
||||
|
||||
// Date range (created_at is "Y-m-d H:i:s")
|
||||
if (dateFrom && p.created_at && p.created_at.slice(0, 10) < dateFrom) return false;
|
||||
if (dateTo && p.created_at && p.created_at.slice(0, 10) > dateTo) return false;
|
||||
// When time is also selected, compare full datetime strings;
|
||||
// otherwise compare only the date portion (YYYY-MM-DD).
|
||||
const created = p.created_at ?? '';
|
||||
if (dateFrom) {
|
||||
const datePart = created.slice(0, 10);
|
||||
if (timeFrom) {
|
||||
// Full datetime comparison: "YYYY-MM-DD HH:mm:ss"
|
||||
if (created < `${dateFrom} ${timeFrom}`) return false;
|
||||
} else if (datePart < dateFrom) return false;
|
||||
}
|
||||
if (dateTo) {
|
||||
const datePart = created.slice(0, 10);
|
||||
if (timeTo) {
|
||||
if (created > `${dateTo} ${timeTo}`) return false;
|
||||
} else if (datePart > dateTo) return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
});
|
||||
|
||||
setResult(computeAccounting(filtered, myket, cafe));
|
||||
}, [allPurchases, statuses, selectedProductId, selectedPackageName, dateFrom, dateTo, myketRate, cafeRate]);
|
||||
setResult(computeAccounting(filtered, myket, cafe, fee));
|
||||
}, [allPurchases, statuses, selectedProductId, selectedPackageName, dateFrom, dateTo, timeFrom, timeTo, myketRate, cafeRate, transactionFee]);
|
||||
|
||||
// Recompute on filter/rate changes (no refetch needed once data is cached)
|
||||
useEffect(() => {
|
||||
if (allPurchases) runAnalysis();
|
||||
}, [runAnalysis, allPurchases]);
|
||||
|
||||
const applyPreset = (key: DatePreset) => {
|
||||
const range = presetRange(key);
|
||||
setPreset(key);
|
||||
setDateFrom(range.from);
|
||||
setDateTo(range.to);
|
||||
setTimeFrom('');
|
||||
setTimeTo('');
|
||||
};
|
||||
|
||||
const handleDateFromChange = (value: string) => {
|
||||
setPreset(null);
|
||||
setDateFrom(value);
|
||||
};
|
||||
|
||||
const handleDateToChange = (value: string) => {
|
||||
setPreset(null);
|
||||
setDateTo(value);
|
||||
};
|
||||
|
||||
const handleReset = () => {
|
||||
setSelectedPackageName(packages[0]?.name || '');
|
||||
setSelectedPackageName('');
|
||||
setSelectedProductId('');
|
||||
setDateFrom('');
|
||||
setDateTo('');
|
||||
applyPreset('today');
|
||||
setStatuses([...PAID_STATUSES]);
|
||||
setMyketRate('15');
|
||||
setCafeRate('15');
|
||||
setMyketRate('85');
|
||||
setCafeRate('85');
|
||||
setTransactionFee('1200');
|
||||
};
|
||||
|
||||
const toggleStatus = (code: number) => {
|
||||
@@ -257,11 +406,6 @@ export default function AccountingPage() {
|
||||
);
|
||||
};
|
||||
|
||||
const statCardClass =
|
||||
'rounded-2xl bg-white dark:bg-gray-900 ring-1 ring-gray-200 dark:ring-gray-800 p-5 shadow-sm';
|
||||
const statIconClass = 'h-5 w-5';
|
||||
const statValueClass = 'text-2xl font-bold text-gray-900 dark:text-gray-100 mt-1.5';
|
||||
|
||||
return (
|
||||
<div className="p-4 sm:p-8">
|
||||
<div className="max-w-7xl mx-auto">
|
||||
@@ -290,7 +434,7 @@ export default function AccountingPage() {
|
||||
}}
|
||||
className="bg-white dark:bg-gray-900 ring-1 ring-gray-200 dark:ring-gray-800 rounded-2xl p-5 sm:p-6 mb-6 shadow-sm"
|
||||
>
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-4">
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-6">
|
||||
<div>
|
||||
<label htmlFor="package_name" className={labelClass}>پکیج</label>
|
||||
<select
|
||||
@@ -331,7 +475,19 @@ export default function AccountingPage() {
|
||||
label="از تاریخ"
|
||||
placeholder="انتخاب تاریخ شروع"
|
||||
value={dateFrom}
|
||||
onChange={setDateFrom}
|
||||
onChange={handleDateFromChange}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label htmlFor="time_from" className={labelClass}>از ساعت</label>
|
||||
<input
|
||||
type="time"
|
||||
id="time_from"
|
||||
value={timeFrom}
|
||||
onChange={(e) => setTimeFrom(e.target.value)}
|
||||
className={inputClass}
|
||||
placeholder="۰۰:۰۰"
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -341,9 +497,45 @@ export default function AccountingPage() {
|
||||
label="تا تاریخ"
|
||||
placeholder="انتخاب تاریخ پایان"
|
||||
value={dateTo}
|
||||
onChange={setDateTo}
|
||||
onChange={handleDateToChange}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label htmlFor="time_to" className={labelClass}>تا ساعت</label>
|
||||
<input
|
||||
type="time"
|
||||
id="time_to"
|
||||
value={timeTo}
|
||||
onChange={(e) => setTimeTo(e.target.value)}
|
||||
className={inputClass}
|
||||
placeholder="۲۳:۵۹"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Quick date-range presets */}
|
||||
<div className="mt-4">
|
||||
<label className={labelClass}>بازه زمانی</label>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{PRESET_LABELS.map(({ key, label }) => {
|
||||
const active = preset === key;
|
||||
return (
|
||||
<button
|
||||
key={key}
|
||||
type="button"
|
||||
onClick={() => applyPreset(key)}
|
||||
className={`px-3.5 py-1.5 rounded-xl text-sm font-medium transition-colors ${
|
||||
active
|
||||
? 'bg-indigo-600 text-white shadow-sm shadow-indigo-500/20'
|
||||
: 'bg-gray-50 dark:bg-gray-800 text-gray-600 dark:text-gray-300 ring-1 ring-gray-200 dark:ring-gray-700 hover:bg-gray-100 dark:hover:bg-gray-700'
|
||||
}`}
|
||||
>
|
||||
{label}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Status checkboxes */}
|
||||
@@ -368,11 +560,11 @@ export default function AccountingPage() {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Commission rates */}
|
||||
{/* Commission settings */}
|
||||
<div className="mt-4 grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3">
|
||||
<div>
|
||||
<label htmlFor="myket_rate" className={labelClass}>
|
||||
سهم مایکت (%)
|
||||
سهم توسعهدهنده مایکت (٪)
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
@@ -381,12 +573,12 @@ export default function AccountingPage() {
|
||||
value={myketRate}
|
||||
onChange={(e) => setMyketRate(e.target.value)}
|
||||
className={inputClass}
|
||||
placeholder="۱۵"
|
||||
placeholder="۸۵"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label htmlFor="cafe_rate" className={labelClass}>
|
||||
سهم کافه بازار (%)
|
||||
سهم توسعهدهنده کافه بازار (٪)
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
@@ -395,15 +587,30 @@ export default function AccountingPage() {
|
||||
value={cafeRate}
|
||||
onChange={(e) => setCafeRate(e.target.value)}
|
||||
className={inputClass}
|
||||
placeholder="۱۵"
|
||||
placeholder="۸۵"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label htmlFor="transaction_fee" className={labelClass}>
|
||||
کارمزد تراکنش (ریال)
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
id="transaction_fee"
|
||||
inputMode="numeric"
|
||||
value={transactionFee}
|
||||
onChange={(e) => setTransactionFee(e.target.value)}
|
||||
className={inputClass}
|
||||
placeholder="۱۲۰۰"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<p className="mt-2 text-xs text-gray-400 dark:text-gray-500">
|
||||
مایکت معمولاً ۱۵٪ یا ۳۰٪ و کافه بازار ۱۵٪ (زیر یک میلیارد تومان) یا ۳۰٪ کارمزد میگیرد.
|
||||
سهم توسعهدهنده = (قیمت ÷ ۱٫۱ − کارمزد تراکنش) × درصد سهم. پیشفرض مایکت و
|
||||
کافهبازار ۸۵٪ (فروش زیر ۱۰ میلیارد ریال) و ۷۰٪ (بالای آن) است.
|
||||
</p>
|
||||
|
||||
<div className="flex items-center gap-3 mt-5">
|
||||
<div className="flex flex-wrap items-center gap-3 mt-5">
|
||||
<button
|
||||
type="submit"
|
||||
disabled={isLoading}
|
||||
@@ -445,38 +652,10 @@ export default function AccountingPage() {
|
||||
<>
|
||||
{/* Summary stat cards */}
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 mb-6">
|
||||
<div className={statCardClass}>
|
||||
<div className="flex items-center gap-2 text-sm font-medium text-gray-500 dark:text-gray-400">
|
||||
<WalletIcon className={statIconClass} />
|
||||
تعداد فروش
|
||||
</div>
|
||||
<div className={statValueClass}>{formatPrice(result.totals.count)}</div>
|
||||
</div>
|
||||
<div className={statCardClass}>
|
||||
<div className="flex items-center gap-2 text-sm font-medium text-gray-500 dark:text-gray-400">
|
||||
<BanknotesIcon className={statIconClass} />
|
||||
فروش ناخالص
|
||||
</div>
|
||||
<div className={statValueClass}>{formatPrice(result.totals.gross)} <span className="text-sm font-normal text-gray-400">تومان</span></div>
|
||||
</div>
|
||||
<div className={statCardClass}>
|
||||
<div className="flex items-center gap-2 text-sm font-medium text-gray-500 dark:text-gray-400">
|
||||
<ChartPieIcon className={statIconClass} />
|
||||
کارمزد فروشگاهها
|
||||
</div>
|
||||
<div className={`${statValueClass} text-amber-600 dark:text-amber-400`}>
|
||||
{formatPrice(result.totals.commission)} <span className="text-sm font-normal text-gray-400">تومان</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className={statCardClass}>
|
||||
<div className="flex items-center gap-2 text-sm font-medium text-gray-500 dark:text-gray-400">
|
||||
<CalculatorIcon className={statIconClass} />
|
||||
سود خالص
|
||||
</div>
|
||||
<div className={`${statValueClass} text-emerald-600 dark:text-emerald-400`}>
|
||||
{formatPrice(result.totals.net)} <span className="text-sm font-normal text-gray-400">تومان</span>
|
||||
</div>
|
||||
</div>
|
||||
<StatCard label="تعداد فروش" value={formatPrice(result.totals.count)} Icon={WalletIcon} tone="indigo" />
|
||||
<StatCard label="فروش ناخالص" value={formatPrice(result.totals.gross)} unit="تومان" Icon={BanknotesIcon} tone="sky" />
|
||||
<StatCard label="کارمزد فروشگاهها" value={formatPrice(result.totals.commission)} unit="تومان" Icon={ChartPieIcon} tone="amber" />
|
||||
<StatCard label="سود خالص" value={formatPrice(result.totals.net)} unit="تومان" Icon={CalculatorIcon} tone="emerald" />
|
||||
</div>
|
||||
|
||||
{/* Per-store breakdown */}
|
||||
@@ -501,7 +680,50 @@ export default function AccountingPage() {
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="overflow-x-auto">
|
||||
<>
|
||||
{/* Mobile: stacked cards */}
|
||||
<ul className="divide-y divide-gray-200 dark:divide-gray-800 md:hidden">
|
||||
{result.rows.map((row) => (
|
||||
<li key={row.productId} className="px-5 py-4">
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
<div className="min-w-0">
|
||||
<p className="text-sm font-semibold text-gray-900 dark:text-gray-100 truncate">
|
||||
{row.title}
|
||||
</p>
|
||||
<p className="text-xs text-gray-500 dark:text-gray-400 mt-0.5 truncate">
|
||||
{row.packageName}
|
||||
</p>
|
||||
</div>
|
||||
<span className="flex-shrink-0 px-2.5 py-1 text-xs font-semibold rounded-lg bg-indigo-50 text-indigo-700 dark:bg-indigo-500/10 dark:text-indigo-400">
|
||||
{formatPrice(row.count)} فروش
|
||||
</span>
|
||||
</div>
|
||||
<div className="grid grid-cols-3 gap-2 mt-3 pt-3 border-t border-gray-100 dark:border-gray-800/60">
|
||||
<div>
|
||||
<p className="text-[11px] text-gray-400 dark:text-gray-500">فروش ناخالص</p>
|
||||
<p className="text-xs font-bold text-gray-900 dark:text-gray-100 mt-0.5">
|
||||
{formatPrice(row.gross)}
|
||||
</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-[11px] text-gray-400 dark:text-gray-500">کارمزد</p>
|
||||
<p className="text-xs font-bold text-amber-600 dark:text-amber-400 mt-0.5">
|
||||
{formatPrice(row.commission)}
|
||||
</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-[11px] text-gray-400 dark:text-gray-500">سود خالص</p>
|
||||
<p className="text-xs font-bold text-emerald-600 dark:text-emerald-400 mt-0.5">
|
||||
{formatPrice(row.net)}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
|
||||
{/* Desktop: table */}
|
||||
<div className="hidden md:block overflow-x-auto">
|
||||
<table className="min-w-full divide-y divide-gray-200 dark:divide-gray-800">
|
||||
<thead className="bg-gray-50 dark:bg-gray-800/60">
|
||||
<tr className="text-right text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
|
||||
@@ -539,6 +761,7 @@ export default function AccountingPage() {
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
@@ -559,6 +782,48 @@ export default function AccountingPage() {
|
||||
);
|
||||
}
|
||||
|
||||
const STAT_TONES = {
|
||||
indigo: 'bg-indigo-50 text-indigo-600 dark:bg-indigo-500/10 dark:text-indigo-400',
|
||||
sky: 'bg-sky-50 text-sky-600 dark:bg-sky-500/10 dark:text-sky-400',
|
||||
amber: 'bg-amber-50 text-amber-600 dark:bg-amber-500/10 dark:text-amber-400',
|
||||
emerald: 'bg-emerald-50 text-emerald-600 dark:bg-emerald-500/10 dark:text-emerald-400',
|
||||
} as const;
|
||||
|
||||
function StatCard({
|
||||
label,
|
||||
value,
|
||||
unit,
|
||||
Icon,
|
||||
tone,
|
||||
}: {
|
||||
label: string;
|
||||
value: string;
|
||||
unit?: string;
|
||||
Icon: ComponentType<{ className?: string }>;
|
||||
tone: keyof typeof STAT_TONES;
|
||||
}) {
|
||||
const valueColor =
|
||||
tone === 'amber'
|
||||
? 'text-amber-600 dark:text-amber-400'
|
||||
: tone === 'emerald'
|
||||
? 'text-emerald-600 dark:text-emerald-400'
|
||||
: 'text-gray-900 dark:text-gray-100';
|
||||
|
||||
return (
|
||||
<div className="rounded-2xl bg-white dark:bg-gray-900 ring-1 ring-gray-200 dark:ring-gray-800 p-5 shadow-sm">
|
||||
<div className="flex items-center gap-2.5">
|
||||
<span className={`h-9 w-9 rounded-xl flex items-center justify-center flex-shrink-0 ${STAT_TONES[tone]}`}>
|
||||
<Icon className="h-5 w-5" />
|
||||
</span>
|
||||
<span className="text-sm font-medium text-gray-500 dark:text-gray-400">{label}</span>
|
||||
</div>
|
||||
<div className={`text-2xl font-bold mt-2.5 ${valueColor}`}>
|
||||
{value} {unit && <span className="text-sm font-normal text-gray-400">{unit}</span>}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function StoreCard({ title, summary }: { title: string; summary: StoreSummary }) {
|
||||
return (
|
||||
<div className="bg-white dark:bg-gray-900 ring-1 ring-gray-200 dark:ring-gray-800 rounded-2xl p-5 shadow-sm">
|
||||
@@ -566,7 +831,7 @@ function StoreCard({ title, summary }: { title: string; summary: StoreSummary })
|
||||
<h4 className="text-sm font-semibold text-gray-900 dark:text-gray-100">{title}</h4>
|
||||
{summary.rate > 0 && (
|
||||
<span className="px-2 py-0.5 text-xs font-medium rounded-lg bg-indigo-50 text-indigo-700 dark:bg-indigo-500/15 dark:text-indigo-400">
|
||||
کارمزد {summary.rate}٪
|
||||
سهم توسعهدهنده {summary.rate}٪
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
@@ -580,8 +845,8 @@ function StoreCard({ title, summary }: { title: string; summary: StoreSummary })
|
||||
<span className="text-gray-900 dark:text-gray-100 font-medium">{formatPrice(summary.gross)} تومان</span>
|
||||
</div>
|
||||
<div className="flex justify-between text-gray-500 dark:text-gray-400">
|
||||
<span>کارمزد</span>
|
||||
<span className="text-amber-600 dark:text-amber-400 font-medium">{formatPrice(summary.commission)} تومان</span>
|
||||
<span>سهم فروشگاهها</span>
|
||||
<span className="text-amber-600 dark:text-amber-400 font-medium">{formatPrice(summary.fee)} تومان</span>
|
||||
</div>
|
||||
<div className="flex justify-between pt-1.5 border-t border-gray-100 dark:border-gray-800 text-gray-500 dark:text-gray-400">
|
||||
<span>سود خالص</span>
|
||||
|
||||
@@ -0,0 +1,570 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useEffect, useCallback, useMemo } from 'react';
|
||||
import { useAuth } from '@/contexts/AuthContext';
|
||||
import { authLogsApi } from '@/lib/api/authLogs';
|
||||
import { packagesApi } from '@/lib/api/packages';
|
||||
import PageHeader from '@/components/admin/PageHeader';
|
||||
import PersianDatePicker from '@/components/admin/PersianDatePicker';
|
||||
import { PackageName } from '@/types/package';
|
||||
import {
|
||||
AuthLog,
|
||||
AuthLogFilters,
|
||||
AuthStats,
|
||||
AUTH_EVENTS,
|
||||
getAuthEventLabel,
|
||||
PaginatedAuthLogs,
|
||||
} from '@/types/auth-log';
|
||||
import { formatPrice, formatDate, formatTime } from '@/lib/utils';
|
||||
import {
|
||||
MagnifyingGlassIcon,
|
||||
ArrowPathIcon,
|
||||
DevicePhoneMobileIcon,
|
||||
ArrowRightOnRectangleIcon,
|
||||
CheckBadgeIcon,
|
||||
BanknotesIcon,
|
||||
UserGroupIcon,
|
||||
ExclamationTriangleIcon,
|
||||
} from '@heroicons/react/24/outline';
|
||||
|
||||
// Default price of one Kavenegar verify SMS, in Toman. Only used to price the
|
||||
// SMS total in the panel — the admin can change it and the choice is remembered.
|
||||
const DEFAULT_SMS_UNIT_COST = 2000;
|
||||
const SMS_COST_STORAGE_KEY = 'approagency:sms_unit_cost';
|
||||
|
||||
// Today as the Gregorian YYYY-MM-DD the API and PersianDatePicker exchange.
|
||||
const todayValue = (): string => {
|
||||
const now = new Date();
|
||||
const month = String(now.getMonth() + 1).padStart(2, '0');
|
||||
const day = String(now.getDate()).padStart(2, '0');
|
||||
return `${now.getFullYear()}-${month}-${day}`;
|
||||
};
|
||||
|
||||
// The section opens on today's activity; widen the range with the date pickers.
|
||||
const createDefaultFilters = (): AuthLogFilters => ({
|
||||
event: '',
|
||||
mobile: '',
|
||||
package_name: '',
|
||||
date_from: todayValue(),
|
||||
date_to: todayValue(),
|
||||
});
|
||||
|
||||
const eventBadgeClass = (event: string, success: boolean): string => {
|
||||
if (!success) return 'bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-300';
|
||||
if (event === 'otp_sent' || event === 'mobile_otp_sent') {
|
||||
return 'bg-amber-100 text-amber-800 dark:bg-amber-900/30 dark:text-amber-300';
|
||||
}
|
||||
return 'bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-300';
|
||||
};
|
||||
|
||||
export default function AuthAnalyticsPage() {
|
||||
const { token } = useAuth();
|
||||
const [packages, setPackages] = useState<PackageName[]>([]);
|
||||
const [filters, setFilters] = useState<AuthLogFilters>(createDefaultFilters);
|
||||
const [smsUnitCost, setSmsUnitCost] = useState<number>(DEFAULT_SMS_UNIT_COST);
|
||||
const [initialized, setInitialized] = useState(false);
|
||||
const [stats, setStats] = useState<AuthStats | null>(null);
|
||||
const [logs, setLogs] = useState<PaginatedAuthLogs | null>(null);
|
||||
const [page, setPage] = useState(1);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const load = useCallback(async (
|
||||
targetPage: number,
|
||||
activeFilters: AuthLogFilters,
|
||||
unitCost: number
|
||||
) => {
|
||||
if (!token) return;
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const [statsData, logsData] = await Promise.all([
|
||||
authLogsApi.getStats({ ...activeFilters, sms_unit_cost: unitCost }, token),
|
||||
authLogsApi.getLogs({ ...activeFilters, page: targetPage, per_page: 30 }, token),
|
||||
]);
|
||||
setStats(statsData);
|
||||
setLogs(logsData);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'خطا در دریافت آمار ورود و پیامک');
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, [token]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!token) return;
|
||||
packagesApi.getAllPackages(token).then(setPackages).catch(() => setPackages([]));
|
||||
}, [token]);
|
||||
|
||||
// First load: restore the last SMS unit price the admin entered, then fetch
|
||||
// today's activity with it (so the cost card is right on the very first render).
|
||||
useEffect(() => {
|
||||
if (!token || initialized) return;
|
||||
|
||||
const saved = window.localStorage.getItem(SMS_COST_STORAGE_KEY);
|
||||
const parsed = saved ? parseInt(saved, 10) : NaN;
|
||||
const unitCost = !Number.isNaN(parsed) && parsed >= 0 ? parsed : DEFAULT_SMS_UNIT_COST;
|
||||
|
||||
setSmsUnitCost(unitCost);
|
||||
setInitialized(true);
|
||||
load(1, createDefaultFilters(), unitCost);
|
||||
}, [token, initialized, load]);
|
||||
|
||||
const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) => {
|
||||
const { name, value } = e.target;
|
||||
setFilters((prev) => ({ ...prev, [name]: value }));
|
||||
};
|
||||
|
||||
const handleUnitCostChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const digits = e.target.value.replace(/[^\d]/g, '');
|
||||
const parsed = digits ? parseInt(digits, 10) : 0;
|
||||
setSmsUnitCost(parsed);
|
||||
window.localStorage.setItem(SMS_COST_STORAGE_KEY, String(parsed));
|
||||
};
|
||||
|
||||
const handleSearch = (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setPage(1);
|
||||
load(1, filters, smsUnitCost);
|
||||
};
|
||||
|
||||
const handleReset = () => {
|
||||
const defaults = createDefaultFilters();
|
||||
setFilters(defaults);
|
||||
setSmsUnitCost(DEFAULT_SMS_UNIT_COST);
|
||||
window.localStorage.setItem(SMS_COST_STORAGE_KEY, String(DEFAULT_SMS_UNIT_COST));
|
||||
setPage(1);
|
||||
load(1, defaults, DEFAULT_SMS_UNIT_COST);
|
||||
};
|
||||
|
||||
const goToPage = (targetPage: number) => {
|
||||
setPage(targetPage);
|
||||
load(targetPage, filters, smsUnitCost);
|
||||
};
|
||||
|
||||
// Tallest bar in the daily chart, used to scale the rest
|
||||
const dailyMax = useMemo(
|
||||
() => Math.max(1, ...(stats?.daily || []).map((d) => Math.max(d.otp_sent, d.otp_verified))),
|
||||
[stats]
|
||||
);
|
||||
|
||||
const inputClass =
|
||||
'block w-full px-3 py-2.5 text-gray-900 dark:text-gray-100 border border-gray-200 dark:border-gray-700 rounded-xl shadow-sm focus:ring-2 focus:ring-indigo-500 focus:border-transparent sm:text-sm dark:bg-gray-800/80 transition-colors';
|
||||
const labelClass = 'block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5';
|
||||
|
||||
const cards = stats ? [
|
||||
{
|
||||
title: 'پیامک ارسالشده',
|
||||
value: formatPrice(stats.totals.sms_sent),
|
||||
hint: 'مجموع کدهای ارسالی (قابل محاسبه برای هزینه)',
|
||||
Icon: DevicePhoneMobileIcon,
|
||||
iconBg: 'bg-amber-100 dark:bg-amber-500/15',
|
||||
iconColor: 'text-amber-600 dark:text-amber-400',
|
||||
},
|
||||
{
|
||||
title: 'هزینه تخمینی پیامک',
|
||||
value: `${formatPrice(stats.totals.sms_cost)} تومان`,
|
||||
hint: `بر پایه ${formatPrice(stats.totals.sms_unit_cost)} تومان برای هر پیامک`,
|
||||
Icon: BanknotesIcon,
|
||||
iconBg: 'bg-cyan-100 dark:bg-cyan-500/15',
|
||||
iconColor: 'text-cyan-600 dark:text-cyan-400',
|
||||
},
|
||||
{
|
||||
title: 'ورود موفق',
|
||||
value: formatPrice(stats.totals.logins),
|
||||
hint: 'تأیید کد + رمز عبور + گوگل',
|
||||
Icon: ArrowRightOnRectangleIcon,
|
||||
iconBg: 'bg-green-100 dark:bg-green-500/15',
|
||||
iconColor: 'text-green-600 dark:text-green-400',
|
||||
},
|
||||
{
|
||||
title: 'نرخ تأیید کد',
|
||||
value: `${formatPrice(stats.totals.otp_conversion_rate)}٪`,
|
||||
hint: `${formatPrice(stats.totals.otp_verified)} تأیید از ${formatPrice(stats.totals.otp_sent)} ارسال`,
|
||||
Icon: CheckBadgeIcon,
|
||||
iconBg: 'bg-indigo-100 dark:bg-indigo-500/15',
|
||||
iconColor: 'text-indigo-600 dark:text-indigo-400',
|
||||
},
|
||||
{
|
||||
title: 'کاربران یکتا',
|
||||
value: formatPrice(stats.totals.unique_mobiles),
|
||||
hint: 'شمارههای یکتا در این بازه',
|
||||
Icon: UserGroupIcon,
|
||||
iconBg: 'bg-purple-100 dark:bg-purple-500/15',
|
||||
iconColor: 'text-purple-600 dark:text-purple-400',
|
||||
},
|
||||
{
|
||||
title: 'کد نامعتبر',
|
||||
value: formatPrice(stats.totals.otp_failed),
|
||||
hint: 'پیامکهایی که به ورود نرسیدند',
|
||||
Icon: ExclamationTriangleIcon,
|
||||
iconBg: 'bg-red-100 dark:bg-red-500/15',
|
||||
iconColor: 'text-red-600 dark:text-red-400',
|
||||
},
|
||||
] : [];
|
||||
|
||||
return (
|
||||
<div className="p-4 sm:p-8">
|
||||
<div className="max-w-7xl mx-auto">
|
||||
<PageHeader
|
||||
title="آمار ورود و پیامک"
|
||||
subtitle="تعداد کدهای ارسالی، تأییدها و ورودها برای محاسبه هزینه پیامک"
|
||||
/>
|
||||
|
||||
{/* Filters */}
|
||||
<form
|
||||
onSubmit={handleSearch}
|
||||
className="bg-white dark:bg-gray-900 ring-1 ring-gray-200 dark:ring-gray-800 rounded-2xl p-5 sm:p-6 mb-6 shadow-sm"
|
||||
>
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3">
|
||||
<div>
|
||||
<PersianDatePicker
|
||||
id="date_from"
|
||||
label="از تاریخ"
|
||||
placeholder="انتخاب تاریخ شروع"
|
||||
value={filters.date_from || ''}
|
||||
onChange={(value) => setFilters((prev) => ({ ...prev, date_from: value }))}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<PersianDatePicker
|
||||
id="date_to"
|
||||
label="تا تاریخ"
|
||||
placeholder="انتخاب تاریخ پایان"
|
||||
value={filters.date_to || ''}
|
||||
onChange={(value) => setFilters((prev) => ({ ...prev, date_to: value }))}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label htmlFor="package_name" className={labelClass}>پکیج</label>
|
||||
<select
|
||||
id="package_name"
|
||||
name="package_name"
|
||||
value={filters.package_name || ''}
|
||||
onChange={handleInputChange}
|
||||
className={inputClass}
|
||||
>
|
||||
<option value="">همه پکیجها</option>
|
||||
{packages.map((pkg) => (
|
||||
<option key={pkg.id} value={pkg.name || ''}>
|
||||
{pkg.title || pkg.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label htmlFor="event" className={labelClass}>نوع رویداد</label>
|
||||
<select
|
||||
id="event"
|
||||
name="event"
|
||||
value={filters.event || ''}
|
||||
onChange={handleInputChange}
|
||||
className={inputClass}
|
||||
>
|
||||
<option value="">همه رویدادها</option>
|
||||
{Object.entries(AUTH_EVENTS).map(([key, e]) => (
|
||||
<option key={key} value={key}>{e.label}</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label htmlFor="mobile" className={labelClass}>شماره موبایل</label>
|
||||
<input
|
||||
type="text"
|
||||
id="mobile"
|
||||
name="mobile"
|
||||
value={filters.mobile || ''}
|
||||
onChange={handleInputChange}
|
||||
className={inputClass}
|
||||
placeholder="0912xxxxxxx"
|
||||
dir="ltr"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label htmlFor="sms_unit_cost" className={labelClass}>هزینه هر پیامک (تومان)</label>
|
||||
<input
|
||||
type="text"
|
||||
id="sms_unit_cost"
|
||||
value={smsUnitCost ? formatPrice(smsUnitCost) : ''}
|
||||
onChange={handleUnitCostChange}
|
||||
className={inputClass}
|
||||
placeholder="۲۰۰۰"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-wrap items-center gap-3 mt-5">
|
||||
<button
|
||||
type="submit"
|
||||
disabled={isLoading}
|
||||
className="inline-flex items-center gap-2 px-5 py-2.5 bg-indigo-600 text-white rounded-xl text-sm font-medium hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 dark:focus:ring-offset-gray-900 focus:ring-indigo-500 disabled:opacity-50 transition-colors shadow-sm shadow-indigo-500/20"
|
||||
>
|
||||
<MagnifyingGlassIcon className="h-4 w-4" />
|
||||
اعمال فیلتر
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleReset}
|
||||
disabled={isLoading}
|
||||
className="inline-flex items-center gap-2 px-5 py-2.5 border border-gray-200 dark:border-gray-700 rounded-xl text-sm font-medium text-gray-700 dark:text-gray-200 bg-white dark:bg-gray-800 hover:bg-gray-50 dark:hover:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-offset-2 dark:focus:ring-offset-gray-900 focus:ring-indigo-500 disabled:opacity-50 transition-colors shadow-sm"
|
||||
>
|
||||
<ArrowPathIcon className="h-4 w-4" />
|
||||
پاک کردن فیلترها
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
{error && (
|
||||
<div className="mb-4 rounded-xl bg-red-50 dark:bg-red-950/40 ring-1 ring-red-200 dark:ring-red-800/60 p-4 flex items-center gap-3">
|
||||
<p className="text-sm text-red-700 dark:text-red-300">{error}</p>
|
||||
<button onClick={() => setError(null)} className="mr-auto text-red-400 hover:text-red-600">
|
||||
<svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" strokeWidth={2} stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" d="M6 18 18 6M6 6l12 12" />
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Summary cards */}
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4 mb-6">
|
||||
{cards.map(({ title, value, hint, Icon, iconBg, iconColor }) => (
|
||||
<div
|
||||
key={title}
|
||||
className="bg-white dark:bg-gray-900 rounded-2xl p-5 ring-1 ring-gray-200 dark:ring-gray-800 shadow-sm"
|
||||
>
|
||||
<div className="flex items-start gap-3">
|
||||
<div className={`inline-flex h-11 w-11 flex-shrink-0 items-center justify-center rounded-xl ${iconBg}`}>
|
||||
<Icon className={`h-5 w-5 ${iconColor}`} />
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
<p className="text-sm text-gray-500 dark:text-gray-400">{title}</p>
|
||||
<p className="text-xl font-bold text-gray-900 dark:text-gray-100 mt-0.5">{value}</p>
|
||||
<p className="text-xs text-gray-400 dark:text-gray-500 mt-1 leading-relaxed">{hint}</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Daily chart: sent vs verified OTPs */}
|
||||
{stats && stats.daily.length > 0 && (
|
||||
<div className="bg-white dark:bg-gray-900 ring-1 ring-gray-200 dark:ring-gray-800 rounded-2xl p-5 sm:p-6 mb-6 shadow-sm">
|
||||
<div className="flex flex-wrap items-center justify-between gap-3 mb-5">
|
||||
<h3 className="text-sm font-medium text-gray-900 dark:text-gray-100">روند روزانه</h3>
|
||||
<div className="flex items-center gap-4 text-xs text-gray-500 dark:text-gray-400">
|
||||
<span className="flex items-center gap-1.5">
|
||||
<span className="h-2.5 w-2.5 rounded-sm bg-amber-500" />
|
||||
کد ارسالی
|
||||
</span>
|
||||
<span className="flex items-center gap-1.5">
|
||||
<span className="h-2.5 w-2.5 rounded-sm bg-green-500" />
|
||||
کد تأییدشده
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="overflow-x-auto">
|
||||
<div className="flex items-end gap-3 min-w-full h-48" style={{ minWidth: `${stats.daily.length * 44}px` }}>
|
||||
{stats.daily.map((day) => (
|
||||
<div key={day.date} className="flex-1 flex flex-col items-center gap-2 min-w-[32px]">
|
||||
<div className="w-full flex items-end justify-center gap-0.5 h-40">
|
||||
<div
|
||||
className="w-1/2 bg-amber-500/80 rounded-t-md transition-all"
|
||||
style={{ height: `${(day.otp_sent / dailyMax) * 100}%` }}
|
||||
title={`${day.otp_sent} کد ارسالی`}
|
||||
/>
|
||||
<div
|
||||
className="w-1/2 bg-green-500/80 rounded-t-md transition-all"
|
||||
style={{ height: `${(day.otp_verified / dailyMax) * 100}%` }}
|
||||
title={`${day.otp_verified} کد تأییدشده`}
|
||||
/>
|
||||
</div>
|
||||
<span className="text-[10px] text-gray-400 dark:text-gray-500 whitespace-nowrap">
|
||||
{formatDate(day.date)}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Breakdown by event and package */}
|
||||
{stats && (
|
||||
<div className="grid grid-cols-1 lg:grid-cols-2 gap-4 mb-6">
|
||||
<div className="bg-white dark:bg-gray-900 ring-1 ring-gray-200 dark:ring-gray-800 rounded-2xl overflow-hidden shadow-sm">
|
||||
<div className="px-5 py-4 border-b border-gray-200 dark:border-gray-800">
|
||||
<h3 className="text-sm font-medium text-gray-900 dark:text-gray-100">تفکیک بر اساس رویداد</h3>
|
||||
</div>
|
||||
<ul className="divide-y divide-gray-200 dark:divide-gray-800">
|
||||
{Object.entries(AUTH_EVENTS).map(([key, e]) => (
|
||||
<li key={key} className="px-5 py-3 flex items-center justify-between gap-3">
|
||||
<span className="text-sm text-gray-700 dark:text-gray-300">
|
||||
{e.label}
|
||||
</span>
|
||||
<span className="text-sm font-semibold text-gray-900 dark:text-gray-100">
|
||||
{formatPrice(stats.by_event[key] ?? 0)}
|
||||
</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div className="bg-white dark:bg-gray-900 ring-1 ring-gray-200 dark:ring-gray-800 rounded-2xl overflow-hidden shadow-sm">
|
||||
<div className="px-5 py-4 border-b border-gray-200 dark:border-gray-800">
|
||||
<h3 className="text-sm font-medium text-gray-900 dark:text-gray-100">تفکیک بر اساس پکیج</h3>
|
||||
</div>
|
||||
{stats.by_package.length === 0 ? (
|
||||
<p className="px-5 py-8 text-sm text-center text-gray-500 dark:text-gray-400">
|
||||
دادهای برای نمایش نیست
|
||||
</p>
|
||||
) : (
|
||||
<ul className="divide-y divide-gray-200 dark:divide-gray-800">
|
||||
{stats.by_package.map((row) => (
|
||||
<li key={row.package_name} className="px-5 py-3 flex items-center justify-between gap-3">
|
||||
<span className="text-sm text-gray-700 dark:text-gray-300 truncate" dir="ltr">
|
||||
{packages.find((p) => p.name === row.package_name)?.title || row.package_name}
|
||||
</span>
|
||||
<span className="flex items-center gap-3 flex-shrink-0 text-xs">
|
||||
<span className="px-2 py-0.5 rounded-md bg-amber-100 text-amber-800 dark:bg-amber-900/30 dark:text-amber-300">
|
||||
{formatPrice(row.sms)} پیامک
|
||||
</span>
|
||||
<span className="px-2 py-0.5 rounded-md bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-300">
|
||||
{formatPrice(row.logins)} ورود
|
||||
</span>
|
||||
</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Raw event log */}
|
||||
<div className="bg-white dark:bg-gray-900 ring-1 ring-gray-200 dark:ring-gray-800 rounded-2xl overflow-hidden shadow-sm">
|
||||
<div className="px-5 py-4 flex items-center justify-between border-b border-gray-200 dark:border-gray-800">
|
||||
<h3 className="text-sm font-medium text-gray-900 dark:text-gray-100">
|
||||
{logs ? `${formatPrice(logs.total)} رویداد یافت شد` : 'در حال بارگذاری...'}
|
||||
</h3>
|
||||
</div>
|
||||
|
||||
{isLoading ? (
|
||||
<div className="flex justify-center items-center py-16">
|
||||
<div className="h-10 w-10 border-4 border-indigo-200 dark:border-indigo-800 border-t-indigo-600 rounded-full animate-spin" />
|
||||
</div>
|
||||
) : !logs || logs.data.length === 0 ? (
|
||||
<div className="text-center py-16">
|
||||
<div className="mx-auto h-12 w-12 rounded-xl bg-gray-100 dark:bg-gray-800 flex items-center justify-center mb-3">
|
||||
<DevicePhoneMobileIcon className="h-6 w-6 text-gray-400" />
|
||||
</div>
|
||||
<p className="text-gray-500 dark:text-gray-400 text-sm">
|
||||
هیچ رویدادی با این فیلترها یافت نشد
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
{/* Mobile: stacked cards */}
|
||||
<ul className="divide-y divide-gray-200 dark:divide-gray-800 md:hidden">
|
||||
{logs.data.map((log: AuthLog) => (
|
||||
<li key={log.id} className="px-5 py-4 space-y-2">
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
<div className="min-w-0">
|
||||
<p className="text-sm font-semibold text-gray-900 dark:text-gray-100 truncate" dir="ltr">
|
||||
{log.mobile || log.email || '—'}
|
||||
</p>
|
||||
<p className="text-xs text-gray-500 dark:text-gray-400 mt-0.5 truncate">
|
||||
{log.package_name || '—'}
|
||||
</p>
|
||||
</div>
|
||||
<span className={`flex-shrink-0 px-2.5 py-1 inline-flex text-xs leading-5 font-semibold rounded-lg ${eventBadgeClass(log.event, log.success)}`}>
|
||||
{getAuthEventLabel(log.event)}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex items-center justify-between gap-3 text-xs text-gray-400 dark:text-gray-500">
|
||||
<span dir="ltr">{log.ip || '—'}</span>
|
||||
<span>{formatDate(log.created_at)} {formatTime(log.created_at)}</span>
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
|
||||
{/* Desktop: table */}
|
||||
<div className="hidden md:block overflow-x-auto">
|
||||
<table className="min-w-full divide-y divide-gray-200 dark:divide-gray-800">
|
||||
<thead className="bg-gray-50 dark:bg-gray-800/60">
|
||||
<tr className="text-right text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
|
||||
<th className="px-4 py-3">کاربر</th>
|
||||
<th className="px-4 py-3">رویداد</th>
|
||||
<th className="px-4 py-3">پیامک</th>
|
||||
<th className="px-4 py-3">پکیج</th>
|
||||
<th className="px-4 py-3">IP</th>
|
||||
<th className="px-4 py-3">تاریخ و ساعت</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-gray-200 dark:divide-gray-800">
|
||||
{logs.data.map((log: AuthLog) => (
|
||||
<tr key={log.id} className="hover:bg-gray-50 dark:hover:bg-gray-800/40 transition-colors">
|
||||
<td className="px-4 py-3.5">
|
||||
<div className="text-sm text-gray-900 dark:text-gray-100" dir="ltr">
|
||||
{log.mobile || '—'}
|
||||
</div>
|
||||
<div className="text-xs text-gray-500 dark:text-gray-400" dir="ltr">
|
||||
{log.email || '—'}
|
||||
</div>
|
||||
</td>
|
||||
<td className="px-4 py-3.5 whitespace-nowrap">
|
||||
<span className={`px-2.5 py-1 inline-flex text-xs leading-5 font-semibold rounded-lg ${eventBadgeClass(log.event, log.success)}`}>
|
||||
{getAuthEventLabel(log.event)}
|
||||
</span>
|
||||
</td>
|
||||
<td className="px-4 py-3.5 text-sm whitespace-nowrap">
|
||||
{log.sms_sent ? (
|
||||
<span className="text-amber-600 dark:text-amber-400 font-medium">۱</span>
|
||||
) : (
|
||||
<span className="text-gray-400 dark:text-gray-500">—</span>
|
||||
)}
|
||||
</td>
|
||||
<td className="px-4 py-3.5 text-sm text-gray-700 dark:text-gray-300 whitespace-nowrap">
|
||||
{log.package_name || '—'}
|
||||
</td>
|
||||
<td className="px-4 py-3.5 text-xs text-gray-500 dark:text-gray-400 whitespace-nowrap" dir="ltr">
|
||||
{log.ip || '—'}
|
||||
</td>
|
||||
<td className="px-4 py-3.5 text-xs text-gray-500 dark:text-gray-400 whitespace-nowrap">
|
||||
{formatDate(log.created_at)} {formatTime(log.created_at)}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* Pagination */}
|
||||
{logs && logs.last_page > 1 && (
|
||||
<div className="flex items-center justify-between px-5 py-3.5 border-t border-gray-200 dark:border-gray-800">
|
||||
<button
|
||||
onClick={() => goToPage(page - 1)}
|
||||
disabled={page <= 1 || isLoading}
|
||||
className="px-4 py-2 text-sm border border-gray-200 dark:border-gray-700 rounded-xl text-gray-700 dark:text-gray-200 bg-white dark:bg-gray-800 hover:bg-gray-50 dark:hover:bg-gray-700 disabled:opacity-40 disabled:cursor-not-allowed transition-colors"
|
||||
>
|
||||
قبلی
|
||||
</button>
|
||||
<span className="text-sm text-gray-600 dark:text-gray-400">
|
||||
صفحه {logs.current_page} از {logs.last_page}
|
||||
</span>
|
||||
<button
|
||||
onClick={() => goToPage(page + 1)}
|
||||
disabled={page >= logs.last_page || isLoading}
|
||||
className="px-4 py-2 text-sm border border-gray-200 dark:border-gray-700 rounded-xl text-gray-700 dark:text-gray-200 bg-white dark:bg-gray-800 hover:bg-gray-50 dark:hover:bg-gray-700 disabled:opacity-40 disabled:cursor-not-allowed transition-colors"
|
||||
>
|
||||
بعدی
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
import { useAuth } from '@/contexts/AuthContext';
|
||||
import Link from 'next/link';
|
||||
import { UsersIcon, CubeIcon, TagIcon, BellIcon, GiftIcon, ShoppingBagIcon, CalculatorIcon } from '@heroicons/react/24/outline';
|
||||
import { UsersIcon, CubeIcon, TagIcon, BellIcon, GiftIcon, ShoppingBagIcon, CalculatorIcon, ChartBarIcon } from '@heroicons/react/24/outline';
|
||||
import { MegaphoneIcon } from 'lucide-react';
|
||||
|
||||
export default function Dashboard() {
|
||||
@@ -36,6 +36,15 @@ export default function Dashboard() {
|
||||
iconColor: 'text-cyan-600 dark:text-cyan-400',
|
||||
hoverBorder: 'hover:border-cyan-300 dark:hover:border-cyan-700',
|
||||
},
|
||||
{
|
||||
href: '/admin/auth-analytics',
|
||||
title: 'آمار ورود و پیامک',
|
||||
desc: 'تعداد کدهای ارسالی، تأییدها و ورودها برای محاسبه هزینه پیامک',
|
||||
Icon: ChartBarIcon,
|
||||
iconBg: 'bg-amber-100 dark:bg-amber-500/15',
|
||||
iconColor: 'text-amber-600 dark:text-amber-400',
|
||||
hoverBorder: 'hover:border-amber-300 dark:hover:border-amber-700',
|
||||
},
|
||||
{
|
||||
href: '/admin/packages',
|
||||
title: 'مدیریت پکیجها',
|
||||
@@ -113,7 +122,7 @@ export default function Dashboard() {
|
||||
<p className="text-sm text-gray-500 dark:text-gray-400 mt-1.5 leading-relaxed">
|
||||
{desc}
|
||||
</p>
|
||||
<div className="mt-4 flex items-center text-xs font-medium text-indigo-600 dark:text-indigo-400 opacity-0 group-hover:opacity-100 transition-opacity">
|
||||
<div className="mt-4 flex items-center text-xs font-medium text-indigo-600 dark:text-indigo-400 opacity-100 md:opacity-0 md:group-hover:opacity-100 transition-opacity">
|
||||
ورود به بخش
|
||||
<svg className="h-4 w-4 mr-1 rotate-180" fill="none" viewBox="0 0 24 24" strokeWidth={2} stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" d="M13.5 4.5 21 12m0 0-7.5 7.5M21 12H3" />
|
||||
|
||||
@@ -23,7 +23,9 @@ export default function AdminLayout({
|
||||
) : (
|
||||
<AuthGuard>
|
||||
<Sidebar />
|
||||
<main className="lg:pr-64 min-h-screen">
|
||||
{/* Extra top padding on mobile so content clears the
|
||||
fixed hamburger button; the desktop sidebar needs none. */}
|
||||
<main className="lg:pr-64 min-h-screen pt-16 lg:pt-0">
|
||||
{children}
|
||||
</main>
|
||||
</AuthGuard>
|
||||
|
||||
@@ -6,6 +6,7 @@ import { packagesApi } from '@/lib/api/packages';
|
||||
import PackageList from '@/components/admin/packages/PackageList';
|
||||
import PackageForm from '@/components/admin/packages/PackageForm';
|
||||
import PageHeader from '@/components/admin/PageHeader';
|
||||
import ConfirmDialog from '@/components/admin/ConfirmDialog';
|
||||
import { showToast } from '@/components/Toast';
|
||||
import { PackageName, CreatePackageData, UpdatePackageData } from '@/types/package';
|
||||
import { PlusIcon } from '@heroicons/react/24/outline';
|
||||
@@ -17,6 +18,7 @@ export default function PackagesPage() {
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [isFormVisible, setIsFormVisible] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [deleteTarget, setDeleteTarget] = useState<PackageName | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (token) {
|
||||
@@ -47,10 +49,13 @@ export default function PackagesPage() {
|
||||
setIsFormVisible(true);
|
||||
};
|
||||
|
||||
const handleDelete = async (pkg: PackageName) => {
|
||||
if (!confirm(`آیا از حذف پکیج "${pkg.title}" اطمینان دارید؟`)) {
|
||||
return;
|
||||
}
|
||||
const handleDelete = (pkg: PackageName) => {
|
||||
setDeleteTarget(pkg);
|
||||
};
|
||||
|
||||
const confirmDelete = async () => {
|
||||
if (!deleteTarget) return;
|
||||
const pkg = deleteTarget;
|
||||
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
@@ -63,6 +68,7 @@ export default function PackagesPage() {
|
||||
setError(err instanceof Error ? err.message : 'خطا در حذف پکیج');
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
setDeleteTarget(null);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -139,6 +145,16 @@ export default function PackagesPage() {
|
||||
isLoading={isLoading}
|
||||
/>
|
||||
)}
|
||||
|
||||
<ConfirmDialog
|
||||
open={!!deleteTarget}
|
||||
title="حذف پکیج"
|
||||
message={`آیا از حذف پکیج «${deleteTarget?.title || deleteTarget?.name || ''}» اطمینان دارید؟`}
|
||||
confirmLabel="حذف"
|
||||
isLoading={isLoading}
|
||||
onConfirm={confirmDelete}
|
||||
onCancel={() => setDeleteTarget(null)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -7,6 +7,7 @@ import { productsApi } from '@/lib/api/products';
|
||||
import ProductList from '@/components/admin/products/ProductList';
|
||||
import ProductForm from '@/components/admin/products/ProductForm';
|
||||
import PageHeader from '@/components/admin/PageHeader';
|
||||
import ConfirmDialog from '@/components/admin/ConfirmDialog';
|
||||
import { showToast } from '@/components/Toast';
|
||||
import { PackageName } from '@/types/package';
|
||||
import { Product, CreateProductData, UpdateProductData } from '@/types/product';
|
||||
@@ -22,6 +23,7 @@ export default function ProductsPage() {
|
||||
const [isLoadingPackages, setIsLoadingPackages] = useState(false);
|
||||
const [isFormVisible, setIsFormVisible] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [deleteTarget, setDeleteTarget] = useState<Product | null>(null);
|
||||
|
||||
const initialLoadRef = useRef(false);
|
||||
const prevPackageRef = useRef<string | null>(null);
|
||||
@@ -94,11 +96,13 @@ export default function ProductsPage() {
|
||||
setIsFormVisible(true);
|
||||
};
|
||||
|
||||
const handleDelete = async (product: Product) => {
|
||||
if (!selectedPackage) return;
|
||||
if (!confirm(`آیا از حذف محصول "${product.title}" اطمینان دارید؟`)) {
|
||||
return;
|
||||
}
|
||||
const handleDelete = (product: Product) => {
|
||||
setDeleteTarget(product);
|
||||
};
|
||||
|
||||
const confirmDelete = async () => {
|
||||
if (!selectedPackage || !deleteTarget) return;
|
||||
const product = deleteTarget;
|
||||
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
@@ -114,6 +118,7 @@ export default function ProductsPage() {
|
||||
setError(err instanceof Error ? err.message : 'خطا در حذف محصول');
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
setDeleteTarget(null);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -226,6 +231,16 @@ export default function ProductsPage() {
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
<ConfirmDialog
|
||||
open={!!deleteTarget}
|
||||
title="حذف محصول"
|
||||
message={`آیا از حذف محصول «${deleteTarget?.title || ''}» اطمینان دارید؟`}
|
||||
confirmLabel="حذف"
|
||||
isLoading={isLoading}
|
||||
onConfirm={confirmDelete}
|
||||
onCancel={() => setDeleteTarget(null)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -6,6 +6,7 @@ import { promotionsApi } from '@/lib/api/promotions';
|
||||
import PromotionList from '@/components/admin/promotions/PromotionList';
|
||||
import PromotionForm from '@/components/admin/promotions/PromotionForm';
|
||||
import PageHeader from '@/components/admin/PageHeader';
|
||||
import ConfirmDialog from '@/components/admin/ConfirmDialog';
|
||||
import { showToast } from '@/components/Toast';
|
||||
import { Promotion, CreatePromotionData, UpdatePromotionData } from '@/types/promotion';
|
||||
import { PlusIcon } from '@heroicons/react/24/outline';
|
||||
@@ -17,6 +18,7 @@ export default function PromotionsPage() {
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [isFormVisible, setIsFormVisible] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [deleteTarget, setDeleteTarget] = useState<Promotion | null>(null);
|
||||
|
||||
const initialLoadRef = useRef(false);
|
||||
|
||||
@@ -50,10 +52,13 @@ export default function PromotionsPage() {
|
||||
setIsFormVisible(true);
|
||||
};
|
||||
|
||||
const handleDelete = async (promotion: Promotion) => {
|
||||
if (!confirm(`آیا از حذف تبلیغ "${promotion.title || 'بدون عنوان'}" اطمینان دارید؟`)) {
|
||||
return;
|
||||
}
|
||||
const handleDelete = (promotion: Promotion) => {
|
||||
setDeleteTarget(promotion);
|
||||
};
|
||||
|
||||
const confirmDelete = async () => {
|
||||
if (!deleteTarget) return;
|
||||
const promotion = deleteTarget;
|
||||
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
@@ -66,6 +71,7 @@ export default function PromotionsPage() {
|
||||
setError(err instanceof Error ? err.message : 'خطا در حذف تبلیغ');
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
setDeleteTarget(null);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -159,6 +165,16 @@ export default function PromotionsPage() {
|
||||
isLoading={isLoading}
|
||||
/>
|
||||
)}
|
||||
|
||||
<ConfirmDialog
|
||||
open={!!deleteTarget}
|
||||
title="حذف تبلیغ"
|
||||
message={`آیا از حذف تبلیغ «${deleteTarget?.title || 'بدون عنوان'}» اطمینان دارید؟`}
|
||||
confirmLabel="حذف"
|
||||
isLoading={isLoading}
|
||||
onConfirm={confirmDelete}
|
||||
onCancel={() => setDeleteTarget(null)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -15,7 +15,7 @@ import {
|
||||
getPurchaseStatusLabel,
|
||||
} from '@/types/purchase';
|
||||
import { PackageName } from '@/types/package';
|
||||
import { formatPrice, formatDate, getProductTypeLabel, getPurchaseFinalPrice } from '@/lib/utils';
|
||||
import { formatPrice, formatDate, formatTime, getProductTypeLabel, getPurchaseFinalPrice } from '@/lib/utils';
|
||||
import { MagnifyingGlassIcon, ArrowPathIcon } from '@heroicons/react/24/outline';
|
||||
|
||||
const statusBadgeClass = (status: number): string => {
|
||||
@@ -148,7 +148,7 @@ export default function PurchasesPage() {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-3 mt-5">
|
||||
<div className="flex flex-wrap items-center gap-3 mt-5">
|
||||
<button
|
||||
type="submit"
|
||||
disabled={isLoading}
|
||||
@@ -202,7 +202,55 @@ export default function PurchasesPage() {
|
||||
<p className="text-gray-500 dark:text-gray-400 text-sm">هیچ خریدی با این فیلترها یافت نشد</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="overflow-x-auto">
|
||||
<>
|
||||
{/* Mobile: stacked cards */}
|
||||
<ul className="divide-y divide-gray-200 dark:divide-gray-800 md:hidden">
|
||||
{result.data.map((purchase) => (
|
||||
<li key={purchase.id} className="px-5 py-4 space-y-2.5">
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
<div className="min-w-0">
|
||||
<p className="text-sm font-semibold text-gray-900 dark:text-gray-100 truncate">
|
||||
{purchase.product?.title || '—'}
|
||||
</p>
|
||||
<p className="text-xs text-gray-500 dark:text-gray-400 mt-0.5 truncate">
|
||||
{purchase.product?.package_name?.title || purchase.product?.package_name?.name || '—'}
|
||||
{purchase.product ? ` • ${getProductTypeLabel(purchase.product.type)}` : ''}
|
||||
</p>
|
||||
</div>
|
||||
<span className={`flex-shrink-0 px-2.5 py-1 inline-flex text-xs leading-5 font-semibold rounded-lg ${statusBadgeClass(purchase.status)}`}>
|
||||
{getPurchaseStatusLabel(purchase.status)}
|
||||
</span>
|
||||
</div>
|
||||
<div className="text-xs text-gray-500 dark:text-gray-400 space-y-0.5">
|
||||
<p className="font-medium text-gray-700 dark:text-gray-300">
|
||||
{purchase.user?.full_name?.trim() || 'بدون نام'}
|
||||
</p>
|
||||
{purchase.user?.email && (
|
||||
<p dir="ltr" className="text-right truncate">{purchase.user.email}</p>
|
||||
)}
|
||||
{purchase.user?.mobile && (
|
||||
<p dir="ltr" className="text-right truncate">{purchase.user.mobile}</p>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center justify-between gap-3 pt-2.5 border-t border-gray-100 dark:border-gray-800/60">
|
||||
<span className="text-sm font-bold text-gray-900 dark:text-gray-100">
|
||||
{formatPrice(getPurchaseFinalPrice(purchase))} تومان
|
||||
</span>
|
||||
<div className="flex flex-col items-end gap-1">
|
||||
<span className="px-2 py-0.5 text-[11px] font-medium rounded-md bg-gray-100 text-gray-600 dark:bg-gray-800 dark:text-gray-300">
|
||||
{getGatewayLabel(purchase.gateway)}
|
||||
</span>
|
||||
<span className="text-[11px] text-gray-400 dark:text-gray-500">
|
||||
{formatDate(purchase.created_at)} {formatTime(purchase.created_at)}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
|
||||
{/* Desktop: table */}
|
||||
<div className="hidden md:block overflow-x-auto">
|
||||
<table className="min-w-full divide-y divide-gray-200 dark:divide-gray-800">
|
||||
<thead className="bg-gray-50 dark:bg-gray-800/60">
|
||||
<tr className="text-right text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
|
||||
@@ -212,7 +260,7 @@ export default function PurchasesPage() {
|
||||
<th className="px-4 py-3">قیمت نهایی</th>
|
||||
<th className="px-4 py-3">منبع پرداخت</th>
|
||||
<th className="px-4 py-3">وضعیت</th>
|
||||
<th className="px-4 py-3">تاریخ</th>
|
||||
<th className="px-4 py-3">تاریخ و ساعت</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-gray-200 dark:divide-gray-800">
|
||||
@@ -254,13 +302,14 @@ export default function PurchasesPage() {
|
||||
</span>
|
||||
</td>
|
||||
<td className="px-4 py-3.5 text-xs text-gray-500 dark:text-gray-400 whitespace-nowrap">
|
||||
{formatDate(purchase.created_at)}
|
||||
{formatDate(purchase.created_at)} {formatTime(purchase.created_at)}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* Pagination */}
|
||||
|
||||
@@ -5,6 +5,7 @@ import { useAuth } from '@/contexts/AuthContext';
|
||||
import { referralApi } from '@/lib/api/referral';
|
||||
import ReferralList from '@/components/admin/referral/ReferralList';
|
||||
import PageHeader from '@/components/admin/PageHeader';
|
||||
import ConfirmDialog from '@/components/admin/ConfirmDialog';
|
||||
import { showToast } from '@/components/Toast';
|
||||
import { ReferralRewardUser } from '@/types/referral';
|
||||
import { ArrowPathIcon } from '@heroicons/react/24/outline';
|
||||
@@ -16,6 +17,7 @@ export default function ReferralRewardsPage() {
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [fulfillingId, setFulfillingId] = useState<number | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [fulfillTarget, setFulfillTarget] = useState<ReferralRewardUser | null>(null);
|
||||
|
||||
const initialLoadRef = useRef(false);
|
||||
|
||||
@@ -40,10 +42,13 @@ export default function ReferralRewardsPage() {
|
||||
}
|
||||
};
|
||||
|
||||
const handleFulfill = async (user: ReferralRewardUser) => {
|
||||
if (!confirm(`آیا از اعطای یک ماه اشتراک رایگان به «${user.name || user.mobile || user.email}» اطمینان دارید؟`)) {
|
||||
return;
|
||||
}
|
||||
const handleFulfill = (user: ReferralRewardUser) => {
|
||||
setFulfillTarget(user);
|
||||
};
|
||||
|
||||
const confirmFulfill = async () => {
|
||||
if (!fulfillTarget) return;
|
||||
const user = fulfillTarget;
|
||||
|
||||
setFulfillingId(user.id);
|
||||
setIsLoading(true);
|
||||
@@ -58,6 +63,7 @@ export default function ReferralRewardsPage() {
|
||||
} finally {
|
||||
setFulfillingId(null);
|
||||
setIsLoading(false);
|
||||
setFulfillTarget(null);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -104,6 +110,17 @@ export default function ReferralRewardsPage() {
|
||||
fulfillingId={fulfillingId}
|
||||
/>
|
||||
)}
|
||||
|
||||
<ConfirmDialog
|
||||
open={!!fulfillTarget}
|
||||
title="اعطای پاداش معرفی"
|
||||
message={`آیا از اعطای یک ماه اشتراک رایگان به «${fulfillTarget?.name || fulfillTarget?.mobile || fulfillTarget?.email || ''}» اطمینان دارید؟`}
|
||||
confirmLabel="اعطای اشتراک"
|
||||
tone="primary"
|
||||
isLoading={isLoading}
|
||||
onConfirm={confirmFulfill}
|
||||
onCancel={() => setFulfillTarget(null)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -7,6 +7,7 @@ import { remindersApi } from '@/lib/api/reminders';
|
||||
import ReminderList from '@/components/admin/reminders/ReminderList';
|
||||
import ReminderForm from '@/components/admin/reminders/ReminderForm';
|
||||
import PageHeader from '@/components/admin/PageHeader';
|
||||
import ConfirmDialog from '@/components/admin/ConfirmDialog';
|
||||
import { showToast } from '@/components/Toast';
|
||||
import { PackageName } from '@/types/package';
|
||||
import { Reminder, CreateReminderData, UpdateReminderData } from '@/types/reminder';
|
||||
@@ -22,6 +23,7 @@ export default function RemindersPage() {
|
||||
const [isLoadingPackages, setIsLoadingPackages] = useState(false);
|
||||
const [isFormVisible, setIsFormVisible] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [deleteTarget, setDeleteTarget] = useState<Reminder | null>(null);
|
||||
|
||||
const initialLoadRef = useRef(false);
|
||||
const prevPackageRef = useRef<string | null>(null);
|
||||
@@ -94,11 +96,13 @@ export default function RemindersPage() {
|
||||
setIsFormVisible(true);
|
||||
};
|
||||
|
||||
const handleDelete = async (reminder: Reminder) => {
|
||||
if (!selectedPackage) return;
|
||||
if (!confirm(`آیا از حذف یادآوری "${reminder.title}" اطمینان دارید؟`)) {
|
||||
return;
|
||||
}
|
||||
const handleDelete = (reminder: Reminder) => {
|
||||
setDeleteTarget(reminder);
|
||||
};
|
||||
|
||||
const confirmDelete = async () => {
|
||||
if (!selectedPackage || !deleteTarget) return;
|
||||
const reminder = deleteTarget;
|
||||
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
@@ -114,6 +118,7 @@ export default function RemindersPage() {
|
||||
setError(err instanceof Error ? err.message : 'خطا در حذف یادآوری');
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
setDeleteTarget(null);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -226,6 +231,16 @@ export default function RemindersPage() {
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
<ConfirmDialog
|
||||
open={!!deleteTarget}
|
||||
title="حذف یادآوری"
|
||||
message={`آیا از حذف یادآوری «${deleteTarget?.title || ''}» اطمینان دارید؟`}
|
||||
confirmLabel="حذف"
|
||||
isLoading={isLoading}
|
||||
onConfirm={confirmDelete}
|
||||
onCancel={() => setDeleteTarget(null)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -11,6 +11,7 @@ import UserEditForm from '@/components/admin/users/UserEditForm';
|
||||
import PackageSelector from '@/components/admin/users/PackageSelector';
|
||||
import PageHeader from '@/components/admin/PageHeader';
|
||||
import StepIndicator from '@/components/admin/StepIndicator';
|
||||
import ConfirmDialog from '@/components/admin/ConfirmDialog';
|
||||
import { showToast } from '@/components/Toast';
|
||||
import { User, Product, UpdateUserProfileData } from '@/types/user';
|
||||
import { PackageName } from '@/types/package';
|
||||
@@ -159,7 +160,9 @@ export default function UsersPage() {
|
||||
}
|
||||
};
|
||||
|
||||
const handleDeleteUser = async () => {
|
||||
const [isDeleteConfirmOpen, setIsDeleteConfirmOpen] = useState(false);
|
||||
|
||||
const handleDeleteUser = () => {
|
||||
if (!user) return;
|
||||
const identifier = user.email || user.mobile;
|
||||
if (!identifier) {
|
||||
@@ -167,9 +170,13 @@ export default function UsersPage() {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!confirm('آیا از حذف این کاربر اطمینان دارید؟ این عملیات قابل بازگشت نیست.')) {
|
||||
return;
|
||||
}
|
||||
setIsDeleteConfirmOpen(true);
|
||||
};
|
||||
|
||||
const confirmDeleteUser = async () => {
|
||||
if (!user) return;
|
||||
const identifier = user.email || user.mobile;
|
||||
if (!identifier) return;
|
||||
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
@@ -178,6 +185,7 @@ export default function UsersPage() {
|
||||
await usersApi.deleteUser(identifier, token!);
|
||||
showToast('success', 'کاربر با موفقیت حذف شد');
|
||||
setUser(null);
|
||||
setIsDeleteConfirmOpen(false);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'خطا در حذف کاربر');
|
||||
} finally {
|
||||
@@ -324,6 +332,16 @@ export default function UsersPage() {
|
||||
isLoading={isLoading}
|
||||
/>
|
||||
)}
|
||||
|
||||
<ConfirmDialog
|
||||
open={isDeleteConfirmOpen && !!user}
|
||||
title="حذف کاربر"
|
||||
message="آیا از حذف این کاربر اطمینان دارید؟ این عملیات قابل بازگشت نیست."
|
||||
confirmLabel="حذف کاربر"
|
||||
isLoading={isLoading}
|
||||
onConfirm={confirmDeleteUser}
|
||||
onCancel={() => setIsDeleteConfirmOpen(false)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
+1
-2
@@ -35,8 +35,7 @@ export default function RootLayout({
|
||||
/>
|
||||
{/* 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" />
|
||||
<link rel="icon" href="/favicon.png" type="image/png" sizes="512x512" />
|
||||
|
||||
{/* Preload critical resources */}
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com" />
|
||||
|
||||
+2
-2
@@ -7,8 +7,8 @@ export default function Home() {
|
||||
const router = useRouter();
|
||||
|
||||
useEffect(() => {
|
||||
router.push('/admin/login');
|
||||
router.replace('/admin/login');
|
||||
}, [router]);
|
||||
|
||||
|
||||
return null;
|
||||
}
|
||||
@@ -40,7 +40,7 @@ export default function ToastContainer() {
|
||||
if (toasts.length === 0) return null;
|
||||
|
||||
return (
|
||||
<div className="fixed top-4 left-1/2 -translate-x-1/2 z-[100] flex flex-col gap-2 w-full max-w-md pointer-events-none">
|
||||
<div className="fixed top-4 left-1/2 -translate-x-1/2 z-[100] flex flex-col gap-2 w-full max-w-md px-4 pointer-events-none">
|
||||
{toasts.map((toast) => (
|
||||
<div
|
||||
key={toast.id}
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect } from 'react';
|
||||
import { ExclamationTriangleIcon } from '@heroicons/react/24/outline';
|
||||
|
||||
interface ConfirmDialogProps {
|
||||
open: boolean;
|
||||
title: string;
|
||||
message: string;
|
||||
confirmLabel?: string;
|
||||
cancelLabel?: string;
|
||||
tone?: 'danger' | 'primary';
|
||||
isLoading?: boolean;
|
||||
onConfirm: () => void;
|
||||
onCancel: () => void;
|
||||
}
|
||||
|
||||
// Styled replacement for the native confirm() dialog so destructive actions
|
||||
// match the rest of the panel.
|
||||
export default function ConfirmDialog({
|
||||
open,
|
||||
title,
|
||||
message,
|
||||
confirmLabel = 'تأیید',
|
||||
cancelLabel = 'انصراف',
|
||||
tone = 'danger',
|
||||
isLoading = false,
|
||||
onConfirm,
|
||||
onCancel,
|
||||
}: ConfirmDialogProps) {
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
const handleKeyDown = (event: KeyboardEvent) => {
|
||||
if (event.key === 'Escape' && !isLoading) onCancel();
|
||||
};
|
||||
document.addEventListener('keydown', handleKeyDown);
|
||||
return () => document.removeEventListener('keydown', handleKeyDown);
|
||||
}, [open, isLoading, onCancel]);
|
||||
|
||||
if (!open) return null;
|
||||
|
||||
const confirmClass =
|
||||
tone === 'danger'
|
||||
? 'bg-red-600 hover:bg-red-700 focus:ring-red-500/30 shadow-red-500/20'
|
||||
: 'bg-indigo-600 hover:bg-indigo-700 focus:ring-indigo-500/30 shadow-indigo-500/20';
|
||||
const iconWrapClass =
|
||||
tone === 'danger'
|
||||
? 'bg-red-50 text-red-600 dark:bg-red-500/10 dark:text-red-400'
|
||||
: 'bg-indigo-50 text-indigo-600 dark:bg-indigo-500/10 dark:text-indigo-400';
|
||||
|
||||
return (
|
||||
<div
|
||||
className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 dark:bg-black/60 p-4"
|
||||
onClick={() => {
|
||||
if (!isLoading) onCancel();
|
||||
}}
|
||||
>
|
||||
<div
|
||||
className="bg-white dark:bg-gray-900 rounded-2xl shadow-xl ring-1 ring-gray-200 dark:ring-gray-800 w-full max-w-md"
|
||||
dir="rtl"
|
||||
onClick={(event) => event.stopPropagation()}
|
||||
role="alertdialog"
|
||||
aria-modal="true"
|
||||
aria-label={title}
|
||||
>
|
||||
<div className="px-6 py-5 flex items-start gap-4">
|
||||
<div className={`flex-shrink-0 h-11 w-11 rounded-xl flex items-center justify-center ${iconWrapClass}`}>
|
||||
<ExclamationTriangleIcon className="h-6 w-6" />
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
<h3 className="text-base font-semibold text-gray-900 dark:text-gray-100">{title}</h3>
|
||||
<p className="mt-1.5 text-sm text-gray-500 dark:text-gray-400 leading-6">{message}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end gap-3 px-6 py-4 border-t border-gray-100 dark:border-gray-800">
|
||||
<button
|
||||
type="button"
|
||||
onClick={onCancel}
|
||||
disabled={isLoading}
|
||||
className="px-5 py-2.5 rounded-xl border border-gray-200 dark:border-gray-700 text-sm font-medium text-gray-700 dark:text-gray-200 bg-white dark:bg-gray-800 hover:bg-gray-50 dark:hover:bg-gray-700 disabled:opacity-50 transition-colors"
|
||||
>
|
||||
{cancelLabel}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onConfirm}
|
||||
disabled={isLoading}
|
||||
className={`inline-flex items-center gap-2 px-5 py-2.5 rounded-xl text-white text-sm font-medium focus:outline-none focus:ring-2 focus:ring-offset-2 dark:focus:ring-offset-gray-900 disabled:opacity-50 transition-colors shadow-sm ${confirmClass}`}
|
||||
>
|
||||
{isLoading && (
|
||||
<span className="h-4 w-4 border-2 border-white/40 border-t-white rounded-full animate-spin" />
|
||||
)}
|
||||
{isLoading ? 'در حال انجام...' : confirmLabel}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -139,7 +139,7 @@ export default function PersianDatePicker({
|
||||
</button>
|
||||
|
||||
{open && (
|
||||
<div className="absolute right-0 z-50 mt-2 bg-white dark:bg-gray-900 ring-1 ring-gray-200 dark:ring-gray-800 rounded-2xl shadow-xl p-2">
|
||||
<div className="absolute right-0 z-50 mt-2 bg-white dark:bg-gray-900 ring-1 ring-gray-200 dark:ring-gray-800 rounded-2xl shadow-xl p-2 max-w-[calc(100vw-3rem)] overflow-x-auto">
|
||||
<DayPicker
|
||||
mode="single"
|
||||
selected={selectedDate ?? undefined}
|
||||
|
||||
@@ -14,6 +14,7 @@ import {
|
||||
ShoppingBagIcon,
|
||||
HomeIcon,
|
||||
CalculatorIcon,
|
||||
ChartBarIcon,
|
||||
Bars3Icon,
|
||||
XMarkIcon,
|
||||
} from '@heroicons/react/24/outline';
|
||||
@@ -25,6 +26,7 @@ const navItems = [
|
||||
{ href: '/admin/users', label: 'کاربران', Icon: UsersIcon },
|
||||
{ href: '/admin/purchases', label: 'خریدها', Icon: ShoppingBagIcon },
|
||||
{ href: '/admin/accounting', label: 'حسابداری', Icon: CalculatorIcon },
|
||||
{ href: '/admin/auth-analytics', label: 'ورود و پیامک', Icon: ChartBarIcon },
|
||||
{ href: '/admin/packages', label: 'پکیجها', Icon: CubeIcon },
|
||||
{ href: '/admin/products', label: 'محصولات', Icon: TagIcon },
|
||||
{ href: '/admin/reminders', label: 'یادآوریها', Icon: BellIcon },
|
||||
|
||||
@@ -34,7 +34,7 @@ export default function StepIndicator({ steps }: StepIndicatorProps) {
|
||||
)}
|
||||
</div>
|
||||
<span
|
||||
className={`mt-1.5 text-xs font-medium whitespace-nowrap ${
|
||||
className={`mt-1.5 text-[10px] sm:text-xs font-medium whitespace-nowrap ${
|
||||
step.isCurrent
|
||||
? 'text-indigo-700 dark:text-indigo-400'
|
||||
: step.isCompleted
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
import { apiClient } from './client';
|
||||
import { AuthLogFilters, AuthStats, PaginatedAuthLogs } from '@/types/auth-log';
|
||||
|
||||
const buildAuthLogQuery = (filters: AuthLogFilters): string => {
|
||||
const params = new URLSearchParams();
|
||||
|
||||
if (filters.event) params.append('event', filters.event);
|
||||
if (filters.mobile) params.append('mobile', filters.mobile);
|
||||
if (filters.email) params.append('email', filters.email);
|
||||
if (filters.package_name) params.append('package_name', filters.package_name);
|
||||
if (filters.success !== undefined) params.append('success', filters.success ? '1' : '0');
|
||||
if (filters.sms_only) params.append('sms_only', '1');
|
||||
if (filters.date_from) params.append('date_from', filters.date_from);
|
||||
if (filters.date_to) params.append('date_to', filters.date_to);
|
||||
if (filters.time_from) params.append('time_from', filters.time_from);
|
||||
if (filters.time_to) params.append('time_to', filters.time_to);
|
||||
if (filters.sms_unit_cost !== undefined) params.append('sms_unit_cost', String(filters.sms_unit_cost));
|
||||
if (filters.per_page) params.append('per_page', String(filters.per_page));
|
||||
if (filters.page) params.append('page', String(filters.page));
|
||||
|
||||
return params.toString();
|
||||
};
|
||||
|
||||
export const authLogsApi = {
|
||||
// Aggregated OTP/SMS and login stats for the analytics cards and chart
|
||||
getStats: async (filters: AuthLogFilters, token: string): Promise<AuthStats> => {
|
||||
const qs = buildAuthLogQuery(filters);
|
||||
return apiClient.get<AuthStats>(`/admin/auth-stats${qs ? `?${qs}` : ''}`, token);
|
||||
},
|
||||
|
||||
// Raw paginated event log
|
||||
getLogs: async (filters: AuthLogFilters, token: string): Promise<PaginatedAuthLogs> => {
|
||||
const qs = buildAuthLogQuery(filters);
|
||||
return apiClient.get<PaginatedAuthLogs>(`/admin/auth-logs${qs ? `?${qs}` : ''}`, token);
|
||||
},
|
||||
};
|
||||
@@ -35,7 +35,6 @@ class ApiClient {
|
||||
|
||||
// Check if there's already a pending request with the same key
|
||||
if (pendingRequests.has(requestKey)) {
|
||||
console.log('Deduplicating request:', endpoint);
|
||||
return pendingRequests.get(requestKey);
|
||||
}
|
||||
|
||||
|
||||
@@ -14,6 +14,10 @@ const buildPurchaseQuery = (filters: PurchaseFilters): string => {
|
||||
if (filters.product_id !== undefined && filters.product_id !== null) {
|
||||
params.append('product_id', String(filters.product_id));
|
||||
}
|
||||
if (filters.date_from) params.append('date_from', filters.date_from);
|
||||
if (filters.date_to) params.append('date_to', filters.date_to);
|
||||
if (filters.time_from) params.append('time_from', filters.time_from);
|
||||
if (filters.time_to) params.append('time_to', filters.time_to);
|
||||
if (filters.per_page) params.append('per_page', String(filters.per_page));
|
||||
if (filters.page) params.append('page', String(filters.page));
|
||||
|
||||
|
||||
@@ -35,6 +35,16 @@ export const parseStoreRate = (value: string | number): number => {
|
||||
return Math.min(100, Math.max(0, n));
|
||||
};
|
||||
|
||||
// Parse a non-negative integer input (e.g. transaction fee in Rial).
|
||||
export const parseFee = (value: string | number): number => {
|
||||
if (value === null || value === undefined || value === '') return 0;
|
||||
const str = String(value).replace(/[^\d]/g, '');
|
||||
if (!str) return 0;
|
||||
const n = parseInt(str, 10);
|
||||
if (Number.isNaN(n)) return 0;
|
||||
return Math.max(0, n);
|
||||
};
|
||||
|
||||
export const formatDate = (dateString: string | null): string => {
|
||||
if (!dateString) return 'نامشخص';
|
||||
|
||||
|
||||
Generated
+13
@@ -74,6 +74,7 @@
|
||||
"integrity": "sha512-e7jT4DxYvIDLk1ZHmU/m/mB19rex9sv0c2ftBtjSBv+kVM/902eh0fINUzD7UwLLNR+jU585GxUJ8/EBfAM5fw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@babel/code-frame": "^7.27.1",
|
||||
"@babel/generator": "^7.28.5",
|
||||
@@ -1610,6 +1611,7 @@
|
||||
"integrity": "sha512-6mDvHUFSjyT2B2yeNx2nUgMxh9LtOWvkhIU3uePn2I2oyNymUAX1NIsdgviM4CH+JSrp2D2hsMvJOkxY+0wNRA==",
|
||||
"devOptional": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"csstype": "^3.0.2"
|
||||
}
|
||||
@@ -1670,6 +1672,7 @@
|
||||
"integrity": "sha512-6m1I5RmHBGTnUGS113G04DMu3CpSdxCAU/UvtjNWL4Nuf3MW9tQhiJqRlHzChIkhy6kZSAQmc+I1bcGjE3yNKg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@typescript-eslint/scope-manager": "8.46.3",
|
||||
"@typescript-eslint/types": "8.46.3",
|
||||
@@ -2200,6 +2203,7 @@
|
||||
"integrity": "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"bin": {
|
||||
"acorn": "bin/acorn"
|
||||
},
|
||||
@@ -2578,6 +2582,7 @@
|
||||
}
|
||||
],
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"baseline-browser-mapping": "^2.9.0",
|
||||
"caniuse-lite": "^1.0.30001759",
|
||||
@@ -3161,6 +3166,7 @@
|
||||
"integrity": "sha512-BhHmn2yNOFA9H9JmmIVKJmd288g9hrVRDkdoIgRCRuSySRUHH7r/DI6aAXW9T1WwUuY3DFgrcaqB+deURBLR5g==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@eslint-community/eslint-utils": "^4.8.0",
|
||||
"@eslint-community/regexpp": "^4.12.1",
|
||||
@@ -3346,6 +3352,7 @@
|
||||
"integrity": "sha512-whOE1HFo/qJDyX4SnXzP4N6zOWn79WhnCUY/iDR0mPfQZO8wcYE4JClzI2oZrhBnnMUCBCHZhO6VQyoBU95mZA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@rtsao/scc": "^1.1.0",
|
||||
"array-includes": "^3.1.9",
|
||||
@@ -5522,6 +5529,7 @@
|
||||
}
|
||||
],
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"nanoid": "^3.3.11",
|
||||
"picocolors": "^1.1.1",
|
||||
@@ -5596,6 +5604,7 @@
|
||||
"resolved": "https://registry.npmjs.org/react/-/react-19.2.0.tgz",
|
||||
"integrity": "sha512-tmbWg6W31tQLeB5cdIBOicJDJRR2KzXsV7uSK9iNfLWQ5bIZfxuPEHp7M8wiHyHnn0DD1i7w3Zmin0FtkrwoCQ==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
@@ -5631,6 +5640,7 @@
|
||||
"resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.2.0.tgz",
|
||||
"integrity": "sha512-UlbRu4cAiGaIewkPyiRGJk0imDN2T3JjieT6spoL2UeSf5od4n5LB/mQ4ejmxhCFT1tYe8IvaFulzynWovsEFQ==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"scheduler": "^0.27.0"
|
||||
},
|
||||
@@ -6317,6 +6327,7 @@
|
||||
"integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
},
|
||||
@@ -6479,6 +6490,7 @@
|
||||
"integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"peer": true,
|
||||
"bin": {
|
||||
"tsc": "bin/tsc",
|
||||
"tsserver": "bin/tsserver"
|
||||
@@ -6754,6 +6766,7 @@
|
||||
"integrity": "sha512-JInaHOamG8pt5+Ey8kGmdcAcg3OL9reK8ltczgHTAwNhMys/6ThXHityHxVV2p3fkw/c+MAvBHFVYHFZDmjMCQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/colinhacks"
|
||||
}
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
import { Paginated } from './purchase';
|
||||
|
||||
// Nested user on an auth log row (subset of the full User model)
|
||||
export interface AuthLogUser {
|
||||
id: number;
|
||||
uuid: string;
|
||||
first_name: string | null;
|
||||
last_name: string | null;
|
||||
email: string | null;
|
||||
mobile: string | null;
|
||||
}
|
||||
|
||||
// One authentication event — matches backend App\Models\AuthLog
|
||||
export interface AuthLog {
|
||||
id: number;
|
||||
user_id: number | null;
|
||||
mobile: string | null;
|
||||
email: string | null;
|
||||
event: AuthEvent;
|
||||
package_name: string | null;
|
||||
source: number | null;
|
||||
success: boolean;
|
||||
sms_sent: boolean;
|
||||
ip: string | null;
|
||||
user_agent: string | null;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
user: AuthLogUser | null;
|
||||
}
|
||||
|
||||
// Event keys — must stay in sync with AuthLog::EVENTS on the backend
|
||||
export const AUTH_EVENTS = {
|
||||
otp_sent: { label: 'ارسال کد ورود (پیامک)', sms: true },
|
||||
otp_verified: { label: 'تأیید کد ورود', sms: false },
|
||||
otp_failed: { label: 'کد ورود نامعتبر', sms: false },
|
||||
mobile_otp_sent: { label: 'ارسال کد تأیید شماره (پیامک)', sms: true },
|
||||
mobile_verified: { label: 'تأیید شماره موبایل', sms: false },
|
||||
mobile_verify_failed: { label: 'تأیید شماره ناموفق', sms: false },
|
||||
login: { label: 'ورود با رمز عبور', sms: false },
|
||||
login_failed: { label: 'ورود ناموفق', sms: false },
|
||||
register: { label: 'ثبتنام', sms: false },
|
||||
google_login: { label: 'ورود با گوگل', sms: false },
|
||||
} as const;
|
||||
|
||||
export type AuthEvent = keyof typeof AUTH_EVENTS;
|
||||
|
||||
export const getAuthEventLabel = (event: string): string =>
|
||||
(AUTH_EVENTS as Record<string, { label: string }>)[event]?.label || event;
|
||||
|
||||
export interface AuthStatsDaily {
|
||||
date: string;
|
||||
total: number;
|
||||
sms: number;
|
||||
otp_sent: number;
|
||||
otp_verified: number;
|
||||
otp_failed: number;
|
||||
}
|
||||
|
||||
export interface AuthStatsPackage {
|
||||
package_name: string;
|
||||
sms: number;
|
||||
logins: number;
|
||||
}
|
||||
|
||||
export interface AuthStats {
|
||||
filters: {
|
||||
date_from: string | null;
|
||||
date_to: string | null;
|
||||
event: string | null;
|
||||
package_name: string | null;
|
||||
};
|
||||
totals: {
|
||||
events: number;
|
||||
unique_mobiles: number;
|
||||
unique_users: number;
|
||||
sms_sent: number;
|
||||
sms_cost: number;
|
||||
sms_unit_cost: number;
|
||||
otp_sent: number;
|
||||
otp_verified: number;
|
||||
otp_failed: number;
|
||||
otp_conversion_rate: number;
|
||||
logins: number;
|
||||
registers: number;
|
||||
};
|
||||
by_event: Record<string, number>;
|
||||
by_package: AuthStatsPackage[];
|
||||
daily: AuthStatsDaily[];
|
||||
}
|
||||
|
||||
// Filters shared by the auth-logs and auth-stats endpoints
|
||||
export interface AuthLogFilters {
|
||||
event?: string;
|
||||
mobile?: string;
|
||||
email?: string;
|
||||
package_name?: string;
|
||||
success?: boolean;
|
||||
sms_only?: boolean;
|
||||
// Date/time window on created_at (Y-m-d dates, H:i(:s) times, Tehran-local)
|
||||
date_from?: string;
|
||||
date_to?: string;
|
||||
time_from?: string;
|
||||
time_to?: string;
|
||||
// Only used by the stats endpoint, to price the SMS total
|
||||
sms_unit_cost?: number;
|
||||
per_page?: number;
|
||||
page?: number;
|
||||
}
|
||||
|
||||
export type PaginatedAuthLogs = Paginated<AuthLog>;
|
||||
@@ -90,6 +90,12 @@ export interface PurchaseFilters {
|
||||
gateway?: string; // gateway name key (e.g. "zarinpal")
|
||||
status?: number;
|
||||
product_id?: number; // filter by a specific product
|
||||
// Date/time window on created_at (Y-m-d dates, H:i(:s) times, Tehran-local —
|
||||
// same values the accounting filters use). Times only apply with their date.
|
||||
date_from?: string;
|
||||
date_to?: string;
|
||||
time_from?: string;
|
||||
time_to?: string;
|
||||
per_page?: number;
|
||||
page?: number;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user