feat: response in mobile and accouting
This commit is contained in:
+248
-75
@@ -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';
|
||||
@@ -25,6 +26,51 @@ 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;
|
||||
@@ -166,9 +212,10 @@ 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>('');
|
||||
@@ -187,20 +234,20 @@ export default function AccountingPage() {
|
||||
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]);
|
||||
|
||||
@@ -218,28 +265,61 @@ 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);
|
||||
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]);
|
||||
|
||||
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),
|
||||
parseFee(transactionFee)
|
||||
)
|
||||
);
|
||||
})
|
||||
.catch((err) => {
|
||||
if (!cancelled) {
|
||||
setError(err instanceof Error ? err.message : 'خطا در دریافت دادهها');
|
||||
}
|
||||
})
|
||||
.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(() => {
|
||||
@@ -291,13 +371,29 @@ export default function AccountingPage() {
|
||||
if (allPurchases) runAnalysis();
|
||||
}, [runAnalysis, allPurchases]);
|
||||
|
||||
const handleReset = () => {
|
||||
setSelectedPackageName(packages[0]?.name || '');
|
||||
setSelectedProductId('');
|
||||
setDateFrom('');
|
||||
setDateTo('');
|
||||
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('');
|
||||
setSelectedProductId('');
|
||||
applyPreset('today');
|
||||
setStatuses([...PAID_STATUSES]);
|
||||
setMyketRate('85');
|
||||
setCafeRate('85');
|
||||
@@ -310,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">
|
||||
@@ -384,7 +475,7 @@ export default function AccountingPage() {
|
||||
label="از تاریخ"
|
||||
placeholder="انتخاب تاریخ شروع"
|
||||
value={dateFrom}
|
||||
onChange={setDateFrom}
|
||||
onChange={handleDateFromChange}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -406,7 +497,7 @@ export default function AccountingPage() {
|
||||
label="تا تاریخ"
|
||||
placeholder="انتخاب تاریخ پایان"
|
||||
value={dateTo}
|
||||
onChange={setDateTo}
|
||||
onChange={handleDateToChange}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -423,6 +514,30 @@ export default function AccountingPage() {
|
||||
</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 */}
|
||||
<div className="mt-4">
|
||||
<label className={labelClass}>وضعیت</label>
|
||||
@@ -495,7 +610,7 @@ export default function AccountingPage() {
|
||||
کافهبازار ۸۵٪ (فروش زیر ۱۰ میلیارد ریال) و ۷۰٪ (بالای آن) است.
|
||||
</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}
|
||||
@@ -537,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 */}
|
||||
@@ -593,8 +680,51 @@ export default function AccountingPage() {
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="overflow-x-auto">
|
||||
<table className="min-w-full divide-y divide-gray-200 dark:divide-gray-800">
|
||||
<>
|
||||
{/* 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">
|
||||
<th className="px-4 py-3">محصول</th>
|
||||
@@ -630,7 +760,8 @@ export default function AccountingPage() {
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
@@ -651,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">
|
||||
|
||||
Reference in New Issue
Block a user