Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e3071b8692 | ||
|
|
ba7147ff59 | ||
|
|
dd5b6d4616 |
@@ -0,0 +1,685 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { useAuth } from '@/contexts/AuthContext';
|
||||
import { purchasesApi } from '@/lib/api/purchases';
|
||||
import { packagesApi } from '@/lib/api/packages';
|
||||
import { productsApi } from '@/lib/api/products';
|
||||
import PageHeader from '@/components/admin/PageHeader';
|
||||
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, parseFee } from '@/lib/utils';
|
||||
import {
|
||||
MagnifyingGlassIcon,
|
||||
ArrowPathIcon,
|
||||
CalculatorIcon,
|
||||
BanknotesIcon,
|
||||
WalletIcon,
|
||||
ChartPieIcon,
|
||||
} from '@heroicons/react/24/outline';
|
||||
|
||||
// A single paid sale = success (موفق) or consumed (مصرفشده).
|
||||
// مایکت/کافهبازار تراکنش را مستقیماً با وضعیت «مصرفشده» ثبت میکنند (نه «موفق»)،
|
||||
// بنابراین هر دو وضعیت باید بهعنوان فروش محسوب شوند.
|
||||
const PAID_STATUSES = [2, 3];
|
||||
|
||||
interface StoreSummary {
|
||||
count: number;
|
||||
gross: number;
|
||||
rate: number;
|
||||
fee: number;
|
||||
net: number;
|
||||
}
|
||||
|
||||
interface ProductRow {
|
||||
productId: number | null;
|
||||
title: string;
|
||||
packageName: string;
|
||||
count: number;
|
||||
gross: number;
|
||||
commission: number;
|
||||
net: number;
|
||||
}
|
||||
|
||||
interface AccountingResult {
|
||||
rows: ProductRow[];
|
||||
totals: { count: number; gross: number; commission: number; net: number };
|
||||
myket: StoreSummary;
|
||||
cafe: StoreSummary;
|
||||
other: StoreSummary;
|
||||
}
|
||||
|
||||
// خلاصه فروش هر محصول و هر فروشگاه با احتساب کارمزد
|
||||
const computeAccounting = (
|
||||
purchases: Purchase[],
|
||||
myketRate: number,
|
||||
cafeRate: number,
|
||||
transactionFee: number,
|
||||
): AccountingResult => {
|
||||
const rows = new Map<number, ProductRow>();
|
||||
let totalCount = 0;
|
||||
let totalGross = 0;
|
||||
let totalCommission = 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);
|
||||
|
||||
// سهم توسعهدهنده برای مایکت/کافهبازار:
|
||||
// (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.fee += price - net;
|
||||
store.net += net;
|
||||
};
|
||||
|
||||
for (const purchase of purchases) {
|
||||
const price = getPurchaseFinalPrice(purchase);
|
||||
const gateway = purchase.gateway;
|
||||
|
||||
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, feePerTransaction);
|
||||
|
||||
totalCount += 1;
|
||||
totalGross += price;
|
||||
totalCommission += price - developerShare(price, rate, feePerTransaction);
|
||||
|
||||
const productId = purchase.product_id ?? purchase.product?.id ?? -1;
|
||||
let row = rows.get(productId);
|
||||
if (!row) {
|
||||
row = {
|
||||
productId,
|
||||
title: purchase.product?.title || 'نامشخص',
|
||||
packageName:
|
||||
purchase.product?.package_name?.title ||
|
||||
purchase.product?.package_name?.name ||
|
||||
'—',
|
||||
count: 0,
|
||||
gross: 0,
|
||||
commission: 0,
|
||||
net: 0,
|
||||
};
|
||||
rows.set(productId, row);
|
||||
}
|
||||
row.count += 1;
|
||||
row.gross += price;
|
||||
row.commission += price - developerShare(price, rate, feePerTransaction);
|
||||
row.net += developerShare(price, rate, feePerTransaction);
|
||||
}
|
||||
|
||||
return {
|
||||
rows: Array.from(rows.values()),
|
||||
totals: {
|
||||
count: totalCount,
|
||||
gross: totalGross,
|
||||
commission: totalCommission,
|
||||
net: totalGross - totalCommission,
|
||||
},
|
||||
myket,
|
||||
cafe,
|
||||
other,
|
||||
};
|
||||
};
|
||||
|
||||
export default function AccountingPage() {
|
||||
const { token } = useAuth();
|
||||
|
||||
// Package / product filters
|
||||
const [packages, setPackages] = useState<PackageName[]>([]);
|
||||
const [selectedPackageName, setSelectedPackageName] = useState<string>('');
|
||||
const [products, setProducts] = useState<Product[]>([]);
|
||||
const [selectedProductId, setSelectedProductId] = useState<string>('');
|
||||
|
||||
// Date range
|
||||
const [dateFrom, setDateFrom] = useState<string>('');
|
||||
const [dateTo, setDateTo] = useState<string>('');
|
||||
|
||||
// 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]);
|
||||
|
||||
// درصد سهم توسعهدهنده (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);
|
||||
|
||||
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
|
||||
useEffect(() => {
|
||||
if (!token) return;
|
||||
packagesApi
|
||||
.getAllPackages(token)
|
||||
.then((data) => {
|
||||
setPackages(data);
|
||||
if (data.length > 0) setSelectedPackageName(data[0].name || '');
|
||||
})
|
||||
.catch(() => setError('خطا در دریافت لیست پکیجها'));
|
||||
}, [token]);
|
||||
|
||||
// Load products when a package is selected
|
||||
useEffect(() => {
|
||||
if (!token || !selectedPackageName) {
|
||||
setProducts([]);
|
||||
setSelectedProductId('');
|
||||
return;
|
||||
}
|
||||
setSelectedProductId('');
|
||||
productsApi
|
||||
.getProducts(selectedPackageName, token)
|
||||
.then(setProducts)
|
||||
.catch(() => setProducts([]));
|
||||
}, [selectedPackageName, token]);
|
||||
|
||||
const handleAnalyze = useCallback(async () => {
|
||||
if (!token) return;
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
// Fetch all purchases once, then filter/aggregate in-memory.
|
||||
const purchases = await purchasesApi.getAllPurchases({ per_page: 500 }, token);
|
||||
setAllPurchases(purchases);
|
||||
setResult(
|
||||
computeAccounting(
|
||||
purchases,
|
||||
parseStoreRate(myketRate),
|
||||
parseStoreRate(cafeRate),
|
||||
parseFee(transactionFee)
|
||||
)
|
||||
);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'خطا در دریافت دادهها');
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, [token, myketRate, cafeRate, transactionFee]);
|
||||
|
||||
// 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
|
||||
if (statuses.length > 0 && !statuses.includes(p.status)) return false;
|
||||
|
||||
// Product
|
||||
if (selectedProductId !== '' && String(p.product_id) !== selectedProductId) return false;
|
||||
|
||||
// Package (via nested product)
|
||||
if (selectedPackageName) {
|
||||
const pkgName =
|
||||
p.product?.package_name?.name || p.product?.package_name?.title || '';
|
||||
if (pkgName && pkgName !== selectedPackageName) return false;
|
||||
}
|
||||
|
||||
// Date range (created_at is "Y-m-d H:i:s")
|
||||
// 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, 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 handleReset = () => {
|
||||
setSelectedPackageName(packages[0]?.name || '');
|
||||
setSelectedProductId('');
|
||||
setDateFrom('');
|
||||
setDateTo('');
|
||||
setTimeFrom('');
|
||||
setTimeTo('');
|
||||
setStatuses([...PAID_STATUSES]);
|
||||
setMyketRate('85');
|
||||
setCafeRate('85');
|
||||
setTransactionFee('1200');
|
||||
};
|
||||
|
||||
const toggleStatus = (code: number) => {
|
||||
setStatuses((prev) =>
|
||||
prev.includes(code) ? prev.filter((c) => c !== code) : [...prev, code]
|
||||
);
|
||||
};
|
||||
|
||||
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">
|
||||
<PageHeader
|
||||
title="حسابداری"
|
||||
subtitle="تحلیل فروش محصولات و محاسبه کارمزد فروشگاهها"
|
||||
action={
|
||||
allPurchases ? (
|
||||
<button
|
||||
onClick={handleAnalyze}
|
||||
disabled={isLoading}
|
||||
className="inline-flex items-center gap-2 px-4 py-2.5 border border-gray-200 dark:border-gray-700 rounded-xl text-sm font-medium text-gray-700 dark:text-gray-200 bg-white dark:bg-gray-800 hover:bg-gray-50 dark:hover:bg-gray-700 disabled:opacity-50 transition-colors shadow-sm"
|
||||
>
|
||||
<ArrowPathIcon className="h-4 w-4" />
|
||||
بارگذاری مجدد
|
||||
</button>
|
||||
) : null
|
||||
}
|
||||
/>
|
||||
|
||||
{/* Filters */}
|
||||
<form
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
handleAnalyze();
|
||||
}}
|
||||
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-6">
|
||||
<div>
|
||||
<label htmlFor="package_name" className={labelClass}>پکیج</label>
|
||||
<select
|
||||
id="package_name"
|
||||
value={selectedPackageName}
|
||||
onChange={(e) => setSelectedPackageName(e.target.value)}
|
||||
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="product" className={labelClass}>محصول</label>
|
||||
<select
|
||||
id="product"
|
||||
value={selectedProductId}
|
||||
onChange={(e) => setSelectedProductId(e.target.value)}
|
||||
className={inputClass}
|
||||
>
|
||||
<option value="">همه محصولات</option>
|
||||
{products.map((prod) => (
|
||||
<option key={prod.id} value={String(prod.id)}>
|
||||
{prod.title || `#${prod.id}`}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<PersianDatePicker
|
||||
id="date_from"
|
||||
label="از تاریخ"
|
||||
placeholder="انتخاب تاریخ شروع"
|
||||
value={dateFrom}
|
||||
onChange={setDateFrom}
|
||||
/>
|
||||
</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>
|
||||
|
||||
<div>
|
||||
<PersianDatePicker
|
||||
id="date_to"
|
||||
label="تا تاریخ"
|
||||
placeholder="انتخاب تاریخ پایان"
|
||||
value={dateTo}
|
||||
onChange={setDateTo}
|
||||
/>
|
||||
</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>
|
||||
|
||||
{/* Status checkboxes */}
|
||||
<div className="mt-4">
|
||||
<label className={labelClass}>وضعیت</label>
|
||||
<div className="flex flex-wrap gap-3">
|
||||
{[
|
||||
{ code: 2, label: 'موفق' },
|
||||
{ code: 3, label: 'مصرفشده' },
|
||||
{ code: 1, label: 'در انتظار پرداخت' },
|
||||
].map(({ code, label }) => (
|
||||
<label key={code} className="inline-flex items-center gap-2 text-sm text-gray-700 dark:text-gray-300 cursor-pointer">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={statuses.includes(code)}
|
||||
onChange={() => toggleStatus(code)}
|
||||
className="h-4 w-4 rounded border-gray-300 text-indigo-600 focus:ring-indigo-500"
|
||||
/>
|
||||
{label}
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 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"
|
||||
id="myket_rate"
|
||||
inputMode="numeric"
|
||||
value={myketRate}
|
||||
onChange={(e) => setMyketRate(e.target.value)}
|
||||
className={inputClass}
|
||||
placeholder="۸۵"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label htmlFor="cafe_rate" className={labelClass}>
|
||||
سهم توسعهدهنده کافه بازار (٪)
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
id="cafe_rate"
|
||||
inputMode="numeric"
|
||||
value={cafeRate}
|
||||
onChange={(e) => setCafeRate(e.target.value)}
|
||||
className={inputClass}
|
||||
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">
|
||||
<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>
|
||||
)}
|
||||
|
||||
{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>
|
||||
)}
|
||||
|
||||
{!isLoading && allPurchases && result && (
|
||||
<>
|
||||
{/* 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>
|
||||
</div>
|
||||
|
||||
{/* Per-store breakdown */}
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4 mb-6">
|
||||
<StoreCard title="مایکت" summary={result.myket} />
|
||||
<StoreCard title="کافه بازار" summary={result.cafe} />
|
||||
<StoreCard title="سایر درگاهها" summary={result.other} />
|
||||
</div>
|
||||
|
||||
{/* Per-product table */}
|
||||
<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>
|
||||
|
||||
{result.rows.length === 0 ? (
|
||||
<div className="text-center py-16">
|
||||
<p className="text-gray-500 dark:text-gray-400 text-sm">
|
||||
هیچ فروشی با این فیلترها یافت نشد
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="overflow-x-auto">
|
||||
<table className="min-w-full divide-y divide-gray-200 dark:divide-gray-800">
|
||||
<thead className="bg-gray-50 dark:bg-gray-800/60">
|
||||
<tr className="text-right text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
|
||||
<th className="px-4 py-3">محصول</th>
|
||||
<th className="px-4 py-3">پکیج</th>
|
||||
<th className="px-4 py-3">تعداد فروش</th>
|
||||
<th className="px-4 py-3">فروش ناخالص</th>
|
||||
<th className="px-4 py-3">کارمزد فروشگاه</th>
|
||||
<th className="px-4 py-3">سود خالص</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-gray-200 dark:divide-gray-800">
|
||||
{result.rows.map((row) => (
|
||||
<tr key={row.productId} className="hover:bg-gray-50 dark:hover:bg-gray-800/40 transition-colors">
|
||||
<td className="px-4 py-3.5 text-sm font-medium text-gray-900 dark:text-gray-100 whitespace-nowrap">
|
||||
{row.title}
|
||||
</td>
|
||||
<td className="px-4 py-3.5 text-sm text-gray-700 dark:text-gray-300 whitespace-nowrap">
|
||||
{row.packageName}
|
||||
</td>
|
||||
<td className="px-4 py-3.5 text-sm text-gray-900 dark:text-gray-100 whitespace-nowrap">
|
||||
{formatPrice(row.count)}
|
||||
</td>
|
||||
<td className="px-4 py-3.5 text-sm text-gray-900 dark:text-gray-100 whitespace-nowrap font-medium">
|
||||
{formatPrice(row.gross)} <span className="text-xs text-gray-400">تومان</span>
|
||||
</td>
|
||||
<td className="px-4 py-3.5 text-sm text-amber-600 dark:text-amber-400 whitespace-nowrap">
|
||||
{formatPrice(row.commission)} <span className="text-xs text-gray-400">تومان</span>
|
||||
</td>
|
||||
<td className="px-4 py-3.5 text-sm text-emerald-600 dark:text-emerald-400 whitespace-nowrap font-medium">
|
||||
{formatPrice(row.net)} <span className="text-xs text-gray-400">تومان</span>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
{!isLoading && !allPurchases && (
|
||||
<div className="text-center py-16 bg-white dark:bg-gray-900 ring-1 ring-gray-200 dark:ring-gray-800 rounded-2xl shadow-sm">
|
||||
<div className="mx-auto h-12 w-12 rounded-xl bg-indigo-50 dark:bg-indigo-500/15 flex items-center justify-center mb-3">
|
||||
<CalculatorIcon className="h-6 w-6 text-indigo-600 dark:text-indigo-400" />
|
||||
</div>
|
||||
<p className="text-gray-500 dark:text-gray-400 text-sm">
|
||||
برای تحلیل فروش، فیلترها را تنظیم و روی «تحلیل» کلیک کنید
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</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">
|
||||
<div className="flex items-center justify-between">
|
||||
<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}٪
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="mt-3 space-y-1.5 text-sm">
|
||||
<div className="flex justify-between text-gray-500 dark:text-gray-400">
|
||||
<span>تعداد فروش</span>
|
||||
<span className="text-gray-900 dark:text-gray-100 font-medium">{formatPrice(summary.count)}</span>
|
||||
</div>
|
||||
<div className="flex justify-between text-gray-500 dark:text-gray-400">
|
||||
<span>فروش ناخالص</span>
|
||||
<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.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>
|
||||
<span className="text-emerald-600 dark:text-emerald-400 font-bold">{formatPrice(summary.net)} تومان</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
import { useAuth } from '@/contexts/AuthContext';
|
||||
import Link from 'next/link';
|
||||
import { UsersIcon, CubeIcon, TagIcon, BellIcon, GiftIcon, ShoppingBagIcon } from '@heroicons/react/24/outline';
|
||||
import { UsersIcon, CubeIcon, TagIcon, BellIcon, GiftIcon, ShoppingBagIcon, CalculatorIcon } from '@heroicons/react/24/outline';
|
||||
import { MegaphoneIcon } from 'lucide-react';
|
||||
|
||||
export default function Dashboard() {
|
||||
@@ -27,6 +27,15 @@ export default function Dashboard() {
|
||||
iconColor: 'text-orange-600 dark:text-orange-400',
|
||||
hoverBorder: 'hover:border-orange-300 dark:hover:border-orange-700',
|
||||
},
|
||||
{
|
||||
href: '/admin/accounting',
|
||||
title: 'حسابداری',
|
||||
desc: 'تحلیل فروش محصولات و محاسبه کارمزد مایکت و کافه بازار',
|
||||
Icon: CalculatorIcon,
|
||||
iconBg: 'bg-cyan-100 dark:bg-cyan-500/15',
|
||||
iconColor: 'text-cyan-600 dark:text-cyan-400',
|
||||
hoverBorder: 'hover:border-cyan-300 dark:hover:border-cyan-700',
|
||||
},
|
||||
{
|
||||
href: '/admin/packages',
|
||||
title: 'مدیریت پکیجها',
|
||||
|
||||
@@ -15,7 +15,7 @@ import {
|
||||
getPurchaseStatusLabel,
|
||||
} from '@/types/purchase';
|
||||
import { PackageName } from '@/types/package';
|
||||
import { formatPrice, formatDate, getProductTypeLabel } 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 => {
|
||||
@@ -37,26 +37,6 @@ const emptyFilters: PurchaseFilters = {
|
||||
status: undefined,
|
||||
};
|
||||
|
||||
// قیمت نهایی خرید (مبلغ قابلنمایش در جدول).
|
||||
// وقتی محصول تخفیف دارد، مقدار نهایی همان «قیمت کلی تخفیفخورده» است؛
|
||||
// اما در پکیجهایی که تخفیف ندارند، «قیمت» خود محصول مقدار نهایی است.
|
||||
const getPurchaseFinalPrice = (purchase: Purchase): number => {
|
||||
const product = purchase.product;
|
||||
|
||||
// اگر محصول تخفیف دارد، قیمت نهایی همان قیمت تخفیفخورده است
|
||||
const discountedPrice = product?.discounted_price;
|
||||
if (discountedPrice) {
|
||||
const parsed = parseInt(discountedPrice.replace(/[^\d]/g, ''), 10);
|
||||
if (!Number.isNaN(parsed) && parsed > 0) return parsed;
|
||||
}
|
||||
|
||||
// بدون تخفیف → قیمت اصلی محصول (فقط وقتی discount نداشته باشد)
|
||||
if (product?.price) return product.price;
|
||||
|
||||
// برگشت به مبلغ ثبتشدهٔ تراکنش وقتی محصول در دسترس نیست
|
||||
return purchase.amount || 0;
|
||||
};
|
||||
|
||||
export default function PurchasesPage() {
|
||||
const { token } = useAuth();
|
||||
const [packages, setPackages] = useState<PackageName[]>([]);
|
||||
@@ -232,7 +212,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">
|
||||
@@ -274,7 +254,7 @@ 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>
|
||||
))}
|
||||
|
||||
@@ -0,0 +1,154 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { DayPicker } from '@daypicker/persian';
|
||||
import '@daypicker/react/style.css';
|
||||
import { CalendarDaysIcon, XMarkIcon } from '@heroicons/react/24/outline';
|
||||
|
||||
interface PersianDatePickerProps {
|
||||
/** Gregorian YYYY-MM-DD, or '' when empty. */
|
||||
value: string;
|
||||
/** Called with the selected Gregorian YYYY-MM-DD, or '' when cleared. */
|
||||
onChange: (value: string) => void;
|
||||
label?: string;
|
||||
placeholder?: string;
|
||||
id?: string;
|
||||
}
|
||||
|
||||
// Parses a Gregorian "YYYY-MM-DD" into a local Date (pinned at noon to avoid
|
||||
// any date shift from timezone offsets).
|
||||
const parseGregorian = (value: string): Date | null => {
|
||||
const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(value);
|
||||
if (!match) return null;
|
||||
const date = new Date(Number(match[1]), Number(match[2]) - 1, Number(match[3]), 12, 0, 0);
|
||||
return Number.isNaN(date.getTime()) ? null : date;
|
||||
};
|
||||
|
||||
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}`;
|
||||
};
|
||||
|
||||
// Renders the given Gregorian date as a Persian (Jalali) string with Persian
|
||||
// digits, e.g. "۱۴۰۴/۰۵/۱۱".
|
||||
const jalaliFormat = new Intl.DateTimeFormat('fa-IR-u-ca-persian', {
|
||||
year: 'numeric',
|
||||
month: '2-digit',
|
||||
day: '2-digit',
|
||||
});
|
||||
|
||||
const formatJalali = (date: Date): string => jalaliFormat.format(date);
|
||||
|
||||
/**
|
||||
* A Persian (Jalali) date input built on @daypicker/persian.
|
||||
*
|
||||
* The calendar operates in the Jalali calendar, but the public value is a
|
||||
* Gregorian "YYYY-MM-DD" string — the same format the native <input
|
||||
* type="date"> produced — so the accounting filters keep working unchanged.
|
||||
*
|
||||
* Note: with the default dateLib (no `timeZone` prop), @daypicker/persian
|
||||
* works with plain JS `Date` objects whose native getters already return the
|
||||
* Gregorian date; the Jalali conversion happens inside the calendar library.
|
||||
* That's why we can read `getFullYear()/getMonth()/getDate()` straight off the
|
||||
* picked date.
|
||||
*/
|
||||
export default function PersianDatePicker({
|
||||
value,
|
||||
onChange,
|
||||
label,
|
||||
placeholder,
|
||||
id,
|
||||
}: PersianDatePickerProps) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const rootRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
const selectedDate = value ? parseGregorian(value) : null;
|
||||
|
||||
// Controlled month so the popover opens on the selected month (or now).
|
||||
const [viewMonth, setViewMonth] = useState<Date>(() => selectedDate ?? new Date());
|
||||
|
||||
// Close on outside click or Escape.
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
const handlePointerDown = (event: MouseEvent) => {
|
||||
if (rootRef.current && !rootRef.current.contains(event.target as Node)) {
|
||||
setOpen(false);
|
||||
}
|
||||
};
|
||||
const handleKeyDown = (event: KeyboardEvent) => {
|
||||
if (event.key === 'Escape') setOpen(false);
|
||||
};
|
||||
document.addEventListener('mousedown', handlePointerDown);
|
||||
document.addEventListener('keydown', handleKeyDown);
|
||||
return () => {
|
||||
document.removeEventListener('mousedown', handlePointerDown);
|
||||
document.removeEventListener('keydown', handleKeyDown);
|
||||
};
|
||||
}, [open]);
|
||||
|
||||
const handleSelect = (date: Date | undefined) => {
|
||||
if (date) onChange(toGregorianValue(date));
|
||||
setOpen(false);
|
||||
};
|
||||
|
||||
const handleClear = () => {
|
||||
onChange('');
|
||||
setOpen(false);
|
||||
};
|
||||
|
||||
const toggle = () => {
|
||||
setViewMonth(selectedDate ?? new Date());
|
||||
setOpen((prev) => !prev);
|
||||
};
|
||||
|
||||
return (
|
||||
<div ref={rootRef} className="relative">
|
||||
{label && (
|
||||
<label htmlFor={id} className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5">
|
||||
{label}
|
||||
</label>
|
||||
)}
|
||||
|
||||
<button
|
||||
type="button"
|
||||
id={id}
|
||||
onClick={toggle}
|
||||
aria-haspopup="dialog"
|
||||
aria-expanded={open}
|
||||
className={`flex w-full items-center justify-between gap-2 px-3 py-2.5 text-right text-gray-900 dark:text-gray-100 border border-gray-200 dark:border-gray-700 rounded-xl shadow-sm focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-transparent sm:text-sm dark:bg-gray-800/80 transition-colors ${
|
||||
selectedDate
|
||||
? 'text-gray-900 dark:text-gray-100'
|
||||
: 'text-gray-400 dark:text-gray-500'
|
||||
}`}
|
||||
>
|
||||
<span className="truncate">{selectedDate ? formatJalali(selectedDate) : placeholder || 'انتخاب تاریخ'}</span>
|
||||
{selectedDate ? (
|
||||
<XMarkIcon
|
||||
className="h-4 w-4 shrink-0 text-gray-400 hover:text-red-500 transition-colors"
|
||||
onClick={(event) => {
|
||||
event.stopPropagation();
|
||||
handleClear();
|
||||
}}
|
||||
aria-label="پاک کردن تاریخ"
|
||||
/>
|
||||
) : (
|
||||
<CalendarDaysIcon className="h-4 w-4 shrink-0 text-gray-400" />
|
||||
)}
|
||||
</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">
|
||||
<DayPicker
|
||||
mode="single"
|
||||
selected={selectedDate ?? undefined}
|
||||
onSelect={handleSelect}
|
||||
month={viewMonth}
|
||||
onMonthChange={setViewMonth}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
PowerIcon,
|
||||
ShoppingBagIcon,
|
||||
HomeIcon,
|
||||
CalculatorIcon,
|
||||
Bars3Icon,
|
||||
XMarkIcon,
|
||||
} from '@heroicons/react/24/outline';
|
||||
@@ -23,6 +24,7 @@ const navItems = [
|
||||
{ href: '/admin/dashboard', label: 'داشبورد', Icon: HomeIcon },
|
||||
{ href: '/admin/users', label: 'کاربران', Icon: UsersIcon },
|
||||
{ href: '/admin/purchases', label: 'خریدها', Icon: ShoppingBagIcon },
|
||||
{ href: '/admin/accounting', label: 'حسابداری', Icon: CalculatorIcon },
|
||||
{ href: '/admin/packages', label: 'پکیجها', Icon: CubeIcon },
|
||||
{ href: '/admin/products', label: 'محصولات', Icon: TagIcon },
|
||||
{ href: '/admin/reminders', label: 'یادآوریها', Icon: BellIcon },
|
||||
|
||||
+48
-13
@@ -1,22 +1,57 @@
|
||||
import { apiClient } from './client';
|
||||
import { Purchase, Paginated, PurchaseFilters } from '@/types/purchase';
|
||||
|
||||
const buildPurchaseQuery = (filters: PurchaseFilters): string => {
|
||||
const params = new URLSearchParams();
|
||||
|
||||
if (filters.email) params.append('email', filters.email);
|
||||
if (filters.mobile) params.append('mobile', filters.mobile);
|
||||
if (filters.package_name) params.append('package_name', filters.package_name);
|
||||
if (filters.gateway) params.append('gateway', filters.gateway);
|
||||
if (filters.status !== undefined && filters.status !== null) {
|
||||
params.append('status', String(filters.status));
|
||||
}
|
||||
if (filters.product_id !== undefined && filters.product_id !== null) {
|
||||
params.append('product_id', String(filters.product_id));
|
||||
}
|
||||
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 purchasesApi = {
|
||||
// List all subscription purchases with optional filters
|
||||
getPurchases: async (filters: PurchaseFilters, token: string): Promise<Paginated<Purchase>> => {
|
||||
const params = new URLSearchParams();
|
||||
|
||||
if (filters.email) params.append('email', filters.email);
|
||||
if (filters.mobile) params.append('mobile', filters.mobile);
|
||||
if (filters.package_name) params.append('package_name', filters.package_name);
|
||||
if (filters.gateway) params.append('gateway', filters.gateway);
|
||||
if (filters.status !== undefined && filters.status !== null) {
|
||||
params.append('status', String(filters.status));
|
||||
}
|
||||
if (filters.per_page) params.append('per_page', String(filters.per_page));
|
||||
if (filters.page) params.append('page', String(filters.page));
|
||||
|
||||
const qs = params.toString();
|
||||
const qs = buildPurchaseQuery(filters);
|
||||
return apiClient.get<Paginated<Purchase>>(`/admin/purchases${qs ? `?${qs}` : ''}`, token);
|
||||
},
|
||||
|
||||
// Fetch ALL purchases matching the filters (used by the accounting section).
|
||||
// Learns the total from page 1, then fetches the remaining pages concurrently.
|
||||
getAllPurchases: async (filters: PurchaseFilters, token: string): Promise<Purchase[]> => {
|
||||
const perPage = filters.per_page || 500;
|
||||
const first = await purchasesApi.getPurchases({ ...filters, per_page: perPage, page: 1 }, token);
|
||||
|
||||
const all = new Map<number, Purchase>();
|
||||
first.data.forEach((p) => all.set(p.id, p));
|
||||
|
||||
const lastPage = first.last_page ?? 1;
|
||||
if (lastPage > 1) {
|
||||
const pages: number[] = [];
|
||||
for (let page = 2; page <= lastPage; page++) pages.push(page);
|
||||
|
||||
// Fetch in small concurrent batches to avoid hammering the API
|
||||
const batchSize = 4;
|
||||
for (let i = 0; i < pages.length; i += batchSize) {
|
||||
const batch = pages.slice(i, i + batchSize);
|
||||
const results = await Promise.all(
|
||||
batch.map((page) => purchasesApi.getPurchases({ ...filters, per_page: perPage, page }, token))
|
||||
);
|
||||
results.forEach((res) => res.data.forEach((p) => all.set(p.id, p)));
|
||||
}
|
||||
}
|
||||
|
||||
return Array.from(all.values());
|
||||
},
|
||||
};
|
||||
|
||||
@@ -1,10 +1,50 @@
|
||||
import { User } from "@/types/user";
|
||||
import { Purchase } from "@/types/purchase";
|
||||
|
||||
// Single source of truth for product type labels lives in types/product.ts
|
||||
// (kept in sync with the backend Product::TYPES). Re-exported here so existing
|
||||
// `@/lib/utils` imports keep working without a divergent (previously wrong) map.
|
||||
export { getProductTypeLabel } from "@/types/product";
|
||||
|
||||
// قیمت نهایی خرید — shared between purchases table and accounting page.
|
||||
// اگر محصول تخفیف داشته باشد قیمت تخفیفخورده، در غیر این صورت قیمت اصلی، و در نهایت مبلغ تراکنش.
|
||||
export const getPurchaseFinalPrice = (purchase: Purchase): number => {
|
||||
const product = purchase.product;
|
||||
|
||||
// اگر محصول تخفیف دارد، قیمت نهایی همان قیمت تخفیفخورده است
|
||||
const discountedPrice = product?.discounted_price;
|
||||
if (discountedPrice) {
|
||||
const parsed = parseInt(discountedPrice.replace(/[^\d]/g, ''), 10);
|
||||
if (!Number.isNaN(parsed) && parsed > 0) return parsed;
|
||||
}
|
||||
|
||||
// بدون تخفیف → قیمت اصلی محصول
|
||||
if (product?.price) return product.price;
|
||||
|
||||
// برگشت به مبلغ ثبتشدهٔ تراکنش وقتی محصول در دسترس نیست
|
||||
return purchase.amount || 0;
|
||||
};
|
||||
|
||||
// Parse a percentage input (e.g. "۱۵%" / "15") and clamp to 0–100.
|
||||
export const parseStoreRate = (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.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
+103
-15
@@ -8,7 +8,9 @@
|
||||
"name": "approagency admin pannel",
|
||||
"version": "0.1.0",
|
||||
"dependencies": {
|
||||
"@daypicker/persian": "^10.0.1",
|
||||
"@heroicons/react": "^2.2.0",
|
||||
"date-fns-jalali": "^4.4.0-0",
|
||||
"framer-motion": "^12.23.24",
|
||||
"lucide-react": "^0.552.0",
|
||||
"next": "16.0.1",
|
||||
@@ -72,7 +74,6 @@
|
||||
"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",
|
||||
@@ -282,6 +283,63 @@
|
||||
"node": ">=6.9.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@date-fns/tz": {
|
||||
"version": "1.5.0",
|
||||
"resolved": "https://registry.npmjs.org/@date-fns/tz/-/tz-1.5.0.tgz",
|
||||
"integrity": "sha512-lwYN/vDPeNRULcepoE/LO2Pgx+7/RV+S9ARfbc9lr2DtGkOD7pAiruHvbR1RX3Qyf6ja47EWJDMsNK5vK08DJg==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@daypicker/persian": {
|
||||
"version": "10.0.1",
|
||||
"resolved": "https://registry.npmjs.org/@daypicker/persian/-/persian-10.0.1.tgz",
|
||||
"integrity": "sha512-dRgANykUb+QOMaHNlYx1Vz9G4HXT2RC2SLQ6RBdIkGYImBHteFJ72zvISSEQ7EepcYpS4CGXL2D+P9f5ddbAZg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@date-fns/tz": "^1.4.1",
|
||||
"@daypicker/react": "10.0.1",
|
||||
"date-fns-jalali": "4.1.0-0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@types/react": ">=16.8.0",
|
||||
"react": ">=16.8.0"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"@types/react": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/@daypicker/persian/node_modules/date-fns-jalali": {
|
||||
"version": "4.1.0-0",
|
||||
"resolved": "https://registry.npmjs.org/date-fns-jalali/-/date-fns-jalali-4.1.0-0.tgz",
|
||||
"integrity": "sha512-hTIP/z+t+qKwBDcmmsnmjWTduxCg+5KfdqWQvb2X/8C9+knYY6epN/pfxdDuyVlSVeFz0sM5eEfwIUQ70U4ckg==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@daypicker/react": {
|
||||
"version": "10.0.1",
|
||||
"resolved": "https://registry.npmjs.org/@daypicker/react/-/react-10.0.1.tgz",
|
||||
"integrity": "sha512-lH4YQz4iMBWP8hsI1bD9Eg0T7t503IkSUR/WDGGkV5mKZvwVv+ukCkJz7yN+uVFBv7vHTK+ww7a5EvlkeFwPYQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"react-day-picker": "10.0.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
},
|
||||
"funding": {
|
||||
"type": "individual",
|
||||
"url": "https://github.com/sponsors/gpbl"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@types/react": ">=16.8.0",
|
||||
"react": ">=16.8.0"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"@types/react": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/@emnapi/core": {
|
||||
"version": "1.7.0",
|
||||
"resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.7.0.tgz",
|
||||
@@ -1550,9 +1608,8 @@
|
||||
"version": "19.2.2",
|
||||
"resolved": "https://registry.npmjs.org/@types/react/-/react-19.2.2.tgz",
|
||||
"integrity": "sha512-6mDvHUFSjyT2B2yeNx2nUgMxh9LtOWvkhIU3uePn2I2oyNymUAX1NIsdgviM4CH+JSrp2D2hsMvJOkxY+0wNRA==",
|
||||
"dev": true,
|
||||
"devOptional": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"csstype": "^3.0.2"
|
||||
}
|
||||
@@ -1613,7 +1670,6 @@
|
||||
"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",
|
||||
@@ -2144,7 +2200,6 @@
|
||||
"integrity": "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"bin": {
|
||||
"acorn": "bin/acorn"
|
||||
},
|
||||
@@ -2523,7 +2578,6 @@
|
||||
}
|
||||
],
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"baseline-browser-mapping": "^2.9.0",
|
||||
"caniuse-lite": "^1.0.30001759",
|
||||
@@ -2694,7 +2748,7 @@
|
||||
"version": "3.1.3",
|
||||
"resolved": "https://registry.npmjs.org/csstype/-/csstype-3.1.3.tgz",
|
||||
"integrity": "sha512-M1uQkMl8rQK/szD0LNhtqxIPLpimGm8sOBwU7lLnCpSbTyY3yeU1Vc7l4KT5zT4s/yOxHH5O7tIuuLOCnLADRw==",
|
||||
"dev": true,
|
||||
"devOptional": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/damerau-levenshtein": {
|
||||
@@ -2758,6 +2812,22 @@
|
||||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/date-fns": {
|
||||
"version": "4.4.0",
|
||||
"resolved": "https://registry.npmjs.org/date-fns/-/date-fns-4.4.0.tgz",
|
||||
"integrity": "sha512-+1UMbeh68lH1SegH83CGWwpb6OHHbpSgr3+s5Eww5M4CAgswBpoWS0AjTOfEJ33HiYKz1hdj/KTFprzXHmq/6w==",
|
||||
"license": "MIT",
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/kossnocorp"
|
||||
}
|
||||
},
|
||||
"node_modules/date-fns-jalali": {
|
||||
"version": "4.4.0-0",
|
||||
"resolved": "https://registry.npmjs.org/date-fns-jalali/-/date-fns-jalali-4.4.0-0.tgz",
|
||||
"integrity": "sha512-4kei2k9Hr/fFvxNL7C6k+WeEYVehe5jO8zDcpREDDZ4ILa9af8tNmqNUJKAGJyPqKAHsdMmwY0jX5gTCiRWw4A==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/debug": {
|
||||
"version": "4.4.3",
|
||||
"resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
|
||||
@@ -3091,7 +3161,6 @@
|
||||
"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",
|
||||
@@ -3277,7 +3346,6 @@
|
||||
"integrity": "sha512-whOE1HFo/qJDyX4SnXzP4N6zOWn79WhnCUY/iDR0mPfQZO8wcYE4JClzI2oZrhBnnMUCBCHZhO6VQyoBU95mZA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@rtsao/scc": "^1.1.0",
|
||||
"array-includes": "^3.1.9",
|
||||
@@ -5454,7 +5522,6 @@
|
||||
}
|
||||
],
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"nanoid": "^3.3.11",
|
||||
"picocolors": "^1.1.1",
|
||||
@@ -5529,17 +5596,41 @@
|
||||
"resolved": "https://registry.npmjs.org/react/-/react-19.2.0.tgz",
|
||||
"integrity": "sha512-tmbWg6W31tQLeB5cdIBOicJDJRR2KzXsV7uSK9iNfLWQ5bIZfxuPEHp7M8wiHyHnn0DD1i7w3Zmin0FtkrwoCQ==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/react-day-picker": {
|
||||
"version": "10.0.1",
|
||||
"resolved": "https://registry.npmjs.org/react-day-picker/-/react-day-picker-10.0.1.tgz",
|
||||
"integrity": "sha512-eNh6BlwcYInWaJtRv18mXQ06Ys/H6rdTZAnTaSdOYJuTpwP1JMCHNd1FDRadA+gbeinq+psdULN5Xnowy9mV8w==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@date-fns/tz": "^1.4.1",
|
||||
"date-fns": "^4.1.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
},
|
||||
"funding": {
|
||||
"type": "individual",
|
||||
"url": "https://github.com/sponsors/gpbl"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@types/react": ">=16.8.0",
|
||||
"react": ">=16.8.0"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"@types/react": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/react-dom": {
|
||||
"version": "19.2.0",
|
||||
"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"
|
||||
},
|
||||
@@ -6226,7 +6317,6 @@
|
||||
"integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
},
|
||||
@@ -6389,7 +6479,6 @@
|
||||
"integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"peer": true,
|
||||
"bin": {
|
||||
"tsc": "bin/tsc",
|
||||
"tsserver": "bin/tsserver"
|
||||
@@ -6665,7 +6754,6 @@
|
||||
"integrity": "sha512-JInaHOamG8pt5+Ey8kGmdcAcg3OL9reK8ltczgHTAwNhMys/6ThXHityHxVV2p3fkw/c+MAvBHFVYHFZDmjMCQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/colinhacks"
|
||||
}
|
||||
|
||||
@@ -10,7 +10,9 @@
|
||||
"prepare": "git config core.hooksPath .githooks || true"
|
||||
},
|
||||
"dependencies": {
|
||||
"@daypicker/persian": "^10.0.1",
|
||||
"@heroicons/react": "^2.2.0",
|
||||
"date-fns-jalali": "^4.4.0-0",
|
||||
"framer-motion": "^12.23.24",
|
||||
"lucide-react": "^0.552.0",
|
||||
"next": "16.0.1",
|
||||
|
||||
@@ -89,6 +89,7 @@ export interface PurchaseFilters {
|
||||
package_name?: string;
|
||||
gateway?: string; // gateway name key (e.g. "zarinpal")
|
||||
status?: number;
|
||||
product_id?: number; // filter by a specific product
|
||||
per_page?: number;
|
||||
page?: number;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user