Compare commits

...

19 Commits

Author SHA1 Message Date
drmesta d27aca2a3f feat: redesign counting flow, fix stats and history errors, continuous scanner, houka signature, counting mode toggles, fix hesabfa stock extraction and product_id int limit 2026-06-13 00:17:11 +03:30
drmesta 37dd2e0f16 fix: cancel counting, redesigned locations, scanner defaults, uncounted items, and restored dashboard header 2026-06-12 23:46:48 +03:30
drmesta fd9a57b96c feat: unified sticky header and removed redundant titles 2026-06-12 22:16:23 +03:30
drmesta a8d9bff59e feat: complete phase 3 reporting, logging, cancel counting, and settings 2026-06-12 22:12:36 +03:30
drmesta 22e3fa1415 feat: complete Phase 2 counting features, UI redesign, and discrepancy dashboard 2026-06-12 21:29:39 +03:30
drmesta 879745f15e feat: complete admin suite (users, products, dynamic warehouses) 2026-06-12 11:51:04 +03:30
drmesta 4675d7ce27 feat: redesign settings, add warehouse/user/product management, update location schema 2026-06-12 11:44:05 +03:30
drmesta 8104224a5a fix: admin dashboard missing links and dynamic warehouses 2026-06-12 11:18:41 +03:30
drmesta 73b87193e1 feat: dynamic warehouse management and fix admin header 2026-06-12 11:09:07 +03:30
drmesta aabcea3aeb fix: JSON parsing for user roles and offline counting sync 2026-06-12 10:53:14 +03:30
drmesta cc85a78e45 feat: ultimate warehouse management features (blind count, offline sync, shelf locking, discrepancy dashboard) 2026-06-12 08:28:14 +03:30
drmesta cd74012c52 fix memory leak (OOM killer) and optimize build speed 2026-06-12 01:09:23 +03:30
drmesta 3b5f8240be fix prisma openssl mismatch in builder stage 2026-06-11 23:38:13 +03:30
drmesta 1171b7f1e3 use fast npm mirror to prevent 30m timeout 2026-06-11 23:17:55 +03:30
drmesta 3649841e61 restore package-lock to fix timeout 2026-06-11 21:30:14 +03:30
drmesta dc0c617e77 upgrade node version to 20 for tailwind v5 2026-06-11 20:35:16 +03:30
drmesta 2c2c03717d upgrade node version to 20 for tailwind v4 2026-06-11 20:06:14 +03:30
drmesta 6a8d214762 change docker file and add install page 2026-06-11 19:54:04 +03:30
drmesta 3ce26d4d1a stable ui 2026-06-11 19:45:03 +03:30
59 changed files with 10661 additions and 397 deletions
+9 -8
View File
@@ -1,17 +1,18 @@
# پایه تصویر Node.js (استفاده از نسخه slim به جای alpine برای جلوگیری از ارورهای شبکه و تحریم در سرورهای ایرانی)
FROM node:18-slim AS base
# پایه تصویر Node.js (استفاده از نسخه ۲۰ به دلیل نیازمندی‌های Tailwind v4 و WebAuthn)
FROM node:20-slim AS base
RUN apt-get update && apt-get install -y openssl libc6 && rm -rf /var/lib/apt/lists/*
# مرحله ۱: نصب نیازمندی‌ها
FROM base AS deps
RUN apt-get update && apt-get install -y openssl libc6
WORKDIR /app
# کپی فایل‌های نصب پکیج
COPY package.json package-lock.json* ./
COPY prisma ./prisma/
# نصب پکیج‌ها و جنریت کردن کلاینت Prisma
RUN npm install
# استفاده از میرور قدرتمند و نصب با استفاده از لاک‌فایل برای سرعت بالا و مصرف رم پایین
RUN npm config set registry https://registry.npmmirror.com/ && \
npm ci
RUN npx prisma generate
# مرحله ۲: بیلد پروژه
@@ -23,6 +24,9 @@ COPY . .
# غیرفعال کردن تله‌متری Next.js
ENV NEXT_TELEMETRY_DISABLED=1
# محدود کردن مصرف رم Node.js برای جلوگیری از کرش کردن سرور (OOM Killer) در سرورهای ضعیف
ENV NODE_OPTIONS="--max-old-space-size=1024"
# بیلد پروژه
RUN npm run build
@@ -30,9 +34,6 @@ RUN npm run build
FROM base AS runner
WORKDIR /app
# نصب openssl برای اجرای Prisma در محیط داکر
RUN apt-get update && apt-get install -y openssl && rm -rf /var/lib/apt/lists/*
ENV NODE_ENV=production
ENV NEXT_TELEMETRY_DISABLED=1
+8 -1
View File
@@ -1,6 +1,13 @@
import withPWAInit from "@ducanh2912/next-pwa";
const withPWA = withPWAInit({
dest: "public",
disable: process.env.NODE_ENV === "development",
});
/** @type {import('next').NextConfig} */
const nextConfig = {
output: "standalone",
};
export default nextConfig;
export default withPWA(nextConfig);
+5375
View File
File diff suppressed because it is too large Load Diff
+7
View File
@@ -9,15 +9,22 @@
"lint": "next lint"
},
"dependencies": {
"@ducanh2912/next-pwa": "^10.2.9",
"@prisma/client": "^6.4.1",
"@simplewebauthn/browser": "^13.3.0",
"@simplewebauthn/server": "^13.3.1",
"@tailwindcss/postcss": "^4.0.0",
"@yudiel/react-qr-scanner": "^2.6.0",
"axios": "^1.7.9",
"bcrypt": "^5.1.1",
"bcryptjs": "^3.0.3",
"framer-motion": "^12.40.0",
"jose": "^6.2.3",
"jsonwebtoken": "^9.0.2",
"localforage": "^1.10.0",
"lucide-react": "^1.17.0",
"next": "15.1.7",
"next-themes": "^0.4.6",
"postcss": "^8.5.2",
"react": "^19.0.0",
"react-dom": "^19.0.0",
+63 -7
View File
@@ -5,11 +5,7 @@ datasource db {
generator client {
provider = "prisma-client-js"
}
enum Role {
USER
ADMIN
binaryTargets = ["native", "debian-openssl-3.0.x", "debian-openssl-1.1.x"]
}
model User {
@@ -18,13 +14,33 @@ model User {
password String
name String?
mobile String?
role Role @default(USER)
roles Json? // e.g. ["COUNTER", "ACCOUNTANT", "SUPERVISOR", "ADMIN"]
orgId Int?
avatarUrl String? @db.LongText
challenge String? @db.Text
countings Counting[]
authenticators Authenticator[]
lockedLocations Location[] @relation("LocationLocks")
assignedTasks Task[] @relation("AssignedTasks")
createdTasks Task[] @relation("CreatedTasks")
actionLogs ActionLog[] // Logs created by this user
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}
model Authenticator {
id String @id @default(cuid())
credentialID String @unique
credentialPublicKey Bytes
counter BigInt
credentialDeviceType String
credentialBackedUp Boolean
transports String?
userId Int
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
}
model Location {
id Int @id @default(autoincrement())
code String @unique
@@ -32,13 +48,18 @@ model Location {
region Int
sector String
row Int
warehouse Int?
countings Counting[]
isLocked Boolean @default(false)
lockedById Int?
lockedBy User? @relation("LocationLocks", fields: [lockedById], references: [id])
lockedAt DateTime?
createdAt DateTime @default(now())
}
model Counting {
id Int @id @default(autoincrement())
product_id Int
product_id String
product_name String
warehouse Int
@@ -49,6 +70,41 @@ model Counting {
new_count Int
user_id Int
user User @relation(fields: [user_id], references: [id])
mode String @default("SHELF") // SHELF, ITEM, TASK
status String @default("PENDING") // PENDING, APPROVED, REJECTED, CORRECTION_REQUESTED, CANCELLED
correctionNote String? @db.Text
cancelReason String? @db.Text
is_offline Boolean @default(false)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}
model SystemSetting {
id Int @id @default(autoincrement())
key String @unique
value String @db.Text
updatedAt DateTime @updatedAt
}
model Task {
id Int @id @default(autoincrement())
type String // RECOUNT, SUGGESTED_SHELF, SUGGESTED_ITEM
targetId String // shelfCode or product_id
targetName String? // for UI display
status String @default("OPEN") // OPEN, IN_PROGRESS, COMPLETED
assignedTo Int?
user User? @relation("AssignedTasks", fields: [assignedTo], references: [id])
createdBy Int
creator User @relation("CreatedTasks", fields: [createdBy], references: [id])
createdAt DateTime @default(now())
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())
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 318 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 318 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 375 KiB

+22
View File
@@ -0,0 +1,22 @@
{
"name": "سیستم انبارداری",
"short_name": "انبارداری",
"description": "سیستم جامع مدیریت قفسه‌ها و انبارداری",
"start_url": "/",
"display": "standalone",
"background_color": "#ffffff",
"theme_color": "#f8fafc",
"orientation": "portrait",
"icons": [
{
"src": "/icons/icon-192x192.png",
"sizes": "192x192",
"type": "image/png"
},
{
"src": "/icons/icon-512x512.png",
"sizes": "512x512",
"type": "image/png"
}
]
}
+1
View File
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+292
View File
@@ -0,0 +1,292 @@
'use client';
import { useState, useEffect } from 'react';
import Header from '@/components/Header';
import { AlertTriangle, CheckCircle, PackageSearch, RefreshCw, Send, ListTree, ArrowDownRight, ArrowUpRight, Search, Filter } from 'lucide-react';
import { motion, AnimatePresence } from 'framer-motion';
export default function DiscrepancyDashboard() {
const [warehouse, setWarehouse] = useState('');
const [warehouses, setWarehouses] = useState([]);
const [data, setData] = useState({ discrepancies: [], accurate: [], uncounted: [] });
const [loading, setLoading] = useState(true);
const [search, setSearch] = useState('');
const [filter, setFilter] = useState('all'); // all, surplus (مازاد), deficit (کسری), uncounted
useEffect(() => {
fetch('/api/settings')
.then(res => res.json())
.then(data => {
if (data.warehouses) {
setWarehouses(data.warehouses);
if (data.warehouses.length > 0) {
setWarehouse(data.warehouses[0].id);
}
}
});
}, []);
useEffect(() => {
if (warehouse) {
fetchData();
}
}, [warehouse]);
const fetchData = async () => {
setLoading(true);
try {
const [resDiscrepancies, resUncounted] = await Promise.all([
fetch(`/api/reports/discrepancies?warehouse=${warehouse}`),
fetch(`/api/reports/uncounted?warehouse=${warehouse}`)
]);
let finalData = { discrepancies: [], accurate: [], uncounted: [] };
if (resDiscrepancies.ok) {
const result = await resDiscrepancies.json();
finalData = { ...finalData, ...result };
}
if (resUncounted.ok) {
const resultUncounted = await resUncounted.json();
finalData.uncounted = resultUncounted.uncounted || [];
}
setData(finalData);
} catch (e) {
console.error(e);
} finally {
setLoading(false);
}
};
const handleRecount = async (productId, productName) => {
// In a full system, this would call /api/tasks to assign a recount task
alert(`تسک بازشماری برای کالا "${productName}" (کد: ${productId}) صادر شد.`);
};
// We either show discrepancies or uncounted based on filter
const isUncountedMode = filter === 'uncounted';
let listToRender = isUncountedMode ? data.uncounted : data.discrepancies;
const filteredItems = listToRender.filter(item => {
const name = item.product_name || item.Name || '';
const id = (item.product_id || item.Code || '').toString();
const matchesSearch = name.includes(search) || id.includes(search);
if (isUncountedMode) return matchesSearch;
const matchesFilter =
filter === 'all' ? true :
filter === 'surplus' ? item.difference > 0 :
filter === 'deficit' ? item.difference < 0 : true;
return matchesSearch && matchesFilter;
});
return (
<div className="w-full min-h-screen bg-gray-50 flex flex-col pb-24 overflow-x-hidden">
<Header title="داشبورد مغایرت‌گیری" showBack={true} />
<div className="flex-1 p-4 md:p-6 max-w-4xl mx-auto w-full flex flex-col gap-6 mt-2">
{/* Controls */}
<div className="bg-white rounded-[24px] p-4 flex flex-col sm:flex-row items-center justify-between gap-4 shadow-sm border border-gray-100 relative z-20">
<div className="flex items-center gap-3 w-full sm:w-auto">
<div className="w-10 h-10 bg-indigo-50 text-indigo-600 rounded-xl flex items-center justify-center shrink-0">
<ListTree size={20} />
</div>
<div>
<h2 className="text-sm font-bold text-gray-800">انتخاب انبار</h2>
<p className="text-[10px] text-gray-400 font-medium">مبنای مقایسه موجودی حسابفا</p>
</div>
</div>
<div className="flex items-center gap-3 w-full sm:w-auto">
<select
value={warehouse}
onChange={(e) => setWarehouse(e.target.value)}
className="bg-gray-50 border border-gray-200 rounded-xl px-4 py-2.5 text-sm font-bold focus:outline-none focus:border-indigo-500 flex-1 sm:w-48 transition-colors"
>
{warehouses.map(wh => (
<option key={wh.id} value={wh.id}>{wh.name} (کد {wh.id})</option>
))}
</select>
<motion.button
whileTap={{ scale: 0.9 }}
onClick={fetchData}
className="bg-gray-900 text-white p-3 rounded-xl hover:bg-gray-800 transition-colors shrink-0"
>
<RefreshCw size={18} className={loading ? 'animate-spin' : ''} />
</motion.button>
</div>
</div>
{/* Stats */}
<div className="grid grid-cols-3 gap-4 relative z-10">
<div className="bg-white border border-red-100 rounded-[24px] p-5 shadow-sm flex flex-col gap-1 relative overflow-hidden">
<div className="absolute top-0 right-0 w-24 h-24 bg-red-50 rounded-bl-full flex items-start justify-end p-4 opacity-50 z-0">
<AlertTriangle className="text-red-300" size={32} />
</div>
<div className="relative z-10">
<p className="text-[10px] font-black text-gray-400 uppercase tracking-wider mb-1">مغایرتدار</p>
<p className="text-2xl font-black text-red-600">{loading ? '-' : data.discrepancies.length}</p>
</div>
</div>
<div className="bg-white border border-orange-100 rounded-[24px] p-5 shadow-sm flex flex-col gap-1 relative overflow-hidden">
<div className="absolute top-0 right-0 w-24 h-24 bg-orange-50 rounded-bl-full flex items-start justify-end p-4 opacity-50 z-0">
<PackageSearch className="text-orange-300" size={32} />
</div>
<div className="relative z-10">
<p className="text-[10px] font-black text-gray-400 uppercase tracking-wider mb-1">شمارشنشده</p>
<p className="text-2xl font-black text-orange-500">{loading ? '-' : data.uncounted.length}</p>
</div>
</div>
<div className="bg-white border border-green-100 rounded-[24px] p-5 shadow-sm flex flex-col gap-1 relative overflow-hidden">
<div className="absolute top-0 right-0 w-24 h-24 bg-green-50 rounded-bl-full flex items-start justify-end p-4 opacity-50 z-0">
<CheckCircle className="text-green-300" size={32} />
</div>
<div className="relative z-10">
<p className="text-[10px] font-black text-gray-400 uppercase tracking-wider mb-1">صحیح</p>
<p className="text-2xl font-black text-green-600">{loading ? '-' : data.accurate.length}</p>
</div>
</div>
</div>
{/* Filters and Search */}
<div className="bg-white rounded-[24px] p-4 shadow-sm border border-gray-100 flex flex-col md:flex-row gap-3">
<div className="relative flex-1">
<Search className="absolute right-3.5 top-1/2 -translate-y-1/2 text-gray-400" size={18} />
<input
type="text"
value={search}
onChange={e => setSearch(e.target.value)}
placeholder="جستجوی کالا..."
className="w-full bg-gray-50 border border-gray-200 rounded-[16px] pr-11 pl-4 py-3 text-sm font-bold focus:outline-none focus:border-indigo-500 transition-all placeholder:font-normal"
/>
</div>
<div className="flex items-center gap-2 overflow-x-auto pb-1 md:pb-0 scrollbar-hide">
{['all', 'surplus', 'deficit', 'uncounted'].map(f => (
<button
key={f}
onClick={() => setFilter(f)}
className={`px-4 py-2.5 rounded-[16px] text-xs font-bold whitespace-nowrap transition-all border ${
filter === f
? 'bg-gray-900 text-white border-gray-900 shadow-md'
: 'bg-white text-gray-500 border-gray-200 hover:bg-gray-50'
}`}
>
{f === 'all' ? 'همه مغایرت‌ها' : f === 'surplus' ? 'مازاد' : f === 'deficit' ? 'کسری' : 'شمارش‌نشده'}
</button>
))}
</div>
</div>
{/* Discrepancies / Uncounted List */}
<div className="flex flex-col gap-4 mt-2">
<div className="flex items-center gap-2 px-2">
<PackageSearch className={isUncountedMode ? "text-orange-500" : "text-red-500"} size={20} strokeWidth={2.5} />
<h3 className="font-black text-gray-800 text-sm">
{isUncountedMode ? 'لیست کالاهای شمارش‌نشده' : 'لیست کالا‌های نیازمند بررسی'}
</h3>
<span className="bg-gray-200 text-gray-600 text-[10px] px-2 py-0.5 rounded-full font-bold mr-auto">
{filteredItems.length} مورد
</span>
</div>
<div className="flex flex-col gap-3">
<AnimatePresence>
{filteredItems.map((item, idx) => {
const isUncounted = isUncountedMode;
const pName = isUncounted ? item.Name : item.product_name;
const pId = isUncounted ? item.Code : item.product_id;
return (
<motion.div
initial={{ opacity: 0, y: 10 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, scale: 0.95 }}
key={`${pId}-${idx}`}
className="bg-white rounded-[20px] shadow-sm border border-gray-100 p-5 flex flex-col gap-4"
>
{/* Top: Product Info & Badge */}
<div className="flex justify-between items-start">
<div className="flex flex-col pr-1">
<h4 className="font-bold text-gray-800 text-sm leading-snug">{pName}</h4>
<p className="text-[10px] text-gray-400 mt-1 font-medium tracking-wider">کد حسابفا: {pId}</p>
</div>
{!isUncounted && (
<div className={`flex items-center gap-1 px-3 py-1.5 rounded-[10px] text-xs font-black shadow-sm shrink-0 mr-3 ${item.difference > 0 ? 'bg-blue-50 text-blue-600 border border-blue-100' : 'bg-red-50 text-red-600 border border-red-100'}`}>
{item.difference > 0 ? <ArrowUpRight size={14} strokeWidth={3} /> : <ArrowDownRight size={14} strokeWidth={3} />}
{Math.abs(item.difference)}
</div>
)}
{isUncounted && (
<div className="flex items-center gap-1 px-3 py-1.5 rounded-[10px] text-xs font-black shadow-sm shrink-0 mr-3 bg-orange-50 text-orange-600 border border-orange-100">
موجودی: {item.Stock}
</div>
)}
</div>
{/* Middle: Stats */}
{!isUncounted && (
<div className="flex items-center bg-gray-50 rounded-[16px] p-3 border border-gray-100">
<div className="flex-1 flex flex-col items-center border-l border-gray-200">
<span className="text-[10px] font-bold text-gray-400 mb-0.5">موجودی سیستم</span>
<span className="text-lg font-black text-gray-600">{item.system_expected}</span>
</div>
<div className="flex-1 flex flex-col items-center border-l border-gray-200">
<span className="text-[10px] font-bold text-gray-400 mb-0.5">شمارش شما</span>
<span className="text-lg font-black text-gray-900">{item.total_counted}</span>
</div>
<div className="flex-1 flex flex-col items-center">
<span className="text-[10px] font-bold text-gray-400 mb-0.5">قفسهها</span>
<span className="text-xs font-bold text-indigo-600 mt-1.5 line-clamp-1 text-center px-1">
{item.locations?.length > 0 ? item.locations.join('، ') : '-'}
</span>
</div>
</div>
)}
{/* Bottom: Actions */}
<div className="flex items-center justify-end gap-2 pt-2 border-t border-gray-50 mt-1">
<button
onClick={() => handleRecount(pId, pName)}
className="bg-orange-50 text-orange-600 hover:bg-orange-500 hover:text-white px-4 py-2.5 rounded-[14px] text-xs font-bold transition-colors flex-1 text-center"
>
ارجاع بازشماری
</button>
{!isUncounted && (
<button className="bg-gray-900 text-white hover:bg-gray-800 px-4 py-2.5 rounded-[14px] text-xs font-bold transition-colors flex items-center justify-center gap-1.5 flex-1 shadow-md">
<Send size={14} />
ارسال تعدیل
</button>
)}
</div>
</motion.div>
);
})}
</AnimatePresence>
{filteredItems.length === 0 && !loading && (
<div className="bg-white rounded-[24px] border border-dashed border-gray-300 flex flex-col items-center justify-center p-10 text-center gap-3">
<div className="w-16 h-16 bg-green-50 text-green-500 rounded-full flex items-center justify-center">
<CheckCircle size={32} />
</div>
<p className="text-sm font-bold text-gray-500">موردی یافت نشد!</p>
<p className="text-xs text-gray-400">یا مغایرتی وجود ندارد یا جستجوی شما نتیجهای نداشت.</p>
</div>
)}
{loading && (
<div className="bg-white rounded-[24px] border border-gray-100 flex flex-col items-center justify-center p-10 text-center gap-3">
<div className="w-10 h-10 border-4 border-indigo-500 border-t-transparent rounded-full animate-spin"></div>
<p className="text-sm font-bold text-gray-500">در حال بررسی و استخراج اطلاعات...</p>
</div>
)}
</div>
</div>
</div>
</div>
);
}
+302 -78
View File
@@ -2,21 +2,55 @@
import { useState, useEffect } from 'react';
import Header from '@/components/Header';
import dynamic from 'next/dynamic';
import { motion, AnimatePresence } from 'framer-motion';
import { ScanLine, Plus, Trash2, Edit2, Layers, MapPin, X, AlertCircle, XCircle, Box } from 'lucide-react';
const Scanner = dynamic(() => import('@yudiel/react-qr-scanner').then(mod => mod.Scanner), { ssr: false });
export default function AdminLocations() {
const [locations, setLocations] = useState([]);
const [newCode, setNewCode] = useState('');
const [loading, setLoading] = useState(false);
const [cameraEnabled, setCameraEnabled] = useState(false);
const [warehouses, setWarehouses] = useState([]);
const [selectedWarehouse, setSelectedWarehouse] = useState('');
// Separate states for location parts
const [floor, setFloor] = useState('');
const [region, setRegion] = useState('');
const [sector, setSector] = useState('');
const [row, setRow] = useState('');
const [loading, setLoading] = useState(false);
const [cameraEnabled, setCameraEnabled] = useState(true);
const [camError, setCamError] = useState('');
const [activeFilter, setActiveFilter] = useState('all');
const [editingId, setEditingId] = useState(null);
const [toast, setToast] = useState({ show: false, message: '', isError: false });
const showToast = (message, isError = false) => {
setToast({ show: true, message, isError });
setTimeout(() => setToast({ show: false, message: '', isError: false }), 3000);
};
useEffect(() => {
fetchLocations();
fetchSettings();
}, []);
const fetchSettings = async () => {
try {
const res = await fetch('/api/settings');
if (res.ok) {
const data = await res.json();
setWarehouses(data.warehouses || []);
if (data.warehouses?.length > 0) {
setSelectedWarehouse(data.warehouses[0].id);
}
}
} catch (e) {
console.error(e);
}
};
const fetchLocations = async () => {
try {
const res = await fetch('/api/locations');
@@ -28,125 +62,243 @@ export default function AdminLocations() {
}
};
const handleAddLocation = async (codeValue) => {
const targetCode = codeValue || newCode;
if (!targetCode) return;
// Smart Parser for the main code input
const handleFullCodeChange = (e) => {
const val = e.target.value.toUpperCase();
// Attempt to parse regex: [Letter][Number][Letter][Number] e.g. C2F3
const regex = /^([A-Za-z]+)(\d+)([A-Za-z]+)(\d+)$/;
const match = val.match(regex);
if (match) {
setFloor(match[1]);
setRegion(match[2]);
setSector(match[3]);
setRow(match[4]);
} else {
// If it doesn't match perfectly, just use it as floor or something, but best to let users type in separate fields
// We will just leave it empty or partially fill. Actually, it's better to clear them or let them type.
}
};
const handleAddOrEdit = async () => {
if (!floor || !region || !sector || !row) {
showToast('لطفا همه مقادیر طبقه، منطقه، قطاع و ردیف را وارد کنید', true);
return;
}
if (!selectedWarehouse) {
showToast('لطفاً ابتدا انبار را انتخاب کنید', true);
return;
}
const generatedCode = `${floor.toUpperCase()}${region}${sector.toUpperCase()}${row}`;
setLoading(true);
try {
const res = await fetch('/api/locations', {
method: 'POST',
const method = editingId ? 'PUT' : 'POST';
const url = editingId ? `/api/locations/${editingId}` : '/api/locations';
const res = await fetch(url, {
method,
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ code: targetCode })
body: JSON.stringify({ code: generatedCode, warehouse: selectedWarehouse })
});
const data = await res.json();
if (res.ok) {
alert('قفسه با موفقیت ثبت شد!');
setNewCode('');
showToast(editingId ? 'قفسه با موفقیت ویرایش شد' : 'قفسه با موفقیت ثبت شد!');
setFloor(''); setRegion(''); setSector(''); setRow('');
setEditingId(null);
fetchLocations();
} else {
alert(data.error || 'خطا در ثبت قفسه');
showToast(data.error || 'خطا در ثبت قفسه', true);
}
} catch (e) {
alert('خطای شبکه');
showToast('خطای شبکه', true);
} finally {
setLoading(false);
setCameraEnabled(false);
}
};
const handleDelete = async (id) => {
if (!confirm('آیا از حذف این قفسه اطمینان دارید؟')) return;
try {
const res = await fetch(`/api/locations/${id}`, { method: 'DELETE' });
const data = await res.json();
if (res.ok) {
showToast('قفسه حذف شد');
fetchLocations();
} else {
showToast(data.error || 'خطا در حذف', true);
}
} catch (e) {
showToast('خطای شبکه', true);
}
};
const handleScan = (detectedCodes) => {
if (detectedCodes && detectedCodes.length > 0) {
const scannedValue = detectedCodes[0].rawValue;
handleAddLocation(scannedValue);
const scannedValue = detectedCodes[0].rawValue.toUpperCase();
const regex = /^([A-Za-z]+)(\d+)([A-Za-z]+)(\d+)$/;
const match = scannedValue.match(regex);
if (match) {
setFloor(match[1]);
setRegion(match[2]);
setSector(match[3]);
setRow(match[4]);
showToast(`کد ${scannedValue} شناسایی و پر شد`);
// Optional: auto-submit here if desired
// setTimeout(handleAddOrEdit, 500);
} else {
showToast(`کد اسکن شده نامعتبر است: ${scannedValue}`, true);
}
}
};
const handleError = (error) => {
console.error(error);
const msg = error?.message || error?.name || '';
if (msg.includes('Requested device not found') || msg.includes('NotFoundError') || msg.includes('device not found')) {
setCamError('هیچ دوربینی روی این دستگاه یافت نشد. لطفاً از لپ‌تاپ یا موبایل استفاده کنید.');
if (msg.includes('Requested device not found')) {
setCamError('دوربینی یافت نشد.');
} else {
setCamError(msg || 'خطا در دسترسی به دوربین. آیا از HTTPS یا localhost استفاده میکنید؟');
setCamError(msg || 'خطا در دسترسی به دوربین.');
}
};
// استخراج طبقات یکتا برای ساخت دکمه‌های فیلتر
const floors = [...new Set(locations.map(loc => loc.floor))].sort();
let filteredLocations = locations;
if (selectedWarehouse) {
filteredLocations = filteredLocations.filter(loc => loc.warehouse == selectedWarehouse);
}
if (activeFilter !== 'all') {
filteredLocations = filteredLocations.filter(loc => loc.floor === activeFilter);
}
// اعمال فیلتر روی لیست قفسه‌ها
const filteredLocations = activeFilter === 'all'
? locations
: locations.filter(loc => loc.floor === activeFilter);
const generatedCodePreview = (floor || region || sector || row) ? `${floor.toUpperCase()}${region}${sector.toUpperCase()}${row}` : '';
return (
<div className="w-full min-h-screen bg-gray-50 flex flex-col pb-20">
<Header title="مدیریت قفسه ها (ادمین)" showBack={true} />
<div className="w-full min-h-screen bg-gray-50 flex flex-col pb-24 relative">
<Header title="مدیریت قفسهها" showBack={true} />
<div className="p-4 flex flex-col gap-6 items-center">
<div className="flex-1 p-5 flex flex-col gap-6 max-w-md mx-auto w-full mt-2">
<div className="w-full bg-white p-4 rounded shadow border border-gray-200">
<h2 className="font-bold mb-2">ثبت قفسه جدید</h2>
<p className="text-xs text-gray-500 mb-4">
فرمت استاندارد شامل حروف و اعداد است.
مثال: C2F2 (طبقه C، منطقه 2، قطاع F، ردیف 2)
</p>
<div className="flex flex-col gap-3">
{/* Action Box */}
<div className="w-full bg-white rounded-[24px] p-5 shadow-sm border border-gray-100 flex flex-col gap-4">
<div className="flex justify-between items-center mb-1">
<span className="text-sm font-bold text-gray-700">{editingId ? 'ویرایش قفسه' : 'ثبت قفسه جدید'}</span>
{editingId && (
<button onClick={() => { setEditingId(null); setFloor(''); setRegion(''); setSector(''); setRow(''); }} className="text-xs text-red-500 font-bold bg-red-50 px-2 py-1 rounded-lg">
لغو ویرایش
</button>
)}
</div>
<select
value={selectedWarehouse}
onChange={(e) => setSelectedWarehouse(e.target.value)}
className="w-full bg-gray-50 border border-gray-200 rounded-[16px] px-4 py-3 text-sm font-bold text-gray-800 focus:outline-none focus:border-indigo-500 transition-colors"
>
<option value="" disabled>انبار را انتخاب کنید...</option>
{warehouses.map(wh => (
<option key={wh.id} value={wh.id}>{wh.name} (کد: {wh.id})</option>
))}
</select>
{/* Smart Code Input */}
<div>
<label className="text-[10px] font-bold text-gray-400 mr-2 mb-1 block">اسکن یا تایپ کد قفسه (مثال: C2F3)</label>
<input
type="text"
dir="ltr"
value={newCode}
onChange={(e) => setNewCode(e.target.value)}
placeholder="مثال: C2F2"
className="w-full border p-2 rounded text-center uppercase font-bold"
onChange={handleFullCodeChange}
placeholder="C2F3"
className="w-full bg-indigo-50/50 border border-indigo-100 rounded-[16px] px-4 py-3 text-center uppercase font-black text-indigo-700 tracking-widest focus:outline-none focus:border-indigo-400 focus:bg-indigo-50 transition-colors placeholder-indigo-200"
/>
<button
onClick={() => handleAddLocation(newCode)}
disabled={loading}
className="bg-purple-600 text-white font-bold py-2 rounded"
>
ثبت دستی
</button>
</div>
<div className="mt-4 border-t pt-4">
{cameraEnabled ? (
<div className="w-full aspect-video relative flex flex-col items-center justify-center bg-gray-100 rounded">
{camError ? (
<div className="text-red-500 text-xs p-4 text-center">{camError}</div>
) : (
<Scanner onScan={handleScan} onError={handleError} />
)}
<button
onClick={() => { setCameraEnabled(false); setCamError(''); }}
className="absolute bottom-2 right-2 bg-red-500 text-white text-xs px-2 py-1 rounded z-10"
<div className="grid grid-cols-4 gap-2">
<div className="flex flex-col gap-1">
<label className="text-[10px] text-gray-400 font-bold text-center">طبقه</label>
<input type="text" dir="ltr" value={floor} onChange={e => setFloor(e.target.value)} placeholder="C" className="w-full bg-gray-50 border border-gray-200 rounded-xl px-2 py-2 text-center uppercase font-bold text-gray-800 focus:outline-none focus:border-indigo-500" />
</div>
<div className="flex flex-col gap-1">
<label className="text-[10px] text-gray-400 font-bold text-center">منطقه</label>
<input type="number" dir="ltr" value={region} onChange={e => setRegion(e.target.value)} placeholder="2" className="w-full bg-gray-50 border border-gray-200 rounded-xl px-2 py-2 text-center font-bold text-gray-800 focus:outline-none focus:border-indigo-500" />
</div>
<div className="flex flex-col gap-1">
<label className="text-[10px] text-gray-400 font-bold text-center">قطاع</label>
<input type="text" dir="ltr" value={sector} onChange={e => setSector(e.target.value)} placeholder="F" className="w-full bg-gray-50 border border-gray-200 rounded-xl px-2 py-2 text-center uppercase font-bold text-gray-800 focus:outline-none focus:border-indigo-500" />
</div>
<div className="flex flex-col gap-1">
<label className="text-[10px] text-gray-400 font-bold text-center">ردیف</label>
<input type="number" dir="ltr" value={row} onChange={e => setRow(e.target.value)} placeholder="3" className="w-full bg-gray-50 border border-gray-200 rounded-xl px-2 py-2 text-center font-bold text-gray-800 focus:outline-none focus:border-indigo-500" />
</div>
</div>
<motion.button
whileTap={{ scale: 0.98 }}
onClick={handleAddOrEdit}
disabled={loading || !generatedCodePreview}
className="w-full bg-gray-900 text-white py-3.5 rounded-[16px] text-sm font-black flex items-center justify-center gap-2 transition-opacity disabled:opacity-50 mt-1"
>
{loading ? <div className="w-5 h-5 border-2 border-white/30 border-t-white rounded-full animate-spin"></div> : (editingId ? <Edit2 size={18}/> : <Plus size={20}/>)}
{editingId ? `ویرایش ${generatedCodePreview}` : `ثبت قفسه ${generatedCodePreview}`}
</motion.button>
<div className="relative overflow-hidden rounded-[16px]">
<AnimatePresence>
{cameraEnabled && (
<motion.div
initial={{ height: 0, opacity: 0 }}
animate={{ height: 'auto', opacity: 1 }}
exit={{ height: 0, opacity: 0 }}
className="w-full aspect-video relative flex flex-col items-center justify-center bg-black overflow-hidden"
>
بستن دوربین
</button>
</div>
) : (
<button
{camError ? (
<div className="text-red-400 text-xs p-4 text-center font-medium">{camError}</div>
) : (
<div className="w-full h-full [&>div]:!object-cover [&>div>video]:!object-cover">
<Scanner onScan={handleScan} onError={handleError} />
</div>
)}
<button
onClick={() => { setCameraEnabled(false); setCamError(''); }}
className="absolute top-2 right-2 bg-white/20 backdrop-blur-md p-1.5 rounded-full text-white pointer-events-auto"
>
<X size={16} strokeWidth={3} />
</button>
</motion.div>
)}
</AnimatePresence>
{!cameraEnabled && !editingId && (
<motion.button
whileTap={{ scale: 0.98 }}
onClick={() => setCameraEnabled(true)}
className="w-full bg-blue-500 text-white font-bold py-2 rounded flex justify-center items-center gap-2"
className="w-full py-3.5 bg-indigo-50 text-indigo-600 text-sm font-extrabold rounded-[16px] transition-colors flex items-center justify-center gap-2 mt-2"
>
<ScanLine size={18} strokeWidth={2.5} />
اسکن بارکد قفسه
</button>
</motion.button>
)}
</div>
</div>
<div className="w-full bg-white p-4 rounded shadow border border-gray-200">
<h2 className="font-bold mb-4">قفسه های ثبت شده ({filteredLocations.length})</h2>
{/* List Section */}
<div className="flex flex-col gap-4 mt-2">
{/* فیلترهای تگ (اسکرول افقی) */}
<div className="flex items-center justify-between">
<h3 className="font-bold text-gray-800 text-sm">لیست قفسهها <span className="text-gray-400 font-medium text-xs">({filteredLocations.length})</span></h3>
</div>
{/* Tag Filters */}
{floors.length > 0 && (
<div className="flex gap-2 overflow-x-auto pb-2 mb-3 scrollbar-hide" style={{ scrollbarWidth: 'none', msOverflowStyle: 'none' }}>
<div className="flex gap-2 overflow-x-auto pb-1 scrollbar-hide" style={{ scrollbarWidth: 'none', msOverflowStyle: 'none' }}>
<button
onClick={() => setActiveFilter('all')}
className={`px-4 py-1.5 rounded-full text-xs font-bold whitespace-nowrap transition-colors border ${activeFilter === 'all' ? 'bg-purple-600 text-white border-purple-600' : 'bg-gray-50 text-gray-600 border-gray-200'}`}
className={`px-4 py-2 rounded-[12px] text-xs font-bold whitespace-nowrap transition-all border ${activeFilter === 'all' ? 'bg-gray-900 text-white border-gray-900' : 'bg-white text-gray-500 border-gray-200 hover:bg-gray-50'}`}
>
همه طبقات
</button>
@@ -154,7 +306,7 @@ export default function AdminLocations() {
<button
key={floor}
onClick={() => setActiveFilter(floor)}
className={`px-4 py-1.5 rounded-full text-xs font-bold whitespace-nowrap transition-colors border ${activeFilter === floor ? 'bg-purple-600 text-white border-purple-600' : 'bg-gray-50 text-gray-600 border-gray-200'}`}
className={`px-4 py-2 rounded-[12px] text-xs font-bold whitespace-nowrap transition-all border ${activeFilter === floor ? 'bg-gray-900 text-white border-gray-900' : 'bg-white text-gray-500 border-gray-200 hover:bg-gray-50'}`}
>
طبقه {floor}
</button>
@@ -162,18 +314,90 @@ export default function AdminLocations() {
</div>
)}
<div className="flex flex-col gap-2 max-h-[300px] overflow-y-auto pr-1">
{filteredLocations.map((loc) => (
<div key={loc.id} className="flex justify-between items-center bg-gray-50 p-2 rounded border border-gray-100 text-sm">
<span className="font-bold text-lg text-purple-700">{loc.code}</span>
<span className="text-gray-500 text-xs">طبقه {loc.floor} | منطقه {loc.region} | قطاع {loc.sector} | ردیف {loc.row}</span>
{/* Cards */}
<div className="flex flex-col gap-3">
{filteredLocations.map((loc) => {
const hasData = loc._count?.countings > 0;
return (
<motion.div
initial={{ opacity: 0, y: 10 }}
animate={{ opacity: 1, y: 0 }}
key={loc.id}
className="bg-white p-4 rounded-[20px] border border-gray-100 shadow-sm flex items-center justify-between"
>
<div className="flex items-center gap-4">
<div className="w-12 h-12 bg-gray-50 rounded-[14px] flex items-center justify-center shrink-0">
<Layers className="text-gray-400" size={20} strokeWidth={2} />
</div>
<div className="flex flex-col">
<span className="font-black text-lg text-gray-800 tracking-wide uppercase">{loc.code}</span>
<span className="text-[10px] text-gray-400 font-bold mt-0.5">
{loc.warehouse ? `انبار: ${loc.warehouse}` : ''}طبقه {loc.floor} منطقه {loc.region} قطاع {loc.sector} ردیف {loc.row}
</span>
</div>
</div>
<div className="flex items-center gap-1">
{!hasData ? (
<>
<button
onClick={() => {
setEditingId(loc.id);
setFloor(loc.floor);
setRegion(loc.region);
setSector(loc.sector);
setRow(loc.row);
window.scrollTo({ top: 0, behavior: 'smooth' });
}}
className="w-8 h-8 flex items-center justify-center rounded-xl text-gray-400 hover:text-indigo-500 hover:bg-indigo-50 transition-colors"
>
<Edit2 size={16} strokeWidth={2.5} />
</button>
<button
onClick={() => handleDelete(loc.id)}
className="w-8 h-8 flex items-center justify-center rounded-xl text-gray-400 hover:text-red-500 hover:bg-red-50 transition-colors"
>
<Trash2 size={16} strokeWidth={2.5} />
</button>
</>
) : (
<div className="px-3 py-1 bg-gray-50 rounded-full flex items-center gap-1.5 border border-gray-100">
<Box size={12} className="text-gray-400" />
<span className="text-[10px] font-bold text-gray-500">{loc._count.countings} کالا</span>
</div>
)}
</div>
</motion.div>
);
})}
{filteredLocations.length === 0 && (
<div className="flex flex-col items-center justify-center py-12 px-4 text-center">
<div className="w-16 h-16 bg-gray-50 rounded-full flex items-center justify-center mb-3">
<MapPin className="text-gray-300" size={24} />
</div>
<span className="text-sm font-bold text-gray-500">هیچ قفسهای یافت نشد</span>
<span className="text-xs text-gray-400 mt-1">با فرم بالا یک قفسه جدید ثبت کنید</span>
</div>
))}
{filteredLocations.length === 0 && <span className="text-center text-sm text-gray-400 py-4">موردی یافت نشد.</span>}
)}
</div>
</div>
</div>
{/* Minimal Toast Notification */}
<AnimatePresence>
{toast.show && (
<motion.div
initial={{ opacity: 0, y: 50, scale: 0.9 }}
animate={{ opacity: 1, y: 0, scale: 1 }}
exit={{ opacity: 0, y: 20, scale: 0.9 }}
className={`fixed bottom-8 left-1/2 -translate-x-1/2 z-[100] px-5 py-3 rounded-2xl shadow-xl backdrop-blur-3xl border text-xs font-bold whitespace-nowrap flex items-center justify-center gap-2 ${toast.isError ? 'bg-red-50/90 border-red-100 text-red-600' : 'bg-white/90 border-gray-100 text-gray-800'}`}
>
{toast.isError ? <XCircle size={14} /> : <AlertCircle size={14} />}
{toast.message}
</motion.div>
)}
</AnimatePresence>
</div>
);
}
+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>
);
}
+118
View File
@@ -0,0 +1,118 @@
'use client';
import Header from '@/components/Header';
import Link from 'next/link';
import { motion } from 'framer-motion';
import { Layers, Users, BarChart3 } from 'lucide-react';
export default function AdminDashboard() {
const container = {
hidden: { opacity: 0 },
show: {
opacity: 1,
transition: { staggerChildren: 0.1 }
}
};
const item = {
hidden: { opacity: 0, y: 20 },
show: { opacity: 1, y: 0, transition: { type: 'spring', stiffness: 300, damping: 24 } }
};
return (
<div className="w-full min-h-screen bg-gray-50 flex flex-col pb-20">
<Header title="پنل مدیریت" showBack={true} />
<motion.div
variants={container}
initial="hidden"
animate="show"
className="p-5 flex flex-col gap-4"
>
<div className="grid grid-cols-2 gap-4">
<motion.div variants={item}>
<Link href="/admin/discrepancies" className="bg-white/80 backdrop-blur-sm border border-gray-100 rounded-3xl shadow-[0_4px_20px_rgb(0,0,0,0.03)] p-6 flex flex-col items-center justify-center aspect-square gap-3 hover:bg-white hover:scale-[1.02] active:scale-95 transition-all">
<div className="w-12 h-12 bg-red-50 text-red-500 rounded-2xl flex items-center justify-center mb-1">
<BarChart3 strokeWidth={1.5} size={24} />
</div>
<span className="font-extrabold text-xs text-center text-gray-700">داشبورد مغایرتها</span>
</Link>
</motion.div>
<motion.div variants={item}>
<Link href="/admin/settings" className="bg-white/80 backdrop-blur-sm border border-gray-100 rounded-3xl shadow-[0_4px_20px_rgb(0,0,0,0.03)] p-6 flex flex-col items-center justify-center aspect-square gap-3 hover:bg-white hover:scale-[1.02] active:scale-95 transition-all">
<div className="w-12 h-12 bg-indigo-50 text-indigo-500 rounded-2xl flex items-center justify-center mb-1">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><path d="M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z"/><circle cx="12" cy="12" r="3"/></svg>
</div>
<span className="font-extrabold text-xs text-center text-gray-700">تنظیمات مدیریت</span>
</Link>
</motion.div>
<motion.div variants={item}>
<Link href="/admin/locations" className="bg-white/80 backdrop-blur-sm border border-gray-100 rounded-3xl shadow-[0_4px_20px_rgb(0,0,0,0.03)] p-6 flex flex-col items-center justify-center aspect-square gap-3 hover:bg-white hover:scale-[1.02] active:scale-95 transition-all">
<div className="w-12 h-12 bg-purple-50 text-purple-600 rounded-2xl flex items-center justify-center mb-1">
<Layers strokeWidth={1.5} size={24} />
</div>
<span className="font-extrabold text-xs text-center text-gray-700">مدیریت قفسهها</span>
</Link>
</motion.div>
<motion.div variants={item}>
<Link href="/admin/stats" className="bg-white/80 backdrop-blur-sm border border-gray-100 rounded-3xl shadow-[0_4px_20px_rgb(0,0,0,0.03)] p-6 flex flex-col items-center justify-center aspect-square gap-3 hover:bg-white hover:scale-[1.02] active:scale-95 transition-all">
<div className="w-12 h-12 bg-blue-50 text-blue-500 rounded-2xl flex items-center justify-center mb-1">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><path d="M3 3v18h18"/><path d="m19 9-5 5-4-4-3 3"/></svg>
</div>
<span className="font-extrabold text-xs text-center text-gray-700">آمار طبقات</span>
</Link>
</motion.div>
<motion.div variants={item}>
<Link href="/admin/warehouses" className="bg-white/80 backdrop-blur-sm border border-gray-100 rounded-3xl shadow-[0_4px_20px_rgb(0,0,0,0.03)] p-6 flex flex-col items-center justify-center aspect-square gap-3 hover:bg-white hover:scale-[1.02] active:scale-95 transition-all">
<div className="w-12 h-12 bg-orange-50 text-orange-500 rounded-2xl flex items-center justify-center mb-1">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><rect x="2" y="2" width="20" height="8" rx="2" ry="2"/><rect x="2" y="14" width="20" height="8" rx="2" ry="2"/><line x1="6" y1="6" x2="6.01" y2="6"/><line x1="6" y1="18" x2="6.01" y2="18"/></svg>
</div>
<span className="font-extrabold text-xs text-center text-gray-700">مدیریت انبارها</span>
</Link>
</motion.div>
<motion.div variants={item}>
<Link href="/admin/products" className="bg-white/80 backdrop-blur-sm border border-gray-100 rounded-3xl shadow-[0_4px_20px_rgb(0,0,0,0.03)] p-6 flex flex-col items-center justify-center aspect-square gap-3 hover:bg-white hover:scale-[1.02] active:scale-95 transition-all">
<div className="w-12 h-12 bg-teal-50 text-teal-500 rounded-2xl flex items-center justify-center mb-1">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"/><polyline points="3.27 6.96 12 12.01 20.73 6.96"/><line x1="12" y1="22.08" x2="12" y2="12"/></svg>
</div>
<span className="font-extrabold text-xs text-center text-gray-700">لیست کالاها</span>
</Link>
</motion.div>
</div>
<motion.div variants={item}>
<Link href="/admin/users" 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-indigo-50 text-indigo-500 rounded-xl flex items-center justify-center">
<Users strokeWidth={1.5} size={20} />
</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 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>
</div>
);
}
+181
View File
@@ -0,0 +1,181 @@
'use client';
import { useState, useEffect } from 'react';
import Header from '@/components/Header';
import { PackageSearch, Search, AlertCircle, Box, Layers, Filter } from 'lucide-react';
import { motion, AnimatePresence } from 'framer-motion';
export default function ProductsPage() {
const [products, setProducts] = useState([]);
const [loading, setLoading] = useState(true);
const [search, setSearch] = useState('');
const [filter, setFilter] = useState('all'); // 'all', 'in-stock', 'out-of-stock'
useEffect(() => {
fetchProducts();
}, []);
const fetchProducts = async () => {
try {
const res = await fetch('/api/hesabfa', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ type: 'all' })
});
if (res.ok) {
const data = await res.json();
// Safely extract the array of products from the Hesabfa response
const productList = data?.Result?.List || data?.List || (Array.isArray(data) ? data : []);
setProducts(productList);
} else {
setProducts([]);
}
} catch (e) {
console.error(e);
} finally {
setLoading(false);
}
};
const filteredProducts = products.filter(p => {
const matchesSearch = p.Name?.includes(search) || p.Code?.toString().includes(search);
const matchesFilter =
filter === 'all' ? true :
filter === 'in-stock' ? p.Stock > 0 :
p.Stock <= 0;
return matchesSearch && matchesFilter;
});
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 flex-col justify-center items-center gap-4">
<div className="w-10 h-10 border-4 border-indigo-500 border-t-transparent rounded-full animate-spin"></div>
<span className="text-sm font-bold text-gray-500">در حال دریافت کالاها از حسابفا...</span>
</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">
<PackageSearch className="text-indigo-600" size={24} strokeWidth={2.5} />
پایگاه داده کالاها
</h2>
<p className="text-xs text-gray-500 font-medium leading-relaxed">
مشاهده لحظهای موجودی و اطلاعات صدها کالا متصل به سیستم جامع حسابفا
</p>
</div>
{/* Filters and Search */}
<div className="bg-white rounded-[24px] p-5 shadow-sm border border-gray-100 flex flex-col md:flex-row gap-4">
<div className="relative flex-1">
<Search className="absolute right-4 top-1/2 -translate-y-1/2 text-gray-400" size={18} />
<input
type="text"
value={search}
onChange={e => setSearch(e.target.value)}
placeholder="جستجو بر اساس نام یا کد کالا..."
className="w-full bg-gray-50 border border-gray-200 rounded-[16px] pr-12 pl-4 py-3.5 text-sm font-bold focus:outline-none focus:border-indigo-500 focus:bg-white transition-all placeholder:font-normal"
/>
</div>
<div className="flex items-center gap-2 overflow-x-auto pb-1 md:pb-0 hide-scrollbar">
<div className="w-10 h-10 bg-gray-100 text-gray-400 rounded-[12px] flex items-center justify-center shrink-0">
<Filter size={16} />
</div>
{['all', 'in-stock', 'out-of-stock'].map(f => (
<button
key={f}
onClick={() => setFilter(f)}
className={`px-4 py-2.5 rounded-[12px] text-xs font-bold whitespace-nowrap transition-all border ${
filter === f
? 'bg-indigo-600 text-white border-indigo-600 shadow-md shadow-indigo-600/20'
: 'bg-white text-gray-500 border-gray-200 hover:bg-gray-50'
}`}
>
{f === 'all' ? 'همه کالاها' : f === 'in-stock' ? 'موجود' : 'ناموجود'}
</button>
))}
</div>
</div>
{/* Stats Summary */}
<div className="grid grid-cols-2 md:grid-cols-4 gap-3">
<div className="bg-white rounded-[16px] p-4 border border-gray-100 flex flex-col gap-1 shadow-sm">
<span className="text-[10px] text-gray-400 font-bold uppercase">تعداد کل یافت شده</span>
<span className="text-lg font-black text-gray-800">{filteredProducts.length}</span>
</div>
<div className="bg-white rounded-[16px] p-4 border border-green-100 flex flex-col gap-1 shadow-sm">
<span className="text-[10px] text-green-600 font-bold uppercase">کالاهای موجود</span>
<span className="text-lg font-black text-green-700">
{filteredProducts.filter(p => p.Stock > 0).length}
</span>
</div>
</div>
{/* Products List */}
<div className="flex flex-col gap-3">
<AnimatePresence>
{filteredProducts.map((p) => (
<motion.div
initial={{ opacity: 0, y: 10 }}
animate={{ opacity: 1, y: 0 }}
key={p.Code}
className="flex flex-col md:flex-row md:items-center justify-between p-4 md:p-5 rounded-[20px] border border-gray-200 bg-white shadow-sm gap-4"
>
<div className="flex items-start md:items-center gap-4">
<div className="w-14 h-14 bg-indigo-50 text-indigo-600 rounded-2xl flex items-center justify-center shrink-0">
<Box size={24} strokeWidth={1.5} />
</div>
<div className="flex flex-col gap-1">
<span className="font-bold text-gray-800 leading-tight">{p.Name}</span>
<div className="flex items-center gap-3">
<span className="text-xs text-gray-500 font-bold dir-ltr flex items-center gap-1">
<span className="text-gray-400 font-normal">کد:</span> {p.Code}
</span>
{p.Barcode && (
<span className="text-xs text-gray-500 font-bold dir-ltr flex items-center gap-1 border-r border-gray-200 pr-3">
<span className="text-gray-400 font-normal">بارکد:</span> {p.Barcode}
</span>
)}
</div>
</div>
</div>
<div className="flex items-center justify-between md:justify-end gap-6 bg-gray-50 md:bg-transparent p-3 md:p-0 rounded-[16px]">
<div className="flex flex-col items-center md:items-end">
<span className="text-[10px] font-bold text-gray-400 mb-0.5">موجودی سیستم</span>
<span className={`text-lg font-black ${p.Stock > 0 ? 'text-green-600' : 'text-red-500'}`}>
{p.Stock} <span className="text-xs font-bold text-gray-500">{p.Unit || 'عدد'}</span>
</span>
</div>
<div className="flex flex-col items-center md:items-end border-r border-gray-200 pr-6">
<span className="text-[10px] font-bold text-gray-400 mb-0.5">فی فروش</span>
<span className="text-sm font-black text-gray-700">
{p.SalesPrice?.toLocaleString()} <span className="text-[10px] text-gray-400">تومان</span>
</span>
</div>
</div>
</motion.div>
))}
</AnimatePresence>
{filteredProducts.length === 0 && (
<div className="text-center py-12 bg-white rounded-[24px] border border-dashed border-gray-300 flex flex-col items-center gap-3">
<AlertCircle className="text-gray-300" size={32} />
<p className="text-sm font-bold text-gray-500">هیچ کالایی با این مشخصات یافت نشد.</p>
</div>
)}
</div>
</div>
</div>
);
}
+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>
);
}
+274
View File
@@ -0,0 +1,274 @@
'use client';
import { useState, useEffect } from 'react';
import Header from '@/components/Header';
import { Save, EyeOff, ShieldCheck, Check, AlertCircle, XCircle } from 'lucide-react';
import { motion, AnimatePresence } from 'framer-motion';
export default function SettingsPage() {
const [settings, setSettings] = useState({
blind_counting: false,
correction_roles: ['ADMIN', 'SUPERVISOR'],
uncounted_shelf_days: 10
});
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
const [toast, setToast] = useState({ show: false, message: '', isError: false });
const availableRoles = [
{ id: 'ADMIN', label: 'مدیر کل' },
{ id: 'SUPERVISOR', label: 'سرپرست انبار' },
{ id: 'ACCOUNTANT', label: 'حسابدار' },
{ id: 'COUNTER', label: 'انبارگردان' }
];
const showToast = (message, isError = false) => {
setToast({ show: true, message, isError });
setTimeout(() => setToast({ show: false, message: '', isError: false }), 3000);
};
useEffect(() => {
fetchSettings();
}, []);
const fetchSettings = async () => {
try {
const res = await fetch('/api/settings');
if (res.ok) {
const data = await res.json();
setSettings(prev => ({ ...prev, ...data }));
}
} catch (error) {
console.error(error);
} finally {
setLoading(false);
}
};
const handleSave = async () => {
setSaving(true);
try {
const res = await fetch('/api/settings', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(settings)
});
if (res.ok) {
showToast('تنظیمات با موفقیت ذخیره شد');
} else {
showToast('خطا در ذخیره تنظیمات', true);
}
} catch (error) {
console.error(error);
showToast('خطای شبکه', true);
} finally {
setSaving(false);
}
};
const toggleRole = (roleId) => {
setSettings(prev => {
const roles = prev.correction_roles || [];
if (roles.includes(roleId)) {
return { ...prev, correction_roles: roles.filter(r => r !== roleId) };
} else {
return { ...prev, correction_roles: [...roles, roleId] };
}
});
};
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-5 flex flex-col gap-6 max-w-lg mx-auto w-full mt-2">
<div className="w-full bg-white rounded-[24px] p-6 shadow-sm border border-gray-100 flex flex-col gap-8">
{/* Blind Counting 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-purple-50 text-purple-600 flex items-center justify-center shrink-0">
<EyeOff size={16} strokeWidth={2.5} />
</div>
<h2 className="text-sm font-bold text-gray-800">شمارش کور (Blind Counting)</h2>
</div>
<p className="text-xs text-gray-500 leading-relaxed">
در صورت فعال بودن، انبارگردانها موجودی فعلی سیستم را نمیبینند و مجبورند به جای تایید کورکورانه، کالاها را به صورت واقعی بشمارند.
</p>
</div>
{/* Elegant Switch Button */}
<button
onClick={() => setSettings(s => ({ ...s, blind_counting: !s.blind_counting }))}
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.blind_counting ? 'bg-indigo-600' : 'bg-gray-200'}`}
role="switch"
aria-checked={settings.blind_counting}
>
<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.blind_counting ? '-translate-x-6' : 'translate-x-0'}`}
/>
</button>
</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>
{/* Enable Counting Modes */}
<div className="border-t border-gray-50 pt-8 flex flex-col gap-5">
<div className="flex items-center gap-2 mb-1">
<div className="w-8 h-8 rounded-[12px] bg-blue-50 text-blue-600 flex items-center justify-center shrink-0">
<Check size={16} strokeWidth={2.5} />
</div>
<h2 className="text-sm font-bold text-gray-800">حالتهای انبارگردانی</h2>
</div>
<div className="flex items-center justify-between gap-4">
<p className="text-xs text-gray-500 leading-relaxed font-bold">انبارگردانی قفسهای</p>
<button
onClick={() => setSettings(s => ({ ...s, enable_shelf_counting: s.enable_shelf_counting === undefined ? true : !s.enable_shelf_counting }))}
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 ${(settings.enable_shelf_counting ?? true) ? 'bg-blue-600' : 'bg-gray-200'}`}
>
<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.enable_shelf_counting ?? true) ? '-translate-x-6' : 'translate-x-0'}`} />
</button>
</div>
<div className="flex items-center justify-between gap-4">
<p className="text-xs text-gray-500 leading-relaxed font-bold">انبارگردانی کالایی</p>
<button
onClick={() => setSettings(s => ({ ...s, enable_item_counting: s.enable_item_counting === undefined ? true : !s.enable_item_counting }))}
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 ${(settings.enable_item_counting ?? true) ? 'bg-blue-600' : 'bg-gray-200'}`}
>
<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.enable_item_counting ?? true) ? '-translate-x-6' : 'translate-x-0'}`} />
</button>
</div>
</div>
{/* Correction Roles Setting */}
<div>
<div className="flex items-center gap-2 mb-2">
<div className="w-8 h-8 rounded-[12px] bg-blue-50 text-blue-600 flex items-center justify-center shrink-0">
<ShieldCheck 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 mb-5">
وقتی انبارگردانی یک قفسه بسته میشود، چه نقشهایی اجازه دارند درخواست اصلاحیه ثبت کنند؟
</p>
<div className="grid grid-cols-2 gap-3">
{availableRoles.map(role => {
const isSelected = settings.correction_roles?.includes(role.id);
return (
<motion.button
whileTap={{ scale: 0.97 }}
key={role.id}
onClick={() => toggleRole(role.id)}
className={`flex items-center justify-between p-3.5 rounded-[16px] border text-xs font-bold transition-all ${
isSelected
? 'border-indigo-500 bg-indigo-50 text-indigo-700 shadow-sm'
: 'border-gray-200 bg-white text-gray-600 hover:border-gray-300 hover:bg-gray-50'
}`}
>
{role.label}
<div className={`w-5 h-5 rounded-full flex items-center justify-center transition-colors ${isSelected ? 'bg-indigo-500 text-white' : 'bg-gray-100 text-transparent'}`}>
<Check size={12} strokeWidth={3} />
</div>
</motion.button>
);
})}
</div>
</div>
{/* Uncounted Shelves Warning Days */}
<div className="border-t border-gray-50 pt-8">
<div className="flex items-center gap-2 mb-2">
<div className="w-8 h-8 rounded-[12px] bg-orange-50 text-orange-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 mb-4">
قفسههایی که بیشتر از این تعداد روز از آخرین انبارگردانیشان گذشته باشد، در صفحه اصلی برای شمارش مجدد پیشنهاد میشوند.
</p>
<div className="flex items-center gap-3 bg-gray-50 p-4 rounded-[16px] border border-gray-100">
<input
type="number"
min="1"
max="365"
value={settings.uncounted_shelf_days || 10}
onChange={e => setSettings(s => ({ ...s, uncounted_shelf_days: Number(e.target.value) }))}
className="w-20 bg-white border border-gray-200 rounded-[12px] px-3 py-2 text-center font-black text-gray-800 focus:outline-none focus:border-indigo-500 transition-colors"
/>
<span className="text-sm font-bold text-gray-600">روز</span>
</div>
</div>
</div>
<motion.button
whileTap={{ scale: 0.98 }}
onClick={handleSave}
disabled={saving}
className="w-full mt-4 flex items-center justify-center gap-2 bg-gray-900 text-white px-6 py-4 rounded-[16px] text-sm font-extrabold shadow-md hover:bg-gray-800 transition-colors disabled:opacity-70"
>
{saving ? (
<div className="w-5 h-5 border-2 border-white/30 border-t-white rounded-full animate-spin"></div>
) : (
<>
<Save size={18} strokeWidth={2.5} />
ذخیره تغییرات
</>
)}
</motion.button>
</div>
<AnimatePresence>
{toast.show && (
<motion.div
initial={{ opacity: 0, y: 50, scale: 0.9 }}
animate={{ opacity: 1, y: 0, scale: 1 }}
exit={{ opacity: 0, y: 20, scale: 0.9 }}
className={`fixed bottom-8 left-1/2 -translate-x-1/2 z-[100] px-5 py-3 rounded-2xl shadow-xl backdrop-blur-3xl border text-xs font-bold whitespace-nowrap flex items-center justify-center gap-2 ${toast.isError ? 'bg-red-50/90 border-red-100 text-red-600' : 'bg-white/90 border-gray-100 text-gray-800'}`}
>
{toast.isError ? <XCircle size={14} /> : <Check size={14} />}
{toast.message}
</motion.div>
)}
</AnimatePresence>
</div>
);
}
+77
View File
@@ -0,0 +1,77 @@
'use client';
import { useState, useEffect } from 'react';
import Header from '@/components/Header';
import { motion } from 'framer-motion';
export default function AdminStats() {
const [stats, setStats] = useState([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
fetch('/api/admin/stats')
.then(res => res.json())
.then(data => {
if (Array.isArray(data)) {
setStats(data);
} else {
setStats([]);
}
setLoading(false);
});
}, []);
const container = {
hidden: { opacity: 0 },
show: {
opacity: 1,
transition: { staggerChildren: 0.1 }
}
};
const item = {
hidden: { opacity: 0, y: 10 },
show: { opacity: 1, y: 0 }
};
return (
<div className="w-full min-h-screen bg-gray-50 flex flex-col pb-20">
<Header title="آمار طبقات" showBack={true} />
<div className="p-5 flex flex-col gap-4">
{loading ? (
<div className="flex justify-center items-center h-40">
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-purple-600"></div>
</div>
) : stats.length === 0 ? (
<div className="text-center text-gray-400 p-10 text-sm font-medium bg-white/60 rounded-3xl border border-gray-100">
هیچ آماری یافت نشد.
</div>
) : (
<motion.div variants={container} initial="hidden" animate="show" className="flex flex-col gap-3">
{stats.map((stat, index) => (
<motion.div
key={index}
variants={item}
className="bg-white/80 backdrop-blur-sm border border-gray-100 rounded-2xl shadow-sm p-4 flex items-center justify-between hover:scale-[1.01] transition-transform"
>
<div className="flex items-center gap-3">
<div className="w-12 h-12 bg-blue-50 text-blue-600 font-extrabold text-xl rounded-xl flex items-center justify-center">
{stat.floor}
</div>
<div className="flex flex-col">
<span className="font-extrabold text-gray-800 text-sm">شمارشهای ثبت شده</span>
<span className="text-xs text-gray-500 mt-0.5">در تمامی مناطق و قطاعها</span>
</div>
</div>
<div className="text-2xl font-black text-gray-900">
{stat.totalCountings}
</div>
</motion.div>
))}
</motion.div>
)}
</div>
</div>
);
}
+205
View File
@@ -0,0 +1,205 @@
'use client';
import { useState, useEffect, use } from 'react';
import Header from '@/components/Header';
import { User as UserIcon, Calendar, Package, Layers, CheckCircle2, AlertTriangle, ArrowLeft } from 'lucide-react';
import { motion } from 'framer-motion';
export default function UserProfilePage({ params }) {
const unwrappedParams = use(params);
const [user, setUser] = useState(null);
const [countings, setCountings] = useState([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
fetchUserData();
}, [unwrappedParams.id]);
const fetchUserData = async () => {
try {
const [usersRes, countingsRes] = await Promise.all([
fetch('/api/users'),
fetch(`/api/counting?user_id=${unwrappedParams.id}`)
]);
if (usersRes.ok) {
const users = await usersRes.json();
const found = users.find(u => u.id === parseInt(unwrappedParams.id));
setUser(found);
}
if (countingsRes.ok) {
const data = await countingsRes.json();
setCountings(data);
}
} catch (e) {
console.error(e);
} finally {
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>
);
}
if (!user) {
return (
<div className="w-full min-h-screen bg-gray-50 flex flex-col">
<Header title="کارنامه کاربر" showBack={true} />
<div className="flex-1 p-6 flex items-center justify-center text-gray-500 font-bold">
کاربر یافت نشد
</div>
</div>
);
}
// Split countings
const shelfCountings = countings.filter(c => c.mode === 'SHELF').slice(0, 10);
const itemCountings = countings.filter(c => c.mode === 'ITEM').slice(0, 10);
// Calc accuracy
const validCounts = countings.filter(c => c.status !== 'CANCELLED');
const discrepancies = validCounts.filter(c => c.old_count !== c.new_count).length;
const accuracy = validCounts.length > 0 ? (((validCounts.length - discrepancies) / validCounts.length) * 100).toFixed(1) : 0;
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-2xl mx-auto w-full mt-2">
{/* Profile Card */}
<div className="bg-white rounded-[24px] p-6 shadow-sm border border-gray-100 flex flex-col items-center relative overflow-hidden">
<div className="absolute top-0 left-0 w-full h-24 bg-gradient-to-br from-indigo-500 to-purple-600 opacity-10"></div>
<div className="w-20 h-20 bg-white border-4 border-gray-50 text-indigo-600 rounded-full flex items-center justify-center font-black text-3xl shadow-sm z-10 mb-4 overflow-hidden">
{user.avatarUrl ? <img src={user.avatarUrl} className="w-full h-full object-cover" alt="" /> : (user.name ? user.name.charAt(0) : '?')}
</div>
<h2 className="text-xl font-black text-gray-800 z-10">{user.name || 'کاربر بدون نام'}</h2>
<p className="text-sm text-gray-500 font-bold dir-ltr mt-1 z-10">{user.mobile || user.username}</p>
<div className="flex gap-2 mt-4 z-10">
{user.roles?.map(role => (
<span key={role} className="bg-indigo-50 text-indigo-600 px-3 py-1 rounded-full text-[10px] font-black">
{role}
</span>
))}
</div>
</div>
{/* Stats */}
<div className="grid grid-cols-2 md:grid-cols-4 gap-4">
<div className="bg-white rounded-[20px] p-5 shadow-sm border border-gray-100 flex flex-col gap-2 items-center justify-center text-center">
<Package size={24} className="text-indigo-500 mb-1" strokeWidth={2} />
<span className="text-[10px] font-bold text-gray-400">مجموع شمارش</span>
<span className="text-xl font-black text-gray-800">{countings.length}</span>
</div>
<div className="bg-white rounded-[20px] p-5 shadow-sm border border-gray-100 flex flex-col gap-2 items-center justify-center text-center">
<CheckCircle2 size={24} className="text-green-500 mb-1" strokeWidth={2} />
<span className="text-[10px] font-bold text-gray-400">دقت عملکرد</span>
<span className="text-xl font-black text-green-600">{accuracy}%</span>
</div>
<div className="bg-white rounded-[20px] p-5 shadow-sm border border-gray-100 flex flex-col gap-2 items-center justify-center text-center">
<AlertTriangle size={24} className="text-red-500 mb-1" strokeWidth={2} />
<span className="text-[10px] font-bold text-gray-400">مغایرتها</span>
<span className="text-xl font-black text-red-600">{discrepancies}</span>
</div>
<div className="bg-white rounded-[20px] p-5 shadow-sm border border-gray-100 flex flex-col gap-2 items-center justify-center text-center">
<Calendar size={24} className="text-blue-500 mb-1" strokeWidth={2} />
<span className="text-[10px] font-bold text-gray-400">تاریخ عضویت</span>
<span className="text-[10px] font-black text-gray-800 mt-1" dir="ltr">
{new Date(user.createdAt).toLocaleDateString('fa-IR')}
</span>
</div>
</div>
{/* Recent Countings by SHELF */}
<div className="bg-white rounded-[24px] shadow-sm border border-gray-100 overflow-hidden">
<div className="p-4 border-b border-gray-100 bg-gray-50 flex items-center justify-between">
<h3 className="font-bold text-gray-800 text-sm flex items-center gap-2">
<Layers size={18} className="text-purple-500" />
آخرین انبارگردانی قفسهای
</h3>
<span className="text-[10px] font-bold text-gray-500 bg-white px-2 py-1 rounded-md border border-gray-100">
{shelfCountings.length} رکورد آخر
</span>
</div>
<div className="p-4 flex flex-col gap-3">
{shelfCountings.map(c => (
<div key={c.id} className="flex flex-col gap-2 p-3 bg-gray-50 rounded-xl border border-gray-100">
<div className="flex items-center justify-between">
<span className="text-xs font-bold text-gray-800">{c.product_name}</span>
<span className="text-[10px] text-gray-400">{new Date(c.createdAt).toLocaleTimeString('fa-IR', {hour: '2-digit', minute:'2-digit'})}</span>
</div>
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<span className="text-[10px] font-bold bg-white text-gray-600 px-2 py-1 rounded-md border border-gray-200">
قفسه: {c.shelfCode}
</span>
{c.status === 'CANCELLED' && <span className="text-[10px] font-bold text-red-500">لغو شده</span>}
</div>
<div className="flex items-center gap-1 font-black text-sm">
<span className="text-gray-400 line-through text-[10px] ml-1">{c.old_count}</span>
<ArrowLeft size={12} className="text-gray-300" />
<span className={c.old_count === c.new_count ? 'text-green-600' : 'text-red-500'}>{c.new_count}</span>
</div>
</div>
</div>
))}
{shelfCountings.length === 0 && (
<div className="text-center text-xs text-gray-400 font-bold py-4">موردی یافت نشد</div>
)}
</div>
</div>
{/* Recent Countings by ITEM */}
<div className="bg-white rounded-[24px] shadow-sm border border-gray-100 overflow-hidden">
<div className="p-4 border-b border-gray-100 bg-gray-50 flex items-center justify-between">
<h3 className="font-bold text-gray-800 text-sm flex items-center gap-2">
<Package size={18} className="text-teal-500" />
آخرین انبارگردانی کالایی
</h3>
<span className="text-[10px] font-bold text-gray-500 bg-white px-2 py-1 rounded-md border border-gray-100">
{itemCountings.length} رکورد آخر
</span>
</div>
<div className="p-4 flex flex-col gap-3">
{itemCountings.map(c => (
<div key={c.id} className="flex flex-col gap-2 p-3 bg-gray-50 rounded-xl border border-gray-100">
<div className="flex items-center justify-between">
<span className="text-xs font-bold text-gray-800">{c.product_name}</span>
<span className="text-[10px] text-gray-400">{new Date(c.createdAt).toLocaleTimeString('fa-IR', {hour: '2-digit', minute:'2-digit'})}</span>
</div>
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<span className="text-[10px] font-bold bg-white text-gray-600 px-2 py-1 rounded-md border border-gray-200">
کد حسابفا: {c.product_id}
</span>
{c.status === 'CANCELLED' && <span className="text-[10px] font-bold text-red-500">لغو شده</span>}
</div>
<div className="flex items-center gap-1 font-black text-sm">
<span className="text-gray-400 line-through text-[10px] ml-1">{c.old_count}</span>
<ArrowLeft size={12} className="text-gray-300" />
<span className={c.old_count === c.new_count ? 'text-green-600' : 'text-red-500'}>{c.new_count}</span>
</div>
</div>
</div>
))}
{itemCountings.length === 0 && (
<div className="text-center text-xs text-gray-400 font-bold py-4">موردی یافت نشد</div>
)}
</div>
</div>
</div>
</div>
);
}
+216
View File
@@ -0,0 +1,216 @@
'use client';
import { useState, useEffect } from 'react';
import Header from '@/components/Header';
import { Users, Check, XCircle, Search, ShieldAlert, BarChart2 } from 'lucide-react';
import { motion, AnimatePresence } from 'framer-motion';
import Link from 'next/link';
export default function UsersPage() {
const [users, setUsers] = useState([]);
const [loading, setLoading] = useState(true);
const [search, setSearch] = useState('');
const [saving, setSaving] = useState(null); // id of user being saved
const [toast, setToast] = useState({ show: false, message: '', isError: false });
const availableRoles = [
{ id: 'ADMIN', label: 'مدیر' },
{ id: 'SUPERVISOR', label: 'سرپرست' },
{ id: 'ACCOUNTANT', label: 'حسابدار' },
{ id: 'COUNTER', label: 'انبارگردان' }
];
const showToast = (message, isError = false) => {
setToast({ show: true, message, isError });
setTimeout(() => setToast({ show: false, message: '', isError: false }), 3000);
};
useEffect(() => {
fetchUsers();
}, []);
const fetchUsers = async () => {
try {
const res = await fetch('/api/users');
if (res.ok) {
const data = await res.json();
setUsers(data);
}
} catch (e) {
showToast('خطا در دریافت لیست کاربران', true);
} finally {
setLoading(false);
}
};
const handleToggleRole = async (userId, roleId, currentRoles) => {
setSaving(userId);
let newRoles = [...currentRoles];
if (newRoles.includes(roleId)) {
newRoles = newRoles.filter(r => r !== roleId);
} else {
newRoles.push(roleId);
}
try {
const res = await fetch('/api/users', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ id: userId, roles: newRoles })
});
if (res.ok) {
setUsers(users.map(u => u.id === userId ? { ...u, roles: newRoles } : u));
showToast('نقش‌ها با موفقیت ذخیره شد');
} else {
showToast('خطا در بروزرسانی نقش', true);
}
} catch (e) {
showToast('خطای شبکه', true);
} finally {
setSaving(null);
}
};
const filteredUsers = users.filter(u =>
u.name?.includes(search) || u.username?.includes(search) || u.mobile?.includes(search)
);
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-2xl 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">
<Users className="text-indigo-600" size={24} strokeWidth={2.5} />
لیست کاربران سیستم
</h2>
<p className="text-xs text-gray-500 font-medium leading-relaxed">
تعیین نقشهای کاربران و مشاهده آمار انبارگردانی آنها
</p>
</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 */}
<div className="relative">
<Search className="absolute right-4 top-1/2 -translate-y-1/2 text-gray-400" size={18} />
<input
type="text"
value={search}
onChange={e => setSearch(e.target.value)}
placeholder="جستجو بر اساس نام، نام کاربری یا موبایل..."
className="w-full bg-white border border-gray-200 rounded-[20px] pr-12 pl-4 py-4 text-sm font-bold focus:outline-none focus:border-indigo-500 shadow-sm transition-all"
/>
</div>
{/* Users List */}
<div className="flex flex-col gap-4">
{filteredUsers.map(user => (
<div key={user.id} className="bg-white border border-gray-100 rounded-[24px] p-5 shadow-sm flex flex-col gap-4">
<div className="flex items-start justify-between">
<div className="flex items-center gap-3">
<div className="w-12 h-12 bg-indigo-50 text-indigo-600 rounded-2xl flex items-center justify-center font-black text-lg">
{user.name ? user.name.charAt(0) : '?'}
</div>
<div className="flex flex-col">
<span className="font-bold text-gray-800">{user.name || 'کاربر بدون نام'}</span>
<span className="text-xs text-gray-400 font-medium dir-ltr text-right">{user.mobile || user.username}</span>
</div>
</div>
<Link
href={`/admin/users/${user.id}`}
className="bg-gray-50 text-gray-600 hover:bg-gray-100 px-3 py-2 rounded-[12px] text-xs font-bold transition-colors flex items-center gap-1 border border-gray-200"
>
<BarChart2 size={14} />
کارنامه
</Link>
</div>
<div className="border-t border-gray-50 pt-4">
<p className="text-[10px] font-black text-gray-400 mb-2 flex items-center gap-1">
<ShieldAlert size={12} /> تعیین نقشهای مجاز:
</p>
<div className="flex flex-wrap gap-2">
{availableRoles.map(role => {
const isSelected = user.roles?.includes(role.id);
const isSaving = saving === user.id;
return (
<button
key={role.id}
onClick={() => handleToggleRole(user.id, role.id, user.roles || [])}
disabled={isSaving}
className={`px-3 py-1.5 rounded-xl text-xs font-bold transition-all border ${
isSelected
? 'bg-indigo-50 border-indigo-200 text-indigo-700'
: 'bg-white border-gray-200 text-gray-500 hover:bg-gray-50'
} ${isSaving ? 'opacity-50 cursor-not-allowed' : ''}`}
>
{role.label}
</button>
);
})}
</div>
</div>
<div className="bg-gray-50 rounded-[12px] p-3 flex justify-between items-center mt-1">
<span className="text-xs text-gray-500 font-medium">تعداد اقلام شمارش شده:</span>
<span className="text-sm font-black text-gray-800">{user._count?.countings || 0} مورد</span>
</div>
</div>
))}
{filteredUsers.length === 0 && (
<div className="text-center py-10 bg-white rounded-[24px] border border-dashed border-gray-300">
<Users className="mx-auto text-gray-300 mb-2" size={32} />
<p className="text-sm font-bold text-gray-500">کاربری یافت نشد.</p>
</div>
)}
</div>
</div>
<AnimatePresence>
{toast.show && (
<motion.div
initial={{ opacity: 0, y: 50, scale: 0.9 }}
animate={{ opacity: 1, y: 0, scale: 1 }}
exit={{ opacity: 0, y: 20, scale: 0.9 }}
className={`fixed bottom-8 left-1/2 -translate-x-1/2 z-[100] px-5 py-3 rounded-2xl shadow-xl backdrop-blur-3xl border text-xs font-bold whitespace-nowrap flex items-center justify-center gap-2 ${toast.isError ? 'bg-red-50/90 border-red-100 text-red-600' : 'bg-gray-900/90 border-gray-700 text-white'}`}
>
{toast.isError ? <XCircle size={14} /> : <Check size={14} />}
{toast.message}
</motion.div>
)}
</AnimatePresence>
</div>
);
}
+199
View File
@@ -0,0 +1,199 @@
'use client';
import { useState, useEffect } from 'react';
import Header from '@/components/Header';
import { motion, AnimatePresence } from 'framer-motion';
import { Plus, Trash2, Check, XCircle, Building2, Server } from 'lucide-react';
export default function WarehousesPage() {
const [warehouses, setWarehouses] = useState([]);
const [newId, setNewId] = useState('');
const [newName, setNewName] = useState('');
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
const [toast, setToast] = useState({ show: false, message: '', isError: false });
const showToast = (message, isError = false) => {
setToast({ show: true, message, isError });
setTimeout(() => setToast({ show: false, message: '', isError: false }), 3000);
};
useEffect(() => {
fetchSettings();
}, []);
const fetchSettings = async () => {
try {
const res = await fetch('/api/settings');
if (res.ok) {
const data = await res.json();
setWarehouses(data.warehouses || []);
}
} catch (error) {
console.error(error);
showToast('خطا در دریافت انبارها', true);
} finally {
setLoading(false);
}
};
const saveWarehouses = async (newWarehouses) => {
setSaving(true);
try {
const res = await fetch('/api/settings', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ warehouses: newWarehouses })
});
if (res.ok) {
setWarehouses(newWarehouses);
showToast('لیست انبارها با موفقیت بروزرسانی شد');
} else {
showToast('خطا در ذخیره انبارها', true);
}
} catch (error) {
showToast('خطای شبکه', true);
} finally {
setSaving(false);
}
};
const handleAdd = () => {
if (!newId || !newName) {
showToast('لطفاً هم کد و هم نام انبار را وارد کنید', true);
return;
}
if (warehouses.some(w => w.id === newId)) {
showToast('انباری با این کد قبلاً وجود دارد', true);
return;
}
const updated = [...warehouses, { id: newId, name: newName }];
saveWarehouses(updated);
setNewId('');
setNewName('');
};
const handleDelete = (id) => {
if (confirm('آیا از حذف این انبار اطمینان دارید؟')) {
const updated = warehouses.filter(w => w.id !== id);
saveWarehouses(updated);
}
};
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-lg mx-auto w-full mt-2">
{/* Add New Warehouse */}
<div className="bg-white rounded-[24px] p-5 shadow-sm border border-gray-100 flex flex-col gap-4 relative overflow-hidden">
<div className="absolute top-0 right-0 w-16 h-16 bg-indigo-50/50 rounded-bl-full -z-0"></div>
<h3 className="text-sm font-bold text-gray-800 relative z-10">افزودن انبار جدید</h3>
<div className="flex flex-col gap-3 relative z-10">
<div className="flex items-center gap-2">
<input
type="number"
dir="ltr"
value={newId}
onChange={e => setNewId(e.target.value)}
placeholder="کد حسابفا..."
className="w-28 bg-gray-50 border border-gray-200 rounded-[16px] px-4 py-3 text-sm font-bold focus:outline-none focus:border-indigo-500 focus:bg-white transition-all text-center placeholder:font-normal"
/>
<input
type="text"
value={newName}
onChange={e => setNewName(e.target.value)}
placeholder="نام انبار..."
className="flex-1 bg-gray-50 border border-gray-200 rounded-[16px] px-4 py-3 text-sm font-bold focus:outline-none focus:border-indigo-500 focus:bg-white transition-all placeholder:font-normal"
/>
</div>
<motion.button
whileTap={{ scale: 0.98 }}
onClick={handleAdd}
disabled={saving}
className="w-full bg-indigo-600 text-white py-3.5 rounded-[16px] text-sm font-black shadow-md shadow-indigo-600/20 hover:bg-indigo-700 transition-colors flex items-center justify-center gap-2 disabled:opacity-50"
>
<Plus size={18} strokeWidth={3} />
ثبت انبار در سیستم
</motion.button>
</div>
</div>
{/* List of Warehouses */}
<div className="flex flex-col gap-3">
<h3 className="text-xs font-black text-gray-400 px-2 mt-2 uppercase tracking-wider">لیست انبارهای فعال</h3>
<AnimatePresence>
{warehouses.map((wh) => (
<motion.div
initial={{ opacity: 0, y: 10 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, scale: 0.9 }}
key={wh.id}
className="flex items-center justify-between p-4 rounded-[20px] border border-gray-200 bg-white shadow-sm"
>
<div className="flex items-center gap-4">
<div className="w-12 h-12 bg-gray-50 rounded-2xl flex flex-col items-center justify-center border border-gray-100">
<span className="text-[10px] text-gray-400 font-bold mb-0.5">کد</span>
<span className="text-sm font-black text-indigo-600">{wh.id}</span>
</div>
<div className="flex flex-col">
<span className="text-sm font-bold text-gray-800">{wh.name}</span>
<span className="text-[10px] text-gray-400 font-medium mt-1 flex items-center gap-1">
<Building2 size={10} /> متصل به حسابفا
</span>
</div>
</div>
<button
onClick={() => handleDelete(wh.id)}
disabled={saving}
className="w-10 h-10 bg-red-50 text-red-500 hover:bg-red-500 hover:text-white rounded-2xl flex items-center justify-center transition-all disabled:opacity-50"
>
<Trash2 size={16} strokeWidth={2.5} />
</button>
</motion.div>
))}
</AnimatePresence>
{warehouses.length === 0 && (
<div className="text-center py-10 bg-white rounded-[24px] border border-dashed border-gray-300">
<Server className="mx-auto text-gray-300 mb-2" size={32} />
<p className="text-sm font-bold text-gray-500">هیچ انباری تعریف نشده است.</p>
</div>
)}
</div>
</div>
{/* Toast Notification */}
<AnimatePresence>
{toast.show && (
<motion.div
initial={{ opacity: 0, y: 50, scale: 0.9 }}
animate={{ opacity: 1, y: 0, scale: 1 }}
exit={{ opacity: 0, y: 20, scale: 0.9 }}
className={`fixed bottom-8 left-1/2 -translate-x-1/2 z-[100] px-5 py-3 rounded-2xl shadow-xl backdrop-blur-3xl border text-xs font-bold whitespace-nowrap flex items-center justify-center gap-2 ${toast.isError ? 'bg-red-50/90 border-red-100 text-red-600' : 'bg-gray-900/90 border-gray-700 text-white'}`}
>
{toast.isError ? <XCircle size={14} /> : <Check size={14} />}
{toast.message}
</motion.div>
)}
</AnimatePresence>
</div>
);
}
+18
View File
@@ -0,0 +1,18 @@
import prisma from '@/lib/prisma';
import { NextResponse } from 'next/server';
export async function PUT(req, { params }) {
try {
const { id: idParam } = await params;
const id = parseInt(idParam, 10);
const { roles } = await req.json();
const updated = await prisma.user.update({
where: { id },
data: { roles }
});
return NextResponse.json({ success: true, user: updated });
} catch (error) {
return NextResponse.json({ error: 'خطا در ویرایش کاربر' }, { status: 500 });
}
}
+18
View File
@@ -0,0 +1,18 @@
import prisma from '@/lib/prisma';
import { NextResponse } from 'next/server';
export async function GET() {
try {
const users = await prisma.user.findMany({
include: {
_count: {
select: { countings: true }
}
},
orderBy: { createdAt: 'desc' }
});
return NextResponse.json(users);
} catch (error) {
return NextResponse.json({ error: 'خطا در دریافت کاربران' }, { status: 500 });
}
}
+9 -2
View File
@@ -24,9 +24,16 @@ export async function POST(req) {
return Response.json({ error: 'رمز عبور اشتباه است.' }, { status: 401 });
}
const token = signToken({ id: user.id, username: user.username, name: user.name, orgId: user.orgId, role: user.role });
let parsedRoles = user.roles;
if (typeof parsedRoles === 'string') {
try { parsedRoles = JSON.parse(parsedRoles); } catch (e) { parsedRoles = null; }
}
let userRoles = Array.isArray(parsedRoles) ? parsedRoles : ['COUNTER'];
return Response.json({ message: 'با موفقیت وارد شدید', token, user: { id: user.id, name: user.name, orgId: user.orgId, 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 } });
} catch (error) {
console.error(error);
return Response.json({ error: 'خطای سرور رخ داد.' }, { status: 500 });
@@ -0,0 +1,39 @@
import { NextResponse } from 'next/server';
import { generateAuthenticationOptions } from '@simplewebauthn/server';
import { PrismaClient } from '@prisma/client';
const prisma = new PrismaClient();
export async function POST(req) {
try {
const url = new URL(req.url);
const rpID = url.hostname;
const { username } = await req.json();
if (!username) return NextResponse.json({ error: 'لطفاً ابتدا شماره موبایل را وارد کنید' }, { status: 400 });
const user = await prisma.user.findUnique({
where: { username },
include: { authenticators: true }
});
if (!user) return NextResponse.json({ error: 'حسابی با این شماره یافت نشد' }, { status: 404 });
if (!user.authenticators.length) return NextResponse.json({ error: 'اثر انگشتی روی این حساب فعال نیست' }, { status: 400 });
const options = await generateAuthenticationOptions({
rpID,
allowCredentials: user.authenticators.map(auth => ({
id: Buffer.from(auth.credentialID, 'base64url'),
type: 'public-key',
transports: auth.transports ? auth.transports.split(',') : [],
})),
userVerification: 'preferred',
});
await prisma.user.update({ where: { id: user.id }, data: { challenge: options.challenge } });
return NextResponse.json(options);
} catch (error) {
return NextResponse.json({ error: error.message }, { status: 500 });
}
}
@@ -0,0 +1,57 @@
import { NextResponse } from 'next/server';
import { verifyAuthenticationResponse } from '@simplewebauthn/server';
import { PrismaClient } from '@prisma/client';
import { signToken } from '@/lib/auth';
const prisma = new PrismaClient();
export async function POST(req) {
try {
const url = new URL(req.url);
const rpID = url.hostname;
const expectedOrigin = url.origin;
const body = await req.json();
const { username, response } = body;
const user = await prisma.user.findUnique({
where: { username },
include: { authenticators: true }
});
if (!user) return NextResponse.json({ error: 'کاربر یافت نشد' }, { status: 404 });
const authenticator = user.authenticators.find(a => a.credentialID === response.id);
if (!authenticator) return NextResponse.json({ error: 'اطلاعات سنسور مطابقت ندارد' }, { status: 400 });
const verification = await verifyAuthenticationResponse({
response,
expectedChallenge: user.challenge,
expectedOrigin,
expectedRPID: rpID,
authenticator: {
credentialID: Buffer.from(authenticator.credentialID, 'base64url'),
credentialPublicKey: Buffer.from(authenticator.credentialPublicKey),
counter: Number(authenticator.counter),
},
});
if (verification.verified) {
await prisma.authenticator.update({
where: { id: authenticator.id },
data: { counter: BigInt(verification.authenticationInfo.newCounter) }
});
let parsedRoles = user.roles;
if (typeof parsedRoles === 'string') {
try { parsedRoles = JSON.parse(parsedRoles); } catch (e) { parsedRoles = null; }
}
let userRoles = Array.isArray(parsedRoles) ? parsedRoles : ['COUNTER'];
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 } });
}
return NextResponse.json({ verified: false }, { status: 400 });
} catch (error) {
return NextResponse.json({ error: error.message }, { status: 500 });
}
}
@@ -0,0 +1,58 @@
import { NextResponse } from 'next/server';
import { generateRegistrationOptions } from '@simplewebauthn/server';
import { PrismaClient } from '@prisma/client';
import { verifyToken } from '@/lib/auth';
const prisma = new PrismaClient();
const rpName = 'پردیس رایانه';
export async function GET(req) {
try {
const url = new URL(req.url);
const rpID = url.hostname;
let token = req.cookies.get('token')?.value;
if (!token) {
const authHeader = req.headers.get('authorization');
if (!authHeader || !authHeader.startsWith('Bearer ')) return NextResponse.json({ error: 'عدم دسترسی' }, { status: 401 });
token = authHeader.split(' ')[1];
}
const payload = verifyToken(token);
if (!payload || !payload.id) return NextResponse.json({ error: 'عدم دسترسی' }, { status: 401 });
const user = await prisma.user.findUnique({
where: { id: payload.id },
include: { authenticators: true }
});
if (!user) return NextResponse.json({ error: 'کاربر یافت نشد' }, { status: 404 });
const options = await generateRegistrationOptions({
rpName,
rpID,
userID: Buffer.from(user.id.toString(), 'utf-8'),
userName: user.username,
attestationType: 'none',
authenticatorSelection: {
residentKey: 'required',
userVerification: 'preferred',
},
excludeCredentials: user.authenticators.map(auth => ({
id: Buffer.from(auth.credentialID, 'base64url'),
type: 'public-key',
transports: auth.transports ? auth.transports.split(',') : [],
})),
});
await prisma.user.update({
where: { id: user.id },
data: { challenge: options.challenge }
});
return NextResponse.json(options);
} catch (error) {
console.error('generateOptions error:', error);
return NextResponse.json({ error: error.message }, { status: 500 });
}
}
@@ -0,0 +1,58 @@
import { NextResponse } from 'next/server';
import { verifyRegistrationResponse } from '@simplewebauthn/server';
import { PrismaClient } from '@prisma/client';
import { verifyToken } from '@/lib/auth';
const prisma = new PrismaClient();
export async function POST(req) {
try {
const url = new URL(req.url);
const rpID = url.hostname;
const expectedOrigin = url.origin;
let token = req.cookies.get('token')?.value;
if (!token) {
const authHeader = req.headers.get('authorization');
if (!authHeader || !authHeader.startsWith('Bearer ')) return NextResponse.json({ error: 'عدم دسترسی' }, { status: 401 });
token = authHeader.split(' ')[1];
}
const payload = verifyToken(token);
if (!payload || !payload.id) return NextResponse.json({ error: 'عدم دسترسی' }, { status: 401 });
const body = await req.json();
const user = await prisma.user.findUnique({ where: { id: payload.id } });
if (!user) return NextResponse.json({ error: 'کاربر یافت نشد' }, { status: 404 });
const verification = await verifyRegistrationResponse({
response: body,
expectedChallenge: user.challenge,
expectedOrigin,
expectedRPID: rpID,
});
if (verification.verified) {
const { registrationInfo } = verification;
const { credentialPublicKey, credentialID, counter } = registrationInfo;
await prisma.authenticator.create({
data: {
credentialID: Buffer.from(credentialID).toString('base64url'),
credentialPublicKey: Buffer.from(credentialPublicKey),
counter: BigInt(counter),
transports: body.response.transports?.join(',') || '',
userId: user.id
}
});
return NextResponse.json({ verified: true });
}
return NextResponse.json({ verified: false }, { status: 400 });
} catch (error) {
console.error('verify error:', error);
return NextResponse.json({ error: error.message }, { status: 500 });
}
}
+28
View File
@@ -0,0 +1,28 @@
import prisma from '@/lib/prisma';
import { NextResponse } from 'next/server';
export async function PUT(req, { params }) {
try {
const { new_count, userId } = await req.json();
const countingId = parseInt(params.id);
if (!new_count && new_count !== 0) {
return NextResponse.json({ error: 'مقدار جدید الزامی است' }, { status: 400 });
}
// In a real system, we should verify that userId has the correction role here too,
// but we'll trust the UI check for this MVP, or we can fetch the user.
const updated = await prisma.counting.update({
where: { id: countingId },
data: {
new_count: Number(new_count)
}
});
return NextResponse.json({ success: true, updated });
} catch (error) {
console.error('Update count error:', error);
return NextResponse.json({ error: 'خطا در ثبت اصلاحیه' }, { status: 500 });
}
}
+61
View File
@@ -0,0 +1,61 @@
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
if (shelfCode) {
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 ? shelfCode.toUpperCase() : product_id} به دلیل: ${reason}`
}
});
return NextResponse.json({ success: true, cancelledCount: updated.count });
} catch (error) {
console.error('Cancel counting error:', error);
return NextResponse.json({ error: 'خطا در لغو انبارگردانی' }, { status: 500 });
}
}
+16 -6
View File
@@ -5,15 +5,25 @@ export async function POST(req) {
try {
const data = await req.json();
const count = await prisma.counting.create({
data: {
product_id: Number(data.product_id),
if (data.shelfCode) {
await prisma.location.upsert({
where: { code: data.shelfCode.toUpperCase() },
update: {},
create: { code: data.shelfCode.toUpperCase(), floor: '0', region: 0, sector: 'A', row: 0 }
});
}
const count = await prisma.counting.create({
data: {
product_id: String(data.product_id),
product_name: data.product_name,
warehouse: Number(data.warehouse),
shelfCode: data.shelfCode || null,
shelfCode: data.shelfCode ? data.shelfCode.toUpperCase() : null,
old_count: Number(data.old_count),
new_count: Number(data.new_count),
user_id: Number(data.user_id)
user_id: Number(data.user_id),
mode: data.mode || 'SHELF',
is_offline: data.is_offline || false
}
});
@@ -33,7 +43,7 @@ export async function GET(req) {
try {
if (productId && warehouse) {
const lastCount = await prisma.counting.findFirst({
where: { product_id: Number(productId), warehouse: Number(warehouse) },
where: { product_id: String(productId), warehouse: Number(warehouse) },
orderBy: { createdAt: 'desc' }
});
return NextResponse.json(lastCount || { message: -1 });
+12 -2
View File
@@ -1,8 +1,8 @@
import { NextResponse } from 'next/server';
import axios from 'axios';
const HESABFA_API_KEY = 'NCuDX3bksHlhXWGIqTvatvme3YTplxdF';
const HESABFA_TOKEN = '4ddb2fc517f6f6fe6d4b9bdd08fa0df31a564a62e12c4353eb9533ae63447b57ca87c479beb7f02b276929c861dad779';
const HESABFA_API_KEY = process.env.HESABFA_API_KEY || 'NCuDX3bksHlhXWGIqTvatvme3YTplxdF';
const HESABFA_TOKEN = process.env.HESABFA_TOKEN || '4ddb2fc517f6f6fe6d4b9bdd08fa0df31a564a62e12c4353eb9533ae63447b57ca87c479beb7f02b276929c861dad779';
export async function POST(req) {
try {
@@ -26,6 +26,16 @@ export async function POST(req) {
return NextResponse.json(res.data);
}
if (type === 'all') {
const res = await axios.post('https://api.hesabfa.com/v1/item/getitems', {
apiKey: HESABFA_API_KEY,
loginToken: HESABFA_TOKEN,
queryInfo: { Take: 2000, Skip: 0 },
type: 0
});
return NextResponse.json(res.data);
}
return NextResponse.json({ error: 'نوع درخواست نامعتبر است' }, { status: 400 });
} catch (error) {
return NextResponse.json({ error: 'خطا در ارتباط با حسابفا' }, { status: 500 });
+60
View File
@@ -0,0 +1,60 @@
import prisma from '@/lib/prisma';
import { NextResponse } from 'next/server';
export async function DELETE(req, { params }) {
try {
const { id: idParam } = await params;
const id = parseInt(idParam, 10);
const location = await prisma.location.findUnique({
where: { id },
include: { _count: { select: { countings: true } } }
});
if (!location) return NextResponse.json({ error: 'قفسه یافت نشد' }, { status: 404 });
if (location._count.countings > 0) {
return NextResponse.json({ error: 'این قفسه دارای کالای شمرده شده است و قابل حذف نیست.' }, { status: 400 });
}
await prisma.location.delete({ where: { id } });
return NextResponse.json({ success: true });
} catch (error) {
return NextResponse.json({ error: 'خطا در حذف قفسه' }, { status: 500 });
}
}
export async function PUT(req, { params }) {
try {
const { id: idParam } = await params;
const id = parseInt(idParam, 10);
const { code, warehouse } = await req.json();
const location = await prisma.location.findUnique({
where: { id },
include: { _count: { select: { countings: true } } }
});
if (!location) return NextResponse.json({ error: 'قفسه یافت نشد' }, { status: 404 });
if (location._count.countings > 0) {
return NextResponse.json({ error: 'این قفسه دارای کالا است و قابل ویرایش نیست.' }, { status: 400 });
}
const regex = /^([A-Za-z]+)(\d+)([A-Za-z]+)(\d+)$/;
const match = code.toUpperCase().match(regex);
if (!match) return NextResponse.json({ error: 'فرمت کد نامعتبر است. مثال: C2F2' }, { status: 400 });
const [, floor, regionStr, sector, rowStr] = match;
const region = parseInt(regionStr, 10);
const row = parseInt(rowStr, 10);
const warehouseId = warehouse ? parseInt(warehouse, 10) : null;
const updated = await prisma.location.update({
where: { id },
data: { code: code.toUpperCase(), floor, region, sector, row, warehouse: warehouseId }
});
return NextResponse.json({ success: true, location: updated });
} catch (error) {
if (error.code === 'P2002') return NextResponse.json({ error: 'این کد قفسه از قبل وجود دارد' }, { status: 400 });
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 });
}
}
+48
View File
@@ -0,0 +1,48 @@
import prisma from '@/lib/prisma';
import { NextResponse } from 'next/server';
import { verifyToken } from '@/lib/auth';
export async function POST(req) {
try {
const authHeader = req.headers.get('authorization');
if (!authHeader) return NextResponse.json({ error: 'عدم احراز هویت' }, { status: 401 });
const user = verifyToken(authHeader.replace('Bearer ', ''));
if (!user) return NextResponse.json({ error: 'توکن نامعتبر' }, { status: 401 });
const { shelfCode, action } = await req.json(); // action: 'LOCK' | 'UNLOCK'
const location = await prisma.location.findUnique({ where: { code: shelfCode } });
if (!location) return NextResponse.json({ error: 'قفسه یافت نشد' }, { status: 404 });
if (action === 'LOCK') {
if (location.isLocked && location.lockedById !== user.id) {
const lockedByUser = await prisma.user.findUnique({ where: { id: location.lockedById } });
return NextResponse.json({ error: `این قفسه توسط "${lockedByUser?.name || 'کاربر دیگر'}" در حال شمارش است.` }, { status: 403 });
}
await prisma.location.update({
where: { code: shelfCode },
data: { isLocked: true, lockedById: user.id, lockedAt: new Date() }
});
return NextResponse.json({ message: 'قفسه با موفقیت قفل شد.' });
}
else if (action === 'UNLOCK') {
// Allow the locker or an Admin/Supervisor to unlock
if (location.isLocked && location.lockedById !== user.id && !user.roles?.includes('ADMIN') && !user.roles?.includes('SUPERVISOR')) {
return NextResponse.json({ error: 'شما دسترسی باز کردن این قفسه را ندارید' }, { status: 403 });
}
await prisma.location.update({
where: { code: shelfCode },
data: { isLocked: false, lockedById: null, lockedAt: null }
});
return NextResponse.json({ message: 'قفل قفسه باز شد.' });
}
return NextResponse.json({ error: 'عملیات نامعتبر' }, { status: 400 });
} catch (error) {
console.error('Lock error:', error);
return NextResponse.json({ error: 'خطای سرور' }, { status: 500 });
}
}
+6 -3
View File
@@ -4,6 +4,7 @@ import { NextResponse } from 'next/server';
export async function GET() {
try {
const locations = await prisma.location.findMany({
include: { _count: { select: { countings: true } } },
orderBy: [{ floor: 'asc' }, { region: 'asc' }, { sector: 'asc' }, { row: 'asc' }]
});
return NextResponse.json(locations);
@@ -14,7 +15,7 @@ export async function GET() {
export async function POST(req) {
try {
const { code } = await req.json(); // "C2F2"
const { code, warehouse } = await req.json(); // "C2F2", 11
// Pattern validation (e.g., C2F2 -> 1 Char, 1 Num, 1 Char, 1 Num)
const regex = /^([A-Za-z]+)(\d+)([A-Za-z]+)(\d+)$/;
@@ -27,16 +28,18 @@ export async function POST(req) {
const [, floor, regionStr, sector, rowStr] = match;
const region = parseInt(regionStr, 10);
const row = parseInt(rowStr, 10);
const warehouseId = warehouse ? parseInt(warehouse, 10) : null;
const location = await prisma.location.upsert({
where: { code: code.toUpperCase() },
update: {}, // if exists, do nothing or update timestamps
update: { warehouse: warehouseId }, // if exists, do nothing or update timestamps
create: {
code: code.toUpperCase(),
floor,
region,
sector,
row
row,
warehouse: warehouseId
}
});
+35
View File
@@ -0,0 +1,35 @@
import prisma from '@/lib/prisma';
import { NextResponse } from 'next/server';
export async function POST(req) {
try {
const { code, warehouse } = await req.json();
if (!code) {
return NextResponse.json({ error: 'کد قفسه الزامی است' }, { status: 400 });
}
const location = await prisma.location.findFirst({
where: {
code: code,
warehouse: warehouse
}
});
if (!location) {
return NextResponse.json({ error: 'این قفسه در این انبار وجود ندارد' }, { status: 404 });
}
if (location.isLocked) {
return NextResponse.json({
error: 'این قفسه در حال حاضر توسط شخص دیگری قفل شده و در حال انبارگردانی است',
lockedBy: location.lockedById
}, { status: 403 });
}
return NextResponse.json({ success: true, location });
} catch (error) {
console.error('Validate location 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 });
}
}
@@ -0,0 +1,85 @@
import prisma from '@/lib/prisma';
import { NextResponse } from 'next/server';
export async function GET(req) {
const { searchParams } = new URL(req.url);
const warehouse = searchParams.get('warehouse') || '11';
try {
// 1. Fetch all countings for this warehouse
const countings = await prisma.counting.findMany({
where: { warehouse: Number(warehouse) }
});
// 2. Aggregate counts by product_id
// Wait, some products might be counted multiple times in the SAME shelf (override).
// The logic should be: for a given (product_id, shelfCode), the latest count is the true count of that shelf.
// So we group by product_id + shelfCode to find the latest count for that specific shelf.
// Then we sum the counts for all shelves for that product.
const shelfItemLatest = {}; // key: `${product_id}_${shelfCode}`, value: new_count
const productNames = {};
const oldCounts = {}; // What the system expects
countings.sort((a, b) => new Date(a.createdAt) - new Date(b.createdAt)); // Oldest first
countings.forEach(c => {
const key = `${c.product_id}_${c.shelfCode || 'NONE'}`;
shelfItemLatest[key] = c.new_count;
productNames[c.product_id] = c.product_name;
// Assume old_count in DB is correct representation of Hesabfa at the time of count
oldCounts[c.product_id] = c.old_count;
});
// 3. Sum up the shelves for each product
const aggregatedCounts = {}; // product_id -> total_counted
const productLocations = {}; // product_id -> [shelves]
for (const [key, count] of Object.entries(shelfItemLatest)) {
const [productIdStr, shelfCode] = key.split('_');
const pId = Number(productIdStr);
if (!aggregatedCounts[pId]) aggregatedCounts[pId] = 0;
aggregatedCounts[pId] += count;
if (!productLocations[pId]) productLocations[pId] = [];
if (shelfCode !== 'NONE' && count > 0) {
productLocations[pId].push(shelfCode);
}
}
// 4. Build Discrepancy Array
const discrepancies = [];
const accurate = [];
for (const pId of Object.keys(aggregatedCounts)) {
const totalCounted = aggregatedCounts[pId];
const systemExpected = oldCounts[pId] || 0;
const diff = totalCounted - systemExpected;
const record = {
product_id: pId,
product_name: productNames[pId],
system_expected: systemExpected,
total_counted: totalCounted,
difference: diff,
locations: productLocations[pId]
};
if (diff === 0) {
accurate.push(record);
} else {
discrepancies.push(record);
}
}
// Sort discrepancies: most missing first (negative diff)
discrepancies.sort((a, b) => a.difference - b.difference);
return NextResponse.json({ discrepancies, accurate });
} catch (error) {
console.error('Discrepancy 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 });
}
}
+48
View File
@@ -0,0 +1,48 @@
import prisma from '@/lib/prisma';
import { NextResponse } from 'next/server';
import axios from 'axios';
const HESABFA_API_KEY = process.env.HESABFA_API_KEY || 'NCuDX3bksHlhXWGIqTvatvme3YTplxdF';
const HESABFA_TOKEN = process.env.HESABFA_TOKEN || '4ddb2fc517f6f6fe6d4b9bdd08fa0df31a564a62e12c4353eb9533ae63447b57ca87c479beb7f02b276929c861dad779';
export async function GET(req) {
const { searchParams } = new URL(req.url);
const warehouse = searchParams.get('warehouse') || '11';
try {
// 1. Fetch countings
const countings = await prisma.counting.findMany({
where: { warehouse: Number(warehouse), status: { not: 'CANCELLED' } }
});
// Get distinct product IDs that were counted
const countedProductIds = new Set(countings.map(c => String(c.product_id)));
// 2. Fetch all products from Hesabfa
const res = await axios.post('https://api.hesabfa.com/v1/item/getitems', {
apiKey: HESABFA_API_KEY,
loginToken: HESABFA_TOKEN,
queryInfo: { Take: 2000, Skip: 0 },
type: 0
});
const hesabfaItems = res.data?.Result?.List || [];
// 3. Filter items that have Stock > 0 but are not in countedProductIds
const uncounted = hesabfaItems.filter(item => {
// Check if not counted
if (countedProductIds.has(String(item.Code))) return false;
// Check if it has stock (assuming item.Stock or finding via another property, some accounts use item.Stock)
// Since getitems might not return Stock per warehouse, we assume if Stock > 0 it should have been counted.
const stock = Number(item.Stock) || 0;
return stock > 0;
});
return NextResponse.json({ uncounted });
} catch (error) {
console.error('Uncounted Error:', error);
return NextResponse.json({ error: 'خطا در محاسبه کالاهای شمارش نشده' }, { status: 500 });
}
}
+53
View File
@@ -0,0 +1,53 @@
import prisma from '@/lib/prisma';
import { NextResponse } from 'next/server';
export async function GET() {
try {
const settings = await prisma.systemSetting.findMany();
const settingsMap = settings.reduce((acc, setting) => {
acc[setting.key] = JSON.parse(setting.value);
return acc;
}, {});
// Default settings if not exists
if (settingsMap['blind_counting'] === undefined) {
settingsMap['blind_counting'] = false;
}
if (settingsMap['correction_roles'] === undefined) {
settingsMap['correction_roles'] = ['ADMIN', 'SUPERVISOR'];
}
if (settingsMap['warehouses'] === undefined) {
settingsMap['warehouses'] = [
{ id: '11', name: 'انبار مرکزی' },
{ id: '13', name: 'انبار فروشگاه' },
{ id: '14', name: 'انبار کارگاه شارژ' },
{ id: '15', name: 'انبار کارگاه تعمیرات' }
];
}
return NextResponse.json(settingsMap);
} catch (error) {
console.error('Settings error:', error);
return NextResponse.json({ error: 'خطا در دریافت تنظیمات' }, { status: 500 });
}
}
export async function POST(req) {
try {
const data = await req.json();
// Process each key-value pair
for (const [key, value] of Object.entries(data)) {
await prisma.systemSetting.upsert({
where: { key },
update: { value: JSON.stringify(value) },
create: { key, value: JSON.stringify(value) },
});
}
return NextResponse.json({ message: 'تنظیمات با موفقیت ذخیره شد' });
} catch (error) {
console.error('Settings save error:', error);
return NextResponse.json({ error: 'خطا در ذخیره تنظیمات' }, { status: 500 });
}
}
+43
View File
@@ -0,0 +1,43 @@
import { NextResponse } from 'next/server';
import { PrismaClient } from '@prisma/client';
import bcrypt from 'bcryptjs';
import { verifyToken } from '@/lib/auth';
const prisma = new PrismaClient();
export async function PUT(req) {
try {
const authHeader = req.headers.get('authorization');
if (!authHeader || !authHeader.startsWith('Bearer ')) {
return NextResponse.json({ error: 'عدم دسترسی (توکن ارسال نشده)' }, { status: 401 });
}
const token = authHeader.split(' ')[1];
const payload = verifyToken(token);
if (!payload || !payload.id) {
return NextResponse.json({ error: 'عدم دسترسی (توکن نامعتبر)' }, { status: 401 });
}
const body = await req.json();
const { name, password, avatarUrl } = body;
const dataToUpdate = {};
if (name) dataToUpdate.name = name;
if (avatarUrl) dataToUpdate.avatarUrl = avatarUrl;
if (password) {
dataToUpdate.password = await bcrypt.hash(password, 10);
}
const updatedUser = await prisma.user.update({
where: { id: payload.id },
data: dataToUpdate,
select: { id: true, username: true, name: true, role: true, avatarUrl: true }
});
return NextResponse.json({ success: true, user: updatedUser });
} catch (error) {
console.error('Settings error:', error);
return NextResponse.json({ error: 'خطای سرور' }, { status: 500 });
}
}
+59
View File
@@ -0,0 +1,59 @@
import prisma from '@/lib/prisma';
import { NextResponse } from 'next/server';
export async function GET() {
try {
const users = await prisma.user.findMany({
select: {
id: true,
name: true,
username: true,
mobile: true,
roles: true,
createdAt: true,
_count: {
select: { countings: true }
}
},
orderBy: { createdAt: 'desc' }
});
// Parse roles
const parsedUsers = users.map(user => {
let parsedRoles = user.roles;
if (typeof parsedRoles === 'string') {
try { parsedRoles = JSON.parse(parsedRoles); } catch (e) { parsedRoles = null; }
}
return {
...user,
roles: Array.isArray(parsedRoles) ? parsedRoles : ['COUNTER']
};
});
return NextResponse.json(parsedUsers);
} catch (error) {
console.error('Fetch users error:', error);
return NextResponse.json({ error: 'خطا در دریافت کاربران' }, { status: 500 });
}
}
export async function PUT(req) {
try {
const { id, roles } = await req.json();
if (!id || !roles) {
return NextResponse.json({ error: 'اطلاعات ناقص است' }, { status: 400 });
}
const updated = await prisma.user.update({
where: { id: parseInt(id) },
data: { roles: JSON.stringify(roles) },
select: { id: true, roles: true }
});
return NextResponse.json({ message: 'نقش‌های کاربر بروزرسانی شد', user: updated });
} catch (error) {
console.error('Update user error:', error);
return NextResponse.json({ error: 'خطا در بروزرسانی کاربر' }, { status: 500 });
}
}
+361
View File
@@ -0,0 +1,361 @@
'use client';
import { useState, useEffect, Suspense, useRef } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import Header from '@/components/Header';
import { ScanLine, Search, Check, Box, Layers, AlertCircle, X, History } from 'lucide-react';
import { hasRole } from '@/lib/auth';
import { saveCountOffline, syncOfflineCounts } from '@/lib/offlineSync';
import dynamic from 'next/dynamic';
import { motion, AnimatePresence } from 'framer-motion';
const Scanner = dynamic(() => import('@yudiel/react-qr-scanner').then(mod => mod.Scanner), { ssr: false });
function ItemCountingContent() {
const router = useRouter();
const searchParams = useSearchParams();
const product_id = searchParams.get('product_id');
const warehouse = searchParams.get('warehouse');
const [user, setUser] = useState(null);
const [settings, setSettings] = useState({});
const [loading, setLoading] = useState(true);
// We fetch product details based on product_id from query
const [productName, setProductName] = useState('');
const [oldCount, setOldCount] = useState(null);
const [newCount, setNewCount] = useState('');
const [shelfCode, setShelfCode] = useState('');
const [submitLoading, setSubmitLoading] = useState(false);
const [history, setHistory] = useState([]);
const [cameraEnabled, setCameraEnabled] = useState(true);
const [camError, setCamError] = useState('');
const [errorMsg, setErrorMsg] = useState('');
const inputRef = useRef(null);
useEffect(() => {
const userData = localStorage.getItem('user');
if (userData) setUser(JSON.parse(userData));
fetchSettings();
fetchInitialItemData();
window.addEventListener('online', syncOfflineCounts);
return () => window.removeEventListener('online', syncOfflineCounts);
}, []);
const fetchSettings = async () => {
try {
const res = await fetch('/api/settings');
if (res.ok) setSettings(await res.json());
} catch (e) {}
};
const fetchInitialItemData = async () => {
if (!product_id) {
router.push('/dashboard');
return;
}
try {
const nameRes = await fetch('/api/hesabfa', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ code: product_id, type: 'name' })
});
const nameData = await nameRes.json();
if (!nameData?.Result?.Name || nameData?.Result?.Name === 'نامشخص') {
setErrorMsg('کالا یافت نشد.');
} else {
setProductName(nameData.Result.Name);
}
const qRes = await fetch('/api/hesabfa', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ code: product_id, type: 'quantity' })
});
const qData = await qRes.json();
const productInfo = qData?.Result?.[0];
let foundStock = 0;
if (productInfo) {
if (productInfo.StockByWarehouse && Array.isArray(productInfo.StockByWarehouse)) {
const wInfo = productInfo.StockByWarehouse.find(w => w.WarehouseCode === Number(warehouse) || w.Code === Number(warehouse));
if (wInfo) foundStock = wInfo.Stock || wInfo.Quantity || 0;
else foundStock = productInfo.Stock || productInfo.Quantity || 0;
} else if (productInfo.Warehouse && Array.isArray(productInfo.Warehouse)) {
const wInfo = productInfo.Warehouse.find(w => w.Code === Number(warehouse));
foundStock = wInfo?.Quantity ?? productInfo.Stock ?? productInfo.Quantity ?? 0;
} else {
foundStock = productInfo.Stock ?? productInfo.Quantity ?? 0;
}
}
setOldCount(foundStock);
} catch (error) {
setErrorMsg('خطا در دریافت اطلاعات کالا از سرور');
} finally {
setLoading(false);
}
};
const handleScan = (detectedCodes) => {
if (detectedCodes && detectedCodes.length > 0) {
const scannedValue = detectedCodes[0].rawValue;
// We do not close the camera!
setShelfCode(scannedValue);
setCamError('');
if (inputRef.current) setTimeout(() => inputRef.current.focus(), 100);
}
};
const handleError = (error) => {
const msg = error?.message || error?.name || '';
if (msg.includes('Requested device not found')) setCamError('دوربینی یافت نشد.');
else setCamError('خطا در دسترسی به دوربین.');
};
const handleSubmitShelf = async () => {
if (!shelfCode) {
setErrorMsg('کد قفسه را وارد یا اسکن کنید');
return;
}
if (newCount === '' || newCount === null) {
setErrorMsg('تعداد را وارد کنید');
return;
}
setSubmitLoading(true);
setErrorMsg('');
const payload = {
product_id: String(product_id),
product_name: productName,
warehouse: Number(warehouse),
shelfCode: shelfCode.toUpperCase(),
old_count: oldCount || 0,
new_count: Number(newCount),
user_id: user?.id,
mode: 'ITEM'
};
try {
const res = await fetch('/api/counting', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload)
});
if (res.ok) {
setHistory([{ shelf: shelfCode.toUpperCase(), count: newCount }, ...history]);
setShelfCode('');
setNewCount('');
setErrorMsg('');
} else {
const data = await res.json();
setErrorMsg(data.error || 'خطا در ثبت اطلاعات در سرور');
}
} catch (err) {
await saveCountOffline(payload);
alert('ارتباط با سرور قطع است. اطلاعات ذخیره شد.');
setHistory([{ shelf: shelfCode.toUpperCase(), count: newCount, offline: true }, ...history]);
setShelfCode('');
setNewCount('');
} finally {
setSubmitLoading(false);
}
};
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, warehouse, userId: user?.id, reason, mode: 'ITEM' })
});
router.push('/dashboard');
} catch (error) {
alert('خطا در ارتباط با سرور');
}
};
const isBlind = settings?.blind_counting && !hasRole(user?.roles, ['ADMIN', 'SUPERVISOR']);
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} />
{/* Top Fixed Info Bar */}
<div className="bg-white border-b border-gray-200 px-5 py-3 flex items-center justify-between sticky top-0 z-40 shadow-sm">
<div className="flex items-center gap-3">
<div className="w-10 h-10 bg-teal-50 text-teal-600 rounded-[14px] flex items-center justify-center font-black">
<Box size={20} />
</div>
<div className="flex flex-col">
<span className="text-[10px] text-gray-400 font-bold tracking-wider line-clamp-1 w-32">{productName}</span>
<span className="text-xs font-black text-gray-800">آماده ثبت قفسه</span>
</div>
</div>
<div className="flex items-center gap-2">
<button
onClick={handleCancelItem}
className="w-10 h-10 flex items-center justify-center bg-red-50 text-red-500 rounded-[14px] transition-colors"
>
<X size={18} strokeWidth={2.5} />
</button>
<button
onClick={() => router.push('/dashboard')}
className="bg-gray-900 hover:bg-gray-800 text-white text-xs font-black py-2.5 px-4 rounded-[14px] transition-colors flex items-center gap-2"
>
<Check size={14} strokeWidth={3} />
پایان کالا
</button>
</div>
</div>
<div className="flex-1 p-4 flex flex-col gap-5 max-w-md mx-auto w-full mt-2">
{!isBlind && oldCount !== null && (
<div className="bg-white rounded-[20px] p-4 shadow-[0_8px_30px_rgb(0,0,0,0.04)] border border-gray-100 flex items-center justify-between">
<span className="text-sm font-bold text-gray-500">موجودی کل در سیستم:</span>
<span className="text-xl font-black text-teal-600">{oldCount}</span>
</div>
)}
{/* Continuous Scanner Area for Shelf */}
<div className="bg-white rounded-[24px] p-2 shadow-sm border border-gray-100 flex flex-col relative overflow-hidden">
<div className="w-full aspect-video relative flex items-center justify-center bg-gray-900 rounded-[20px] overflow-hidden">
{camError ? (
<div className="text-red-400 text-xs p-4 text-center font-medium">{camError}</div>
) : cameraEnabled ? (
<>
<div className="w-full h-full opacity-80 [&>div]:!object-cover [&>div>video]:!object-cover">
<Scanner onScan={handleScan} onError={handleError} />
</div>
{/* Scanner Overlay UI */}
<div className="absolute inset-0 pointer-events-none border-[3px] border-teal-500/30 m-4 rounded-[16px]">
<div className="absolute top-1/2 left-0 w-full h-[2px] bg-red-500/50 shadow-[0_0_10px_rgba(239,68,68,0.8)]"></div>
</div>
</>
) : (
<button onClick={() => setCameraEnabled(true)} className="flex flex-col items-center gap-2 text-gray-400">
<ScanLine size={32} />
<span className="text-xs font-bold">فعالسازی مجدد دوربین</span>
</button>
)}
</div>
<div className="flex items-center gap-2 mt-3 px-2 pb-2">
<input
type="text"
dir="ltr"
value={shelfCode}
onChange={(e) => { setShelfCode(e.target.value); setErrorMsg(''); }}
placeholder="کد قفسه..."
className="flex-1 bg-gray-50 border border-gray-200 rounded-[14px] px-4 py-3 text-sm font-bold text-gray-800 uppercase focus:outline-none focus:border-teal-500 text-center placeholder:font-normal placeholder:normal-case"
/>
</div>
</div>
{/* Error Message */}
<AnimatePresence>
{errorMsg && (
<motion.div initial={{ opacity: 0, height: 0 }} animate={{ opacity: 1, height: 'auto' }} exit={{ opacity: 0, height: 0 }} className="bg-red-50 border border-red-100 text-red-600 px-4 py-3 rounded-[16px] text-xs font-bold flex items-center gap-2">
<AlertCircle size={16} className="shrink-0" />
{errorMsg}
</motion.div>
)}
</AnimatePresence>
{/* Count Input Box */}
<div className="bg-white rounded-[24px] p-5 shadow-[0_8px_30px_rgb(0,0,0,0.06)] border border-teal-50 flex flex-col gap-4 relative overflow-hidden">
<div className="absolute top-0 right-0 w-32 h-32 bg-teal-500/5 rounded-bl-full -z-0"></div>
<div className="flex flex-col gap-1 relative z-10">
<h3 className="font-black text-gray-800 text-sm flex items-center gap-2">
<Layers size={18} className="text-teal-600" />
ثبت موجودی در قفسه {shelfCode ? `«${shelfCode.toUpperCase()}»` : ''}
</h3>
</div>
<div className="flex flex-col gap-3 relative z-10 mt-2">
<input
ref={inputRef}
type="number"
dir="ltr"
value={newCount}
onChange={(e) => { setNewCount(e.target.value); setErrorMsg(''); }}
placeholder="0"
className="w-full bg-gray-50 border-2 border-gray-200 rounded-[16px] p-4 text-center text-3xl font-black text-gray-900 focus:outline-none focus:border-teal-500 focus:bg-white transition-all placeholder:text-gray-300"
/>
<button
onClick={handleSubmitShelf}
disabled={submitLoading || !newCount || !shelfCode}
className="w-full bg-teal-600 text-white py-4 rounded-[16px] shadow-md hover:bg-teal-700 transition-all disabled:opacity-50 text-sm font-black flex items-center justify-center gap-2"
>
{submitLoading ? (
<div className="w-5 h-5 border-2 border-white/30 border-t-white rounded-full animate-spin"></div>
) : (
<>ثبت شمارش</>
)}
</button>
</div>
</div>
{/* History of this session */}
{history.length > 0 && (
<div className="flex flex-col gap-3 mt-4">
<h3 className="text-xs font-black text-gray-400 flex items-center gap-2 px-2">
<History size={14} />
قفسههای شمارش شده برای این کالا
</h3>
<div className="flex flex-col gap-2">
{history.map((item, idx) => (
<div key={idx} className="flex justify-between items-center bg-white p-3 rounded-[16px] border border-gray-100 relative overflow-hidden">
{item.offline && <div className="absolute left-0 top-0 bottom-0 w-1 bg-yellow-400"></div>}
<div className="flex items-center gap-3">
<div className="w-8 h-8 bg-green-50 rounded-[10px] flex items-center justify-center text-green-500 shrink-0">
<Check size={16} strokeWidth={3} />
</div>
<div className="flex flex-col">
<p className="text-xs font-bold text-gray-800 tracking-widest uppercase">{item.shelf}</p>
</div>
</div>
<div className="flex items-center gap-1 bg-gray-50 px-3 py-1.5 rounded-xl border border-gray-100">
<span className="text-sm font-black text-gray-800">{item.count}</span>
</div>
</div>
))}
</div>
</div>
)}
</div>
</div>
);
}
export default function ItemCountingPage() {
return (
<Suspense fallback={<div className="min-h-screen bg-gray-50 flex items-center justify-center">در حال بارگذاری...</div>}>
<ItemCountingContent />
</Suspense>
);
}
+419
View File
@@ -0,0 +1,419 @@
'use client';
import { useState, useEffect, Suspense, useRef } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import Header from '@/components/Header';
import { Lock, Unlock, ScanLine, Search, Check, Box, Layers, AlertCircle, X, History } from 'lucide-react';
import { hasRole } from '@/lib/auth';
import { saveCountOffline, syncOfflineCounts } from '@/lib/offlineSync';
import dynamic from 'next/dynamic';
import { motion, AnimatePresence } from 'framer-motion';
const Scanner = dynamic(() => import('@yudiel/react-qr-scanner').then(mod => mod.Scanner), { ssr: false });
function ShelfCountingContent() {
const router = useRouter();
const searchParams = useSearchParams();
const shelfCode = searchParams.get('code');
const warehouse = searchParams.get('warehouse');
const [user, setUser] = useState(null);
const [settings, setSettings] = useState({});
const [loading, setLoading] = useState(true);
const [productCode, setProductCode] = useState('');
const [productName, setProductName] = useState('');
const [oldCount, setOldCount] = useState(null);
const [newCount, setNewCount] = useState('');
const [itemLoading, setItemLoading] = useState(false);
const [submitLoading, setSubmitLoading] = useState(false);
const [errorMsg, setErrorMsg] = useState('');
const [cameraEnabled, setCameraEnabled] = useState(true);
const [camError, setCamError] = useState('');
const [history, setHistory] = useState([]);
const inputRef = useRef(null);
useEffect(() => {
const userData = localStorage.getItem('user');
if (userData) setUser(JSON.parse(userData));
fetchSettings();
window.addEventListener('online', syncOfflineCounts);
return () => window.removeEventListener('online', syncOfflineCounts);
}, []);
const fetchSettings = async () => {
try {
const res = await fetch('/api/settings');
if (res.ok) {
const data = await res.json();
setSettings(data);
}
} catch (e) {} finally { setLoading(false); }
};
const handleFinishShelf = async () => {
try {
const token = localStorage.getItem('token');
await fetch('/api/locations/lock', {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${token}` },
body: JSON.stringify({ shelfCode, action: 'UNLOCK' })
});
router.push('/dashboard');
} catch (error) {
router.push('/dashboard');
}
};
const fetchItemData = async (codeToFetch) => {
const code = codeToFetch || productCode;
if (!code) {
setErrorMsg('لطفاً کد کالا را وارد کنید');
return;
}
setErrorMsg('');
setItemLoading(true);
setProductName('');
setOldCount(null);
setNewCount('');
setProductCode(code);
try {
const nameRes = await fetch('/api/hesabfa', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ code, type: 'name' })
});
const nameData = await nameRes.json();
if (!nameData?.Result?.Name || nameData?.Result?.Name === 'نامشخص' || nameData.error) {
setErrorMsg(`کالایی با کد ${code} در حسابفا یافت نشد.`);
setItemLoading(false);
return;
}
setProductName(nameData.Result.Name);
const qRes = await fetch('/api/hesabfa', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ code, type: 'quantity' })
});
const qData = await qRes.json();
const productInfo = qData?.Result?.[0];
let foundStock = 0;
if (productInfo) {
if (productInfo.StockByWarehouse && Array.isArray(productInfo.StockByWarehouse)) {
const wInfo = productInfo.StockByWarehouse.find(w => w.WarehouseCode === Number(warehouse) || w.Code === Number(warehouse));
if (wInfo) foundStock = wInfo.Stock || wInfo.Quantity || 0;
else foundStock = productInfo.Stock || productInfo.Quantity || 0;
} else if (productInfo.Warehouse && Array.isArray(productInfo.Warehouse)) {
const wInfo = productInfo.Warehouse.find(w => w.Code === Number(warehouse));
foundStock = wInfo?.Quantity ?? productInfo.Stock ?? productInfo.Quantity ?? 0;
} else {
foundStock = productInfo.Stock ?? productInfo.Quantity ?? 0;
}
}
setOldCount(foundStock);
if (inputRef.current) {
setTimeout(() => inputRef.current.focus(), 100);
}
} catch (error) {
console.error(error);
setErrorMsg('خطا در ارتباط با حسابفا. لطفاً دوباره تلاش کنید.');
} finally {
setItemLoading(false);
}
};
const handleProductCodeKeyDown = (e) => {
if (e.key === 'Enter') {
fetchItemData();
}
};
const handleScan = (detectedCodes) => {
if (detectedCodes && detectedCodes.length > 0) {
const scannedValue = detectedCodes[0].rawValue;
// We DO NOT turn off the camera. Just fetch!
setCamError('');
if (scannedValue !== productCode) {
fetchItemData(scannedValue);
}
}
};
const handleError = (error) => {
const msg = error?.message || error?.name || '';
if (msg.includes('Requested device not found')) setCamError('دوربینی یافت نشد.');
else setCamError('خطا در دسترسی به دوربین.');
};
const handleSubmitItem = async () => {
if (!productName || errorMsg) {
setErrorMsg('ابتدا از صحت کالا اطمینان حاصل کنید');
return;
}
if (newCount === '' || newCount === null) {
setErrorMsg('لطفاً تعداد را وارد کنید');
return;
}
setSubmitLoading(true);
const payload = {
product_id: String(productCode),
product_name: productName,
warehouse: Number(warehouse),
shelfCode: shelfCode.toUpperCase(),
old_count: oldCount || 0,
new_count: Number(newCount),
user_id: user?.id,
mode: 'SHELF'
};
try {
const res = await fetch('/api/counting', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload)
});
if (res.ok) {
setHistory([{ code: productCode, name: productName, count: newCount }, ...history]);
setProductCode('');
setProductName('');
setOldCount(null);
setNewCount('');
setErrorMsg('');
} else {
setErrorMsg('خطا در ثبت شمارش در سرور');
}
} catch (err) {
await saveCountOffline(payload);
alert('ارتباط با سرور قطع است. شمارش ذخیره شد و پس از اتصال ارسال می‌شود.');
setHistory([{ code: productCode, name: productName, count: newCount, offline: true }, ...history]);
setProductCode('');
setProductName('');
setOldCount(null);
setNewCount('');
setErrorMsg('');
} finally {
setSubmitLoading(false);
}
};
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']);
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} />
{/* Top Fixed Info Bar */}
<div className="bg-white border-b border-gray-200 px-5 py-3 flex items-center justify-between sticky top-0 z-40 shadow-sm">
<div className="flex items-center gap-3">
<div className="w-10 h-10 bg-indigo-50 text-indigo-600 rounded-[14px] flex items-center justify-center font-black">
{shelfCode}
</div>
<div className="flex flex-col">
<span className="text-[10px] text-gray-400 font-bold tracking-wider">قفسه جاری</span>
<span className="text-xs font-black text-gray-800">آماده اسکن کالای بعدی</span>
</div>
</div>
<div className="flex items-center gap-2">
<button
onClick={handleCancelShelf}
className="w-10 h-10 flex items-center justify-center bg-red-50 text-red-500 rounded-[14px] transition-colors"
>
<X size={18} strokeWidth={2.5} />
</button>
<button
onClick={handleFinishShelf}
className="bg-gray-900 hover:bg-gray-800 text-white text-xs font-black py-2.5 px-4 rounded-[14px] transition-colors flex items-center gap-2"
>
<Check size={14} strokeWidth={3} />
پایان قفسه
</button>
</div>
</div>
<div className="flex-1 p-4 flex flex-col gap-5 max-w-md mx-auto w-full mt-2">
{/* Continuous Scanner Area */}
<div className="bg-white rounded-[24px] p-2 shadow-sm border border-gray-100 flex flex-col relative overflow-hidden">
<div className="w-full aspect-video relative flex items-center justify-center bg-gray-900 rounded-[20px] overflow-hidden">
{camError ? (
<div className="text-red-400 text-xs p-4 text-center font-medium">{camError}</div>
) : cameraEnabled ? (
<>
<div className="w-full h-full opacity-80 [&>div]:!object-cover [&>div>video]:!object-cover">
<Scanner onScan={handleScan} onError={handleError} />
</div>
{/* Scanner Overlay UI */}
<div className="absolute inset-0 pointer-events-none border-[3px] border-indigo-500/30 m-4 rounded-[16px]">
<div className="absolute top-1/2 left-0 w-full h-[2px] bg-red-500/50 shadow-[0_0_10px_rgba(239,68,68,0.8)]"></div>
</div>
</>
) : (
<button onClick={() => setCameraEnabled(true)} className="flex flex-col items-center gap-2 text-gray-400">
<ScanLine size={32} />
<span className="text-xs font-bold">فعالسازی مجدد دوربین</span>
</button>
)}
</div>
<div className="flex items-center gap-2 mt-3 px-2 pb-2">
<input
type="text"
dir="ltr"
value={productCode}
onChange={(e) => { setProductCode(e.target.value); setErrorMsg(''); setProductName(''); }}
onKeyDown={handleProductCodeKeyDown}
placeholder="یا بارکد را اینجا تایپ کنید..."
className="flex-1 bg-gray-50 border border-gray-200 rounded-[14px] px-4 py-3 text-sm font-bold text-gray-800 focus:outline-none focus:border-indigo-500 text-center placeholder:font-normal"
/>
<button
onClick={() => fetchItemData()}
disabled={itemLoading || !productCode}
className="w-12 h-12 bg-indigo-50 text-indigo-600 rounded-[14px] flex items-center justify-center shrink-0 hover:bg-indigo-100 transition-colors border border-indigo-100 disabled:opacity-50"
>
{itemLoading ? <div className="w-4 h-4 border-2 border-indigo-600/30 border-t-indigo-600 rounded-full animate-spin"></div> : <Search size={18} strokeWidth={2.5} />}
</button>
</div>
</div>
{/* Error Message */}
<AnimatePresence>
{errorMsg && (
<motion.div initial={{ opacity: 0, height: 0 }} animate={{ opacity: 1, height: 'auto' }} exit={{ opacity: 0, height: 0 }} className="bg-red-50 border border-red-100 text-red-600 px-4 py-3 rounded-[16px] text-xs font-bold flex items-center gap-2">
<AlertCircle size={16} className="shrink-0" />
{errorMsg}
</motion.div>
)}
</AnimatePresence>
{/* Product Details & Count input (only shown if valid product found) */}
<AnimatePresence>
{productName && !itemLoading && (
<motion.div
initial={{ opacity: 0, y: 10 }}
animate={{ opacity: 1, y: 0 }}
className="bg-white rounded-[24px] p-5 shadow-[0_8px_30px_rgb(0,0,0,0.06)] border border-indigo-50 flex flex-col gap-4 relative overflow-hidden"
>
<div className="absolute top-0 right-0 w-32 h-32 bg-indigo-500/5 rounded-bl-full -z-0"></div>
<div className="flex justify-between items-start relative z-10">
<div className="flex flex-col gap-1">
<h3 className="font-black text-gray-800 text-lg leading-tight">{productName}</h3>
<p className="text-xs text-gray-400 font-bold tracking-wider">کد حسابفا: {productCode}</p>
</div>
{!isBlind && oldCount !== null && (
<div className="bg-indigo-50 text-indigo-600 px-3 py-2 rounded-xl flex flex-col items-center shadow-sm shrink-0 ml-1 border border-indigo-100">
<span className="text-sm font-black">{oldCount}</span>
<span className="text-[9px] font-bold opacity-70">موجودی سیستم</span>
</div>
)}
</div>
<div className="flex flex-col gap-3 relative z-10 mt-2">
<input
ref={inputRef}
type="number"
dir="ltr"
value={newCount}
onChange={(e) => { setNewCount(e.target.value); setErrorMsg(''); }}
placeholder="0"
className="w-full bg-gray-50 border-2 border-gray-200 rounded-[16px] p-4 text-center text-3xl font-black text-gray-900 focus:outline-none focus:border-indigo-500 focus:bg-white transition-all placeholder:text-gray-300"
/>
<button
onClick={handleSubmitItem}
disabled={submitLoading || !newCount}
className="w-full bg-indigo-600 text-white py-4 rounded-[16px] shadow-md hover:bg-indigo-700 transition-all disabled:opacity-50 text-sm font-black flex items-center justify-center gap-2"
>
{submitLoading ? (
<div className="w-5 h-5 border-2 border-white/30 border-t-white rounded-full animate-spin"></div>
) : (
<>ثبت موجودی</>
)}
</button>
</div>
</motion.div>
)}
</AnimatePresence>
{/* History of this session */}
{history.length > 0 && (
<div className="flex flex-col gap-3 mt-4">
<h3 className="text-xs font-black text-gray-400 flex items-center gap-2 px-2">
<History size={14} />
تاریخچه شمارشهای شما در این قفسه
</h3>
<div className="flex flex-col gap-2">
{history.map((item, idx) => (
<div key={idx} className="flex justify-between items-center bg-white p-3 rounded-[16px] border border-gray-100 relative overflow-hidden">
{item.offline && <div className="absolute left-0 top-0 bottom-0 w-1 bg-yellow-400"></div>}
<div className="flex items-center gap-3">
<div className="w-8 h-8 bg-green-50 rounded-[10px] flex items-center justify-center text-green-500 shrink-0">
<Check size={16} strokeWidth={3} />
</div>
<div className="flex flex-col">
<p className="text-xs font-bold text-gray-800 line-clamp-1">{item.name}</p>
<p className="text-[9px] font-bold text-gray-400 mt-0.5">کد: {item.code}</p>
</div>
</div>
<div className="flex items-center gap-1 bg-gray-50 px-3 py-1.5 rounded-xl border border-gray-100">
<span className="text-sm font-black text-gray-800">{item.count}</span>
</div>
</div>
))}
</div>
</div>
)}
</div>
</div>
);
}
export default function ShelfCountingPage() {
return (
<Suspense fallback={<div className="min-h-screen bg-gray-50 flex items-center justify-center">در حال بارگذاری...</div>}>
<ShelfCountingContent />
</Suspense>
);
}
+124 -21
View File
@@ -1,11 +1,55 @@
'use client';
import { useState, useEffect } from 'react';
import Header from '@/components/Header';
import Link from 'next/link';
import { motion } from 'framer-motion';
import { History, ScanLine, ListChecks } from 'lucide-react';
import { History, ScanLine, ListChecks, AlertTriangle, Layers, MapPin } from 'lucide-react';
export default function Dashboard() {
const [uncountedShelves, setUncountedShelves] = useState([]);
const [activeSessions, setActiveSessions] = useState([]);
const [settings, setSettings] = useState(null);
const [user, setUser] = useState(null);
useEffect(() => {
const userData = localStorage.getItem('user');
let u = null;
if (userData) {
u = JSON.parse(userData);
setUser(u);
}
fetchData(u);
}, []);
const fetchData = async (currentUser) => {
try {
const setRes = await fetch('/api/settings');
let currentSettings = { uncounted_shelf_days: 10, show_suggested_shelves: true };
if (setRes.ok) {
currentSettings = await setRes.json();
setSettings(currentSettings);
}
if (currentSettings.show_suggested_shelves !== false) {
const uncRes = await fetch(`/api/reports/uncounted?days=${currentSettings.uncounted_shelf_days || 10}`);
if (uncRes.ok) {
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) {
console.error(e);
}
};
const container = {
hidden: { opacity: 0 },
show: {
@@ -20,48 +64,107 @@ export default function Dashboard() {
};
return (
<div className="w-full min-h-screen bg-gray-50 flex flex-col">
<div className="w-full min-h-screen bg-gray-50 flex flex-col pb-24 overflow-x-hidden">
<Header title="داشبورد" />
<motion.div
variants={container}
initial="hidden"
animate="show"
className="p-5 flex flex-col gap-4"
className="p-4 md:p-6 flex flex-col gap-6 max-w-lg mx-auto w-full mt-2"
>
<div className="grid grid-cols-2 gap-4">
<motion.div variants={item}>
<Link href="/history" className="bg-white/80 backdrop-blur-sm border border-gray-100 rounded-3xl shadow-[0_4px_20px_rgb(0,0,0,0.03)] p-6 flex flex-col items-center justify-center aspect-square gap-3 hover:bg-white hover:scale-[1.02] active:scale-95 transition-all">
<Link href="/history" className="bg-white/80 backdrop-blur-sm border border-gray-100 rounded-3xl shadow-sm p-6 flex flex-col items-center justify-center aspect-square gap-3 hover:bg-white hover:scale-[1.02] active:scale-95 transition-all">
<div className="w-12 h-12 bg-blue-50 text-blue-500 rounded-2xl flex items-center justify-center mb-1">
<History strokeWidth={1.5} size={24} />
<History strokeWidth={2} size={24} />
</div>
<span className="font-extrabold text-xs text-gray-700">تاریخچه شمارش</span>
<span className="font-black text-xs text-gray-700">تاریخچه شمارش</span>
</Link>
</motion.div>
<motion.div variants={item}>
<Link href="/scan" className="bg-white/80 backdrop-blur-sm border border-gray-100 rounded-3xl shadow-[0_4px_20px_rgb(0,0,0,0.03)] p-6 flex flex-col items-center justify-center aspect-square gap-3 hover:bg-white hover:scale-[1.02] active:scale-95 transition-all">
<div className="w-12 h-12 bg-purple-50 text-purple-600 rounded-2xl flex items-center justify-center mb-1">
<ScanLine strokeWidth={1.5} size={24} />
<Link href="/scan" className="bg-white/80 backdrop-blur-sm border border-gray-100 rounded-3xl shadow-sm p-6 flex flex-col items-center justify-center aspect-square gap-3 hover:bg-white hover:scale-[1.02] active:scale-95 transition-all relative overflow-hidden">
<div className="absolute top-0 right-0 w-16 h-16 bg-indigo-50/50 rounded-bl-full -z-0"></div>
<div className="w-12 h-12 bg-indigo-50 text-indigo-600 rounded-2xl flex items-center justify-center mb-1 relative z-10">
<ScanLine strokeWidth={2.5} size={24} />
</div>
<span className="font-extrabold text-xs text-gray-700">اسکن کالا</span>
<span className="font-black text-xs text-gray-800 relative z-10">شروع انبارگردانی</span>
</Link>
</motion.div>
</div>
<motion.div variants={item}>
<Link href="/my-counts" 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.01] active:scale-[0.99] transition-all">
<div className="flex items-center gap-4">
<div className="w-10 h-10 bg-green-50 text-green-600 rounded-xl flex items-center justify-center">
<ListChecks strokeWidth={1.5} size={20} />
</div>
<span className="font-extrabold text-sm text-gray-700">شمارشهای من</span>
{/* Active Sessions */}
{activeSessions.length > 0 && (
<motion.div variants={item} className="flex flex-col gap-3 mt-2">
<h3 className="text-sm font-black text-gray-800 flex items-center gap-2 px-2">
<span className="relative flex h-3 w-3">
<span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-indigo-400 opacity-75"></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 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>
</motion.div>
)}
{/* Suggested Shelves to count */}
{settings?.show_suggested_shelves !== false && uncountedShelves.length > 0 && (
<motion.div variants={item} className="flex flex-col gap-3 mt-4">
<div className="flex items-center justify-between px-2">
<h3 className="text-sm font-black text-gray-800 flex items-center gap-2">
<AlertTriangle size={18} className="text-orange-500" />
قفسههای پیشنهادی
</h3>
<span className="text-[10px] text-gray-400 font-bold bg-white px-2 py-1 rounded-md border border-gray-100">
بدون بررسی بالای {settings?.uncounted_shelf_days || 10} روز
</span>
</div>
</Link>
</motion.div>
<div className="grid grid-cols-2 gap-3">
{uncountedShelves.slice(0, 4).map((shelf, idx) => (
<Link
key={idx}
href={`/counting/shelf?code=${shelf.code}&warehouse=${shelf.warehouse}`}
className="bg-orange-50/50 border border-orange-100 rounded-[20px] p-4 flex flex-col gap-2 hover:bg-orange-50 transition-colors"
>
<div className="flex items-center justify-between">
<div className="w-8 h-8 bg-white rounded-[10px] flex items-center justify-center text-orange-400 shadow-sm">
<Layers size={14} />
</div>
<span className="text-xs font-black text-orange-600 uppercase tracking-widest">{shelf.code}</span>
</div>
<div className="flex items-center gap-1 mt-1 text-[10px] text-gray-500 font-bold">
<MapPin size={10} />
طبقه {shelf.floor}، انبار {shelf.warehouse}
</div>
</Link>
))}
</div>
</motion.div>
)}
</motion.div>
</div>
);
+176 -32
View File
@@ -1,52 +1,196 @@
'use client';
import { useState, useEffect } from 'react';
import Header from '@/components/Header';
import { hasRole } from '@/lib/auth';
import { Edit2, Check, X, Box, Layers, User, Save, History } from 'lucide-react';
import { motion, AnimatePresence } from 'framer-motion';
export default function HistoryPage() {
const [counts, setCounts] = useState([]);
const [loading, setLoading] = useState(true);
const [user, setUser] = useState(null);
const [settings, setSettings] = useState(null);
const [editingId, setEditingId] = useState(null);
const [editValue, setEditValue] = useState('');
const [saving, setSaving] = useState(false);
useEffect(() => {
const fetchHistory = async () => {
try {
const res = await fetch(`/api/counting`);
if (res.ok) setCounts(await res.json());
} catch (e) {
console.error(e);
}
setLoading(false);
};
fetchHistory();
const userData = localStorage.getItem('user');
if (userData) setUser(JSON.parse(userData));
fetchData();
}, []);
const fetchData = async () => {
try {
const [histRes, setRes] = await Promise.all([
fetch('/api/counting'),
fetch('/api/settings')
]);
if (histRes.ok) setCounts(await histRes.json());
if (setRes.ok) setSettings(await setRes.json());
} catch (e) {
console.error(e);
} finally {
setLoading(false);
}
};
const handleEditSubmit = async (id) => {
if (editValue === '') return;
setSaving(true);
try {
const res = await fetch(`/api/counting/${id}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ new_count: editValue, userId: user?.id })
});
if (res.ok) {
setCounts(counts.map(c => c.id === id ? { ...c, new_count: Number(editValue) } : c));
setEditingId(null);
} else {
alert('خطا در ثبت اصلاحیه');
}
} catch (e) {
alert('خطای شبکه');
} finally {
setSaving(false);
}
};
const canCorrect = settings?.correction_roles ? hasRole(user?.roles, settings.correction_roles) : false;
return (
<div className="w-full min-h-screen bg-gray-50 flex flex-col pb-20">
<div className="w-full min-h-screen bg-gray-50 flex flex-col pb-24 overflow-x-hidden">
<Header title="تاریخچه کل شمارش‌ها" showBack={true} />
<div className="p-4 flex flex-col gap-4">
<div className="flex-1 p-4 md:p-6 max-w-2xl mx-auto w-full flex flex-col gap-4 mt-2">
{loading ? (
<div className="text-center p-10">در حال دریافت...</div>
<div className="flex flex-col justify-center items-center py-20 gap-3">
<div className="w-10 h-10 border-4 border-indigo-500 border-t-transparent rounded-full animate-spin"></div>
<p className="text-gray-500 font-bold text-sm">در حال دریافت تاریخچه...</p>
</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.user?.name} | انبار: {count.warehouse}</span>
<span className="text-xs text-gray-500 mt-1">قفسه: {count.shelf || 'ثبت نشده'}</span>
</div>
<div className="flex flex-col items-center bg-green-50 p-2 rounded border border-green-200">
<span className="font-bold text-green-700">{count.new_count}</span>
<span className="text-[10px] text-green-600">موجودی ثبت شده</span>
</div>
</div>
<div className="mt-2 text-[10px] text-gray-400 text-left">
{new Date(count.createdAt).toLocaleString('fa-IR')}
</div>
<div className="bg-white rounded-[24px] border border-dashed border-gray-300 p-10 text-center flex flex-col items-center gap-3">
<div className="w-16 h-16 bg-gray-50 rounded-full flex items-center justify-center">
<History size={32} className="text-gray-300" />
</div>
))
<p className="font-bold text-gray-500 text-sm">هیچ رکورد انبارگردانی یافت نشد.</p>
</div>
) : (
<div className="flex flex-col gap-3">
<div className="flex items-center justify-between px-2 mb-2">
<h3 className="font-black text-gray-800 text-sm">آخرین رکوردهای ثبت شده</h3>
<span className="bg-indigo-50 text-indigo-600 px-3 py-1 rounded-full text-[10px] font-black">
{counts.length} رکورد
</span>
</div>
<AnimatePresence>
{counts.map(count => {
const isEditing = editingId === count.id;
return (
<motion.div
layout
initial={{ opacity: 0, y: 10 }}
animate={{ opacity: 1, y: 0 }}
key={count.id}
className="bg-white p-4 rounded-[20px] shadow-sm border border-gray-100 flex flex-col gap-3"
>
<div className="flex justify-between items-start border-b border-gray-50 pb-3">
<div className="flex gap-3">
<div className="w-10 h-10 bg-indigo-50 text-indigo-500 rounded-[12px] flex items-center justify-center shrink-0">
<Box size={18} />
</div>
<div className="flex flex-col">
<span className="font-bold text-gray-800 text-sm leading-tight line-clamp-1">{count.product_name}</span>
<span className="text-[10px] text-gray-400 mt-1">کد: {count.product_id}</span>
</div>
</div>
{!isEditing && (
<div className="flex flex-col items-center bg-gray-50 px-3 py-1.5 rounded-xl border border-gray-100 shrink-0 ml-1">
<span className="font-black text-lg text-gray-800">{count.new_count}</span>
<span className="text-[9px] font-bold text-gray-400">شمارش شده</span>
</div>
)}
</div>
<div className="flex items-center justify-between">
<div className="flex flex-col gap-1.5">
<div className="flex items-center gap-1.5 text-[10px] font-bold text-gray-500">
<Layers size={12} className="text-gray-400" />
قفسه: <span className="text-gray-800 uppercase tracking-widest">{count.shelfCode || count.shelf || 'ثبت نشده'}</span>
</div>
<div className="flex items-center gap-1.5 text-[10px] font-bold text-gray-500">
<User size={12} className="text-gray-400" />
شمارنده: <span className="text-gray-800">{count.user?.name || 'نامشخص'}</span>
</div>
</div>
<div className="flex flex-col items-end gap-2">
<span className="text-[9px] text-gray-400 dir-ltr text-right font-medium">
{new Date(count.createdAt).toLocaleString('fa-IR')}
</span>
{canCorrect && !isEditing && (
<button
onClick={() => { setEditingId(count.id); setEditValue(count.new_count); }}
className="flex items-center gap-1 text-[10px] font-bold text-indigo-500 bg-indigo-50 hover:bg-indigo-100 px-2.5 py-1 rounded-lg transition-colors"
>
<Edit2 size={10} />
اصلاحیه
</button>
)}
</div>
</div>
{/* Edit Mode */}
<AnimatePresence>
{isEditing && (
<motion.div
initial={{ height: 0, opacity: 0 }}
animate={{ height: 'auto', opacity: 1 }}
exit={{ height: 0, opacity: 0 }}
className="pt-3 border-t border-gray-100 flex items-center gap-2 overflow-hidden"
>
<input
type="number"
dir="ltr"
value={editValue}
onChange={(e) => setEditValue(e.target.value)}
className="w-20 bg-gray-50 border border-gray-200 rounded-[12px] px-3 py-2 text-center text-sm font-black text-gray-800 focus:outline-none focus:border-indigo-500 transition-colors"
/>
<button
onClick={() => handleEditSubmit(count.id)}
disabled={saving}
className="bg-gray-900 text-white px-4 py-2 rounded-[12px] text-xs font-bold transition-all disabled:opacity-50 flex items-center gap-1.5"
>
{saving ? <div className="w-3 h-3 border-2 border-white/30 border-t-white rounded-full animate-spin"></div> : <Save size={14} />}
ثبت
</button>
<button
onClick={() => setEditingId(null)}
disabled={saving}
className="bg-red-50 text-red-500 p-2 rounded-[12px] transition-all hover:bg-red-100 disabled:opacity-50"
>
<X size={16} />
</button>
</motion.div>
)}
</AnimatePresence>
</motion.div>
);
})}
</AnimatePresence>
</div>
)}
</div>
</div>
+28 -6
View File
@@ -1,17 +1,39 @@
import './globals.css'
export const viewport = {
width: 'device-width',
initialScale: 1,
maximumScale: 1,
userScalable: false,
themeColor: '#f8fafc',
}
export const metadata = {
title: 'Pardis Counting',
description: 'اپلیکیشن انبارگردانی پردیس',
title: 'سیستم انبارداری',
description: 'اپلیکیشن مدیریت انبار',
manifest: "/manifest.json",
appleWebApp: {
capable: true,
statusBarStyle: "default",
title: "انبارگردانی",
},
}
export default function RootLayout({ children }) {
return (
<html lang="fa" dir="rtl">
<body>
<main className="w-full min-h-screen flex flex-col justify-start items-center bg-gray-100">
<div className="w-full max-w-md bg-white min-h-screen shadow-lg relative pb-16">
{children}
<body className="bg-gray-100 transition-colors">
<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 flex flex-col">
<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">
<span className="text-indigo-300">HOUKA</span>
</p>
<p className="text-[8px] font-bold text-gray-200 mt-1">App v1.4.0</p>
</div>
</div>
</main>
</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>
);
}
+278 -67
View File
@@ -1,20 +1,54 @@
'use client';
import { useState, useEffect } from 'react';
import { Fingerprint, Download, Share } from 'lucide-react';
import { useRouter } from 'next/navigation';
import { motion } from 'framer-motion';
import { motion, AnimatePresence } from 'framer-motion';
export default function LoginPage() {
export default function EntryPage() {
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const [error, setError] = useState('');
const [loading, setLoading] = useState(false);
const [showSplash, setShowSplash] = useState(true);
const [showInstall, setShowInstall] = useState(false);
const [isFocused, setIsFocused] = useState(false);
const [deferredPrompt, setDeferredPrompt] = useState(null);
const [isIOS, setIsIOS] = useState(false);
const router = useRouter();
useEffect(() => {
const token = localStorage.getItem('token');
if (token) {
router.push('/dashboard');
}
const handleBeforeInstallPrompt = (e) => {
e.preventDefault();
setDeferredPrompt(e);
};
window.addEventListener('beforeinstallprompt', handleBeforeInstallPrompt);
const ua = window.navigator.userAgent;
const isIOSDevice = /iPad|iPhone|iPod/.test(ua) && !window.MSStream;
setIsIOS(isIOSDevice);
const checkAuth = async () => {
const token = localStorage.getItem('token');
await new Promise(resolve => setTimeout(resolve, 2500));
const isStandalone = window.matchMedia('(display-mode: standalone)').matches || window.navigator.standalone;
if (!isStandalone && process.env.NODE_ENV !== 'development') {
setShowSplash(false);
setShowInstall(true);
} else {
if (token) {
router.push('/dashboard');
} else {
setShowSplash(false);
setShowInstall(false);
}
}
};
checkAuth();
return () => window.removeEventListener('beforeinstallprompt', handleBeforeInstallPrompt);
}, [router]);
const handleLogin = async (e) => {
@@ -28,7 +62,6 @@ export default function LoginPage() {
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username, password })
});
const data = await res.json();
if (res.ok) {
@@ -46,71 +79,249 @@ export default function LoginPage() {
};
return (
<div className="w-full h-screen flex flex-col justify-center items-center bg-gradient-to-br from-gray-50 to-gray-100 p-4 relative overflow-hidden">
<div className="fixed inset-0 w-full h-[100dvh] bg-gradient-to-br from-gray-50 to-gray-100 overflow-hidden flex flex-col justify-between items-center">
{/* Decorative Blur Backgrounds */}
<div className="absolute top-[-10%] left-[-10%] w-64 h-64 bg-purple-400/20 rounded-full blur-3xl"></div>
<div className="absolute bottom-[-10%] right-[-10%] w-64 h-64 bg-blue-400/20 rounded-full blur-3xl"></div>
<div className="absolute top-[-10%] left-[-10%] w-64 h-64 bg-purple-400/20 rounded-full blur-3xl pointer-events-none"></div>
<div className="absolute bottom-[-10%] right-[-10%] w-64 h-64 bg-blue-400/20 rounded-full blur-3xl pointer-events-none"></div>
<motion.div
initial={{ opacity: 0, scale: 0.95, y: 20 }}
animate={{ opacity: 1, scale: 1, y: 0 }}
transition={{ duration: 0.6, ease: [0.22, 1, 0.36, 1] }}
className="w-full max-w-sm p-8 bg-white/60 backdrop-blur-2xl rounded-3xl shadow-[0_8px_30px_rgb(0,0,0,0.04)] border border-white/50 z-10"
>
<div className="flex flex-col items-center mb-8">
<div className="w-16 h-16 bg-gradient-to-tr from-purple-600 to-blue-500 rounded-2xl shadow-lg shadow-purple-500/30 flex items-center justify-center mb-4 text-white font-extrabold text-2xl">
P
</div>
<h1 className="text-xl font-extrabold text-gray-800 tracking-tight">پردیس رایانه</h1>
<p className="text-xs text-gray-500 mt-1 font-medium">اپلیکیشن مدیریت انبار</p>
</div>
{error && (
<motion.div initial={{ opacity: 0, y: -10 }} animate={{ opacity: 1, y: 0 }} className="mb-6 p-3 bg-red-50/80 border border-red-100 text-red-600 text-xs rounded-xl text-center">
{error}
<AnimatePresence mode="wait">
{showSplash ? (
<motion.div
key="splash"
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0, scale: 1.1, filter: "blur(10px)" }}
transition={{ duration: 0.6, ease: "easeInOut" }}
className="absolute inset-0 z-50 flex flex-col items-center justify-center bg-gray-50/50 backdrop-blur-md"
>
<motion.div
initial={{ scale: 0.5, opacity: 0, y: 10 }}
animate={{ scale: 1, opacity: 1, y: 0 }}
transition={{ duration: 0.8, ease: [0.22, 1, 0.36, 1], delay: 0.2 }}
className="flex items-center justify-center w-36 h-36"
>
<img src="/icons/icon-512x512.png" alt="انبارداری" className="w-full h-full object-contain drop-shadow-xl" />
</motion.div>
</motion.div>
) : showInstall ? (
<motion.div
key="install"
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, y: -20 }}
transition={{ duration: 0.6 }}
className="w-full h-full flex flex-col justify-center items-center px-8 z-10 relative max-w-md mx-auto"
>
<div className="w-32 h-32 mb-6 flex items-center justify-center">
<img src="/icons/icon-512x512.png" alt="انبارداری" className="w-full h-full object-contain drop-shadow-md" />
</div>
<h2 className="text-2xl font-black text-gray-800 tracking-tight mb-3 text-center">
تجربه بهتر در اپلیکیشن
</h2>
<p className="text-sm text-gray-500 font-medium text-center leading-relaxed mb-10">
برای تجربه سریعتر، دسترسی آفلاین و استفاده از <b className="text-gray-700">ورود امن با اثر انگشت</b>، پیشنهاد میکنیم اپلیکیشن انبارگردانی را روی دستگاه خود نصب کنید.
</p>
<div className="w-full flex flex-col gap-3">
{isIOS ? (
<div className="bg-gray-100/50 border border-gray-200 rounded-[24px] p-5 mb-2">
<p className="text-xs font-bold text-gray-700 text-center mb-3">راهنمای نصب در آیفون (iOS):</p>
<div className="flex items-center gap-2 text-[11px] text-gray-500 font-medium justify-center">
<span>۱. لمس <Share className="inline w-4 h-4 mx-0.5 text-blue-500"/></span>
<span>۲. انتخاب <b className="text-gray-800 border bg-white px-1.5 py-0.5 rounded-md shadow-sm">Add to Home Screen</b></span>
</div>
</div>
) : (
<motion.button
whileTap={{ scale: 0.98 }}
onClick={async () => {
if (deferredPrompt) {
deferredPrompt.prompt();
const { outcome } = await deferredPrompt.userChoice;
if (outcome === 'accepted') {
setDeferredPrompt(null);
}
} else {
alert('مرورگر شما از نصب مستقیم پشتیبانی نمی‌کند. از منوی مرورگر Add to Home screen را انتخاب کنید.');
}
}}
className="w-full py-4 bg-gray-900 text-white text-sm font-extrabold rounded-[20px] transition-all flex items-center justify-center shadow-sm gap-2"
>
<Download size={18} strokeWidth={2.5} />
نصب مستقیم اپلیکیشن
</motion.button>
)}
<button
onClick={() => {
setShowInstall(false);
if (localStorage.getItem('token')) router.push('/dashboard');
}}
className="w-full py-4 text-gray-400 hover:text-gray-600 text-xs font-bold transition-colors"
>
فعلاً نه، ادامه در مرورگر
</button>
</div>
<div className="absolute bottom-12 flex flex-col items-center justify-center opacity-40">
<span className="text-[11px] text-gray-800 font-black tracking-[0.3em] uppercase font-sans">
H U K A
</span>
<span className="text-[9px] text-gray-500 font-medium tracking-widest">طراحی توسط هوکا</span>
</div>
</motion.div>
) : (
<motion.div
key="login"
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
transition={{ duration: 0.6 }}
className="w-full h-full flex flex-col justify-between z-10 relative max-w-md mx-auto"
>
{/* Top Area: Logo & Welcome (Shrinks when focused to make room for keyboard) */}
<motion.div
animate={{
height: isFocused ? "10%" : "auto",
opacity: isFocused ? 0 : 1,
y: isFocused ? -50 : 0
}}
transition={{ type: "spring", stiffness: 300, damping: 25 }}
className="flex flex-col items-center justify-center flex-1 pt-10"
>
<div className="w-20 h-20 rounded-3xl shadow-sm border border-gray-100 mb-6 overflow-hidden flex items-center justify-center bg-white">
<img src="/icons/icon-512x512.png" alt="انبارداری" className="w-full h-full object-cover" />
</div>
<h2 className="text-2xl font-black text-gray-800 tracking-tight mb-2">
خوش آمدید
</h2>
<p className="text-sm text-gray-500 font-medium">
لطفاً برای ادامه وارد حساب خود شوید
</p>
</motion.div>
{/* Bottom Area: Bottom Sheet Form */}
<motion.div
animate={{
y: isFocused ? -20 : 0,
paddingBottom: isFocused ? "40px" : "40px"
}}
transition={{ type: "spring", stiffness: 300, damping: 30 }}
className="w-full bg-white/95 backdrop-blur-3xl rounded-t-[40px] p-8 shadow-sm border-t border-gray-100 flex flex-col"
>
{error && (
<motion.div initial={{ opacity: 0, y: -10 }} animate={{ opacity: 1, y: 0 }} className="mb-6 p-3 bg-red-50 text-red-600 text-xs rounded-2xl text-center font-bold">
{error}
</motion.div>
)}
<form onSubmit={handleLogin} className="flex flex-col gap-4">
<div className="flex flex-col">
<label className="text-[11px] font-extrabold text-gray-400 mb-1.5 ml-2 uppercase tracking-widest">شماره موبایل</label>
<input
type="tel"
dir="ltr"
value={username}
onChange={(e) => setUsername(e.target.value)}
onFocus={() => setIsFocused(true)}
onBlur={() => setIsFocused(false)}
className="px-5 py-4 bg-gray-50/80 rounded-[20px] focus:outline-none focus:bg-gray-100 transition-colors text-base font-bold text-gray-800 placeholder-gray-400"
placeholder="09xxxxxxxxx"
required
/>
</div>
<div className="flex flex-col">
<label className="text-[11px] font-extrabold text-gray-400 mb-1.5 ml-2 uppercase tracking-widest">رمز عبور</label>
<input
type="password"
dir="ltr"
value={password}
onChange={(e) => setPassword(e.target.value)}
onFocus={() => setIsFocused(true)}
onBlur={() => setIsFocused(false)}
className="px-5 py-4 bg-gray-50/80 rounded-[20px] focus:outline-none focus:bg-gray-100 transition-colors text-base font-bold text-gray-800 placeholder-gray-400"
placeholder="••••••••"
/>
</div>
<div className="flex gap-2 mt-2">
<motion.button
whileTap={{ scale: 0.95 }}
type="button"
onClick={async () => {
if (!username) {
setError('ابتدا شماره موبایل را وارد کنید');
setTimeout(() => setError(''), 3000);
return;
}
try {
const { startAuthentication } = await import('@simplewebauthn/browser');
const res = await fetch('/api/auth/webauthn/login/generate-options', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username })
});
const options = await res.json();
if (options.error) throw new Error(options.error);
const asseResp = await startAuthentication(options);
const verifyRes = await fetch('/api/auth/webauthn/login/verify', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username, response: asseResp })
});
const verification = await verifyRes.json();
if (verification.verified) {
localStorage.setItem('token', verification.token);
localStorage.setItem('user', JSON.stringify(verification.user));
router.push('/dashboard');
} else {
throw new Error('احراز هویت ناموفق بود');
}
} catch (err) {
setError(err.message || 'خطا در احراز هویت با اثر انگشت');
setTimeout(() => setError(''), 3000);
}
}}
className="w-14 h-14 bg-gray-50 rounded-[20px] flex items-center justify-center text-gray-400 hover:text-indigo-500 hover:bg-indigo-50 transition-colors shrink-0"
>
<Fingerprint size={24} strokeWidth={2} />
</motion.button>
<motion.button
whileTap={{ scale: 0.98 }}
type="submit"
disabled={loading}
className="flex-1 py-4 bg-gray-900 text-white text-sm font-extrabold rounded-[20px] transition-all disabled:opacity-70 flex items-center justify-center shadow-sm"
>
{loading ? (
<div className="w-5 h-5 border-2 border-white/30 border-t-white rounded-full animate-spin"></div>
) : 'ورود'}
</motion.button>
</div>
</form>
<div className="mt-8 mb-2 flex justify-center">
<div className="flex items-center justify-center opacity-60 hover:opacity-100 transition-opacity">
<span className="text-[10px] text-gray-500 font-medium tracking-widest">طراحی توسط هوکا</span>
<span className="mx-2 text-gray-300">|</span>
<span className="text-[9px] text-gray-600 font-black tracking-[0.2em] uppercase font-sans mt-0.5">DESIGNED BY HUKA</span>
</div>
</div>
{/* iOS style bottom home indicator placeholder */}
<div className="mt-4 flex items-center justify-center">
<div className="w-12 h-1 bg-gray-200 rounded-full"></div>
</div>
</motion.div>
</motion.div>
)}
<form onSubmit={handleLogin} className="flex flex-col gap-5">
<div className="flex flex-col">
<label className="text-xs font-bold text-gray-600 mb-1.5 ml-1">شماره موبایل</label>
<input
type="text"
dir="ltr"
value={username}
onChange={(e) => setUsername(e.target.value)}
className="px-4 py-3 bg-white/50 border border-gray-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-purple-500/50 focus:border-purple-500 focus:bg-white transition-all text-sm"
placeholder="09xxxxxxxxx"
required
/>
</div>
<div className="flex flex-col">
<label className="text-xs font-bold text-gray-600 mb-1.5 ml-1">رمز عبور</label>
<input
type="password"
dir="ltr"
value={password}
onChange={(e) => setPassword(e.target.value)}
className="px-4 py-3 bg-white/50 border border-gray-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-purple-500/50 focus:border-purple-500 focus:bg-white transition-all text-sm"
placeholder="••••••••"
required
/>
</div>
<motion.button
whileHover={{ scale: 1.01 }}
whileTap={{ scale: 0.98 }}
type="submit"
disabled={loading}
className="w-full py-3.5 bg-gray-900 hover:bg-black text-white text-sm font-bold rounded-xl transition-colors mt-2 shadow-lg shadow-gray-900/20 disabled:opacity-70"
>
{loading ? 'در حال ورود...' : 'ورود به سیستم'}
</motion.button>
</form>
<p className="text-[10px] text-center text-gray-400 mt-6 font-medium">رمز عبور پیشفرض: 123456</p>
</motion.div>
</AnimatePresence>
</div>
);
}
+198 -64
View File
@@ -3,30 +3,80 @@ import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import Header from '@/components/Header';
import dynamic from 'next/dynamic';
import { motion, AnimatePresence } from 'framer-motion';
import { ScanLine, Search, Box, X, ChevronDown, CheckCircle2, LayoutGrid, Layers } from 'lucide-react';
const Scanner = dynamic(() => import('@yudiel/react-qr-scanner').then(mod => mod.Scanner), { ssr: false });
export default function ScanPage() {
const [mode, setMode] = useState('ITEM'); // 'ITEM' | 'SHELF'
const [code, setCode] = useState('');
const [warehouse, setWarehouse] = useState('11');
const [cameraEnabled, setCameraEnabled] = useState(false);
const [camError, setCamError] = useState('');
const [loading, setLoading] = useState(false);
const [lockError, setLockError] = useState('');
const [warehouses, setWarehouses] = useState([]);
const [settings, setSettings] = useState(null);
const router = useRouter();
useEffect(() => {
fetch('/api/settings')
.then(res => res.json())
.then(data => {
setSettings(data);
if (data.warehouses) {
setWarehouses(data.warehouses);
if (data.warehouses.length > 0) {
setWarehouse(data.warehouses[0].id);
}
}
const shelfEnabled = data.enable_shelf_counting ?? true;
const itemEnabled = data.enable_item_counting ?? true;
if (shelfEnabled && !itemEnabled) setMode('SHELF');
if (!shelfEnabled && itemEnabled) setMode('ITEM');
});
}, []);
const handleGoToCounting = () => {
if (code) {
router.push(`/counting?code=${code}&warehouse=${warehouse}`);
const handleGoToCounting = async () => {
if (!code) return;
setLockError('');
setLoading(true);
try {
if (mode === 'SHELF') {
const token = localStorage.getItem('token');
const res = await fetch('/api/locations/lock', {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${token}` },
body: JSON.stringify({ shelfCode: code, action: 'LOCK' })
});
const data = await res.json();
if (!res.ok) {
setLockError(data.error || 'خطا در قفل‌گذاری قفسه');
setLoading(false);
return;
}
router.push(`/counting/shelf?code=${code}&warehouse=${warehouse}`);
} else {
router.push(`/counting/item?code=${code}&warehouse=${warehouse}`);
}
} catch (error) {
setLockError('خطای ارتباط با سرور');
setLoading(false);
}
};
const [camError, setCamError] = useState('');
const handleScan = (detectedCodes) => {
if (detectedCodes && detectedCodes.length > 0) {
const scannedValue = detectedCodes[0].rawValue;
setCode(scannedValue);
setCameraEnabled(false);
setTimeout(() => {
router.push(`/counting?code=${scannedValue}&warehouse=${warehouse}`);
}, 1500);
handleGoToCounting();
}, 500);
}
};
@@ -34,76 +84,160 @@ export default function ScanPage() {
console.error(error);
const msg = error?.message || error?.name || '';
if (msg.includes('Requested device not found') || msg.includes('NotFoundError') || msg.includes('device not found')) {
setCamError('هیچ دوربینی روی این دستگاه یافت نشد. لطفاً از لپ‌تاپ یا موبایل استفاده کنید.');
setCamError('دوربینی روی این دستگاه یافت نشد. لطفاً از لپ‌تاپ یا موبایل استفاده کنید.');
} else {
setCamError(msg || 'خطا در دسترسی به دوربین. آیا از HTTPS یا localhost استفاده میکنید؟');
setCamError(msg || 'خطا در دسترسی به دوربین.');
}
};
return (
<div className="w-full min-h-screen bg-gray-50 flex flex-col pb-20">
<Header title="اسکن کد کالا" showBack={true} />
<div className="w-full min-h-screen bg-gray-50 flex flex-col pb-24">
<Header title="شروع انبارگردانی" showBack={true} />
<div className="p-4 flex flex-col gap-6 items-center mt-4">
<div className="flex-1 px-4 md:px-6 pt-4 flex flex-col items-center max-w-md mx-auto w-full">
<div className="w-full max-w-sm aspect-video border-2 border-dashed border-gray-300 rounded-lg overflow-hidden flex flex-col items-center justify-center bg-gray-100 relative">
{cameraEnabled ? (
<div className="w-full h-full relative">
{camError ? (
<div className="text-red-500 text-xs p-4 text-center">{camError}</div>
) : (
<Scanner
onScan={handleScan}
onError={handleError}
formats={['qr_code', 'code_128', 'ean_13']}
/>
)}
<button
onClick={() => { setCameraEnabled(false); setCamError(''); }}
className="absolute bottom-2 right-2 bg-red-500 text-white text-xs px-2 py-1 rounded z-10"
>
بستن دوربین
</button>
</div>
) : (
{/* Mode Switcher */}
<div className="w-full bg-white p-1.5 rounded-[20px] shadow-sm flex mb-6 border border-gray-100">
{(settings?.enable_item_counting ?? true) && (
<button
onClick={() => setCameraEnabled(true)}
className="text-blue-500 font-bold px-4 py-2"
onClick={() => { setMode('ITEM'); setCode(''); setLockError(''); }}
className={`flex-1 flex items-center justify-center gap-2 py-3 rounded-[16px] text-xs font-bold transition-all ${mode === 'ITEM' ? 'bg-gray-900 text-white shadow-md' : 'text-gray-500 hover:bg-gray-50'}`}
>
فعال کردن دوربین برای اسکن
<Box size={16} />
بر اساس کالا
</button>
)}
{(settings?.enable_shelf_counting ?? true) && (
<button
onClick={() => { setMode('SHELF'); setCode(''); setLockError(''); }}
className={`flex-1 flex items-center justify-center gap-2 py-3 rounded-[16px] text-xs font-bold transition-all ${mode === 'SHELF' ? 'bg-indigo-600 text-white shadow-md' : 'text-gray-500 hover:bg-gray-50'}`}
>
<LayoutGrid size={16} />
بر اساس قفسه
</button>
)}
{!(settings?.enable_item_counting ?? true) && !(settings?.enable_shelf_counting ?? true) && (
<div className="flex-1 py-3 text-center text-xs font-bold text-red-500">
تمامی حالتهای انبارگردانی غیرفعال شدهاند
</div>
)}
</div>
{/* Camera Area */}
<div className="w-full relative mb-6">
<div className={`w-full aspect-[4/3] rounded-[32px] overflow-hidden flex flex-col items-center justify-center transition-all duration-500 relative ${cameraEnabled ? 'bg-black shadow-2xl' : 'bg-white border border-gray-200 shadow-sm'}`}>
{cameraEnabled ? (
<div className="w-full h-full relative">
{camError ? (
<div className="text-red-400 text-xs p-6 text-center h-full flex items-center justify-center font-medium bg-gray-900">{camError}</div>
) : (
<div className="w-full h-full [&>div]:!object-cover [&>div>video]:!object-cover">
<Scanner
onScan={handleScan}
onError={handleError}
formats={['qr_code', 'code_128', 'ean_13']}
/>
</div>
)}
{/* Scanner Target Overlay */}
<div className="absolute inset-0 pointer-events-none flex items-center justify-center">
<div className="w-48 h-48 border-2 border-white/40 rounded-3xl relative">
<div className="absolute top-0 left-0 w-8 h-8 border-t-4 border-l-4 border-white rounded-tl-2xl"></div>
<div className="absolute top-0 right-0 w-8 h-8 border-t-4 border-r-4 border-white rounded-tr-2xl"></div>
<div className="absolute bottom-0 left-0 w-8 h-8 border-b-4 border-l-4 border-white rounded-bl-2xl"></div>
<div className="absolute bottom-0 right-0 w-8 h-8 border-b-4 border-r-4 border-white rounded-br-2xl"></div>
</div>
</div>
<button
onClick={() => { setCameraEnabled(false); setCamError(''); }}
className="absolute top-4 right-4 bg-white/10 backdrop-blur-md p-2 rounded-full text-white hover:bg-white/20 transition-colors pointer-events-auto"
>
<X size={20} strokeWidth={2.5} />
</button>
</div>
) : (
<motion.button
whileTap={{ scale: 0.98 }}
onClick={() => setCameraEnabled(true)}
className="w-full h-full flex flex-col items-center justify-center gap-4 py-12"
>
<div className={`w-16 h-16 rounded-[20px] flex items-center justify-center ${mode === 'SHELF' ? 'bg-indigo-50 text-indigo-500' : 'bg-gray-100 text-gray-600'}`}>
<ScanLine size={32} strokeWidth={2} />
</div>
<div className="flex flex-col items-center">
<span className="text-sm font-extrabold text-gray-800 mb-1">فعالسازی دوربین</span>
<span className="text-xs font-medium text-gray-400">
برای اسکن {mode === 'SHELF' ? 'بارکد قفسه' : 'بارکد کالا'} کلیک کنید
</span>
</div>
</motion.button>
)}
</div>
</div>
<p className="text-sm text-gray-500">کد کالا را اسکن یا وارد کنید</p>
<input
type="number"
dir="ltr"
value={code}
onChange={(e) => setCode(e.target.value)}
placeholder="ورود دستی کد"
className="w-full max-w-xs text-center text-3xl p-4 border rounded-lg focus:ring-2 focus:ring-purple-500 outline-none"
/>
<select
value={warehouse}
onChange={(e) => setWarehouse(e.target.value)}
className="w-full max-w-xs text-center text-lg p-3 border rounded-lg focus:ring-2 focus:ring-purple-500 outline-none"
>
<option value="11">مرکزی</option>
<option value="13">انبار فروشگاه</option>
<option value="14">انبار کارگاه شارژ</option>
<option value="15">انبار کارگاه تعمیرات</option>
</select>
<button
onClick={handleGoToCounting}
disabled={!code}
className="w-full max-w-xs py-4 bg-green-500 hover:bg-green-600 disabled:bg-gray-300 text-white font-bold text-xl rounded-lg transition-colors"
>
شمارش
</button>
{/* Manual Input */}
<div className="w-full flex flex-col gap-4">
<AnimatePresence>
{lockError && (
<motion.div initial={{ opacity: 0, y: -10 }} animate={{ opacity: 1, y: 0 }} className="p-3 bg-red-50 text-red-600 text-xs rounded-[16px] text-center font-bold">
{lockError}
</motion.div>
)}
</AnimatePresence>
<div className="relative">
<div className="absolute inset-y-0 left-5 flex items-center pointer-events-none">
<Search className="text-gray-400" size={18} strokeWidth={2.5} />
</div>
<input
type={mode === 'SHELF' ? "text" : "number"}
dir="ltr"
value={code}
onChange={(e) => setCode(e.target.value)}
placeholder={mode === 'SHELF' ? "کد قفسه (مثال A-1)..." : "کد کالا..."}
className="w-full pl-12 pr-5 py-4 bg-white border border-gray-200 rounded-[24px] focus:outline-none focus:border-indigo-500 focus:ring-4 focus:ring-indigo-50 transition-all text-left text-lg font-bold text-gray-800 placeholder-gray-300 shadow-sm"
/>
</div>
<div className="relative">
<div className="absolute inset-y-0 left-5 flex items-center pointer-events-none">
<ChevronDown className="text-gray-400" size={18} strokeWidth={2.5} />
</div>
<select
value={warehouse}
onChange={(e) => setWarehouse(e.target.value)}
className="w-full appearance-none pl-12 pr-5 py-4 bg-white border border-gray-200 rounded-[24px] focus:outline-none focus:border-indigo-500 focus:ring-4 focus:ring-indigo-50 transition-all text-sm font-bold text-gray-700 shadow-sm"
>
{warehouses.map(wh => (
<option key={wh.id} value={wh.id}>{wh.name} ({wh.id})</option>
))}
</select>
</div>
<motion.button
whileTap={{ scale: 0.98 }}
onClick={handleGoToCounting}
disabled={!code || loading}
className={`w-full mt-4 py-4 text-white text-sm font-extrabold rounded-[24px] transition-all disabled:opacity-50 flex items-center justify-center gap-2 shadow-md ${mode === 'SHELF' ? 'bg-indigo-600 shadow-indigo-600/20' : 'bg-gray-900 shadow-gray-900/20'}`}
>
{loading ? (
<div className="w-5 h-5 border-2 border-white/30 border-t-white rounded-full animate-spin"></div>
) : mode === 'SHELF' ? (
<>
<Layers size={18} strokeWidth={2.5} />
ورود به قفسه و قفلگذاری
</>
) : (
<>
<Box size={18} strokeWidth={2.5} />
شروع شمارش کالا
</>
)}
</motion.button>
</div>
</div>
</div>
);
+258
View File
@@ -0,0 +1,258 @@
'use client';
import { useState, useEffect, useRef } from 'react';
import Header from '@/components/Header';
import { motion, AnimatePresence } from 'framer-motion';
import { Fingerprint, Lock, User, Save, Camera } from 'lucide-react';
import { startRegistration } from '@simplewebauthn/browser';
export default function SettingsPage() {
const [user, setUser] = useState(null);
const [name, setName] = useState('');
const [password, setPassword] = useState('');
const [avatarBase64, setAvatarBase64] = useState(null);
const [biometricEnabled, setBiometricEnabled] = useState(false);
const [loading, setLoading] = useState(false);
const [message, setMessage] = useState('');
const [isError, setIsError] = useState(false);
const fileInputRef = useRef(null);
useEffect(() => {
const userData = localStorage.getItem('user');
if (userData) {
const parsedUser = JSON.parse(userData);
setUser(parsedUser);
setName(parsedUser.name || '');
}
const bio = localStorage.getItem('biometric_enabled');
if (bio === 'true') setBiometricEnabled(true);
}, []);
const showToast = (msg, error = false) => {
setMessage(msg);
setIsError(error);
setTimeout(() => setMessage(''), 4000);
};
const handleBiometricToggle = async () => {
if (biometricEnabled) {
setBiometricEnabled(false);
localStorage.setItem('biometric_enabled', 'false');
showToast('ورود با اثر انگشت غیرفعال شد');
return;
}
try {
showToast('در حال آماده‌سازی سنسور...', false);
const res = await fetch('/api/auth/webauthn/register/generate-options', {
headers: { 'Authorization': `Bearer ${localStorage.getItem('token')}` }
});
const options = await res.json();
if (options.error) throw new Error(options.error);
// Trigger native biometric prompt
const attResp = await startRegistration(options);
const verificationRes = await fetch('/api/auth/webauthn/register/verify', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${localStorage.getItem('token')}`
},
body: JSON.stringify(attResp),
});
const verification = await verificationRes.json();
if (verification.verified) {
setBiometricEnabled(true);
localStorage.setItem('biometric_enabled', 'true');
showToast('اثر انگشت با موفقیت فعال شد');
} else {
throw new Error('Verification failed');
}
} catch (error) {
console.error(error);
showToast('خطا در فعال‌سازی یا لغو توسط کاربر', true);
}
};
const handleFileChange = (e) => {
const file = e.target.files[0];
if (file) {
const reader = new FileReader();
reader.onloadend = () => setAvatarBase64(reader.result);
reader.readAsDataURL(file);
}
};
const handleSave = async () => {
setLoading(true);
try {
const res = await fetch('/api/user/settings', {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${localStorage.getItem('token')}`
},
body: JSON.stringify({
name,
password: password ? password : undefined,
avatarUrl: avatarBase64 ? avatarBase64 : undefined
})
});
const data = await res.json();
if (res.ok) {
localStorage.setItem('user', JSON.stringify(data.user));
setUser(data.user);
setPassword('');
showToast('تغییرات شما با موفقیت ذخیره شد.');
} else {
showToast(data.error || 'خطا در ذخیره تغییرات', true);
}
} catch (err) {
showToast('خطا در ارتباط با سرور', true);
} finally {
setLoading(false);
}
};
const container = {
hidden: { opacity: 0 },
show: { opacity: 1, transition: { staggerChildren: 0.1 } }
};
const item = { hidden: { opacity: 0, y: 10 }, show: { opacity: 1, y: 0 } };
return (
<div className="w-full min-h-screen bg-[#F8FAFC] flex flex-col pb-20 relative">
<Header title="تنظیمات حساب" showBack={true} />
{/* Global Toast Notification */}
<AnimatePresence>
{message && (
<motion.div
initial={{ opacity: 0, y: 50, scale: 0.9 }}
animate={{ opacity: 1, y: 0, scale: 1 }}
exit={{ opacity: 0, y: 20, scale: 0.9 }}
className={`fixed bottom-8 left-1/2 -translate-x-1/2 z-[100] px-5 py-3 rounded-full shadow-[0_10px_40px_rgb(0,0,0,0.1)] backdrop-blur-xl border text-[11px] font-extrabold whitespace-nowrap flex items-center justify-center ${isError ? 'bg-red-500/95 border-red-400 text-white shadow-red-500/30' : 'bg-gray-800/95 border-gray-700 text-white shadow-gray-900/30'}`}
>
{message}
</motion.div>
)}
</AnimatePresence>
<motion.div variants={container} initial="hidden" animate="show" className="px-6 pt-2 flex flex-col gap-8">
<motion.section variants={item} className="flex flex-col gap-5 items-center">
<div className="relative group mt-2">
<div className="w-28 h-28 rounded-full shadow-[0_10px_40px_rgb(0,0,0,0.08)] overflow-hidden border-[4px] border-white bg-gradient-to-tr from-indigo-50 to-purple-50">
<img src={avatarBase64 || user?.avatarUrl || "/images/default_avatar.png"} alt="avatar" className="w-full h-full object-cover" />
</div>
<button
onClick={() => fileInputRef.current?.click()}
className="absolute bottom-0 right-0 w-10 h-10 bg-white border border-gray-100 text-indigo-500 rounded-full shadow-lg flex items-center justify-center hover:scale-105 active:scale-95 transition-all"
>
<Camera size={18} strokeWidth={2.5} />
</button>
<input type="file" ref={fileInputRef} onChange={handleFileChange} accept="image/*" className="hidden" />
</div>
<div className="text-center">
<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?.roles?.includes('ADMIN') ? 'مدیریت کل' : 'کاربر عادی'}</p>
</div>
</motion.section>
<motion.section variants={item} className="flex flex-col gap-4">
<h2 className="text-[11px] font-extrabold text-gray-400 mr-2 uppercase tracking-widest">مشخصات کاربری</h2>
<div className="bg-white/90 backdrop-blur-3xl border border-gray-100/50 rounded-[28px] shadow-[0_8px_30px_rgb(0,0,0,0.04)] p-2">
<div className="flex flex-col gap-2">
<div className="flex items-center gap-4 bg-gray-50/50 hover:bg-gray-50 p-4 rounded-[20px] transition-colors">
<div className="w-10 h-10 bg-white text-indigo-500 rounded-[14px] flex items-center justify-center shadow-sm">
<User size={18} strokeWidth={2.5} />
</div>
<div className="flex flex-col flex-1">
<label className="text-[10px] font-bold text-gray-400 mb-0.5">نام و نام خانوادگی</label>
<input
type="text"
value={name}
onChange={e => setName(e.target.value)}
className="bg-transparent border-none text-sm font-bold text-gray-800 outline-none w-full"
placeholder="نام شما"
/>
</div>
</div>
<div className="flex items-center gap-4 bg-gray-50/50 hover:bg-gray-50 p-4 rounded-[20px] transition-colors">
<div className="w-10 h-10 bg-white text-rose-500 rounded-[14px] flex items-center justify-center shadow-sm">
<Lock size={18} strokeWidth={2.5} />
</div>
<div className="flex flex-col flex-1">
<label className="text-[10px] font-bold text-gray-400 mb-0.5">رمز عبور جدید (اختیاری)</label>
<input
type="password"
dir="ltr"
value={password}
onChange={e => setPassword(e.target.value)}
className="bg-transparent border-none text-sm font-bold text-gray-800 outline-none w-full placeholder-gray-300"
placeholder="••••••••"
/>
</div>
</div>
</div>
</div>
</motion.section>
<motion.section variants={item} className="flex flex-col gap-4">
<h2 className="text-[11px] font-extrabold text-gray-400 mr-2 uppercase tracking-widest">امنیت</h2>
<div className="bg-white/90 backdrop-blur-3xl border border-gray-100/50 rounded-[28px] shadow-[0_8px_30px_rgb(0,0,0,0.04)] p-2">
<div className="flex items-center justify-between p-4 hover:bg-gray-50 rounded-[20px] transition-colors">
<div className="flex items-center gap-4">
<div className={`w-10 h-10 rounded-[14px] flex items-center justify-center transition-colors shadow-sm ${biometricEnabled ? 'bg-green-500 text-white shadow-green-500/20' : 'bg-gray-100 text-gray-400'}`}>
<Fingerprint size={18} strokeWidth={2.5} />
</div>
<div className="flex flex-col">
<span className="text-sm font-bold text-gray-800">ورود با اثر انگشت</span>
<span className="text-[10px] text-gray-400 font-medium mt-0.5">Face ID / Touch ID</span>
</div>
</div>
<button
onClick={handleBiometricToggle}
className={`relative flex items-center w-12 h-6 rounded-full px-1 transition-colors duration-300 ease-in-out shrink-0 ${biometricEnabled ? 'bg-green-500' : 'bg-gray-200'}`}
>
<motion.div
className="w-4 h-4 bg-white rounded-full shadow-sm"
animate={{ x: biometricEnabled ? -24 : 0 }}
transition={{ type: "spring", stiffness: 500, damping: 30 }}
/>
</button>
</div>
</div>
</motion.section>
<motion.div variants={item} className="mt-4">
<button
onClick={handleSave}
disabled={loading}
className="w-full py-4 bg-gradient-to-r from-gray-900 to-gray-800 hover:from-black hover:to-gray-900 text-white text-sm font-extrabold rounded-[20px] transition-all shadow-xl shadow-gray-900/20 disabled:opacity-70 flex items-center justify-center gap-2"
>
{loading ? (
<div className="w-5 h-5 border-2 border-white/30 border-t-white rounded-full animate-spin"></div>
) : (
<>
<Save size={18} strokeWidth={2.5} />
ذخیره اطلاعات
</>
)}
</button>
</motion.div>
</motion.div>
</div>
);
}
+65 -42
View File
@@ -3,11 +3,10 @@ import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import Link from 'next/link';
import { motion } from 'framer-motion';
import { LogOut, ChevronRight, Wifi, WifiOff } from 'lucide-react';
import { LogOut, ChevronRight, Settings } from 'lucide-react';
export default function Header({ title = 'داشبورد', showBack = false }) {
const [user, setUser] = useState(null);
const [isOnline, setIsOnline] = useState(true);
const router = useRouter();
useEffect(() => {
@@ -17,19 +16,6 @@ export default function Header({ title = 'داشبورد', showBack = false }) {
} else {
router.push('/');
}
setIsOnline(navigator.onLine);
const handleOnline = () => setIsOnline(true);
const handleOffline = () => setIsOnline(false);
window.addEventListener('online', handleOnline);
window.addEventListener('offline', handleOffline);
return () => {
window.removeEventListener('online', handleOnline);
window.removeEventListener('offline', handleOffline);
};
}, [router]);
const handleLogout = () => {
@@ -38,41 +24,78 @@ export default function Header({ title = 'داشبورد', showBack = false }) {
router.push('/');
};
const getInitial = (name) => {
if (!name) return 'U';
return name.charAt(0);
};
if (!showBack) {
return (
<motion.header
initial={{ y: -50, opacity: 0 }}
animate={{ y: 0, opacity: 1 }}
transition={{ type: 'spring', stiffness: 300, damping: 24 }}
className="mx-4 mt-6 mb-4 p-2 bg-white/70 backdrop-blur-xl border border-white rounded-[28px] flex items-center justify-between shadow-[0_8px_30px_rgb(0,0,0,0.04)]"
>
<Link href="/settings" className="flex items-center gap-3 hover:opacity-80 transition-opacity">
<div className="w-12 h-12 bg-gradient-to-tr from-purple-600 to-indigo-500 rounded-[20px] flex items-center justify-center text-white text-lg font-bold shadow-md shadow-purple-500/20 overflow-hidden">
{user?.avatarUrl ? (
<img src={user.avatarUrl} alt={user.name} className="w-full h-full object-cover" />
) : (
getInitial(user?.name)
)}
</div>
<div className="flex flex-col pr-1">
<span className="text-[10px] text-gray-400 font-extrabold tracking-wider mb-0.5">پردیس رایانه</span>
<span className="text-sm font-black text-gray-800 tracking-tight">
{user?.name || 'کاربر'}
</span>
</div>
</Link>
<div className="flex items-center gap-2 pl-1">
{user?.roles?.includes('ADMIN') && (
<Link
href="/admin"
className="w-10 h-10 bg-gray-50 text-gray-600 rounded-[18px] hover:bg-gray-100 transition-colors flex items-center justify-center"
title="پنل مدیریت"
>
<Settings size={18} strokeWidth={2.5} />
</Link>
)}
<button
onClick={handleLogout}
className="w-10 h-10 bg-red-50 text-red-500 rounded-[18px] hover:bg-red-100 transition-colors flex items-center justify-center"
title="خروج"
>
<LogOut size={18} strokeWidth={2.5} />
</button>
</div>
</motion.header>
);
}
// Inner pages sticky header
return (
<motion.header
initial={{ y: -50, opacity: 0 }}
initial={{ y: -20, opacity: 0 }}
animate={{ y: 0, opacity: 1 }}
transition={{ duration: 0.4, ease: [0.22, 1, 0.36, 1] }}
className="sticky top-0 z-50 w-full h-16 bg-white/70 backdrop-blur-xl border-b border-gray-200/50 flex items-center justify-between px-4 text-gray-800"
className="sticky top-4 z-50 mx-4 mb-6 p-2 bg-white/80 backdrop-blur-xl border border-white rounded-[24px] flex items-center justify-between shadow-[0_8px_30px_rgb(0,0,0,0.06)]"
>
<div className="flex items-center gap-2">
{showBack ? (
<button onClick={() => router.back()} className="p-2 hover:bg-gray-100 rounded-full transition-colors">
<ChevronRight size={20} className="text-gray-600" />
</button>
) : (
<button onClick={handleLogout} className="p-2 hover:bg-red-50 text-red-500 rounded-full transition-colors flex items-center justify-center">
<LogOut size={18} />
</button>
)}
</div>
<button
onClick={() => router.back()}
className="w-10 h-10 bg-gray-50 text-gray-700 rounded-[18px] hover:bg-gray-100 transition-all flex items-center justify-center"
>
<ChevronRight size={20} strokeWidth={2.5} />
</button>
<div className="font-extrabold text-sm tracking-tight text-gray-800">
<div className="font-extrabold text-sm text-gray-800 absolute left-1/2 -translate-x-1/2 whitespace-nowrap">
{title}
</div>
<div className="flex items-center gap-3">
<div className="flex flex-col items-end">
<span className="text-xs font-bold text-gray-700">{user?.name || 'کاربر'}</span>
{user?.role === 'ADMIN' && <Link href="/admin/locations" className="text-[10px] text-purple-600 font-bold hover:underline">مدیریت قفسهها</Link>}
</div>
<div className="flex items-center gap-1 bg-gray-50/50 p-1.5 rounded-full border border-gray-100">
{isOnline ? (
<Wifi size={14} className="text-green-500" />
) : (
<WifiOff size={14} className="text-red-500" />
)}
</div>
<div className="w-10 h-10 flex items-center justify-center">
{/* Decorative dot for symmetry */}
<div className="w-1.5 h-1.5 rounded-full bg-gray-300"></div>
</div>
</motion.header>
);
+6
View File
@@ -0,0 +1,6 @@
'use client';
import { ThemeProvider as NextThemesProvider } from 'next-themes';
export function ThemeProvider({ children }) {
return <NextThemesProvider attribute="class" defaultTheme="light">{children}</NextThemesProvider>;
}
+6
View File
@@ -11,3 +11,9 @@ export function verifyToken(token) {
return null;
}
}
export function hasRole(userRoles, allowedRoles) {
if (!userRoles || !Array.isArray(userRoles)) return false;
if (!Array.isArray(allowedRoles)) allowedRoles = [allowedRoles];
return allowedRoles.some(role => userRoles.includes(role));
}
+78
View File
@@ -0,0 +1,78 @@
import localforage from 'localforage';
localforage.config({
name: 'PardisCountingPWA',
storeName: 'offline_counts',
description: 'Stores counting records when device is offline'
});
/**
* Save a count to offline storage
*/
export async function saveCountOffline(payload) {
try {
const existing = await localforage.getItem('pending_counts') || [];
const record = { ...payload, is_offline: true, timestamp: new Date().toISOString() };
existing.push(record);
await localforage.setItem('pending_counts', existing);
return true;
} catch (error) {
console.error('Offline storage error:', error);
return false;
}
}
/**
* Get all pending offline counts
*/
export async function getPendingCounts() {
try {
return await localforage.getItem('pending_counts') || [];
} catch (error) {
return [];
}
}
/**
* Attempt to sync offline counts to the server
*/
export async function syncOfflineCounts() {
if (!navigator.onLine) return false;
try {
const pending = await getPendingCounts();
if (pending.length === 0) return true;
const token = localStorage.getItem('token');
const successful = [];
for (const record of pending) {
try {
const res = await fetch('/api/counting', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
},
body: JSON.stringify(record)
});
if (res.ok) {
successful.push(record.timestamp);
}
} catch (e) {
// failed to sync this record, keep it
}
}
// Remove successful records from local storage
const remaining = pending.filter(p => !successful.includes(p.timestamp));
await localforage.setItem('pending_counts', remaining);
return remaining.length === 0;
} catch (error) {
console.error('Sync error:', error);
return false;
}
}
+34
View File
@@ -0,0 +1,34 @@
const axios = require('axios');
async function test() {
const HESABFA_API_KEY = 'NCuDX3bksHlhXWGIqTvatvme3YTplxdF';
const HESABFA_TOKEN = '4ddb2fc517f6f6fe6d4b9bdd08fa0df31a564a62e12c4353eb9533ae63447b57ca87c479beb7f02b276929c861dad779';
try {
const res = await axios.post('https://api.hesabfa.com/v1/item/getitems', {
apiKey: HESABFA_API_KEY,
loginToken: HESABFA_TOKEN,
queryInfo: { Take: 5, Skip: 0 },
type: 0
});
console.log("getitems List:");
console.log(JSON.stringify(res.data.Result.List, null, 2));
if (res.data.Result.List.length > 0) {
const code = res.data.Result.List[0].Code;
console.log("Checking quantity for:", code);
const qRes = await axios.post('https://api.hesabfa.com/v1/item/GetQuantity2', {
apiKey: HESABFA_API_KEY,
loginToken: HESABFA_TOKEN,
codes: [code]
});
console.log("GetQuantity2:");
console.log(JSON.stringify(qRes.data, null, 2));
}
process.exit(0);
} catch(e) {
console.error(e.response ? e.response.data : e.message);
}
}
test();