feat: ultimate warehouse management features (blind count, offline sync, shelf locking, discrepancy dashboard)

This commit is contained in:
2026-06-12 08:28:14 +03:30
parent cd74012c52
commit cc85a78e45
19 changed files with 1273 additions and 29 deletions
+25
View File
@@ -20,6 +20,7 @@
"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",
@@ -4943,6 +4944,12 @@
"integrity": "sha512-gchesWBzyvGHRO9W8tzUWFDycow5gwjvFKfyV9FF32Y7F50yZMp7mP+T2mJIWFx49zicqyC4uefHM17o6xKIVQ==",
"license": "ISC"
},
"node_modules/immediate": {
"version": "3.0.6",
"resolved": "https://registry.npmjs.org/immediate/-/immediate-3.0.6.tgz",
"integrity": "sha512-XXOFtyqDjNDAQxVfYxuF7g9Il/IbWmmlQg2MYKOH8ExIT1qg6xc4zyS3HaEEATgs1btfzxq15ciUiY7gjSXRGQ==",
"license": "MIT"
},
"node_modules/inflight": {
"version": "1.0.6",
"resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz",
@@ -5558,6 +5565,15 @@
"node": ">=6"
}
},
"node_modules/lie": {
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/lie/-/lie-3.1.1.tgz",
"integrity": "sha512-RiNhHysUjhrDQntfYSfY4MU24coXXdEOgw9WGcKHNeEwffDYbF//u87M1EWaMGzuFoSbqW0C9C6lEEhDOAswfw==",
"license": "MIT",
"dependencies": {
"immediate": "~3.0.5"
}
},
"node_modules/lightningcss": {
"version": "1.32.0",
"resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.32.0.tgz",
@@ -5821,6 +5837,15 @@
"url": "https://opencollective.com/webpack"
}
},
"node_modules/localforage": {
"version": "1.10.0",
"resolved": "https://registry.npmjs.org/localforage/-/localforage-1.10.0.tgz",
"integrity": "sha512-14/H1aX7hzBBmmh7sGPd+AOMkkIrHM3Z1PAyGgZigA1H1p5O5ANnMyWzvpAETtG68/dC4pC0ncy3+PPGzXZHPg==",
"license": "Apache-2.0",
"dependencies": {
"lie": "3.1.1"
}
},
"node_modules/lodash": {
"version": "4.18.1",
"resolved": "https://registry.npmjs.org/lodash/-/lodash-4.18.1.tgz",
+1
View File
@@ -21,6 +21,7 @@
"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",
+34 -1
View File
@@ -19,12 +19,16 @@ model User {
password String
name String?
mobile String?
role Role @default(USER)
role Role @default(USER) // Deprecated, use roles instead
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")
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}
@@ -50,6 +54,10 @@ model Location {
sector String
row Int
countings Counting[]
isLocked Boolean @default(false)
lockedById Int?
lockedBy User? @relation("LocationLocks", fields: [lockedById], references: [id])
lockedAt DateTime?
createdAt DateTime @default(now())
}
@@ -66,6 +74,31 @@ 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
correctionNote 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
}
+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
+163
View File
@@ -0,0 +1,163 @@
'use client';
import { useState, useEffect } from 'react';
import Header from '@/components/Header';
import { AlertTriangle, CheckCircle, PackageSearch, RefreshCw, Send, ListTree, ArrowDownRight, ArrowUpRight } from 'lucide-react';
export default function DiscrepancyDashboard() {
const [warehouse, setWarehouse] = useState('11');
const [data, setData] = useState({ discrepancies: [], accurate: [] });
const [loading, setLoading] = useState(true);
useEffect(() => {
fetchData();
}, [warehouse]);
const fetchData = async () => {
setLoading(true);
try {
const res = await fetch(`/api/reports/discrepancies?warehouse=${warehouse}`);
if (res.ok) {
const result = await res.json();
setData(result);
}
} 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}) صادر شد.`);
};
return (
<div className="w-full min-h-screen bg-gray-50 flex flex-col pb-24">
<Header title="داشبورد مغایرت‌گیری" showBack={true} />
<div className="flex-1 px-4 md:px-8 pt-6 max-w-5xl mx-auto w-full flex flex-col gap-6">
{/* 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">
<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">
<ListTree size={20} />
</div>
<div>
<h2 className="text-sm font-bold text-gray-800">انتخاب انبار</h2>
<p className="text-xs text-gray-400">انبار مورد نظر برای بررسی مغایرت</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"
>
<option value="11">انبار مرکزی (11)</option>
<option value="13">انبار فروشگاه (13)</option>
<option value="14">انبار کارگاه شارژ (14)</option>
<option value="15">انبار کارگاه تعمیرات (15)</option>
</select>
<button onClick={fetchData} className="bg-gray-900 text-white p-3 rounded-xl hover:bg-gray-800 transition-colors">
<RefreshCw size={18} className={loading ? 'animate-spin' : ''} />
</button>
</div>
</div>
{/* Stats */}
<div className="grid grid-cols-2 gap-4">
<div className="bg-white border border-red-100 rounded-[24px] p-5 shadow-sm flex flex-col gap-2 relative overflow-hidden">
<div className="absolute top-0 right-0 w-16 h-16 bg-red-50 rounded-bl-[40px] flex items-center justify-center -mr-2 -mt-2">
<AlertTriangle className="text-red-500" size={20} />
</div>
<p className="text-xs font-bold text-gray-500">کالاهای دارای مغایرت</p>
<p className="text-3xl font-black text-red-600">{loading ? '-' : data.discrepancies.length}</p>
</div>
<div className="bg-white border border-green-100 rounded-[24px] p-5 shadow-sm flex flex-col gap-2 relative overflow-hidden">
<div className="absolute top-0 right-0 w-16 h-16 bg-green-50 rounded-bl-[40px] flex items-center justify-center -mr-2 -mt-2">
<CheckCircle className="text-green-500" size={20} />
</div>
<p className="text-xs font-bold text-gray-500">کالاهای بدون مغایرت</p>
<p className="text-3xl font-black text-green-600">{loading ? '-' : data.accurate.length}</p>
</div>
</div>
{/* Discrepancies List */}
<div className="bg-white rounded-[24px] shadow-sm border border-gray-100 overflow-hidden flex flex-col">
<div className="p-5 border-b border-gray-100 flex items-center gap-2">
<PackageSearch className="text-red-500" size={20} />
<h3 className="font-bold text-gray-800">لیست کالاهای مغایرتدار</h3>
</div>
<div className="p-0 overflow-x-auto">
<table className="w-full text-right text-sm">
<thead className="bg-gray-50 text-gray-500 text-xs font-bold">
<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">مغایرت</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">
{data.discrepancies.map((item, idx) => (
<tr key={idx} className="hover:bg-red-50/50 transition-colors">
<td className="px-6 py-4">
<p className="font-bold text-gray-800">{item.product_name}</p>
<p className="text-[10px] text-gray-400">کد: {item.product_id}</p>
</td>
<td className="px-6 py-4 font-bold text-gray-600">{item.system_expected}</td>
<td className="px-6 py-4 font-bold text-gray-900">{item.total_counted}</td>
<td className="px-6 py-4">
<div className={`inline-flex items-center gap-1 px-2.5 py-1 rounded-lg text-xs font-black ${item.difference > 0 ? 'bg-blue-100 text-blue-700' : 'bg-red-100 text-red-700'}`}>
{item.difference > 0 ? <ArrowUpRight size={14} /> : <ArrowDownRight size={14} />}
{Math.abs(item.difference)}
</div>
</td>
<td className="px-6 py-4 text-xs font-medium text-gray-500">
{item.locations.length > 0 ? item.locations.join('، ') : 'پیدا نشد'}
</td>
<td className="px-6 py-4 text-left">
<div className="flex items-center justify-end gap-2">
<button
onClick={() => handleRecount(item.product_id, item.product_name)}
className="bg-orange-50 text-orange-600 hover:bg-orange-100 px-3 py-1.5 rounded-lg text-xs font-bold transition-colors"
>
درخواست بازشماری
</button>
<button className="bg-gray-900 text-white hover:bg-gray-800 px-3 py-1.5 rounded-lg text-xs font-bold transition-colors flex items-center gap-1">
<Send size={12} />
ارسال تعدیل
</button>
</div>
</td>
</tr>
))}
{data.discrepancies.length === 0 && !loading && (
<tr>
<td colSpan="6" className="px-6 py-12 text-center text-gray-400 font-bold">
هیچ مغایرتی یافت نشد. همه چیز مرتب است! 🎉
</td>
</tr>
)}
{loading && (
<tr>
<td colSpan="6" className="px-6 py-12 text-center text-indigo-500 font-bold animate-pulse">
در حال پردازش و مقایسه اطلاعات...
</td>
</tr>
)}
</tbody>
</table>
</div>
</div>
</div>
</div>
);
}
+163
View File
@@ -0,0 +1,163 @@
'use client';
import { useState, useEffect } from 'react';
import { Save, EyeOff, ShieldCheck, Check } from 'lucide-react';
import { motion } from 'framer-motion';
export default function SettingsPage() {
const [settings, setSettings] = useState({
blind_counting: false,
correction_roles: ['ADMIN', 'SUPERVISOR']
});
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
const [saved, setSaved] = useState(false);
const availableRoles = [
{ id: 'ADMIN', label: 'مدیر کل' },
{ id: 'SUPERVISOR', label: 'سرپرست انبار' },
{ id: 'ACCOUNTANT', label: 'حسابدار' },
{ id: 'COUNTER', label: 'انبارگردان' }
];
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);
setSaved(false);
try {
const res = await fetch('/api/settings', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(settings)
});
if (res.ok) {
setSaved(true);
setTimeout(() => setSaved(false), 3000);
}
} catch (error) {
console.error(error);
} 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="p-8 flex justify-center"><div className="w-8 h-8 border-2 border-indigo-500 border-t-transparent rounded-full animate-spin"></div></div>;
return (
<div className="max-w-3xl mx-auto p-4 md:p-8 space-y-8">
<div>
<h1 className="text-2xl font-black text-gray-800 tracking-tight">تنظیمات سیستم</h1>
<p className="text-sm text-gray-500 font-medium mt-1">مدیریت قوانین انبارگردانی و دسترسیها</p>
</div>
<div className="bg-white rounded-[24px] p-6 shadow-sm border border-gray-100 space-y-8">
{/* Blind Counting Setting */}
<div className="flex items-start justify-between gap-4 border-b border-gray-50 pb-8">
<div>
<div className="flex items-center gap-2 mb-2">
<div className="w-8 h-8 rounded-xl bg-purple-50 text-purple-600 flex items-center justify-center">
<EyeOff size={18} />
</div>
<h2 className="text-base font-bold text-gray-800">شمارش کور (Blind Counting)</h2>
</div>
<p className="text-xs text-gray-500 leading-relaxed max-w-lg">
در صورت فعال بودن، انبارگردانها موجودی فعلی سیستم را نمیبینند و مجبورند به جای تایید کورکورانه، کالاها را به صورت واقعی بشمارند.
</p>
</div>
<button
onClick={() => setSettings(s => ({ ...s, blind_counting: !s.blind_counting }))}
className={`relative inline-flex h-7 w-14 items-center rounded-full transition-colors ${settings.blind_counting ? 'bg-indigo-600' : 'bg-gray-200'}`}
>
<span className={`inline-block h-5 w-5 transform rounded-full bg-white transition-transform shadow-sm ${settings.blind_counting ? '-translate-x-1.5' : '-translate-x-8'}`} />
</button>
</div>
{/* Correction Roles Setting */}
<div>
<div className="flex items-center gap-2 mb-2">
<div className="w-8 h-8 rounded-xl bg-blue-50 text-blue-600 flex items-center justify-center">
<ShieldCheck size={18} />
</div>
<h2 className="text-base font-bold text-gray-800">دسترسی ثبت اصلاحیه</h2>
</div>
<p className="text-xs text-gray-500 leading-relaxed mb-4">
وقتی انبارگردانی یک قفسه بسته میشود، چه نقشهایی اجازه دارند درخواست اصلاحیه ثبت کنند؟ (حالت چندانتخابی)
</p>
<div className="grid grid-cols-2 md:grid-cols-4 gap-3">
{availableRoles.map(role => {
const isSelected = settings.correction_roles?.includes(role.id);
return (
<button
key={role.id}
onClick={() => toggleRole(role.id)}
className={`flex items-center justify-between p-4 rounded-[16px] border text-xs font-bold transition-all ${
isSelected
? 'border-blue-500 bg-blue-50 text-blue-700'
: 'border-gray-200 bg-white text-gray-600 hover:border-gray-300'
}`}
>
{role.label}
{isSelected && <Check size={14} />}
</button>
);
})}
</div>
</div>
</div>
<div className="flex justify-end">
<motion.button
whileTap={{ scale: 0.97 }}
onClick={handleSave}
disabled={saving}
className="flex items-center gap-2 bg-gray-900 text-white px-8 py-4 rounded-[20px] text-sm font-bold 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>
) : saved ? (
<>
<Check size={18} />
ذخیره شد
</>
) : (
<>
<Save size={18} />
ذخیره تغییرات
</>
)}
</motion.button>
</div>
</div>
);
}
+4 -2
View File
@@ -24,9 +24,11 @@ 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 userRoles = Array.isArray(user.roles) ? user.roles : (user.role === 'ADMIN' ? ['ADMIN'] : ['COUNTER']);
return Response.json({ message: 'با موفقیت وارد شدید', token, user: { id: user.id, name: user.name, orgId: user.orgId, role: user.role, avatarUrl: user.avatarUrl } });
const token = signToken({ id: user.id, username: user.username, name: user.name, orgId: user.orgId, roles: userRoles, role: user.role });
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 });
@@ -41,8 +41,9 @@ export async function POST(req) {
where: { id: authenticator.id },
data: { counter: BigInt(verification.authenticationInfo.newCounter) }
});
const token = signToken({ id: user.id, username: user.username, name: user.name, role: user.role });
return NextResponse.json({ verified: true, token, user: { id: user.id, name: user.name, role: user.role } });
let userRoles = Array.isArray(user.roles) ? user.roles : (user.role === 'ADMIN' ? ['ADMIN'] : ['COUNTER']);
const token = signToken({ id: user.id, username: user.username, name: user.name, roles: userRoles, role: user.role });
return NextResponse.json({ verified: true, token, user: { id: user.id, name: user.name, roles: userRoles, role: user.role } });
}
return NextResponse.json({ verified: false }, { status: 400 });
} catch (error) {
+12 -2
View File
@@ -5,15 +5,25 @@ export async function POST(req) {
try {
const data = await req.json();
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: Number(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
}
});
+2 -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 {
+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 });
}
}
@@ -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 });
}
}
+45
View File
@@ -0,0 +1,45 @@
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'];
}
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 });
}
}
+227
View File
@@ -0,0 +1,227 @@
'use client';
import { useState, useEffect, Suspense } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import Header from '@/components/Header';
import { Box, Layers, CheckCircle2 } from 'lucide-react';
import { hasRole } from '@/lib/auth';
import { saveCountOffline, syncOfflineCounts } from '@/lib/offlineSync';
function ItemCountingContent() {
const router = useRouter();
const searchParams = useSearchParams();
const code = searchParams.get('code');
const warehouse = searchParams.get('warehouse');
const [user, setUser] = useState(null);
const [settings, setSettings] = useState({});
const [loading, setLoading] = useState(true);
const [productName, setProductName] = useState('');
const [oldCount, setOldCount] = useState(null);
const [shelfCode, setShelfCode] = useState('');
const [newCount, setNewCount] = useState('');
const [submitLoading, setSubmitLoading] = useState(false);
const [history, setHistory] = useState([]);
useEffect(() => {
const userData = localStorage.getItem('user');
if (userData) setUser(JSON.parse(userData));
fetchSettingsAndData();
window.addEventListener('online', syncOfflineCounts);
return () => window.removeEventListener('online', syncOfflineCounts);
}, [code, warehouse]);
const fetchSettingsAndData = async () => {
try {
const setRes = await fetch('/api/settings');
if (setRes.ok) {
const data = await setRes.json();
setSettings(data);
}
if (code) {
const nameRes = await fetch('/api/hesabfa', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ code, type: 'name' })
});
const nameData = await nameRes.json();
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];
const wInfo = productInfo?.Warehouse?.find(w => w.Code === Number(warehouse));
setOldCount(wInfo?.Quantity ?? 0);
}
} catch (e) {
console.error(e);
} finally {
setLoading(false);
}
};
const handleSubmit = async () => {
if (!shelfCode) return alert('کد قفسه را وارد کنید');
if (newCount === '' || newCount === null) return alert('تعداد را وارد کنید');
setSubmitLoading(true);
const payload = {
product_id: code,
product_name: productName,
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('');
} else {
alert('خطا در ثبت شمارش');
}
} catch (err) {
await saveCountOffline(payload);
alert('ارتباط با سرور قطع است. اطلاعات در گوشی شما ذخیره شد و بعداً ارسال می‌شود.');
setHistory([{ shelf: shelfCode.toUpperCase(), count: newCount, offline: true }, ...history]);
setShelfCode('');
setNewCount('');
} finally {
setSubmitLoading(false);
}
};
const handleFinish = () => {
router.push('/dashboard');
};
const isBlind = settings?.blind_counting && !hasRole(user?.roles, ['ADMIN', 'SUPERVISOR']);
if (loading) {
return <div className="min-h-screen flex items-center justify-center bg-gray-50"><div className="animate-pulse font-bold text-gray-500">در حال دریافت اطلاعات...</div></div>;
}
return (
<div className="w-full min-h-screen bg-gray-50 flex flex-col pb-24">
<Header title="انبارگردانی کالا" showBack={true} />
{/* Top Banner */}
<div className="bg-gray-900 text-white px-6 py-4 shadow-md flex items-center gap-3">
<div className="w-10 h-10 bg-white/10 rounded-xl flex items-center justify-center">
<Box size={20} />
</div>
<div className="flex-1">
<h2 className="text-sm font-bold leading-tight">{productName}</h2>
<p className="text-xs text-gray-400 mt-1 font-medium tracking-wider">کد: {code}</p>
</div>
{!isBlind && oldCount !== null && (
<div className="bg-white/10 px-3 py-2 rounded-xl flex flex-col items-center">
<span className="text-sm font-black">{oldCount}</span>
<span className="text-[10px] text-gray-300">سیستم</span>
</div>
)}
</div>
<div className="flex-1 p-4 md:p-6 max-w-md mx-auto w-full flex flex-col gap-6">
{/* Input Form */}
<div className="bg-white rounded-[24px] p-5 shadow-sm border border-gray-100 flex flex-col gap-4">
<h3 className="text-sm font-bold text-gray-800 mb-2">ثبت شمارش در قفسه</h3>
<div className="flex flex-col gap-3">
<div className="relative">
<div className="absolute inset-y-0 left-4 flex items-center pointer-events-none">
<Layers size={16} className="text-gray-400" />
</div>
<input
type="text"
dir="ltr"
value={shelfCode}
onChange={(e) => setShelfCode(e.target.value)}
placeholder="کد قفسه (مثال A-1)..."
className="w-full pl-10 pr-4 py-3 bg-gray-50 border border-gray-200 rounded-[16px] text-center text-sm font-bold text-gray-800 uppercase focus:outline-none focus:border-gray-500 focus:ring-2 focus:ring-gray-100 transition-all"
/>
</div>
<input
type="number"
dir="ltr"
value={newCount}
onChange={(e) => setNewCount(e.target.value)}
placeholder="تعداد یافت شده در این قفسه"
className="w-full border-2 border-gray-200 bg-white rounded-[16px] p-4 text-center text-xl font-black text-gray-800 focus:outline-none focus:border-gray-900 focus:ring-4 focus:ring-gray-100 transition-all placeholder:text-sm placeholder:font-medium placeholder:text-gray-300"
/>
<button
onClick={handleSubmit}
disabled={submitLoading || !newCount || !shelfCode}
className="w-full bg-gray-900 text-white p-4 rounded-[16px] shadow-md hover:bg-gray-800 transition-all disabled:opacity-50 text-sm font-bold 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>
) : (
<>
<CheckCircle2 size={18} />
ثبت رکورد
</>
)}
</button>
</div>
</div>
{/* History of this item in different shelves */}
{history.length > 0 && (
<div className="bg-white rounded-[24px] p-5 shadow-sm border border-gray-100">
<h3 className="text-xs font-bold text-gray-400 mb-4 px-2">مکانهای یافت شده</h3>
<div className="flex flex-col gap-3">
{history.map((item, idx) => (
<div key={idx} className="flex justify-between items-center bg-gray-50 p-3 rounded-[16px] border border-gray-100">
<div className="flex items-center gap-2">
<Layers size={16} className="text-gray-400" />
<span className="text-sm font-bold text-gray-800">قفسه {item.shelf}</span>
</div>
<div className="bg-gray-200 text-gray-800 px-3 py-1 rounded-lg text-sm font-black shadow-sm">
{item.count} عدد
</div>
</div>
))}
</div>
</div>
)}
<button
onClick={handleFinish}
className="w-full py-4 bg-white border-2 border-gray-200 text-gray-700 text-sm font-extrabold rounded-[20px] transition-all hover:bg-gray-50 mt-4"
>
پایان شمارش این کالا
</button>
</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>
);
}
+290
View File
@@ -0,0 +1,290 @@
'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, PlusCircle, Check, Box } from 'lucide-react';
import { hasRole } from '@/lib/auth';
import { saveCountOffline, syncOfflineCounts } from '@/lib/offlineSync';
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);
// Item scanning state
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);
// History of scanned items in this session
const [history, setHistory] = useState([]);
useEffect(() => {
const userData = localStorage.getItem('user');
if (userData) setUser(JSON.parse(userData));
fetchSettings();
// Attempt to sync offline counts when page loads and we're online
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) {
console.error(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 (code) => {
if (!code) return;
setItemLoading(true);
setProductName('');
setOldCount(null);
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();
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];
const wInfo = productInfo?.Warehouse?.find(w => w.Code === Number(warehouse));
setOldCount(wInfo?.Quantity ?? 0);
} catch (error) {
console.error(error);
setProductName('خطا در دریافت اطلاعات');
} finally {
setItemLoading(false);
}
};
const handleProductCodeChange = (e) => {
const code = e.target.value;
setProductCode(code);
};
const handleProductCodeKeyDown = (e) => {
if (e.key === 'Enter') {
fetchItemData(productCode);
}
};
const handleSubmitItem = async () => {
if (newCount === '' || newCount === null) {
alert('لطفاً تعداد را وارد کنید');
return;
}
setSubmitLoading(true);
const payload = {
product_id: productCode,
product_name: productName,
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('');
} else {
alert('خطا در ثبت کالا');
}
} catch (err) {
// Network error (offline or server down)
await saveCountOffline(payload);
alert('ارتباط با سرور قطع است. اطلاعات در گوشی شما ذخیره شد و به محض اتصال ارسال می‌شود.');
setHistory([{ code: productCode, name: productName, count: newCount, offline: true }, ...history]);
setProductCode('');
setProductName('');
setOldCount(null);
setNewCount('');
} finally {
setSubmitLoading(false);
}
};
const isBlind = settings?.blind_counting && !hasRole(user?.roles, ['ADMIN', 'SUPERVISOR']);
return (
<div className="w-full min-h-screen bg-gray-50 flex flex-col pb-24">
<Header title="انبارگردانی قفسه" showBack={true} />
{/* Top Banner */}
<div className="bg-indigo-600 text-white px-6 py-4 flex items-center justify-between shadow-md">
<div>
<p className="text-xs text-indigo-200 font-medium mb-1">شما در حال شمارش هستید</p>
<div className="flex items-center gap-2">
<Lock size={18} />
<h2 className="text-xl font-black">قفسه {shelfCode}</h2>
</div>
</div>
<button
onClick={handleFinishShelf}
className="bg-white/20 hover:bg-white/30 text-white text-xs font-bold py-2 px-4 rounded-xl transition-colors flex items-center gap-2 backdrop-blur-sm"
>
<Unlock size={14} />
خروج و پایان
</button>
</div>
<div className="flex-1 p-4 md:p-6 max-w-md mx-auto w-full flex flex-col gap-6">
{/* Scanner Input */}
<div className="bg-white rounded-[24px] p-5 shadow-sm border border-gray-100 flex flex-col gap-4 relative z-10">
<div className="flex items-center gap-2 mb-2 text-indigo-600">
<ScanLine size={18} />
<span className="text-sm font-bold text-gray-800">اسکن کالای جدید در این قفسه</span>
</div>
<div className="flex gap-2">
<input
type="number"
dir="ltr"
value={productCode}
onChange={handleProductCodeChange}
onKeyDown={handleProductCodeKeyDown}
placeholder="بارکد کالا..."
className="flex-1 bg-gray-50 border border-gray-200 rounded-[16px] px-4 py-3 text-lg font-bold text-gray-800 focus:outline-none focus:border-indigo-500 focus:ring-2 focus:ring-indigo-100 transition-all text-center"
/>
<button
onClick={() => fetchItemData(productCode)}
className="bg-indigo-50 text-indigo-600 p-3 rounded-[16px] flex items-center justify-center hover:bg-indigo-100 transition-colors"
>
<Search size={20} strokeWidth={2.5} />
</button>
</div>
{itemLoading && (
<div className="text-center py-4 text-xs font-bold text-indigo-500 animate-pulse">
در حال استعلام از حسابفا...
</div>
)}
{productName && !itemLoading && (
<div className="mt-2 pt-4 border-t border-gray-100 flex flex-col gap-4">
<div className="flex justify-between items-start">
<div>
<h3 className="font-bold text-gray-800 text-sm">{productName}</h3>
<p className="text-xs text-gray-400 mt-1">کد: {productCode}</p>
</div>
{!isBlind && oldCount !== null && (
<div className="bg-green-50 text-green-700 px-3 py-1.5 rounded-lg flex flex-col items-center">
<span className="text-sm font-black">{oldCount}</span>
<span className="text-[10px] font-bold">سیستم</span>
</div>
)}
</div>
<div className="flex items-center gap-3">
<input
type="number"
dir="ltr"
value={newCount}
onChange={(e) => setNewCount(e.target.value)}
placeholder="تعداد شمارش شده..."
className="flex-1 border-2 border-gray-200 bg-white rounded-[16px] p-3 text-center text-xl font-black text-gray-800 focus:outline-none focus:border-indigo-500 focus:ring-4 focus:ring-indigo-50 transition-all placeholder:text-sm placeholder:font-medium placeholder:text-gray-300"
/>
<button
onClick={handleSubmitItem}
disabled={submitLoading || !newCount}
className="bg-gray-900 text-white p-4 rounded-[16px] shadow-md hover:bg-gray-800 transition-all disabled:opacity-50"
>
{submitLoading ? <div className="w-6 h-6 border-2 border-white/30 border-t-white rounded-full animate-spin"></div> : <Check size={24} />}
</button>
</div>
</div>
)}
</div>
{/* History of this session */}
{history.length > 0 && (
<div className="bg-white rounded-[24px] p-5 shadow-sm border border-gray-100">
<h3 className="text-xs font-bold text-gray-400 mb-4 px-2">کالاهای ثبت شده در این قفسه</h3>
<div className="flex flex-col gap-3">
{history.map((item, idx) => (
<div key={idx} className="flex justify-between items-center bg-gray-50 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-white rounded-lg flex items-center justify-center text-gray-400 border border-gray-200">
<Box size={14} />
</div>
<div>
<p className="text-xs font-bold text-gray-800 line-clamp-1">{item.name}</p>
<p className="text-[10px] font-medium text-gray-400">{item.code} {item.offline && <span className="text-yellow-600 ml-1">(آفلاین)</span>}</p>
</div>
</div>
<div className="bg-indigo-100 text-indigo-700 px-3 py-1 rounded-lg text-sm font-black shadow-sm">
{item.count}
</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>
);
}
+84 -19
View File
@@ -3,31 +3,57 @@ import { useState } from 'react';
import { useRouter } from 'next/navigation';
import Header from '@/components/Header';
import dynamic from 'next/dynamic';
import { motion } from 'framer-motion';
import { ScanLine, Search, Box, X, ChevronDown, CheckCircle2 } from 'lucide-react';
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 router = useRouter();
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}`);
handleGoToCounting();
}, 500);
}
};
@@ -44,12 +70,30 @@ export default function ScanPage() {
return (
<div className="w-full min-h-screen bg-gray-50 flex flex-col pb-24">
<Header title="اسکن کالا" showBack={true} />
<Header title="شروع انبارگردانی" showBack={true} />
<div className="flex-1 px-6 pt-6 flex flex-col items-center max-w-md mx-auto w-full">
<div className="flex-1 px-4 md:px-6 pt-4 flex flex-col items-center max-w-md mx-auto w-full">
{/* Mode Switcher */}
<div className="w-full bg-white p-1.5 rounded-[20px] shadow-sm flex mb-6 border border-gray-100">
<button
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>
<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>
</div>
{/* Camera Area */}
<div className="w-full relative mb-8">
<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">
@@ -88,12 +132,14 @@ export default function ScanPage() {
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] bg-indigo-50 flex items-center justify-center text-indigo-500">
<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">برای اسکن بارکد کالا کلیک کنید</span>
<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>
)}
@@ -102,16 +148,24 @@ export default function ScanPage() {
{/* 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="number"
type={mode === 'SHELF' ? "text" : "number"}
dir="ltr"
value={code}
onChange={(e) => setCode(e.target.value)}
placeholder="ورود دستی کد کالا..."
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>
@@ -135,11 +189,22 @@ export default function ScanPage() {
<motion.button
whileTap={{ scale: 0.98 }}
onClick={handleGoToCounting}
disabled={!code}
className="w-full mt-4 py-4 bg-gray-900 text-white text-sm font-extrabold rounded-[24px] transition-all disabled:opacity-50 disabled:bg-gray-300 flex items-center justify-center gap-2 shadow-md shadow-gray-900/10"
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'}`}
>
{code ? <CheckCircle2 size={18} strokeWidth={2.5} /> : <Box size={18} strokeWidth={2.5} />}
{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>
+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;
}
}