Compare commits
17 Commits
6a8d214762
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
| d27aca2a3f | |||
| 37dd2e0f16 | |||
| fd9a57b96c | |||
| a8d9bff59e | |||
| 22e3fa1415 | |||
| 879745f15e | |||
| 4675d7ce27 | |||
| 8104224a5a | |||
| 73b87193e1 | |||
| aabcea3aeb | |||
| cc85a78e45 | |||
| cd74012c52 | |||
| 3b5f8240be | |||
| 1171b7f1e3 | |||
| 3649841e61 | |||
| dc0c617e77 | |||
| 2c2c03717d |
+10
-9
@@ -1,17 +1,18 @@
|
|||||||
# پایه تصویر Node.js (استفاده از نسخه slim به جای alpine برای جلوگیری از ارورهای شبکه و تحریم در سرورهای ایرانی)
|
# پایه تصویر Node.js (استفاده از نسخه ۲۰ به دلیل نیازمندیهای Tailwind v4 و WebAuthn)
|
||||||
FROM node:18-slim AS base
|
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
|
FROM base AS deps
|
||||||
RUN apt-get update && apt-get install -y openssl libc6
|
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
|
|
||||||
# کپی فایلهای نصب پکیج
|
# کپی فایلهای نصب پکیج
|
||||||
COPY package.json ./
|
COPY package.json package-lock.json* ./
|
||||||
COPY prisma ./prisma/
|
COPY prisma ./prisma/
|
||||||
|
|
||||||
# نصب پکیجها و دریافت باینریهای مناسب لینوکس
|
# استفاده از میرور قدرتمند و نصب با استفاده از لاکفایل برای سرعت بالا و مصرف رم پایین
|
||||||
RUN rm -rf package-lock.json && npm install
|
RUN npm config set registry https://registry.npmmirror.com/ && \
|
||||||
|
npm ci
|
||||||
RUN npx prisma generate
|
RUN npx prisma generate
|
||||||
|
|
||||||
# مرحله ۲: بیلد پروژه
|
# مرحله ۲: بیلد پروژه
|
||||||
@@ -23,6 +24,9 @@ COPY . .
|
|||||||
# غیرفعال کردن تلهمتری Next.js
|
# غیرفعال کردن تلهمتری Next.js
|
||||||
ENV NEXT_TELEMETRY_DISABLED=1
|
ENV NEXT_TELEMETRY_DISABLED=1
|
||||||
|
|
||||||
|
# محدود کردن مصرف رم Node.js برای جلوگیری از کرش کردن سرور (OOM Killer) در سرورهای ضعیف
|
||||||
|
ENV NODE_OPTIONS="--max-old-space-size=1024"
|
||||||
|
|
||||||
# بیلد پروژه
|
# بیلد پروژه
|
||||||
RUN npm run build
|
RUN npm run build
|
||||||
|
|
||||||
@@ -30,9 +34,6 @@ RUN npm run build
|
|||||||
FROM base AS runner
|
FROM base AS runner
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
|
|
||||||
# نصب openssl برای اجرای Prisma در محیط داکر
|
|
||||||
RUN apt-get update && apt-get install -y openssl && rm -rf /var/lib/apt/lists/*
|
|
||||||
|
|
||||||
ENV NODE_ENV=production
|
ENV NODE_ENV=production
|
||||||
ENV NEXT_TELEMETRY_DISABLED=1
|
ENV NEXT_TELEMETRY_DISABLED=1
|
||||||
|
|
||||||
|
|||||||
Generated
+25
@@ -20,6 +20,7 @@
|
|||||||
"framer-motion": "^12.40.0",
|
"framer-motion": "^12.40.0",
|
||||||
"jose": "^6.2.3",
|
"jose": "^6.2.3",
|
||||||
"jsonwebtoken": "^9.0.2",
|
"jsonwebtoken": "^9.0.2",
|
||||||
|
"localforage": "^1.10.0",
|
||||||
"lucide-react": "^1.17.0",
|
"lucide-react": "^1.17.0",
|
||||||
"next": "15.1.7",
|
"next": "15.1.7",
|
||||||
"next-themes": "^0.4.6",
|
"next-themes": "^0.4.6",
|
||||||
@@ -4943,6 +4944,12 @@
|
|||||||
"integrity": "sha512-gchesWBzyvGHRO9W8tzUWFDycow5gwjvFKfyV9FF32Y7F50yZMp7mP+T2mJIWFx49zicqyC4uefHM17o6xKIVQ==",
|
"integrity": "sha512-gchesWBzyvGHRO9W8tzUWFDycow5gwjvFKfyV9FF32Y7F50yZMp7mP+T2mJIWFx49zicqyC4uefHM17o6xKIVQ==",
|
||||||
"license": "ISC"
|
"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": {
|
"node_modules/inflight": {
|
||||||
"version": "1.0.6",
|
"version": "1.0.6",
|
||||||
"resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz",
|
"resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz",
|
||||||
@@ -5558,6 +5565,15 @@
|
|||||||
"node": ">=6"
|
"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": {
|
"node_modules/lightningcss": {
|
||||||
"version": "1.32.0",
|
"version": "1.32.0",
|
||||||
"resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.32.0.tgz",
|
"resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.32.0.tgz",
|
||||||
@@ -5821,6 +5837,15 @@
|
|||||||
"url": "https://opencollective.com/webpack"
|
"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": {
|
"node_modules/lodash": {
|
||||||
"version": "4.18.1",
|
"version": "4.18.1",
|
||||||
"resolved": "https://registry.npmjs.org/lodash/-/lodash-4.18.1.tgz",
|
"resolved": "https://registry.npmjs.org/lodash/-/lodash-4.18.1.tgz",
|
||||||
|
|||||||
@@ -21,6 +21,7 @@
|
|||||||
"framer-motion": "^12.40.0",
|
"framer-motion": "^12.40.0",
|
||||||
"jose": "^6.2.3",
|
"jose": "^6.2.3",
|
||||||
"jsonwebtoken": "^9.0.2",
|
"jsonwebtoken": "^9.0.2",
|
||||||
|
"localforage": "^1.10.0",
|
||||||
"lucide-react": "^1.17.0",
|
"lucide-react": "^1.17.0",
|
||||||
"next": "15.1.7",
|
"next": "15.1.7",
|
||||||
"next-themes": "^0.4.6",
|
"next-themes": "^0.4.6",
|
||||||
|
|||||||
+47
-7
@@ -5,11 +5,7 @@ datasource db {
|
|||||||
|
|
||||||
generator client {
|
generator client {
|
||||||
provider = "prisma-client-js"
|
provider = "prisma-client-js"
|
||||||
}
|
binaryTargets = ["native", "debian-openssl-3.0.x", "debian-openssl-1.1.x"]
|
||||||
|
|
||||||
enum Role {
|
|
||||||
USER
|
|
||||||
ADMIN
|
|
||||||
}
|
}
|
||||||
|
|
||||||
model User {
|
model User {
|
||||||
@@ -18,12 +14,16 @@ model User {
|
|||||||
password String
|
password String
|
||||||
name String?
|
name String?
|
||||||
mobile String?
|
mobile String?
|
||||||
role Role @default(USER)
|
roles Json? // e.g. ["COUNTER", "ACCOUNTANT", "SUPERVISOR", "ADMIN"]
|
||||||
orgId Int?
|
orgId Int?
|
||||||
avatarUrl String? @db.LongText
|
avatarUrl String? @db.LongText
|
||||||
challenge String? @db.Text
|
challenge String? @db.Text
|
||||||
countings Counting[]
|
countings Counting[]
|
||||||
authenticators Authenticator[]
|
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())
|
createdAt DateTime @default(now())
|
||||||
updatedAt DateTime @updatedAt
|
updatedAt DateTime @updatedAt
|
||||||
}
|
}
|
||||||
@@ -48,13 +48,18 @@ model Location {
|
|||||||
region Int
|
region Int
|
||||||
sector String
|
sector String
|
||||||
row Int
|
row Int
|
||||||
|
warehouse Int?
|
||||||
countings Counting[]
|
countings Counting[]
|
||||||
|
isLocked Boolean @default(false)
|
||||||
|
lockedById Int?
|
||||||
|
lockedBy User? @relation("LocationLocks", fields: [lockedById], references: [id])
|
||||||
|
lockedAt DateTime?
|
||||||
createdAt DateTime @default(now())
|
createdAt DateTime @default(now())
|
||||||
}
|
}
|
||||||
|
|
||||||
model Counting {
|
model Counting {
|
||||||
id Int @id @default(autoincrement())
|
id Int @id @default(autoincrement())
|
||||||
product_id Int
|
product_id String
|
||||||
product_name String
|
product_name String
|
||||||
warehouse Int
|
warehouse Int
|
||||||
|
|
||||||
@@ -65,6 +70,41 @@ model Counting {
|
|||||||
new_count Int
|
new_count Int
|
||||||
user_id Int
|
user_id Int
|
||||||
user User @relation(fields: [user_id], references: [id])
|
user User @relation(fields: [user_id], references: [id])
|
||||||
|
mode String @default("SHELF") // SHELF, ITEM, TASK
|
||||||
|
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())
|
createdAt DateTime @default(now())
|
||||||
updatedAt DateTime @updatedAt
|
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())
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"name": "پردیس رایانه - سیستم انبارگردانی",
|
"name": "سیستم انبارداری",
|
||||||
"short_name": "انبارگردانی",
|
"short_name": "انبارداری",
|
||||||
"description": "سیستم جامع مدیریت قفسهها و انبارگردانی",
|
"description": "سیستم جامع مدیریت قفسهها و انبارداری",
|
||||||
"start_url": "/",
|
"start_url": "/",
|
||||||
"display": "standalone",
|
"display": "standalone",
|
||||||
"background_color": "#ffffff",
|
"background_color": "#ffffff",
|
||||||
|
|||||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -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>
|
||||||
|
);
|
||||||
|
}
|
||||||
+301
-77
@@ -2,21 +2,55 @@
|
|||||||
import { useState, useEffect } from 'react';
|
import { useState, useEffect } from 'react';
|
||||||
import Header from '@/components/Header';
|
import Header from '@/components/Header';
|
||||||
import dynamic from 'next/dynamic';
|
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 });
|
const Scanner = dynamic(() => import('@yudiel/react-qr-scanner').then(mod => mod.Scanner), { ssr: false });
|
||||||
|
|
||||||
export default function AdminLocations() {
|
export default function AdminLocations() {
|
||||||
const [locations, setLocations] = useState([]);
|
const [locations, setLocations] = useState([]);
|
||||||
const [newCode, setNewCode] = useState('');
|
const [warehouses, setWarehouses] = useState([]);
|
||||||
const [loading, setLoading] = useState(false);
|
const [selectedWarehouse, setSelectedWarehouse] = useState('');
|
||||||
const [cameraEnabled, setCameraEnabled] = useState(false);
|
|
||||||
|
|
||||||
|
// 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 [camError, setCamError] = useState('');
|
||||||
const [activeFilter, setActiveFilter] = useState('all');
|
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(() => {
|
useEffect(() => {
|
||||||
fetchLocations();
|
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 () => {
|
const fetchLocations = async () => {
|
||||||
try {
|
try {
|
||||||
const res = await fetch('/api/locations');
|
const res = await fetch('/api/locations');
|
||||||
@@ -28,125 +62,243 @@ export default function AdminLocations() {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleAddLocation = async (codeValue) => {
|
// Smart Parser for the main code input
|
||||||
const targetCode = codeValue || newCode;
|
const handleFullCodeChange = (e) => {
|
||||||
if (!targetCode) return;
|
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);
|
setLoading(true);
|
||||||
try {
|
try {
|
||||||
const res = await fetch('/api/locations', {
|
const method = editingId ? 'PUT' : 'POST';
|
||||||
method: 'POST',
|
const url = editingId ? `/api/locations/${editingId}` : '/api/locations';
|
||||||
|
|
||||||
|
const res = await fetch(url, {
|
||||||
|
method,
|
||||||
headers: { 'Content-Type': 'application/json' },
|
headers: { 'Content-Type': 'application/json' },
|
||||||
body: JSON.stringify({ code: targetCode })
|
body: JSON.stringify({ code: generatedCode, warehouse: selectedWarehouse })
|
||||||
});
|
});
|
||||||
|
|
||||||
const data = await res.json();
|
const data = await res.json();
|
||||||
if (res.ok) {
|
if (res.ok) {
|
||||||
alert('قفسه با موفقیت ثبت شد!');
|
showToast(editingId ? 'قفسه با موفقیت ویرایش شد' : 'قفسه با موفقیت ثبت شد!');
|
||||||
setNewCode('');
|
setFloor(''); setRegion(''); setSector(''); setRow('');
|
||||||
|
setEditingId(null);
|
||||||
fetchLocations();
|
fetchLocations();
|
||||||
} else {
|
} else {
|
||||||
alert(data.error || 'خطا در ثبت قفسه');
|
showToast(data.error || 'خطا در ثبت قفسه', true);
|
||||||
}
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
alert('خطای شبکه');
|
showToast('خطای شبکه', true);
|
||||||
} finally {
|
} finally {
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
setCameraEnabled(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) => {
|
const handleScan = (detectedCodes) => {
|
||||||
if (detectedCodes && detectedCodes.length > 0) {
|
if (detectedCodes && detectedCodes.length > 0) {
|
||||||
const scannedValue = detectedCodes[0].rawValue;
|
const scannedValue = detectedCodes[0].rawValue.toUpperCase();
|
||||||
handleAddLocation(scannedValue);
|
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) => {
|
const handleError = (error) => {
|
||||||
console.error(error);
|
|
||||||
const msg = error?.message || error?.name || '';
|
const msg = error?.message || error?.name || '';
|
||||||
if (msg.includes('Requested device not found') || msg.includes('NotFoundError') || msg.includes('device not found')) {
|
if (msg.includes('Requested device not found')) {
|
||||||
setCamError('هیچ دوربینی روی این دستگاه یافت نشد. لطفاً از لپتاپ یا موبایل استفاده کنید.');
|
setCamError('دوربینی یافت نشد.');
|
||||||
} else {
|
} else {
|
||||||
setCamError(msg || 'خطا در دسترسی به دوربین. آیا از HTTPS یا localhost استفاده میکنید؟');
|
setCamError(msg || 'خطا در دسترسی به دوربین.');
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// استخراج طبقات یکتا برای ساخت دکمههای فیلتر
|
|
||||||
const floors = [...new Set(locations.map(loc => loc.floor))].sort();
|
const floors = [...new Set(locations.map(loc => loc.floor))].sort();
|
||||||
|
|
||||||
// اعمال فیلتر روی لیست قفسهها
|
let filteredLocations = locations;
|
||||||
const filteredLocations = activeFilter === 'all'
|
if (selectedWarehouse) {
|
||||||
? locations
|
filteredLocations = filteredLocations.filter(loc => loc.warehouse == selectedWarehouse);
|
||||||
: locations.filter(loc => loc.floor === activeFilter);
|
}
|
||||||
|
if (activeFilter !== 'all') {
|
||||||
|
filteredLocations = filteredLocations.filter(loc => loc.floor === activeFilter);
|
||||||
|
}
|
||||||
|
|
||||||
|
const generatedCodePreview = (floor || region || sector || row) ? `${floor.toUpperCase()}${region}${sector.toUpperCase()}${row}` : '';
|
||||||
|
|
||||||
return (
|
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 relative">
|
||||||
<Header title="مدیریت قفسه ها (ادمین)" showBack={true} />
|
<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">
|
{/* Action Box */}
|
||||||
<h2 className="font-bold mb-2">ثبت قفسه جدید</h2>
|
<div className="w-full bg-white rounded-[24px] p-5 shadow-sm border border-gray-100 flex flex-col gap-4">
|
||||||
<p className="text-xs text-gray-500 mb-4">
|
|
||||||
فرمت استاندارد شامل حروف و اعداد است.
|
|
||||||
مثال: C2F2 (طبقه C، منطقه 2، قطاع F، ردیف 2)
|
|
||||||
</p>
|
|
||||||
|
|
||||||
<div className="flex flex-col gap-3">
|
<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
|
<input
|
||||||
type="text"
|
type="text"
|
||||||
dir="ltr"
|
dir="ltr"
|
||||||
value={newCode}
|
onChange={handleFullCodeChange}
|
||||||
onChange={(e) => setNewCode(e.target.value)}
|
placeholder="C2F3"
|
||||||
placeholder="مثال: C2F2"
|
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"
|
||||||
className="w-full border p-2 rounded text-center uppercase font-bold"
|
|
||||||
/>
|
/>
|
||||||
<button
|
|
||||||
onClick={() => handleAddLocation(newCode)}
|
|
||||||
disabled={loading}
|
|
||||||
className="bg-purple-600 text-white font-bold py-2 rounded"
|
|
||||||
>
|
|
||||||
ثبت دستی
|
|
||||||
</button>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="mt-4 border-t pt-4">
|
<div className="grid grid-cols-4 gap-2">
|
||||||
{cameraEnabled ? (
|
<div className="flex flex-col gap-1">
|
||||||
<div className="w-full aspect-video relative flex flex-col items-center justify-center bg-gray-100 rounded">
|
<label className="text-[10px] text-gray-400 font-bold text-center">طبقه</label>
|
||||||
{camError ? (
|
<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 className="text-red-500 text-xs p-4 text-center">{camError}</div>
|
</div>
|
||||||
) : (
|
<div className="flex flex-col gap-1">
|
||||||
<Scanner onScan={handleScan} onError={handleError} />
|
<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" />
|
||||||
<button
|
</div>
|
||||||
onClick={() => { setCameraEnabled(false); setCamError(''); }}
|
<div className="flex flex-col gap-1">
|
||||||
className="absolute bottom-2 right-2 bg-red-500 text-white text-xs px-2 py-1 rounded z-10"
|
<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"
|
||||||
>
|
>
|
||||||
بستن دوربین
|
{camError ? (
|
||||||
</button>
|
<div className="text-red-400 text-xs p-4 text-center font-medium">{camError}</div>
|
||||||
</div>
|
) : (
|
||||||
) : (
|
<div className="w-full h-full [&>div]:!object-cover [&>div>video]:!object-cover">
|
||||||
<button
|
<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)}
|
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>
|
</div>
|
||||||
|
|
||||||
<div className="w-full bg-white p-4 rounded shadow border border-gray-200">
|
{/* List Section */}
|
||||||
<h2 className="font-bold mb-4">قفسه های ثبت شده ({filteredLocations.length})</h2>
|
<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 && (
|
{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
|
<button
|
||||||
onClick={() => setActiveFilter('all')}
|
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>
|
</button>
|
||||||
@@ -154,7 +306,7 @@ export default function AdminLocations() {
|
|||||||
<button
|
<button
|
||||||
key={floor}
|
key={floor}
|
||||||
onClick={() => setActiveFilter(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}
|
طبقه {floor}
|
||||||
</button>
|
</button>
|
||||||
@@ -162,18 +314,90 @@ export default function AdminLocations() {
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
<div className="flex flex-col gap-2 max-h-[300px] overflow-y-auto pr-1">
|
{/* Cards */}
|
||||||
{filteredLocations.map((loc) => (
|
<div className="flex flex-col gap-3">
|
||||||
<div key={loc.id} className="flex justify-between items-center bg-gray-50 p-2 rounded border border-gray-100 text-sm">
|
{filteredLocations.map((loc) => {
|
||||||
<span className="font-bold text-lg text-purple-700">{loc.code}</span>
|
const hasData = loc._count?.countings > 0;
|
||||||
<span className="text-gray-500 text-xs">طبقه {loc.floor} | منطقه {loc.region} | قطاع {loc.sector} | ردیف {loc.row}</span>
|
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>
|
</div>
|
||||||
))}
|
)}
|
||||||
{filteredLocations.length === 0 && <span className="text-center text-sm text-gray-400 py-4">موردی یافت نشد.</span>}
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</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>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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>
|
||||||
|
);
|
||||||
|
}
|
||||||
+58
-8
@@ -30,37 +30,87 @@ export default function AdminDashboard() {
|
|||||||
className="p-5 flex flex-col gap-4"
|
className="p-5 flex flex-col gap-4"
|
||||||
>
|
>
|
||||||
<div className="grid grid-cols-2 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}>
|
<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">
|
<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">
|
<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} />
|
<Layers strokeWidth={1.5} size={24} />
|
||||||
</div>
|
</div>
|
||||||
<span className="font-extrabold text-xs text-gray-700">مدیریت قفسهها</span>
|
<span className="font-extrabold text-xs text-center text-gray-700">مدیریت قفسهها</span>
|
||||||
</Link>
|
</Link>
|
||||||
</motion.div>
|
</motion.div>
|
||||||
|
|
||||||
<motion.div variants={item}>
|
<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">
|
<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">
|
<div className="w-12 h-12 bg-blue-50 text-blue-500 rounded-2xl flex items-center justify-center mb-1">
|
||||||
<BarChart3 strokeWidth={1.5} size={24} />
|
<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>
|
</div>
|
||||||
<span className="font-extrabold text-xs text-gray-700">آمار طبقات</span>
|
<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>
|
</Link>
|
||||||
</motion.div>
|
</motion.div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<motion.div variants={item}>
|
<motion.div variants={item}>
|
||||||
<div className="opacity-60 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 transition-all cursor-not-allowed">
|
<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="flex items-center gap-4">
|
||||||
<div className="w-10 h-10 bg-gray-100 text-gray-400 rounded-xl flex items-center justify-center">
|
<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} />
|
<Users strokeWidth={1.5} size={20} />
|
||||||
</div>
|
</div>
|
||||||
<span className="font-extrabold text-sm text-gray-500">مدیریت کاربران (به زودی)</span>
|
<span className="font-extrabold text-sm text-gray-800">کاربران</span>
|
||||||
</div>
|
</div>
|
||||||
<div className="w-8 h-8 bg-gray-50 rounded-full flex items-center justify-center">
|
<div className="w-8 h-8 bg-gray-50 rounded-full flex items-center justify-center">
|
||||||
<svg className="w-4 h-4 text-gray-300 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>
|
<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>
|
</div>
|
||||||
</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>
|
||||||
</motion.div>
|
</motion.div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -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>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -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>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -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>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -11,7 +11,11 @@ export default function AdminStats() {
|
|||||||
fetch('/api/admin/stats')
|
fetch('/api/admin/stats')
|
||||||
.then(res => res.json())
|
.then(res => res.json())
|
||||||
.then(data => {
|
.then(data => {
|
||||||
setStats(data);
|
if (Array.isArray(data)) {
|
||||||
|
setStats(data);
|
||||||
|
} else {
|
||||||
|
setStats([]);
|
||||||
|
}
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
});
|
});
|
||||||
}, []);
|
}, []);
|
||||||
|
|||||||
@@ -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>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -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>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -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>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -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 });
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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 });
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -24,9 +24,16 @@ export async function POST(req) {
|
|||||||
return Response.json({ error: 'رمز عبور اشتباه است.' }, { status: 401 });
|
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; }
|
||||||
|
}
|
||||||
|
|
||||||
return Response.json({ message: 'با موفقیت وارد شدید', token, user: { id: user.id, name: user.name, orgId: user.orgId, role: user.role, avatarUrl: user.avatarUrl } });
|
let userRoles = Array.isArray(parsedRoles) ? parsedRoles : ['COUNTER'];
|
||||||
|
|
||||||
|
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) {
|
} catch (error) {
|
||||||
console.error(error);
|
console.error(error);
|
||||||
return Response.json({ error: 'خطای سرور رخ داد.' }, { status: 500 });
|
return Response.json({ error: 'خطای سرور رخ داد.' }, { status: 500 });
|
||||||
|
|||||||
@@ -41,8 +41,14 @@ export async function POST(req) {
|
|||||||
where: { id: authenticator.id },
|
where: { id: authenticator.id },
|
||||||
data: { counter: BigInt(verification.authenticationInfo.newCounter) }
|
data: { counter: BigInt(verification.authenticationInfo.newCounter) }
|
||||||
});
|
});
|
||||||
const token = signToken({ id: user.id, username: user.username, name: user.name, role: user.role });
|
let parsedRoles = user.roles;
|
||||||
return NextResponse.json({ verified: true, token, user: { id: user.id, name: user.name, role: user.role } });
|
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 });
|
return NextResponse.json({ verified: false }, { status: 400 });
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
|||||||
@@ -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 });
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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 });
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -5,15 +5,25 @@ export async function POST(req) {
|
|||||||
try {
|
try {
|
||||||
const data = await req.json();
|
const data = await req.json();
|
||||||
|
|
||||||
const count = await prisma.counting.create({
|
if (data.shelfCode) {
|
||||||
data: {
|
await prisma.location.upsert({
|
||||||
product_id: Number(data.product_id),
|
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,
|
product_name: data.product_name,
|
||||||
warehouse: Number(data.warehouse),
|
warehouse: Number(data.warehouse),
|
||||||
shelfCode: data.shelfCode || null,
|
shelfCode: data.shelfCode ? data.shelfCode.toUpperCase() : null,
|
||||||
old_count: Number(data.old_count),
|
old_count: Number(data.old_count),
|
||||||
new_count: Number(data.new_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 {
|
try {
|
||||||
if (productId && warehouse) {
|
if (productId && warehouse) {
|
||||||
const lastCount = await prisma.counting.findFirst({
|
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' }
|
orderBy: { createdAt: 'desc' }
|
||||||
});
|
});
|
||||||
return NextResponse.json(lastCount || { message: -1 });
|
return NextResponse.json(lastCount || { message: -1 });
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
import { NextResponse } from 'next/server';
|
import { NextResponse } from 'next/server';
|
||||||
import axios from 'axios';
|
import axios from 'axios';
|
||||||
|
|
||||||
const HESABFA_API_KEY = 'NCuDX3bksHlhXWGIqTvatvme3YTplxdF';
|
const HESABFA_API_KEY = process.env.HESABFA_API_KEY || 'NCuDX3bksHlhXWGIqTvatvme3YTplxdF';
|
||||||
const HESABFA_TOKEN = '4ddb2fc517f6f6fe6d4b9bdd08fa0df31a564a62e12c4353eb9533ae63447b57ca87c479beb7f02b276929c861dad779';
|
const HESABFA_TOKEN = process.env.HESABFA_TOKEN || '4ddb2fc517f6f6fe6d4b9bdd08fa0df31a564a62e12c4353eb9533ae63447b57ca87c479beb7f02b276929c861dad779';
|
||||||
|
|
||||||
export async function POST(req) {
|
export async function POST(req) {
|
||||||
try {
|
try {
|
||||||
@@ -26,6 +26,16 @@ export async function POST(req) {
|
|||||||
return NextResponse.json(res.data);
|
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 });
|
return NextResponse.json({ error: 'نوع درخواست نامعتبر است' }, { status: 400 });
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
return NextResponse.json({ error: 'خطا در ارتباط با حسابفا' }, { status: 500 });
|
return NextResponse.json({ error: 'خطا در ارتباط با حسابفا' }, { status: 500 });
|
||||||
|
|||||||
@@ -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 });
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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 });
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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 });
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -4,6 +4,7 @@ import { NextResponse } from 'next/server';
|
|||||||
export async function GET() {
|
export async function GET() {
|
||||||
try {
|
try {
|
||||||
const locations = await prisma.location.findMany({
|
const locations = await prisma.location.findMany({
|
||||||
|
include: { _count: { select: { countings: true } } },
|
||||||
orderBy: [{ floor: 'asc' }, { region: 'asc' }, { sector: 'asc' }, { row: 'asc' }]
|
orderBy: [{ floor: 'asc' }, { region: 'asc' }, { sector: 'asc' }, { row: 'asc' }]
|
||||||
});
|
});
|
||||||
return NextResponse.json(locations);
|
return NextResponse.json(locations);
|
||||||
@@ -14,7 +15,7 @@ export async function GET() {
|
|||||||
|
|
||||||
export async function POST(req) {
|
export async function POST(req) {
|
||||||
try {
|
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)
|
// Pattern validation (e.g., C2F2 -> 1 Char, 1 Num, 1 Char, 1 Num)
|
||||||
const regex = /^([A-Za-z]+)(\d+)([A-Za-z]+)(\d+)$/;
|
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 [, floor, regionStr, sector, rowStr] = match;
|
||||||
const region = parseInt(regionStr, 10);
|
const region = parseInt(regionStr, 10);
|
||||||
const row = parseInt(rowStr, 10);
|
const row = parseInt(rowStr, 10);
|
||||||
|
const warehouseId = warehouse ? parseInt(warehouse, 10) : null;
|
||||||
|
|
||||||
const location = await prisma.location.upsert({
|
const location = await prisma.location.upsert({
|
||||||
where: { code: code.toUpperCase() },
|
where: { code: code.toUpperCase() },
|
||||||
update: {}, // if exists, do nothing or update timestamps
|
update: { warehouse: warehouseId }, // if exists, do nothing or update timestamps
|
||||||
create: {
|
create: {
|
||||||
code: code.toUpperCase(),
|
code: code.toUpperCase(),
|
||||||
floor,
|
floor,
|
||||||
region,
|
region,
|
||||||
sector,
|
sector,
|
||||||
row
|
row,
|
||||||
|
warehouse: warehouseId
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -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 });
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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 });
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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 });
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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 });
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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 });
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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 });
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -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
@@ -1,10 +1,54 @@
|
|||||||
'use client';
|
'use client';
|
||||||
|
import { useState, useEffect } from 'react';
|
||||||
import Header from '@/components/Header';
|
import Header from '@/components/Header';
|
||||||
import Link from 'next/link';
|
import Link from 'next/link';
|
||||||
import { motion } from 'framer-motion';
|
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() {
|
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 = {
|
const container = {
|
||||||
hidden: { opacity: 0 },
|
hidden: { opacity: 0 },
|
||||||
@@ -20,48 +64,107 @@ export default function Dashboard() {
|
|||||||
};
|
};
|
||||||
|
|
||||||
return (
|
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="داشبورد" />
|
<Header title="داشبورد" />
|
||||||
|
|
||||||
<motion.div
|
<motion.div
|
||||||
variants={container}
|
variants={container}
|
||||||
initial="hidden"
|
initial="hidden"
|
||||||
animate="show"
|
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">
|
<div className="grid grid-cols-2 gap-4">
|
||||||
<motion.div variants={item}>
|
<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">
|
<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>
|
</div>
|
||||||
<span className="font-extrabold text-xs text-gray-700">تاریخچه شمارش</span>
|
<span className="font-black text-xs text-gray-700">تاریخچه شمارش</span>
|
||||||
</Link>
|
</Link>
|
||||||
</motion.div>
|
</motion.div>
|
||||||
|
|
||||||
<motion.div variants={item}>
|
<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">
|
<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="w-12 h-12 bg-purple-50 text-purple-600 rounded-2xl flex items-center justify-center mb-1">
|
<div className="absolute top-0 right-0 w-16 h-16 bg-indigo-50/50 rounded-bl-full -z-0"></div>
|
||||||
<ScanLine strokeWidth={1.5} size={24} />
|
<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>
|
</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>
|
</Link>
|
||||||
</motion.div>
|
</motion.div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<motion.div variants={item}>
|
{/* Active Sessions */}
|
||||||
<Link href="/my-counts" className="bg-white/80 backdrop-blur-sm border border-gray-100 rounded-3xl shadow-[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">
|
{activeSessions.length > 0 && (
|
||||||
<div className="flex items-center gap-4">
|
<motion.div variants={item} className="flex flex-col gap-3 mt-2">
|
||||||
<div className="w-10 h-10 bg-green-50 text-green-600 rounded-xl flex items-center justify-center">
|
<h3 className="text-sm font-black text-gray-800 flex items-center gap-2 px-2">
|
||||||
<ListChecks strokeWidth={1.5} size={20} />
|
<span className="relative flex h-3 w-3">
|
||||||
</div>
|
<span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-indigo-400 opacity-75"></span>
|
||||||
<span className="font-extrabold text-sm text-gray-700">شمارشهای من</span>
|
<span className="relative inline-flex rounded-full h-3 w-3 bg-indigo-500"></span>
|
||||||
|
</span>
|
||||||
|
قفسههای باز شما (ناتمام)
|
||||||
|
</h3>
|
||||||
|
|
||||||
|
<div className="flex flex-col gap-3">
|
||||||
|
{activeSessions.map((session, idx) => (
|
||||||
|
<div key={idx} className="bg-white border border-indigo-100 rounded-[20px] p-4 flex items-center justify-between shadow-sm shadow-indigo-100/50">
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
<div className="w-10 h-10 bg-indigo-50 text-indigo-600 rounded-xl flex items-center justify-center">
|
||||||
|
<Layers size={18} />
|
||||||
|
</div>
|
||||||
|
<div className="flex flex-col">
|
||||||
|
<span className="text-xs font-black text-gray-800 tracking-widest uppercase">{session.code}</span>
|
||||||
|
<span className="text-[10px] text-gray-400 font-bold mt-1">انبار: {session.warehouse || '-'}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<Link
|
||||||
|
href={`/counting/shelf?code=${session.code}&warehouse=${session.warehouse}`}
|
||||||
|
className="bg-gray-900 text-white px-4 py-2.5 rounded-[12px] text-xs font-bold hover:bg-gray-800 transition-colors"
|
||||||
|
>
|
||||||
|
ادامه / پایان
|
||||||
|
</Link>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
</div>
|
</div>
|
||||||
<div className="w-8 h-8 bg-gray-50 rounded-full flex items-center justify-center">
|
</motion.div>
|
||||||
<svg className="w-4 h-4 text-gray-400 rotate-180" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M9 5l7 7-7 7" /></svg>
|
)}
|
||||||
|
|
||||||
|
{/* 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>
|
</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>
|
</motion.div>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|||||||
+176
-32
@@ -1,52 +1,196 @@
|
|||||||
'use client';
|
'use client';
|
||||||
import { useState, useEffect } from 'react';
|
import { useState, useEffect } from 'react';
|
||||||
import Header from '@/components/Header';
|
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() {
|
export default function HistoryPage() {
|
||||||
const [counts, setCounts] = useState([]);
|
const [counts, setCounts] = useState([]);
|
||||||
const [loading, setLoading] = useState(true);
|
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(() => {
|
useEffect(() => {
|
||||||
const fetchHistory = async () => {
|
const userData = localStorage.getItem('user');
|
||||||
try {
|
if (userData) setUser(JSON.parse(userData));
|
||||||
const res = await fetch(`/api/counting`);
|
|
||||||
if (res.ok) setCounts(await res.json());
|
fetchData();
|
||||||
} catch (e) {
|
|
||||||
console.error(e);
|
|
||||||
}
|
|
||||||
setLoading(false);
|
|
||||||
};
|
|
||||||
fetchHistory();
|
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
|
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 (
|
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} />
|
<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 ? (
|
{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 ? (
|
) : counts.length === 0 ? (
|
||||||
<div className="text-center text-gray-500 p-10">تاریخچه خالی است.</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">
|
||||||
counts.map(count => (
|
<History size={32} className="text-gray-300" />
|
||||||
<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>
|
</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>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
+12
-4
@@ -9,8 +9,8 @@ export const viewport = {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export const metadata = {
|
export const metadata = {
|
||||||
title: 'پردیس رایانه - انبارگردانی',
|
title: 'سیستم انبارداری',
|
||||||
description: 'اپلیکیشن انبارگردانی پردیس',
|
description: 'اپلیکیشن مدیریت انبار',
|
||||||
manifest: "/manifest.json",
|
manifest: "/manifest.json",
|
||||||
appleWebApp: {
|
appleWebApp: {
|
||||||
capable: true,
|
capable: true,
|
||||||
@@ -24,8 +24,16 @@ export default function RootLayout({ children }) {
|
|||||||
<html lang="fa" dir="rtl">
|
<html lang="fa" dir="rtl">
|
||||||
<body className="bg-gray-100 transition-colors">
|
<body className="bg-gray-100 transition-colors">
|
||||||
<main className="w-full min-h-screen flex flex-col justify-start items-center">
|
<main className="w-full min-h-screen flex flex-col justify-start items-center">
|
||||||
<div className="w-full max-w-md bg-white min-h-screen shadow-lg relative pb-16">
|
<div className="w-full max-w-md bg-white min-h-screen shadow-lg relative flex flex-col">
|
||||||
{children}
|
<div className="flex-1 pb-10">
|
||||||
|
{children}
|
||||||
|
</div>
|
||||||
|
<div className="w-full py-4 text-center mt-auto">
|
||||||
|
<p className="text-[9px] font-bold text-gray-300 dir-ltr tracking-widest uppercase">
|
||||||
|
<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>
|
</div>
|
||||||
</main>
|
</main>
|
||||||
</body>
|
</body>
|
||||||
|
|||||||
@@ -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>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
+6
-49
@@ -96,56 +96,13 @@ export default function EntryPage() {
|
|||||||
className="absolute inset-0 z-50 flex flex-col items-center justify-center bg-gray-50/50 backdrop-blur-md"
|
className="absolute inset-0 z-50 flex flex-col items-center justify-center bg-gray-50/50 backdrop-blur-md"
|
||||||
>
|
>
|
||||||
<motion.div
|
<motion.div
|
||||||
initial={{ scale: 0.5, opacity: 0, y: 20 }}
|
initial={{ scale: 0.5, opacity: 0, y: 10 }}
|
||||||
animate={{ scale: 1, opacity: 1, y: 0 }}
|
animate={{ scale: 1, opacity: 1, y: 0 }}
|
||||||
transition={{ duration: 0.8, ease: [0.22, 1, 0.36, 1], delay: 0.2 }}
|
transition={{ duration: 0.8, ease: [0.22, 1, 0.36, 1], delay: 0.2 }}
|
||||||
className="flex flex-col items-center"
|
className="flex items-center justify-center w-36 h-36"
|
||||||
>
|
>
|
||||||
<motion.div
|
<img src="/icons/icon-512x512.png" alt="انبارداری" className="w-full h-full object-contain drop-shadow-xl" />
|
||||||
className="w-24 h-24 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" />
|
|
||||||
</motion.div>
|
|
||||||
|
|
||||||
<motion.h1
|
|
||||||
initial={{ opacity: 0, y: 10 }}
|
|
||||||
animate={{ opacity: 1, y: 0 }}
|
|
||||||
transition={{ duration: 0.5, delay: 0.6 }}
|
|
||||||
className="text-2xl font-black text-gray-800 tracking-tight"
|
|
||||||
>
|
|
||||||
انبارگردانی هوشمند
|
|
||||||
</motion.h1>
|
|
||||||
|
|
||||||
<motion.p
|
|
||||||
initial={{ opacity: 0 }}
|
|
||||||
animate={{ opacity: 1 }}
|
|
||||||
transition={{ duration: 0.5, delay: 0.8 }}
|
|
||||||
className="text-sm text-gray-500 mt-2 font-medium"
|
|
||||||
>
|
|
||||||
مدیریت حرفهای انبار و قفسهها
|
|
||||||
</motion.p>
|
|
||||||
</motion.div>
|
</motion.div>
|
||||||
|
|
||||||
<motion.div
|
|
||||||
initial={{ opacity: 0 }}
|
|
||||||
animate={{ opacity: 1 }}
|
|
||||||
transition={{ duration: 1, delay: 1 }}
|
|
||||||
className="absolute bottom-12 flex flex-col items-center"
|
|
||||||
>
|
|
||||||
<div className="flex flex-col items-center justify-center opacity-40 hover:opacity-100 transition-opacity gap-1">
|
|
||||||
<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
|
|
||||||
initial={{ opacity: 0, width: 0 }}
|
|
||||||
animate={{ opacity: 1, width: "120px" }}
|
|
||||||
transition={{ duration: 1.5, delay: 0.5, ease: "easeInOut" }}
|
|
||||||
className="absolute bottom-6 h-1 bg-gradient-to-r from-purple-500 to-blue-500 rounded-full"
|
|
||||||
/>
|
|
||||||
</motion.div>
|
</motion.div>
|
||||||
) : showInstall ? (
|
) : showInstall ? (
|
||||||
<motion.div
|
<motion.div
|
||||||
@@ -156,8 +113,8 @@ export default function EntryPage() {
|
|||||||
transition={{ duration: 0.6 }}
|
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"
|
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-28 h-28 rounded-3xl shadow-sm border border-gray-100 mb-8 overflow-hidden flex items-center justify-center bg-white p-2">
|
<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-cover" />
|
<img src="/icons/icon-512x512.png" alt="انبارداری" className="w-full h-full object-contain drop-shadow-md" />
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<h2 className="text-2xl font-black text-gray-800 tracking-tight mb-3 text-center">
|
<h2 className="text-2xl font-black text-gray-800 tracking-tight mb-3 text-center">
|
||||||
@@ -235,7 +192,7 @@ export default function EntryPage() {
|
|||||||
className="flex flex-col items-center justify-center flex-1 pt-10"
|
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">
|
<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" />
|
<img src="/icons/icon-512x512.png" alt="انبارداری" className="w-full h-full object-cover" />
|
||||||
</div>
|
</div>
|
||||||
<h2 className="text-2xl font-black text-gray-800 tracking-tight mb-2">
|
<h2 className="text-2xl font-black text-gray-800 tracking-tight mb-2">
|
||||||
خوش آمدید
|
خوش آمدید
|
||||||
|
|||||||
+195
-61
@@ -3,30 +3,80 @@ import { useState, useEffect } from 'react';
|
|||||||
import { useRouter } from 'next/navigation';
|
import { useRouter } from 'next/navigation';
|
||||||
import Header from '@/components/Header';
|
import Header from '@/components/Header';
|
||||||
import dynamic from 'next/dynamic';
|
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 });
|
const Scanner = dynamic(() => import('@yudiel/react-qr-scanner').then(mod => mod.Scanner), { ssr: false });
|
||||||
|
|
||||||
export default function ScanPage() {
|
export default function ScanPage() {
|
||||||
|
const [mode, setMode] = useState('ITEM'); // 'ITEM' | 'SHELF'
|
||||||
const [code, setCode] = useState('');
|
const [code, setCode] = useState('');
|
||||||
const [warehouse, setWarehouse] = useState('11');
|
const [warehouse, setWarehouse] = useState('11');
|
||||||
const [cameraEnabled, setCameraEnabled] = useState(false);
|
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();
|
const router = useRouter();
|
||||||
|
|
||||||
const handleGoToCounting = () => {
|
useEffect(() => {
|
||||||
if (code) {
|
fetch('/api/settings')
|
||||||
router.push(`/counting?code=${code}&warehouse=${warehouse}`);
|
.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 = 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) => {
|
const handleScan = (detectedCodes) => {
|
||||||
if (detectedCodes && detectedCodes.length > 0) {
|
if (detectedCodes && detectedCodes.length > 0) {
|
||||||
const scannedValue = detectedCodes[0].rawValue;
|
const scannedValue = detectedCodes[0].rawValue;
|
||||||
setCode(scannedValue);
|
setCode(scannedValue);
|
||||||
setCameraEnabled(false);
|
setCameraEnabled(false);
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
router.push(`/counting?code=${scannedValue}&warehouse=${warehouse}`);
|
handleGoToCounting();
|
||||||
}, 1500);
|
}, 500);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -34,76 +84,160 @@ export default function ScanPage() {
|
|||||||
console.error(error);
|
console.error(error);
|
||||||
const msg = error?.message || error?.name || '';
|
const msg = error?.message || error?.name || '';
|
||||||
if (msg.includes('Requested device not found') || msg.includes('NotFoundError') || msg.includes('device not found')) {
|
if (msg.includes('Requested device not found') || msg.includes('NotFoundError') || msg.includes('device not found')) {
|
||||||
setCamError('هیچ دوربینی روی این دستگاه یافت نشد. لطفاً از لپتاپ یا موبایل استفاده کنید.');
|
setCamError('دوربینی روی این دستگاه یافت نشد. لطفاً از لپتاپ یا موبایل استفاده کنید.');
|
||||||
} else {
|
} else {
|
||||||
setCamError(msg || 'خطا در دسترسی به دوربین. آیا از HTTPS یا localhost استفاده میکنید؟');
|
setCamError(msg || 'خطا در دسترسی به دوربین.');
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
return (
|
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">
|
||||||
<Header title="اسکن کد کالا" showBack={true} />
|
<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">
|
{/* Mode Switcher */}
|
||||||
{cameraEnabled ? (
|
<div className="w-full bg-white p-1.5 rounded-[20px] shadow-sm flex mb-6 border border-gray-100">
|
||||||
<div className="w-full h-full relative">
|
{(settings?.enable_item_counting ?? true) && (
|
||||||
{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>
|
|
||||||
) : (
|
|
||||||
<button
|
<button
|
||||||
onClick={() => setCameraEnabled(true)}
|
onClick={() => { setMode('ITEM'); setCode(''); setLockError(''); }}
|
||||||
className="text-blue-500 font-bold px-4 py-2"
|
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>
|
||||||
)}
|
)}
|
||||||
|
{(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>
|
</div>
|
||||||
|
|
||||||
<p className="text-sm text-gray-500">کد کالا را اسکن یا وارد کنید</p>
|
{/* 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>
|
||||||
|
)}
|
||||||
|
|
||||||
<input
|
{/* Scanner Target Overlay */}
|
||||||
type="number"
|
<div className="absolute inset-0 pointer-events-none flex items-center justify-center">
|
||||||
dir="ltr"
|
<div className="w-48 h-48 border-2 border-white/40 rounded-3xl relative">
|
||||||
value={code}
|
<div className="absolute top-0 left-0 w-8 h-8 border-t-4 border-l-4 border-white rounded-tl-2xl"></div>
|
||||||
onChange={(e) => setCode(e.target.value)}
|
<div className="absolute top-0 right-0 w-8 h-8 border-t-4 border-r-4 border-white rounded-tr-2xl"></div>
|
||||||
placeholder="ورود دستی کد"
|
<div className="absolute bottom-0 left-0 w-8 h-8 border-b-4 border-l-4 border-white rounded-bl-2xl"></div>
|
||||||
className="w-full max-w-xs text-center text-3xl p-4 border rounded-lg focus:ring-2 focus:ring-purple-500 outline-none"
|
<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>
|
||||||
|
|
||||||
<select
|
<button
|
||||||
value={warehouse}
|
onClick={() => { setCameraEnabled(false); setCamError(''); }}
|
||||||
onChange={(e) => setWarehouse(e.target.value)}
|
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"
|
||||||
className="w-full max-w-xs text-center text-lg p-3 border rounded-lg focus:ring-2 focus:ring-purple-500 outline-none"
|
>
|
||||||
>
|
<X size={20} strokeWidth={2.5} />
|
||||||
<option value="11">مرکزی</option>
|
</button>
|
||||||
<option value="13">انبار فروشگاه</option>
|
</div>
|
||||||
<option value="14">انبار کارگاه شارژ</option>
|
) : (
|
||||||
<option value="15">انبار کارگاه تعمیرات</option>
|
<motion.button
|
||||||
</select>
|
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>
|
||||||
|
|
||||||
|
{/* 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>
|
||||||
|
|
||||||
<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>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -158,7 +158,7 @@ export default function SettingsPage() {
|
|||||||
|
|
||||||
<div className="text-center">
|
<div className="text-center">
|
||||||
<h3 className="text-lg font-black text-gray-800">{user?.name || 'کاربر'}</h3>
|
<h3 className="text-lg font-black text-gray-800">{user?.name || 'کاربر'}</h3>
|
||||||
<p className="text-xs text-gray-400 font-medium mt-1 uppercase tracking-wider">{user?.role === 'ADMIN' ? 'مدیریت کل' : 'کاربر عادی'}</p>
|
<p className="text-xs text-gray-400 font-medium mt-1 uppercase tracking-wider">{user?.roles?.includes('ADMIN') ? 'مدیریت کل' : 'کاربر عادی'}</p>
|
||||||
</div>
|
</div>
|
||||||
</motion.section>
|
</motion.section>
|
||||||
|
|
||||||
|
|||||||
@@ -30,7 +30,6 @@ export default function Header({ title = 'داشبورد', showBack = false }) {
|
|||||||
};
|
};
|
||||||
|
|
||||||
if (!showBack) {
|
if (!showBack) {
|
||||||
// Style 4: Modern Floating Island (Pill) Design
|
|
||||||
return (
|
return (
|
||||||
<motion.header
|
<motion.header
|
||||||
initial={{ y: -50, opacity: 0 }}
|
initial={{ y: -50, opacity: 0 }}
|
||||||
@@ -55,7 +54,7 @@ export default function Header({ title = 'داشبورد', showBack = false }) {
|
|||||||
</Link>
|
</Link>
|
||||||
|
|
||||||
<div className="flex items-center gap-2 pl-1">
|
<div className="flex items-center gap-2 pl-1">
|
||||||
{user?.role === 'ADMIN' && (
|
{user?.roles?.includes('ADMIN') && (
|
||||||
<Link
|
<Link
|
||||||
href="/admin"
|
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"
|
className="w-10 h-10 bg-gray-50 text-gray-600 rounded-[18px] hover:bg-gray-100 transition-colors flex items-center justify-center"
|
||||||
@@ -76,7 +75,7 @@ export default function Header({ title = 'داشبورد', showBack = false }) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Inner pages (showBack = true)
|
// Inner pages sticky header
|
||||||
return (
|
return (
|
||||||
<motion.header
|
<motion.header
|
||||||
initial={{ y: -20, opacity: 0 }}
|
initial={{ y: -20, opacity: 0 }}
|
||||||
@@ -90,7 +89,7 @@ export default function Header({ title = 'داشبورد', showBack = false }) {
|
|||||||
<ChevronRight size={20} strokeWidth={2.5} />
|
<ChevronRight size={20} strokeWidth={2.5} />
|
||||||
</button>
|
</button>
|
||||||
|
|
||||||
<div className="font-extrabold text-sm text-gray-800 absolute left-1/2 -translate-x-1/2">
|
<div className="font-extrabold text-sm text-gray-800 absolute left-1/2 -translate-x-1/2 whitespace-nowrap">
|
||||||
{title}
|
{title}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|||||||
@@ -11,3 +11,9 @@ export function verifyToken(token) {
|
|||||||
return null;
|
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));
|
||||||
|
}
|
||||||
|
|||||||
@@ -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;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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();
|
||||||
Reference in New Issue
Block a user