feat: complete phase 3 reporting, logging, cancel counting, and settings

This commit is contained in:
2026-06-12 22:12:36 +03:30
parent 22e3fa1415
commit a8d9bff59e
20 changed files with 741 additions and 110 deletions
+12 -7
View File
@@ -8,18 +8,12 @@ generator client {
binaryTargets = ["native", "debian-openssl-3.0.x", "debian-openssl-1.1.x"] binaryTargets = ["native", "debian-openssl-3.0.x", "debian-openssl-1.1.x"]
} }
enum Role {
USER
ADMIN
}
model User { model User {
id Int @id @default(autoincrement()) id Int @id @default(autoincrement())
username String @unique username String @unique
password String password String
name String? name String?
mobile String? mobile String?
role Role @default(USER) // Deprecated, use roles instead
roles Json? // e.g. ["COUNTER", "ACCOUNTANT", "SUPERVISOR", "ADMIN"] roles Json? // e.g. ["COUNTER", "ACCOUNTANT", "SUPERVISOR", "ADMIN"]
orgId Int? orgId Int?
avatarUrl String? @db.LongText avatarUrl String? @db.LongText
@@ -29,6 +23,7 @@ model User {
lockedLocations Location[] @relation("LocationLocks") lockedLocations Location[] @relation("LocationLocks")
assignedTasks Task[] @relation("AssignedTasks") assignedTasks Task[] @relation("AssignedTasks")
createdTasks Task[] @relation("CreatedTasks") createdTasks Task[] @relation("CreatedTasks")
actionLogs ActionLog[] // Logs created by this user
createdAt DateTime @default(now()) createdAt DateTime @default(now())
updatedAt DateTime @updatedAt updatedAt DateTime @updatedAt
} }
@@ -76,8 +71,9 @@ model Counting {
user_id Int user_id Int
user User @relation(fields: [user_id], references: [id]) user User @relation(fields: [user_id], references: [id])
mode String @default("SHELF") // SHELF, ITEM, TASK mode String @default("SHELF") // SHELF, ITEM, TASK
status String @default("PENDING") // PENDING, APPROVED, REJECTED, CORRECTION_REQUESTED status String @default("PENDING") // PENDING, APPROVED, REJECTED, CORRECTION_REQUESTED, CANCELLED
correctionNote String? @db.Text correctionNote String? @db.Text
cancelReason String? @db.Text
is_offline Boolean @default(false) is_offline Boolean @default(false)
createdAt DateTime @default(now()) createdAt DateTime @default(now())
updatedAt DateTime @updatedAt updatedAt DateTime @updatedAt
@@ -103,3 +99,12 @@ model Task {
createdAt DateTime @default(now()) createdAt DateTime @default(now())
updatedAt DateTime @updatedAt updatedAt DateTime @updatedAt
} }
model ActionLog {
id Int @id @default(autoincrement())
userId Int
user User @relation(fields: [userId], references: [id])
action String // e.g., "LOGIN", "START_SHELF", "CANCEL_SHELF", "COUNT_ITEM"
details String? @db.Text
createdAt DateTime @default(now())
}
+181
View File
@@ -0,0 +1,181 @@
'use client';
import { useState, useEffect } from 'react';
import Header from '@/components/Header';
import { Activity, Search, Filter, CalendarDays, History, X } from 'lucide-react';
export default function LogsPage() {
const [logs, setLogs] = useState([]);
const [total, setTotal] = useState(0);
const [loading, setLoading] = useState(true);
const [typeFilter, setTypeFilter] = useState('ALL');
const [page, setPage] = useState(1);
const take = 50;
const actionTypes = [
{ id: 'ALL', label: 'همه عملیات‌ها' },
{ id: 'LOGIN', label: 'ورود' },
{ id: 'CANCEL_COUNTING', label: 'لغو انبارگردانی' },
];
useEffect(() => {
fetchLogs();
}, [page, typeFilter]);
const fetchLogs = async () => {
setLoading(true);
try {
const skip = (page - 1) * take;
const res = await fetch(`/api/logs?skip=${skip}&take=${take}&type=${typeFilter}`);
if (res.ok) {
const data = await res.json();
setLogs(data.logs || []);
setTotal(data.total || 0);
}
} catch (e) {
console.error(e);
} finally {
setLoading(false);
}
};
const totalPages = Math.ceil(total / take);
return (
<div className="w-full min-h-screen bg-gray-50 flex flex-col pb-24 relative overflow-x-hidden">
<Header title="لاگ عملیات سیستم" showBack={true} />
<div className="flex-1 p-4 md:p-6 flex flex-col gap-6 max-w-4xl mx-auto w-full mt-2">
<div className="flex flex-col gap-1">
<h2 className="text-xl font-black text-gray-800 tracking-tight flex items-center gap-2">
<Activity className="text-indigo-600" size={24} strokeWidth={2.5} />
رهگیری فعالیت کاربران
</h2>
<p className="text-xs text-gray-500 font-medium leading-relaxed">
گزارش کامل عملیاتهای حساس از جمله ورود، لغو انبارگردانی و ...
</p>
</div>
{/* Filters */}
<div className="bg-white rounded-[24px] p-4 shadow-sm border border-gray-100 flex flex-wrap items-center gap-3">
<div className="flex items-center gap-2 text-sm font-bold text-gray-600 ml-2">
<Filter size={16} /> فیلتر نوع:
</div>
{actionTypes.map(t => (
<button
key={t.id}
onClick={() => { setTypeFilter(t.id); setPage(1); }}
className={`px-4 py-2 rounded-[14px] text-xs font-bold transition-all border ${
typeFilter === t.id
? 'bg-gray-900 text-white border-gray-900 shadow-md'
: 'bg-white text-gray-500 border-gray-200 hover:bg-gray-50'
}`}
>
{t.label}
</button>
))}
</div>
{/* Logs List */}
<div className="bg-white border border-gray-100 rounded-[24px] overflow-hidden shadow-sm flex flex-col">
<div className="p-0 overflow-x-auto">
<table className="w-full text-right text-sm min-w-[600px]">
<thead className="bg-gray-50 text-gray-500 text-xs font-bold border-b border-gray-100">
<tr>
<th className="px-6 py-4">کاربر</th>
<th className="px-6 py-4">نوع عملیات</th>
<th className="px-6 py-4">جزئیات</th>
<th className="px-6 py-4 text-left">تاریخ و زمان</th>
</tr>
</thead>
<tbody className="divide-y divide-gray-100">
{logs.map((log) => (
<tr key={log.id} className="hover:bg-gray-50/50 transition-colors">
<td className="px-6 py-4">
<div className="flex items-center gap-2">
<div className="w-8 h-8 bg-indigo-50 text-indigo-600 rounded-lg flex items-center justify-center font-bold text-xs shrink-0">
{log.user?.name ? log.user.name.charAt(0) : '?'}
</div>
<div className="flex flex-col">
<span className="font-bold text-gray-800 text-xs">{log.user?.name || 'ناشناس'}</span>
<span className="text-[10px] text-gray-400 font-medium dir-ltr text-right">{log.user?.username}</span>
</div>
</div>
</td>
<td className="px-6 py-4">
<span className={`px-2.5 py-1 rounded-lg text-[10px] font-black ${
log.action === 'CANCEL_COUNTING' ? 'bg-red-50 text-red-600' :
log.action === 'LOGIN' ? 'bg-green-50 text-green-600' :
'bg-gray-100 text-gray-600'
}`}>
{log.action}
</span>
</td>
<td className="px-6 py-4">
<p className="text-xs text-gray-600 font-medium leading-relaxed max-w-xs truncate">
{log.details || '-'}
</p>
</td>
<td className="px-6 py-4 text-left">
<div className="flex items-center justify-end gap-1.5 text-[10px] font-bold text-gray-500 dir-ltr">
{new Date(log.createdAt).toLocaleString('fa-IR')}
<CalendarDays size={12} className="text-gray-400" />
</div>
</td>
</tr>
))}
{logs.length === 0 && !loading && (
<tr>
<td colSpan="4" className="px-6 py-16 text-center">
<div className="flex flex-col items-center justify-center gap-3">
<History size={32} className="text-gray-300" />
<span className="text-gray-500 font-bold text-sm">هیچ لاگی یافت نشد.</span>
</div>
</td>
</tr>
)}
{loading && (
<tr>
<td colSpan="4" className="px-6 py-16 text-center text-indigo-500 font-bold">
<div className="flex flex-col items-center justify-center gap-3">
<div className="w-8 h-8 border-2 border-indigo-500 border-t-transparent rounded-full animate-spin"></div>
<span className="text-xs">در حال دریافت لاگها...</span>
</div>
</td>
</tr>
)}
</tbody>
</table>
</div>
{/* Pagination */}
{!loading && totalPages > 1 && (
<div className="p-4 border-t border-gray-100 flex items-center justify-between bg-gray-50 text-xs font-bold text-gray-600">
<span>تعداد کل: {total}</span>
<div className="flex items-center gap-2">
<button
disabled={page === 1}
onClick={() => setPage(p => p - 1)}
className="px-3 py-1.5 bg-white border border-gray-200 rounded-lg hover:bg-gray-50 disabled:opacity-50"
>
قبلی
</button>
<span>صفحه {page} از {totalPages}</span>
<button
disabled={page === totalPages}
onClick={() => setPage(p => p + 1)}
className="px-3 py-1.5 bg-white border border-gray-200 rounded-lg hover:bg-gray-50 disabled:opacity-50"
>
بعدی
</button>
</div>
</div>
)}
</div>
</div>
</div>
);
}
+14
View File
@@ -98,6 +98,20 @@ export default function AdminDashboard() {
</div> </div>
</Link> </Link>
</motion.div> </motion.div>
<motion.div variants={item}>
<Link href="/admin/logs" className="bg-white/80 backdrop-blur-sm border border-gray-100 rounded-3xl shadow-[0_4px_20px_rgb(0,0,0,0.03)] p-5 flex items-center justify-between hover:bg-white hover:scale-[1.02] active:scale-95 transition-all">
<div className="flex items-center gap-4">
<div className="w-10 h-10 bg-gray-100 text-gray-600 rounded-xl flex items-center justify-center">
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M22 12h-4l-3 9L9 3l-3 9H2"/></svg>
</div>
<span className="font-extrabold text-sm text-gray-800">لاگ عملیات و فعالیتها</span>
</div>
<div className="w-8 h-8 bg-gray-50 rounded-full flex items-center justify-center">
<svg className="w-4 h-4 text-gray-400 rotate-180" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M9 5l7 7-7 7" /></svg>
</div>
</Link>
</motion.div>
</motion.div> </motion.div>
</div> </div>
); );
+5 -2
View File
@@ -23,8 +23,11 @@ export default function ProductsPage() {
}); });
if (res.ok) { if (res.ok) {
const data = await res.json(); const data = await res.json();
// Assuming Hesabfa returns data.List for query responses // Safely extract the array of products from the Hesabfa response
setProducts(data.List || data || []); const productList = data?.Result?.List || data?.List || (Array.isArray(data) ? data : []);
setProducts(productList);
} else {
setProducts([]);
} }
} catch (e) { } catch (e) {
console.error(e); console.error(e);
+155
View File
@@ -0,0 +1,155 @@
'use client';
import { useState, useEffect } from 'react';
import Header from '@/components/Header';
import { Trophy, AlertTriangle, Activity, BarChart2, CheckCircle2, TrendingUp } from 'lucide-react';
import { motion } from 'framer-motion';
export default function ReportsPage() {
const [data, setData] = useState({ topPerformers: [], mostDiscrepancies: [], all: [] });
const [loading, setLoading] = useState(true);
useEffect(() => {
fetch('/api/reports/leaderboard')
.then(res => res.json())
.then(d => {
if (d.topPerformers) setData(d);
setLoading(false);
});
}, []);
if (loading) {
return (
<div className="w-full min-h-screen bg-gray-50 flex flex-col">
<Header title="گزارشات پرسنل" showBack={true} />
<div className="flex-1 flex justify-center items-center">
<div className="w-8 h-8 border-2 border-indigo-500 border-t-transparent rounded-full animate-spin"></div>
</div>
</div>
);
}
return (
<div className="w-full min-h-screen bg-gray-50 flex flex-col pb-24 relative overflow-x-hidden">
<Header title="گزارشات و عملکرد" showBack={true} />
<div className="flex-1 p-4 md:p-6 flex flex-col gap-6 max-w-4xl mx-auto w-full mt-2">
<div className="flex flex-col gap-1">
<h2 className="text-xl font-black text-gray-800 tracking-tight flex items-center gap-2">
<BarChart2 className="text-indigo-600" size={24} strokeWidth={2.5} />
کارنامه عملکرد تیم
</h2>
<p className="text-xs text-gray-500 font-medium leading-relaxed">
بررسی جامع آمار انبارگردانی، برترینها و میزان خطاهای ثبت شده
</p>
</div>
{/* Top Performers */}
<div className="bg-white border border-indigo-100 rounded-[24px] p-5 shadow-sm flex flex-col gap-4 relative overflow-hidden">
<div className="absolute top-0 right-0 w-24 h-24 bg-indigo-50/50 rounded-bl-full z-0"></div>
<div className="flex items-center gap-2 relative z-10">
<Trophy className="text-yellow-500" size={20} strokeWidth={2.5} />
<h3 className="font-bold text-gray-800">برترین انبارگردانها</h3>
</div>
<div className="flex flex-col gap-3 relative z-10">
{data.topPerformers.map((user, idx) => (
<div key={user.id} className="flex items-center justify-between p-3 bg-gray-50 rounded-[16px] border border-gray-100">
<div className="flex items-center gap-3">
<div className={`w-8 h-8 rounded-xl flex items-center justify-center font-black text-sm text-white shadow-sm ${idx === 0 ? 'bg-yellow-400' : idx === 1 ? 'bg-gray-400' : idx === 2 ? 'bg-amber-600' : 'bg-indigo-400'}`}>
{idx + 1}
</div>
<span className="font-bold text-gray-800 text-sm">{user.name}</span>
</div>
<div className="flex items-center gap-4">
<div className="flex flex-col items-center">
<span className="text-[10px] text-gray-400 font-bold">شمارشها</span>
<span className="text-sm font-black text-indigo-600">{user.totalCounted}</span>
</div>
<div className="flex flex-col items-center">
<span className="text-[10px] text-gray-400 font-bold">دقت عملکرد</span>
<span className="text-sm font-black text-green-600">{user.accuracy}%</span>
</div>
</div>
</div>
))}
{data.topPerformers.length === 0 && (
<p className="text-xs text-gray-400 text-center py-4">هنوز هیچ انبارگردانی ثبت نشده است.</p>
)}
</div>
</div>
{/* Most Discrepancies */}
<div className="bg-white border border-red-100 rounded-[24px] p-5 shadow-sm flex flex-col gap-4 relative overflow-hidden">
<div className="flex items-center gap-2 relative z-10">
<AlertTriangle className="text-red-500" size={20} strokeWidth={2.5} />
<h3 className="font-bold text-gray-800">بیشترین مغایرتهای ثبت شده</h3>
</div>
<div className="flex flex-col gap-3 relative z-10">
{data.mostDiscrepancies.filter(u => u.discrepancies > 0).map((user, idx) => (
<div key={user.id} className="flex items-center justify-between p-3 bg-red-50/30 rounded-[16px] border border-red-50">
<div className="flex items-center gap-3">
<div className="w-8 h-8 rounded-xl bg-red-100 flex items-center justify-center font-black text-xs text-red-600">
{idx + 1}
</div>
<span className="font-bold text-gray-800 text-sm">{user.name}</span>
</div>
<div className="flex items-center gap-4">
<div className="flex flex-col items-center">
<span className="text-[10px] text-red-400 font-bold">مغایرتها</span>
<span className="text-sm font-black text-red-600">{user.discrepancies}</span>
</div>
</div>
</div>
))}
{data.mostDiscrepancies.filter(u => u.discrepancies > 0).length === 0 && (
<p className="text-xs text-gray-400 text-center py-4">خوشبختانه هیچ کاربری مغایرتی نداشته است.</p>
)}
</div>
</div>
{/* Full Details */}
<div className="bg-white border border-gray-100 rounded-[24px] overflow-hidden shadow-sm flex flex-col mt-2">
<div className="p-5 border-b border-gray-100">
<h3 className="font-bold text-gray-800 flex items-center gap-2">
<Activity className="text-gray-500" size={18} />
جزئیات عملکرد همه پرسنل
</h3>
</div>
<div className="overflow-x-auto">
<table className="w-full text-right text-sm">
<thead className="bg-gray-50 text-gray-500 text-[10px] font-black uppercase tracking-widest border-b border-gray-100">
<tr>
<th className="px-5 py-3">نام کاربر</th>
<th className="px-5 py-3 text-center">تعداد شمارش</th>
<th className="px-5 py-3 text-center">قفسههای پوشش داده</th>
<th className="px-5 py-3 text-center">خطا/مغایرت</th>
<th className="px-5 py-3 text-center">لغو شده</th>
<th className="px-5 py-3 text-left">دقت</th>
</tr>
</thead>
<tbody className="divide-y divide-gray-100">
{data.all.map((user) => (
<tr key={user.id} className="hover:bg-gray-50/50 transition-colors">
<td className="px-5 py-4 font-bold text-gray-800">{user.name}</td>
<td className="px-5 py-4 text-center font-black text-indigo-600">{user.totalCounted}</td>
<td className="px-5 py-4 text-center font-bold text-gray-600">{user.uniqueShelves}</td>
<td className="px-5 py-4 text-center font-bold text-red-500">{user.discrepancies}</td>
<td className="px-5 py-4 text-center font-bold text-orange-500">{user.cancelled}</td>
<td className="px-5 py-4 text-left">
<div className="flex items-center justify-end gap-1 font-black text-green-600">
{user.accuracy}%
</div>
</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
</div>
</div>
);
}
+26
View File
@@ -126,6 +126,32 @@ export default function SettingsPage() {
</button> </button>
</div> </div>
{/* Show Suggested Shelves Setting */}
<div className="flex items-start justify-between gap-4 border-b border-gray-50 pb-8">
<div className="flex-1 pr-2">
<div className="flex items-center gap-2 mb-2">
<div className="w-8 h-8 rounded-[12px] bg-emerald-50 text-emerald-600 flex items-center justify-center shrink-0">
<AlertCircle size={16} strokeWidth={2.5} />
</div>
<h2 className="text-sm font-bold text-gray-800">پیشنهاد قفسههای شمارشنشده</h2>
</div>
<p className="text-xs text-gray-500 leading-relaxed">
در صورت فعال بودن، در صفحه داشبورد لیستی از قفسههایی که مدتی شمارش نشدهاند به کاربر پیشنهاد داده میشود.
</p>
</div>
<button
onClick={() => setSettings(s => ({ ...s, show_suggested_shelves: s.show_suggested_shelves === undefined ? false : !s.show_suggested_shelves }))}
className={`relative inline-flex h-8 w-14 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent transition-colors duration-300 focus:outline-none focus-visible:ring-2 focus-visible:ring-indigo-500 focus-visible:ring-offset-2 ${(settings.show_suggested_shelves ?? true) ? 'bg-emerald-600' : 'bg-gray-200'}`}
role="switch"
aria-checked={settings.show_suggested_shelves ?? true}
>
<span
className={`pointer-events-none inline-block h-6 w-6 transform rounded-full bg-white shadow-md ring-0 transition-transform duration-300 ${(settings.show_suggested_shelves ?? true) ? '-translate-x-6' : 'translate-x-0'}`}
/>
</button>
</div>
{/* Correction Roles Setting */} {/* Correction Roles Setting */}
<div> <div>
<div className="flex items-center gap-2 mb-2"> <div className="flex items-center gap-2 mb-2">
+18
View File
@@ -101,6 +101,24 @@ export default function UsersPage() {
</p> </p>
</div> </div>
<Link
href="/admin/reports"
className="bg-indigo-600 text-white p-4 rounded-[20px] shadow-md hover:bg-indigo-700 transition-all flex items-center justify-between group"
>
<div className="flex items-center gap-3">
<div className="w-10 h-10 bg-white/20 rounded-xl flex items-center justify-center backdrop-blur-sm">
<BarChart2 size={20} />
</div>
<div className="flex flex-col">
<span className="font-black text-sm">گزارشات و رتبهبندی پرسنل</span>
<span className="text-[10px] text-indigo-200 mt-0.5">کارمندان برتر، بیشترین خطا و...</span>
</div>
</div>
<div className="w-8 h-8 bg-white/10 rounded-full flex items-center justify-center group-hover:-translate-x-1 transition-transform">
<svg className="w-4 h-4 rotate-180" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M9 5l7 7-7 7" /></svg>
</div>
</Link>
{/* Search */} {/* Search */}
<div className="relative"> <div className="relative">
<Search className="absolute right-4 top-1/2 -translate-y-1/2 text-gray-400" size={18} /> <Search className="absolute right-4 top-1/2 -translate-y-1/2 text-gray-400" size={18} />
+2 -2
View File
@@ -29,9 +29,9 @@ export async function POST(req) {
try { parsedRoles = JSON.parse(parsedRoles); } catch (e) { parsedRoles = null; } try { parsedRoles = JSON.parse(parsedRoles); } catch (e) { parsedRoles = null; }
} }
let userRoles = Array.isArray(parsedRoles) ? parsedRoles : (user.role === 'ADMIN' ? ['ADMIN'] : ['COUNTER']); let userRoles = Array.isArray(parsedRoles) ? parsedRoles : ['COUNTER'];
const token = signToken({ id: user.id, username: user.username, name: user.name, orgId: user.orgId, roles: userRoles, role: user.role }); const token = signToken({ id: user.id, username: user.username, name: user.name, orgId: user.orgId, roles: userRoles });
return Response.json({ message: 'با موفقیت وارد شدید', token, user: { id: user.id, name: user.name, orgId: user.orgId, roles: userRoles, avatarUrl: user.avatarUrl } }); return Response.json({ message: 'با موفقیت وارد شدید', token, user: { id: user.id, name: user.name, orgId: user.orgId, roles: userRoles, avatarUrl: user.avatarUrl } });
} catch (error) { } catch (error) {
@@ -46,9 +46,9 @@ export async function POST(req) {
try { parsedRoles = JSON.parse(parsedRoles); } catch (e) { parsedRoles = null; } try { parsedRoles = JSON.parse(parsedRoles); } catch (e) { parsedRoles = null; }
} }
let userRoles = Array.isArray(parsedRoles) ? parsedRoles : (user.role === 'ADMIN' ? ['ADMIN'] : ['COUNTER']); let userRoles = Array.isArray(parsedRoles) ? parsedRoles : ['COUNTER'];
const token = signToken({ id: user.id, username: user.username, name: user.name, roles: userRoles, role: user.role }); const token = signToken({ id: user.id, username: user.username, name: user.name, roles: userRoles });
return NextResponse.json({ verified: true, token, user: { id: user.id, name: user.name, roles: userRoles, role: user.role } }); return NextResponse.json({ verified: true, token, user: { id: user.id, name: user.name, roles: userRoles } });
} }
return NextResponse.json({ verified: false }, { status: 400 }); return NextResponse.json({ verified: false }, { status: 400 });
} catch (error) { } catch (error) {
+59
View File
@@ -0,0 +1,59 @@
import prisma from '@/lib/prisma';
import { NextResponse } from 'next/server';
export async function POST(req) {
try {
const body = await req.json();
const { shelfCode, warehouse, userId, reason, mode, product_id } = body;
if (!reason) {
return NextResponse.json({ error: 'اطلاعات کامل نیست' }, { status: 400 });
}
// 1. Mark recent countings in this shelf/warehouse by this user as CANCELLED
// We assume counts created in the last 24h by this user for this shelf
const twentyFourHoursAgo = new Date();
twentyFourHoursAgo.setHours(twentyFourHoursAgo.getHours() - 24);
const where = {
warehouse: Number(warehouse),
user_id: Number(userId),
createdAt: { gte: twentyFourHoursAgo },
status: 'PENDING'
};
if (mode === 'SHELF' && shelfCode) {
where.shelfCode = shelfCode.toUpperCase();
} else if (mode === 'ITEM' && product_id) {
where.product_id = Number(product_id);
}
const updated = await prisma.counting.updateMany({
where,
data: {
status: 'CANCELLED',
cancelReason: reason
}
});
// 2. Unlock the location
await prisma.location.updateMany({
where: { code: shelfCode.toUpperCase(), warehouse: Number(warehouse) },
data: { isLocked: false, lockedById: null, lockedAt: null }
});
// 3. Log the action
await prisma.actionLog.create({
data: {
userId: Number(userId),
action: 'CANCEL_COUNTING',
details: `لغو شمارش ${mode === 'SHELF' ? 'قفسه' : 'کالا'} ${shelfCode.toUpperCase()} به دلیل: ${reason}`
}
});
return NextResponse.json({ success: true, cancelledCount: updated.count });
} catch (error) {
console.error('Cancel counting error:', error);
return NextResponse.json({ error: 'خطا در لغو انبارگردانی' }, { status: 500 });
}
}
+30
View File
@@ -0,0 +1,30 @@
import prisma from '@/lib/prisma';
import { NextResponse } from 'next/server';
export async function GET(req) {
try {
const url = new URL(req.url);
const userId = url.searchParams.get('userId');
if (!userId) {
return NextResponse.json({ error: 'کاربر نامشخص' }, { status: 400 });
}
const activeLocations = await prisma.location.findMany({
where: {
isLocked: true,
lockedById: Number(userId)
},
select: {
code: true,
warehouse: true,
floor: true
}
});
return NextResponse.json({ active: activeLocations });
} catch (error) {
console.error('Fetch active locations error:', error);
return NextResponse.json({ error: 'خطا در سرور' }, { status: 500 });
}
}
+52
View File
@@ -0,0 +1,52 @@
import prisma from '@/lib/prisma';
import { NextResponse } from 'next/server';
export async function GET(req) {
try {
const url = new URL(req.url);
const take = parseInt(url.searchParams.get('take')) || 50;
const skip = parseInt(url.searchParams.get('skip')) || 0;
const type = url.searchParams.get('type'); // optional filter
const where = type && type !== 'ALL' ? { action: type } : {};
const [logs, total] = await Promise.all([
prisma.actionLog.findMany({
where,
take,
skip,
orderBy: { createdAt: 'desc' },
include: { user: { select: { name: true, username: true } } }
}),
prisma.actionLog.count({ where })
]);
return NextResponse.json({ logs, total });
} catch (error) {
console.error('Fetch logs error:', error);
return NextResponse.json({ error: 'خطا در دریافت لاگ‌ها' }, { status: 500 });
}
}
export async function POST(req) {
try {
const { userId, action, details } = await req.json();
if (!userId || !action) {
return NextResponse.json({ error: 'اطلاعات ناقص است' }, { status: 400 });
}
const log = await prisma.actionLog.create({
data: {
userId: Number(userId),
action,
details
}
});
return NextResponse.json({ success: true, log });
} catch (error) {
console.error('Create log error:', error);
return NextResponse.json({ error: 'خطا در ثبت لاگ' }, { status: 500 });
}
}
+51
View File
@@ -0,0 +1,51 @@
import prisma from '@/lib/prisma';
import { NextResponse } from 'next/server';
export async function GET() {
try {
const users = await prisma.user.findMany({
include: {
countings: true
}
});
const report = users.map(user => {
const counts = user.countings || [];
const totalCounted = counts.length;
// Calculate discrepancies (assuming old_count !== new_count)
const discrepancies = counts.filter(c => c.old_count !== c.new_count).length;
// Calculate total cancelled
const cancelled = counts.filter(c => c.status === 'CANCELLED').length;
// Unique shelves visited
const uniqueShelves = new Set(counts.map(c => c.shelfCode).filter(Boolean)).size;
return {
id: user.id,
name: user.name || user.username,
totalCounted,
discrepancies,
cancelled,
uniqueShelves,
accuracy: totalCounted > 0 ? (((totalCounted - discrepancies) / totalCounted) * 100).toFixed(1) : 0
};
}).filter(u => u.totalCounted > 0);
// Sort top performers by totalCounted
const topPerformers = [...report].sort((a, b) => b.totalCounted - a.totalCounted).slice(0, 5);
// Sort most discrepancies
const mostDiscrepancies = [...report].sort((a, b) => b.discrepancies - a.discrepancies).slice(0, 5);
return NextResponse.json({
topPerformers,
mostDiscrepancies,
all: report.sort((a, b) => b.totalCounted - a.totalCounted)
});
} catch (error) {
console.error('Fetch leaderboard error:', error);
return NextResponse.json({ error: 'خطا در دریافت گزارش' }, { status: 500 });
}
}
+1 -2
View File
@@ -10,7 +10,6 @@ export async function GET() {
username: true, username: true,
mobile: true, mobile: true,
roles: true, roles: true,
role: true,
createdAt: true, createdAt: true,
_count: { _count: {
select: { countings: true } select: { countings: true }
@@ -27,7 +26,7 @@ export async function GET() {
} }
return { return {
...user, ...user,
roles: Array.isArray(parsedRoles) ? parsedRoles : (user.role === 'ADMIN' ? ['ADMIN'] : ['COUNTER']) roles: Array.isArray(parsedRoles) ? parsedRoles : ['COUNTER']
}; };
}); });
+30 -6
View File
@@ -168,6 +168,22 @@ function ItemCountingContent() {
} }
}; };
const handleCancelItem = async () => {
const reason = window.prompt('لطفاً دلیل لغو انبارگردانی این کالا را وارد کنید:');
if (!reason) return;
try {
await fetch('/api/counting/cancel', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ product_id: code, warehouse, userId: user?.id, reason, mode: 'ITEM' })
});
router.push('/dashboard');
} catch (error) {
alert('خطا در لغو انبارگردانی کالا');
}
};
const handleFinish = () => { const handleFinish = () => {
router.push('/dashboard'); router.push('/dashboard');
}; };
@@ -317,12 +333,20 @@ function ItemCountingContent() {
</div> </div>
)} )}
<button <div className="flex items-center gap-2 mt-2">
onClick={handleFinish} <button
className="w-full py-4 bg-white border border-gray-200 text-gray-600 text-sm font-extrabold rounded-[20px] transition-all hover:bg-gray-50 hover:text-gray-900 mt-2 shadow-sm" onClick={handleCancelItem}
> className="flex-1 py-4 bg-red-50 border border-red-100 text-red-500 text-sm font-extrabold rounded-[20px] transition-all hover:bg-red-100 shadow-sm"
پایان کار با این کالا >
</button> لغو انبارگردانی
</button>
<button
onClick={handleFinish}
className="flex-[2] py-4 bg-white border border-gray-200 text-gray-600 text-sm font-extrabold rounded-[20px] transition-all hover:bg-gray-50 hover:text-gray-900 shadow-sm"
>
پایان کار با این کالا
</button>
</div>
</div> </div>
</div> </div>
+32 -7
View File
@@ -205,6 +205,22 @@ function ShelfCountingContent() {
} }
}; };
const handleCancelShelf = async () => {
const reason = window.prompt('لطفاً دلیل لغو انبارگردانی این قفسه را وارد کنید:');
if (!reason) return;
try {
await fetch('/api/counting/cancel', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ shelfCode, warehouse, userId: user?.id, reason, mode: 'SHELF' })
});
router.push('/dashboard');
} catch (error) {
alert('خطا در لغو انبارگردانی');
}
};
const isBlind = settings?.blind_counting && !hasRole(user?.roles, ['ADMIN', 'SUPERVISOR']); const isBlind = settings?.blind_counting && !hasRole(user?.roles, ['ADMIN', 'SUPERVISOR']);
if (loading) { if (loading) {
@@ -234,13 +250,22 @@ function ShelfCountingContent() {
</div> </div>
</div> </div>
<button <div className="flex items-center gap-2">
onClick={handleFinishShelf} <button
className="bg-white/20 hover:bg-white/30 text-white text-xs font-black py-2.5 px-4 rounded-[14px] transition-colors flex items-center gap-2 backdrop-blur-sm shadow-sm" onClick={handleCancelShelf}
> className="bg-red-500/20 hover:bg-red-500/40 text-red-100 text-xs font-black py-2.5 px-3 rounded-[14px] transition-colors flex items-center gap-1 backdrop-blur-sm"
<Unlock size={14} strokeWidth={3} /> >
پایان قفسه <X size={14} strokeWidth={3} />
</button> لغو
</button>
<button
onClick={handleFinishShelf}
className="bg-white/20 hover:bg-white/30 text-white text-xs font-black py-2.5 px-4 rounded-[14px] transition-colors flex items-center gap-2 backdrop-blur-sm shadow-sm"
>
<Unlock size={14} strokeWidth={3} />
پایان قفسه
</button>
</div>
</div> </div>
<div className="flex-1 p-4 md:p-6 max-w-md mx-auto w-full flex flex-col gap-6 mt-2"> <div className="flex-1 p-4 md:p-6 max-w-md mx-auto w-full flex flex-col gap-6 mt-2">
+59 -20
View File
@@ -7,25 +7,43 @@ import { History, ScanLine, ListChecks, AlertTriangle, Layers, MapPin } from 'lu
export default function Dashboard() { export default function Dashboard() {
const [uncountedShelves, setUncountedShelves] = useState([]); const [uncountedShelves, setUncountedShelves] = useState([]);
const [activeSessions, setActiveSessions] = useState([]);
const [settings, setSettings] = useState(null); const [settings, setSettings] = useState(null);
const [user, setUser] = useState(null);
useEffect(() => { useEffect(() => {
fetchData(); const userData = localStorage.getItem('user');
let u = null;
if (userData) {
u = JSON.parse(userData);
setUser(u);
}
fetchData(u);
}, []); }, []);
const fetchData = async () => { const fetchData = async (currentUser) => {
try { try {
const setRes = await fetch('/api/settings'); const setRes = await fetch('/api/settings');
let currentSettings = { uncounted_shelf_days: 10 }; let currentSettings = { uncounted_shelf_days: 10, show_suggested_shelves: true };
if (setRes.ok) { if (setRes.ok) {
currentSettings = await setRes.json(); currentSettings = await setRes.json();
setSettings(currentSettings); setSettings(currentSettings);
} }
const uncRes = await fetch(`/api/reports/uncounted?days=${currentSettings.uncounted_shelf_days || 10}`); if (currentSettings.show_suggested_shelves !== false) {
if (uncRes.ok) { const uncRes = await fetch(`/api/reports/uncounted?days=${currentSettings.uncounted_shelf_days || 10}`);
const uncData = await uncRes.json(); if (uncRes.ok) {
setUncountedShelves(uncData.uncounted || []); const uncData = await uncRes.json();
setUncountedShelves(uncData.uncounted || []);
}
}
if (currentUser?.id) {
const actRes = await fetch(`/api/locations/active?userId=${currentUser.id}`);
if (actRes.ok) {
const actData = await actRes.json();
setActiveSessions(actData.active || []);
}
} }
} catch (e) { } catch (e) {
console.error(e); console.error(e);
@@ -76,22 +94,43 @@ export default function Dashboard() {
</motion.div> </motion.div>
</div> </div>
<motion.div variants={item}> {/* Active Sessions */}
<Link href="/my-counts" className="bg-white/80 backdrop-blur-sm border border-gray-100 rounded-3xl shadow-sm p-5 flex items-center justify-between hover:bg-white hover:scale-[1.02] active:scale-95 transition-all"> {activeSessions.length > 0 && (
<div className="flex items-center gap-4"> <motion.div variants={item} className="flex flex-col gap-3 mt-2">
<div className="w-10 h-10 bg-green-50 text-green-600 rounded-xl flex items-center justify-center"> <h3 className="text-sm font-black text-gray-800 flex items-center gap-2 px-2">
<ListChecks strokeWidth={2} size={20} /> <span className="relative flex h-3 w-3">
</div> <span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-indigo-400 opacity-75"></span>
<span className="font-black text-sm text-gray-800">شمارشهای من</span> <span className="relative inline-flex rounded-full h-3 w-3 bg-indigo-500"></span>
</span>
قفسههای باز شما (ناتمام)
</h3>
<div className="flex flex-col gap-3">
{activeSessions.map((session, idx) => (
<div key={idx} className="bg-white border border-indigo-100 rounded-[20px] p-4 flex items-center justify-between shadow-sm shadow-indigo-100/50">
<div className="flex items-center gap-3">
<div className="w-10 h-10 bg-indigo-50 text-indigo-600 rounded-xl flex items-center justify-center">
<Layers size={18} />
</div>
<div className="flex flex-col">
<span className="text-xs font-black text-gray-800 tracking-widest uppercase">{session.code}</span>
<span className="text-[10px] text-gray-400 font-bold mt-1">انبار: {session.warehouse || '-'}</span>
</div>
</div>
<Link
href={`/counting/shelf?code=${session.code}&warehouse=${session.warehouse}`}
className="bg-gray-900 text-white px-4 py-2.5 rounded-[12px] text-xs font-bold hover:bg-gray-800 transition-colors"
>
ادامه / پایان
</Link>
</div>
))}
</div> </div>
<div className="w-8 h-8 bg-gray-50 rounded-full flex items-center justify-center"> </motion.div>
<svg className="w-4 h-4 text-gray-400 rotate-180" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M9 5l7 7-7 7" /></svg> )}
</div>
</Link>
</motion.div>
{/* Suggested Shelves to count */} {/* Suggested Shelves to count */}
{uncountedShelves.length > 0 && ( {settings?.show_suggested_shelves !== false && uncountedShelves.length > 0 && (
<motion.div variants={item} className="flex flex-col gap-3 mt-4"> <motion.div variants={item} className="flex flex-col gap-3 mt-4">
<div className="flex items-center justify-between px-2"> <div className="flex items-center justify-between px-2">
<h3 className="text-sm font-black text-gray-800 flex items-center gap-2"> <h3 className="text-sm font-black text-gray-800 flex items-center gap-2">
+10 -2
View File
@@ -24,8 +24,16 @@ export default function RootLayout({ children }) {
<html lang="fa" dir="rtl"> <html lang="fa" dir="rtl">
<body className="bg-gray-100 transition-colors"> <body className="bg-gray-100 transition-colors">
<main className="w-full min-h-screen flex flex-col justify-start items-center"> <main className="w-full min-h-screen flex flex-col justify-start items-center">
<div className="w-full max-w-md bg-white min-h-screen shadow-lg relative pb-16"> <div className="w-full max-w-md bg-white min-h-screen shadow-lg relative flex flex-col">
{children} <div className="flex-1 pb-10">
{children}
</div>
<div className="w-full py-4 text-center mt-auto">
<p className="text-[9px] font-bold text-gray-300 dir-ltr tracking-widest uppercase">
Designed & Developed by <span className="text-indigo-300">DrMesta</span>
</p>
<p className="text-[8px] font-bold text-gray-200 mt-1">App v1.4.0</p>
</div>
</div> </div>
</main> </main>
</body> </body>
-58
View File
@@ -1,58 +0,0 @@
'use client';
import { useState, useEffect } from 'react';
import Header from '@/components/Header';
export default function MyCountsPage() {
const [counts, setCounts] = useState([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
const fetchMyCounts = async () => {
const userData = localStorage.getItem('user');
if (userData) {
const user = JSON.parse(userData);
try {
const res = await fetch(`/api/counting?user_id=${user.id}`);
if (res.ok) setCounts(await res.json());
} catch (e) {
console.error(e);
}
}
setLoading(false);
};
fetchMyCounts();
}, []);
return (
<div className="w-full min-h-screen bg-gray-50 flex flex-col pb-20">
<Header title="شمارش های من" showBack={true} />
<div className="p-4 flex flex-col gap-4">
{loading ? (
<div className="text-center p-10">در حال دریافت...</div>
) : counts.length === 0 ? (
<div className="text-center text-gray-500 p-10">هنوز شمارشی ثبت نکردهاید.</div>
) : (
counts.map(count => (
<div key={count.id} className="bg-white p-4 rounded shadow border border-gray-200">
<div className="flex justify-between items-start">
<div className="flex flex-col">
<span className="font-bold text-sm">{count.product_name}</span>
<span className="text-xs text-gray-500 mt-1">کد: {count.product_id} | انبار: {count.warehouse}</span>
<span className="text-xs text-gray-500 mt-1">قفسه: {count.shelf || 'ثبت نشده'}</span>
</div>
<div className="flex flex-col items-center bg-gray-100 p-2 rounded">
<span className="font-bold">{count.new_count}</span>
<span className="text-[10px]">شمارش شما</span>
</div>
</div>
<div className="mt-2 text-[10px] text-gray-400 text-left">
{new Date(count.createdAt).toLocaleString('fa-IR')}
</div>
</div>
))
)}
</div>
</div>
);
}
+1 -1
View File
@@ -158,7 +158,7 @@ export default function SettingsPage() {
<div className="text-center"> <div className="text-center">
<h3 className="text-lg font-black text-gray-800">{user?.name || 'کاربر'}</h3> <h3 className="text-lg font-black text-gray-800">{user?.name || 'کاربر'}</h3>
<p className="text-xs text-gray-400 font-medium mt-1 uppercase tracking-wider">{user?.role === 'ADMIN' ? 'مدیریت کل' : 'کاربر عادی'}</p> <p className="text-xs text-gray-400 font-medium mt-1 uppercase tracking-wider">{user?.roles?.includes('ADMIN') ? 'مدیریت کل' : 'کاربر عادی'}</p>
</div> </div>
</motion.section> </motion.section>