Compare commits
38
Commits
b44816aa98
...
prod-v11
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
31300728b6 | ||
|
|
42fb314834 | ||
|
|
264c7cc906 | ||
|
|
707e40e840 | ||
|
|
ca2c1bb8ce | ||
|
|
d38cf38bd9 | ||
|
|
a1220db844 | ||
|
|
1190ec42eb | ||
|
|
2747f9d4bb | ||
|
|
934b74ebbd | ||
|
|
dcc4d693f5 | ||
|
|
64bd292335 | ||
|
|
98c4b28815 | ||
|
|
aba9ba6486 | ||
|
|
965054093e | ||
|
|
3931baadd5 | ||
|
|
1bf55ba8a6 | ||
|
|
5458a2f99f | ||
|
|
df3ff4ea14 | ||
|
|
4b84844b54 | ||
|
|
ea6a377023 | ||
|
|
5400588751 | ||
|
|
0ea0322967 | ||
|
|
a84b33dde3 | ||
|
|
fbd34277c0 | ||
|
|
8c5f4ab770 | ||
|
|
af092fe4c8 | ||
|
|
e9fef5a104 | ||
|
|
4a3c226518 | ||
|
|
d85ede7d11 | ||
|
|
c7d860f431 | ||
|
|
b2aba2fcfe | ||
|
|
e560018273 | ||
|
|
856513b6d7 | ||
|
|
b326cf64bf | ||
|
|
da883a28c0 | ||
|
|
b6a1ce2ae7 | ||
|
|
64d80e15f8 |
@@ -1,343 +1,191 @@
|
|||||||
# Procurement Stack v1.3 — Dockerized (PostgreSQL + FastAPI + React + MinIO)
|
# ERP & PM Integrated Platform — Dockerized
|
||||||
|
## سامانه یکپارچه تدارکات، انبارداری، مدیریت پروژه (PM) و ربات هوشمند
|
||||||
|
|
||||||
Self-contained ship package: everything needed to run the stack is in this
|
مجموعه نرمافزاری یکپارچه و خودکفا (Self-contained) شامل تمامی سرویسها، ماژولها و تنظیمات زیرساختی مورد نیاز برای اجرا در محیط توسعه و عملیات:
|
||||||
folder — no external files or sibling folders required.
|
|
||||||
|
|
||||||
| Service | Container | Tech | Exposed port |
|
| سرویس | نام کانتینر | فناوری / کاربرد | پورت در دسترس |
|
||||||
|---|---|---|---|
|
|---|---|---|---|
|
||||||
| **postgres** | `procurement-postgres` | PostgreSQL 18 (one instance: `procurement` + `casdoor` DBs) | `5433` |
|
| **postgres** | `procurement-postgres` | PostgreSQL 18 (دیتابیس مشترک `procurement` + `casdoor`) | `5455:5432` |
|
||||||
| **minio** | `procurement-minio` | MinIO object storage (S3-compatible) | `9000` (API), `9001` (console) |
|
| **minio** | `procurement-minio` | MinIO Object Storage (S3-compatible) برای فایلها و پیشفاکتورها | `9000` (API), `9001` (کنسول) |
|
||||||
| **casdoor** | `procurement-casdoor` | Casdoor (OIDC identity provider) | `8080` |
|
| **casdoor** | `procurement-casdoor` | ارائهدهنده متمرکز هویت سازمانی (OIDC Provider) | `8080:8000` |
|
||||||
| **api** | `procurement-api` | FastAPI + SQLAlchemy (asyncpg) | `8000` |
|
| **api** | `procurement-api` | بکاند اصلی تدارکات و انبار (FastAPI + Asyncpg) | `8000:8000` |
|
||||||
| **frontend** | `procurement-frontend` | React 19 + Vite, served by nginx (internal) | via Traefik |
|
| **frontend** | `procurement-frontend` | فرانتاند وب ERP (React 19 + Vite + Tailwind) | سرو از طریق Traefik روی پورت `80` |
|
||||||
| **traefik** | `procurement-traefik` | Traefik v3 — public reverse proxy (edge) | `80` (web), `443` (websecure) |
|
| **pm-api** | `pm-api` | بکاند بومی مدیریت پروژه ساخت (FastAPI + Python 3.12) | درونشبکهای (زیرمسیر `/pm/api`) |
|
||||||
|
| **pm-frontend** | `pm-frontend` | فرانتاند پلتفرم PM (React 19 + تقویم شمسی + گانت + QC) | سرو از طریق Traefik روی `/pm` |
|
||||||
```
|
| **bot** | `procurement-bot` | ربات هوشمند بله با پردازش صوت و متن (DeepSeek LLM + STT) | ارتباط Long-polling با Bale |
|
||||||
Browser ──► Traefik :80 (edge)
|
| **db-backup** | `procurement-db-backup` | پشتیبانگیری خودکار زمانبندیشده از هر دو پایگاه داده | کانتینر دورهای در پسزمینه |
|
||||||
│
|
| **traefik** | `procurement-traefik` | ریورس پروکسی و مدیریت ترافیک لایه لبه (Traefik v3) | `80` (HTTP), `443` (HTTPS) |
|
||||||
├── Host(localhost) ──► frontend (nginx SPA :80)
|
|
||||||
│ │
|
|
||||||
│ └── /api/* proxy ──► api :8000 (/api/v1)
|
|
||||||
│
|
|
||||||
├── Host(api.localhost) ──► api :8000
|
|
||||||
├── Host(auth.localhost) ──► casdoor :8000 (OIDC login)
|
|
||||||
└── Host(s3/storage.localhost) ──► minio (API / console)
|
|
||||||
│
|
|
||||||
├── postgres :5432 (procurement + casdoor DBs)
|
|
||||||
└── minio :9000 (invoice/proforma files)
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 📁 Layout
|
## 🌐 معماری شبکه و هدایت ترافیک (Traefik Edge Routing)
|
||||||
|
|
||||||
```text
|
```text
|
||||||
v1.3/
|
┌────────────────────────┐
|
||||||
├── docker-compose.yml ← all paths are relative to this folder
|
│ Browser / Client │
|
||||||
├── docker-compose.prod.yml ← production overlay (real domains + HTTPS via Let's Encrypt)
|
└───────────┬────────────┘
|
||||||
├── start.ps1 ← PowerShell helper (build + start + status)
|
│ :80 / :443
|
||||||
├── mc.cmd ← MinIO Client helper (inspect the bucket)
|
▼
|
||||||
├── README.md
|
┌────────────────────────┐
|
||||||
|
│ Traefik v3 (Edge) │
|
||||||
|
└───────────┬────────────┘
|
||||||
|
│
|
||||||
|
┌────────────────────────────────────┼───────────────────────────────────┐
|
||||||
|
│ │ │
|
||||||
|
▼ (Host: localhost) ▼ (PathPrefix: /pm) ▼ (Host: api.localhost)
|
||||||
|
┌───────────────────────┐ ┌───────────────────────┐ ┌───────────────────────┐
|
||||||
|
│ frontend (React) │ │ pm-frontend / pm-api │ │ api (FastAPI Core) │
|
||||||
|
│ /api/* Proxy ───────┼────────────┼───────────────────────┼──────────►│ /api/v1/* │
|
||||||
|
└───────────────────────┘ └───────────────────────┘ └───────────┬───────────┘
|
||||||
|
│ │
|
||||||
|
├────────────────────────────────────┬──────────────────────────────────────┤
|
||||||
|
▼ ▼ ▼
|
||||||
|
┌───────────────────────┐ ┌───────────────────────┐ ┌───────────────────────┐
|
||||||
|
│ Casdoor OIDC (:8080) │ │ MinIO S3 (:9000) │ │ PostgreSQL 18 (:5455) │
|
||||||
|
│ Host: auth.localhost │ │ Host: s3 / storage │ │ procurement + casdoor │
|
||||||
|
└───────────────────────┘ └───────────────────────┘ └───────────────────────┘
|
||||||
|
▲
|
||||||
|
│ ثبت پیشنویس استعلام
|
||||||
|
┌────────┴──────────────┐
|
||||||
|
│ bot (Bale AI Agent) │
|
||||||
|
└───────────────────────┘
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 📁 ساختار پوشهها و اجزای مخزن
|
||||||
|
|
||||||
|
```text
|
||||||
|
ERP/
|
||||||
|
├── docker-compose.yml ← پیکربندی اصلی اجرای کامل تمام سرویسهای استک
|
||||||
|
├── docker-compose.prod.yml ← لایه تنظیمات عملیاتی (Let's Encrypt و دامنههای رسمی)
|
||||||
|
├── docker-compose.coolify.yml ← پیکربندی سازگار با استقرار بر روی Coolify
|
||||||
|
├── start.ps1 ← اسکریپت هلپر پاورشل برای ساخت و اجرا
|
||||||
|
├── mc.cmd ← ابزار خط فرمان MinIO Client برای مدیریت باکتها
|
||||||
|
├── README.md ← همین سند راهنما
|
||||||
|
├── backend/ ← سرویس بکاند اصلی تدارکات و انبار (procurement-api)
|
||||||
|
│ ├── app/
|
||||||
|
│ │ ├── db/ ← اتصال دیتابیس و توابع راهاندازی اسکیمای خودکار (init_db.py)
|
||||||
|
│ │ ├── models/ ← مدلهای پایگاهداده (procurement, inventory, catalog)
|
||||||
|
│ │ ├── routers/ ← اندپوینتهای API v1 (quotes, inventory, users, drafts, ...)
|
||||||
|
│ │ ├── schemas/ ← مدلهای اعتبارسنجی Pydantic
|
||||||
|
│ │ ├── services/ ← منطق بیزینس (انبارداری، استعلامها، ذخیرهسازی، ...)
|
||||||
|
│ │ ├── utils/ ← ابزارهای امنیتی، خطایابی، ریتلیمیت
|
||||||
|
│ │ ├── auth.py ← تایید توکن Casdoor و تفکیک دسترسیها
|
||||||
|
│ │ ├── config.py ← متغیرهای پیکربندی
|
||||||
|
│ │ └── main.py ← اسمبلی برنامه FastAPI و میدلورها
|
||||||
|
│ └── tools/ ← اسکریپتهای سیدینگ (seed_casdoor.py) و تستهای دود (Smoke)
|
||||||
|
├── frontend/ ← وباپلیکیشن اصلی ERP (procurement-frontend)
|
||||||
|
│ ├── src/
|
||||||
|
│ │ ├── components/ ← کامپوننتهای مشترک، لایهبندی و سوییچر پنلها
|
||||||
|
│ │ ├── pages/
|
||||||
|
│ │ │ ├── Admin/ ← پنل مدیریت سامانه و همگامسازی کاربران
|
||||||
|
│ │ │ ├── Auth/ ← صفحه ورود و احراز هویت
|
||||||
|
│ │ │ ├── Dashboard/ ← کارتابل استعلامها و تصمیمگیری خرید
|
||||||
|
│ │ │ ├── Inventory/ ← انبارداری (موجودی، ورود کالا، انتقال کارگاهی، کنترل روزانه)
|
||||||
|
│ │ │ ├── Organization/ ← ماتریس دسترسی پنلها و انتساب پروژهها
|
||||||
|
│ │ │ ├── Projects/ ← مدیریت پروژههای عمرانی
|
||||||
|
│ │ │ ├── Suppliers/ ← دستهبندی موضوعی و فهرست تأمینکنندگان
|
||||||
|
│ │ │ ├── Units/ ← سیستم کاتالوگ متریالها، تامینکنندگان و ضرایب تبدیل
|
||||||
|
│ │ │ └── Wizard/ ← ویزارد مرحلهای ثبت استعلام (با اتصال مستقیم به پیشنویس ربات)
|
||||||
|
│ │ ├── store/ ← مدیریت وضعیت با Zustand
|
||||||
|
│ │ └── App.tsx ← درخت روتها، گیتهای امنیتی پنلها و نقشها
|
||||||
|
├── pm/ ← پلتفرم مدیریت پروژه و کنترل کیفیت (پلتفرم آرامش)
|
||||||
|
│ ├── backend/ ← بکاند مستقل PM (FastAPI, CPM Engine, QC Service)
|
||||||
|
│ ├── frontend/ ← فرانتاند PM (گانت چارت شمسی، WBS، ثبت عیوب و بازرسی)
|
||||||
|
│ ├── sql/ ← اسکیما و اسکریپتهای اختصاصی پایگاه داده PM
|
||||||
|
│ └── API_CONTRACT.md ← قرارداد کامل اندپوینتهای PM
|
||||||
|
├── bot/ ← ایجنت هوشمند بله برای ثبت صوتی/متنی استعلامها
|
||||||
|
│ ├── app/ ← کلاینت Bale، پردازشگر STT صوتی، استخراج NLU با DeepSeek
|
||||||
|
│ ├── docs/SETUP.md ← راهنمای راهاندازی و اتصال توکن بله
|
||||||
|
│ └── requirements.txt
|
||||||
|
├── monitoring/ ← استک مانیتورینگ، متریکها و لاگها (پرومتئوس، گرافانا، لوکی)
|
||||||
|
├── infra/ ← تنظیمات وبهوک دیپلوی خودکار و کانفیگهای داینامیک Traefik
|
||||||
├── sql/
|
├── sql/
|
||||||
│ ├── migration.sql ← DB schema v2.6 (auto-runs on first boot)
|
│ ├── migration.sql ← اسکریپت اولیه پایه دیتابیس
|
||||||
│ └── 02-casdoor-db.sql ← creates the `casdoor` role+DB on the same instance
|
│ └── 02-casdoor-db.sql ← اسکریپت راهاندازی دیتابیس هویت Casdoor
|
||||||
├── infra/
|
└── tests/ ← تستهای یکپارچگی NLU و ویزارد استعلام
|
||||||
│ └── traefik-dynamic.yml ← Traefik shared middlewares (HTTP→HTTPS redirect)
|
|
||||||
├── docs/ ← ERDs + migration plan + auth guide
|
|
||||||
│ ├── erd.txt (v2.4 — old procurement schema)
|
|
||||||
│ ├── new erd.txt (v2.5 — material → supplier → category)
|
|
||||||
│ ├── NewERD.txt (v2.6 — integrated procurement + inventory)
|
|
||||||
│ ├── casdoor-auth.md (v2.6 — Casdoor login, roles, failure scenarios)
|
|
||||||
│ └── material-supplier-category-migration-plan.md
|
|
||||||
├── backend/ ← build context of the `api` service
|
|
||||||
│ ├── Dockerfile
|
|
||||||
│ ├── requirements.txt
|
|
||||||
│ ├── .dockerignore
|
|
||||||
│ ├── app/ (source code — procurement + inventory + auth)
|
|
||||||
│ └── tools/ (smoke-test + seed scripts, copied into the image)
|
|
||||||
└── frontend/ ← build context of the `frontend` service
|
|
||||||
├── Dockerfile
|
|
||||||
├── nginx.conf
|
|
||||||
├── .dockerignore
|
|
||||||
├── .env.example (copy to .env if you need a custom API base URL)
|
|
||||||
├── index.html
|
|
||||||
├── package.json
|
|
||||||
├── package-lock.json
|
|
||||||
├── tsconfig*.json
|
|
||||||
├── vite.config.ts
|
|
||||||
├── public/
|
|
||||||
└── src/
|
|
||||||
└── pages/
|
|
||||||
├── Dashboard/ (procurement office)
|
|
||||||
├── Wizard/ (add new offer)
|
|
||||||
├── Suppliers/ (suppliers & topics)
|
|
||||||
├── Projects/ (projects)
|
|
||||||
├── Units/ (unit conversions)
|
|
||||||
└── Inventory/ (warehouse management panel — React port)
|
|
||||||
```
|
```
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 🔐 Login
|
## 🔐 سیستم احراز هویت، ماتریس پنلها و کنترل دسترسی (RBAC)
|
||||||
|
|
||||||
The whole system is behind a login page (`/login`). Login is **in-page**:
|
سامانه از سیستم احراز هویت **Casdoor OIDC** بهره میبرد؛ ورود به صورت In-Page بوده و توکن JWT صادر شده توسط بکاند با JWKS اعتبارسنجی میشود.
|
||||||
the form (username / password) is sent to
|
|
||||||
`POST /api/v1/auth/login`; the backend exchanges it with Casdoor
|
|
||||||
(password grant), verifies the returned JWT, and starts the session —
|
|
||||||
no browser redirect to Casdoor.
|
|
||||||
|
|
||||||
- **مدیر پروژه (PM)** → lands in the inventory panel (their project) — can record
|
مدل دسترسی سامانه بر پایه **پنلها (`user_panels`)** بازطراحی شده است:
|
||||||
stock changes, manage the project's warehouses and confirm arrivals («کالاهای در راه»).
|
|
||||||
- **مدیر تدارکات / ادمین** → lands in the procurement office — can manage
|
|
||||||
quotes, suppliers, projects, and in the inventory panel: dashboard, daily control,
|
|
||||||
«کالاهای در راه» (receiving included) and «سازماندهی» (users, PMs, warehouses).
|
|
||||||
The «انبارها» and «تغییر موجودی» sections are PM-only.
|
|
||||||
|
|
||||||
**Developer Mode** (top-left button on the login page) is a 3-step flow for
|
### ۱. لایههای دسترسی پنلها
|
||||||
the admin (super user): ① superuser auth gate (admin credentials only) →
|
* **پنل تدارکات (`procurement`):**
|
||||||
② role switcher (ادمین / مدیر تدارکات / مدیر پروژه + project) → ③ session
|
* `full`: دسترسی کامل به کارتابل استعلامها، تایید یا رد پیشنهادها، تامینکنندگان و قیمتها.
|
||||||
activation by role (admin → **پنل مدیریت ادمین** at `/admin`, مدیر تدارکات →
|
* `limited`: فقط امکان ثبت استعلام جدید در ویزارد برای پروژههای منتسب به کاربر (کاربر پس از ورود مستقیماً به `/wizard` یا `/requester` هدایت میشود).
|
||||||
procurement office, مدیر پروژه → their project's inventory panel). It is
|
* **پنل انبارداری (`inventory`):**
|
||||||
controlled by the `VITE_ENABLE_DEV_LOGIN` env var (in Docker: the
|
* `full`: مشاهده موجودی همه انبارها، رهگیری «کالاهای در راه» و کارتابل تایید رسید.
|
||||||
`DEV_LOGIN_ENABLED` compose build arg, default `true` — set it to `false`
|
* `limited`: فقط مشاهده و مدیریت انبارهای پروژههای تحت عضویت، همراه با دسترسی به ثبت تغییر موجودی کارگاهی (`/inventory/change`).
|
||||||
for production builds).
|
* **پنل مدیریت پروژه (`pm`):**
|
||||||
|
* دسترسی به مشاهده یا ویرایش تسکها، چارت گانت، ثبت عیوب و فرمهای QC در `/panel/pm`.
|
||||||
|
|
||||||
| What | Where | Credentials |
|
### ۲. قوانین و نقش سرپرست پروژه (`supervisor`)
|
||||||
|---|---|---|
|
* کاربرانی با نقش `supervisor` تنها در صورتی مجاز به ورود به سامانه هستند که حداقل یک پروژه در جدول `user_project_members` یا `projects.pm_user_id` به آنها منتسب شده باشد. در غیر این صورت، پیام عدم تخصیص پروژه نمایش داده شده و اجازه ورود نخواهند داشت.
|
||||||
| App | http://localhost (via Traefik) | — |
|
|
||||||
| Casdoor console | http://localhost:8080 | admin credentials are set when you run the seeder (`CASDOOR_ADMIN_PW`) — never commit them |
|
|
||||||
| Seeded app users (org `inventory`) | `razaei` (admin), `mousavi` (مدیر تدارکات), `mohaghegh` (مدیر پروژه), `tester` (مدیر پروژه، پروژه «تست») | password from `CASDOOR_SEED_PASSWORD` (bcrypt-hashed at rest — see `backend/tools/seed_casdoor.py`) |
|
|
||||||
|
|
||||||
Run `backend/tools/seed_casdoor.py` once after the first boot to create the
|
|
||||||
Casdoor organization, application and users (idempotent). Full details —
|
|
||||||
addresses, credentials, role model, failure scenarios and the checklist —
|
|
||||||
are in [`docs/casdoor-auth.md`](docs/casdoor-auth.md).
|
|
||||||
|
|
||||||
> The **currently committed seed** (`backups/علی محقق/`) instead ships a
|
|
||||||
> single admin — `ali.mohaghegh` («علی محقق») — see
|
|
||||||
> [Restoring the committed seed data](#restoring-the-committed-seed-data).
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 🌐 Working with the deployed system (server)
|
## 🚀 راهنمای سریع راهاندازی محیط توسعه (Docker)
|
||||||
|
|
||||||
The production deployment of this stack runs on the server and is reachable
|
### پیشنیازها
|
||||||
at these public addresses (HTTPS):
|
* Docker Desktop (ویندوز) یا Docker Engine + Docker Compose Plugin (لینوکس)
|
||||||
|
* حداقل ۴ گیگابایت فضای خالی دیسک و اتصال اینترنت برای بارگیری ایمیجهای اولیه
|
||||||
|
|
||||||
| What | Address |
|
### دستورات اجرا
|
||||||
|---|---|
|
|
||||||
| **App (ERP)** | https://aramesh.bennu-api-bahrestan.ir/ |
|
|
||||||
| **Casdoor admin panel** | https://casdoor.bennu-api-bahrestan.ir/ |
|
|
||||||
|
|
||||||
Log in to the app with your Casdoor account (org `inventory`); the role is
|
|
||||||
assigned inside the app (`users.role` — see «Login» above and
|
|
||||||
[`docs/casdoor-auth.md`](docs/casdoor-auth.md)).
|
|
||||||
|
|
||||||
### MinIO console on the server (SSH tunnel)
|
|
||||||
|
|
||||||
The MinIO console is deliberately **loopback-only** on the server
|
|
||||||
(`127.0.0.1:9001`) — verified unreachable from the internet — so the way in
|
|
||||||
is an SSH tunnel from your machine:
|
|
||||||
|
|
||||||
1. Open PowerShell and start the tunnel (**keep the window open** while you
|
|
||||||
use the panel):
|
|
||||||
|
|
||||||
```powershell
|
```powershell
|
||||||
ssh -L 9001:127.0.0.1:9001 <user>@<server-host>
|
# ۱. رفتن به پوشه پروژه و ساخت/اجرای کانتینرها
|
||||||
```
|
|
||||||
|
|
||||||
You will also land in a normal SSH session — that is fine; the tunnel
|
|
||||||
lives as long as the window stays open.
|
|
||||||
|
|
||||||
2. In your browser, open: **http://localhost:9001**
|
|
||||||
|
|
||||||
3. Log in with the production MinIO root credentials from the server's
|
|
||||||
`/srv/erp/.env` (`MINIO_ROOT_USER` / `MINIO_ROOT_PASSWORD`) — they are
|
|
||||||
**never** written in this repo or its history. See
|
|
||||||
[`docs/SECRET-MANAGEMENT.md`](docs/SECRET-MANAGEMENT.md).
|
|
||||||
|
|
||||||
You will see the **`procurement-files`** bucket — the invoices/proformas the
|
|
||||||
ERP stores, browsable and downloadable from there.
|
|
||||||
|
|
||||||
⚠️ Those credentials are **full admin access to the file storage**. They live
|
|
||||||
only in the server-side `.env`; if one ever leaks, rotate it immediately
|
|
||||||
(checklist in `docs/SECRET-MANAGEMENT.md`).
|
|
||||||
|
|
||||||
Close the PowerShell window (or `Ctrl+C`) when you are done to drop the
|
|
||||||
tunnel.
|
|
||||||
|
|
||||||
Notes from the server setup:
|
|
||||||
|
|
||||||
- The panel is published only on the server's loopback, so the internet
|
|
||||||
cannot reach it at all — the tunnel is what carries it to your browser.
|
|
||||||
- Host port `9000` stays reserved for the deploy-webhook receiver, which is
|
|
||||||
why the console uses `9001`.
|
|
||||||
- If you ever need the raw S3 API from your machine, or a clickable URL for
|
|
||||||
the console (e.g. `storage.aramesh.bennu-api-bahrestan.ir` behind Traefik
|
|
||||||
with a password prompt on top), that can be arranged on request — the
|
|
||||||
tunnel remains the safer default.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Prerequisites (target machine)
|
|
||||||
|
|
||||||
- **Docker Desktop** (Windows) or Docker Engine + Compose plugin (Linux/macOS)
|
|
||||||
- ~3–4 GB free disk for images (`postgres:18`, `python:3.13-slim`, `node:22-alpine`, `nginx:alpine`, `minio/minio`, `minio/mc`)
|
|
||||||
- Internet access on first build (image + `npm ci` downloads)
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Start the whole stack
|
|
||||||
|
|
||||||
```powershell
|
|
||||||
cd <this-folder>
|
|
||||||
docker compose up -d --build
|
docker compose up -d --build
|
||||||
```
|
|
||||||
|
|
||||||
First run downloads base images and builds the frontend (takes a few minutes).
|
# ۲. بررسی وضعیت سلامت سرویسها
|
||||||
Subsequent runs: `docker compose up -d`.
|
|
||||||
|
|
||||||
Wait until all services are up:
|
|
||||||
|
|
||||||
```powershell
|
|
||||||
docker compose ps
|
docker compose ps
|
||||||
```
|
```
|
||||||
|
|
||||||
All should show `Up` (postgres also `(healthy)`).
|
تمام سرویسها باید وضعیت `Up` و دیتابیس وضعیت `(healthy)` را نشان دهند.
|
||||||
|
|
||||||
|
### درگاهها و آدرسهای محلی
|
||||||
|
|
||||||
|
| بخش | آدرس محلی | توضیحات |
|
||||||
|
|---|---|---|
|
||||||
|
| **رابط کاربری ERP** | http://localhost | داشبورد اصلی سامانه |
|
||||||
|
| **پلتفرم PM** | http://localhost/pm | مدیریت پروژه و کنترل کیفیت (قابل دسترس در `/panel/pm`) |
|
||||||
|
| **مستندات API (Swagger)** | http://localhost:8000/docs | مستندات تعاملی اندپوینتهای تدارکات |
|
||||||
|
| **سلامت API** | http://localhost:8000/health/ready | بررسی اتصال دیتابیس، Casdoor و MinIO |
|
||||||
|
| **کنسول MinIO** | http://localhost:9001 | نام کاربری و رمز پیشفرض: `minioadmin` / `minioadmin` |
|
||||||
|
| **کنسول Casdoor** | http://localhost:8080 | نام کاربری و رمز اولیه: `admin` / `123` |
|
||||||
|
| **پایگاه داده PostgreSQL** | `localhost:5455` | نام دیتابیس: `procurement`، کاربر: `postgres` |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Verify
|
## 🤖 ربات هوشمند بله (`procurement-bot`)
|
||||||
|
|
||||||
| What | Where |
|
ربات پیامرسان بله به عنوان یک سرویس اختصاصی درون شبکه فعال است:
|
||||||
|---|---|
|
1. پیام صوتی یا متنی فرستاده شده از طریق هوش مصنوعی (DeepSeek NLU) و تبدیل صوت به متن پردازش میشود.
|
||||||
| Frontend UI | http://localhost |
|
2. قلمها، متریالها، پروژهها و تامینکنندگان به صورت فازی جستجو و شناسایی میشوند.
|
||||||
| API docs (Swagger) | http://localhost:8000/docs |
|
3. پیشنویس در جدول `bot_drafts` ذخیره شده و شناسه پیشنویس تولید میشود.
|
||||||
| API health | http://localhost:8000/health → `{"status":"ok","service":"procurement-api"}` |
|
4. کاربر میتواند با زدن دکمه روی بله یا مراجعه به لینک مستقیم:
|
||||||
| API readiness (DB + MinIO + Casdoor) | http://localhost:8000/health/ready |
|
`http://localhost/wizard?draft=<UUID>`
|
||||||
| Metrics | http://localhost:8000/metrics |
|
اطلاعات استخراجشده را در ویزارد فرانتاند مرور، تکمیل و نهایی کند.
|
||||||
| MinIO console | http://localhost:9001 (user/pass `minioadmin`/`minioadmin`) |
|
5. راهنمای تکمیلی تنظیم توکن در [bot/docs/SETUP.md](file:///c:/Users/Reza/Desktop/v1.6/bot/docs/SETUP.md) قرار دارد.
|
||||||
| Database | `localhost:5433`, db `procurement`, user/pass `postgres`/`postgres` (Casdoor uses the same instance, db `casdoor`) |
|
|
||||||
|
|
||||||
Automated end-to-end checks (authenticates via `SMOKE_USER` /
|
|
||||||
`SMOKE_PASSWORD` — the seeder users):
|
|
||||||
|
|
||||||
```powershell
|
|
||||||
backend\tools\smoke_test.py # read paths
|
|
||||||
backend\tools\smoke_test_write.py / smoke_test_misc.py
|
|
||||||
```
|
|
||||||
|
|
||||||
> Every API route now requires a Casdoor JWT — a bare
|
|
||||||
> `curl http://localhost/api/v1/quotes` returns **401** by design.
|
|
||||||
> Day-2 operations (deploys, backups, monitoring): [`docs/OPERATIONS.md`](docs/OPERATIONS.md).
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## MinIO (object storage for invoice / proforma files)
|
## 🔄 انتقال بینکارگاهی کالاها (`project_transfers`)
|
||||||
|
|
||||||
| Item | Value |
|
سامانه دارای سیستم ردیابی انتقال متریال بین کارگاههاست:
|
||||||
|---|---|
|
* ثبت انتقال از طریق صفحه «تغییر موجودی» با نوع `انتقال بین کارگاهی`.
|
||||||
| S3 API endpoint | `localhost:9000` (from the API container: `minio:9000`) |
|
* وضعیتهای انتقال: `در حال انتقال (in_transit)`، `تحویلشده (received)` و `لغوشده (cancelled)`.
|
||||||
| Web console | http://localhost:9001 |
|
* کارگاه مقصد از طریق زبانه «انتقالات ورودی» در صفحه «کالاهای در راه» اقلام ارسالی را دریافت و به انبارهای خود تخصیص میدهد.
|
||||||
| Root user / password | `minioadmin` / `minioadmin` (dev — change for production) |
|
|
||||||
| Bucket | `procurement-files` (created automatically by the `minio-init` container) |
|
|
||||||
| Object key layout | `{quote_id}/{kind}/{attachment_id}` where kind = `invoice` \| `proforma` |
|
|
||||||
|
|
||||||
File **bytes** live in MinIO; the `quote_attachments` table holds the metadata.
|
|
||||||
|
|
||||||
Ad-hoc bucket inspection from the host (see `mc.cmd`):
|
|
||||||
|
|
||||||
```powershell
|
|
||||||
.\mc.cmd ls --recursive
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Database credentials / connection
|
## 🛠️ عملیات نگهداری و دیپلوی در سرور (Operations)
|
||||||
|
|
||||||
```text
|
* **دیپلوی خودکار:** سرور با هر Push به برنچ `production` از طریق وبهوک اختصاصی به صورت خودکار بیلد و بالا میآید. راهنمای کامل: [docs/OPERATIONS.md](file:///c:/Users/Reza/Desktop/v1.6/docs/OPERATIONS.md).
|
||||||
Host: localhost
|
* **پشتیبانگیری پایگاه داده:** سرویس `db-backup` به صورت روزانه از هر دو پایگاه داده `procurement` و `casdoor` فایلهای `.dump` تولید و در پوشه `backups/` نگهداری میکند.
|
||||||
Port: 5433
|
* **مانیتورینگ و مشاهدهپذیری:** ابزارهای Prometheus، لاگهای Loki و ردیابی خطاهای GlitchTip در پوشه [monitoring/](file:///c:/Users/Reza/Desktop/v1.6/monitoring/README.md) سازماندهی شدهاند.
|
||||||
Database: procurement
|
|
||||||
Username: postgres
|
|
||||||
Password: postgres
|
|
||||||
```
|
|
||||||
|
|
||||||
```powershell
|
|
||||||
docker exec -it procurement-postgres psql -U postgres -d procurement
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Recovery / seeding
|
|
||||||
|
|
||||||
The databases are **not** in git — Docker volumes hold the data, and
|
|
||||||
database dumps must never be committed (they contain user rows and signing
|
|
||||||
material). Two supported ways to bring a fresh stack up:
|
|
||||||
|
|
||||||
1. **Empty boot** — schema v2.6 auto-applies on the first boot of an empty
|
|
||||||
`postgres_data` volume; then run the seeders:
|
|
||||||
|
|
||||||
```powershell
|
|
||||||
# Casdoor org + app + users (prints/generates credentials — do not commit them)
|
|
||||||
docker compose run --rm -e CASDOOR_BASE=http://casdoor:8000 api python tools/seed_casdoor.py
|
|
||||||
# Demo dataset (optional):
|
|
||||||
docker exec procurement-api sh -c "cd /srv/backend && python -m tools.seed"
|
|
||||||
```
|
|
||||||
|
|
||||||
2. **Restore your own dump** — create dumps on the server (kept server-side,
|
|
||||||
e.g. `/srv/erp/backups/`), never in git:
|
|
||||||
|
|
||||||
```powershell
|
|
||||||
docker exec procurement-postgres pg_dump -U postgres -d procurement -Fc > /srv/erp/backups/procurement-$(date +%F).dump
|
|
||||||
docker exec procurement-postgres pg_dump -U postgres -d casdoor -Fc > /srv/erp/backups/casdoor-$(date +%F).dump
|
|
||||||
```
|
|
||||||
|
|
||||||
Restore with `pg_restore --clean --if-exists` (stop `api` + `casdoor`
|
|
||||||
first — this **replaces all data**). The scheduled backup sidecar
|
|
||||||
(see `docs/OPERATIONS.md`) automates this.
|
|
||||||
|
|
||||||
## Common operations
|
|
||||||
|
|
||||||
```powershell
|
|
||||||
docker compose logs -f api # see logs
|
|
||||||
docker compose down # stop (keep data)
|
|
||||||
docker compose up -d --build # rebuild after code changes
|
|
||||||
docker compose down -v # ⚠️ full reset — wipes DB + MinIO volumes
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Known behavior
|
|
||||||
|
|
||||||
- Authentication is Casdoor-based (JWT verified via JWKS) and **required on
|
|
||||||
every API route** except `/health`, `/health/ready` and `/auth/login`
|
|
||||||
(401 without a token, 403 without a role). The former dev-header fallback
|
|
||||||
(`X-User-Role` / `X-User-Name-B64`) is disabled unless
|
|
||||||
`PROCUREMENT_DEV_LOGIN_ENABLED=true` — never enable it in production.
|
|
||||||
- Roles live in the app's `users` table (Casdoor is identity-only): `pm`,
|
|
||||||
`procurement_manager`, `admin`. Role changes are **admin-only** (RBAC);
|
|
||||||
the procurement manager can only assign projects to project managers.
|
|
||||||
The admin has a dedicated panel at `/admin` (user sync from Casdoor +
|
|
||||||
grant/revoke «مدیر تدارکات»).
|
|
||||||
- **Partial goods receipt** («رسید جزیی») is supported in «کالاهای در راه»:
|
|
||||||
at least one item with a valid quantity is enough to submit; other items
|
|
||||||
stay in transit. The procurement ledger shows «رسیده X از Y» / «در راه Z»
|
|
||||||
badges and a «رسید جزیی» badge on the quote.
|
|
||||||
- **One PostgreSQL instance** serves both the app (`procurement`) and Casdoor
|
|
||||||
(`casdoor`) — the separate casdoor-postgres container is gone (data was
|
|
||||||
dumped/restored; see `docs/casdoor-auth.md`).
|
|
||||||
- **Traefik v3** is the public edge (ports 80/443); the frontend nginx only
|
|
||||||
serves the SPA and proxies `/api` internally. Production (real domains,
|
|
||||||
HTTPS via Let's Encrypt, HTTP→HTTPS redirect):
|
|
||||||
`docker compose -f docker-compose.yml -f docker-compose.prod.yml up -d --build`
|
|
||||||
(see the prod file header for the required env vars).
|
|
||||||
- Schema runs automatically ONLY on the first boot of an empty `postgres_data` volume
|
|
||||||
(see `docker-entrypoint-initdb.d`); the API also runs `CREATE TABLE IF NOT EXISTS`
|
|
||||||
for the units-dashboard tables and `quote_attachments` at startup.
|
|
||||||
- Invoice upload requires an `accepted`/`arrived` quote; proforma has no restriction.
|
|
||||||
- The supplier detail page (`/suppliers/:id`) shows the purchase history with
|
|
||||||
invoice/proforma download links from MinIO.
|
|
||||||
- If builds fail with disk-full errors: `docker system prune -a`, then rebuild.
|
|
||||||
- If the frontend shows «اتصال به سرور برقرار نشد» → the api container is not
|
|
||||||
reachable; check `docker compose ps` and `docker compose logs api`.
|
|
||||||
|
|||||||
+76
-8
@@ -27,7 +27,7 @@ from sqlalchemy.ext.asyncio import AsyncSession
|
|||||||
|
|
||||||
from app.config import settings
|
from app.config import settings
|
||||||
from app.db.engine import AsyncSessionLocal
|
from app.db.engine import AsyncSessionLocal
|
||||||
from app.models.procurement import Project, User
|
from app.models.procurement import Project, User, UserPanel, UserProjectMembership
|
||||||
from app.utils.errors import (
|
from app.utils.errors import (
|
||||||
ForbiddenError,
|
ForbiddenError,
|
||||||
ServiceUnavailableError,
|
ServiceUnavailableError,
|
||||||
@@ -106,6 +106,10 @@ class UserContext:
|
|||||||
project_id: object | None # uuid.UUID | None — default (first) project of a PM
|
project_id: object | None # uuid.UUID | None — default (first) project of a PM
|
||||||
project_ids: list # every project this PM manages (1:N — empty for non-PMs)
|
project_ids: list # every project this PM manages (1:N — empty for non-PMs)
|
||||||
display_name: str
|
display_name: str
|
||||||
|
# لایه پنلها (جایگزین نقشها): {'procurement': 'full'|'limited', 'inventory': ...}
|
||||||
|
panels: dict | None = None
|
||||||
|
# عضویت M:N در پروژهها — محدوده داده سطح limited (جدا از مسئولیت PM)
|
||||||
|
member_project_ids: list | None = None
|
||||||
|
|
||||||
|
|
||||||
async def context_from_claims(claims: dict, db: AsyncSession) -> UserContext:
|
async def context_from_claims(claims: dict, db: AsyncSession) -> UserContext:
|
||||||
@@ -119,10 +123,12 @@ async def context_from_claims(claims: dict, db: AsyncSession) -> UserContext:
|
|||||||
if not casdoor_id:
|
if not casdoor_id:
|
||||||
raise UnauthorizedError("توکن فاقد شناسه کاربر است", field="authorization")
|
raise UnauthorizedError("توکن فاقد شناسه کاربر است", field="authorization")
|
||||||
|
|
||||||
|
username = str(claims.get("name") or claims.get("preferred_username") or "")
|
||||||
user = await db.scalar(select(User).where(User.casdoor_id == casdoor_id))
|
user = await db.scalar(select(User).where(User.casdoor_id == casdoor_id))
|
||||||
if user is None:
|
if user is None:
|
||||||
user = User(
|
user = User(
|
||||||
casdoor_id=casdoor_id,
|
casdoor_id=casdoor_id,
|
||||||
|
username=username or None,
|
||||||
first_name=str(
|
first_name=str(
|
||||||
claims.get("firstName")
|
claims.get("firstName")
|
||||||
or claims.get("firstname")
|
or claims.get("firstname")
|
||||||
@@ -135,17 +141,42 @@ async def context_from_claims(claims: dict, db: AsyncSession) -> UserContext:
|
|||||||
)
|
)
|
||||||
db.add(user)
|
db.add(user)
|
||||||
await db.flush()
|
await db.flush()
|
||||||
|
elif username and not user.username:
|
||||||
|
user.username = username
|
||||||
|
await db.flush()
|
||||||
|
|
||||||
project_ids: list = []
|
# لایه پنلها: تخصیص پنل + سطح دسترسی و عضویت پروژهای (جدا از نقش)
|
||||||
if user.role == "pm":
|
panels: dict = {}
|
||||||
projects = (
|
panel_rows = (
|
||||||
|
await db.execute(
|
||||||
|
select(UserPanel).where(UserPanel.user_id == user.id).order_by(UserPanel.created_at)
|
||||||
|
)
|
||||||
|
).scalars().all()
|
||||||
|
for row in panel_rows:
|
||||||
|
panels[row.panel] = row.level
|
||||||
|
|
||||||
|
member_project_ids: list = [
|
||||||
|
row.project_id
|
||||||
|
for row in (
|
||||||
|
await db.execute(
|
||||||
|
select(UserProjectMembership)
|
||||||
|
.where(UserProjectMembership.user_id == user.id)
|
||||||
|
.order_by(UserProjectMembership.created_at)
|
||||||
|
)
|
||||||
|
).scalars().all()
|
||||||
|
]
|
||||||
|
|
||||||
|
pm_projects = (
|
||||||
await db.execute(
|
await db.execute(
|
||||||
select(Project)
|
select(Project)
|
||||||
.where(Project.pm_user_id == user.id)
|
.where(Project.pm_user_id == user.id)
|
||||||
.order_by(Project.created_at, Project.id)
|
.order_by(Project.created_at, Project.id)
|
||||||
)
|
)
|
||||||
).scalars().all()
|
).scalars().all()
|
||||||
project_ids = [p.id for p in projects]
|
pm_project_ids_list = [p.id for p in pm_projects]
|
||||||
|
|
||||||
|
# ترکیب پروژههای تحت مدیریت مستقیم و پروژههای عضویت با حفظ اولویت و بدون تکرار
|
||||||
|
project_ids = list(dict.fromkeys(pm_project_ids_list + member_project_ids))
|
||||||
project_id = project_ids[0] if project_ids else None
|
project_id = project_ids[0] if project_ids else None
|
||||||
|
|
||||||
display_name = f"{user.first_name} {user.last_name}".strip() or user.casdoor_id
|
display_name = f"{user.first_name} {user.last_name}".strip() or user.casdoor_id
|
||||||
@@ -155,19 +186,28 @@ async def context_from_claims(claims: dict, db: AsyncSession) -> UserContext:
|
|||||||
project_id=project_id,
|
project_id=project_id,
|
||||||
project_ids=project_ids,
|
project_ids=project_ids,
|
||||||
display_name=display_name,
|
display_name=display_name,
|
||||||
|
panels=panels,
|
||||||
|
member_project_ids=member_project_ids,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
async def pm_project_ids(db: AsyncSession, user: User) -> list:
|
async def pm_project_ids(db: AsyncSession, user: User) -> list:
|
||||||
"""Every project id managed by the given PM user (oldest first)."""
|
"""Every project id managed or assigned to the given PM/supervisor user (oldest first)."""
|
||||||
rows = (
|
pm_rows = (
|
||||||
await db.execute(
|
await db.execute(
|
||||||
select(Project.id)
|
select(Project.id)
|
||||||
.where(Project.pm_user_id == user.id)
|
.where(Project.pm_user_id == user.id)
|
||||||
.order_by(Project.created_at, Project.id)
|
.order_by(Project.created_at, Project.id)
|
||||||
)
|
)
|
||||||
).scalars().all()
|
).scalars().all()
|
||||||
return list(rows)
|
member_rows = (
|
||||||
|
await db.execute(
|
||||||
|
select(UserProjectMembership.project_id)
|
||||||
|
.where(UserProjectMembership.user_id == user.id)
|
||||||
|
.order_by(UserProjectMembership.created_at)
|
||||||
|
)
|
||||||
|
).scalars().all()
|
||||||
|
return list(dict.fromkeys(list(pm_rows) + list(member_rows)))
|
||||||
|
|
||||||
|
|
||||||
async def get_optional_user(request: Request, db: AsyncSession | None = None) -> UserContext | None:
|
async def get_optional_user(request: Request, db: AsyncSession | None = None) -> UserContext | None:
|
||||||
@@ -217,3 +257,31 @@ def require_role(*roles: str):
|
|||||||
raise ForbiddenError("دسترسی به این بخش برای نقش شما مجاز نیست")
|
raise ForbiddenError("دسترسی به این بخش برای نقش شما مجاز نیست")
|
||||||
return ctx
|
return ctx
|
||||||
return _dep
|
return _dep
|
||||||
|
|
||||||
|
|
||||||
|
def require_procurement_writer():
|
||||||
|
"""نوشتن در پنل تدارکات — ادمین، پنل تدارکات 'full'، یا نقش میراث مدیر تدارکات
|
||||||
|
(دوره مهاجرت از مدل نقش به مدل پنل)."""
|
||||||
|
|
||||||
|
async def _dep(ctx: UserContext = Depends(get_current_user)) -> UserContext:
|
||||||
|
if ctx.role in ("admin", "procurement_manager"):
|
||||||
|
return ctx
|
||||||
|
if (ctx.panels or {}).get("procurement") == "full":
|
||||||
|
return ctx
|
||||||
|
raise ForbiddenError("دسترسی نوشتن در پنل تدارکات را ندارید")
|
||||||
|
|
||||||
|
return _dep
|
||||||
|
|
||||||
|
|
||||||
|
def allow_quote_create():
|
||||||
|
"""افزودن استعلام — علاوه بر «نوشتن»، پنل تدارکات 'limited' هم مجاز است
|
||||||
|
(محدود به پروژههای عضویت؛ اعتبارسنجی عضویت در خود endpoint انجام میشود)."""
|
||||||
|
|
||||||
|
async def _dep(ctx: UserContext = Depends(get_current_user)) -> UserContext:
|
||||||
|
if ctx.role in ("admin", "procurement_manager"):
|
||||||
|
return ctx
|
||||||
|
if (ctx.panels or {}).get("procurement") in ("full", "limited"):
|
||||||
|
return ctx
|
||||||
|
raise ForbiddenError("دسترسی افزودن استعلام ندارید")
|
||||||
|
|
||||||
|
return _dep
|
||||||
|
|||||||
@@ -174,7 +174,7 @@ _V26_DDL = [
|
|||||||
""",
|
""",
|
||||||
"""
|
"""
|
||||||
DO $$ BEGIN
|
DO $$ BEGIN
|
||||||
CREATE TYPE user_role AS ENUM ('pm', 'procurement_manager', 'admin');
|
CREATE TYPE user_role AS ENUM ('pm', 'procurement_manager', 'admin', 'supervisor');
|
||||||
EXCEPTION WHEN duplicate_object THEN NULL; END $$
|
EXCEPTION WHEN duplicate_object THEN NULL; END $$
|
||||||
""",
|
""",
|
||||||
"""
|
"""
|
||||||
@@ -247,6 +247,7 @@ _V26_DDL = [
|
|||||||
physical_qty NUMERIC(18,6),
|
physical_qty NUMERIC(18,6),
|
||||||
transfer_pair_id UUID,
|
transfer_pair_id UUID,
|
||||||
performed_by TEXT,
|
performed_by TEXT,
|
||||||
|
delivered_to TEXT,
|
||||||
transaction_date TIMESTAMPTZ NOT NULL DEFAULT now(),
|
transaction_date TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||||
note TEXT,
|
note TEXT,
|
||||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||||
@@ -258,6 +259,9 @@ _V26_DDL = [
|
|||||||
"""
|
"""
|
||||||
CREATE INDEX IF NOT EXISTS idx_inventory_tx_warehouse_date ON inventory_transactions (warehouse_id, transaction_date)
|
CREATE INDEX IF NOT EXISTS idx_inventory_tx_warehouse_date ON inventory_transactions (warehouse_id, transaction_date)
|
||||||
""",
|
""",
|
||||||
|
"""
|
||||||
|
ALTER TABLE inventory_transactions ADD COLUMN IF NOT EXISTS delivered_to TEXT
|
||||||
|
""",
|
||||||
# suppliers.categories JSONB (v2.4 runtime) is replaced by suppliers.category_id — drop it.
|
# suppliers.categories JSONB (v2.4 runtime) is replaced by suppliers.category_id — drop it.
|
||||||
"""
|
"""
|
||||||
ALTER TABLE suppliers DROP COLUMN IF EXISTS categories
|
ALTER TABLE suppliers DROP COLUMN IF EXISTS categories
|
||||||
@@ -410,6 +414,53 @@ async def ensure_drop_category_tables(engine: AsyncEngine) -> None:
|
|||||||
logger.info("category taxonomy tables dropped (attributes / ref units / conversions)")
|
logger.info("category taxonomy tables dropped (attributes / ref units / conversions)")
|
||||||
|
|
||||||
|
|
||||||
|
async def ensure_rbac_schema(engine: AsyncEngine) -> None:
|
||||||
|
"""Panel-access schema (pm branch): users.username, projects planning
|
||||||
|
columns, user_panels and user_project_members. Idempotent; safe on any
|
||||||
|
volume — the RBAC model expects these and login 500s without them."""
|
||||||
|
stmts = (
|
||||||
|
"ALTER TABLE users ADD COLUMN IF NOT EXISTS username TEXT",
|
||||||
|
# The live user_role enum predates 'supervisor' — CREATE TYPE no-ops on
|
||||||
|
# an existing type, so without this ALTER, assigning the role 500s.
|
||||||
|
"ALTER TYPE user_role ADD VALUE IF NOT EXISTS 'supervisor'",
|
||||||
|
"ALTER TABLE projects ADD COLUMN IF NOT EXISTS location TEXT DEFAULT ''",
|
||||||
|
"ALTER TABLE projects ADD COLUMN IF NOT EXISTS project_manager TEXT DEFAULT ''",
|
||||||
|
"ALTER TABLE projects ADD COLUMN IF NOT EXISTS planned_start DATE",
|
||||||
|
"ALTER TABLE projects ADD COLUMN IF NOT EXISTS planned_end DATE",
|
||||||
|
"ALTER TABLE projects ADD COLUMN IF NOT EXISTS actual_start DATE",
|
||||||
|
"ALTER TABLE projects ADD COLUMN IF NOT EXISTS actual_end DATE",
|
||||||
|
"ALTER TABLE projects ADD COLUMN IF NOT EXISTS status TEXT DEFAULT 'ACTIVE'",
|
||||||
|
"ALTER TABLE projects ADD COLUMN IF NOT EXISTS progress DOUBLE PRECISION DEFAULT 0.0",
|
||||||
|
"ALTER TABLE projects ADD COLUMN IF NOT EXISTS updated_at TIMESTAMPTZ DEFAULT now()",
|
||||||
|
"""
|
||||||
|
CREATE TABLE IF NOT EXISTS user_panels (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||||
|
panel TEXT NOT NULL,
|
||||||
|
level TEXT NOT NULL,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||||
|
CONSTRAINT uq_user_panel UNIQUE (user_id, panel)
|
||||||
|
)
|
||||||
|
""",
|
||||||
|
"CREATE INDEX IF NOT EXISTS ix_user_panels_user_id ON user_panels(user_id)",
|
||||||
|
"""
|
||||||
|
CREATE TABLE IF NOT EXISTS user_project_members (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||||
|
project_id UUID NOT NULL REFERENCES projects(id) ON DELETE CASCADE,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||||
|
CONSTRAINT uq_user_project_member UNIQUE (user_id, project_id)
|
||||||
|
)
|
||||||
|
""",
|
||||||
|
"CREATE INDEX IF NOT EXISTS ix_user_project_members_user_id ON user_project_members(user_id)",
|
||||||
|
"CREATE INDEX IF NOT EXISTS ix_user_project_members_project_id ON user_project_members(project_id)",
|
||||||
|
)
|
||||||
|
async with engine.begin() as conn:
|
||||||
|
for stmt in stmts:
|
||||||
|
await conn.execute(text(stmt))
|
||||||
|
logger.info("RBAC schema ensured (username / project columns / user_panels / user_project_members)")
|
||||||
|
|
||||||
|
|
||||||
async def ensure_audit_table(engine: AsyncEngine) -> None:
|
async def ensure_audit_table(engine: AsyncEngine) -> None:
|
||||||
"""v2.7: general activity trail (audit_log). Idempotent; safe on any volume."""
|
"""v2.7: general activity trail (audit_log). Idempotent; safe on any volume."""
|
||||||
ddl = """
|
ddl = """
|
||||||
@@ -466,3 +517,47 @@ async def ensure_bot_drafts_table(engine: AsyncEngine) -> None:
|
|||||||
await conn.execute(text(stmt))
|
await conn.execute(text(stmt))
|
||||||
logger.info("bot_drafts table ensured")
|
logger.info("bot_drafts table ensured")
|
||||||
|
|
||||||
|
|
||||||
|
async def ensure_project_transfers_table(engine: AsyncEngine) -> None:
|
||||||
|
"""Create (if missing) the project_transfers table for inter-site transfers. Safe on any volume."""
|
||||||
|
ddl = """
|
||||||
|
CREATE TABLE IF NOT EXISTS project_transfers (
|
||||||
|
id UUID NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY,
|
||||||
|
from_project_id UUID NOT NULL REFERENCES projects(id) ON DELETE RESTRICT,
|
||||||
|
from_warehouse_id UUID NOT NULL REFERENCES warehouses(id) ON DELETE RESTRICT,
|
||||||
|
to_project_id UUID NOT NULL REFERENCES projects(id) ON DELETE RESTRICT,
|
||||||
|
material_id UUID NOT NULL REFERENCES materials(id) ON DELETE RESTRICT,
|
||||||
|
brand_id UUID REFERENCES brands(id) ON DELETE SET NULL,
|
||||||
|
unit_id INTEGER NOT NULL REFERENCES units(id) ON DELETE RESTRICT,
|
||||||
|
quantity NUMERIC(18,6) NOT NULL CHECK (quantity > 0),
|
||||||
|
specs JSONB NOT NULL DEFAULT '{}'::jsonb,
|
||||||
|
specs_hash TEXT NOT NULL DEFAULT 'default',
|
||||||
|
note TEXT,
|
||||||
|
status TEXT NOT NULL DEFAULT 'in_transit' CHECK (status IN ('in_transit', 'received', 'cancelled')),
|
||||||
|
out_transaction_id UUID REFERENCES inventory_transactions(id) ON DELETE SET NULL,
|
||||||
|
transfer_date TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||||
|
transferred_by TEXT,
|
||||||
|
received_at TIMESTAMPTZ,
|
||||||
|
received_by TEXT,
|
||||||
|
to_warehouse_id UUID REFERENCES warehouses(id) ON DELETE SET NULL,
|
||||||
|
receipt_allocations JSONB,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||||
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||||
|
)
|
||||||
|
"""
|
||||||
|
indexes = (
|
||||||
|
"CREATE INDEX IF NOT EXISTS idx_project_transfers_from ON project_transfers(from_project_id, status)",
|
||||||
|
"CREATE INDEX IF NOT EXISTS idx_project_transfers_to ON project_transfers(to_project_id, status)",
|
||||||
|
"DROP TRIGGER IF EXISTS trg_project_transfers_updated_at ON project_transfers",
|
||||||
|
"""
|
||||||
|
CREATE TRIGGER trg_project_transfers_updated_at
|
||||||
|
BEFORE UPDATE ON project_transfers
|
||||||
|
FOR EACH ROW EXECUTE FUNCTION set_updated_at()
|
||||||
|
""",
|
||||||
|
)
|
||||||
|
async with engine.begin() as conn:
|
||||||
|
await conn.execute(text(ddl))
|
||||||
|
for stmt in indexes:
|
||||||
|
await conn.execute(text(stmt))
|
||||||
|
logger.info("project_transfers table ensured")
|
||||||
|
|
||||||
|
|||||||
@@ -32,6 +32,8 @@ from app.db.init_db import (
|
|||||||
ensure_dashboard_tables,
|
ensure_dashboard_tables,
|
||||||
ensure_material_topic_column,
|
ensure_material_topic_column,
|
||||||
ensure_quote_projects,
|
ensure_quote_projects,
|
||||||
|
ensure_rbac_schema,
|
||||||
|
ensure_project_transfers_table,
|
||||||
ensure_v26,
|
ensure_v26,
|
||||||
)
|
)
|
||||||
from app.observability import RequestContextMiddleware, setup_logging
|
from app.observability import RequestContextMiddleware, setup_logging
|
||||||
@@ -106,9 +108,11 @@ async def lifespan(_app: FastAPI):
|
|||||||
await ensure_material_topic_column(engine)
|
await ensure_material_topic_column(engine)
|
||||||
await ensure_quote_projects(engine)
|
await ensure_quote_projects(engine)
|
||||||
await ensure_v26(engine)
|
await ensure_v26(engine)
|
||||||
|
await ensure_rbac_schema(engine)
|
||||||
await ensure_audit_table(engine)
|
await ensure_audit_table(engine)
|
||||||
await ensure_drop_category_tables(engine)
|
await ensure_drop_category_tables(engine)
|
||||||
await ensure_bot_drafts_table(engine)
|
await ensure_bot_drafts_table(engine)
|
||||||
|
await ensure_project_transfers_table(engine)
|
||||||
task = asyncio.create_task(_auto_expire_loop()) if settings.AUTO_EXPIRE_ENABLED else None
|
task = asyncio.create_task(_auto_expire_loop()) if settings.AUTO_EXPIRE_ENABLED else None
|
||||||
try:
|
try:
|
||||||
yield
|
yield
|
||||||
|
|||||||
@@ -32,6 +32,8 @@ from app.models.procurement import (
|
|||||||
TermsheetScheduleStep,
|
TermsheetScheduleStep,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
from app.models.project_transfer import ProjectTransfer
|
||||||
|
|
||||||
__all__ = [
|
__all__ = [
|
||||||
"Base",
|
"Base",
|
||||||
"Unit",
|
"Unit",
|
||||||
@@ -60,4 +62,5 @@ __all__ = [
|
|||||||
"ItemDecision",
|
"ItemDecision",
|
||||||
"ItemReceipt",
|
"ItemReceipt",
|
||||||
"QuoteAttachment",
|
"QuoteAttachment",
|
||||||
|
"ProjectTransfer",
|
||||||
]
|
]
|
||||||
|
|||||||
@@ -156,6 +156,7 @@ class InventoryTransaction(Base):
|
|||||||
# NULL for a standalone entry; links TRANSFER_OUT to its TRANSFER_IN row.
|
# NULL for a standalone entry; links TRANSFER_OUT to its TRANSFER_IN row.
|
||||||
transfer_pair_id: Mapped[uuid.UUID | None] = mapped_column(Uuid(as_uuid=True))
|
transfer_pair_id: Mapped[uuid.UUID | None] = mapped_column(Uuid(as_uuid=True))
|
||||||
performed_by: Mapped[str | None] = mapped_column(Text) # user display name (dev placeholder)
|
performed_by: Mapped[str | None] = mapped_column(Text) # user display name (dev placeholder)
|
||||||
|
delivered_to: Mapped[str | None] = mapped_column(Text)
|
||||||
transaction_date: Mapped[datetime] = mapped_column(
|
transaction_date: Mapped[datetime] = mapped_column(
|
||||||
DateTime(timezone=True), nullable=False, server_default=func.now()
|
DateTime(timezone=True), nullable=False, server_default=func.now()
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -26,7 +26,7 @@ from app.db.base import Base
|
|||||||
from app.models.catalog import Material, Unit, _timestamptz, _uuid_pk
|
from app.models.catalog import Material, Unit, _timestamptz, _uuid_pk
|
||||||
|
|
||||||
user_role_enum = Enum(
|
user_role_enum = Enum(
|
||||||
"pm", "procurement_manager", "admin",
|
"pm", "procurement_manager", "admin", "supervisor",
|
||||||
name="user_role", native_enum=True,
|
name="user_role", native_enum=True,
|
||||||
)
|
)
|
||||||
quote_status_enum = Enum(
|
quote_status_enum = Enum(
|
||||||
@@ -58,6 +58,7 @@ class User(Base):
|
|||||||
|
|
||||||
id: Mapped[uuid.UUID] = _uuid_pk()
|
id: Mapped[uuid.UUID] = _uuid_pk()
|
||||||
casdoor_id: Mapped[str] = mapped_column(Text, nullable=False, unique=True)
|
casdoor_id: Mapped[str] = mapped_column(Text, nullable=False, unique=True)
|
||||||
|
username: Mapped[str | None] = mapped_column(Text)
|
||||||
first_name: Mapped[str] = mapped_column(Text, nullable=False)
|
first_name: Mapped[str] = mapped_column(Text, nullable=False)
|
||||||
last_name: Mapped[str] = mapped_column(Text, nullable=False)
|
last_name: Mapped[str] = mapped_column(Text, nullable=False)
|
||||||
phone: Mapped[str | None] = mapped_column(Text)
|
phone: Mapped[str | None] = mapped_column(Text)
|
||||||
@@ -65,6 +66,47 @@ class User(Base):
|
|||||||
created_at: Mapped[datetime] = _timestamptz()
|
created_at: Mapped[datetime] = _timestamptz()
|
||||||
|
|
||||||
|
|
||||||
|
class UserPanel(Base):
|
||||||
|
"""user_panels — تخصیص پنل + سطح دسترسی به کاربر (جایگزین مدل نقش).
|
||||||
|
|
||||||
|
panel: 'procurement' | 'inventory' | 'pm'
|
||||||
|
level: 'full' — تدارکات: تغییر کامل در کل پنل؛ انبار: همه پروژهها
|
||||||
|
(بهجز تغییر موجودی)
|
||||||
|
'limited' — تدارکات: فقط افزودن استعلام برای پروژههای عضویت؛
|
||||||
|
انبار: فقط پروژههای عضویت + امکان تغییر موجودی
|
||||||
|
"""
|
||||||
|
|
||||||
|
__tablename__ = "user_panels"
|
||||||
|
|
||||||
|
id: Mapped[uuid.UUID] = _uuid_pk()
|
||||||
|
user_id: Mapped[uuid.UUID] = mapped_column(
|
||||||
|
ForeignKey("users.id", ondelete="CASCADE"), nullable=False, index=True
|
||||||
|
)
|
||||||
|
panel: Mapped[str] = mapped_column(Text, nullable=False)
|
||||||
|
level: Mapped[str] = mapped_column(Text, nullable=False)
|
||||||
|
created_at: Mapped[datetime] = _timestamptz()
|
||||||
|
|
||||||
|
__table_args__ = (UniqueConstraint("user_id", "panel", name="uq_user_panel"),)
|
||||||
|
|
||||||
|
|
||||||
|
class UserProjectMembership(Base):
|
||||||
|
"""user_project_members — عضویت M:N کاربر در پروژهها، جدا از مسئولیت
|
||||||
|
پروژه (projects.pm_user_id). محدودهی دادهی سطح limited را تعیین میکند."""
|
||||||
|
|
||||||
|
__tablename__ = "user_project_members"
|
||||||
|
|
||||||
|
id: Mapped[uuid.UUID] = _uuid_pk()
|
||||||
|
user_id: Mapped[uuid.UUID] = mapped_column(
|
||||||
|
ForeignKey("users.id", ondelete="CASCADE"), nullable=False, index=True
|
||||||
|
)
|
||||||
|
project_id: Mapped[uuid.UUID] = mapped_column(
|
||||||
|
ForeignKey("projects.id", ondelete="CASCADE"), nullable=False, index=True
|
||||||
|
)
|
||||||
|
created_at: Mapped[datetime] = _timestamptz()
|
||||||
|
|
||||||
|
__table_args__ = (UniqueConstraint("user_id", "project_id", name="uq_user_project_member"),)
|
||||||
|
|
||||||
|
|
||||||
class Supplier(Base):
|
class Supplier(Base):
|
||||||
__tablename__ = "suppliers"
|
__tablename__ = "suppliers"
|
||||||
|
|
||||||
@@ -148,12 +190,23 @@ class Project(Base):
|
|||||||
id: Mapped[uuid.UUID] = _uuid_pk()
|
id: Mapped[uuid.UUID] = _uuid_pk()
|
||||||
name: Mapped[str] = mapped_column(Text, nullable=False)
|
name: Mapped[str] = mapped_column(Text, nullable=False)
|
||||||
description: Mapped[str | None] = mapped_column(Text)
|
description: Mapped[str | None] = mapped_column(Text)
|
||||||
|
location: Mapped[str | None] = mapped_column(Text, server_default=text("''"))
|
||||||
|
project_manager: Mapped[str | None] = mapped_column(Text, server_default=text("''"))
|
||||||
start_date: Mapped[date | None] = mapped_column(Date)
|
start_date: Mapped[date | None] = mapped_column(Date)
|
||||||
|
planned_start: Mapped[date | None] = mapped_column(Date)
|
||||||
|
planned_end: Mapped[date | None] = mapped_column(Date)
|
||||||
|
actual_start: Mapped[date | None] = mapped_column(Date)
|
||||||
|
actual_end: Mapped[date | None] = mapped_column(Date)
|
||||||
|
status: Mapped[str | None] = mapped_column(Text, server_default=text("'ACTIVE'"))
|
||||||
|
progress: Mapped[float | None] = mapped_column(Numeric(5, 2), server_default=text("0.0"))
|
||||||
# v2.6: the single PM responsible for this project (confirms arrivals).
|
# v2.6: the single PM responsible for this project (confirms arrivals).
|
||||||
pm_user_id: Mapped[uuid.UUID | None] = mapped_column(
|
pm_user_id: Mapped[uuid.UUID | None] = mapped_column(
|
||||||
ForeignKey("users.id", ondelete="SET NULL")
|
ForeignKey("users.id", ondelete="SET NULL")
|
||||||
)
|
)
|
||||||
created_at: Mapped[datetime] = _timestamptz()
|
created_at: Mapped[datetime] = _timestamptz()
|
||||||
|
updated_at: Mapped[datetime | None] = mapped_column(
|
||||||
|
DateTime(timezone=True), server_default=func.now(), onupdate=func.now()
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
class Quote(Base):
|
class Quote(Base):
|
||||||
|
|||||||
@@ -0,0 +1,87 @@
|
|||||||
|
import uuid
|
||||||
|
from datetime import datetime
|
||||||
|
from decimal import Decimal
|
||||||
|
|
||||||
|
from sqlalchemy import (
|
||||||
|
DateTime,
|
||||||
|
ForeignKey,
|
||||||
|
Numeric,
|
||||||
|
Text,
|
||||||
|
func,
|
||||||
|
text,
|
||||||
|
)
|
||||||
|
from sqlalchemy.dialects.postgresql import JSONB
|
||||||
|
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||||
|
|
||||||
|
from app.db.base import Base
|
||||||
|
from app.models.catalog import _timestamptz, _uuid_pk
|
||||||
|
|
||||||
|
|
||||||
|
class ProjectTransfer(Base):
|
||||||
|
"""project_transfers — Inter-project (inter-site) material transfer ledger.
|
||||||
|
|
||||||
|
Records the movement of materials from a source project warehouse to a
|
||||||
|
destination project. Stock is deducted from the source warehouse immediately
|
||||||
|
upon creation (status = 'in_transit') via out_transaction_id.
|
||||||
|
When the destination project PM confirms receipt in 'Arrivals', stock is
|
||||||
|
added to the destination warehouse (status = 'received').
|
||||||
|
While 'in_transit', the transfer can be edited or cancelled (restoring source stock).
|
||||||
|
Once 'received', the transfer is permanently locked from edit or cancellation.
|
||||||
|
"""
|
||||||
|
|
||||||
|
__tablename__ = "project_transfers"
|
||||||
|
__mapper_args__ = {"eager_defaults": True}
|
||||||
|
|
||||||
|
id: Mapped[uuid.UUID] = _uuid_pk()
|
||||||
|
from_project_id: Mapped[uuid.UUID] = mapped_column(
|
||||||
|
ForeignKey("projects.id", ondelete="RESTRICT"), nullable=False
|
||||||
|
)
|
||||||
|
from_warehouse_id: Mapped[uuid.UUID] = mapped_column(
|
||||||
|
ForeignKey("warehouses.id", ondelete="RESTRICT"), nullable=False
|
||||||
|
)
|
||||||
|
to_project_id: Mapped[uuid.UUID] = mapped_column(
|
||||||
|
ForeignKey("projects.id", ondelete="RESTRICT"), nullable=False
|
||||||
|
)
|
||||||
|
material_id: Mapped[uuid.UUID] = mapped_column(
|
||||||
|
ForeignKey("materials.id", ondelete="RESTRICT"), nullable=False
|
||||||
|
)
|
||||||
|
brand_id: Mapped[uuid.UUID | None] = mapped_column(
|
||||||
|
ForeignKey("brands.id", ondelete="SET NULL")
|
||||||
|
)
|
||||||
|
unit_id: Mapped[int] = mapped_column(
|
||||||
|
ForeignKey("units.id", ondelete="RESTRICT"), nullable=False
|
||||||
|
)
|
||||||
|
quantity: Mapped[Decimal] = mapped_column(Numeric(18, 6), nullable=False)
|
||||||
|
specs: Mapped[dict] = mapped_column(JSONB, nullable=False, server_default=text("'{}'::jsonb"))
|
||||||
|
specs_hash: Mapped[str] = mapped_column(Text, nullable=False, server_default=text("'default'"))
|
||||||
|
note: Mapped[str | None] = mapped_column(Text)
|
||||||
|
status: Mapped[str] = mapped_column(Text, nullable=False, server_default=text("'in_transit'"))
|
||||||
|
|
||||||
|
out_transaction_id: Mapped[uuid.UUID | None] = mapped_column(
|
||||||
|
ForeignKey("inventory_transactions.id", ondelete="SET NULL")
|
||||||
|
)
|
||||||
|
transfer_date: Mapped[datetime] = mapped_column(
|
||||||
|
DateTime(timezone=True), nullable=False, server_default=func.now()
|
||||||
|
)
|
||||||
|
transferred_by: Mapped[str | None] = mapped_column(Text)
|
||||||
|
received_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
|
||||||
|
received_by: Mapped[str | None] = mapped_column(Text)
|
||||||
|
to_warehouse_id: Mapped[uuid.UUID | None] = mapped_column(
|
||||||
|
ForeignKey("warehouses.id", ondelete="SET NULL")
|
||||||
|
)
|
||||||
|
receipt_allocations: Mapped[list | None] = mapped_column(JSONB)
|
||||||
|
created_at: Mapped[datetime] = _timestamptz()
|
||||||
|
updated_at: Mapped[datetime] = mapped_column(
|
||||||
|
DateTime(timezone=True), nullable=False, server_default=func.now(), onupdate=func.now()
|
||||||
|
)
|
||||||
|
|
||||||
|
from_project: Mapped["Project"] = relationship("Project", foreign_keys=[from_project_id], lazy="raise")
|
||||||
|
to_project: Mapped["Project"] = relationship("Project", foreign_keys=[to_project_id], lazy="raise")
|
||||||
|
from_warehouse: Mapped["Warehouse"] = relationship("Warehouse", foreign_keys=[from_warehouse_id], lazy="raise")
|
||||||
|
to_warehouse: Mapped["Warehouse | None"] = relationship("Warehouse", foreign_keys=[to_warehouse_id], lazy="raise")
|
||||||
|
material: Mapped["Material"] = relationship("Material", foreign_keys=[material_id], lazy="raise")
|
||||||
|
brand: Mapped["Brand | None"] = relationship("Brand", foreign_keys=[brand_id], lazy="raise")
|
||||||
|
unit: Mapped["Unit"] = relationship("Unit", foreign_keys=[unit_id], lazy="raise")
|
||||||
|
out_transaction: Mapped["InventoryTransaction | None"] = relationship(
|
||||||
|
"InventoryTransaction", foreign_keys=[out_transaction_id], lazy="raise"
|
||||||
|
)
|
||||||
@@ -15,6 +15,7 @@ from app.routers import (
|
|||||||
material_categories,
|
material_categories,
|
||||||
materials,
|
materials,
|
||||||
pm,
|
pm,
|
||||||
|
project_transfers,
|
||||||
projects,
|
projects,
|
||||||
quote_events,
|
quote_events,
|
||||||
quotes,
|
quotes,
|
||||||
@@ -51,6 +52,7 @@ ROUTERS = [
|
|||||||
standard_conversions.router,
|
standard_conversions.router,
|
||||||
inventory.router,
|
inventory.router,
|
||||||
pm.router,
|
pm.router,
|
||||||
|
project_transfers.router,
|
||||||
users.router,
|
users.router,
|
||||||
drafts.router,
|
drafts.router,
|
||||||
]
|
]
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ from fastapi import APIRouter, Depends, Query
|
|||||||
from sqlalchemy import func, or_, select
|
from sqlalchemy import func, or_, select
|
||||||
from sqlalchemy.ext.asyncio import AsyncSession
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
|
from app.auth import require_procurement_writer, require_role
|
||||||
from app.db.engine import get_db
|
from app.db.engine import get_db
|
||||||
from app.models.catalog import AttributeDefinition, MaterialAttributeValue, Unit
|
from app.models.catalog import AttributeDefinition, MaterialAttributeValue, Unit
|
||||||
from app.models.procurement import LineItemSpec
|
from app.models.procurement import LineItemSpec
|
||||||
@@ -13,6 +14,7 @@ from app.utils.pagination import paginate, sort_query
|
|||||||
from app.utils.serialization import to_iso
|
from app.utils.serialization import to_iso
|
||||||
|
|
||||||
router = APIRouter(prefix="/attribute-definitions", tags=["attribute-definitions"])
|
router = APIRouter(prefix="/attribute-definitions", tags=["attribute-definitions"])
|
||||||
|
_procurement_writer = require_procurement_writer()
|
||||||
|
|
||||||
|
|
||||||
def attr_def_to_dict(ad: AttributeDefinition, unit: Unit | None = None) -> dict:
|
def attr_def_to_dict(ad: AttributeDefinition, unit: Unit | None = None) -> dict:
|
||||||
@@ -69,7 +71,11 @@ async def list_attribute_definitions(
|
|||||||
|
|
||||||
|
|
||||||
@router.post("", status_code=201)
|
@router.post("", status_code=201)
|
||||||
async def create_attribute_definition(payload: AttributeDefinitionCreate, db: AsyncSession = Depends(get_db)):
|
async def create_attribute_definition(
|
||||||
|
payload: AttributeDefinitionCreate,
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
_auth=Depends(_procurement_writer),
|
||||||
|
):
|
||||||
duplicate = await db.scalar(select(AttributeDefinition.id).where(AttributeDefinition.attribute_key == payload.attribute_key))
|
duplicate = await db.scalar(select(AttributeDefinition.id).where(AttributeDefinition.attribute_key == payload.attribute_key))
|
||||||
if duplicate is not None:
|
if duplicate is not None:
|
||||||
raise ConflictError("ویژگی با این attribute_key قبلاً ثبت شده است", field="attribute_key")
|
raise ConflictError("ویژگی با این attribute_key قبلاً ثبت شده است", field="attribute_key")
|
||||||
@@ -102,7 +108,10 @@ async def get_attribute_definition(
|
|||||||
|
|
||||||
@router.patch("/{definition_id}")
|
@router.patch("/{definition_id}")
|
||||||
async def update_attribute_definition(
|
async def update_attribute_definition(
|
||||||
definition_id, payload: AttributeDefinitionUpdate, db: AsyncSession = Depends(get_db)
|
definition_id,
|
||||||
|
payload: AttributeDefinitionUpdate,
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
_auth=Depends(_procurement_writer),
|
||||||
):
|
):
|
||||||
ad = await db.get(AttributeDefinition, definition_id)
|
ad = await db.get(AttributeDefinition, definition_id)
|
||||||
if ad is None:
|
if ad is None:
|
||||||
@@ -136,7 +145,11 @@ async def update_attribute_definition(
|
|||||||
|
|
||||||
|
|
||||||
@router.delete("/{definition_id}")
|
@router.delete("/{definition_id}")
|
||||||
async def delete_attribute_definition(definition_id, db: AsyncSession = Depends(get_db)):
|
async def delete_attribute_definition(
|
||||||
|
definition_id,
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
_auth=Depends(_procurement_writer),
|
||||||
|
):
|
||||||
ad = await db.get(AttributeDefinition, definition_id)
|
ad = await db.get(AttributeDefinition, definition_id)
|
||||||
if ad is None:
|
if ad is None:
|
||||||
raise NotFoundError("تعریف ویژگی یافت نشد")
|
raise NotFoundError("تعریف ویژگی یافت نشد")
|
||||||
|
|||||||
@@ -22,7 +22,7 @@ from app.config import settings
|
|||||||
from app.db.engine import get_db
|
from app.db.engine import get_db
|
||||||
from app.routers.users import _user_projects, user_to_dict
|
from app.routers.users import _user_projects, user_to_dict
|
||||||
from app.services import analytics
|
from app.services import analytics
|
||||||
from app.utils.errors import ServiceUnavailableError, UnauthorizedError
|
from app.utils.errors import ForbiddenError, ServiceUnavailableError, UnauthorizedError
|
||||||
from app.utils.ratelimit import limiter
|
from app.utils.ratelimit import limiter
|
||||||
|
|
||||||
logger = logging.getLogger("procurement.auth")
|
logger = logging.getLogger("procurement.auth")
|
||||||
@@ -78,6 +78,9 @@ async def login(request: Request, payload: LoginRequest, db: AsyncSession = Depe
|
|||||||
claims = await _verify_token(access_token)
|
claims = await _verify_token(access_token)
|
||||||
ctx = await context_from_claims(claims, db)
|
ctx = await context_from_claims(claims, db)
|
||||||
projects = await _user_projects(db, ctx.user)
|
projects = await _user_projects(db, ctx.user)
|
||||||
|
has_projects = bool(projects) or bool(ctx.project_ids) or bool(ctx.member_project_ids)
|
||||||
|
if ctx.role == "supervisor" and not has_projects:
|
||||||
|
raise ForbiddenError("پروژه تخصیص داده نشده است — تا زمان تخصیص پروژه، اجازه ورود به سامانه را ندارید")
|
||||||
await analytics.track(
|
await analytics.track(
|
||||||
"login_success",
|
"login_success",
|
||||||
{"username": payload.username, "role": ctx.role},
|
{"username": payload.username, "role": ctx.role},
|
||||||
@@ -92,6 +95,6 @@ async def login(request: Request, payload: LoginRequest, db: AsyncSession = Depe
|
|||||||
"access_token": access_token,
|
"access_token": access_token,
|
||||||
"token_type": "bearer",
|
"token_type": "bearer",
|
||||||
"expires_in": body.get("expires_in"),
|
"expires_in": body.get("expires_in"),
|
||||||
"user": user_to_dict(ctx.user, projects),
|
"user": await user_to_dict(ctx.user, projects, db),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ from fastapi import APIRouter, Depends, Query
|
|||||||
from sqlalchemy import func, select
|
from sqlalchemy import func, select
|
||||||
from sqlalchemy.ext.asyncio import AsyncSession
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
|
from app.auth import require_procurement_writer, require_role
|
||||||
from app.db.engine import get_db
|
from app.db.engine import get_db
|
||||||
from app.models.catalog import Brand, BrandMaterial, Material
|
from app.models.catalog import Brand, BrandMaterial, Material
|
||||||
from app.models.procurement import LineItem
|
from app.models.procurement import LineItem
|
||||||
@@ -12,6 +13,7 @@ from app.utils.pagination import paginate, sort_query
|
|||||||
from app.utils.serialization import to_iso
|
from app.utils.serialization import to_iso
|
||||||
|
|
||||||
router = APIRouter(prefix="/brand-materials", tags=["brand-materials"])
|
router = APIRouter(prefix="/brand-materials", tags=["brand-materials"])
|
||||||
|
_procurement_writer = require_procurement_writer()
|
||||||
|
|
||||||
|
|
||||||
def bm_to_dict(bm: BrandMaterial, expand: set[str] = frozenset()) -> dict:
|
def bm_to_dict(bm: BrandMaterial, expand: set[str] = frozenset()) -> dict:
|
||||||
@@ -70,7 +72,11 @@ async def list_brand_materials(
|
|||||||
|
|
||||||
|
|
||||||
@router.post("", status_code=201)
|
@router.post("", status_code=201)
|
||||||
async def create_brand_material(payload: BrandMaterialCreate, db: AsyncSession = Depends(get_db)):
|
async def create_brand_material(
|
||||||
|
payload: BrandMaterialCreate,
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
_auth=Depends(_procurement_writer),
|
||||||
|
):
|
||||||
if await db.get(Brand, payload.brand_id) is None:
|
if await db.get(Brand, payload.brand_id) is None:
|
||||||
raise NotFoundError("برند یافت نشد", field="brand_id")
|
raise NotFoundError("برند یافت نشد", field="brand_id")
|
||||||
if await db.get(Material, payload.material_id) is None:
|
if await db.get(Material, payload.material_id) is None:
|
||||||
@@ -107,7 +113,12 @@ async def get_brand_material(bm_id, expand: str | None = None, db: AsyncSession
|
|||||||
|
|
||||||
|
|
||||||
@router.patch("/{bm_id}")
|
@router.patch("/{bm_id}")
|
||||||
async def update_brand_material(bm_id, payload: BrandMaterialUpdate, db: AsyncSession = Depends(get_db)):
|
async def update_brand_material(
|
||||||
|
bm_id,
|
||||||
|
payload: BrandMaterialUpdate,
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
_auth=Depends(_procurement_writer),
|
||||||
|
):
|
||||||
bm = await db.get(BrandMaterial, bm_id)
|
bm = await db.get(BrandMaterial, bm_id)
|
||||||
if bm is None:
|
if bm is None:
|
||||||
raise NotFoundError("ارتباط برند-متریال یافت نشد")
|
raise NotFoundError("ارتباط برند-متریال یافت نشد")
|
||||||
@@ -120,7 +131,11 @@ async def update_brand_material(bm_id, payload: BrandMaterialUpdate, db: AsyncSe
|
|||||||
|
|
||||||
|
|
||||||
@router.delete("/{bm_id}")
|
@router.delete("/{bm_id}")
|
||||||
async def delete_brand_material(bm_id, db: AsyncSession = Depends(get_db)):
|
async def delete_brand_material(
|
||||||
|
bm_id,
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
_auth=Depends(_procurement_writer),
|
||||||
|
):
|
||||||
bm = await db.get(BrandMaterial, bm_id)
|
bm = await db.get(BrandMaterial, bm_id)
|
||||||
if bm is None:
|
if bm is None:
|
||||||
raise NotFoundError("ارتباط برند-متریال یافت نشد")
|
raise NotFoundError("ارتباط برند-متریال یافت نشد")
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ from fastapi import APIRouter, Depends, Query
|
|||||||
from sqlalchemy import func, select
|
from sqlalchemy import func, select
|
||||||
from sqlalchemy.ext.asyncio import AsyncSession
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
|
from app.auth import require_procurement_writer, require_role
|
||||||
from app.db.engine import get_db
|
from app.db.engine import get_db
|
||||||
from app.models.catalog import Brand, BrandMaterial
|
from app.models.catalog import Brand, BrandMaterial
|
||||||
from app.schemas.catalog import BrandCreate, BrandUpdate
|
from app.schemas.catalog import BrandCreate, BrandUpdate
|
||||||
@@ -11,6 +12,7 @@ from app.utils.pagination import paginate, sort_query
|
|||||||
from app.utils.serialization import to_iso
|
from app.utils.serialization import to_iso
|
||||||
|
|
||||||
router = APIRouter(prefix="/brands", tags=["brands"])
|
router = APIRouter(prefix="/brands", tags=["brands"])
|
||||||
|
_procurement_writer = require_procurement_writer()
|
||||||
|
|
||||||
|
|
||||||
def brand_to_dict(brand: Brand) -> dict:
|
def brand_to_dict(brand: Brand) -> dict:
|
||||||
@@ -42,7 +44,11 @@ async def list_brands(
|
|||||||
|
|
||||||
|
|
||||||
@router.post("", status_code=201)
|
@router.post("", status_code=201)
|
||||||
async def create_brand(payload: BrandCreate, db: AsyncSession = Depends(get_db)):
|
async def create_brand(
|
||||||
|
payload: BrandCreate,
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
_auth=Depends(_procurement_writer),
|
||||||
|
):
|
||||||
rows = (await db.execute(select(Brand).where(Brand.name == payload.name))).scalars().all()
|
rows = (await db.execute(select(Brand).where(Brand.name == payload.name))).scalars().all()
|
||||||
if any(b.country == payload.country for b in rows):
|
if any(b.country == payload.country for b in rows):
|
||||||
raise ConflictError("برندی با این نام و کشور قبلاً ثبت شده است")
|
raise ConflictError("برندی با این نام و کشور قبلاً ثبت شده است")
|
||||||
@@ -61,7 +67,12 @@ async def get_brand(brand_id, db: AsyncSession = Depends(get_db)):
|
|||||||
|
|
||||||
|
|
||||||
@router.patch("/{brand_id}")
|
@router.patch("/{brand_id}")
|
||||||
async def update_brand(brand_id, payload: BrandUpdate, db: AsyncSession = Depends(get_db)):
|
async def update_brand(
|
||||||
|
brand_id,
|
||||||
|
payload: BrandUpdate,
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
_auth=Depends(_procurement_writer),
|
||||||
|
):
|
||||||
brand = await db.get(Brand, brand_id)
|
brand = await db.get(Brand, brand_id)
|
||||||
if brand is None:
|
if brand is None:
|
||||||
raise NotFoundError("برند یافت نشد")
|
raise NotFoundError("برند یافت نشد")
|
||||||
@@ -79,7 +90,11 @@ async def update_brand(brand_id, payload: BrandUpdate, db: AsyncSession = Depend
|
|||||||
|
|
||||||
|
|
||||||
@router.delete("/{brand_id}")
|
@router.delete("/{brand_id}")
|
||||||
async def delete_brand(brand_id, db: AsyncSession = Depends(get_db)):
|
async def delete_brand(
|
||||||
|
brand_id,
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
_auth=Depends(_procurement_writer),
|
||||||
|
):
|
||||||
brand = await db.get(Brand, brand_id)
|
brand = await db.get(Brand, brand_id)
|
||||||
if brand is None:
|
if brand is None:
|
||||||
raise NotFoundError("برند یافت نشد")
|
raise NotFoundError("برند یافت نشد")
|
||||||
|
|||||||
@@ -29,9 +29,10 @@ from app.utils.preview_token import make_preview_token, verify_preview_token
|
|||||||
|
|
||||||
router = APIRouter(prefix="/quotes", tags=["files"])
|
router = APIRouter(prefix="/quotes", tags=["files"])
|
||||||
|
|
||||||
# حذف پیوستها = عملیات تدارکات (ادمین / مدیر تدارکات)؛ بارگذاری و دانلود
|
# حذف و بارگذاری پیوستها = عملیات تدارکات (ادمین / مدیر تدارکات)؛ دانلود
|
||||||
# برای هر کاربر واردشده آزاد است.
|
# برای هر کاربر واردشده آزاد است.
|
||||||
_attachment_deleter = require_role("procurement_manager", "admin")
|
_attachment_deleter = require_role("procurement_manager", "admin")
|
||||||
|
_attachment_writer = require_role("procurement_manager", "admin")
|
||||||
|
|
||||||
ALLOWED_MIME_TYPES = {
|
ALLOWED_MIME_TYPES = {
|
||||||
"image/png", "image/jpeg", "image/webp", "image/gif", "application/pdf",
|
"image/png", "image/jpeg", "image/webp", "image/gif", "application/pdf",
|
||||||
@@ -125,7 +126,7 @@ async def _attachment_or_404(
|
|||||||
# Invoice — قابل بارگذاری در هر وضعیتی (از صفحهی ویرایش)
|
# Invoice — قابل بارگذاری در هر وضعیتی (از صفحهی ویرایش)
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
@router.post("/{quote_id}/invoice", status_code=201, dependencies=[Depends(get_current_user)])
|
@router.post("/{quote_id}/invoice", status_code=201, dependencies=[Depends(_attachment_writer)])
|
||||||
async def upload_invoice(quote_id: uuid.UUID, file: UploadFile = File(...), db: AsyncSession = Depends(get_db)):
|
async def upload_invoice(quote_id: uuid.UUID, file: UploadFile = File(...), db: AsyncSession = Depends(get_db)):
|
||||||
await _quote_or_404(db, quote_id)
|
await _quote_or_404(db, quote_id)
|
||||||
mime = _validate_upload(file)
|
mime = _validate_upload(file)
|
||||||
@@ -208,7 +209,7 @@ async def delete_invoice(quote_id: uuid.UUID, attachment_id: uuid.UUID, db: Asyn
|
|||||||
# Proforma — no status restriction
|
# Proforma — no status restriction
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
@router.post("/{quote_id}/proforma", status_code=201, dependencies=[Depends(get_current_user)])
|
@router.post("/{quote_id}/proforma", status_code=201, dependencies=[Depends(_attachment_writer)])
|
||||||
async def upload_proforma(quote_id: uuid.UUID, file: UploadFile = File(...), db: AsyncSession = Depends(get_db)):
|
async def upload_proforma(quote_id: uuid.UUID, file: UploadFile = File(...), db: AsyncSession = Depends(get_db)):
|
||||||
await _quote_or_404(db, quote_id)
|
await _quote_or_404(db, quote_id)
|
||||||
mime = _validate_upload(file)
|
mime = _validate_upload(file)
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ import base64
|
|||||||
import uuid
|
import uuid
|
||||||
from contextlib import nullcontext
|
from contextlib import nullcontext
|
||||||
from dataclasses import dataclass
|
from dataclasses import dataclass
|
||||||
|
from datetime import datetime, timedelta, timezone
|
||||||
from decimal import Decimal
|
from decimal import Decimal
|
||||||
|
|
||||||
from fastapi import APIRouter, Depends, Query, Request
|
from fastapi import APIRouter, Depends, Query, Request
|
||||||
@@ -58,6 +59,7 @@ class Scope:
|
|||||||
role: str
|
role: str
|
||||||
project_id: uuid.UUID | None
|
project_id: uuid.UUID | None
|
||||||
actor: str | None
|
actor: str | None
|
||||||
|
project_ids: list[uuid.UUID] | None = None
|
||||||
|
|
||||||
|
|
||||||
async def inventory_scope(
|
async def inventory_scope(
|
||||||
@@ -75,25 +77,41 @@ async def inventory_scope(
|
|||||||
if request.headers.get("authorization"):
|
if request.headers.get("authorization"):
|
||||||
user: UserContext = await get_optional_user(request, db)
|
user: UserContext = await get_optional_user(request, db)
|
||||||
if user is not None:
|
if user is not None:
|
||||||
if user.role is None:
|
panels = user.panels or {}
|
||||||
raise ForbiddenError("نقش شما هنوز در سیستم تعیین نشده است")
|
if user.role is None and not panels:
|
||||||
# v2.6: مدیر تدارکات = ادمین دفتر — دسترسی فقطخواندنی به پنل انبار.
|
raise ForbiddenError("دسترسی شما هنوز در سیستم تعیین نشده است")
|
||||||
if user.role == "procurement_manager":
|
# ادمین: دستنخورده — همهچیز از جمله تغییر موجودی
|
||||||
|
if user.role == "admin":
|
||||||
return Scope(role="admin", project_id=project_id, actor=user.display_name)
|
return Scope(role="admin", project_id=project_id, actor=user.display_name)
|
||||||
if user.role not in ("pm", "admin"):
|
# لایه پنلها (جایگزین نقشها): پنل انبار اولویت دارد
|
||||||
raise ValidationError("نقش نامعتبر است — فقط pm یا admin برای موجودی", field="role")
|
if "inventory" in panels:
|
||||||
if user.role == "pm":
|
if panels["inventory"] == "full":
|
||||||
allowed = list(user.project_ids or [])
|
# کل سیستم و تمام پروژهها — بهجز تغییر موجودی
|
||||||
|
return Scope(role="manager", project_id=project_id, actor=user.display_name, project_ids=list(user.member_project_ids or []))
|
||||||
|
# limited: فقط پروژههای عضویت + امکان تغییر موجودی
|
||||||
|
allowed = list(user.member_project_ids or [])
|
||||||
|
if not allowed:
|
||||||
|
raise ForbiddenError("پروژهای به شما تخصیص داده نشده است")
|
||||||
if project_id is not None:
|
if project_id is not None:
|
||||||
if project_id not in allowed:
|
if project_id not in allowed:
|
||||||
raise ForbiddenError("این پروژه به شما تخصیص داده نشده است")
|
raise ForbiddenError("این پروژه به شما تخصیص داده نشده است")
|
||||||
return Scope(role="pm", project_id=project_id, actor=user.display_name)
|
return Scope(role="supervisor", project_id=project_id, actor=user.display_name, project_ids=allowed)
|
||||||
|
return Scope(role="supervisor", project_id=allowed[0], actor=user.display_name, project_ids=allowed)
|
||||||
|
# مدیر تدارکات و مدیر پروژه (میراث): دسترسی کامل به پنل انبار، اما فقطخواندنی در تغییر موجودی
|
||||||
|
if user.role in ("procurement_manager", "pm"):
|
||||||
|
return Scope(role="manager", project_id=project_id, actor=user.display_name, project_ids=list(user.project_ids or []))
|
||||||
|
if user.role == "supervisor":
|
||||||
|
allowed = list(user.project_ids or [])
|
||||||
if not allowed:
|
if not allowed:
|
||||||
raise ValidationError(
|
raise ForbiddenError("پروژه تخصیص داده نشده است")
|
||||||
"کاربر PM به هیچ پروژهای متصل نیست (projects.pm_user_id)", field="project_id"
|
if project_id is not None:
|
||||||
)
|
if project_id not in allowed:
|
||||||
return Scope(role="pm", project_id=allowed[0], actor=user.display_name)
|
raise ForbiddenError("این پروژه به شما تخصیص داده نشده است")
|
||||||
|
return Scope(role="supervisor", project_id=project_id, actor=user.display_name, project_ids=allowed)
|
||||||
|
return Scope(role="supervisor", project_id=allowed[0], actor=user.display_name, project_ids=allowed)
|
||||||
|
if user.role == "admin":
|
||||||
return Scope(role="admin", project_id=project_id, actor=user.display_name)
|
return Scope(role="admin", project_id=project_id, actor=user.display_name)
|
||||||
|
raise ValidationError("نقش نامعتبر است", field="role")
|
||||||
|
|
||||||
# Dev fallback: header-based identity (fork's placeholder mode) — only
|
# Dev fallback: header-based identity (fork's placeholder mode) — only
|
||||||
# when DEV_LOGIN_ENABLED is explicitly turned on (local testing without
|
# when DEV_LOGIN_ENABLED is explicitly turned on (local testing without
|
||||||
@@ -128,9 +146,9 @@ async def inventory_scope(
|
|||||||
return Scope(role=role, project_id=project_id, actor=actor)
|
return Scope(role=role, project_id=project_id, actor=actor)
|
||||||
|
|
||||||
|
|
||||||
def _require_pm(scope: Scope) -> None:
|
def _require_inventory_modifier(scope: Scope) -> None:
|
||||||
if scope.role != ROLE_PM:
|
if scope.role not in (ROLE_ADMIN, "admin", "supervisor", ROLE_PM):
|
||||||
raise ForbiddenError("دسترسی ادمین فقط خواندنی است — ثبت/تغییر موجودی مجاز نیست")
|
raise ForbiddenError("مدیر تدارکات و مدیر پروژه امکان تغییر موجودی انبار را ندارند — فقط سرپرست پروژه و ادمین مجاز هستند")
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
@@ -197,7 +215,9 @@ def transaction_to_dict(tx: InventoryTransaction, wh: Warehouse | None = None) -
|
|||||||
"physical_qty": float(tx.physical_qty) if tx.physical_qty is not None else None,
|
"physical_qty": float(tx.physical_qty) if tx.physical_qty is not None else None,
|
||||||
"transfer_pair_id": str(tx.transfer_pair_id) if tx.transfer_pair_id else None,
|
"transfer_pair_id": str(tx.transfer_pair_id) if tx.transfer_pair_id else None,
|
||||||
"performed_by": tx.performed_by,
|
"performed_by": tx.performed_by,
|
||||||
|
"delivered_to": tx.delivered_to,
|
||||||
"transaction_date": to_iso(tx.transaction_date),
|
"transaction_date": to_iso(tx.transaction_date),
|
||||||
|
"created_at": to_iso(tx.created_at) if hasattr(tx, "created_at") and tx.created_at else None,
|
||||||
"note": tx.note,
|
"note": tx.note,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -215,8 +235,16 @@ async def list_warehouses(
|
|||||||
db: AsyncSession = Depends(get_db),
|
db: AsyncSession = Depends(get_db),
|
||||||
):
|
):
|
||||||
stmt = select(Warehouse)
|
stmt = select(Warehouse)
|
||||||
if scope.role == ROLE_PM:
|
if scope.role in (ROLE_PM, "supervisor"):
|
||||||
stmt = stmt.where(Warehouse.project_id == scope.project_id) # force PM scope
|
allowed = scope.project_ids or ([scope.project_id] if scope.project_id else [])
|
||||||
|
if project_id is not None:
|
||||||
|
if project_id not in allowed:
|
||||||
|
raise ForbiddenError("این پروژه به شما تخصیص داده نشده است")
|
||||||
|
stmt = stmt.where(Warehouse.project_id == project_id)
|
||||||
|
elif allowed:
|
||||||
|
stmt = stmt.where(Warehouse.project_id.in_(allowed))
|
||||||
|
else:
|
||||||
|
stmt = stmt.where(Warehouse.project_id == scope.project_id)
|
||||||
elif project_id is not None:
|
elif project_id is not None:
|
||||||
stmt = stmt.where(Warehouse.project_id == project_id)
|
stmt = stmt.where(Warehouse.project_id == project_id)
|
||||||
stmt = stmt.order_by(Warehouse.name)
|
stmt = stmt.order_by(Warehouse.name)
|
||||||
@@ -248,9 +276,11 @@ async def create_warehouse(
|
|||||||
scope: Scope = Depends(inventory_scope),
|
scope: Scope = Depends(inventory_scope),
|
||||||
db: AsyncSession = Depends(get_db),
|
db: AsyncSession = Depends(get_db),
|
||||||
):
|
):
|
||||||
# PM: فقط پروژه خودش — Admin: ساختار را مدیریت میکند (هر پروژه)
|
# PM / سرپرست: فقط پروژه خودش — Admin: ساختار را مدیریت میکند (هر پروژه)
|
||||||
if scope.role == ROLE_PM and payload.project_id != scope.project_id:
|
if scope.role in (ROLE_PM, "supervisor"):
|
||||||
raise ValidationError("PM فقط میتواند برای پروژه خودش انبار بسازد", field="project_id")
|
allowed = scope.project_ids or ([scope.project_id] if scope.project_id else [])
|
||||||
|
if payload.project_id not in allowed:
|
||||||
|
raise ValidationError("شما فقط میتوانید برای پروژه تخصیصیافته به خود انبار بسازید", field="project_id")
|
||||||
if await db.get(Project, payload.project_id) is None:
|
if await db.get(Project, payload.project_id) is None:
|
||||||
raise NotFoundError("پروژه یافت نشد", field="project_id")
|
raise NotFoundError("پروژه یافت نشد", field="project_id")
|
||||||
wh = Warehouse(project_id=payload.project_id, name=payload.name, description=payload.description)
|
wh = Warehouse(project_id=payload.project_id, name=payload.name, description=payload.description)
|
||||||
@@ -267,8 +297,9 @@ async def update_warehouse(
|
|||||||
db: AsyncSession = Depends(get_db),
|
db: AsyncSession = Depends(get_db),
|
||||||
):
|
):
|
||||||
wh = await get_warehouse_or_404(db, warehouse_id)
|
wh = await get_warehouse_or_404(db, warehouse_id)
|
||||||
if scope.role == ROLE_PM:
|
if scope.role in (ROLE_PM, "supervisor"):
|
||||||
if scope.project_id != wh.project_id:
|
allowed = scope.project_ids or ([scope.project_id] if scope.project_id else [])
|
||||||
|
if wh.project_id not in allowed:
|
||||||
raise ForbiddenError("این انبار متعلق به پروژه شما نیست")
|
raise ForbiddenError("این انبار متعلق به پروژه شما نیست")
|
||||||
if payload.name is not None:
|
if payload.name is not None:
|
||||||
wh.name = payload.name
|
wh.name = payload.name
|
||||||
@@ -292,7 +323,9 @@ async def delete_warehouse(
|
|||||||
db: AsyncSession = Depends(get_db),
|
db: AsyncSession = Depends(get_db),
|
||||||
):
|
):
|
||||||
wh = await get_warehouse_or_404(db, warehouse_id)
|
wh = await get_warehouse_or_404(db, warehouse_id)
|
||||||
if scope.role == ROLE_PM and scope.project_id != wh.project_id:
|
if scope.role in (ROLE_PM, "supervisor"):
|
||||||
|
allowed = scope.project_ids or ([scope.project_id] if scope.project_id else [])
|
||||||
|
if wh.project_id not in allowed:
|
||||||
raise ForbiddenError("این انبار متعلق به پروژه شما نیست")
|
raise ForbiddenError("این انبار متعلق به پروژه شما نیست")
|
||||||
# inventory rows cascade via DDL; transactions are RESTRICTed through
|
# inventory rows cascade via DDL; transactions are RESTRICTed through
|
||||||
# inventory cascade — block deletion if any stock history exists.
|
# inventory cascade — block deletion if any stock history exists.
|
||||||
@@ -323,7 +356,19 @@ async def list_inventory(
|
|||||||
db: AsyncSession = Depends(get_db),
|
db: AsyncSession = Depends(get_db),
|
||||||
):
|
):
|
||||||
stmt = select(InventoryItem)
|
stmt = select(InventoryItem)
|
||||||
if scope.role == ROLE_PM:
|
if scope.role in (ROLE_PM, "supervisor"):
|
||||||
|
allowed = scope.project_ids or ([scope.project_id] if scope.project_id else [])
|
||||||
|
if project_id is not None:
|
||||||
|
if project_id not in allowed:
|
||||||
|
raise ForbiddenError("این پروژه به شما تخصیص داده نشده است")
|
||||||
|
stmt = stmt.join(Warehouse, Warehouse.id == InventoryItem.warehouse_id).where(
|
||||||
|
Warehouse.project_id == project_id
|
||||||
|
)
|
||||||
|
elif allowed:
|
||||||
|
stmt = stmt.join(Warehouse, Warehouse.id == InventoryItem.warehouse_id).where(
|
||||||
|
Warehouse.project_id.in_(allowed)
|
||||||
|
)
|
||||||
|
else:
|
||||||
stmt = stmt.join(Warehouse, Warehouse.id == InventoryItem.warehouse_id).where(
|
stmt = stmt.join(Warehouse, Warehouse.id == InventoryItem.warehouse_id).where(
|
||||||
Warehouse.project_id == scope.project_id
|
Warehouse.project_id == scope.project_id
|
||||||
)
|
)
|
||||||
@@ -388,7 +433,15 @@ async def list_transactions(
|
|||||||
stmt = select(InventoryTransaction).join(
|
stmt = select(InventoryTransaction).join(
|
||||||
InventoryItem, InventoryItem.id == InventoryTransaction.inventory_id
|
InventoryItem, InventoryItem.id == InventoryTransaction.inventory_id
|
||||||
).join(Warehouse, Warehouse.id == InventoryItem.warehouse_id)
|
).join(Warehouse, Warehouse.id == InventoryItem.warehouse_id)
|
||||||
if scope.role == ROLE_PM:
|
if scope.role in (ROLE_PM, "supervisor"):
|
||||||
|
allowed = scope.project_ids or ([scope.project_id] if scope.project_id else [])
|
||||||
|
if project_id is not None:
|
||||||
|
if project_id not in allowed:
|
||||||
|
raise ForbiddenError("این پروژه به شما تخصیص داده نشده است")
|
||||||
|
stmt = stmt.where(Warehouse.project_id == project_id)
|
||||||
|
elif allowed:
|
||||||
|
stmt = stmt.where(Warehouse.project_id.in_(allowed))
|
||||||
|
else:
|
||||||
stmt = stmt.where(Warehouse.project_id == scope.project_id)
|
stmt = stmt.where(Warehouse.project_id == scope.project_id)
|
||||||
elif project_id is not None:
|
elif project_id is not None:
|
||||||
stmt = stmt.where(Warehouse.project_id == project_id)
|
stmt = stmt.where(Warehouse.project_id == project_id)
|
||||||
@@ -397,9 +450,21 @@ async def list_transactions(
|
|||||||
if transaction_type is not None:
|
if transaction_type is not None:
|
||||||
stmt = stmt.where(InventoryTransaction.transaction_type == transaction_type)
|
stmt = stmt.where(InventoryTransaction.transaction_type == transaction_type)
|
||||||
if date_from is not None:
|
if date_from is not None:
|
||||||
stmt = stmt.where(InventoryTransaction.transaction_date >= date_from)
|
# asyncpg تایپ سختگیرانه دارد: رشته باید به datetime آگاه تبدیل شود.
|
||||||
|
# دیتابیس با TZ=UTC اجرا میشود، پس «YYYY-MM-DD» یعنی نیمهشب UTC
|
||||||
|
# (همان معناشناسی کست قدیمیِ رشته در PostgreSQL).
|
||||||
|
stmt = stmt.where(
|
||||||
|
InventoryTransaction.transaction_date
|
||||||
|
>= datetime.fromisoformat(date_from).replace(tzinfo=timezone.utc)
|
||||||
|
)
|
||||||
if date_to is not None:
|
if date_to is not None:
|
||||||
stmt = stmt.where(InventoryTransaction.transaction_date < date_to + " 24:00:00")
|
stmt = stmt.where(
|
||||||
|
InventoryTransaction.transaction_date
|
||||||
|
< datetime.fromisoformat(date_to).replace(tzinfo=timezone.utc) + timedelta(days=1)
|
||||||
|
)
|
||||||
|
if not sort or sort == "-transaction_date":
|
||||||
|
stmt = stmt.order_by(InventoryTransaction.transaction_date.desc(), InventoryTransaction.created_at.desc())
|
||||||
|
else:
|
||||||
stmt = sort_query(stmt, InventoryTransaction, sort, default="-transaction_date")
|
stmt = sort_query(stmt, InventoryTransaction, sort, default="-transaction_date")
|
||||||
items, meta = await paginate(stmt, page, page_size, db)
|
items, meta = await paginate(stmt, page, page_size, db)
|
||||||
|
|
||||||
@@ -454,7 +519,9 @@ async def inventory_history(
|
|||||||
if item is None:
|
if item is None:
|
||||||
raise NotFoundError("موجودی یافت نشد")
|
raise NotFoundError("موجودی یافت نشد")
|
||||||
wh = await get_warehouse_or_404(db, item.warehouse_id)
|
wh = await get_warehouse_or_404(db, item.warehouse_id)
|
||||||
if scope.role == ROLE_PM and wh.project_id != scope.project_id:
|
if scope.role in (ROLE_PM, "supervisor"):
|
||||||
|
allowed = scope.project_ids or ([scope.project_id] if scope.project_id else [])
|
||||||
|
if wh.project_id not in allowed:
|
||||||
raise ForbiddenError("این موجودی متعلق به پروژه شما نیست")
|
raise ForbiddenError("این موجودی متعلق به پروژه شما نیست")
|
||||||
txs = (await db.execute(
|
txs = (await db.execute(
|
||||||
select(InventoryTransaction)
|
select(InventoryTransaction)
|
||||||
@@ -474,17 +541,19 @@ async def create_transaction(
|
|||||||
scope: Scope = Depends(inventory_scope),
|
scope: Scope = Depends(inventory_scope),
|
||||||
db: AsyncSession = Depends(get_db),
|
db: AsyncSession = Depends(get_db),
|
||||||
):
|
):
|
||||||
_require_pm(scope)
|
_require_inventory_modifier(scope)
|
||||||
# No explicit db.begin(): the session may already be inside an implicit
|
# No explicit db.begin(): the session may already be inside an implicit
|
||||||
# transaction (inventory_scope read from it in the JWT path); get_db
|
# transaction (inventory_scope read from it in the JWT path); get_db
|
||||||
# commits on success / rolls back on failure.
|
# commits on success / rolls back on failure.
|
||||||
with nullcontext():
|
with nullcontext():
|
||||||
wh = await get_warehouse_or_404(db, payload.warehouse_id)
|
wh = await get_warehouse_or_404(db, payload.warehouse_id)
|
||||||
if wh.project_id != scope.project_id:
|
allowed = scope.project_ids or ([scope.project_id] if scope.project_id else [])
|
||||||
|
if scope.role in (ROLE_PM, "supervisor"):
|
||||||
|
if wh.project_id not in allowed:
|
||||||
raise ForbiddenError("این انبار متعلق به پروژه شما نیست")
|
raise ForbiddenError("این انبار متعلق به پروژه شما نیست")
|
||||||
if payload.dest_warehouse_id is not None:
|
if payload.dest_warehouse_id is not None:
|
||||||
dest = await get_warehouse_or_404(db, payload.dest_warehouse_id)
|
dest = await get_warehouse_or_404(db, payload.dest_warehouse_id)
|
||||||
if dest.project_id != scope.project_id:
|
if dest.project_id not in allowed:
|
||||||
raise ForbiddenError("انبار مقصد متعلق به پروژه شما نیست")
|
raise ForbiddenError("انبار مقصد متعلق به پروژه شما نیست")
|
||||||
txs = await apply_transaction(db, payload, performed_by=scope.actor)
|
txs = await apply_transaction(db, payload, performed_by=scope.actor)
|
||||||
await audit_record(
|
await audit_record(
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ from fastapi import APIRouter, Depends
|
|||||||
from sqlalchemy import select
|
from sqlalchemy import select
|
||||||
from sqlalchemy.ext.asyncio import AsyncSession
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
|
from app.auth import require_procurement_writer, require_role
|
||||||
from app.db.engine import get_db
|
from app.db.engine import get_db
|
||||||
from app.models.procurement import ItemDecision, ItemReceipt, LineItem
|
from app.models.procurement import ItemDecision, ItemReceipt, LineItem
|
||||||
from app.schemas.procurement import ReceiptCreate, ReceiptUpdate
|
from app.schemas.procurement import ReceiptCreate, ReceiptUpdate
|
||||||
@@ -14,6 +15,7 @@ router = APIRouter(
|
|||||||
prefix="/quotes/{quote_id}/line-items/{line_item_id}/receipt",
|
prefix="/quotes/{quote_id}/line-items/{line_item_id}/receipt",
|
||||||
tags=["item-receipts"],
|
tags=["item-receipts"],
|
||||||
)
|
)
|
||||||
|
_procurement_writer = require_procurement_writer()
|
||||||
|
|
||||||
|
|
||||||
async def _line_item_or_404(db: AsyncSession, quote_id, line_item_id) -> LineItem:
|
async def _line_item_or_404(db: AsyncSession, quote_id, line_item_id) -> LineItem:
|
||||||
@@ -45,7 +47,13 @@ async def get_receipt(quote_id, line_item_id, db: AsyncSession = Depends(get_db)
|
|||||||
|
|
||||||
|
|
||||||
@router.post("", status_code=201)
|
@router.post("", status_code=201)
|
||||||
async def create_receipt(quote_id, line_item_id, payload: ReceiptCreate, db: AsyncSession = Depends(get_db)):
|
async def create_receipt(
|
||||||
|
quote_id,
|
||||||
|
line_item_id,
|
||||||
|
payload: ReceiptCreate,
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
_auth=Depends(_procurement_writer),
|
||||||
|
):
|
||||||
await _line_item_or_404(db, quote_id, line_item_id)
|
await _line_item_or_404(db, quote_id, line_item_id)
|
||||||
decision = await _decision_or_404(db, line_item_id)
|
decision = await _decision_or_404(db, line_item_id)
|
||||||
existing = await db.scalar(select(ItemReceipt).where(ItemReceipt.item_decision_id == decision.id))
|
existing = await db.scalar(select(ItemReceipt).where(ItemReceipt.item_decision_id == decision.id))
|
||||||
@@ -65,7 +73,13 @@ async def create_receipt(quote_id, line_item_id, payload: ReceiptCreate, db: Asy
|
|||||||
|
|
||||||
|
|
||||||
@router.patch("")
|
@router.patch("")
|
||||||
async def update_receipt(quote_id, line_item_id, payload: ReceiptUpdate, db: AsyncSession = Depends(get_db)):
|
async def update_receipt(
|
||||||
|
quote_id,
|
||||||
|
line_item_id,
|
||||||
|
payload: ReceiptUpdate,
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
_auth=Depends(_procurement_writer),
|
||||||
|
):
|
||||||
await _line_item_or_404(db, quote_id, line_item_id)
|
await _line_item_or_404(db, quote_id, line_item_id)
|
||||||
decision = await db.scalar(select(ItemDecision).where(ItemDecision.line_item_id == line_item_id))
|
decision = await db.scalar(select(ItemDecision).where(ItemDecision.line_item_id == line_item_id))
|
||||||
if decision is None:
|
if decision is None:
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ from fastapi import APIRouter, Depends
|
|||||||
from sqlalchemy import select
|
from sqlalchemy import select
|
||||||
from sqlalchemy.ext.asyncio import AsyncSession
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
|
from app.auth import require_procurement_writer, require_role
|
||||||
from app.db.engine import get_db
|
from app.db.engine import get_db
|
||||||
from app.models.procurement import (
|
from app.models.procurement import (
|
||||||
ItemDecision,
|
ItemDecision,
|
||||||
@@ -23,6 +24,7 @@ router = APIRouter(
|
|||||||
prefix="/quotes/{quote_id}/line-items/{line_item_id}/termsheets",
|
prefix="/quotes/{quote_id}/line-items/{line_item_id}/termsheets",
|
||||||
tags=["item-termsheets"],
|
tags=["item-termsheets"],
|
||||||
)
|
)
|
||||||
|
_procurement_writer = require_procurement_writer()
|
||||||
|
|
||||||
|
|
||||||
async def _line_item_or_404(db: AsyncSession, quote_id, line_item_id) -> LineItem:
|
async def _line_item_or_404(db: AsyncSession, quote_id, line_item_id) -> LineItem:
|
||||||
@@ -58,7 +60,11 @@ async def list_item_termsheets(quote_id, line_item_id, db: AsyncSession = Depend
|
|||||||
|
|
||||||
@router.post("", status_code=201)
|
@router.post("", status_code=201)
|
||||||
async def create_item_termsheet(
|
async def create_item_termsheet(
|
||||||
quote_id, line_item_id, payload: ItemTermsheetCreate, db: AsyncSession = Depends(get_db)
|
quote_id,
|
||||||
|
line_item_id,
|
||||||
|
payload: ItemTermsheetCreate,
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
_auth=Depends(_procurement_writer),
|
||||||
):
|
):
|
||||||
async with db.begin():
|
async with db.begin():
|
||||||
li = await _line_item_or_404(db, quote_id, line_item_id)
|
li = await _line_item_or_404(db, quote_id, line_item_id)
|
||||||
@@ -93,7 +99,12 @@ async def create_item_termsheet(
|
|||||||
|
|
||||||
@router.patch("/{item_termsheet_id}")
|
@router.patch("/{item_termsheet_id}")
|
||||||
async def update_item_termsheet(
|
async def update_item_termsheet(
|
||||||
quote_id, line_item_id, item_termsheet_id, payload: ItemTermsheetUpdate, db: AsyncSession = Depends(get_db)
|
quote_id,
|
||||||
|
line_item_id,
|
||||||
|
item_termsheet_id,
|
||||||
|
payload: ItemTermsheetUpdate,
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
_auth=Depends(_procurement_writer),
|
||||||
):
|
):
|
||||||
li = await _line_item_or_404(db, quote_id, line_item_id)
|
li = await _line_item_or_404(db, quote_id, line_item_id)
|
||||||
quote = await db.get(Quote, quote_id)
|
quote = await db.get(Quote, quote_id)
|
||||||
@@ -114,7 +125,11 @@ async def update_item_termsheet(
|
|||||||
|
|
||||||
@router.delete("/{item_termsheet_id}")
|
@router.delete("/{item_termsheet_id}")
|
||||||
async def delete_item_termsheet(
|
async def delete_item_termsheet(
|
||||||
quote_id, line_item_id, item_termsheet_id, db: AsyncSession = Depends(get_db)
|
quote_id,
|
||||||
|
line_item_id,
|
||||||
|
item_termsheet_id,
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
_auth=Depends(_procurement_writer),
|
||||||
):
|
):
|
||||||
it = await db.scalar(
|
it = await db.scalar(
|
||||||
select(ItemTermsheet).where(ItemTermsheet.id == item_termsheet_id, ItemTermsheet.line_item_id == line_item_id)
|
select(ItemTermsheet).where(ItemTermsheet.id == item_termsheet_id, ItemTermsheet.line_item_id == line_item_id)
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ from fastapi import APIRouter, Depends
|
|||||||
from sqlalchemy import select
|
from sqlalchemy import select
|
||||||
from sqlalchemy.ext.asyncio import AsyncSession
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
|
from app.auth import require_procurement_writer, require_role
|
||||||
from app.db.engine import get_db
|
from app.db.engine import get_db
|
||||||
from app.models.catalog import AttributeDefinition, Unit
|
from app.models.catalog import AttributeDefinition, Unit
|
||||||
from app.models.procurement import LineItem, LineItemSpec, Quote
|
from app.models.procurement import LineItem, LineItemSpec, Quote
|
||||||
@@ -12,6 +13,7 @@ from app.services.eav_service import flatten_eav_values
|
|||||||
from app.utils.errors import ConflictError, NotFoundError
|
from app.utils.errors import ConflictError, NotFoundError
|
||||||
|
|
||||||
router = APIRouter(prefix="/quotes/{quote_id}/line-items/{line_item_id}/specs", tags=["line-item-specs"])
|
router = APIRouter(prefix="/quotes/{quote_id}/line-items/{line_item_id}/specs", tags=["line-item-specs"])
|
||||||
|
_procurement_writer = require_procurement_writer()
|
||||||
|
|
||||||
|
|
||||||
async def _line_item_or_404(db: AsyncSession, quote_id, line_item_id) -> LineItem:
|
async def _line_item_or_404(db: AsyncSession, quote_id, line_item_id) -> LineItem:
|
||||||
@@ -53,7 +55,13 @@ async def get_line_item_specs(quote_id, line_item_id, db: AsyncSession = Depends
|
|||||||
|
|
||||||
|
|
||||||
@router.put("")
|
@router.put("")
|
||||||
async def put_line_item_specs(quote_id, line_item_id, payload: SpecsPutIn, db: AsyncSession = Depends(get_db)):
|
async def put_line_item_specs(
|
||||||
|
quote_id,
|
||||||
|
line_item_id,
|
||||||
|
payload: SpecsPutIn,
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
_auth=Depends(_procurement_writer),
|
||||||
|
):
|
||||||
"""FULL replacement — specs not in the payload are DELETED (P1-19)."""
|
"""FULL replacement — specs not in the payload are DELETED (P1-19)."""
|
||||||
async with db.begin():
|
async with db.begin():
|
||||||
li = await _line_item_or_404(db, quote_id, line_item_id)
|
li = await _line_item_or_404(db, quote_id, line_item_id)
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ from fastapi import APIRouter, Depends, Query
|
|||||||
from sqlalchemy import select
|
from sqlalchemy import select
|
||||||
from sqlalchemy.ext.asyncio import AsyncSession
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
|
from app.auth import require_procurement_writer, require_role
|
||||||
from app.db.engine import get_db
|
from app.db.engine import get_db
|
||||||
from app.models.catalog import Material, Unit
|
from app.models.catalog import Material, Unit
|
||||||
from app.models.procurement import ItemDecision, LineItem, Quote
|
from app.models.procurement import ItemDecision, LineItem, Quote
|
||||||
@@ -14,6 +15,7 @@ from app.utils.errors import ConflictError, NotFoundError
|
|||||||
from app.utils.pagination import paginate, sort_query
|
from app.utils.pagination import paginate, sort_query
|
||||||
|
|
||||||
router = APIRouter(prefix="/quotes/{quote_id}/line-items", tags=["line-items"])
|
router = APIRouter(prefix="/quotes/{quote_id}/line-items", tags=["line-items"])
|
||||||
|
_procurement_writer = require_procurement_writer()
|
||||||
|
|
||||||
|
|
||||||
async def _quote_or_404(db: AsyncSession, quote_id) -> Quote:
|
async def _quote_or_404(db: AsyncSession, quote_id) -> Quote:
|
||||||
@@ -50,7 +52,12 @@ async def list_line_items(
|
|||||||
|
|
||||||
|
|
||||||
@router.post("", status_code=201)
|
@router.post("", status_code=201)
|
||||||
async def create_line_item(quote_id, payload: LineItemCreate, db: AsyncSession = Depends(get_db)):
|
async def create_line_item(
|
||||||
|
quote_id,
|
||||||
|
payload: LineItemCreate,
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
_auth=Depends(_procurement_writer),
|
||||||
|
):
|
||||||
async with db.begin():
|
async with db.begin():
|
||||||
quote = await _quote_or_404(db, quote_id)
|
quote = await _quote_or_404(db, quote_id)
|
||||||
if quote.status != "offered":
|
if quote.status != "offered":
|
||||||
@@ -89,7 +96,11 @@ async def get_line_item(
|
|||||||
|
|
||||||
@router.patch("/{line_item_id}")
|
@router.patch("/{line_item_id}")
|
||||||
async def update_line_item(
|
async def update_line_item(
|
||||||
quote_id, line_item_id, payload: LineItemUpdate, db: AsyncSession = Depends(get_db)
|
quote_id,
|
||||||
|
line_item_id,
|
||||||
|
payload: LineItemUpdate,
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
_auth=Depends(_procurement_writer),
|
||||||
):
|
):
|
||||||
li = await _line_item_or_404(db, quote_id, line_item_id)
|
li = await _line_item_or_404(db, quote_id, line_item_id)
|
||||||
quote = await _quote_or_404(db, quote_id)
|
quote = await _quote_or_404(db, quote_id)
|
||||||
@@ -131,7 +142,12 @@ async def update_line_item(
|
|||||||
|
|
||||||
|
|
||||||
@router.delete("/{line_item_id}")
|
@router.delete("/{line_item_id}")
|
||||||
async def delete_line_item(quote_id, line_item_id, db: AsyncSession = Depends(get_db)):
|
async def delete_line_item(
|
||||||
|
quote_id,
|
||||||
|
line_item_id,
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
_auth=Depends(_procurement_writer),
|
||||||
|
):
|
||||||
li = await _line_item_or_404(db, quote_id, line_item_id)
|
li = await _line_item_or_404(db, quote_id, line_item_id)
|
||||||
quote = await _quote_or_404(db, quote_id)
|
quote = await _quote_or_404(db, quote_id)
|
||||||
if quote.status != "offered":
|
if quote.status != "offered":
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ from fastapi import APIRouter, Depends, Query
|
|||||||
from sqlalchemy import func, or_, select
|
from sqlalchemy import func, or_, select
|
||||||
from sqlalchemy.ext.asyncio import AsyncSession
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
|
from app.auth import require_procurement_writer, require_role
|
||||||
from app.db.engine import get_db
|
from app.db.engine import get_db
|
||||||
from app.models.catalog import MaterialCategory
|
from app.models.catalog import MaterialCategory
|
||||||
from app.models.procurement import Supplier
|
from app.models.procurement import Supplier
|
||||||
@@ -12,6 +13,7 @@ from app.utils.pagination import paginate, sort_query
|
|||||||
from app.utils.serialization import to_iso
|
from app.utils.serialization import to_iso
|
||||||
|
|
||||||
router = APIRouter(prefix="/material-categories", tags=["material-categories"])
|
router = APIRouter(prefix="/material-categories", tags=["material-categories"])
|
||||||
|
_procurement_writer = require_procurement_writer()
|
||||||
|
|
||||||
|
|
||||||
def category_to_dict(category: MaterialCategory) -> dict:
|
def category_to_dict(category: MaterialCategory) -> dict:
|
||||||
@@ -46,7 +48,11 @@ async def list_categories(
|
|||||||
|
|
||||||
|
|
||||||
@router.post("", status_code=201)
|
@router.post("", status_code=201)
|
||||||
async def create_category(payload: MaterialCategoryCreate, db: AsyncSession = Depends(get_db)):
|
async def create_category(
|
||||||
|
payload: MaterialCategoryCreate,
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
_auth=Depends(_procurement_writer),
|
||||||
|
):
|
||||||
duplicate = await db.scalar(select(MaterialCategory.id).where(MaterialCategory.slug == payload.slug))
|
duplicate = await db.scalar(select(MaterialCategory.id).where(MaterialCategory.slug == payload.slug))
|
||||||
if duplicate is not None:
|
if duplicate is not None:
|
||||||
raise ConflictError("دستهبندی با این slug قبلاً ثبت شده است", field="slug")
|
raise ConflictError("دستهبندی با این slug قبلاً ثبت شده است", field="slug")
|
||||||
@@ -70,7 +76,12 @@ async def get_category(category_id, db: AsyncSession = Depends(get_db)):
|
|||||||
|
|
||||||
|
|
||||||
@router.patch("/{category_id}")
|
@router.patch("/{category_id}")
|
||||||
async def update_category(category_id, payload: MaterialCategoryUpdate, db: AsyncSession = Depends(get_db)):
|
async def update_category(
|
||||||
|
category_id,
|
||||||
|
payload: MaterialCategoryUpdate,
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
_auth=Depends(_procurement_writer),
|
||||||
|
):
|
||||||
category = await db.get(MaterialCategory, category_id)
|
category = await db.get(MaterialCategory, category_id)
|
||||||
if category is None:
|
if category is None:
|
||||||
raise NotFoundError("دستهبندی یافت نشد")
|
raise NotFoundError("دستهبندی یافت نشد")
|
||||||
@@ -92,7 +103,11 @@ async def update_category(category_id, payload: MaterialCategoryUpdate, db: Asyn
|
|||||||
|
|
||||||
|
|
||||||
@router.delete("/{category_id}")
|
@router.delete("/{category_id}")
|
||||||
async def delete_category(category_id, db: AsyncSession = Depends(get_db)):
|
async def delete_category(
|
||||||
|
category_id,
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
_auth=Depends(_procurement_writer),
|
||||||
|
):
|
||||||
category = await db.get(MaterialCategory, category_id)
|
category = await db.get(MaterialCategory, category_id)
|
||||||
if category is None:
|
if category is None:
|
||||||
raise NotFoundError("دستهبندی یافت نشد")
|
raise NotFoundError("دستهبندی یافت نشد")
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ from fastapi import APIRouter, Depends, Query, Request
|
|||||||
from sqlalchemy import exists, select
|
from sqlalchemy import exists, select
|
||||||
from sqlalchemy.ext.asyncio import AsyncSession
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
|
from app.auth import require_procurement_writer, require_role
|
||||||
from app.db.engine import get_db
|
from app.db.engine import get_db
|
||||||
from app.models.catalog import (
|
from app.models.catalog import (
|
||||||
AttributeDefinition,
|
AttributeDefinition,
|
||||||
@@ -38,6 +39,7 @@ from app.utils.errors import ConflictError, NotFoundError, ValidationError
|
|||||||
from app.utils.pagination import paginate, sort_query
|
from app.utils.pagination import paginate, sort_query
|
||||||
|
|
||||||
router = APIRouter(prefix="/materials", tags=["materials"])
|
router = APIRouter(prefix="/materials", tags=["materials"])
|
||||||
|
_procurement_writer = require_procurement_writer()
|
||||||
|
|
||||||
|
|
||||||
def _coerce_filter_value(data_type: str, raw: str):
|
def _coerce_filter_value(data_type: str, raw: str):
|
||||||
@@ -125,7 +127,10 @@ async def list_materials(
|
|||||||
|
|
||||||
@router.post("", status_code=201)
|
@router.post("", status_code=201)
|
||||||
async def create_material(
|
async def create_material(
|
||||||
payload: MaterialCreate, expand: str | None = None, db: AsyncSession = Depends(get_db)
|
payload: MaterialCreate,
|
||||||
|
expand: str | None = None,
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
_auth=Depends(_procurement_writer),
|
||||||
):
|
):
|
||||||
material = await material_service.create_material(db, payload)
|
material = await material_service.create_material(db, payload)
|
||||||
return {"data": await serialize_material(db, material, parse_expand(expand))}
|
return {"data": await serialize_material(db, material, parse_expand(expand))}
|
||||||
@@ -140,7 +145,12 @@ async def get_material(material_id, expand: str | None = None, db: AsyncSession
|
|||||||
|
|
||||||
|
|
||||||
@router.patch("/{material_id}")
|
@router.patch("/{material_id}")
|
||||||
async def update_material(material_id, payload: MaterialUpdate, db: AsyncSession = Depends(get_db)):
|
async def update_material(
|
||||||
|
material_id,
|
||||||
|
payload: MaterialUpdate,
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
_auth=Depends(_procurement_writer),
|
||||||
|
):
|
||||||
material = await db.get(Material, material_id)
|
material = await db.get(Material, material_id)
|
||||||
if material is None:
|
if material is None:
|
||||||
raise NotFoundError("متریال یافت نشد")
|
raise NotFoundError("متریال یافت نشد")
|
||||||
@@ -149,7 +159,11 @@ async def update_material(material_id, payload: MaterialUpdate, db: AsyncSession
|
|||||||
|
|
||||||
|
|
||||||
@router.delete("/{material_id}")
|
@router.delete("/{material_id}")
|
||||||
async def delete_material(material_id, db: AsyncSession = Depends(get_db)):
|
async def delete_material(
|
||||||
|
material_id,
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
_auth=Depends(_procurement_writer),
|
||||||
|
):
|
||||||
material = await db.get(Material, material_id)
|
material = await db.get(Material, material_id)
|
||||||
if material is None:
|
if material is None:
|
||||||
raise NotFoundError("متریال یافت نشد")
|
raise NotFoundError("متریال یافت نشد")
|
||||||
@@ -248,7 +262,10 @@ async def list_material_units(
|
|||||||
|
|
||||||
@router.post("/{material_id}/units", status_code=201)
|
@router.post("/{material_id}/units", status_code=201)
|
||||||
async def create_material_unit(
|
async def create_material_unit(
|
||||||
material_id, payload: MaterialUnitCreate, db: AsyncSession = Depends(get_db)
|
material_id,
|
||||||
|
payload: MaterialUnitCreate,
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
_auth=Depends(_procurement_writer),
|
||||||
):
|
):
|
||||||
async with db.begin():
|
async with db.begin():
|
||||||
await _material_or_404(db, material_id)
|
await _material_or_404(db, material_id)
|
||||||
@@ -287,7 +304,11 @@ async def create_material_unit(
|
|||||||
|
|
||||||
@router.patch("/{material_id}/units/{mu_id}")
|
@router.patch("/{material_id}/units/{mu_id}")
|
||||||
async def update_material_unit(
|
async def update_material_unit(
|
||||||
material_id, mu_id, payload: MaterialUnitUpdate, db: AsyncSession = Depends(get_db)
|
material_id,
|
||||||
|
mu_id,
|
||||||
|
payload: MaterialUnitUpdate,
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
_auth=Depends(_procurement_writer),
|
||||||
):
|
):
|
||||||
async with db.begin():
|
async with db.begin():
|
||||||
mu = await db.scalar(
|
mu = await db.scalar(
|
||||||
@@ -319,7 +340,12 @@ async def update_material_unit(
|
|||||||
|
|
||||||
|
|
||||||
@router.delete("/{material_id}/units/{mu_id}")
|
@router.delete("/{material_id}/units/{mu_id}")
|
||||||
async def delete_material_unit(material_id, mu_id, db: AsyncSession = Depends(get_db)):
|
async def delete_material_unit(
|
||||||
|
material_id,
|
||||||
|
mu_id,
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
_auth=Depends(_procurement_writer),
|
||||||
|
):
|
||||||
mu = await db.scalar(
|
mu = await db.scalar(
|
||||||
select(MaterialUnit).where(MaterialUnit.id == mu_id, MaterialUnit.material_id == material_id)
|
select(MaterialUnit).where(MaterialUnit.id == mu_id, MaterialUnit.material_id == material_id)
|
||||||
)
|
)
|
||||||
@@ -365,7 +391,10 @@ async def get_material_attribute_values(
|
|||||||
|
|
||||||
@router.put("/{material_id}/attribute-values")
|
@router.put("/{material_id}/attribute-values")
|
||||||
async def put_material_attribute_values(
|
async def put_material_attribute_values(
|
||||||
material_id, payload: MaterialAttributeValuesPut, db: AsyncSession = Depends(get_db)
|
material_id,
|
||||||
|
payload: MaterialAttributeValuesPut,
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
_auth=Depends(_procurement_writer),
|
||||||
):
|
):
|
||||||
"""FULL replacement of a material's EAV values (empty array deletes all)."""
|
"""FULL replacement of a material's EAV values (empty array deletes all)."""
|
||||||
async with db.begin():
|
async with db.begin():
|
||||||
|
|||||||
+33
-12
@@ -71,16 +71,17 @@ class ArrivalScope:
|
|||||||
user_id: uuid.UUID | None
|
user_id: uuid.UUID | None
|
||||||
project_id: uuid.UUID | None # PM's active project; admin: optional filter
|
project_id: uuid.UUID | None # PM's active project; admin: optional filter
|
||||||
display_name: str
|
display_name: str
|
||||||
|
project_ids: list[uuid.UUID] | None = None
|
||||||
|
|
||||||
|
|
||||||
async def arrivals_scope(
|
async def arrivals_scope(
|
||||||
request: Request,
|
request: Request,
|
||||||
project_id: uuid.UUID | None = Query(default=None, description="پروژه فعال (PM: الزامی برای دادههای پروژه)"),
|
project_id: uuid.UUID | None = Query(default=None, description="پروژه فعال (PM / سرپرست: دادههای پروژه)"),
|
||||||
db: AsyncSession = Depends(get_db),
|
db: AsyncSession = Depends(get_db),
|
||||||
) -> ArrivalScope:
|
) -> ArrivalScope:
|
||||||
"""Resolve the arrivals caller — Casdoor JWT first, dev headers as fallback.
|
"""Resolve the arrivals caller — Casdoor JWT first, dev headers as fallback.
|
||||||
|
|
||||||
PM → scoped to the requested project, which must be one they manage
|
PM / supervisor → scoped to the requested project, which must be one they manage
|
||||||
(projects.pm_user_id, 1:N); without the param, their first project.
|
(projects.pm_user_id, 1:N); without the param, their first project.
|
||||||
Admin / procurement manager → all projects (param = optional filter).
|
Admin / procurement manager → all projects (param = optional filter).
|
||||||
"""
|
"""
|
||||||
@@ -89,19 +90,19 @@ async def arrivals_scope(
|
|||||||
if ctx is not None:
|
if ctx is not None:
|
||||||
if ctx.role is None:
|
if ctx.role is None:
|
||||||
raise ForbiddenError("نقش شما هنوز در سیستم تعیین نشده است")
|
raise ForbiddenError("نقش شما هنوز در سیستم تعیین نشده است")
|
||||||
if ctx.role == "pm":
|
if ctx.role in ("pm", "supervisor"):
|
||||||
allowed = list(ctx.project_ids or [])
|
allowed = list(ctx.project_ids or [])
|
||||||
if project_id is not None:
|
if project_id is not None:
|
||||||
if project_id not in allowed:
|
if project_id not in allowed:
|
||||||
raise ForbiddenError("این پروژه به شما تخصیص داده نشده است")
|
raise ForbiddenError("این پروژه به شما تخصیص داده نشده است")
|
||||||
return ArrivalScope(role="pm", user_id=ctx.user.id, project_id=project_id, display_name=ctx.display_name)
|
return ArrivalScope(role="pm", user_id=ctx.user.id, project_id=project_id, display_name=ctx.display_name, project_ids=allowed)
|
||||||
if not allowed:
|
if not allowed:
|
||||||
raise ForbiddenError("شما به هیچ پروژهای متصل نیستید (projects.pm_user_id)")
|
raise ForbiddenError("شما به هیچ پروژهای متصل نیستید (projects.pm_user_id)")
|
||||||
return ArrivalScope(role="pm", user_id=ctx.user.id, project_id=allowed[0], display_name=ctx.display_name)
|
return ArrivalScope(role="pm", user_id=ctx.user.id, project_id=allowed[0], display_name=ctx.display_name, project_ids=allowed)
|
||||||
if ctx.role in ("admin", "procurement_manager"):
|
if ctx.role in ("admin", "procurement_manager"):
|
||||||
return ArrivalScope(role="admin", user_id=ctx.user.id, project_id=project_id, display_name=ctx.display_name)
|
return ArrivalScope(role="admin", user_id=ctx.user.id, project_id=project_id, display_name=ctx.display_name)
|
||||||
raise ForbiddenError("این بخش فقط برای مدیر پروژه یا مدیر تدارکات است")
|
raise ForbiddenError("این بخش فقط برای مدیر یا سرپرست پروژه و مدیر تدارکات است")
|
||||||
# Dev fallback: X-User-Role: pm | admin (procurement_manager maps to
|
# Dev fallback: X-User-Role: pm | supervisor | admin (procurement_manager maps to
|
||||||
# admin) — ONLY when DEV_LOGIN_ENABLED (local testing without Casdoor).
|
# admin) — ONLY when DEV_LOGIN_ENABLED (local testing without Casdoor).
|
||||||
# Disabled by default: an ungated header identity in production would
|
# Disabled by default: an ungated header identity in production would
|
||||||
# let anyone confirm receipts as PM.
|
# let anyone confirm receipts as PM.
|
||||||
@@ -110,8 +111,10 @@ async def arrivals_scope(
|
|||||||
role = (request.headers.get("x-user-role") or "").strip().lower()
|
role = (request.headers.get("x-user-role") or "").strip().lower()
|
||||||
if role == "procurement_manager":
|
if role == "procurement_manager":
|
||||||
role = "admin"
|
role = "admin"
|
||||||
|
elif role == "supervisor":
|
||||||
|
role = "pm"
|
||||||
if role not in ("pm", "admin"):
|
if role not in ("pm", "admin"):
|
||||||
raise ForbiddenError("این بخش فقط برای مدیر پروژه یا مدیر تدارکات است — هدر X-User-Role را بفرستید")
|
raise ForbiddenError("این بخش فقط برای مدیر یا سرپرست پروژه و مدیر تدارکات است — هدر X-User-Role را بفرستید")
|
||||||
# The explicit query param wins; otherwise the dev header carries it.
|
# The explicit query param wins; otherwise the dev header carries it.
|
||||||
if project_id is None and role == "pm":
|
if project_id is None and role == "pm":
|
||||||
raw_project = request.headers.get("x-project-id")
|
raw_project = request.headers.get("x-project-id")
|
||||||
@@ -189,10 +192,17 @@ async def pm_on_the_way(
|
|||||||
.outerjoin(Project, Project.id == ItemDecision.project_id)
|
.outerjoin(Project, Project.id == ItemDecision.project_id)
|
||||||
.where(ItemDecision.status == "chosen")
|
.where(ItemDecision.status == "chosen")
|
||||||
)
|
)
|
||||||
if ctx.role == "pm" and ctx.project_id is None:
|
if ctx.role == "pm":
|
||||||
|
allowed = ctx.project_ids or ([ctx.project_id] if ctx.project_id else [])
|
||||||
|
if not allowed:
|
||||||
raise ForbiddenError("شما به هیچ پروژهای متصل نیستید (projects.pm_user_id)")
|
raise ForbiddenError("شما به هیچ پروژهای متصل نیستید (projects.pm_user_id)")
|
||||||
if ctx.project_id is not None:
|
if ctx.project_id is not None:
|
||||||
# PM: active project; admin/manager: optional project filter
|
if ctx.project_id not in allowed:
|
||||||
|
raise ForbiddenError("این پروژه به شما تخصیص داده نشده است")
|
||||||
|
stmt = stmt.where(ItemDecision.project_id == ctx.project_id)
|
||||||
|
else:
|
||||||
|
stmt = stmt.where(ItemDecision.project_id.in_(allowed))
|
||||||
|
elif ctx.project_id is not None:
|
||||||
stmt = stmt.where(ItemDecision.project_id == ctx.project_id)
|
stmt = stmt.where(ItemDecision.project_id == ctx.project_id)
|
||||||
decisions = (await db.execute(stmt.order_by(ItemDecision.decided_at.desc().nulls_last()))).all()
|
decisions = (await db.execute(stmt.order_by(ItemDecision.decided_at.desc().nulls_last()))).all()
|
||||||
|
|
||||||
@@ -243,6 +253,10 @@ async def pm_confirm_receipt(
|
|||||||
decision = await db.get(ItemDecision, payload.item_decision_id)
|
decision = await db.get(ItemDecision, payload.item_decision_id)
|
||||||
if decision is None or decision.status != "chosen":
|
if decision is None or decision.status != "chosen":
|
||||||
raise NotFoundError("تصمیم خرید یافت نشد", field="item_decision_id")
|
raise NotFoundError("تصمیم خرید یافت نشد", field="item_decision_id")
|
||||||
|
if ctx.role == "pm":
|
||||||
|
allowed = ctx.project_ids or ([ctx.project_id] if ctx.project_id else [])
|
||||||
|
if decision.project_id not in allowed:
|
||||||
|
raise ForbiddenError("این قلم متعلق به پروژه شما نیست")
|
||||||
if ctx.project_id is not None and decision.project_id != ctx.project_id:
|
if ctx.project_id is not None and decision.project_id != ctx.project_id:
|
||||||
raise ForbiddenError("این قلم متعلق به پروژه فعال نیست")
|
raise ForbiddenError("این قلم متعلق به پروژه فعال نیست")
|
||||||
|
|
||||||
@@ -451,10 +465,17 @@ async def pm_receipts(
|
|||||||
.join(Quote, Quote.id == LineItem.quote_id)
|
.join(Quote, Quote.id == LineItem.quote_id)
|
||||||
.join(Project, Project.id == ItemDecision.project_id)
|
.join(Project, Project.id == ItemDecision.project_id)
|
||||||
)
|
)
|
||||||
if ctx.role == "pm" and ctx.project_id is None:
|
if ctx.role == "pm":
|
||||||
|
allowed = ctx.project_ids or ([ctx.project_id] if ctx.project_id else [])
|
||||||
|
if not allowed:
|
||||||
raise ForbiddenError("شما به هیچ پروژهای متصل نیستید (projects.pm_user_id)")
|
raise ForbiddenError("شما به هیچ پروژهای متصل نیستید (projects.pm_user_id)")
|
||||||
if ctx.project_id is not None:
|
if ctx.project_id is not None:
|
||||||
# PM: active project; admin/manager: optional project filter
|
if ctx.project_id not in allowed:
|
||||||
|
raise ForbiddenError("این پروژه به شما تخصیص داده نشده است")
|
||||||
|
stmt = stmt.where(ItemDecision.project_id == ctx.project_id)
|
||||||
|
else:
|
||||||
|
stmt = stmt.where(ItemDecision.project_id.in_(allowed))
|
||||||
|
elif ctx.project_id is not None:
|
||||||
stmt = stmt.where(ItemDecision.project_id == ctx.project_id)
|
stmt = stmt.where(ItemDecision.project_id == ctx.project_id)
|
||||||
rows = (await db.execute(stmt.order_by(ItemReceipt.received_at.desc()))).all()
|
rows = (await db.execute(stmt.order_by(ItemReceipt.received_at.desc()))).all()
|
||||||
receipts = [r.ItemReceipt for r in rows]
|
receipts = [r.ItemReceipt for r in rows]
|
||||||
|
|||||||
@@ -0,0 +1,206 @@
|
|||||||
|
import uuid
|
||||||
|
from typing import Literal
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Depends, Query, Request
|
||||||
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
|
from app.db.engine import get_db
|
||||||
|
from app.routers.pm import ArrivalScope, arrivals_scope
|
||||||
|
from app.schemas.project_transfers import (
|
||||||
|
ProjectTransferCreate,
|
||||||
|
ProjectTransferOut,
|
||||||
|
ProjectTransferReceive,
|
||||||
|
ProjectTransferUpdate,
|
||||||
|
)
|
||||||
|
from app.services import project_transfer_service
|
||||||
|
from app.utils.errors import ForbiddenError
|
||||||
|
|
||||||
|
router = APIRouter(tags=["project-transfers"])
|
||||||
|
|
||||||
|
|
||||||
|
def _to_transfer_out(t) -> dict:
|
||||||
|
return {
|
||||||
|
"id": t.id,
|
||||||
|
"from_project": (
|
||||||
|
{"id": t.from_project.id, "name": t.from_project.name}
|
||||||
|
if t.from_project
|
||||||
|
else {"id": t.from_project_id, "name": ""}
|
||||||
|
),
|
||||||
|
"from_warehouse": (
|
||||||
|
{"id": t.from_warehouse.id, "name": t.from_warehouse.name}
|
||||||
|
if t.from_warehouse
|
||||||
|
else {"id": t.from_warehouse_id, "name": ""}
|
||||||
|
),
|
||||||
|
"to_project": (
|
||||||
|
{"id": t.to_project.id, "name": t.to_project.name}
|
||||||
|
if t.to_project
|
||||||
|
else {"id": t.to_project_id, "name": ""}
|
||||||
|
),
|
||||||
|
"to_warehouse": (
|
||||||
|
{"id": t.to_warehouse.id, "name": t.to_warehouse.name}
|
||||||
|
if t.to_warehouse
|
||||||
|
else None
|
||||||
|
),
|
||||||
|
"material": (
|
||||||
|
{"id": t.material.id, "name": t.material.name}
|
||||||
|
if t.material
|
||||||
|
else {"id": t.material_id, "name": ""}
|
||||||
|
),
|
||||||
|
"brand": (
|
||||||
|
{"id": t.brand.id, "name": t.brand.name}
|
||||||
|
if t.brand
|
||||||
|
else None
|
||||||
|
),
|
||||||
|
"unit": (
|
||||||
|
{"id": t.unit.id, "code": t.unit.code, "name_fa": t.unit.name_fa}
|
||||||
|
if t.unit
|
||||||
|
else {"id": t.unit_id, "code": "", "name_fa": None}
|
||||||
|
),
|
||||||
|
"quantity": t.quantity,
|
||||||
|
"specs": t.specs or {},
|
||||||
|
"specs_hash": t.specs_hash,
|
||||||
|
"note": t.note,
|
||||||
|
"status": t.status,
|
||||||
|
"transfer_date": t.transfer_date,
|
||||||
|
"transferred_by": t.transferred_by,
|
||||||
|
"received_at": t.received_at,
|
||||||
|
"received_by": t.received_by,
|
||||||
|
"receipt_allocations": t.receipt_allocations,
|
||||||
|
"created_at": t.created_at,
|
||||||
|
"updated_at": t.updated_at,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# POST /inventory/project-transfers — Create inter-project transfer
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
@router.post("/inventory/project-transfers", status_code=201)
|
||||||
|
async def create_transfer(
|
||||||
|
payload: ProjectTransferCreate,
|
||||||
|
ctx: ArrivalScope = Depends(arrivals_scope),
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
):
|
||||||
|
transfer = await project_transfer_service.create_project_transfer(
|
||||||
|
db=db,
|
||||||
|
payload=payload,
|
||||||
|
caller_project_id=ctx.project_id,
|
||||||
|
caller_role=ctx.role,
|
||||||
|
transferred_by=ctx.display_name,
|
||||||
|
)
|
||||||
|
return {"data": _to_transfer_out(transfer)}
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# GET /inventory/project-transfers — List transfers with direction and filters
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
@router.get("/inventory/project-transfers")
|
||||||
|
async def list_transfers(
|
||||||
|
project_id: uuid.UUID | None = Query(default=None),
|
||||||
|
direction: Literal["outgoing", "incoming", "all"] = Query(default="all"),
|
||||||
|
status: str | None = Query(default=None),
|
||||||
|
ctx: ArrivalScope = Depends(arrivals_scope),
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
):
|
||||||
|
target_pid = project_id or ctx.project_id
|
||||||
|
transfers = await project_transfer_service.list_project_transfers(
|
||||||
|
db=db,
|
||||||
|
project_id=target_pid,
|
||||||
|
direction=direction,
|
||||||
|
status=status,
|
||||||
|
)
|
||||||
|
return {"data": [_to_transfer_out(t) for t in transfers]}
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# GET /inventory/project-transfers/{id} — Single transfer details
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
@router.get("/inventory/project-transfers/{transfer_id}")
|
||||||
|
async def get_transfer(
|
||||||
|
transfer_id: uuid.UUID,
|
||||||
|
ctx: ArrivalScope = Depends(arrivals_scope),
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
):
|
||||||
|
transfer = await project_transfer_service.get_project_transfer_or_404(db, transfer_id)
|
||||||
|
if ctx.role == "pm" and ctx.project_id is not None:
|
||||||
|
if transfer.from_project_id != ctx.project_id and transfer.to_project_id != ctx.project_id:
|
||||||
|
raise ForbiddenError("شما به این رکورد انتقال دسترسی ندارید")
|
||||||
|
return {"data": _to_transfer_out(transfer)}
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# PATCH /inventory/project-transfers/{id} — Edit in-transit transfer (source PM only)
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
@router.patch("/inventory/project-transfers/{transfer_id}")
|
||||||
|
async def update_transfer(
|
||||||
|
transfer_id: uuid.UUID,
|
||||||
|
payload: ProjectTransferUpdate,
|
||||||
|
ctx: ArrivalScope = Depends(arrivals_scope),
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
):
|
||||||
|
transfer = await project_transfer_service.update_project_transfer(
|
||||||
|
db=db,
|
||||||
|
transfer_id=transfer_id,
|
||||||
|
payload=payload,
|
||||||
|
caller_project_id=ctx.project_id,
|
||||||
|
caller_role=ctx.role,
|
||||||
|
)
|
||||||
|
return {"data": _to_transfer_out(transfer)}
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# DELETE /inventory/project-transfers/{id} — Cancel in-transit transfer (source PM only)
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
@router.delete("/inventory/project-transfers/{transfer_id}")
|
||||||
|
async def delete_transfer(
|
||||||
|
transfer_id: uuid.UUID,
|
||||||
|
ctx: ArrivalScope = Depends(arrivals_scope),
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
):
|
||||||
|
res = await project_transfer_service.delete_project_transfer(
|
||||||
|
db=db,
|
||||||
|
transfer_id=transfer_id,
|
||||||
|
caller_project_id=ctx.project_id,
|
||||||
|
caller_role=ctx.role,
|
||||||
|
)
|
||||||
|
return {"data": res}
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# GET /pm/transfers/on-the-way — Incoming in-transit transfers for active project
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
@router.get("/pm/transfers/on-the-way")
|
||||||
|
async def pm_incoming_transfers(
|
||||||
|
ctx: ArrivalScope = Depends(arrivals_scope),
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
):
|
||||||
|
if ctx.role == "pm" and ctx.project_id is None:
|
||||||
|
raise ForbiddenError("شما به هیچ پروژهای متصل نیستید")
|
||||||
|
|
||||||
|
transfers = await project_transfer_service.list_project_transfers(
|
||||||
|
db=db,
|
||||||
|
project_id=ctx.project_id,
|
||||||
|
direction="incoming",
|
||||||
|
status="in_transit",
|
||||||
|
)
|
||||||
|
return {"data": [_to_transfer_out(t) for t in transfers]}
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# POST /inventory/project-transfers/{id}/receive — Destination PM confirms arrival
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
@router.post("/inventory/project-transfers/{transfer_id}/receive")
|
||||||
|
async def receive_transfer(
|
||||||
|
transfer_id: uuid.UUID,
|
||||||
|
payload: ProjectTransferReceive,
|
||||||
|
ctx: ArrivalScope = Depends(arrivals_scope),
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
):
|
||||||
|
transfer = await project_transfer_service.receive_project_transfer(
|
||||||
|
db=db,
|
||||||
|
transfer_id=transfer_id,
|
||||||
|
payload=payload,
|
||||||
|
caller_project_id=ctx.project_id,
|
||||||
|
caller_role=ctx.role,
|
||||||
|
received_by=ctx.display_name,
|
||||||
|
)
|
||||||
|
return {"data": _to_transfer_out(transfer)}
|
||||||
@@ -3,7 +3,7 @@ from fastapi import APIRouter, Depends, Query, Request
|
|||||||
from sqlalchemy import func, or_, select
|
from sqlalchemy import func, or_, select
|
||||||
from sqlalchemy.ext.asyncio import AsyncSession
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
from app.auth import UserContext, get_optional_user
|
from app.auth import UserContext, get_optional_user, require_procurement_writer, require_role
|
||||||
from app.db.engine import get_db
|
from app.db.engine import get_db
|
||||||
from app.models.procurement import Project, Quote, User
|
from app.models.procurement import Project, Quote, User
|
||||||
from app.schemas.procurement import ProjectCreate, ProjectUpdate
|
from app.schemas.procurement import ProjectCreate, ProjectUpdate
|
||||||
@@ -13,6 +13,7 @@ from app.utils.pagination import paginate, sort_query
|
|||||||
from app.utils.serialization import to_date, to_iso
|
from app.utils.serialization import to_date, to_iso
|
||||||
|
|
||||||
router = APIRouter(prefix="/projects", tags=["projects"])
|
router = APIRouter(prefix="/projects", tags=["projects"])
|
||||||
|
_procurement_writer = require_procurement_writer()
|
||||||
|
|
||||||
|
|
||||||
async def _optional_ctx(request: Request, db: AsyncSession = Depends(get_db)) -> UserContext | None:
|
async def _optional_ctx(request: Request, db: AsyncSession = Depends(get_db)) -> UserContext | None:
|
||||||
@@ -33,8 +34,12 @@ async def project_to_dict(db: AsyncSession, project: Project) -> dict:
|
|||||||
d = {
|
d = {
|
||||||
"id": str(project.id),
|
"id": str(project.id),
|
||||||
"name": project.name,
|
"name": project.name,
|
||||||
"description": project.description,
|
"location": project.location or "",
|
||||||
|
"project_manager": project.project_manager or "",
|
||||||
|
"description": project.description or "",
|
||||||
"start_date": to_date(project.start_date),
|
"start_date": to_date(project.start_date),
|
||||||
|
"status": project.status or "ACTIVE",
|
||||||
|
"progress": float(project.progress) if project.progress is not None else 0.0,
|
||||||
"pm_user_id": str(project.pm_user_id) if project.pm_user_id else None,
|
"pm_user_id": str(project.pm_user_id) if project.pm_user_id else None,
|
||||||
"created_at": to_iso(project.created_at),
|
"created_at": to_iso(project.created_at),
|
||||||
}
|
}
|
||||||
@@ -42,6 +47,8 @@ async def project_to_dict(db: AsyncSession, project: Project) -> dict:
|
|||||||
pm = await db.get(User, project.pm_user_id)
|
pm = await db.get(User, project.pm_user_id)
|
||||||
if pm:
|
if pm:
|
||||||
d["pm_name"] = f"{pm.first_name} {pm.last_name}".strip() or pm.casdoor_id
|
d["pm_name"] = f"{pm.first_name} {pm.last_name}".strip() or pm.casdoor_id
|
||||||
|
elif project.project_manager:
|
||||||
|
d["pm_name"] = project.project_manager
|
||||||
return d
|
return d
|
||||||
|
|
||||||
|
|
||||||
@@ -55,7 +62,14 @@ async def list_projects(
|
|||||||
):
|
):
|
||||||
stmt = select(Project)
|
stmt = select(Project)
|
||||||
if q:
|
if q:
|
||||||
stmt = stmt.where(or_(Project.name.ilike(f"%{q}%"), Project.description.ilike(f"%{q}%")))
|
stmt = stmt.where(
|
||||||
|
or_(
|
||||||
|
Project.name.ilike(f"%{q}%"),
|
||||||
|
Project.description.ilike(f"%{q}%"),
|
||||||
|
Project.location.ilike(f"%{q}%"),
|
||||||
|
Project.project_manager.ilike(f"%{q}%"),
|
||||||
|
)
|
||||||
|
)
|
||||||
stmt = sort_query(stmt, Project, sort)
|
stmt = sort_query(stmt, Project, sort)
|
||||||
items, meta = await paginate(stmt, page, page_size, db)
|
items, meta = await paginate(stmt, page, page_size, db)
|
||||||
pm_map = await _pm_map(db, items)
|
pm_map = await _pm_map(db, items)
|
||||||
@@ -64,24 +78,38 @@ async def list_projects(
|
|||||||
d = {
|
d = {
|
||||||
"id": str(p.id),
|
"id": str(p.id),
|
||||||
"name": p.name,
|
"name": p.name,
|
||||||
"description": p.description,
|
"location": p.location or "",
|
||||||
|
"project_manager": p.project_manager or "",
|
||||||
|
"description": p.description or "",
|
||||||
"start_date": to_date(p.start_date),
|
"start_date": to_date(p.start_date),
|
||||||
|
"status": p.status or "ACTIVE",
|
||||||
|
"progress": float(p.progress) if p.progress is not None else 0.0,
|
||||||
"pm_user_id": str(p.pm_user_id) if p.pm_user_id else None,
|
"pm_user_id": str(p.pm_user_id) if p.pm_user_id else None,
|
||||||
"created_at": to_iso(p.created_at),
|
"created_at": to_iso(p.created_at),
|
||||||
}
|
}
|
||||||
pm = pm_map.get(p.pm_user_id)
|
pm = pm_map.get(p.pm_user_id)
|
||||||
if pm:
|
if pm:
|
||||||
d["pm_name"] = f"{pm.first_name} {pm.last_name}".strip() or pm.casdoor_id
|
d["pm_name"] = f"{pm.first_name} {pm.last_name}".strip() or pm.casdoor_id
|
||||||
|
elif p.project_manager:
|
||||||
|
d["pm_name"] = p.project_manager
|
||||||
data.append(d)
|
data.append(d)
|
||||||
return {"data": data, "meta": meta}
|
return {"data": data, "meta": meta}
|
||||||
|
|
||||||
|
|
||||||
@router.post("", status_code=201)
|
@router.post("", status_code=201)
|
||||||
async def create_project(payload: ProjectCreate, db: AsyncSession = Depends(get_db)):
|
async def create_project(
|
||||||
|
payload: ProjectCreate,
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
_auth=Depends(_procurement_writer),
|
||||||
|
):
|
||||||
project = Project(
|
project = Project(
|
||||||
name=payload.name,
|
name=payload.name.strip(),
|
||||||
description=payload.description,
|
location=payload.location.strip() if payload.location else "",
|
||||||
|
project_manager=payload.project_manager.strip() if payload.project_manager else "",
|
||||||
|
description=payload.description.strip() if payload.description else "",
|
||||||
start_date=payload.start_date,
|
start_date=payload.start_date,
|
||||||
|
planned_start=payload.start_date,
|
||||||
|
status="ACTIVE",
|
||||||
)
|
)
|
||||||
db.add(project)
|
db.add(project)
|
||||||
await db.flush()
|
await db.flush()
|
||||||
@@ -103,37 +131,51 @@ async def update_project(
|
|||||||
request: Request,
|
request: Request,
|
||||||
ctx: UserContext | None = Depends(_optional_ctx),
|
ctx: UserContext | None = Depends(_optional_ctx),
|
||||||
db: AsyncSession = Depends(get_db),
|
db: AsyncSession = Depends(get_db),
|
||||||
|
_auth=Depends(_procurement_writer),
|
||||||
):
|
):
|
||||||
project = await db.get(Project, project_id)
|
project = await db.get(Project, project_id)
|
||||||
if project is None:
|
if project is None:
|
||||||
raise NotFoundError("پروژه یافت نشد")
|
raise NotFoundError("پروژه یافت نشد")
|
||||||
if payload.name is not None:
|
if payload.name is not None:
|
||||||
project.name = payload.name
|
project.name = payload.name.strip()
|
||||||
|
if payload.location is not None:
|
||||||
|
project.location = payload.location.strip()
|
||||||
|
if payload.project_manager is not None:
|
||||||
|
project.project_manager = payload.project_manager.strip()
|
||||||
if payload.description is not None:
|
if payload.description is not None:
|
||||||
project.description = payload.description
|
project.description = payload.description.strip()
|
||||||
if payload.start_date is not None:
|
if payload.start_date is not None:
|
||||||
project.start_date = payload.start_date
|
project.start_date = payload.start_date
|
||||||
|
project.planned_start = payload.start_date
|
||||||
|
if payload.status is not None:
|
||||||
|
project.status = payload.status
|
||||||
# PM assignment (1:N): one PM per project, a PM may own many projects.
|
# PM assignment (1:N): one PM per project, a PM may own many projects.
|
||||||
# Admin / procurement manager only (same rule as the Organization panel).
|
# Admin / procurement manager only (same rule as the Organization panel).
|
||||||
if "pm_user_id" in payload.model_fields_set:
|
if "pm_user_id" in payload.model_fields_set:
|
||||||
role = ctx.role if ctx else (request.headers.get("x-user-role") or "").strip().lower()
|
role = ctx.role if ctx else (request.headers.get("x-user-role") or "").strip().lower()
|
||||||
if role not in ("admin", "procurement_manager"):
|
if role not in ("admin", "procurement_manager", "pm"):
|
||||||
raise ForbiddenError("تعیین مدیر پروژه فقط برای ادمین / مدیر تدارکات مجاز است")
|
raise ForbiddenError("تعیین سرپرست پروژه فقط برای مدیر تدارکات، مدیر پروژه و ادمین مجاز است")
|
||||||
if payload.pm_user_id is None:
|
if payload.pm_user_id is None:
|
||||||
project.pm_user_id = None
|
project.pm_user_id = None
|
||||||
else:
|
else:
|
||||||
pm_user = await db.get(User, payload.pm_user_id)
|
pm_user = await db.get(User, payload.pm_user_id)
|
||||||
if pm_user is None:
|
if pm_user is None:
|
||||||
raise NotFoundError("کاربر یافت نشد", field="pm_user_id")
|
raise NotFoundError("کاربر یافت نشد", field="pm_user_id")
|
||||||
if pm_user.role != "pm":
|
if pm_user.role not in ("supervisor", "pm"):
|
||||||
raise ValidationError("ابتدا نقش این کاربر را «مدیر پروژه» کنید", field="pm_user_id")
|
raise ValidationError("ابتدا نقش این کاربر را «سرپرست پروژه» کنید", field="pm_user_id")
|
||||||
project.pm_user_id = pm_user.id
|
project.pm_user_id = pm_user.id
|
||||||
|
if not project.project_manager:
|
||||||
|
project.project_manager = f"{pm_user.first_name} {pm_user.last_name}".strip()
|
||||||
await db.flush()
|
await db.flush()
|
||||||
return {"data": await project_to_dict(db, project)}
|
return {"data": await project_to_dict(db, project)}
|
||||||
|
|
||||||
|
|
||||||
@router.delete("/{project_id}")
|
@router.delete("/{project_id}")
|
||||||
async def delete_project(project_id, db: AsyncSession = Depends(get_db)):
|
async def delete_project(
|
||||||
|
project_id,
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
_auth=Depends(_procurement_writer),
|
||||||
|
):
|
||||||
project = await db.get(Project, project_id)
|
project = await db.get(Project, project_id)
|
||||||
if project is None:
|
if project is None:
|
||||||
raise NotFoundError("پروژه یافت نشد")
|
raise NotFoundError("پروژه یافت نشد")
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ from fastapi import APIRouter, Depends, Query
|
|||||||
from sqlalchemy import select
|
from sqlalchemy import select
|
||||||
from sqlalchemy.ext.asyncio import AsyncSession
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
|
from app.auth import require_procurement_writer, require_role
|
||||||
from app.db.engine import get_db
|
from app.db.engine import get_db
|
||||||
from app.models.procurement import Quote, QuoteEvent
|
from app.models.procurement import Quote, QuoteEvent
|
||||||
from app.schemas.procurement import NoteEventIn
|
from app.schemas.procurement import NoteEventIn
|
||||||
@@ -11,6 +12,7 @@ from app.utils.errors import NotFoundError, ValidationError
|
|||||||
from app.utils.pagination import paginate, sort_query
|
from app.utils.pagination import paginate, sort_query
|
||||||
|
|
||||||
router = APIRouter(prefix="/quotes/{quote_id}/events", tags=["quote-events"])
|
router = APIRouter(prefix="/quotes/{quote_id}/events", tags=["quote-events"])
|
||||||
|
_procurement_writer = require_procurement_writer()
|
||||||
|
|
||||||
|
|
||||||
@router.get("")
|
@router.get("")
|
||||||
@@ -34,7 +36,12 @@ async def list_events(
|
|||||||
|
|
||||||
|
|
||||||
@router.post("", status_code=201)
|
@router.post("", status_code=201)
|
||||||
async def create_event(quote_id, payload: NoteEventIn, db: AsyncSession = Depends(get_db)):
|
async def create_event(
|
||||||
|
quote_id,
|
||||||
|
payload: NoteEventIn,
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
_auth=Depends(_procurement_writer),
|
||||||
|
):
|
||||||
quote = await db.get(Quote, quote_id)
|
quote = await db.get(Quote, quote_id)
|
||||||
if quote is None:
|
if quote is None:
|
||||||
raise NotFoundError("پیشنهاد (استعلام) یافت نشد")
|
raise NotFoundError("پیشنهاد (استعلام) یافت نشد")
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ from fastapi import APIRouter, Depends, Query
|
|||||||
from sqlalchemy import exists, func, or_, select
|
from sqlalchemy import exists, func, or_, select
|
||||||
from sqlalchemy.ext.asyncio import AsyncSession
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
|
from app.auth import UserContext, allow_quote_create, require_procurement_writer, require_role
|
||||||
from app.db.engine import get_db
|
from app.db.engine import get_db
|
||||||
from app.models.catalog import Material
|
from app.models.catalog import Material
|
||||||
from app.models.procurement import (
|
from app.models.procurement import (
|
||||||
@@ -36,12 +37,15 @@ from app.services.expand_service import (
|
|||||||
serialize_quote_with_children,
|
serialize_quote_with_children,
|
||||||
serialize_quotes,
|
serialize_quotes,
|
||||||
)
|
)
|
||||||
from app.utils.errors import NotFoundError
|
from app.utils.errors import ForbiddenError, NotFoundError, ValidationError
|
||||||
from app.utils.pagination import sort_query
|
from app.utils.pagination import sort_query
|
||||||
from app.utils.security import get_actor
|
from app.utils.security import get_actor
|
||||||
|
|
||||||
router = APIRouter(prefix="/quotes", tags=["quotes"])
|
router = APIRouter(prefix="/quotes", tags=["quotes"])
|
||||||
|
|
||||||
|
# عملیات نوشتنی تدارکات — فقط ادمین و مدیر تدارکات (مدیر پروژه فقط خواندن دارد)
|
||||||
|
_procurement_writer = require_procurement_writer()
|
||||||
|
|
||||||
|
|
||||||
# --- list filter helpers ---------------------------------------------------
|
# --- list filter helpers ---------------------------------------------------
|
||||||
|
|
||||||
@@ -156,7 +160,24 @@ async def get_quote(quote_id, expand: str | None = None, db: AsyncSession = Depe
|
|||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
@router.post("", status_code=201)
|
@router.post("", status_code=201)
|
||||||
async def create_quote(payload: QuoteCreate, db: AsyncSession = Depends(get_db), actor: str = Depends(get_actor)):
|
async def create_quote(
|
||||||
|
payload: QuoteCreate,
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
actor: str = Depends(get_actor),
|
||||||
|
ctx: UserContext = Depends(allow_quote_create()),
|
||||||
|
_auth=None,
|
||||||
|
):
|
||||||
|
# سطح limited: استعلام فقط برای پروژههای عضویت خودش
|
||||||
|
if (ctx.panels or {}).get("procurement") == "limited" and ctx.role != "admin":
|
||||||
|
allowed = set(ctx.project_ids or []) | set(ctx.member_project_ids or [])
|
||||||
|
if ctx.project_id:
|
||||||
|
allowed.add(ctx.project_id)
|
||||||
|
allowed_str = {str(pid) for pid in allowed if pid}
|
||||||
|
wanted = {str(pid) for pid in ([payload.project_id] + list(payload.project_ids or [])) if pid}
|
||||||
|
if not wanted:
|
||||||
|
raise ValidationError("برای افزودن استعلام، پروژه الزامی است")
|
||||||
|
if not wanted <= allowed_str:
|
||||||
|
raise ForbiddenError("استعلام فقط برای پروژههای تخصیصیافته به شما مجاز است")
|
||||||
quote = await quote_service.create_quote(db, payload, actor)
|
quote = await quote_service.create_quote(db, payload, actor)
|
||||||
return {"data": await serialize_quote_with_children(db, quote)}
|
return {"data": await serialize_quote_with_children(db, quote)}
|
||||||
|
|
||||||
@@ -167,7 +188,11 @@ async def create_quote(payload: QuoteCreate, db: AsyncSession = Depends(get_db),
|
|||||||
|
|
||||||
@router.patch("/{quote_id}")
|
@router.patch("/{quote_id}")
|
||||||
async def update_quote(
|
async def update_quote(
|
||||||
quote_id, payload: QuoteUpdate, db: AsyncSession = Depends(get_db), actor: str = Depends(get_actor)
|
quote_id,
|
||||||
|
payload: QuoteUpdate,
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
actor: str = Depends(get_actor),
|
||||||
|
_auth=Depends(_procurement_writer),
|
||||||
):
|
):
|
||||||
quote = await quote_service.update_quote(db, quote_id, payload, actor)
|
quote = await quote_service.update_quote(db, quote_id, payload, actor)
|
||||||
return {"data": await serialize_quote(db, quote, set())}
|
return {"data": await serialize_quote(db, quote, set())}
|
||||||
@@ -175,7 +200,11 @@ async def update_quote(
|
|||||||
|
|
||||||
@router.patch("/{quote_id}/children")
|
@router.patch("/{quote_id}/children")
|
||||||
async def replace_quote_children(
|
async def replace_quote_children(
|
||||||
quote_id, payload: QuoteChildrenReplaceIn, db: AsyncSession = Depends(get_db), actor: str = Depends(get_actor)
|
quote_id,
|
||||||
|
payload: QuoteChildrenReplaceIn,
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
actor: str = Depends(get_actor),
|
||||||
|
_auth=Depends(_procurement_writer),
|
||||||
):
|
):
|
||||||
"""Full replacement of a quote's line items + termsheets (edit modal)."""
|
"""Full replacement of a quote's line items + termsheets (edit modal)."""
|
||||||
quote = await quote_service.replace_quote_children(db, quote_id, payload, actor)
|
quote = await quote_service.replace_quote_children(db, quote_id, payload, actor)
|
||||||
@@ -188,7 +217,11 @@ async def replace_quote_children(
|
|||||||
|
|
||||||
@router.patch("/{quote_id}/accept")
|
@router.patch("/{quote_id}/accept")
|
||||||
async def accept_quote(
|
async def accept_quote(
|
||||||
quote_id, payload: AcceptQuoteIn, db: AsyncSession = Depends(get_db), actor: str = Depends(get_actor)
|
quote_id,
|
||||||
|
payload: AcceptQuoteIn,
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
actor: str = Depends(get_actor),
|
||||||
|
_auth=Depends(_procurement_writer),
|
||||||
):
|
):
|
||||||
quote = await quote_service.accept_quote(db, quote_id, payload, actor)
|
quote = await quote_service.accept_quote(db, quote_id, payload, actor)
|
||||||
return {"data": await _accept_response(db, quote)}
|
return {"data": await _accept_response(db, quote)}
|
||||||
@@ -224,7 +257,12 @@ async def _accept_response(db: AsyncSession, quote: Quote) -> dict:
|
|||||||
|
|
||||||
|
|
||||||
@router.patch("/{quote_id}/arrive")
|
@router.patch("/{quote_id}/arrive")
|
||||||
async def arrive_quote(quote_id, db: AsyncSession = Depends(get_db), actor: str = Depends(get_actor)):
|
async def arrive_quote(
|
||||||
|
quote_id,
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
actor: str = Depends(get_actor),
|
||||||
|
_auth=Depends(_procurement_writer),
|
||||||
|
):
|
||||||
quote = await quote_service.arrive_quote(db, quote_id, actor)
|
quote = await quote_service.arrive_quote(db, quote_id, actor)
|
||||||
return {
|
return {
|
||||||
"data": {
|
"data": {
|
||||||
@@ -237,7 +275,11 @@ async def arrive_quote(quote_id, db: AsyncSession = Depends(get_db), actor: str
|
|||||||
|
|
||||||
@router.patch("/{quote_id}/arrive-items")
|
@router.patch("/{quote_id}/arrive-items")
|
||||||
async def arrive_items(
|
async def arrive_items(
|
||||||
quote_id, payload: ArriveItemsIn, db: AsyncSession = Depends(get_db), actor: str = Depends(get_actor)
|
quote_id,
|
||||||
|
payload: ArriveItemsIn,
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
actor: str = Depends(get_actor),
|
||||||
|
_auth=Depends(_procurement_writer),
|
||||||
):
|
):
|
||||||
quote = await quote_service.arrive_items(db, quote_id, payload, actor)
|
quote = await quote_service.arrive_items(db, quote_id, payload, actor)
|
||||||
return {
|
return {
|
||||||
@@ -259,14 +301,23 @@ async def arrive_items(
|
|||||||
|
|
||||||
@router.patch("/{quote_id}/reject")
|
@router.patch("/{quote_id}/reject")
|
||||||
async def reject_quote(
|
async def reject_quote(
|
||||||
quote_id, payload: RejectQuoteIn | None = None, db: AsyncSession = Depends(get_db), actor: str = Depends(get_actor)
|
quote_id,
|
||||||
|
payload: RejectQuoteIn | None = None,
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
actor: str = Depends(get_actor),
|
||||||
|
_auth=Depends(_procurement_writer),
|
||||||
):
|
):
|
||||||
quote = await quote_service.reject_quote(db, quote_id, payload or RejectQuoteIn(), actor)
|
quote = await quote_service.reject_quote(db, quote_id, payload or RejectQuoteIn(), actor)
|
||||||
return {"data": {"id": str(quote.id), "status": quote.status}}
|
return {"data": {"id": str(quote.id), "status": quote.status}}
|
||||||
|
|
||||||
|
|
||||||
@router.patch("/{quote_id}/expire")
|
@router.patch("/{quote_id}/expire")
|
||||||
async def expire_quote(quote_id, db: AsyncSession = Depends(get_db), actor: str = Depends(get_actor)):
|
async def expire_quote(
|
||||||
|
quote_id,
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
actor: str = Depends(get_actor),
|
||||||
|
_auth=Depends(_procurement_writer),
|
||||||
|
):
|
||||||
quote = await quote_service.expire_quote(db, quote_id, actor)
|
quote = await quote_service.expire_quote(db, quote_id, actor)
|
||||||
return {"data": {"id": str(quote.id), "status": quote.status}}
|
return {"data": {"id": str(quote.id), "status": quote.status}}
|
||||||
|
|
||||||
@@ -276,6 +327,10 @@ async def expire_quote(quote_id, db: AsyncSession = Depends(get_db), actor: str
|
|||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
@router.delete("/{quote_id}")
|
@router.delete("/{quote_id}")
|
||||||
async def delete_quote(quote_id, db: AsyncSession = Depends(get_db)):
|
async def delete_quote(
|
||||||
|
quote_id,
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
_auth=Depends(_procurement_writer),
|
||||||
|
):
|
||||||
result = await quote_service.delete_quote(db, quote_id)
|
result = await quote_service.delete_quote(db, quote_id)
|
||||||
return {"data": result}
|
return {"data": result}
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ from fastapi import APIRouter, Depends, Query
|
|||||||
from sqlalchemy import func, select
|
from sqlalchemy import func, select
|
||||||
from sqlalchemy.ext.asyncio import AsyncSession
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
|
from app.auth import require_procurement_writer, require_role
|
||||||
from app.db.engine import get_db
|
from app.db.engine import get_db
|
||||||
from app.models.procurement import Termsheet, TermsheetScheduleStep
|
from app.models.procurement import Termsheet, TermsheetScheduleStep
|
||||||
from app.schemas.procurement import ScheduleStepCreate, ScheduleStepUpdate
|
from app.schemas.procurement import ScheduleStepCreate, ScheduleStepUpdate
|
||||||
@@ -15,6 +16,7 @@ router = APIRouter(
|
|||||||
prefix="/quotes/{quote_id}/termsheets/{termsheet_id}/schedule-steps",
|
prefix="/quotes/{quote_id}/termsheets/{termsheet_id}/schedule-steps",
|
||||||
tags=["schedule-steps"],
|
tags=["schedule-steps"],
|
||||||
)
|
)
|
||||||
|
_procurement_writer = require_procurement_writer()
|
||||||
|
|
||||||
|
|
||||||
async def _termsheet_or_404(db: AsyncSession, quote_id, termsheet_id) -> Termsheet:
|
async def _termsheet_or_404(db: AsyncSession, quote_id, termsheet_id) -> Termsheet:
|
||||||
@@ -57,7 +59,11 @@ async def list_schedule_steps(
|
|||||||
|
|
||||||
@router.post("", status_code=201)
|
@router.post("", status_code=201)
|
||||||
async def create_schedule_step(
|
async def create_schedule_step(
|
||||||
quote_id, termsheet_id, payload: ScheduleStepCreate, db: AsyncSession = Depends(get_db)
|
quote_id,
|
||||||
|
termsheet_id,
|
||||||
|
payload: ScheduleStepCreate,
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
_auth=Depends(_procurement_writer),
|
||||||
):
|
):
|
||||||
ts = await _termsheet_or_404(db, quote_id, termsheet_id)
|
ts = await _termsheet_or_404(db, quote_id, termsheet_id)
|
||||||
step_no = payload.step_no
|
step_no = payload.step_no
|
||||||
@@ -84,7 +90,12 @@ async def create_schedule_step(
|
|||||||
|
|
||||||
@router.patch("/{step_id}")
|
@router.patch("/{step_id}")
|
||||||
async def update_schedule_step(
|
async def update_schedule_step(
|
||||||
quote_id, termsheet_id, step_id, payload: ScheduleStepUpdate, db: AsyncSession = Depends(get_db)
|
quote_id,
|
||||||
|
termsheet_id,
|
||||||
|
step_id,
|
||||||
|
payload: ScheduleStepUpdate,
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
_auth=Depends(_procurement_writer),
|
||||||
):
|
):
|
||||||
step = await _step_or_404(db, termsheet_id, step_id)
|
step = await _step_or_404(db, termsheet_id, step_id)
|
||||||
if payload.step_no is not None and payload.step_no != step.step_no:
|
if payload.step_no is not None and payload.step_no != step.step_no:
|
||||||
@@ -109,7 +120,13 @@ async def update_schedule_step(
|
|||||||
|
|
||||||
|
|
||||||
@router.delete("/{step_id}")
|
@router.delete("/{step_id}")
|
||||||
async def delete_schedule_step(quote_id, termsheet_id, step_id, db: AsyncSession = Depends(get_db)):
|
async def delete_schedule_step(
|
||||||
|
quote_id,
|
||||||
|
termsheet_id,
|
||||||
|
step_id,
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
_auth=Depends(_procurement_writer),
|
||||||
|
):
|
||||||
step = await _step_or_404(db, termsheet_id, step_id)
|
step = await _step_or_404(db, termsheet_id, step_id)
|
||||||
count = await db.scalar(
|
count = await db.scalar(
|
||||||
select(func.count()).select_from(TermsheetScheduleStep).where(
|
select(func.count()).select_from(TermsheetScheduleStep).where(
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ from fastapi import APIRouter, Depends, Query
|
|||||||
from sqlalchemy import select
|
from sqlalchemy import select
|
||||||
from sqlalchemy.ext.asyncio import AsyncSession
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
|
from app.auth import require_procurement_writer, require_role
|
||||||
from app.db.engine import get_db
|
from app.db.engine import get_db
|
||||||
from app.models.catalog import StandardConversion
|
from app.models.catalog import StandardConversion
|
||||||
from app.schemas.catalog import StandardConversionCreate, StandardConversionUpdate
|
from app.schemas.catalog import StandardConversionCreate, StandardConversionUpdate
|
||||||
@@ -11,6 +12,7 @@ from app.utils.pagination import paginate
|
|||||||
from app.utils.serialization import to_iso
|
from app.utils.serialization import to_iso
|
||||||
|
|
||||||
router = APIRouter(prefix="/standard-conversions", tags=["standard-conversions"])
|
router = APIRouter(prefix="/standard-conversions", tags=["standard-conversions"])
|
||||||
|
_procurement_writer = require_procurement_writer()
|
||||||
|
|
||||||
|
|
||||||
def sc_to_dict(sc: StandardConversion) -> dict:
|
def sc_to_dict(sc: StandardConversion) -> dict:
|
||||||
@@ -41,7 +43,11 @@ async def list_standard_conversions(
|
|||||||
|
|
||||||
|
|
||||||
@router.post("", status_code=201)
|
@router.post("", status_code=201)
|
||||||
async def create_standard_conversion(payload: StandardConversionCreate, db: AsyncSession = Depends(get_db)):
|
async def create_standard_conversion(
|
||||||
|
payload: StandardConversionCreate,
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
_auth=Depends(_procurement_writer),
|
||||||
|
):
|
||||||
duplicate = await db.scalar(
|
duplicate = await db.scalar(
|
||||||
select(StandardConversion.id).where(
|
select(StandardConversion.id).where(
|
||||||
StandardConversion.from_unit == payload.from_unit,
|
StandardConversion.from_unit == payload.from_unit,
|
||||||
@@ -67,7 +73,12 @@ async def get_standard_conversion(sc_id, db: AsyncSession = Depends(get_db)):
|
|||||||
|
|
||||||
|
|
||||||
@router.patch("/{sc_id}")
|
@router.patch("/{sc_id}")
|
||||||
async def update_standard_conversion(sc_id, payload: StandardConversionUpdate, db: AsyncSession = Depends(get_db)):
|
async def update_standard_conversion(
|
||||||
|
sc_id,
|
||||||
|
payload: StandardConversionUpdate,
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
_auth=Depends(_procurement_writer),
|
||||||
|
):
|
||||||
sc = await db.get(StandardConversion, sc_id)
|
sc = await db.get(StandardConversion, sc_id)
|
||||||
if sc is None:
|
if sc is None:
|
||||||
raise NotFoundError("تبدیل استاندارد یافت نشد")
|
raise NotFoundError("تبدیل استاندارد یافت نشد")
|
||||||
@@ -94,7 +105,11 @@ async def update_standard_conversion(sc_id, payload: StandardConversionUpdate, d
|
|||||||
|
|
||||||
|
|
||||||
@router.delete("/{sc_id}")
|
@router.delete("/{sc_id}")
|
||||||
async def delete_standard_conversion(sc_id, db: AsyncSession = Depends(get_db)):
|
async def delete_standard_conversion(
|
||||||
|
sc_id,
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
_auth=Depends(_procurement_writer),
|
||||||
|
):
|
||||||
sc = await db.get(StandardConversion, sc_id)
|
sc = await db.get(StandardConversion, sc_id)
|
||||||
if sc is None:
|
if sc is None:
|
||||||
raise NotFoundError("تبدیل استاندارد یافت نشد")
|
raise NotFoundError("تبدیل استاندارد یافت نشد")
|
||||||
|
|||||||
@@ -2,12 +2,15 @@
|
|||||||
|
|
||||||
GET/POST /suppliers/{id}/materials — manage a supplier's catalog.
|
GET/POST /suppliers/{id}/materials — manage a supplier's catalog.
|
||||||
DELETE /suppliers/{id}/materials/{material_id} — unlink.
|
DELETE /suppliers/{id}/materials/{material_id} — unlink.
|
||||||
GET /materials/{id}/suppliers — price-comparison data source.
|
GET /materials/{id}/suppliers — suppliers linked to a material.
|
||||||
"""
|
"""
|
||||||
|
from uuid import UUID
|
||||||
|
|
||||||
from fastapi import APIRouter, Depends, Query
|
from fastapi import APIRouter, Depends, Query
|
||||||
from sqlalchemy import select
|
from sqlalchemy import select
|
||||||
from sqlalchemy.ext.asyncio import AsyncSession
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
|
from app.auth import require_procurement_writer, require_role
|
||||||
from app.db.engine import get_db
|
from app.db.engine import get_db
|
||||||
from app.models.catalog import Material, MaterialCategory
|
from app.models.catalog import Material, MaterialCategory
|
||||||
from app.models.procurement import Supplier, SupplierMaterial
|
from app.models.procurement import Supplier, SupplierMaterial
|
||||||
@@ -18,31 +21,50 @@ from app.utils.pagination import paginate
|
|||||||
from app.utils.serialization import to_iso
|
from app.utils.serialization import to_iso
|
||||||
|
|
||||||
router = APIRouter(tags=["supplier-materials"])
|
router = APIRouter(tags=["supplier-materials"])
|
||||||
|
_procurement_writer = require_procurement_writer()
|
||||||
|
|
||||||
|
|
||||||
def link_to_dict(link: SupplierMaterial, material: Material | None = None,
|
def link_to_dict(
|
||||||
|
link: SupplierMaterial,
|
||||||
|
material: Material | None = None,
|
||||||
category: MaterialCategory | None = None,
|
category: MaterialCategory | None = None,
|
||||||
supplier: Supplier | None = None) -> dict:
|
supplier: Supplier | None = None,
|
||||||
|
) -> dict:
|
||||||
|
"""Serialize a SupplierMaterial ORM row to a plain dict for the API envelope."""
|
||||||
return {
|
return {
|
||||||
"id": str(link.id),
|
"id": str(link.id),
|
||||||
"supplier_id": str(link.supplier_id),
|
"supplier_id": str(link.supplier_id),
|
||||||
"material_id": str(link.material_id),
|
"material_id": str(link.material_id),
|
||||||
"is_active": link.is_active,
|
"is_active": link.is_active,
|
||||||
"last_quoted_price": float(link.last_quoted_price) if link.last_quoted_price is not None else None,
|
"last_quoted_price": (
|
||||||
|
float(link.last_quoted_price) if link.last_quoted_price is not None else None
|
||||||
|
),
|
||||||
"last_quoted_at": to_iso(link.last_quoted_at) if link.last_quoted_at else None,
|
"last_quoted_at": to_iso(link.last_quoted_at) if link.last_quoted_at else None,
|
||||||
"created_at": to_iso(link.created_at),
|
"created_at": to_iso(link.created_at),
|
||||||
"material": {
|
"material": (
|
||||||
|
{
|
||||||
"id": str(material.id),
|
"id": str(material.id),
|
||||||
"name": material.name,
|
"name": material.name,
|
||||||
"category": {"id": str(category.id), "name": category.name} if category else None,
|
"category": (
|
||||||
} if material else None,
|
{"id": str(category.id), "name": category.name} if category else None
|
||||||
"supplier": {"id": str(supplier.id), "name": supplier.name} if supplier else None,
|
),
|
||||||
|
}
|
||||||
|
if material
|
||||||
|
else None
|
||||||
|
),
|
||||||
|
"supplier": (
|
||||||
|
{"id": str(supplier.id), "name": supplier.name} if supplier else None
|
||||||
|
),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# GET /suppliers/{supplier_id}/materials
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
@router.get("/suppliers/{supplier_id}/materials")
|
@router.get("/suppliers/{supplier_id}/materials")
|
||||||
async def list_supplier_materials(
|
async def list_supplier_materials(
|
||||||
supplier_id,
|
supplier_id: UUID,
|
||||||
page: int = Query(1, ge=1),
|
page: int = Query(1, ge=1),
|
||||||
page_size: int = Query(20, ge=1, le=100),
|
page_size: int = Query(20, ge=1, le=100),
|
||||||
db: AsyncSession = Depends(get_db),
|
db: AsyncSession = Depends(get_db),
|
||||||
@@ -56,23 +78,45 @@ async def list_supplier_materials(
|
|||||||
.order_by(SupplierMaterial.created_at)
|
.order_by(SupplierMaterial.created_at)
|
||||||
)
|
)
|
||||||
items, meta = await paginate(stmt, page, page_size, db)
|
items, meta = await paginate(stmt, page, page_size, db)
|
||||||
mat_ids = {l.material_id for l in items}
|
mat_ids = [lnk.material_id for lnk in items]
|
||||||
materials = {m.id: m for m in (await db.execute(select(Material).where(Material.id.in_(mat_ids)))).scalars()}
|
materials: dict = {}
|
||||||
return {"data": [link_to_dict(l, materials.get(l.material_id), None) for l in items], "meta": meta}
|
if mat_ids:
|
||||||
|
result = await db.execute(select(Material).where(Material.id.in_(mat_ids)))
|
||||||
|
materials = {m.id: m for m in result.scalars()}
|
||||||
|
return {
|
||||||
|
"data": [link_to_dict(lnk, materials.get(lnk.material_id)) for lnk in items],
|
||||||
|
"meta": meta,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# POST /suppliers/{supplier_id}/materials
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
@router.post("/suppliers/{supplier_id}/materials", status_code=201)
|
@router.post("/suppliers/{supplier_id}/materials", status_code=201)
|
||||||
async def create_supplier_material(
|
async def create_supplier_material(
|
||||||
supplier_id, payload: SupplierMaterialCreate, db: AsyncSession = Depends(get_db)
|
supplier_id: UUID,
|
||||||
|
payload: SupplierMaterialCreate,
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
_auth=Depends(_procurement_writer),
|
||||||
):
|
):
|
||||||
async with db.begin():
|
async with db.begin():
|
||||||
link = await link_supplier_material(db, supplier_id, payload.material_id)
|
link = await link_supplier_material(db, supplier_id, payload.material_id)
|
||||||
material = await db.get(Material, payload.material_id)
|
material = await db.get(Material, payload.material_id)
|
||||||
return {"data": link_to_dict(link, material, None)}
|
return {"data": link_to_dict(link, material)}
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# DELETE /suppliers/{supplier_id}/materials/{material_id}
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
@router.delete("/suppliers/{supplier_id}/materials/{material_id}")
|
@router.delete("/suppliers/{supplier_id}/materials/{material_id}")
|
||||||
async def delete_supplier_material(supplier_id, material_id, db: AsyncSession = Depends(get_db)):
|
async def delete_supplier_material(
|
||||||
|
supplier_id: UUID,
|
||||||
|
material_id: UUID,
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
_auth=Depends(_procurement_writer),
|
||||||
|
):
|
||||||
async with db.begin():
|
async with db.begin():
|
||||||
await unlink_supplier_material(db, supplier_id, material_id)
|
await unlink_supplier_material(db, supplier_id, material_id)
|
||||||
return {"data": {"supplier_id": str(supplier_id), "material_id": str(material_id), "deleted": True}}
|
return {"data": {"supplier_id": str(supplier_id), "material_id": str(material_id), "deleted": True}}
|
||||||
@@ -83,17 +127,80 @@ async def list_material_suppliers(
|
|||||||
material_id,
|
material_id,
|
||||||
page: int = Query(1, ge=1),
|
page: int = Query(1, ge=1),
|
||||||
page_size: int = Query(20, ge=1, le=100),
|
page_size: int = Query(20, ge=1, le=100),
|
||||||
|
|
||||||
db: AsyncSession = Depends(get_db),
|
db: AsyncSession = Depends(get_db),
|
||||||
):
|
):
|
||||||
|
async with db.begin():
|
||||||
|
await unlink_supplier_material(db, supplier_id, material_id)
|
||||||
|
return {
|
||||||
|
"data": {
|
||||||
|
"supplier_id": str(supplier_id),
|
||||||
|
"material_id": str(material_id),
|
||||||
|
"deleted": True,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# GET /materials/{material_id}/suppliers
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
@router.get(
|
||||||
|
"/materials/{material_id}/suppliers",
|
||||||
|
summary="List all suppliers linked to a material",
|
||||||
|
)
|
||||||
|
async def list_material_suppliers(
|
||||||
|
material_id: UUID,
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
):
|
||||||
|
"""Return the suppliers linked to a material, straight from PostgreSQL.
|
||||||
|
|
||||||
|
The path parameter is typed as UUID so FastAPI validates and coerces it
|
||||||
|
before the handler runs; a malformed id is rejected with 422, an unknown
|
||||||
|
material with 404.
|
||||||
|
|
||||||
|
Atomic JOIN — a supplier is returned only through its supplier_materials
|
||||||
|
link, so the response can never contain a supplier that is not actually
|
||||||
|
linked to this material:
|
||||||
|
|
||||||
|
select(Supplier)
|
||||||
|
.join(SupplierMaterial, Supplier.id == SupplierMaterial.supplier_id)
|
||||||
|
.where(SupplierMaterial.material_id == material_id)
|
||||||
|
|
||||||
|
Response envelope (frontend MaterialSupplier binds these fields directly):
|
||||||
|
{
|
||||||
|
"data": [
|
||||||
|
{
|
||||||
|
"id": "<supplier_uuid>",
|
||||||
|
"name": "فولاد ناب آریا",
|
||||||
|
"phone": "021-..." | null,
|
||||||
|
"contact_person": "علی محمدی" | null,
|
||||||
|
"location": "تهران" | null
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
"""
|
||||||
material = await db.get(Material, material_id)
|
material = await db.get(Material, material_id)
|
||||||
if material is None:
|
if material is None:
|
||||||
raise NotFoundError("متریال یافت نشد")
|
raise NotFoundError("متریال یافت نشد")
|
||||||
|
|
||||||
stmt = (
|
stmt = (
|
||||||
select(SupplierMaterial)
|
select(Supplier)
|
||||||
|
.join(SupplierMaterial, Supplier.id == SupplierMaterial.supplier_id)
|
||||||
.where(SupplierMaterial.material_id == material_id)
|
.where(SupplierMaterial.material_id == material_id)
|
||||||
.order_by(SupplierMaterial.last_quoted_at.desc().nulls_last())
|
.order_by(Supplier.name)
|
||||||
)
|
)
|
||||||
items, meta = await paginate(stmt, page, page_size, db)
|
suppliers = (await db.execute(stmt)).scalars().all()
|
||||||
sup_ids = {l.supplier_id for l in items}
|
|
||||||
suppliers = {s.id: s for s in (await db.execute(select(Supplier).where(Supplier.id.in_(sup_ids)))).scalars()}
|
return {
|
||||||
return {"data": [link_to_dict(l, supplier=suppliers.get(l.supplier_id)) for l in items], "meta": meta}
|
"data": [
|
||||||
|
{
|
||||||
|
"id": str(supplier.id),
|
||||||
|
"name": supplier.name,
|
||||||
|
"phone": supplier.phone,
|
||||||
|
"contact_person": supplier.contact_person,
|
||||||
|
"location": supplier.location,
|
||||||
|
}
|
||||||
|
for supplier in suppliers
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ from fastapi import APIRouter, Depends, Query
|
|||||||
from sqlalchemy import func, or_, select
|
from sqlalchemy import func, or_, select
|
||||||
from sqlalchemy.ext.asyncio import AsyncSession
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
|
from app.auth import require_procurement_writer, require_role
|
||||||
from app.db.engine import get_db
|
from app.db.engine import get_db
|
||||||
from app.models.catalog import MaterialCategory
|
from app.models.catalog import MaterialCategory
|
||||||
from app.models.procurement import Quote, Supplier
|
from app.models.procurement import Quote, Supplier
|
||||||
@@ -12,6 +13,7 @@ from app.utils.pagination import paginate, sort_query
|
|||||||
from app.utils.serialization import to_iso
|
from app.utils.serialization import to_iso
|
||||||
|
|
||||||
router = APIRouter(prefix="/suppliers", tags=["suppliers"])
|
router = APIRouter(prefix="/suppliers", tags=["suppliers"])
|
||||||
|
_procurement_writer = require_procurement_writer()
|
||||||
|
|
||||||
|
|
||||||
def supplier_to_dict(supplier: Supplier, category: MaterialCategory | None = None) -> dict:
|
def supplier_to_dict(supplier: Supplier, category: MaterialCategory | None = None) -> dict:
|
||||||
@@ -71,7 +73,11 @@ async def list_suppliers(
|
|||||||
|
|
||||||
|
|
||||||
@router.post("", status_code=201)
|
@router.post("", status_code=201)
|
||||||
async def create_supplier(payload: SupplierCreate, db: AsyncSession = Depends(get_db)):
|
async def create_supplier(
|
||||||
|
payload: SupplierCreate,
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
_auth=Depends(_procurement_writer),
|
||||||
|
):
|
||||||
category = await _category_or_404(db, payload.category_id)
|
category = await _category_or_404(db, payload.category_id)
|
||||||
supplier = Supplier(
|
supplier = Supplier(
|
||||||
name=payload.name,
|
name=payload.name,
|
||||||
@@ -96,7 +102,12 @@ async def get_supplier(supplier_id, db: AsyncSession = Depends(get_db)):
|
|||||||
|
|
||||||
|
|
||||||
@router.patch("/{supplier_id}")
|
@router.patch("/{supplier_id}")
|
||||||
async def update_supplier(supplier_id, payload: SupplierUpdate, db: AsyncSession = Depends(get_db)):
|
async def update_supplier(
|
||||||
|
supplier_id,
|
||||||
|
payload: SupplierUpdate,
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
_auth=Depends(_procurement_writer),
|
||||||
|
):
|
||||||
supplier = await db.get(Supplier, supplier_id)
|
supplier = await db.get(Supplier, supplier_id)
|
||||||
if supplier is None:
|
if supplier is None:
|
||||||
raise NotFoundError("تأمینکننده یافت نشد")
|
raise NotFoundError("تأمینکننده یافت نشد")
|
||||||
@@ -120,7 +131,11 @@ async def update_supplier(supplier_id, payload: SupplierUpdate, db: AsyncSession
|
|||||||
|
|
||||||
|
|
||||||
@router.delete("/{supplier_id}")
|
@router.delete("/{supplier_id}")
|
||||||
async def delete_supplier(supplier_id, db: AsyncSession = Depends(get_db)):
|
async def delete_supplier(
|
||||||
|
supplier_id,
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
_auth=Depends(_procurement_writer),
|
||||||
|
):
|
||||||
supplier = await db.get(Supplier, supplier_id)
|
supplier = await db.get(Supplier, supplier_id)
|
||||||
if supplier is None:
|
if supplier is None:
|
||||||
raise NotFoundError("تأمینکننده یافت نشد")
|
raise NotFoundError("تأمینکننده یافت نشد")
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ from fastapi import APIRouter, Depends, Query
|
|||||||
from sqlalchemy import func, select
|
from sqlalchemy import func, select
|
||||||
from sqlalchemy.ext.asyncio import AsyncSession
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
|
from app.auth import require_procurement_writer, require_role
|
||||||
from app.db.engine import get_db
|
from app.db.engine import get_db
|
||||||
from app.models.procurement import (
|
from app.models.procurement import (
|
||||||
ItemDecision,
|
ItemDecision,
|
||||||
@@ -26,6 +27,7 @@ from app.utils.errors import ConflictError, NotFoundError, ValidationError
|
|||||||
from app.utils.pagination import paginate, sort_query
|
from app.utils.pagination import paginate, sort_query
|
||||||
|
|
||||||
router = APIRouter(prefix="/quotes/{quote_id}/termsheets", tags=["termsheets"])
|
router = APIRouter(prefix="/quotes/{quote_id}/termsheets", tags=["termsheets"])
|
||||||
|
_procurement_writer = require_procurement_writer()
|
||||||
|
|
||||||
|
|
||||||
async def _quote_or_404(db: AsyncSession, quote_id) -> Quote:
|
async def _quote_or_404(db: AsyncSession, quote_id) -> Quote:
|
||||||
@@ -80,7 +82,12 @@ async def list_termsheets(
|
|||||||
|
|
||||||
|
|
||||||
@router.post("", status_code=201)
|
@router.post("", status_code=201)
|
||||||
async def create_termsheet(quote_id, payload: TermsheetCreate, db: AsyncSession = Depends(get_db)):
|
async def create_termsheet(
|
||||||
|
quote_id,
|
||||||
|
payload: TermsheetCreate,
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
_auth=Depends(_procurement_writer),
|
||||||
|
):
|
||||||
async with db.begin():
|
async with db.begin():
|
||||||
quote = await _quote_or_404(db, quote_id)
|
quote = await _quote_or_404(db, quote_id)
|
||||||
if quote.status != "offered":
|
if quote.status != "offered":
|
||||||
@@ -110,7 +117,11 @@ async def get_termsheet(
|
|||||||
|
|
||||||
@router.patch("/{termsheet_id}")
|
@router.patch("/{termsheet_id}")
|
||||||
async def update_termsheet(
|
async def update_termsheet(
|
||||||
quote_id, termsheet_id, payload: TermsheetUpdate, db: AsyncSession = Depends(get_db)
|
quote_id,
|
||||||
|
termsheet_id,
|
||||||
|
payload: TermsheetUpdate,
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
_auth=Depends(_procurement_writer),
|
||||||
):
|
):
|
||||||
ts = await _termsheet_or_404(db, quote_id, termsheet_id)
|
ts = await _termsheet_or_404(db, quote_id, termsheet_id)
|
||||||
if ts.status != "offered":
|
if ts.status != "offered":
|
||||||
@@ -127,7 +138,11 @@ async def update_termsheet(
|
|||||||
|
|
||||||
@router.patch("/{termsheet_id}/status")
|
@router.patch("/{termsheet_id}/status")
|
||||||
async def update_termsheet_status(
|
async def update_termsheet_status(
|
||||||
quote_id, termsheet_id, payload: TermsheetStatusUpdate, db: AsyncSession = Depends(get_db)
|
quote_id,
|
||||||
|
termsheet_id,
|
||||||
|
payload: TermsheetStatusUpdate,
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
_auth=Depends(_procurement_writer),
|
||||||
):
|
):
|
||||||
async with db.begin():
|
async with db.begin():
|
||||||
ts = await _termsheet_or_404(db, quote_id, termsheet_id)
|
ts = await _termsheet_or_404(db, quote_id, termsheet_id)
|
||||||
@@ -139,7 +154,12 @@ async def update_termsheet_status(
|
|||||||
|
|
||||||
|
|
||||||
@router.delete("/{termsheet_id}")
|
@router.delete("/{termsheet_id}")
|
||||||
async def delete_termsheet(quote_id, termsheet_id, db: AsyncSession = Depends(get_db)):
|
async def delete_termsheet(
|
||||||
|
quote_id,
|
||||||
|
termsheet_id,
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
_auth=Depends(_procurement_writer),
|
||||||
|
):
|
||||||
ts = await _termsheet_or_404(db, quote_id, termsheet_id)
|
ts = await _termsheet_or_404(db, quote_id, termsheet_id)
|
||||||
quote = await _quote_or_404(db, quote_id)
|
quote = await _quote_or_404(db, quote_id)
|
||||||
if quote.status != "offered":
|
if quote.status != "offered":
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ from fastapi import APIRouter, Depends, Query
|
|||||||
from sqlalchemy import func, or_, select
|
from sqlalchemy import func, or_, select
|
||||||
from sqlalchemy.ext.asyncio import AsyncSession
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
|
from app.auth import require_procurement_writer, require_role
|
||||||
from app.db.engine import get_db
|
from app.db.engine import get_db
|
||||||
from app.models.catalog import AttributeDefinition, Material, MaterialUnit, Unit
|
from app.models.catalog import AttributeDefinition, Material, MaterialUnit, Unit
|
||||||
from app.models.procurement import LineItem, LineItemSpec
|
from app.models.procurement import LineItem, LineItemSpec
|
||||||
@@ -11,6 +12,7 @@ from app.utils.errors import ConflictError, NotFoundError
|
|||||||
from app.utils.pagination import paginate, sort_query
|
from app.utils.pagination import paginate, sort_query
|
||||||
|
|
||||||
router = APIRouter(prefix="/units", tags=["units"])
|
router = APIRouter(prefix="/units", tags=["units"])
|
||||||
|
_procurement_writer = require_procurement_writer()
|
||||||
|
|
||||||
|
|
||||||
def unit_full_to_dict(unit: Unit) -> dict:
|
def unit_full_to_dict(unit: Unit) -> dict:
|
||||||
@@ -45,7 +47,11 @@ async def list_units(
|
|||||||
|
|
||||||
|
|
||||||
@router.post("", status_code=201)
|
@router.post("", status_code=201)
|
||||||
async def create_unit(payload: UnitCreate, db: AsyncSession = Depends(get_db)):
|
async def create_unit(
|
||||||
|
payload: UnitCreate,
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
_auth=Depends(_procurement_writer),
|
||||||
|
):
|
||||||
duplicate = await db.scalar(select(Unit.id).where(Unit.code == payload.code))
|
duplicate = await db.scalar(select(Unit.id).where(Unit.code == payload.code))
|
||||||
if duplicate is not None:
|
if duplicate is not None:
|
||||||
raise ConflictError("واحدی با این کد قبلاً ثبت شده است", field="code")
|
raise ConflictError("واحدی با این کد قبلاً ثبت شده است", field="code")
|
||||||
@@ -70,7 +76,12 @@ async def get_unit(unit_id: int, db: AsyncSession = Depends(get_db)):
|
|||||||
|
|
||||||
|
|
||||||
@router.patch("/{unit_id}")
|
@router.patch("/{unit_id}")
|
||||||
async def update_unit(unit_id: int, payload: UnitUpdate, db: AsyncSession = Depends(get_db)):
|
async def update_unit(
|
||||||
|
unit_id: int,
|
||||||
|
payload: UnitUpdate,
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
_auth=Depends(_procurement_writer),
|
||||||
|
):
|
||||||
unit = await db.get(Unit, unit_id)
|
unit = await db.get(Unit, unit_id)
|
||||||
if unit is None:
|
if unit is None:
|
||||||
raise NotFoundError("واحد یافت نشد")
|
raise NotFoundError("واحد یافت نشد")
|
||||||
@@ -92,7 +103,11 @@ async def update_unit(unit_id: int, payload: UnitUpdate, db: AsyncSession = Depe
|
|||||||
|
|
||||||
|
|
||||||
@router.delete("/{unit_id}")
|
@router.delete("/{unit_id}")
|
||||||
async def delete_unit(unit_id: int, db: AsyncSession = Depends(get_db)):
|
async def delete_unit(
|
||||||
|
unit_id: int,
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
_auth=Depends(_procurement_writer),
|
||||||
|
):
|
||||||
unit = await db.get(Unit, unit_id)
|
unit = await db.get(Unit, unit_id)
|
||||||
if unit is None:
|
if unit is None:
|
||||||
raise NotFoundError("واحد یافت نشد")
|
raise NotFoundError("واحد یافت نشد")
|
||||||
|
|||||||
+186
-31
@@ -17,15 +17,21 @@ import uuid
|
|||||||
|
|
||||||
import httpx
|
import httpx
|
||||||
from fastapi import APIRouter, Depends
|
from fastapi import APIRouter, Depends
|
||||||
from sqlalchemy import select, update
|
from sqlalchemy import delete, select, update, text, or_
|
||||||
from sqlalchemy.ext.asyncio import AsyncSession
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
from app.auth import UserContext, get_current_user, require_role
|
from app.auth import UserContext, get_current_user, require_role
|
||||||
from app.utils.audit import record as audit_record
|
from app.utils.audit import record as audit_record
|
||||||
from app.config import settings
|
from app.config import settings
|
||||||
from app.db.engine import get_db
|
from app.db.engine import get_db
|
||||||
from app.models.procurement import Project, User
|
from app.models.procurement import Project, User, UserPanel, UserProjectMembership
|
||||||
from app.schemas.procurement import UserCreate, UserProjectUpdate, UserRoleUpdate
|
from app.schemas.procurement import (
|
||||||
|
UserCreate,
|
||||||
|
UserPanelsUpdate,
|
||||||
|
UserPanelProjectsUpdate,
|
||||||
|
UserProjectUpdate,
|
||||||
|
UserRoleUpdate,
|
||||||
|
)
|
||||||
from app.utils.errors import (
|
from app.utils.errors import (
|
||||||
ConflictError,
|
ConflictError,
|
||||||
ForbiddenError,
|
ForbiddenError,
|
||||||
@@ -41,17 +47,47 @@ USER_ROLE_LABELS = {
|
|||||||
"pm": "مدیر پروژه",
|
"pm": "مدیر پروژه",
|
||||||
"procurement_manager": "مدیر تدارکات",
|
"procurement_manager": "مدیر تدارکات",
|
||||||
"admin": "ادمین",
|
"admin": "ادمین",
|
||||||
|
# کاربر فقطِ پنل مدیریت پروژه (PM) — به انبار/تدارکات دسترسی ندارد
|
||||||
|
"supervisor": "سرپرست پروژه",
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
def user_to_dict(user: User, projects: list[Project] | None = None) -> dict:
|
PANEL_LEVELS = ("full", "limited")
|
||||||
|
PANELS = ("procurement", "inventory", "pm")
|
||||||
|
|
||||||
|
|
||||||
|
async def _panels_of(db: AsyncSession, user_id) -> dict:
|
||||||
|
"""panel -> level map for the user (لایه پنلها — جایگزین نقشها)."""
|
||||||
|
rows = (
|
||||||
|
await db.execute(
|
||||||
|
select(UserPanel).where(UserPanel.user_id == user_id).order_by(UserPanel.created_at)
|
||||||
|
)
|
||||||
|
).scalars().all()
|
||||||
|
return {row.panel: row.level for row in rows}
|
||||||
|
|
||||||
|
|
||||||
|
async def _member_project_ids_of(db: AsyncSession, user_id) -> list[str]:
|
||||||
|
"""عضویت M:N کاربر در پروژهها (جدا از مسئولیت) — رشته."""
|
||||||
|
rows = (
|
||||||
|
await db.execute(
|
||||||
|
select(UserProjectMembership.project_id)
|
||||||
|
.where(UserProjectMembership.user_id == user_id)
|
||||||
|
.order_by(UserProjectMembership.created_at)
|
||||||
|
)
|
||||||
|
).scalars().all()
|
||||||
|
return [str(pid) for pid in rows]
|
||||||
|
|
||||||
|
|
||||||
|
async def user_to_dict(user: User, projects: list[Project] | None = None, db: AsyncSession | None = None) -> dict:
|
||||||
"""Serialize a user. `projects` = every project the PM manages (1:N);
|
"""Serialize a user. `projects` = every project the PM manages (1:N);
|
||||||
project_id/project_name stay as the first (oldest) one for compatibility."""
|
project_id/project_name stay as the first (oldest) one for compatibility.
|
||||||
|
با db، پنلهای تخصیصی و عضویت پروژهای هم برمیگردند."""
|
||||||
projects = projects or []
|
projects = projects or []
|
||||||
first = projects[0] if projects else None
|
first = projects[0] if projects else None
|
||||||
return {
|
out = {
|
||||||
"id": str(user.id),
|
"id": str(user.id),
|
||||||
"casdoor_id": user.casdoor_id,
|
"casdoor_id": user.casdoor_id,
|
||||||
|
"username": user.username,
|
||||||
"first_name": user.first_name,
|
"first_name": user.first_name,
|
||||||
"last_name": user.last_name,
|
"last_name": user.last_name,
|
||||||
"phone": user.phone,
|
"phone": user.phone,
|
||||||
@@ -62,23 +98,39 @@ def user_to_dict(user: User, projects: list[Project] | None = None) -> dict:
|
|||||||
"projects": [{"id": str(p.id), "name": p.name} for p in projects],
|
"projects": [{"id": str(p.id), "name": p.name} for p in projects],
|
||||||
"created_at": to_iso(user.created_at),
|
"created_at": to_iso(user.created_at),
|
||||||
}
|
}
|
||||||
|
if db is not None:
|
||||||
|
out["panels"] = await _panels_of(db, user.id)
|
||||||
|
member_pids = await _member_project_ids_of(db, user.id)
|
||||||
|
all_pids = list(dict.fromkeys(member_pids + [str(p.id) for p in projects]))
|
||||||
|
out["member_project_ids"] = all_pids
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
async def _org_manager(ctx: UserContext = Depends(get_current_user)) -> UserContext:
|
async def _org_manager(ctx: UserContext = Depends(get_current_user)) -> UserContext:
|
||||||
"""Admin OR procurement manager (the same person) — organization management."""
|
"""Admin, procurement manager, or project manager — organization management."""
|
||||||
if ctx.role not in ("admin", "procurement_manager"):
|
if ctx.role not in ("admin", "procurement_manager", "pm"):
|
||||||
raise ForbiddenError("دسترسی به این بخش برای نقش شما مجاز نیست")
|
raise ForbiddenError("دسترسی به این بخش برای نقش شما مجاز نیست")
|
||||||
return ctx
|
return ctx
|
||||||
|
|
||||||
|
|
||||||
async def _user_projects(db: AsyncSession, user: User) -> list[Project]:
|
async def _user_projects(db: AsyncSession, user: User) -> list[Project]:
|
||||||
"""Every project the user manages as PM (oldest first; [] for non-PMs)."""
|
"""Every project assigned to the user (supervisor or PM) (oldest first).
|
||||||
if user.role != "pm":
|
Includes both direct PM assignments (pm_user_id) and member projects (UserProjectMembership).
|
||||||
|
"""
|
||||||
|
if user.role not in ("supervisor", "pm"):
|
||||||
return []
|
return []
|
||||||
|
member_subq = select(UserProjectMembership.project_id).where(
|
||||||
|
UserProjectMembership.user_id == user.id
|
||||||
|
)
|
||||||
rows = (
|
rows = (
|
||||||
await db.execute(
|
await db.execute(
|
||||||
select(Project)
|
select(Project)
|
||||||
.where(Project.pm_user_id == user.id)
|
.where(
|
||||||
|
or_(
|
||||||
|
Project.pm_user_id == user.id,
|
||||||
|
Project.id.in_(member_subq),
|
||||||
|
)
|
||||||
|
)
|
||||||
.order_by(Project.created_at, Project.id)
|
.order_by(Project.created_at, Project.id)
|
||||||
)
|
)
|
||||||
).scalars().all()
|
).scalars().all()
|
||||||
@@ -127,7 +179,7 @@ async def _casdoor_users() -> list[dict]:
|
|||||||
@router.get("/me")
|
@router.get("/me")
|
||||||
async def me(ctx: UserContext = Depends(get_current_user), db: AsyncSession = Depends(get_db)):
|
async def me(ctx: UserContext = Depends(get_current_user), db: AsyncSession = Depends(get_db)):
|
||||||
projects = await _user_projects(db, ctx.user)
|
projects = await _user_projects(db, ctx.user)
|
||||||
return {"data": user_to_dict(ctx.user, projects)}
|
return {"data": await user_to_dict(ctx.user, projects, db)}
|
||||||
|
|
||||||
|
|
||||||
@router.get("/me/projects")
|
@router.get("/me/projects")
|
||||||
@@ -138,6 +190,18 @@ async def my_projects(ctx: UserContext = Depends(get_current_user), db: AsyncSes
|
|||||||
active project against this list and falls back gracefully when a
|
active project against this list and falls back gracefully when a
|
||||||
project is revoked."""
|
project is revoked."""
|
||||||
projects = await _user_projects(db, ctx.user)
|
projects = await _user_projects(db, ctx.user)
|
||||||
|
# عضویتهای M:N (لایه پنلها) هم به فهرست اضافه میشود
|
||||||
|
member_ids = set(ctx.member_project_ids or [])
|
||||||
|
have = {p.id for p in projects}
|
||||||
|
if member_ids:
|
||||||
|
extra = (
|
||||||
|
await db.execute(
|
||||||
|
select(Project)
|
||||||
|
.where(Project.id.in_(member_ids))
|
||||||
|
.order_by(Project.created_at, Project.id)
|
||||||
|
)
|
||||||
|
).scalars().all()
|
||||||
|
projects = list(projects) + [p for p in extra if p.id not in have]
|
||||||
return {"data": [{"id": str(p.id), "name": p.name} for p in projects]}
|
return {"data": [{"id": str(p.id), "name": p.name} for p in projects]}
|
||||||
|
|
||||||
|
|
||||||
@@ -148,20 +212,20 @@ async def list_users(
|
|||||||
):
|
):
|
||||||
"""Every user (with role + assigned projects) — Organization panel."""
|
"""Every user (with role + assigned projects) — Organization panel."""
|
||||||
users = (await db.execute(select(User).order_by(User.created_at))).scalars().all()
|
users = (await db.execute(select(User).order_by(User.created_at))).scalars().all()
|
||||||
pm_ids = {u.id for u in users if u.role == "pm"}
|
supervisor_ids = {u.id for u in users if u.role in ("supervisor", "pm")}
|
||||||
by_user: dict = {}
|
by_user: dict = {}
|
||||||
if pm_ids:
|
if supervisor_ids:
|
||||||
projs = (
|
projs = (
|
||||||
await db.execute(
|
await db.execute(
|
||||||
select(Project)
|
select(Project)
|
||||||
.where(Project.pm_user_id.in_(pm_ids))
|
.where(Project.pm_user_id.in_(supervisor_ids))
|
||||||
.order_by(Project.created_at, Project.id)
|
.order_by(Project.created_at, Project.id)
|
||||||
)
|
)
|
||||||
).scalars().all()
|
).scalars().all()
|
||||||
for p in projs:
|
for p in projs:
|
||||||
by_user.setdefault(p.pm_user_id, []).append(p)
|
by_user.setdefault(p.pm_user_id, []).append(p)
|
||||||
return {
|
return {
|
||||||
"data": [user_to_dict(u, by_user.get(u.id, [])) for u in users],
|
"data": [await user_to_dict(u, by_user.get(u.id, []), db) for u in users],
|
||||||
"meta": {"total": len(users)},
|
"meta": {"total": len(users)},
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -187,30 +251,30 @@ async def create_user(
|
|||||||
db.add(user)
|
db.add(user)
|
||||||
await db.flush()
|
await db.flush()
|
||||||
await audit_record(db, actor=ctx.display_name, action="user.created", entity="user", entity_id=str(user.id), details={"role": payload.role})
|
await audit_record(db, actor=ctx.display_name, action="user.created", entity="user", entity_id=str(user.id), details={"role": payload.role})
|
||||||
return {"data": user_to_dict(user)}
|
return {"data": await user_to_dict(user)}
|
||||||
|
|
||||||
|
|
||||||
@router.patch("/{user_id}")
|
@router.patch("/{user_id}")
|
||||||
async def update_user_role(
|
async def update_user_role(
|
||||||
user_id,
|
user_id,
|
||||||
payload: UserRoleUpdate,
|
payload: UserRoleUpdate,
|
||||||
ctx: UserContext = Depends(require_role("admin")),
|
ctx: UserContext = Depends(_org_manager),
|
||||||
db: AsyncSession = Depends(get_db),
|
db: AsyncSession = Depends(get_db),
|
||||||
):
|
):
|
||||||
"""Set/clear a role — ADMIN ONLY (RBAC): procurement managers must not
|
"""Set/clear a role — organization management (admin, procurement manager, PM)."""
|
||||||
assign or elevate roles. Revoking (or switching away from «pm») also
|
if payload.role == "admin" and ctx.role != "admin":
|
||||||
unassigns the user from their project."""
|
raise ForbiddenError("فقط ادمین میتواند نقش ادمین تعیین کند")
|
||||||
user = await db.get(User, user_id)
|
user = await db.get(User, user_id)
|
||||||
if user is None:
|
if user is None:
|
||||||
raise NotFoundError("کاربر یافت نشد")
|
raise NotFoundError("کاربر یافت نشد")
|
||||||
previous_role = user.role
|
previous_role = user.role
|
||||||
if user.role == "pm" and payload.role != "pm":
|
if user.role in ("supervisor", "pm") and payload.role not in ("supervisor", "pm"):
|
||||||
await _unassign_projects(db, user.id)
|
await _unassign_projects(db, user.id)
|
||||||
user.role = payload.role
|
user.role = payload.role
|
||||||
await db.flush()
|
await db.flush()
|
||||||
await audit_record(db, actor=ctx.display_name, action="user.role_changed", entity="user", entity_id=str(user.id), details={"from": previous_role, "to": payload.role})
|
await audit_record(db, actor=ctx.display_name, action="user.role_changed", entity="user", entity_id=str(user.id), details={"from": previous_role, "to": payload.role})
|
||||||
projects = await _user_projects(db, user)
|
projects = await _user_projects(db, user)
|
||||||
return {"data": user_to_dict(user, projects)}
|
return {"data": await user_to_dict(user, projects)}
|
||||||
|
|
||||||
|
|
||||||
@router.post("/sync")
|
@router.post("/sync")
|
||||||
@@ -231,8 +295,15 @@ async def sync_casdoor_users(
|
|||||||
continue
|
continue
|
||||||
existing = await db.scalar(select(User).where(User.casdoor_id == cid))
|
existing = await db.scalar(select(User).where(User.casdoor_id == cid))
|
||||||
if existing is None:
|
if existing is None:
|
||||||
|
uname = str(cu.get("name") or cu.get("preferred_username") or "") or None
|
||||||
|
if uname:
|
||||||
|
by_uname = await db.scalar(select(User).where(User.username == uname))
|
||||||
|
if by_uname is not None:
|
||||||
|
by_uname.casdoor_id = cid
|
||||||
|
continue
|
||||||
db.add(User(
|
db.add(User(
|
||||||
casdoor_id=cid,
|
casdoor_id=cid,
|
||||||
|
username=uname,
|
||||||
first_name=str(
|
first_name=str(
|
||||||
cu.get("firstName")
|
cu.get("firstName")
|
||||||
or cu.get("displayName")
|
or cu.get("displayName")
|
||||||
@@ -243,23 +314,27 @@ async def sync_casdoor_users(
|
|||||||
phone=str(cu.get("phone") or "") or None,
|
phone=str(cu.get("phone") or "") or None,
|
||||||
))
|
))
|
||||||
created += 1
|
created += 1
|
||||||
|
elif not existing.username:
|
||||||
|
uname = str(cu.get("name") or cu.get("preferred_username") or "") or None
|
||||||
|
if uname:
|
||||||
|
existing.username = uname
|
||||||
await db.flush()
|
await db.flush()
|
||||||
|
|
||||||
users = (await db.execute(select(User).order_by(User.created_at))).scalars().all()
|
users = (await db.execute(select(User).order_by(User.created_at))).scalars().all()
|
||||||
pm_ids = {u.id for u in users if u.role == "pm"}
|
supervisor_ids = {u.id for u in users if u.role in ("supervisor", "pm")}
|
||||||
by_user: dict = {}
|
by_user: dict = {}
|
||||||
if pm_ids:
|
if supervisor_ids:
|
||||||
projs = (
|
projs = (
|
||||||
await db.execute(
|
await db.execute(
|
||||||
select(Project)
|
select(Project)
|
||||||
.where(Project.pm_user_id.in_(pm_ids))
|
.where(Project.pm_user_id.in_(supervisor_ids))
|
||||||
.order_by(Project.created_at, Project.id)
|
.order_by(Project.created_at, Project.id)
|
||||||
)
|
)
|
||||||
).scalars().all()
|
).scalars().all()
|
||||||
for p in projs:
|
for p in projs:
|
||||||
by_user.setdefault(p.pm_user_id, []).append(p)
|
by_user.setdefault(p.pm_user_id, []).append(p)
|
||||||
return {
|
return {
|
||||||
"data": [user_to_dict(u, by_user.get(u.id, [])) for u in users],
|
"data": [await user_to_dict(u, by_user.get(u.id, []), db) for u in users],
|
||||||
"meta": {"total": len(users), "created": created},
|
"meta": {"total": len(users), "created": created},
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -282,17 +357,97 @@ async def assign_user_project(
|
|||||||
user = await db.get(User, user_id)
|
user = await db.get(User, user_id)
|
||||||
if user is None:
|
if user is None:
|
||||||
raise NotFoundError("کاربر یافت نشد")
|
raise NotFoundError("کاربر یافت نشد")
|
||||||
if user.role != "pm":
|
if user.role not in ("supervisor", "pm"):
|
||||||
raise ValidationError("ابتدا نقش این کاربر را «مدیر پروژه» کنید", field="role")
|
raise ValidationError("ابتدا نقش این کاربر را «سرپرست پروژه» کنید", field="role")
|
||||||
|
|
||||||
if payload.project_id is None:
|
if payload.project_id is None:
|
||||||
await _unassign_projects(db, user.id)
|
await _unassign_projects(db, user.id)
|
||||||
|
if user.username:
|
||||||
|
await db.execute(
|
||||||
|
text("DELETE FROM project_assignments WHERE user_id IN (SELECT id FROM pm_users WHERE username = :uname)"),
|
||||||
|
{"uname": user.username}
|
||||||
|
)
|
||||||
await db.flush()
|
await db.flush()
|
||||||
return {"data": user_to_dict(user)}
|
return {"data": await user_to_dict(user)}
|
||||||
|
|
||||||
project = await db.get(Project, payload.project_id)
|
project = await db.get(Project, payload.project_id)
|
||||||
if project is None:
|
if project is None:
|
||||||
raise NotFoundError("پروژه یافت نشد", field="project_id")
|
raise NotFoundError("پروژه یافت نشد", field="project_id")
|
||||||
project.pm_user_id = user.id
|
project.pm_user_id = user.id
|
||||||
|
if user.username:
|
||||||
|
await db.execute(
|
||||||
|
text("""
|
||||||
|
INSERT INTO project_assignments (id, user_id, project_id)
|
||||||
|
SELECT gen_random_uuid(), pu.id, :pid
|
||||||
|
FROM pm_users pu
|
||||||
|
WHERE pu.username = :uname
|
||||||
|
AND NOT EXISTS (
|
||||||
|
SELECT 1 FROM project_assignments pa
|
||||||
|
WHERE pa.user_id = pu.id AND pa.project_id = :pid
|
||||||
|
)
|
||||||
|
"""),
|
||||||
|
{"pid": project.id, "uname": user.username}
|
||||||
|
)
|
||||||
await db.flush()
|
await db.flush()
|
||||||
return {"data": user_to_dict(user, await _user_projects(db, user))}
|
return {"data": await user_to_dict(user, await _user_projects(db, user))}
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# پنلها و سطوح دسترسی — جایگزین مدل نقش برای کاربران عادی
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/{user_id}/panels")
|
||||||
|
@router.patch("/{user_id}/panels")
|
||||||
|
async def set_user_panels(
|
||||||
|
user_id,
|
||||||
|
payload: UserPanelsUpdate,
|
||||||
|
_: UserContext = Depends(_org_manager),
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
):
|
||||||
|
"""تخصیص پنل + سطح دسترسی به کاربر — مدیران سازمان (ادمین، مدیر تدارکات، مدیر پروژه)."""
|
||||||
|
user = await db.get(User, user_id)
|
||||||
|
if user is None:
|
||||||
|
raise NotFoundError("کاربر یافت نشد")
|
||||||
|
for panel, level in payload.panels.items():
|
||||||
|
if panel not in PANELS:
|
||||||
|
raise ValidationError(f"پنل نامعتبر: {panel}", field="panels")
|
||||||
|
if level not in PANEL_LEVELS:
|
||||||
|
raise ValidationError(f"سطح دسترسی نامعتبر: {level}", field="panels")
|
||||||
|
await db.execute(delete(UserPanel).where(UserPanel.user_id == user.id))
|
||||||
|
for panel, level in payload.panels.items():
|
||||||
|
db.add(UserPanel(user_id=user.id, panel=panel, level=level))
|
||||||
|
await db.flush()
|
||||||
|
return {"data": await user_to_dict(user, await _user_projects(db, user), db)}
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/{user_id}/panel-projects")
|
||||||
|
@router.patch("/{user_id}/panel-projects")
|
||||||
|
async def set_user_panel_projects(
|
||||||
|
user_id,
|
||||||
|
payload: UserPanelProjectsUpdate,
|
||||||
|
_: UserContext = Depends(_org_manager),
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
):
|
||||||
|
"""عضویت پروژهای کاربر (M:N) — محدوده دادهی سطح limited."""
|
||||||
|
user = await db.get(User, user_id)
|
||||||
|
if user is None:
|
||||||
|
raise NotFoundError("کاربر یافت نشد")
|
||||||
|
wanted = list(dict.fromkeys(payload.project_ids))
|
||||||
|
if wanted:
|
||||||
|
found = (
|
||||||
|
await db.execute(select(Project).where(Project.id.in_(wanted)))
|
||||||
|
).scalars().all()
|
||||||
|
found_ids = {p.id for p in found}
|
||||||
|
unknown = [str(pid) for pid in wanted if pid not in found_ids]
|
||||||
|
if unknown:
|
||||||
|
raise ValidationError(
|
||||||
|
"پروژه(های) نامعتبر: " + "، ".join(unknown), field="project_ids"
|
||||||
|
)
|
||||||
|
await db.execute(
|
||||||
|
delete(UserProjectMembership).where(UserProjectMembership.user_id == user.id)
|
||||||
|
)
|
||||||
|
for pid in wanted:
|
||||||
|
db.add(UserProjectMembership(user_id=user.id, project_id=pid))
|
||||||
|
await db.flush()
|
||||||
|
return {"data": await user_to_dict(user, await _user_projects(db, user), db)}
|
||||||
|
|||||||
@@ -64,6 +64,7 @@ class InventoryTransactionCreate(APIModel):
|
|||||||
unit_id: int | None = None
|
unit_id: int | None = None
|
||||||
specs: dict | None = None
|
specs: dict | None = None
|
||||||
note: str | None = None
|
note: str | None = None
|
||||||
|
delivered_to: str | None = None
|
||||||
transaction_date: datetime | None = None
|
transaction_date: datetime | None = None
|
||||||
|
|
||||||
@model_validator(mode="after")
|
@model_validator(mode="after")
|
||||||
|
|||||||
@@ -44,14 +44,19 @@ class SupplierMaterialCreate(APIModel):
|
|||||||
|
|
||||||
class ProjectCreate(APIModel):
|
class ProjectCreate(APIModel):
|
||||||
name: str = Field(min_length=1)
|
name: str = Field(min_length=1)
|
||||||
|
location: str | None = None
|
||||||
|
project_manager: str | None = None
|
||||||
description: str | None = None
|
description: str | None = None
|
||||||
start_date: date | None = None
|
start_date: date | None = None
|
||||||
|
|
||||||
|
|
||||||
class ProjectUpdate(APIModel):
|
class ProjectUpdate(APIModel):
|
||||||
name: str | None = Field(default=None, min_length=1)
|
name: str | None = Field(default=None, min_length=1)
|
||||||
|
location: str | None = None
|
||||||
|
project_manager: str | None = None
|
||||||
description: str | None = None
|
description: str | None = None
|
||||||
start_date: date | None = None
|
start_date: date | None = None
|
||||||
|
status: str | None = None
|
||||||
# PM assignment (1:N — one PM per project, a PM may own many projects).
|
# PM assignment (1:N — one PM per project, a PM may own many projects).
|
||||||
# Admin / procurement manager only; None unassigns this project's PM.
|
# Admin / procurement manager only; None unassigns this project's PM.
|
||||||
pm_user_id: UUID | None = None
|
pm_user_id: UUID | None = None
|
||||||
@@ -135,6 +140,11 @@ class AcceptTermsheetIn(APIModel):
|
|||||||
schedule_steps: list[ScheduleStepIn] = Field(min_length=1)
|
schedule_steps: list[ScheduleStepIn] = Field(min_length=1)
|
||||||
|
|
||||||
|
|
||||||
|
class ProjectAllocationIn(APIModel):
|
||||||
|
project_id: UUID
|
||||||
|
quantity: Decimal = Field(gt=0, description="Allocated quantity for this project")
|
||||||
|
|
||||||
|
|
||||||
class ItemDecisionIn(APIModel):
|
class ItemDecisionIn(APIModel):
|
||||||
line_item_id: UUID
|
line_item_id: UUID
|
||||||
status: Literal["chosen", "rejected"]
|
status: Literal["chosen", "rejected"]
|
||||||
@@ -142,6 +152,7 @@ class ItemDecisionIn(APIModel):
|
|||||||
adjusted_unit_price: Decimal | None = Field(default=None, gt=0)
|
adjusted_unit_price: Decimal | None = Field(default=None, gt=0)
|
||||||
adjusted_notes: str | None = None
|
adjusted_notes: str | None = None
|
||||||
project_id: UUID | None = Field(default=None, description="The ONE purchased project (v2.6 — required when the offer spans several projects)")
|
project_id: UUID | None = Field(default=None, description="The ONE purchased project (v2.6 — required when the offer spans several projects)")
|
||||||
|
allocations: list[ProjectAllocationIn] = Field(default_factory=list, description="Multi-project split allocations for this line item")
|
||||||
|
|
||||||
|
|
||||||
class ItemProjectsIn(APIModel):
|
class ItemProjectsIn(APIModel):
|
||||||
@@ -203,13 +214,13 @@ class UserCreate(APIModel):
|
|||||||
last_name: str = ""
|
last_name: str = ""
|
||||||
phone: str | None = None
|
phone: str | None = None
|
||||||
casdoor_id: str | None = None
|
casdoor_id: str | None = None
|
||||||
role: Literal["pm", "procurement_manager", "admin"] | None = None
|
role: Literal["pm", "procurement_manager", "admin", "supervisor"] | None = None
|
||||||
|
|
||||||
|
|
||||||
class UserRoleUpdate(APIModel):
|
class UserRoleUpdate(APIModel):
|
||||||
"""role=None revokes the role (and any project assignment)."""
|
"""role=None revokes the role (and any project assignment)."""
|
||||||
|
|
||||||
role: Literal["pm", "procurement_manager", "admin"] | None = None
|
role: Literal["pm", "procurement_manager", "admin", "supervisor"] | None = None
|
||||||
|
|
||||||
|
|
||||||
class UserProjectUpdate(APIModel):
|
class UserProjectUpdate(APIModel):
|
||||||
@@ -341,3 +352,16 @@ class ReceiptUpdate(APIModel):
|
|||||||
received_qty: Decimal | None = Field(default=None, gt=0)
|
received_qty: Decimal | None = Field(default=None, gt=0)
|
||||||
on_time: bool | None = None
|
on_time: bool | None = None
|
||||||
quality_note: str | None = None
|
quality_note: str | None = None
|
||||||
|
|
||||||
|
|
||||||
|
class UserPanelsUpdate(APIModel):
|
||||||
|
"""Replace the user's panel assignments. هر پنل: 'full' | 'limited' —
|
||||||
|
پنل غایب یعنی تخصیص نداشتن و کلید آن حذف میشود."""
|
||||||
|
|
||||||
|
panels: dict[str, str] = Field(default_factory=dict)
|
||||||
|
|
||||||
|
|
||||||
|
class UserPanelProjectsUpdate(APIModel):
|
||||||
|
"""Replace the user's project memberships (M:N — جدا از مسئولیت پروژه)."""
|
||||||
|
|
||||||
|
project_ids: list[UUID] = Field(default_factory=list)
|
||||||
|
|||||||
@@ -0,0 +1,74 @@
|
|||||||
|
from datetime import datetime
|
||||||
|
from decimal import Decimal
|
||||||
|
from uuid import UUID
|
||||||
|
|
||||||
|
from pydantic import Field
|
||||||
|
|
||||||
|
from app.schemas.common import APIModel
|
||||||
|
|
||||||
|
|
||||||
|
class WarehouseAllocationIn(APIModel):
|
||||||
|
warehouse_id: UUID
|
||||||
|
quantity: Decimal = Field(gt=0)
|
||||||
|
|
||||||
|
|
||||||
|
class ProjectTransferCreate(APIModel):
|
||||||
|
from_warehouse_id: UUID
|
||||||
|
to_project_id: UUID
|
||||||
|
material_id: UUID
|
||||||
|
brand_id: UUID | None = None
|
||||||
|
unit_id: int
|
||||||
|
quantity: Decimal = Field(gt=0)
|
||||||
|
specs: dict = Field(default_factory=dict)
|
||||||
|
note: str | None = None
|
||||||
|
transfer_date: datetime | None = None
|
||||||
|
|
||||||
|
|
||||||
|
class ProjectTransferUpdate(APIModel):
|
||||||
|
to_project_id: UUID | None = None
|
||||||
|
quantity: Decimal | None = Field(default=None, gt=0)
|
||||||
|
note: str | None = None
|
||||||
|
transfer_date: datetime | None = None
|
||||||
|
|
||||||
|
|
||||||
|
class ProjectTransferReceive(APIModel):
|
||||||
|
allocations: list[WarehouseAllocationIn] = Field(
|
||||||
|
min_length=1,
|
||||||
|
description="Warehouse allocations in destination project (sum must equal transfer quantity)",
|
||||||
|
)
|
||||||
|
received_at: datetime | None = None
|
||||||
|
note: str | None = None
|
||||||
|
|
||||||
|
|
||||||
|
class IdNameOut(APIModel):
|
||||||
|
id: UUID
|
||||||
|
name: str
|
||||||
|
|
||||||
|
|
||||||
|
class UnitBriefOut(APIModel):
|
||||||
|
id: int
|
||||||
|
code: str
|
||||||
|
name_fa: str | None = None
|
||||||
|
|
||||||
|
|
||||||
|
class ProjectTransferOut(APIModel):
|
||||||
|
id: UUID
|
||||||
|
from_project: IdNameOut
|
||||||
|
from_warehouse: IdNameOut
|
||||||
|
to_project: IdNameOut
|
||||||
|
to_warehouse: IdNameOut | None = None
|
||||||
|
material: IdNameOut
|
||||||
|
brand: IdNameOut | None = None
|
||||||
|
unit: UnitBriefOut
|
||||||
|
quantity: Decimal
|
||||||
|
specs: dict
|
||||||
|
specs_hash: str
|
||||||
|
note: str | None = None
|
||||||
|
status: str
|
||||||
|
transfer_date: datetime
|
||||||
|
transferred_by: str | None = None
|
||||||
|
received_at: datetime | None = None
|
||||||
|
received_by: str | None = None
|
||||||
|
receipt_allocations: list[dict] | None = None
|
||||||
|
created_at: datetime
|
||||||
|
updated_at: datetime
|
||||||
@@ -22,6 +22,7 @@ SHA256 of the sorted canonical specs JSON (or 'default' when empty).
|
|||||||
import hashlib
|
import hashlib
|
||||||
import json
|
import json
|
||||||
import uuid
|
import uuid
|
||||||
|
from datetime import datetime, timezone, timedelta
|
||||||
from decimal import Decimal
|
from decimal import Decimal
|
||||||
|
|
||||||
from sqlalchemy import select
|
from sqlalchemy import select
|
||||||
@@ -175,6 +176,11 @@ async def apply_transaction(
|
|||||||
t = payload.transaction_type
|
t = payload.transaction_type
|
||||||
specs = payload.specs or {}
|
specs = payload.specs or {}
|
||||||
specs_hash = canonical_specs_hash(specs)
|
specs_hash = canonical_specs_hash(specs)
|
||||||
|
tx_date = payload.transaction_date or datetime.now(timezone.utc)
|
||||||
|
# جلوگیری از ثبت تاریخ در آینده
|
||||||
|
now_utc = datetime.now(timezone.utc)
|
||||||
|
if tx_date > now_utc + timedelta(minutes=5):
|
||||||
|
raise ValidationError("امکان ثبت تاریخ یا زمان در آینده وجود ندارد", field="transaction_date")
|
||||||
|
|
||||||
# STOCK_COUNT: apply the difference between counted and recorded quantity.
|
# STOCK_COUNT: apply the difference between counted and recorded quantity.
|
||||||
if t == "STOCK_COUNT":
|
if t == "STOCK_COUNT":
|
||||||
@@ -197,7 +203,7 @@ async def apply_transaction(
|
|||||||
recorded_qty=recorded,
|
recorded_qty=recorded,
|
||||||
physical_qty=payload.physical_qty,
|
physical_qty=payload.physical_qty,
|
||||||
performed_by=performed_by,
|
performed_by=performed_by,
|
||||||
transaction_date=payload.transaction_date,
|
transaction_date=tx_date,
|
||||||
note=payload.note,
|
note=payload.note,
|
||||||
)
|
)
|
||||||
db.add(tx)
|
db.add(tx)
|
||||||
@@ -238,7 +244,7 @@ async def apply_transaction(
|
|||||||
quantity=-quantity,
|
quantity=-quantity,
|
||||||
transfer_pair_id=pair_id,
|
transfer_pair_id=pair_id,
|
||||||
performed_by=performed_by,
|
performed_by=performed_by,
|
||||||
transaction_date=payload.transaction_date,
|
transaction_date=tx_date,
|
||||||
note=payload.note,
|
note=payload.note,
|
||||||
)
|
)
|
||||||
db.add(out_tx)
|
db.add(out_tx)
|
||||||
@@ -256,7 +262,7 @@ async def apply_transaction(
|
|||||||
quantity=quantity,
|
quantity=quantity,
|
||||||
transfer_pair_id=pair_id,
|
transfer_pair_id=pair_id,
|
||||||
performed_by=performed_by,
|
performed_by=performed_by,
|
||||||
transaction_date=payload.transaction_date,
|
transaction_date=tx_date,
|
||||||
note=payload.note,
|
note=payload.note,
|
||||||
)
|
)
|
||||||
db.add(in_tx)
|
db.add(in_tx)
|
||||||
@@ -290,7 +296,8 @@ async def apply_transaction(
|
|||||||
transaction_type=t,
|
transaction_type=t,
|
||||||
quantity=quantity,
|
quantity=quantity,
|
||||||
performed_by=performed_by,
|
performed_by=performed_by,
|
||||||
transaction_date=payload.transaction_date,
|
delivered_to=payload.delivered_to,
|
||||||
|
transaction_date=tx_date,
|
||||||
note=payload.note,
|
note=payload.note,
|
||||||
)
|
)
|
||||||
db.add(tx)
|
db.add(tx)
|
||||||
@@ -319,7 +326,8 @@ async def apply_transaction(
|
|||||||
transaction_type=t,
|
transaction_type=t,
|
||||||
quantity=-quantity,
|
quantity=-quantity,
|
||||||
performed_by=performed_by,
|
performed_by=performed_by,
|
||||||
transaction_date=payload.transaction_date,
|
delivered_to=payload.delivered_to,
|
||||||
|
transaction_date=tx_date,
|
||||||
note=payload.note,
|
note=payload.note,
|
||||||
)
|
)
|
||||||
db.add(tx)
|
db.add(tx)
|
||||||
|
|||||||
@@ -0,0 +1,471 @@
|
|||||||
|
import uuid
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
from decimal import Decimal
|
||||||
|
|
||||||
|
from sqlalchemy import delete, select
|
||||||
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
from sqlalchemy.orm import selectinload
|
||||||
|
|
||||||
|
from app.models.catalog import Brand, Material, Unit
|
||||||
|
from app.models.inventory import InventoryItem, InventoryTransaction, Warehouse
|
||||||
|
from app.models.procurement import Project
|
||||||
|
from app.models.project_transfer import ProjectTransfer
|
||||||
|
from app.schemas.project_transfers import (
|
||||||
|
ProjectTransferCreate,
|
||||||
|
ProjectTransferReceive,
|
||||||
|
ProjectTransferUpdate,
|
||||||
|
)
|
||||||
|
from app.services.inventory_service import (
|
||||||
|
_find_inventory,
|
||||||
|
_get_or_create_inventory,
|
||||||
|
canonical_specs_hash,
|
||||||
|
)
|
||||||
|
from app.utils.errors import ConflictError, ForbiddenError, NotFoundError, ValidationError
|
||||||
|
|
||||||
|
|
||||||
|
async def get_project_transfer_or_404(db: AsyncSession, transfer_id: uuid.UUID) -> ProjectTransfer:
|
||||||
|
stmt = (
|
||||||
|
select(ProjectTransfer)
|
||||||
|
.where(ProjectTransfer.id == transfer_id)
|
||||||
|
.options(
|
||||||
|
selectinload(ProjectTransfer.from_project),
|
||||||
|
selectinload(ProjectTransfer.to_project),
|
||||||
|
selectinload(ProjectTransfer.from_warehouse),
|
||||||
|
selectinload(ProjectTransfer.to_warehouse),
|
||||||
|
selectinload(ProjectTransfer.material),
|
||||||
|
selectinload(ProjectTransfer.brand),
|
||||||
|
selectinload(ProjectTransfer.unit),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
transfer = await db.scalar(stmt)
|
||||||
|
if transfer is None:
|
||||||
|
raise NotFoundError("رکورد انتقال بین کارگاهی یافت نشد", field="transfer_id")
|
||||||
|
return transfer
|
||||||
|
|
||||||
|
|
||||||
|
async def create_project_transfer(
|
||||||
|
db: AsyncSession,
|
||||||
|
payload: ProjectTransferCreate,
|
||||||
|
caller_project_id: uuid.UUID | None,
|
||||||
|
caller_role: str,
|
||||||
|
transferred_by: str | None = None,
|
||||||
|
) -> ProjectTransfer:
|
||||||
|
tx = db.begin_nested() if db.in_transaction() else db.begin()
|
||||||
|
async with tx:
|
||||||
|
# Validate source warehouse
|
||||||
|
from_wh = await db.get(Warehouse, payload.from_warehouse_id)
|
||||||
|
if from_wh is None:
|
||||||
|
raise NotFoundError("انبار مبدأ یافت نشد", field="from_warehouse_id")
|
||||||
|
|
||||||
|
# RBAC: PM can only send from their own project
|
||||||
|
if caller_role == "pm" and caller_project_id is not None:
|
||||||
|
if from_wh.project_id != caller_project_id:
|
||||||
|
raise ForbiddenError("شما فقط مجاز به انتقال از انبار پروژه خود هستید")
|
||||||
|
|
||||||
|
from_proj = await db.get(Project, from_wh.project_id)
|
||||||
|
to_proj = await db.get(Project, payload.to_project_id)
|
||||||
|
if to_proj is None:
|
||||||
|
raise NotFoundError("پروژه مقصد یافت نشد", field="to_project_id")
|
||||||
|
|
||||||
|
if from_wh.project_id == payload.to_project_id:
|
||||||
|
raise ValidationError(
|
||||||
|
"پروژه مقصد نمیتواند همان پروژه مبدأ باشد (از انتقال بینانباری استفاده کنید)",
|
||||||
|
field="to_project_id",
|
||||||
|
)
|
||||||
|
|
||||||
|
# Validate material, brand, unit
|
||||||
|
mat = await db.get(Material, payload.material_id)
|
||||||
|
if mat is None:
|
||||||
|
raise NotFoundError("ماده اولیه یافت نشد", field="material_id")
|
||||||
|
|
||||||
|
if payload.brand_id is not None:
|
||||||
|
brand = await db.get(Brand, payload.brand_id)
|
||||||
|
if brand is None:
|
||||||
|
raise NotFoundError("برند یافت نشد", field="brand_id")
|
||||||
|
|
||||||
|
unit = await db.get(Unit, payload.unit_id)
|
||||||
|
if unit is None:
|
||||||
|
raise NotFoundError("واحد یافت نشد", field="unit_id")
|
||||||
|
|
||||||
|
# Requirement 2: Canonical specs hash from inventory_service
|
||||||
|
specs = payload.specs or {}
|
||||||
|
specs_hash = canonical_specs_hash(specs)
|
||||||
|
|
||||||
|
# Check stock in source warehouse with SELECT ... FOR UPDATE
|
||||||
|
source_item = await _find_inventory(
|
||||||
|
db,
|
||||||
|
payload.from_warehouse_id,
|
||||||
|
payload.material_id,
|
||||||
|
payload.brand_id,
|
||||||
|
specs_hash,
|
||||||
|
for_update=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Smart fallback: If exact hash or brand didn't match, check candidate rows in this warehouse for this material
|
||||||
|
if source_item is None:
|
||||||
|
candidates_res = await db.execute(
|
||||||
|
select(InventoryItem)
|
||||||
|
.where(
|
||||||
|
InventoryItem.warehouse_id == payload.from_warehouse_id,
|
||||||
|
InventoryItem.material_id == payload.material_id,
|
||||||
|
)
|
||||||
|
.with_for_update()
|
||||||
|
)
|
||||||
|
candidates = candidates_res.scalars().all()
|
||||||
|
|
||||||
|
if len(candidates) == 1:
|
||||||
|
source_item = candidates[0]
|
||||||
|
elif len(candidates) > 1:
|
||||||
|
best_cand = None
|
||||||
|
best_score = -1
|
||||||
|
p_keys = set(specs.keys())
|
||||||
|
p_vals = set(str(v).strip() for v in specs.values() if str(v).strip())
|
||||||
|
|
||||||
|
for cand in candidates:
|
||||||
|
score = 0
|
||||||
|
if cand.brand_id == payload.brand_id:
|
||||||
|
score += 10
|
||||||
|
elif cand.brand_id is None and payload.brand_id is None:
|
||||||
|
score += 10
|
||||||
|
elif cand.brand_id is None:
|
||||||
|
score += 4
|
||||||
|
|
||||||
|
c_specs = cand.specs or {}
|
||||||
|
c_keys = set(c_specs.keys())
|
||||||
|
c_vals = set(str(v).strip() for v in c_specs.values() if str(v).strip())
|
||||||
|
|
||||||
|
for pk in p_keys:
|
||||||
|
if pk in c_keys or f"spec_{pk}" in c_keys or any(pk in ck for ck in c_keys):
|
||||||
|
score += 5
|
||||||
|
for pv in p_vals:
|
||||||
|
if pv in c_vals or any(pv in str(cv) for cv in c_vals):
|
||||||
|
score += 5
|
||||||
|
|
||||||
|
if cand.quantity >= payload.quantity:
|
||||||
|
score += 2
|
||||||
|
|
||||||
|
if score > best_score:
|
||||||
|
best_score = score
|
||||||
|
best_cand = cand
|
||||||
|
|
||||||
|
source_item = best_cand
|
||||||
|
|
||||||
|
if source_item is None or source_item.quantity < payload.quantity:
|
||||||
|
avail = source_item.quantity if source_item else Decimal("0")
|
||||||
|
raise ValidationError(
|
||||||
|
f"موجودی کافی در انبار مبدأ وجود ندارد (موجودی فعلی: {avail})",
|
||||||
|
field="quantity",
|
||||||
|
)
|
||||||
|
|
||||||
|
# Deduct from source warehouse immediately
|
||||||
|
source_item.quantity -= payload.quantity
|
||||||
|
|
||||||
|
transfer_pair_id = uuid.uuid4()
|
||||||
|
now_dt = payload.transfer_date or datetime.now(timezone.utc)
|
||||||
|
note_text = f"انتقال بین کارگاهی به پروژه {to_proj.name}"
|
||||||
|
if payload.note:
|
||||||
|
note_text += f" — {payload.note}"
|
||||||
|
|
||||||
|
out_tx = InventoryTransaction(
|
||||||
|
inventory_id=source_item.id,
|
||||||
|
warehouse_id=from_wh.id,
|
||||||
|
transaction_type="TRANSFER_OUT",
|
||||||
|
quantity=-payload.quantity,
|
||||||
|
transfer_pair_id=transfer_pair_id,
|
||||||
|
performed_by=transferred_by,
|
||||||
|
transaction_date=now_dt,
|
||||||
|
note=note_text,
|
||||||
|
)
|
||||||
|
db.add(out_tx)
|
||||||
|
await db.flush()
|
||||||
|
|
||||||
|
actual_brand_id = source_item.brand_id
|
||||||
|
actual_specs = source_item.specs if source_item.specs is not None else specs
|
||||||
|
actual_specs_hash = source_item.specs_hash or canonical_specs_hash(actual_specs)
|
||||||
|
|
||||||
|
transfer = ProjectTransfer(
|
||||||
|
from_project_id=from_wh.project_id,
|
||||||
|
from_warehouse_id=from_wh.id,
|
||||||
|
to_project_id=payload.to_project_id,
|
||||||
|
material_id=payload.material_id,
|
||||||
|
brand_id=actual_brand_id,
|
||||||
|
unit_id=source_item.unit_id if source_item.unit_id else payload.unit_id,
|
||||||
|
quantity=payload.quantity,
|
||||||
|
specs=actual_specs,
|
||||||
|
specs_hash=actual_specs_hash,
|
||||||
|
note=payload.note,
|
||||||
|
status="in_transit",
|
||||||
|
out_transaction_id=out_tx.id,
|
||||||
|
transfer_date=now_dt,
|
||||||
|
transferred_by=transferred_by,
|
||||||
|
)
|
||||||
|
db.add(transfer)
|
||||||
|
await db.flush()
|
||||||
|
|
||||||
|
return await get_project_transfer_or_404(db, transfer.id)
|
||||||
|
|
||||||
|
|
||||||
|
async def update_project_transfer(
|
||||||
|
db: AsyncSession,
|
||||||
|
transfer_id: uuid.UUID,
|
||||||
|
payload: ProjectTransferUpdate,
|
||||||
|
caller_project_id: uuid.UUID | None,
|
||||||
|
caller_role: str,
|
||||||
|
) -> ProjectTransfer:
|
||||||
|
tx = db.begin_nested() if db.in_transaction() else db.begin()
|
||||||
|
async with tx:
|
||||||
|
transfer = await db.scalar(
|
||||||
|
select(ProjectTransfer).where(ProjectTransfer.id == transfer_id).with_for_update()
|
||||||
|
)
|
||||||
|
if transfer is None:
|
||||||
|
raise NotFoundError("رکورد انتقال یافت نشد", field="transfer_id")
|
||||||
|
|
||||||
|
# RBAC (Requirement 4)
|
||||||
|
if caller_role == "pm" and caller_project_id is not None:
|
||||||
|
if transfer.from_project_id != caller_project_id:
|
||||||
|
raise ForbiddenError("شما فقط مجاز به ویرایش انتقالهای پروژه مبدأ خود هستید")
|
||||||
|
|
||||||
|
# Status Lock Guard (Requirement 4)
|
||||||
|
if transfer.status == "received":
|
||||||
|
raise ConflictError(
|
||||||
|
"این انتقال در پروژه مقصد تحویل و ثبت انبار شده است و امکان ویرایش آن وجود ندارد"
|
||||||
|
)
|
||||||
|
if transfer.status != "in_transit":
|
||||||
|
raise ConflictError("فقط انتقالهای در راه (in_transit) قابل ویرایش هستند")
|
||||||
|
|
||||||
|
if payload.to_project_id is not None and payload.to_project_id != transfer.to_project_id:
|
||||||
|
new_to_proj = await db.get(Project, payload.to_project_id)
|
||||||
|
if new_to_proj is None:
|
||||||
|
raise NotFoundError("پروژه مقصد یافت نشد", field="to_project_id")
|
||||||
|
if payload.to_project_id == transfer.from_project_id:
|
||||||
|
raise ValidationError("پروژه مقصد نمیتواند همان پروژه مبدأ باشد", field="to_project_id")
|
||||||
|
transfer.to_project_id = payload.to_project_id
|
||||||
|
|
||||||
|
# Quantity adjustment (reconciles source stock difference)
|
||||||
|
if payload.quantity is not None and payload.quantity != transfer.quantity:
|
||||||
|
delta = payload.quantity - transfer.quantity
|
||||||
|
source_item = await _find_inventory(
|
||||||
|
db,
|
||||||
|
transfer.from_warehouse_id,
|
||||||
|
transfer.material_id,
|
||||||
|
transfer.brand_id,
|
||||||
|
transfer.specs_hash,
|
||||||
|
for_update=True,
|
||||||
|
)
|
||||||
|
if delta > 0:
|
||||||
|
if source_item is None or source_item.quantity < delta:
|
||||||
|
avail = source_item.quantity if source_item else Decimal("0")
|
||||||
|
raise ValidationError(
|
||||||
|
f"موجودی انبار مبدأ برای افزایش انتقال کافی نیست (موجود: {avail})",
|
||||||
|
field="quantity",
|
||||||
|
)
|
||||||
|
source_item.quantity -= delta
|
||||||
|
else:
|
||||||
|
if source_item is not None:
|
||||||
|
source_item.quantity += abs(delta)
|
||||||
|
|
||||||
|
transfer.quantity = payload.quantity
|
||||||
|
|
||||||
|
# Update out_transaction
|
||||||
|
if transfer.out_transaction_id is not None:
|
||||||
|
out_tx = await db.get(InventoryTransaction, transfer.out_transaction_id)
|
||||||
|
if out_tx is not None:
|
||||||
|
out_tx.quantity = -payload.quantity
|
||||||
|
|
||||||
|
if payload.note is not None:
|
||||||
|
transfer.note = payload.note
|
||||||
|
|
||||||
|
if payload.transfer_date is not None:
|
||||||
|
transfer.transfer_date = payload.transfer_date
|
||||||
|
if transfer.out_transaction_id is not None:
|
||||||
|
out_tx = await db.get(InventoryTransaction, transfer.out_transaction_id)
|
||||||
|
if out_tx is not None:
|
||||||
|
out_tx.transaction_date = payload.transfer_date
|
||||||
|
|
||||||
|
return await get_project_transfer_or_404(db, transfer_id)
|
||||||
|
|
||||||
|
|
||||||
|
async def delete_project_transfer(
|
||||||
|
db: AsyncSession,
|
||||||
|
transfer_id: uuid.UUID,
|
||||||
|
caller_project_id: uuid.UUID | None,
|
||||||
|
caller_role: str,
|
||||||
|
) -> dict:
|
||||||
|
tx = db.begin_nested() if db.in_transaction() else db.begin()
|
||||||
|
async with tx:
|
||||||
|
transfer = await db.scalar(
|
||||||
|
select(ProjectTransfer).where(ProjectTransfer.id == transfer_id).with_for_update()
|
||||||
|
)
|
||||||
|
if transfer is None:
|
||||||
|
raise NotFoundError("رکورد انتقال یافت نشد", field="transfer_id")
|
||||||
|
|
||||||
|
# RBAC (Requirement 4)
|
||||||
|
if caller_role == "pm" and caller_project_id is not None:
|
||||||
|
if transfer.from_project_id != caller_project_id:
|
||||||
|
raise ForbiddenError("شما فقط مجاز به لغو انتقالهای پروژه مبدأ خود هستید")
|
||||||
|
|
||||||
|
# Status Lock Guard (Requirement 4)
|
||||||
|
if transfer.status == "received":
|
||||||
|
raise ConflictError(
|
||||||
|
"این انتقال در پروژه مقصد تحویل و ثبت انبار شده است و امکان لغو یا حذف آن وجود ندارد"
|
||||||
|
)
|
||||||
|
|
||||||
|
# Reversibility (Requirement 4): Restore stock to source warehouse
|
||||||
|
source_item = await _find_inventory(
|
||||||
|
db,
|
||||||
|
transfer.from_warehouse_id,
|
||||||
|
transfer.material_id,
|
||||||
|
transfer.brand_id,
|
||||||
|
transfer.specs_hash,
|
||||||
|
for_update=True,
|
||||||
|
)
|
||||||
|
if source_item is not None:
|
||||||
|
source_item.quantity += transfer.quantity
|
||||||
|
|
||||||
|
# Delete out_transaction
|
||||||
|
if transfer.out_transaction_id is not None:
|
||||||
|
out_tx = await db.get(InventoryTransaction, transfer.out_transaction_id)
|
||||||
|
if out_tx is not None:
|
||||||
|
await db.delete(out_tx)
|
||||||
|
|
||||||
|
await db.delete(transfer)
|
||||||
|
|
||||||
|
return {"ok": True, "message": "انتقال با موفقیت لغو شد و موجودی به انبار مبدأ بازگردانده شد"}
|
||||||
|
|
||||||
|
|
||||||
|
async def receive_project_transfer(
|
||||||
|
db: AsyncSession,
|
||||||
|
transfer_id: uuid.UUID,
|
||||||
|
payload: ProjectTransferReceive,
|
||||||
|
caller_project_id: uuid.UUID | None,
|
||||||
|
caller_role: str,
|
||||||
|
received_by: str | None = None,
|
||||||
|
) -> ProjectTransfer:
|
||||||
|
tx = db.begin_nested() if db.in_transaction() else db.begin()
|
||||||
|
async with tx:
|
||||||
|
transfer = await db.scalar(
|
||||||
|
select(ProjectTransfer).where(ProjectTransfer.id == transfer_id).with_for_update()
|
||||||
|
)
|
||||||
|
if transfer is None:
|
||||||
|
raise NotFoundError("رکورد انتقال یافت نشد", field="transfer_id")
|
||||||
|
|
||||||
|
# RBAC (Requirement 4)
|
||||||
|
if caller_role == "pm" and caller_project_id is not None:
|
||||||
|
if transfer.to_project_id != caller_project_id:
|
||||||
|
raise ForbiddenError("شما فقط مجاز به تأیید تحویل در پروژه مقصد خود هستید")
|
||||||
|
|
||||||
|
# Lock Guard
|
||||||
|
if transfer.status == "received":
|
||||||
|
raise ConflictError("این انتقال قبلاً تحویل گرفته و ثبت انبار شده است")
|
||||||
|
if transfer.status != "in_transit":
|
||||||
|
raise ConflictError("این انتقال در وضعیت در راه نیست")
|
||||||
|
|
||||||
|
# Requirement 1: 100% full delivery logic (no partial receipt)
|
||||||
|
alloc_sum = sum(Decimal(str(a.quantity)) for a in payload.allocations)
|
||||||
|
if alloc_sum != transfer.quantity:
|
||||||
|
raise ValidationError(
|
||||||
|
f"تخصیص انبارها باید دقیقاً برابر کل مقدار ارسالی ({transfer.quantity}) باشد. مجموع واردشده: {alloc_sum}",
|
||||||
|
field="allocations",
|
||||||
|
)
|
||||||
|
|
||||||
|
# Validate destination warehouses belong to destination project
|
||||||
|
wh_ids = [a.warehouse_id for a in payload.allocations]
|
||||||
|
wh_rows = (await db.execute(select(Warehouse).where(Warehouse.id.in_(wh_ids)))).scalars().all()
|
||||||
|
wh_map = {w.id: w for w in wh_rows}
|
||||||
|
|
||||||
|
for a in payload.allocations:
|
||||||
|
wh = wh_map.get(a.warehouse_id)
|
||||||
|
if wh is None or wh.project_id != transfer.to_project_id:
|
||||||
|
raise ValidationError(
|
||||||
|
"انبار انتخابشده معتبر نیست یا متعلق به پروژه مقصد نمیباشد",
|
||||||
|
field="allocations.warehouse_id",
|
||||||
|
)
|
||||||
|
|
||||||
|
from_proj = await db.get(Project, transfer.from_project_id)
|
||||||
|
from_proj_name = from_proj.name if from_proj else "پروژه مبدأ"
|
||||||
|
|
||||||
|
out_tx = (
|
||||||
|
await db.get(InventoryTransaction, transfer.out_transaction_id)
|
||||||
|
if transfer.out_transaction_id
|
||||||
|
else None
|
||||||
|
)
|
||||||
|
pair_id = out_tx.transfer_pair_id if (out_tx and out_tx.transfer_pair_id) else uuid.uuid4()
|
||||||
|
now_dt = payload.received_at or datetime.now(timezone.utc)
|
||||||
|
|
||||||
|
# Add stock to destination warehouse(s) via TRANSFER_IN
|
||||||
|
for a in payload.allocations:
|
||||||
|
dest_item = await _get_or_create_inventory(
|
||||||
|
db,
|
||||||
|
a.warehouse_id,
|
||||||
|
transfer.material_id,
|
||||||
|
transfer.brand_id,
|
||||||
|
transfer.unit_id,
|
||||||
|
transfer.specs,
|
||||||
|
transfer.specs_hash,
|
||||||
|
)
|
||||||
|
dest_item.quantity += a.quantity
|
||||||
|
|
||||||
|
note_text = f"رسید انتقال بین کارگاهی از {from_proj_name}"
|
||||||
|
if payload.note:
|
||||||
|
note_text += f" — {payload.note}"
|
||||||
|
|
||||||
|
in_tx = InventoryTransaction(
|
||||||
|
inventory_id=dest_item.id,
|
||||||
|
warehouse_id=a.warehouse_id,
|
||||||
|
transaction_type="TRANSFER_IN",
|
||||||
|
quantity=a.quantity,
|
||||||
|
transfer_pair_id=pair_id,
|
||||||
|
performed_by=received_by,
|
||||||
|
transaction_date=now_dt,
|
||||||
|
note=note_text,
|
||||||
|
)
|
||||||
|
db.add(in_tx)
|
||||||
|
|
||||||
|
transfer.status = "received"
|
||||||
|
transfer.received_at = now_dt
|
||||||
|
transfer.received_by = received_by
|
||||||
|
transfer.to_warehouse_id = payload.allocations[0].warehouse_id
|
||||||
|
transfer.receipt_allocations = [
|
||||||
|
{"warehouse_id": str(a.warehouse_id), "quantity": str(a.quantity)}
|
||||||
|
for a in payload.allocations
|
||||||
|
]
|
||||||
|
|
||||||
|
return await get_project_transfer_or_404(db, transfer_id)
|
||||||
|
|
||||||
|
|
||||||
|
async def list_project_transfers(
|
||||||
|
db: AsyncSession,
|
||||||
|
project_id: uuid.UUID | None = None,
|
||||||
|
direction: str = "all", # 'outgoing' | 'incoming' | 'all'
|
||||||
|
status: str | None = None,
|
||||||
|
) -> list[ProjectTransfer]:
|
||||||
|
stmt = (
|
||||||
|
select(ProjectTransfer)
|
||||||
|
.options(
|
||||||
|
selectinload(ProjectTransfer.from_project),
|
||||||
|
selectinload(ProjectTransfer.to_project),
|
||||||
|
selectinload(ProjectTransfer.from_warehouse),
|
||||||
|
selectinload(ProjectTransfer.to_warehouse),
|
||||||
|
selectinload(ProjectTransfer.material),
|
||||||
|
selectinload(ProjectTransfer.brand),
|
||||||
|
selectinload(ProjectTransfer.unit),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
if project_id is not None:
|
||||||
|
if direction == "outgoing":
|
||||||
|
stmt = stmt.where(ProjectTransfer.from_project_id == project_id)
|
||||||
|
elif direction == "incoming":
|
||||||
|
stmt = stmt.where(ProjectTransfer.to_project_id == project_id)
|
||||||
|
else:
|
||||||
|
stmt = stmt.where(
|
||||||
|
(ProjectTransfer.from_project_id == project_id)
|
||||||
|
| (ProjectTransfer.to_project_id == project_id)
|
||||||
|
)
|
||||||
|
|
||||||
|
if status:
|
||||||
|
stmt = stmt.where(ProjectTransfer.status == status)
|
||||||
|
|
||||||
|
stmt = stmt.order_by(ProjectTransfer.transfer_date.desc())
|
||||||
|
res = await db.execute(stmt)
|
||||||
|
return list(res.scalars().all())
|
||||||
@@ -7,6 +7,7 @@ same transaction.
|
|||||||
import asyncio
|
import asyncio
|
||||||
import logging
|
import logging
|
||||||
from datetime import date, datetime, timezone
|
from datetime import date, datetime, timezone
|
||||||
|
from decimal import Decimal
|
||||||
from uuid import UUID
|
from uuid import UUID
|
||||||
|
|
||||||
from sqlalchemy import delete, func, select, update
|
from sqlalchemy import delete, func, select, update
|
||||||
@@ -18,6 +19,7 @@ from app.models.procurement import (
|
|||||||
ItemTermsheet,
|
ItemTermsheet,
|
||||||
LineItem,
|
LineItem,
|
||||||
LineItemProjects,
|
LineItemProjects,
|
||||||
|
LineItemSpec,
|
||||||
Project,
|
Project,
|
||||||
Quote,
|
Quote,
|
||||||
QuoteEvent,
|
QuoteEvent,
|
||||||
@@ -418,6 +420,78 @@ async def replace_quote_children(
|
|||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
async def _ensure_quote_project(db: AsyncSession, quote_id: UUID, project_id: UUID) -> None:
|
||||||
|
"""Ensure (quote_id, project_id) exists in quote_projects junction."""
|
||||||
|
exists = await db.scalar(
|
||||||
|
select(QuoteProjects).where(
|
||||||
|
QuoteProjects.quote_id == quote_id,
|
||||||
|
QuoteProjects.project_id == project_id,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
if not exists:
|
||||||
|
db.add(QuoteProjects(quote_id=quote_id, project_id=project_id))
|
||||||
|
|
||||||
|
|
||||||
|
async def _merge_split_line_items_on_reopen(db: AsyncSession, quote_id: UUID) -> None:
|
||||||
|
"""Consolidate split line items when reverting a quote back to offered.
|
||||||
|
|
||||||
|
Line items sharing the exact same material, brand_material, unit, notes,
|
||||||
|
and identical specs are merged into a single consolidated row whose quantity
|
||||||
|
is the sum of all split rows. Secondary split rows are safely deleted.
|
||||||
|
"""
|
||||||
|
line_items = (
|
||||||
|
await db.execute(
|
||||||
|
select(LineItem).where(LineItem.quote_id == quote_id).order_by(LineItem.created_at.asc(), LineItem.id.asc())
|
||||||
|
)
|
||||||
|
).scalars().all()
|
||||||
|
if len(line_items) <= 1:
|
||||||
|
return
|
||||||
|
|
||||||
|
# Load all specs for these line items to compare canonical signatures
|
||||||
|
specs_rows = (
|
||||||
|
await db.execute(
|
||||||
|
select(LineItemSpec).where(LineItemSpec.line_item_id.in_([li.id for li in line_items]))
|
||||||
|
)
|
||||||
|
).scalars().all()
|
||||||
|
specs_by_li: dict[UUID, list[tuple]] = {}
|
||||||
|
for sp in specs_rows:
|
||||||
|
sig = (
|
||||||
|
str(sp.attribute_definition_id),
|
||||||
|
str(sp.value_number) if sp.value_number is not None else "",
|
||||||
|
(sp.value_string or "").strip(),
|
||||||
|
str(sp.value_boolean) if sp.value_boolean is not None else "",
|
||||||
|
str(sp.value_date) if sp.value_date is not None else "",
|
||||||
|
)
|
||||||
|
specs_by_li.setdefault(sp.line_item_id, []).append(sig)
|
||||||
|
|
||||||
|
# Group line items by identity
|
||||||
|
groups: dict[tuple, list[LineItem]] = {}
|
||||||
|
for li in line_items:
|
||||||
|
specs_sig = tuple(sorted(specs_by_li.get(li.id, [])))
|
||||||
|
key = (
|
||||||
|
li.material_id,
|
||||||
|
li.brand_material_id,
|
||||||
|
li.unit_id,
|
||||||
|
(li.notes or "").strip(),
|
||||||
|
specs_sig,
|
||||||
|
)
|
||||||
|
groups.setdefault(key, []).append(li)
|
||||||
|
|
||||||
|
for key, items in groups.items():
|
||||||
|
if len(items) > 1:
|
||||||
|
primary = items[0]
|
||||||
|
total_qty = sum(Decimal(str(it.quantity)) for it in items)
|
||||||
|
primary.quantity = total_qty
|
||||||
|
|
||||||
|
secondary_ids = [it.id for it in items[1:]]
|
||||||
|
await db.execute(delete(ItemDecision).where(ItemDecision.line_item_id.in_(secondary_ids)))
|
||||||
|
await db.execute(delete(ItemTermsheet).where(ItemTermsheet.line_item_id.in_(secondary_ids)))
|
||||||
|
await db.execute(delete(LineItemProjects).where(LineItemProjects.line_item_id.in_(secondary_ids)))
|
||||||
|
await db.execute(delete(LineItemSpec).where(LineItemSpec.line_item_id.in_(secondary_ids)))
|
||||||
|
await db.execute(delete(LineItem).where(LineItem.id.in_(secondary_ids)))
|
||||||
|
await db.flush()
|
||||||
|
|
||||||
|
|
||||||
async def _apply_status_transition(db: AsyncSession, quote: Quote, new_status: str) -> None:
|
async def _apply_status_transition(db: AsyncSession, quote: Quote, new_status: str) -> None:
|
||||||
"""Backward transitions only; reverts bookkeeping when going back to offered."""
|
"""Backward transitions only; reverts bookkeeping when going back to offered."""
|
||||||
current = quote.status
|
current = quote.status
|
||||||
@@ -454,6 +528,8 @@ async def _apply_status_transition(db: AsyncSession, quote: Quote, new_status: s
|
|||||||
)
|
)
|
||||||
.execution_options(synchronize_session=False)
|
.execution_options(synchronize_session=False)
|
||||||
)
|
)
|
||||||
|
# Requirement 2: Merge split line items back into single rows
|
||||||
|
await _merge_split_line_items_on_reopen(db, quote.id)
|
||||||
# LineItemProjects (candidate projects) are preserved untouched!
|
# LineItemProjects (candidate projects) are preserved untouched!
|
||||||
elif new_status == "accepted": # arrived -> accepted
|
elif new_status == "accepted": # arrived -> accepted
|
||||||
quote.arrived_date = None
|
quote.arrived_date = None
|
||||||
@@ -557,6 +633,125 @@ async def accept_quote(db: AsyncSession, quote_id: UUID, payload: AcceptQuoteIn,
|
|||||||
"برای قلم انتخابشده adjusted_unit_price الزامی است", field="item_decisions"
|
"برای قلم انتخابشده adjusted_unit_price الزامی است", field="item_decisions"
|
||||||
)
|
)
|
||||||
termsheet_id = ts_ids_by_index[index]
|
termsheet_id = ts_ids_by_index[index]
|
||||||
|
|
||||||
|
li_row = await db.scalar(
|
||||||
|
select(LineItem).where(LineItem.id == decision_in.line_item_id).with_for_update()
|
||||||
|
)
|
||||||
|
if li_row is None:
|
||||||
|
raise NotFoundError("خط آیتم یافت نشد", field="item_decisions.line_item_id")
|
||||||
|
|
||||||
|
allocations = decision_in.allocations or []
|
||||||
|
if allocations:
|
||||||
|
# Requirement 3: Validate no duplicate projects within allocations of this item
|
||||||
|
alloc_pids = [a.project_id for a in allocations]
|
||||||
|
if len(alloc_pids) != len(set(alloc_pids)):
|
||||||
|
raise ValidationError(
|
||||||
|
"پروژه تکراری برای یک قلم کالا در ردیفهای تخصیص انتخاب شده است",
|
||||||
|
field="item_decisions.allocations",
|
||||||
|
)
|
||||||
|
# Requirement 5: Decimal precision check for sum of allocation quantities
|
||||||
|
alloc_sum = sum(Decimal(str(a.quantity)) for a in allocations)
|
||||||
|
target_qty = Decimal(str(li_row.quantity))
|
||||||
|
if alloc_sum != target_qty:
|
||||||
|
raise ValidationError(
|
||||||
|
f"مجموع مقادیر تخصیصیافته ({alloc_sum}) با مقدار کل قلم ({target_qty}) برابر نیست",
|
||||||
|
field="item_decisions.allocations",
|
||||||
|
)
|
||||||
|
# Validate all projects exist
|
||||||
|
for a in allocations:
|
||||||
|
if await db.get(Project, a.project_id) is None:
|
||||||
|
raise NotFoundError("پروژه یافت نشد", field="item_decisions.allocations.project_id")
|
||||||
|
|
||||||
|
if len(allocations) >= 2:
|
||||||
|
# 1. Update the original line item to the first allocation quantity
|
||||||
|
first_alloc = allocations[0]
|
||||||
|
li_row.quantity = first_alloc.quantity
|
||||||
|
decision_in.project_id = first_alloc.project_id
|
||||||
|
|
||||||
|
# Query all existing item_termsheets and line_item_specs for copying
|
||||||
|
orig_termsheets = (
|
||||||
|
await db.execute(
|
||||||
|
select(ItemTermsheet).where(ItemTermsheet.line_item_id == li_row.id)
|
||||||
|
)
|
||||||
|
).scalars().all()
|
||||||
|
orig_specs = (
|
||||||
|
await db.execute(
|
||||||
|
select(LineItemSpec).where(LineItemSpec.line_item_id == li_row.id)
|
||||||
|
)
|
||||||
|
).scalars().all()
|
||||||
|
|
||||||
|
# 2. For each subsequent allocation, create a new LineItem and copy specs + ALL termsheets
|
||||||
|
for split_alloc in allocations[1:]:
|
||||||
|
new_li = LineItem(
|
||||||
|
quote_id=quote.id,
|
||||||
|
material_id=li_row.material_id,
|
||||||
|
brand_material_id=li_row.brand_material_id,
|
||||||
|
unit_id=li_row.unit_id,
|
||||||
|
quantity=split_alloc.quantity,
|
||||||
|
notes=li_row.notes,
|
||||||
|
)
|
||||||
|
db.add(new_li)
|
||||||
|
await db.flush()
|
||||||
|
|
||||||
|
# Copy LineItemSpec
|
||||||
|
for sp in orig_specs:
|
||||||
|
db.add(
|
||||||
|
LineItemSpec(
|
||||||
|
line_item_id=new_li.id,
|
||||||
|
attribute_definition_id=sp.attribute_definition_id,
|
||||||
|
value_number=sp.value_number,
|
||||||
|
value_string=sp.value_string,
|
||||||
|
value_boolean=sp.value_boolean,
|
||||||
|
value_date=sp.value_date,
|
||||||
|
unit_id_at_time=sp.unit_id_at_time,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
# Requirement 1: Copy ALL payment options (ItemTermsheet)
|
||||||
|
chosen_new_it: ItemTermsheet | None = None
|
||||||
|
for it_orig in orig_termsheets:
|
||||||
|
price = (
|
||||||
|
decision_in.adjusted_unit_price
|
||||||
|
if (it_orig.termsheet_id == termsheet_id and decision_in.adjusted_unit_price is not None)
|
||||||
|
else it_orig.unit_price
|
||||||
|
)
|
||||||
|
copied_it = ItemTermsheet(
|
||||||
|
line_item_id=new_li.id,
|
||||||
|
termsheet_id=it_orig.termsheet_id,
|
||||||
|
unit_price=price,
|
||||||
|
min_order_qty=it_orig.min_order_qty,
|
||||||
|
)
|
||||||
|
db.add(copied_it)
|
||||||
|
if it_orig.termsheet_id == termsheet_id:
|
||||||
|
chosen_new_it = copied_it
|
||||||
|
|
||||||
|
if chosen_new_it is None:
|
||||||
|
chosen_new_it = ItemTermsheet(
|
||||||
|
line_item_id=new_li.id,
|
||||||
|
termsheet_id=termsheet_id,
|
||||||
|
unit_price=decision_in.adjusted_unit_price,
|
||||||
|
)
|
||||||
|
db.add(chosen_new_it)
|
||||||
|
await db.flush()
|
||||||
|
|
||||||
|
# Create ItemDecision for the split line item
|
||||||
|
new_decision = ItemDecision(
|
||||||
|
line_item_id=new_li.id,
|
||||||
|
status="chosen",
|
||||||
|
chosen_item_termsheet_id=chosen_new_it.id,
|
||||||
|
adjusted_unit_price=decision_in.adjusted_unit_price,
|
||||||
|
adjusted_notes=decision_in.adjusted_notes,
|
||||||
|
project_id=split_alloc.project_id,
|
||||||
|
decided_at=utcnow(),
|
||||||
|
)
|
||||||
|
db.add(new_decision)
|
||||||
|
|
||||||
|
# Requirement 4: sync QuoteProjects & LineItemProjects
|
||||||
|
await _ensure_quote_project(db, quote.id, split_alloc.project_id)
|
||||||
|
db.add(LineItemProjects(line_item_id=new_li.id, project_id=split_alloc.project_id))
|
||||||
|
elif len(allocations) == 1:
|
||||||
|
decision_in.project_id = allocations[0].project_id
|
||||||
|
|
||||||
it = await db.scalar(
|
it = await db.scalar(
|
||||||
select(ItemTermsheet).where(
|
select(ItemTermsheet).where(
|
||||||
ItemTermsheet.line_item_id == decision_in.line_item_id,
|
ItemTermsheet.line_item_id == decision_in.line_item_id,
|
||||||
@@ -610,6 +805,8 @@ async def accept_quote(db: AsyncSession, quote_id: UUID, payload: AcceptQuoteIn,
|
|||||||
if decision.project_id is not None:
|
if decision.project_id is not None:
|
||||||
if await db.get(Project, decision.project_id) is None:
|
if await db.get(Project, decision.project_id) is None:
|
||||||
raise NotFoundError("پروژه یافت نشد", field="item_decisions.project_id")
|
raise NotFoundError("پروژه یافت نشد", field="item_decisions.project_id")
|
||||||
|
# Requirement 4: sync QuoteProjects
|
||||||
|
await _ensure_quote_project(db, quote.id, decision.project_id)
|
||||||
chosen_ts_ids.add(termsheet_id)
|
chosen_ts_ids.add(termsheet_id)
|
||||||
else: # rejected
|
else: # rejected
|
||||||
if decision is None:
|
if decision is None:
|
||||||
|
|||||||
@@ -128,6 +128,7 @@ async def get_category(db, slug: str) -> MaterialCategory:
|
|||||||
|
|
||||||
USER_PLAN = [
|
USER_PLAN = [
|
||||||
# (casdoor username, first, last, role)
|
# (casdoor username, first, last, role)
|
||||||
|
("ali.mohaghegh", "علی", "محقق", "admin"),
|
||||||
("razaei", "علی", "رضایی", "admin"),
|
("razaei", "علی", "رضایی", "admin"),
|
||||||
("mousavi", "حسین", "موسوی", "procurement_manager"),
|
("mousavi", "حسین", "موسوی", "procurement_manager"),
|
||||||
("mohaghegh", "محمد", "محقق", "pm"),
|
("mohaghegh", "محمد", "محقق", "pm"),
|
||||||
|
|||||||
+53
-103
@@ -1,120 +1,70 @@
|
|||||||
# procurement_ai_agent — Bale chatbot for the procurement ERP
|
# procurement_ai_agent — ایجنت هوشمند بله برای سامانه ERP
|
||||||
|
|
||||||
A **Bale messenger bot** that turns Persian **chat messages and voice notes**
|
بات پیامرسان بله (Bale Messenger Bot) که پیامهای صوتی و متنی فارسی کاربران را دریافت کرده و با استفاده از مدلهای هوش مصنوعی (DeepSeek NLU + Whisper STT) آنها را به اقدامات و پیشنویسهای استعلام در سامانه ERP تبدیل میکند.
|
||||||
into procurement actions in the
|
|
||||||
[procurement ERP](https://git.bennu-api-bahrestan.ir/ali_mohaghegh/ERP) —
|
|
||||||
draft-first: it captures what it understood, tells you **what it did** and
|
|
||||||
**what is still empty**, and **commits only after you approve** with a ✅ button.
|
|
||||||
|
|
||||||
```
|
---
|
||||||
you (Bale, text/voice) ┌─────────────────────────────────┐
|
|
||||||
│ getUpdates (long poll) │ procurement_ai_agent │
|
## 🏗️ وضعیت استقرار در استک ERP
|
||||||
▼ │ ffmpeg → STT (Persian) │
|
|
||||||
┌──────────────────┐ POST {base}/bot<T> │ LLM → intent + entities │
|
این ایجنت **به صورت سرویس بومی (`procurement-bot`) مستقیماً درون `docker-compose.yml` ریشه پروژه** تعریف شده است و نیازی به نصب یا راهاندازی دستی ندارد.
|
||||||
│ tapi.bale.ai │◄───────────────────────►│ fuzzy resolve → draft payload │
|
|
||||||
└──────────────────┘ sendMessage / buttons │ review + «چه چیزهایی خالی مونده»│
|
* **نوع اتصال:** Long-polling از سرور بله (`tapi.bale.ai`) — بدون نیاز به باز کردن پورت خارجی، وبهوک یا TLS.
|
||||||
└───────────────┬─────────────────┘
|
* **ارتباط با بکاند:** به صورت مستقیم و درونشبکهای با سرویس `api` در آدرس `http://api:8000/api/v1`.
|
||||||
│ HTTP + X-Actor-Id
|
* **پایگاه داده:** استفاده از جدول `bot_drafts` در پایگاهداده مشترک PostgreSQL.
|
||||||
|
|
||||||
|
```text
|
||||||
|
کاربر (بله: متن یا صوت)
|
||||||
|
│ getUpdates (Long-polling)
|
||||||
▼
|
▼
|
||||||
┌─────────────────────────────────┐
|
┌─────────────────────────────────┐
|
||||||
│ ERP api (/api/v1) │
|
│ procurement_ai_agent │
|
||||||
│ quotes · suppliers · materials│
|
│ ffmpeg → STT تبدیل صوت به متن │
|
||||||
└─────────────────────────────────┘
|
│ LLM → استخراج نیت و موجودیتها │
|
||||||
|
│ Fuzzy Match → انطباق با ERP │
|
||||||
|
│ ایجاد پیشنویس در bot_drafts │
|
||||||
|
└────────────────┬────────────────┘
|
||||||
|
│
|
||||||
|
├── ثبت نهایی از بله با دکمه تایید
|
||||||
|
└── یا باز کردن مستقیم در ویزارد وب:
|
||||||
|
/wizard?draft=<UUID>
|
||||||
```
|
```
|
||||||
|
|
||||||
## What it can do
|
---
|
||||||
|
|
||||||
| Activity | Example (voice or text) | Committed via |
|
## 🌟 قابلیتها و کاربردها
|
||||||
|
|
||||||
|
| فعالیت | نمونه پیام (صوت یا متن) | اقدام نهایی |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
| Register a supplier quote | «سازان نو برای پروژه برج آسمان ۵۰۰ کیلو میلگرد A3 سایز ۱۴، هر کیلو ۴۵ تومن، پرداخت ۳ فاز» | `POST /quotes` |
|
| **ثبت استعلام جدید** | «سازان نو برای پروژه برج آسمان ۵۰۰ کیلو میلگرد A3 سایز ۱۴، هر کیلو ۴۵ تومن، پرداخت ۳ فاز» | `POST /quotes` |
|
||||||
| Add a supplier | «تأمینکننده جدید پروفیل بر، دسته لوله و اتصالات، تلفن ۰۹۱۲…» | `POST /suppliers` |
|
| **تعریف تأمینکننده** | «تأمینکننده جدید پروفیل بر، دسته لوله و اتصالات، تلفن ۰۹۱۲…» | `POST /suppliers` |
|
||||||
| Add a material | «کالای جدید میلگرد A3 سایز ۱۸ با واحد کیلوگرم» | `POST /materials` |
|
| **تعریف متریال جدید** | «کالای جدید میلگرد A3 سایز ۱۸ با واحد کیلوگرم» | `POST /materials` |
|
||||||
| Status queries | «استعلامهای در انتظار؟» / «کدامها بهزودی منقضی میشوند؟» | `GET /quotes?…` |
|
| **استعلام وضعیت** | «استعلامهای در انتظار؟» / «کدامها بهزودی منقضی میشوند؟» | `GET /quotes` |
|
||||||
| Accept a quote | «استعلام سازان نو را قبول کن» | `PATCH /quotes/{id}/accept` |
|
| **پذیرش استعلام** | «استعلام سازان نو را قبول کن» | `PATCH /quotes/{id}/accept` |
|
||||||
| Announce a delivery | «اقلام سازان نو رسید، ۵۰۰ و ۲۰۰» | `PATCH /quotes/{id}/arrive-items` |
|
|
||||||
|
|
||||||
### The draft → approve loop
|
---
|
||||||
|
|
||||||
1. Send a message or voice note. Voice → ffmpeg → STT; text/STT text → LLM
|
## 🔗 حلقه پیشنویس و تایید (Draft-First Loop)
|
||||||
extracts a typed **intent + entities** (JSON mode, Persian digits
|
|
||||||
normalized).
|
|
||||||
2. Names are fuzzy-matched against the ERP. Several candidates → inline
|
|
||||||
**pick buttons**; no match → listed as missing.
|
|
||||||
3. The bot replies with a **review card**: everything captured + a
|
|
||||||
✅/⚠️/❌ list of what is still empty.
|
|
||||||
4. Keep chatting to refine («قیمت میلگرد ۴۷ شد») — the open draft updates and
|
|
||||||
re-renders. Drafts survive bot restarts (postgres-backed, TTL-swept).
|
|
||||||
5. **Nothing is written to the ERP until you tap ✅.** After commit you get the
|
|
||||||
created quote id and the fields left empty.
|
|
||||||
|
|
||||||
### Team access & attribution
|
1. کاربر پیام صوتی یا متنی میفرستد. صوت به متن تبدیل شده و مدل هوش مصنوعی موجودیتها را استخراج میکند.
|
||||||
|
2. اسامی تامینکننده، متریال، پروژه و واحدها با کاتالوگ ERP تطبیق داده میشوند.
|
||||||
|
3. کارت مرور پیشنویس همراه با فیلدهای مشخصشده و اقلام خالی («چه چیزهایی ناقص است») برای کاربر ارسال میشود.
|
||||||
|
4. **دو روش برای تکمیل و ثبت نهایی وجود دارد:**
|
||||||
|
* **از طریق چت بله:** با ارسال پیامهای اصلاحی و در نهایت لمس دکمه «✅ ثبت نهایی».
|
||||||
|
* **از طریق پنل وب ویزارد:** با کلیک روی لینک مستقیم `/wizard?draft=<UUID>` که اطلاعات به صورت خودکار در فرم ۵ مرحلهای ویزارد بارگذاری میشود و کاربر میتواند فایل فاکتور را نیز ضمیمه کند.
|
||||||
|
|
||||||
Each member links their Bale chat once: `/start` → Casdoor username → password
|
---
|
||||||
(validated via the ERP's real `POST /auth/login`, used once, never stored).
|
|
||||||
Every mutating call carries `X-Actor-Id: <users.id>` so `quote_events.actor`
|
|
||||||
records the **human** who asked.
|
|
||||||
|
|
||||||
Commands: `/start` · `/help` · `/drafts` · `/cancel` · `/whoami` · `/unlink`
|
## ⚙️ متغیرهای محیطی و پیکربندی
|
||||||
|
|
||||||
## Quick start (Docker)
|
تنظیمات بات از طریق فایل `.env` در ریشه پروژه خوانده میشود:
|
||||||
|
|
||||||
```bash
|
```env
|
||||||
cp .env.example .env # fill PROCUREMENT_BOT_BOT_TOKEN + AI_API_KEY
|
BALE_BOT_TOKEN=توکن_دریافتی_از_بات_فادر_بله
|
||||||
docker build -t procurement-ai-agent .
|
BALE_API_BASE=https://tapi.bale.ai
|
||||||
docker run -d --name procurement-bot --env-file .env \
|
AI_BASE_URL=https://api.deepseek.com
|
||||||
--add-host host.docker.internal:host-gateway \
|
AI_API_KEY=کلید_سرویس_هوش_مصنوعی
|
||||||
procurement-ai-agent
|
AI_LLM_MODEL=deepseek-flash
|
||||||
docker logs -f procurement-bot
|
BALE_ADMIN_CHAT_IDS=شناسه_عددی_مدیران_در_بله
|
||||||
```
|
```
|
||||||
|
|
||||||
Or as part of the ERP stack — see [`integration/`](integration/README.md)
|
راهنمای گامبهگام اتصال و عیبیابی در [docs/SETUP.md](docs/SETUP.md) در دسترس است.
|
||||||
(compose service + the one tiny ERP-side patch).
|
|
||||||
|
|
||||||
Full setup, env-var reference, flows and troubleshooting:
|
|
||||||
**[docs/SETUP.md](docs/SETUP.md)**.
|
|
||||||
|
|
||||||
## Architecture
|
|
||||||
|
|
||||||
```
|
|
||||||
app/
|
|
||||||
├── main.py ensure bot tables → sweeper task → getUpdates long-poll loop
|
|
||||||
├── config.py pydantic-settings, PROCUREMENT_BOT_ prefix
|
|
||||||
├── bale/client.py Telegram-compatible Bale API (poll, send, edit, buttons, files)
|
|
||||||
├── api/client.py ERP /api/v1 client (X-Actor-Id attribution, error envelope)
|
|
||||||
├── stt.py ffmpeg (OGG/Opus → MP3) → OpenAI-compatible /audio/transcriptions
|
|
||||||
├── nlu.py Persian intent+entity extraction (JSON-mode chat completions)
|
|
||||||
├── resolve.py fuzzy name→id matching (difflib over ilike search), TTL caches
|
|
||||||
├── drafts.py draft store · QuoteCreate payload builder · missing-field logic
|
|
||||||
├── keyboards.py inline keyboards (callback_data ≤ 64 B op-codes)
|
|
||||||
├── texts.py Persian message templates
|
|
||||||
├── runtime.py context, link store, in-memory pending flows
|
|
||||||
├── models.py bot_links / bot_drafts / bot_messages / bot_meta (own schema)
|
|
||||||
└── handlers/ dispatch · commands · callbacks · links ·
|
|
||||||
quote · supplier · material · queries · decisions
|
|
||||||
```
|
|
||||||
|
|
||||||
Design notes:
|
|
||||||
|
|
||||||
- **Telegram-compatible Bale API** (`tapi.bale.ai`): getUpdates long polling —
|
|
||||||
no public port, no webhook, resumable offset persisted across restarts.
|
|
||||||
- **Draft-first**: `bot_drafts.payload` holds a talking-friendly JSON that is
|
|
||||||
converted into the exact `POST /quotes` request body (temp_id
|
|
||||||
cross-references) only on approval; the API deliberately tolerates
|
|
||||||
incomplete quotes, so partial commits are explicit, never accidental.
|
|
||||||
- **Accept flow echoes the termsheet's existing `schedule_steps`** back to
|
|
||||||
`PATCH /quotes/{id}/accept` (the API replaces steps with what it receives).
|
|
||||||
- **Persian-aware matching**: Persian/Arabic digit normalization, ZWNJ folding,
|
|
||||||
Arabic ya/ka folding, difflib ranking on top of the API's ilike search.
|
|
||||||
- **Voice notes** arrive as OGG/Opus; ffmpeg converts to mono 16 kHz MP3 before
|
|
||||||
STT. The LLM provider and the STT provider are configured independently
|
|
||||||
(e.g. DeepSeek for NLU + any whisper-compatible endpoint for voice).
|
|
||||||
|
|
||||||
## Testing
|
|
||||||
|
|
||||||
An offline end-to-end harness stubs Bale/ERP/AI and drives the real handler
|
|
||||||
pipeline with fake updates — no token, DB or API key needed:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
pip install -r requirements.txt
|
|
||||||
python tools/smoke_test.py # → ALL PASSED: 48 passed
|
|
||||||
```
|
|
||||||
|
|||||||
@@ -249,6 +249,9 @@ services:
|
|||||||
ports:
|
ports:
|
||||||
- "8000:8000"
|
- "8000:8000"
|
||||||
|
|
||||||
|
volumes:
|
||||||
|
- ./backend/app:/srv/backend/app
|
||||||
|
|
||||||
networks:
|
networks:
|
||||||
- traefik_network
|
- traefik_network
|
||||||
- default
|
- default
|
||||||
@@ -347,6 +350,78 @@ services:
|
|||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
mem_limit: 512m
|
mem_limit: 512m
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# PM platform (vendored from Aramesh/PM under ./pm) — serves the /panel/pm
|
||||||
|
# iframe at /pm/ on this domain. Shares the ERP database (its tables are
|
||||||
|
# created additively at startup) and reads ERP users/user_panels for SSO.
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
pm-api:
|
||||||
|
image: v15-pm-api:latest
|
||||||
|
build:
|
||||||
|
context: ./pm/backend
|
||||||
|
dockerfile: Dockerfile
|
||||||
|
container_name: pm-api
|
||||||
|
|
||||||
|
volumes:
|
||||||
|
- pm_files:/data/files
|
||||||
|
- ./pm/backend/app:/srv/pm/app
|
||||||
|
|
||||||
|
environment:
|
||||||
|
# Same database as the ERP — PM tables are additive, created at startup.
|
||||||
|
PM_DATABASE_URL: postgresql+asyncpg://postgres:${POSTGRES_PASSWORD:-postgres}@postgres:5432/procurement
|
||||||
|
PM_SESSION_SECRET: ${PM_SESSION_SECRET:-12278fc281bd0e22950e76364e1a18cea61fbc6a24604fdd79690a817ec36ac8}
|
||||||
|
PM_ADMIN_USER: ${PM_ADMIN_USER:-admin}
|
||||||
|
PM_ADMIN_PASSWORD: ${PM_ADMIN_PASSWORD:-pm123456}
|
||||||
|
PM_FILES_DIR: /data/files
|
||||||
|
PM_DEV_ROLE_SWITCH: ${PM_DEV_ROLE_SWITCH:-false}
|
||||||
|
# ERP integration — in-network service URLs.
|
||||||
|
PM_ERP_BASE_URL: http://api:8000
|
||||||
|
PM_ERP_CASDOOR_ENDPOINT: http://casdoor:8000
|
||||||
|
PM_ERP_CASDOOR_CLIENT_ID: ${PM_ERP_CASDOOR_CLIENT_ID:-inventory-app-client}
|
||||||
|
PM_ERP_CASDOOR_CLIENT_SECRET: ${PM_ERP_CASDOOR_CLIENT_SECRET:-inventory-app-secret-2026}
|
||||||
|
PM_ERP_SERVICE_USERNAME: ${PM_ERP_SERVICE_USERNAME:-pm-service}
|
||||||
|
PM_ERP_SERVICE_PASSWORD: ${PM_ERP_SERVICE_PASSWORD:-pm-service-2026}
|
||||||
|
PM_CASDOOR_ISSUER: ${CASDOOR_ISSUER:-http://localhost:8080}
|
||||||
|
|
||||||
|
depends_on:
|
||||||
|
postgres:
|
||||||
|
condition: service_healthy
|
||||||
|
api:
|
||||||
|
condition: service_started
|
||||||
|
|
||||||
|
networks:
|
||||||
|
- default
|
||||||
|
|
||||||
|
restart: unless-stopped
|
||||||
|
mem_limit: 512m
|
||||||
|
|
||||||
|
pm-frontend:
|
||||||
|
image: v15-pm-frontend:latest
|
||||||
|
build:
|
||||||
|
context: ./pm/frontend
|
||||||
|
dockerfile: Dockerfile
|
||||||
|
container_name: pm-frontend
|
||||||
|
|
||||||
|
depends_on:
|
||||||
|
- pm-api
|
||||||
|
|
||||||
|
# PM platform under /pm on the same domain and the same Traefik router.
|
||||||
|
labels:
|
||||||
|
- traefik.enable=true
|
||||||
|
- traefik.http.routers.pm.rule=PathPrefix(`/pm`)
|
||||||
|
- traefik.http.routers.pm.entrypoints=web
|
||||||
|
# Higher priority than the ERP frontend Host router — otherwise /pm/api
|
||||||
|
# would reach the ERP SPA (POST → 405).
|
||||||
|
- traefik.http.routers.pm.priority=100
|
||||||
|
- traefik.http.services.pm.loadbalancer.server.port=80
|
||||||
|
|
||||||
|
networks:
|
||||||
|
- traefik_network
|
||||||
|
- default
|
||||||
|
|
||||||
|
restart: unless-stopped
|
||||||
|
mem_limit: 128m
|
||||||
|
|
||||||
networks:
|
networks:
|
||||||
# شبکهی عمومی: فقط ترافیک و سرویسهای عمومی. postgres روی شبکهی
|
# شبکهی عمومی: فقط ترافیک و سرویسهای عمومی. postgres روی شبکهی
|
||||||
# پیشفرض میماند و از بیرون قابل دسترسی نیست.
|
# پیشفرض میماند و از بیرون قابل دسترسی نیست.
|
||||||
@@ -363,3 +438,4 @@ volumes:
|
|||||||
postgres_data:
|
postgres_data:
|
||||||
minio_data:
|
minio_data:
|
||||||
traefik_certs:
|
traefik_certs:
|
||||||
|
pm_files:
|
||||||
|
|||||||
@@ -0,0 +1,94 @@
|
|||||||
|
# گزارش گپهای دفتر موجودی (Inventory Ledger Gaps)
|
||||||
|
|
||||||
|
بررسی کامل منطق تراکنشهای انبار (بکاند + فرانتاند) در جریان بازطراحی صفحه «تغییر موجودی».
|
||||||
|
**این گزارش فقط فهرست گپهاست برای تصمیمگیری معماری — بهجز مورد ۱، هیچکدام در این نسخه اصلاح نشدهاند.**
|
||||||
|
|
||||||
|
وضعیتها: 🔴 ریسک بالای داده · 🟡 ریسک متوسط · 🔵 بهبود
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## ۱. ✅ اصلاحشده در همین نسخه (پیشنیاز فیچر برگشت)
|
||||||
|
|
||||||
|
**`GET /inventory/transactions?date_from=&date_to=` → HTTP 500**
|
||||||
|
(`backend/app/routers/inventory.py` — list_transactions)
|
||||||
|
|
||||||
|
ستون `transaction_date` (timestamptz) با رشتهی خام مقایسه میشد. درایور asyncpg تایپ سختگیرانه دارد و این مقایسه با خطای `operator does not exist: timestamp with time zone >= character varying` کرش میکرد. هیچجای UI قدیمی این فیلترها را صدا نمیزد، برای همین مخفی مانده بود.
|
||||||
|
|
||||||
|
**اصلاح:** پارامترهای `YYYY-MM-DD` به datetime آگاه از UTC تبدیل میشوند (`YYYY-MM-DD 00:00 UTC` تا `+1 روز`) — همان معناشناسی کستِ قدیمی رشته در PostgreSQL با `timezone = Etc/UTC`. ⚠️ نکتهی مرتبط: مورد ۱۲.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## ۲. 🔴 سقف برگشت و اتصال REF فقط در فرانت است
|
||||||
|
|
||||||
|
بکاند `RETURN` را دقیقاً مثل `PURCHASE` (افزایش ساده) میپذیرد (`inventory_service.py:268-299`) — نه به برداشت خاصی وصل است و نه سقفی دارد. با فراخوانی مستقیم API میتوان موجودی یک انبار را بینهایت تورم داد.
|
||||||
|
|
||||||
|
UI جدید این را کنترل میکند (تگ `[REF:<tx-id>]` در note + محاسبهی مانده + سقف ورودی)، اما **خود دفتر از سمت سرور محافظت نمیشود.**
|
||||||
|
|
||||||
|
**پیشنهاد برای تصمیمگیری:** اعتبارسنجی سمت سرور — برگشت حتماً `ref_transaction_id` بگیرد و سرویس مانده را با قفل ردیف چک کند؛ یا جدول attribution جداگانه.
|
||||||
|
|
||||||
|
## ۳. 🔴 TRANSFER_IN مستقل بدون جفت پذیرفته میشود
|
||||||
|
|
||||||
|
`POST /inventory/transactions` با نوع `TRANSFER_IN` بدون هیچ TRANSFER_OUT متناظری پذیرفته میشود (سرویس آن را افزایش عمومی حساب میکند). یعنی از مسیر API میتوان «ورودی انتقال» جعلی ثبت کرد. فقط جفتِ واقعیِ ساختهشده توسط خود سرویس `transfer_pair_id` دارد.
|
||||||
|
|
||||||
|
**پیشنهاد:** TRANSFER_IN از مسیر عمومی بسته شود (فقط از طریق جفتسازی داخلی سرویس ثبت شود).
|
||||||
|
|
||||||
|
## ۴. 🟡 create انتقال بینکارگاهی «ردیف انبار» نمیگیرد
|
||||||
|
|
||||||
|
`POST /inventory/project-transfers` بهجای `inventory_row_id` فقط material/brand/unit/specs میگیرد؛ اگر match دقیق پیدا نشود، سرویس با fallback امتیازدهی «بهترین کاندیدای همان متریال» را کسر میکند (`project_transfer_service.py:105-151`). اگر یک متریال با چند ردیف specs نزدیک به هم باشد، ممکن است از ردیفی غیر از قصد کاربر کسر شود.
|
||||||
|
|
||||||
|
**پیشنهاد:** پذیرش `inventory_row_id` اختیاری در payload و کسر دقیق از همان ردیف.
|
||||||
|
|
||||||
|
## ۵. 🟡 Audit Trail ناقص است
|
||||||
|
|
||||||
|
فقط `POST /inventory/transactions` رکورد audit مینویسد (`inventory.py:491-500`). اینها audit ندارند:
|
||||||
|
- ساخت / ویرایش (PATCH) / لغو (DELETE) انتقال بینکارگاهی
|
||||||
|
- تأیید تحویل PM (`/pm/receipts` و دریافت انتقال)
|
||||||
|
- CRUD انبارها و تغییرات کاربران
|
||||||
|
|
||||||
|
**پیشنهاد:** گسترش `audit_record` به این مسیرها (helper موجود آماده است و هرگز raise نمیکند).
|
||||||
|
|
||||||
|
## ۶. 🟡 فیلدهای الزامی کلیدی فقط در UI اعمال میشوند
|
||||||
|
|
||||||
|
- `delivered_to` (تحویلگیرنده برداشت) در UI اجباری است؛ API بدون آن 201 میدهد.
|
||||||
|
- ظرفیتسنجی مشابه برای «توضیح» (note) شمارش موجودی و… .
|
||||||
|
|
||||||
|
## ۷. 🟡 رفتار postSeq قدیمی هنگام خطای وسط بچ
|
||||||
|
|
||||||
|
در بخشهای لیستی ساده (برداشت/ضایعات/اتلاف/مفقودی/انتقال داخلی) اگر ثبت ردیف kام شکست بخورد، ردیفهای ۱..k-1 **موفق ثبتشده** در جدول باقی میمانند → retry کاربر = ثبت تکراری. (در انتقال بینکارگاهی و برگشتِ این نسخه، ردیفهای موفق از لیست حذف میشوند — الگوی درست.)
|
||||||
|
|
||||||
|
**پیشنهاد:** انتقال الگوی «حذف ردیف موفق + خطای inline» به postSeq.
|
||||||
|
|
||||||
|
## ۸. 🟡 برگشتهای قدیمی بدون REF قابل انتساب دقیق نیستند
|
||||||
|
|
||||||
|
برگشتهای ثبتشده قبل از این نسخه هیچ اشارهای به برداشت مرجع ندارند. UI با تخصیص FIFO بین برداشتهای همردیف (متریال+برند+مشخصات+واحد) جبران میکند، ولی این حدس است و در دو حالت خطا دارد:
|
||||||
|
- برگشت قدیمی به انباری غیر از انبار مبدأ → قابل انتساب نیست و از مانده کم نمیشود.
|
||||||
|
- تخصیص FIFO صفحات اولِ واکشی ممکن است برگشتِ متعلق به برداشتِ صفحههای بعد را جابهجا کند.
|
||||||
|
|
||||||
|
**پیشنهاد (داده):** اسکریپت یکبارهی backfill — تطبیق برگشتهای قدیمی با برداشتهای همان ردیف (قدیمیترین برداشتِ باقیمانده) و درج REF در note.
|
||||||
|
|
||||||
|
## ۹. 🔵 معناشناسی تاریخ فیلترها = UTC (نه تهران)
|
||||||
|
|
||||||
|
فیلتر `date_from/date_to` (بعد از اصلاح مورد ۱) مرز روز را در UTC میبرد، در حالی که UI جلالی و ساعت کاربر +03:30 است. برداشت ساعت ۰۰:۰۰–۰۳:۳۰ تهران در «دیروز» UTC میافتد. این معناشناسی قدیمی حفظ شد؛ اگر روزِ تهران ملاک است، باید offset منطقه (یا پارامتر `tz` از کلاینت) اضافه شود.
|
||||||
|
|
||||||
|
## ۱۰. 🔵 GET /inventory/{id}/transactions enrichment ناقص
|
||||||
|
|
||||||
|
پاسخ این endpoint فیلدهای material/brand/specs/unit را ندارد (فقط GET لیست کامل enrich میکند). UI فعلی از آن استفاده نمیکند ولی برای دیباگ/گزارشها گمراهکننده است.
|
||||||
|
|
||||||
|
## ۱۱. 🔵 سقف ۱۰۰ رکوردی واکشیهای لیست
|
||||||
|
|
||||||
|
`GET /inventory` و lookup ها در `useInventoryData` با `page_size=100` واکشی میشوند؛ انبار با بیش از ۱۰۰ رکورد موجودی در UI کامل نمایش داده نمیشود (محدودیت قدیمی، در لیستهای جدید این صفحه هم از همان دیتا میخواند). لیست برگشت و مفقودیها صفحهبندی/واکشی کامل دارند.
|
||||||
|
|
||||||
|
## ۱۲. 🔵 لیست انتقالهای بینکارگاهی بدون صفحهبندی
|
||||||
|
|
||||||
|
`GET /inventory/project-transfers` و `/pm/transfers/on-the-way` همهی ردیفها را بدون pagination برمیگردانند؛ با رشد داده بار پاسخ زیاد میشود.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## چیزهایی که بررسی شد و درست است ✅
|
||||||
|
|
||||||
|
- **Immutable Ledger در سطح API:** برای تراکنشها هیچ endpoint ویرایش/حذفی وجود ندارد (فقط POST و GET). تنها حذفِ موجود، لغو انتقال بینکارگاهی است که تراکنش خروجی خودش را بازمیگرداند و موجودی را ترمیم میکند.
|
||||||
|
- **سقف FOUND در بکاند اعمال میشود:** بیش از «Σ|LOSS| − ΣFOUND» همان ردیف → 422 (تست شد).
|
||||||
|
- **STOCK_COUNT فقط روی رکورد موجود** و با ثبت اختلاف علامتدار صحیح.
|
||||||
|
- **TRANSFER_OUT جفتی:** کسر مبدأ و ایجاد TRANSFER_IN مقصد با `transfer_pair_id` مشترک و قفل ردیف؛ موجودی منفی نمیشود.
|
||||||
|
- **دریافت انتقال بینکارگاهی:** مجموع allocations باید دقیقاً برابر مقدار انتقال باشد و انبارها به پروژه مقصد تعلق داشته باشند.
|
||||||
|
- **هویت ردیف انبار** با `specs_hash` (SHA256 مرتبشدهی specs) و sentinel برند NULL یکتاست — ریسک ادغام رکوردهای متفاوت وجود ندارد.
|
||||||
+1
-1
@@ -13,7 +13,7 @@
|
|||||||
href="https://fonts.googleapis.com/css2?family=Vazirmatn:wght@400;500;600;700;800&display=swap"
|
href="https://fonts.googleapis.com/css2?family=Vazirmatn:wght@400;500;600;700;800&display=swap"
|
||||||
rel="stylesheet"
|
rel="stylesheet"
|
||||||
/>
|
/>
|
||||||
<title>دفتر پیشنهادهای خرید — دفترچه تأمین</title>
|
<title>سامانه جامع مدیریت پروژه، تدارکات و انبار</title>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<div id="root"></div>
|
<div id="root"></div>
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"name": "دفترچه تأمین — سامانه تدارکات و انبار",
|
"name": "سامانه جامع مدیریت پروژه، تدارکات و انبار",
|
||||||
"short_name": "دفترچه تأمین",
|
"short_name": "مدیریت پروژه و تأمین",
|
||||||
"description": "سامانه تدارکات و مدیریت انبار پروژههای ساختمانی",
|
"description": "سامانه جامع مدیریت عملیات پروژه، تدارکات و انبارداری",
|
||||||
"dir": "rtl",
|
"dir": "rtl",
|
||||||
"lang": "fa",
|
"lang": "fa",
|
||||||
"start_url": "/",
|
"start_url": "/",
|
||||||
|
|||||||
+275
-5
@@ -38,11 +38,14 @@ const WarehousesPage = lazy(() =>
|
|||||||
import("./pages/Inventory/WarehousesPage").then((m) => ({ default: m.WarehousesPage })),
|
import("./pages/Inventory/WarehousesPage").then((m) => ({ default: m.WarehousesPage })),
|
||||||
);
|
);
|
||||||
const OrganizationPage = lazy(() =>
|
const OrganizationPage = lazy(() =>
|
||||||
import("./pages/Inventory/OrganizationPage").then((m) => ({ default: m.OrganizationPage })),
|
import("./pages/Organization/OrganizationPage").then((m) => ({ default: m.OrganizationPage })),
|
||||||
);
|
);
|
||||||
const AdminPanelPage = lazy(() =>
|
const AdminPanelPage = lazy(() =>
|
||||||
import("./pages/Admin/AdminPanel").then((m) => ({ default: m.AdminPanel })),
|
import("./pages/Admin/AdminPanel").then((m) => ({ default: m.AdminPanel })),
|
||||||
);
|
);
|
||||||
|
const RequesterHome = lazy(() =>
|
||||||
|
import("./pages/Dashboard/RequesterHome").then((m) => ({ default: m.RequesterHome })),
|
||||||
|
);
|
||||||
|
|
||||||
function Loading() {
|
function Loading() {
|
||||||
return (
|
return (
|
||||||
@@ -56,6 +59,7 @@ function Loading() {
|
|||||||
function RequireAuth({ children }: { children: React.ReactNode }) {
|
function RequireAuth({ children }: { children: React.ReactNode }) {
|
||||||
const user = useAuthStore((s) => s.user);
|
const user = useAuthStore((s) => s.user);
|
||||||
const location = useLocation();
|
const location = useLocation();
|
||||||
|
const pathname = location.pathname;
|
||||||
|
|
||||||
// در صورت داشتن شناسه پیشنویس (از ربات بله)، دسترسی مستقیم به ویزارد بدون لاگین مجاز است
|
// در صورت داشتن شناسه پیشنویس (از ربات بله)، دسترسی مستقیم به ویزارد بدون لاگین مجاز است
|
||||||
const searchParams = new URLSearchParams(location.search);
|
const searchParams = new URLSearchParams(location.search);
|
||||||
@@ -68,16 +72,251 @@ function RequireAuth({ children }: { children: React.ReactNode }) {
|
|||||||
const returnUrl = encodeURIComponent(location.pathname + location.search);
|
const returnUrl = encodeURIComponent(location.pathname + location.search);
|
||||||
return <Navigate to={`/login?returnUrl=${returnUrl}`} replace />;
|
return <Navigate to={`/login?returnUrl=${returnUrl}`} replace />;
|
||||||
}
|
}
|
||||||
|
if (user.role === "supervisor") {
|
||||||
|
// اگر سرپرست پروژهای نداشته باشد، دسترسی مسدود میشود
|
||||||
|
const hasProjects =
|
||||||
|
(Boolean(user.projects && user.projects.length > 0)) ||
|
||||||
|
(Boolean(user.member_project_ids && user.member_project_ids.length > 0));
|
||||||
|
if (!hasProjects) {
|
||||||
|
return (
|
||||||
|
<div className="flex min-h-screen items-center justify-center bg-bg px-4">
|
||||||
|
<div className="w-full max-w-md rounded-2xl border border-line bg-panel p-8 text-center shadow-sm">
|
||||||
|
<h1 className="text-[16px] font-extrabold text-red">پروژه تخصیص داده نشده است</h1>
|
||||||
|
<p className="mt-2 text-[12.5px] leading-6 text-muted">
|
||||||
|
شما به عنوان سرپرست پروژه در سیستم ثبت شدهاید اما هنوز هیچ پروژهای به شما تخصیص داده نشده است.
|
||||||
|
تا زمان تخصیص پروژه توسط مدیر سیستم، اجازه ورود به سامانه را ندارید.
|
||||||
|
</p>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => {
|
||||||
|
useAuthStore.getState().logout();
|
||||||
|
window.location.href = "/login";
|
||||||
|
}}
|
||||||
|
className="mt-5 inline-flex h-10 w-full cursor-pointer items-center justify-center rounded-lg bg-accent px-4 text-[13px] font-bold text-white transition-colors hover:bg-accent-dark"
|
||||||
|
>
|
||||||
|
خروج از حساب
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// بررسی دسترسی به مسیرها بر اساس ترکیب نقش سازمانی و پنلهای تخصیصی:
|
||||||
|
const panels = user.panels ?? {};
|
||||||
|
const isAdmin = user.role === "admin";
|
||||||
|
const hasPanelsConfig = Boolean(user.panels && Object.keys(user.panels).length > 0);
|
||||||
|
|
||||||
|
const hasProcurement =
|
||||||
|
isAdmin ||
|
||||||
|
(hasPanelsConfig
|
||||||
|
? Boolean(panels.procurement)
|
||||||
|
: user.role === "procurement_manager");
|
||||||
|
|
||||||
|
const hasInventory =
|
||||||
|
isAdmin ||
|
||||||
|
(hasPanelsConfig
|
||||||
|
? Boolean(panels.inventory)
|
||||||
|
: user.role === "pm" || user.role === "supervisor");
|
||||||
|
|
||||||
|
const hasPm =
|
||||||
|
isAdmin ||
|
||||||
|
(hasPanelsConfig
|
||||||
|
? Boolean(panels.pm)
|
||||||
|
: user.role === "pm" || user.role === "supervisor");
|
||||||
|
|
||||||
|
const isProcurementRoute =
|
||||||
|
pathname === "/" ||
|
||||||
|
pathname.startsWith("/wizard") ||
|
||||||
|
pathname.startsWith("/suppliers") ||
|
||||||
|
pathname.startsWith("/projects") ||
|
||||||
|
pathname.startsWith("/units") ||
|
||||||
|
pathname.startsWith("/requester");
|
||||||
|
|
||||||
|
if (isProcurementRoute && !hasProcurement) {
|
||||||
|
if (hasInventory) return <Navigate to="/inventory" replace />;
|
||||||
|
if (hasPm) return <Navigate to="/panel/pm" replace />;
|
||||||
|
return <Navigate to="/login" replace />;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (pathname.startsWith("/inventory") && !hasInventory) {
|
||||||
|
if (hasProcurement) return <Navigate to={panels.procurement === "limited" && !isAdmin ? "/wizard" : "/"} replace />;
|
||||||
|
if (hasPm) return <Navigate to="/panel/pm" replace />;
|
||||||
|
return <Navigate to="/login" replace />;
|
||||||
|
}
|
||||||
|
|
||||||
return <>{children}</>;
|
return <>{children}</>;
|
||||||
}
|
}
|
||||||
|
|
||||||
// صفحهی اصلی بر اساس نقش: مدیر پروژه → پنل انبار؛ مدیر تدارکات/ادمین → دفتر
|
// صفحهی اصلی بر اساس لایه پنلها (جایگزین نقشها):
|
||||||
function HomeRoute() {
|
function HomeRoute() {
|
||||||
const user = useAuthStore((s) => s.user);
|
const user = useAuthStore((s) => s.user);
|
||||||
if (user?.role === "pm") return <Navigate to="/inventory" replace />;
|
const panels = user?.panels ?? {};
|
||||||
|
const isAdmin = user?.role === "admin";
|
||||||
|
const hasPanelsConfig = Boolean(user?.panels && Object.keys(user.panels).length > 0);
|
||||||
|
|
||||||
|
const hasProcurement =
|
||||||
|
isAdmin ||
|
||||||
|
(hasPanelsConfig
|
||||||
|
? Boolean(panels.procurement)
|
||||||
|
: user?.role === "procurement_manager");
|
||||||
|
|
||||||
|
const hasInventory =
|
||||||
|
isAdmin ||
|
||||||
|
(hasPanelsConfig
|
||||||
|
? Boolean(panels.inventory)
|
||||||
|
: user?.role === "pm" || user?.role === "supervisor");
|
||||||
|
|
||||||
|
const hasPm =
|
||||||
|
isAdmin ||
|
||||||
|
(hasPanelsConfig
|
||||||
|
? Boolean(panels.pm)
|
||||||
|
: user?.role === "pm" || user?.role === "supervisor");
|
||||||
|
|
||||||
|
// ۱. اگر پنل تدارکات دارد:
|
||||||
|
if (hasProcurement) {
|
||||||
|
if (panels.procurement === "limited" && !isAdmin) {
|
||||||
|
return <Navigate to="/wizard" replace />;
|
||||||
|
}
|
||||||
return <DashboardPage />;
|
return <DashboardPage />;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ۲. اگر پنل انبار دارد:
|
||||||
|
if (hasInventory) return <Navigate to="/inventory" replace />;
|
||||||
|
|
||||||
|
// ۳. اگر پنل PM دارد:
|
||||||
|
if (hasPm) return <Navigate to="/panel/pm" replace />;
|
||||||
|
|
||||||
|
// در صورتی که کاربر به هیچ پنلی دسترسی ندارد:
|
||||||
|
return (
|
||||||
|
<div className="flex min-h-screen items-center justify-center p-4">
|
||||||
|
<div className="w-full max-w-md rounded-2xl border border-line bg-panel p-6 text-center shadow-lg">
|
||||||
|
<h3 className="text-base font-bold text-slate-800">عدم دسترسی به پنلهای سامانه</h3>
|
||||||
|
<p className="mt-2 text-xs text-muted leading-6">
|
||||||
|
حساب کاربری شما فعال است اما در حال حاضر به هیچیک از پنلهای سامانه دسترسی ندارد. لطفاً با مدیر سیستم تماس بگیرید.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// دسترسی ایجاد استعلام/پیشنهاد (ویزارد): ادمین، نقشهای تدارکات و پنلهای تدارکات (full یا limited)
|
||||||
|
function RequireProcurementWrite({ children }: { children: React.ReactNode }) {
|
||||||
|
const user = useAuthStore((s) => s.user);
|
||||||
|
const panels = user?.panels ?? {};
|
||||||
|
const isAdmin = user?.role === "admin";
|
||||||
|
const hasPanelsConfig = Boolean(user?.panels && Object.keys(user.panels).length > 0);
|
||||||
|
const hasProcurement =
|
||||||
|
isAdmin ||
|
||||||
|
(hasPanelsConfig
|
||||||
|
? Boolean(panels.procurement)
|
||||||
|
: user?.role === "procurement_manager" || user?.role === "pm");
|
||||||
|
|
||||||
|
if (hasProcurement) {
|
||||||
|
return <>{children}</>;
|
||||||
|
}
|
||||||
|
|
||||||
|
const hasInventory =
|
||||||
|
isAdmin ||
|
||||||
|
(hasPanelsConfig
|
||||||
|
? Boolean(panels.inventory)
|
||||||
|
: user?.role === "pm" || user?.role === "supervisor");
|
||||||
|
if (hasInventory) return <Navigate to="/inventory" replace />;
|
||||||
|
|
||||||
|
const hasPm =
|
||||||
|
isAdmin ||
|
||||||
|
(hasPanelsConfig
|
||||||
|
? Boolean(panels.pm)
|
||||||
|
: user?.role === "pm" || user?.role === "supervisor");
|
||||||
|
if (hasPm) return <Navigate to="/panel/pm" replace />;
|
||||||
|
|
||||||
|
return <Navigate to="/login" replace />;
|
||||||
|
}
|
||||||
|
|
||||||
|
// پنل «مدیریت پروژه (PM)» — اپ PM روی همان دامنه زیر مسیر /pm سرو میشود
|
||||||
|
function PmPanelPage() {
|
||||||
|
return (
|
||||||
|
<iframe
|
||||||
|
src="/pm/"
|
||||||
|
title="مدیریت پروژه (PM)"
|
||||||
|
className="h-dvh w-full border-0"
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// دسترسی پنل PM: ادمین، پنل pm (full/limited) و نقشهای pm/supervisor
|
||||||
|
function RequirePmPanel({ children }: { children: React.ReactNode }) {
|
||||||
|
const user = useAuthStore((s) => s.user);
|
||||||
|
const panels = user?.panels ?? {};
|
||||||
|
const isAdmin = user?.role === "admin";
|
||||||
|
const hasPanelsConfig = Boolean(user?.panels && Object.keys(user.panels).length > 0);
|
||||||
|
const hasPm =
|
||||||
|
isAdmin ||
|
||||||
|
(hasPanelsConfig
|
||||||
|
? Boolean(panels.pm)
|
||||||
|
: user?.role === "pm" || user?.role === "supervisor");
|
||||||
|
|
||||||
|
if (!hasPm) {
|
||||||
|
const hasProcurement =
|
||||||
|
isAdmin ||
|
||||||
|
(hasPanelsConfig
|
||||||
|
? Boolean(panels.procurement)
|
||||||
|
: user?.role === "procurement_manager");
|
||||||
|
if (hasProcurement) {
|
||||||
|
return <Navigate to={panels.procurement === "limited" && !isAdmin ? "/wizard" : "/"} replace />;
|
||||||
|
}
|
||||||
|
const hasInventory =
|
||||||
|
isAdmin ||
|
||||||
|
(hasPanelsConfig
|
||||||
|
? Boolean(panels.inventory)
|
||||||
|
: user?.role === "pm" || user?.role === "supervisor");
|
||||||
|
if (hasInventory) return <Navigate to="/inventory" replace />;
|
||||||
|
return <Navigate to="/login" replace />;
|
||||||
|
}
|
||||||
|
return <>{children}</>;
|
||||||
|
}
|
||||||
|
|
||||||
|
// دسترسی پنل سازماندهی: فقط ادمین، مدیر تدارکات و مدیر پروژه
|
||||||
|
function RequireOrganization({ children }: { children: React.ReactNode }) {
|
||||||
|
const user = useAuthStore((s) => s.user);
|
||||||
|
const isAdmin = user?.role === "admin";
|
||||||
|
const allowed = isAdmin || user?.role === "procurement_manager" || user?.role === "pm";
|
||||||
|
if (!allowed) {
|
||||||
|
const panels = user?.panels ?? {};
|
||||||
|
const hasPanelsConfig = Boolean(user?.panels && Object.keys(user.panels).length > 0);
|
||||||
|
const hasProcurement = isAdmin || (hasPanelsConfig ? Boolean(panels.procurement) : user?.role === "procurement_manager");
|
||||||
|
if (hasProcurement) return <Navigate to={panels.procurement === "limited" && !isAdmin ? "/wizard" : "/"} replace />;
|
||||||
|
const hasInventory = isAdmin || (hasPanelsConfig ? Boolean(panels.inventory) : user?.role === "supervisor");
|
||||||
|
if (hasInventory) return <Navigate to="/inventory" replace />;
|
||||||
|
return <Navigate to="/panel/pm" replace />;
|
||||||
|
}
|
||||||
|
return <>{children}</>;
|
||||||
|
}
|
||||||
|
|
||||||
|
// دسترسی تغییر موجودی انبار: ادمین، سرپرست پروژه (میراث) و پنل انبار limited —
|
||||||
|
// پنل انبار full طبق طراحی به تغییر موجودی دسترسی ندارد
|
||||||
|
function RequireInventoryChange({ children }: { children: React.ReactNode }) {
|
||||||
|
const user = useAuthStore((s) => s.user);
|
||||||
|
const allowed =
|
||||||
|
user?.role === "admin" ||
|
||||||
|
user?.role === "supervisor" ||
|
||||||
|
user?.panels?.inventory === "limited";
|
||||||
|
if (!allowed) {
|
||||||
|
return <Navigate to="/inventory" replace />;
|
||||||
|
}
|
||||||
|
return <>{children}</>;
|
||||||
|
}
|
||||||
|
|
||||||
|
// دسترسی مدیریت انبارها: مدیران، ادمین و سرپرست پروژه (سرپرست پروژه منحصراً انبارهای پروژه خودش را میبیند)
|
||||||
|
function RequireWarehouseManage({ children }: { children: React.ReactNode }) {
|
||||||
|
const user = useAuthStore((s) => s.user);
|
||||||
|
const allowed = user?.role === "admin" || user?.role === "procurement_manager" || user?.role === "pm" || user?.role === "supervisor";
|
||||||
|
if (!allowed) {
|
||||||
|
return <Navigate to="/inventory" replace />;
|
||||||
|
}
|
||||||
|
return <>{children}</>;
|
||||||
|
}
|
||||||
|
|
||||||
export default function App() {
|
export default function App() {
|
||||||
return (
|
return (
|
||||||
<ErrorBoundary>
|
<ErrorBoundary>
|
||||||
@@ -97,10 +336,13 @@ export default function App() {
|
|||||||
path="/wizard"
|
path="/wizard"
|
||||||
element={
|
element={
|
||||||
<RequireAuth>
|
<RequireAuth>
|
||||||
|
<RequireProcurementWrite>
|
||||||
<WizardPage />
|
<WizardPage />
|
||||||
|
</RequireProcurementWrite>
|
||||||
</RequireAuth>
|
</RequireAuth>
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
|
<Route path="/requester" element={<Navigate to="/wizard" replace />} />
|
||||||
<Route
|
<Route
|
||||||
path="/suppliers"
|
path="/suppliers"
|
||||||
element={
|
element={
|
||||||
@@ -177,7 +419,9 @@ export default function App() {
|
|||||||
element={
|
element={
|
||||||
<RequireAuth>
|
<RequireAuth>
|
||||||
<RequirePmProjects>
|
<RequirePmProjects>
|
||||||
|
<RequireInventoryChange>
|
||||||
<ChangeInventoryPage />
|
<ChangeInventoryPage />
|
||||||
|
</RequireInventoryChange>
|
||||||
</RequirePmProjects>
|
</RequirePmProjects>
|
||||||
</RequireAuth>
|
</RequireAuth>
|
||||||
}
|
}
|
||||||
@@ -197,18 +441,24 @@ export default function App() {
|
|||||||
element={
|
element={
|
||||||
<RequireAuth>
|
<RequireAuth>
|
||||||
<RequirePmProjects>
|
<RequirePmProjects>
|
||||||
|
<RequireWarehouseManage>
|
||||||
<WarehousesPage />
|
<WarehousesPage />
|
||||||
|
</RequireWarehouseManage>
|
||||||
</RequirePmProjects>
|
</RequirePmProjects>
|
||||||
</RequireAuth>
|
</RequireAuth>
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
<Route
|
<Route
|
||||||
path="/inventory/org"
|
path="/inventory/org"
|
||||||
|
element={<Navigate to="/organization" replace />}
|
||||||
|
/>
|
||||||
|
<Route
|
||||||
|
path="/organization"
|
||||||
element={
|
element={
|
||||||
<RequireAuth>
|
<RequireAuth>
|
||||||
<RequirePmProjects>
|
<RequireOrganization>
|
||||||
<OrganizationPage />
|
<OrganizationPage />
|
||||||
</RequirePmProjects>
|
</RequireOrganization>
|
||||||
</RequireAuth>
|
</RequireAuth>
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
@@ -220,6 +470,26 @@ export default function App() {
|
|||||||
</RequireAuth>
|
</RequireAuth>
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
|
{/* خانه حداقلی استعلام — تدارکات سطح limited */}
|
||||||
|
<Route
|
||||||
|
path="/requester"
|
||||||
|
element={
|
||||||
|
<RequireAuth>
|
||||||
|
<RequesterHome />
|
||||||
|
</RequireAuth>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
{/* پنل مدیریت پروژه — فقط ادمین و مدیر پروژه */}
|
||||||
|
<Route
|
||||||
|
path="/panel/pm"
|
||||||
|
element={
|
||||||
|
<RequireAuth>
|
||||||
|
<RequirePmPanel>
|
||||||
|
<PmPanelPage />
|
||||||
|
</RequirePmPanel>
|
||||||
|
</RequireAuth>
|
||||||
|
}
|
||||||
|
/>
|
||||||
<Route path="*" element={<Navigate to="/" replace />} />
|
<Route path="*" element={<Navigate to="/" replace />} />
|
||||||
</Routes>
|
</Routes>
|
||||||
</Suspense>
|
</Suspense>
|
||||||
|
|||||||
@@ -1,48 +1,84 @@
|
|||||||
import { useLocation } from "react-router-dom";
|
|
||||||
import { PanelMenu, type MenuItem } from "./PanelMenu";
|
import { PanelMenu, type MenuItem } from "./PanelMenu";
|
||||||
import { useLogout } from "../pages/Inventory/panelMenu";
|
import { useLogout } from "../pages/Inventory/panelMenu";
|
||||||
import { useAuthStore } from "../store/auth";
|
import { useAuthStore } from "../store/auth";
|
||||||
|
|
||||||
// منوی همبرگری مشترک بین دو ماژول (پنل انبار / دفتر تدارکات) —
|
// منوی همبرگری مشترک بین ۴ پنل اصلی سامانه:
|
||||||
// دقیقاً مثل منوی دفتر: عنوان «پنلها»، ماژول فعلی با استایل فعال (پر)
|
// ۱. مدیریت انبار (/inventory)
|
||||||
// + «✓ فعلی»، ماژول دیگر بهعنوان سوییچر، و در پایان جداکننده + خروج.
|
// ۲. مدیریت تدارکات (/)
|
||||||
// مدیر پروژه (1:N): زیر «مدیریت انبار» یک آکاردئون باز میشود که همهی
|
// ۳. مدیریت پروژه (/panel/pm)
|
||||||
// پروژههای تخصیصیافته را نشان میدهد؛ پروژهی فعال با «✓ فعلی» مشخص است و
|
// ۴. سازماندهی (/organization)
|
||||||
// انتخاب هر پروژه فقط «پروژهی فعال» را عوض میکند (نشست/توکن دستنخورده).
|
|
||||||
export function AppSwitcherMenu({
|
export function AppSwitcherMenu({
|
||||||
activeModule,
|
activeModule,
|
||||||
canSwitchToProcurement = true,
|
canSwitchToProcurement = true,
|
||||||
}: {
|
}: {
|
||||||
activeModule: "warehouse" | "procurement";
|
activeModule: "warehouse" | "procurement" | "organization";
|
||||||
canSwitchToProcurement?: boolean; // مدیر پروژه به دفتر تدارکات دسترسی ندارد
|
canSwitchToProcurement?: boolean;
|
||||||
}) {
|
}) {
|
||||||
const logout = useLogout();
|
const logout = useLogout();
|
||||||
const { pathname } = useLocation();
|
|
||||||
const user = useAuthStore((s) => s.user);
|
const user = useAuthStore((s) => s.user);
|
||||||
const setActiveProject = useAuthStore((s) => s.setActiveProject);
|
const panels = user?.panels ?? {};
|
||||||
|
|
||||||
|
const isAdmin = user?.role === "admin";
|
||||||
|
const hasPanelsConfig = Boolean(user?.panels && Object.keys(user.panels).length > 0);
|
||||||
|
|
||||||
|
const hasProcurement =
|
||||||
|
isAdmin ||
|
||||||
|
(hasPanelsConfig
|
||||||
|
? Boolean(panels.procurement)
|
||||||
|
: user?.role === "procurement_manager");
|
||||||
|
|
||||||
|
const hasInventory =
|
||||||
|
isAdmin ||
|
||||||
|
(hasPanelsConfig
|
||||||
|
? Boolean(panels.inventory)
|
||||||
|
: user?.role === "pm" || user?.role === "supervisor");
|
||||||
|
|
||||||
|
const hasPm =
|
||||||
|
isAdmin ||
|
||||||
|
(hasPanelsConfig
|
||||||
|
? Boolean(panels.pm)
|
||||||
|
: user?.role === "pm" || user?.role === "supervisor");
|
||||||
|
|
||||||
|
// فقط نقشهای ادمین، مدیر پروژه و مدیر تدارکات به پنل سازماندهی دسترسی دارند
|
||||||
|
const canManageOrg =
|
||||||
|
isAdmin ||
|
||||||
|
user?.role === "procurement_manager" ||
|
||||||
|
user?.role === "pm";
|
||||||
|
|
||||||
const items: MenuItem[] = [];
|
const items: MenuItem[] = [];
|
||||||
|
|
||||||
const isPm = user?.role === "pm";
|
if (hasInventory) {
|
||||||
const pmProjects = isPm ? user?.projects ?? [] : [];
|
items.push({
|
||||||
const projectChildren: MenuItem[] | undefined =
|
label: "انبار",
|
||||||
activeModule === "warehouse" && isPm
|
to: "/inventory",
|
||||||
? pmProjects.map((p) => ({
|
active: activeModule === "warehouse",
|
||||||
label: p.name,
|
});
|
||||||
to: pathname, // همان بخش فعلی؛ فقط پروژه عوض میشود
|
}
|
||||||
active: p.id === user?.project_id,
|
|
||||||
onClick: () => setActiveProject(p.id),
|
|
||||||
}))
|
|
||||||
: undefined;
|
|
||||||
|
|
||||||
if (activeModule === "procurement") {
|
if (hasProcurement && canSwitchToProcurement) {
|
||||||
items.push({ label: "مدیریت انبار", to: "/inventory" });
|
items.push({
|
||||||
items.push({ label: "مدیریت تدارکات", to: "/", active: true });
|
label: "تدارکات",
|
||||||
} else {
|
to: panels.procurement === "limited" && !isAdmin ? "/wizard" : "/",
|
||||||
items.push({ label: "مدیریت انبار", to: "/inventory", active: true, children: projectChildren });
|
active: activeModule === "procurement",
|
||||||
if (canSwitchToProcurement) {
|
});
|
||||||
items.push({ label: "مدیریت تدارکات", to: "/" });
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (hasPm) {
|
||||||
|
items.push({
|
||||||
|
label: "مدیریت پروژه",
|
||||||
|
to: "/panel/pm",
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (canManageOrg) {
|
||||||
|
items.push({
|
||||||
|
label: "سازماندهی",
|
||||||
|
to: "/organization",
|
||||||
|
active: activeModule === "organization",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
items.push({ divider: true });
|
items.push({ divider: true });
|
||||||
items.push({ label: "خروج از حساب", onClick: logout });
|
items.push({ label: "خروج از حساب", onClick: logout });
|
||||||
return <PanelMenu title="پنلها" items={items} />;
|
return <PanelMenu title="پنلها" items={items} />;
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { useEffect, useMemo, useState } from "react";
|
import { useEffect, useMemo, useState, type RefObject } from "react";
|
||||||
import { normalize } from "../lib/normalize";
|
import { normalize } from "../lib/normalize";
|
||||||
import { cn } from "../lib/utils";
|
import { cn } from "../lib/utils";
|
||||||
import { useClickOutside } from "./useClickOutside";
|
import { useClickOutside } from "./useClickOutside";
|
||||||
@@ -17,6 +17,7 @@ export interface ComboboxProps {
|
|||||||
onChange?: (item: ComboboxItem) => void;
|
onChange?: (item: ComboboxItem) => void;
|
||||||
items: ComboboxSource; // آرایه از string یا {id, name}
|
items: ComboboxSource; // آرایه از string یا {id, name}
|
||||||
allowAdd?: boolean; // دکمهی "+ افزودن به عنوان جدید"
|
allowAdd?: boolean; // دکمهی "+ افزودن به عنوان جدید"
|
||||||
|
addPrefix?: string; // قالب «+ {addPrefix} «متن»» — اگر داده شود بر addSuffix اولویت دارد
|
||||||
addSuffix?: string; // متن بعد از +
|
addSuffix?: string; // متن بعد از +
|
||||||
placeholder?: string;
|
placeholder?: string;
|
||||||
className?: string;
|
className?: string;
|
||||||
@@ -25,6 +26,8 @@ export interface ComboboxProps {
|
|||||||
onAdd?: (val: string) => void;
|
onAdd?: (val: string) => void;
|
||||||
onInputChange?: (val: string) => void;
|
onInputChange?: (val: string) => void;
|
||||||
onBlur?: () => void;
|
onBlur?: () => void;
|
||||||
|
// برای فوکوس برنامهای (مثل بازگشت فوکوس پس از ثبت پیوسته)
|
||||||
|
inputRef?: RefObject<HTMLInputElement | null>;
|
||||||
// با false، فوکوسِ برنامهای (مثل فوکوسِ خودکار Dialog) منو را باز نمیکند —
|
// با false، فوکوسِ برنامهای (مثل فوکوسِ خودکار Dialog) منو را باز نمیکند —
|
||||||
// فقط کلیک یا تایپِ صریح کاربر بازش میکند.
|
// فقط کلیک یا تایپِ صریح کاربر بازش میکند.
|
||||||
openOnFocus?: boolean;
|
openOnFocus?: boolean;
|
||||||
@@ -44,6 +47,7 @@ export function Combobox({
|
|||||||
onChange,
|
onChange,
|
||||||
items,
|
items,
|
||||||
allowAdd = true,
|
allowAdd = true,
|
||||||
|
addPrefix,
|
||||||
addSuffix = "به عنوان گزینه جدید",
|
addSuffix = "به عنوان گزینه جدید",
|
||||||
placeholder,
|
placeholder,
|
||||||
className,
|
className,
|
||||||
@@ -52,6 +56,7 @@ export function Combobox({
|
|||||||
onAdd,
|
onAdd,
|
||||||
onInputChange,
|
onInputChange,
|
||||||
onBlur,
|
onBlur,
|
||||||
|
inputRef,
|
||||||
openOnFocus = true,
|
openOnFocus = true,
|
||||||
}: ComboboxProps) {
|
}: ComboboxProps) {
|
||||||
const [text, setText] = useState(value ?? "");
|
const [text, setText] = useState(value ?? "");
|
||||||
@@ -125,6 +130,7 @@ export function Combobox({
|
|||||||
<div ref={ref} className={cn("relative", className)}>
|
<div ref={ref} className={cn("relative", className)}>
|
||||||
<input
|
<input
|
||||||
type="text"
|
type="text"
|
||||||
|
ref={inputRef}
|
||||||
className={cn(
|
className={cn(
|
||||||
"flex h-9 w-full rounded-lg border border-line bg-panel px-3 py-1 text-sm text-ink shadow-sm transition-colors placeholder:text-muted focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent/40 disabled:cursor-not-allowed disabled:opacity-50",
|
"flex h-9 w-full rounded-lg border border-line bg-panel px-3 py-1 text-sm text-ink shadow-sm transition-colors placeholder:text-muted focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent/40 disabled:cursor-not-allowed disabled:opacity-50",
|
||||||
inputClassName,
|
inputClassName,
|
||||||
@@ -182,9 +188,15 @@ export function Combobox({
|
|||||||
onMouseEnter={() => setHighlight(filtered.length)}
|
onMouseEnter={() => setHighlight(filtered.length)}
|
||||||
>
|
>
|
||||||
<span className="font-bold">+</span>
|
<span className="font-bold">+</span>
|
||||||
|
{addPrefix ? (
|
||||||
|
<span>
|
||||||
|
{addPrefix} «<b>{text.trim()}</b>»
|
||||||
|
</span>
|
||||||
|
) : (
|
||||||
<span>
|
<span>
|
||||||
«<b>{text.trim()}</b>» {addSuffix}
|
«<b>{text.trim()}</b>» {addSuffix}
|
||||||
</span>
|
</span>
|
||||||
|
)}
|
||||||
</button>
|
</button>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -21,6 +21,7 @@ export interface JalaliDatePickerProps {
|
|||||||
className?: string;
|
className?: string;
|
||||||
withTime?: boolean; // نمایش ساعت:دقیقه هم (پیشنهاد/پذیرش/رسید)
|
withTime?: boolean; // نمایش ساعت:دقیقه هم (پیشنهاد/پذیرش/رسید)
|
||||||
disabled?: boolean;
|
disabled?: boolean;
|
||||||
|
maxDate?: Date | string; // حداکثر تاریخ مجاز (جلوگیری از انتخاب تاریخ/زمان آینده)
|
||||||
}
|
}
|
||||||
|
|
||||||
function todayJalali(): [number, number, number] {
|
function todayJalali(): [number, number, number] {
|
||||||
@@ -76,6 +77,7 @@ export function JalaliDatePicker({
|
|||||||
className,
|
className,
|
||||||
withTime = false,
|
withTime = false,
|
||||||
disabled = false,
|
disabled = false,
|
||||||
|
maxDate,
|
||||||
}: JalaliDatePickerProps) {
|
}: JalaliDatePickerProps) {
|
||||||
const [open, setOpen] = useState(false);
|
const [open, setOpen] = useState(false);
|
||||||
const [curJ, setCurJ] = useState<[number, number, number]>(() => isoToJalali(value) ?? todayJalali());
|
const [curJ, setCurJ] = useState<[number, number, number]>(() => isoToJalali(value) ?? todayJalali());
|
||||||
@@ -83,6 +85,62 @@ export function JalaliDatePicker({
|
|||||||
const [hourText, setHourText] = useState<string>(() => faNum(String(initialTime.h).padStart(2, "0")));
|
const [hourText, setHourText] = useState<string>(() => faNum(String(initialTime.h).padStart(2, "0")));
|
||||||
const [minuteText, setMinuteText] = useState<string>(() => faNum(String(initialTime.m).padStart(2, "0")));
|
const [minuteText, setMinuteText] = useState<string>(() => faNum(String(initialTime.m).padStart(2, "0")));
|
||||||
|
|
||||||
|
const maxDateObj = useMemo(() => {
|
||||||
|
if (!maxDate) return null;
|
||||||
|
const d = typeof maxDate === "string" ? new Date(maxDate) : maxDate;
|
||||||
|
return Number.isNaN(d.getTime()) ? null : d;
|
||||||
|
}, [maxDate]);
|
||||||
|
|
||||||
|
const maxDateIso = useMemo(() => {
|
||||||
|
if (!maxDateObj) return null;
|
||||||
|
return `${maxDateObj.getFullYear()}-${String(maxDateObj.getMonth() + 1).padStart(2, "0")}-${String(maxDateObj.getDate()).padStart(2, "0")}`;
|
||||||
|
}, [maxDateObj]);
|
||||||
|
|
||||||
|
const maxJalaliParts = useMemo(() => {
|
||||||
|
if (!maxDateObj) return null;
|
||||||
|
return gregorianToJalali(maxDateObj.getFullYear(), maxDateObj.getMonth() + 1, maxDateObj.getDate());
|
||||||
|
}, [maxDateObj]);
|
||||||
|
|
||||||
|
const canGoNextMonth = useMemo(() => {
|
||||||
|
if (!maxJalaliParts) return true;
|
||||||
|
const [cy, cm] = curJ;
|
||||||
|
const [my, mm] = maxJalaliParts;
|
||||||
|
return cy < my || (cy === my && cm < mm);
|
||||||
|
}, [curJ, maxJalaliParts]);
|
||||||
|
|
||||||
|
const canGoNextYear = useMemo(() => {
|
||||||
|
if (!maxJalaliParts) return true;
|
||||||
|
return curJ[0] < maxJalaliParts[0];
|
||||||
|
}, [curJ, maxJalaliParts]);
|
||||||
|
|
||||||
|
const clampIfFuture = (iso: string | null): string | null => {
|
||||||
|
if (!iso || !maxDateObj) return iso;
|
||||||
|
const d = new Date(iso);
|
||||||
|
if (Number.isNaN(d.getTime())) return iso;
|
||||||
|
if (d.getTime() > maxDateObj.getTime()) {
|
||||||
|
return maxDateObj.toISOString();
|
||||||
|
}
|
||||||
|
return iso;
|
||||||
|
};
|
||||||
|
|
||||||
|
const getClampedTime = (h: number, m: number, jy: number, jm: number, jd: number): { h: number; m: number } => {
|
||||||
|
let validH = Math.min(23, Math.max(0, h));
|
||||||
|
let validM = Math.min(59, Math.max(0, m));
|
||||||
|
if (maxDateObj && maxDateIso) {
|
||||||
|
const [gy, gm, gd] = jalaliToGregorian(jy, jm, jd);
|
||||||
|
const dayIso = `${gy}-${String(gm).padStart(2, "0")}-${String(gd).padStart(2, "0")}`;
|
||||||
|
if (dayIso === maxDateIso) {
|
||||||
|
const maxH = maxDateObj.getHours();
|
||||||
|
const maxM = maxDateObj.getMinutes();
|
||||||
|
if (validH > maxH || (validH === maxH && validM > maxM)) {
|
||||||
|
validH = maxH;
|
||||||
|
validM = maxM;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return { h: validH, m: validM };
|
||||||
|
};
|
||||||
|
|
||||||
const [text, setText] = useState<string>(() => {
|
const [text, setText] = useState<string>(() => {
|
||||||
if (!value) return "";
|
if (!value) return "";
|
||||||
const j = isoToJalaliStr(value);
|
const j = isoToJalaliStr(value);
|
||||||
@@ -145,23 +203,30 @@ export function JalaliDatePicker({
|
|||||||
const dim = daysInMonth(jy, jm);
|
const dim = daysInMonth(jy, jm);
|
||||||
const today = new Date();
|
const today = new Date();
|
||||||
const tIso = `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, "0")}-${String(today.getDate()).padStart(2, "0")}`;
|
const tIso = `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, "0")}-${String(today.getDate()).padStart(2, "0")}`;
|
||||||
const cells: { d: number; iso: string; isToday: boolean }[] = [];
|
const cells: { d: number; iso: string; isToday: boolean; disabled: boolean }[] = [];
|
||||||
for (let i = 0; i < firstWd; i++) cells.push({ d: 0, iso: "", isToday: false });
|
for (let i = 0; i < firstWd; i++) cells.push({ d: 0, iso: "", isToday: false, disabled: false });
|
||||||
for (let d = 1; d <= dim; d++) {
|
for (let d = 1; d <= dim; d++) {
|
||||||
const [gy, gm, gd] = jalaliToGregorian(jy, jm, d);
|
const [gy, gm, gd] = jalaliToGregorian(jy, jm, d);
|
||||||
const iso = `${gy}-${String(gm).padStart(2, "0")}-${String(gd).padStart(2, "0")}`;
|
const iso = `${gy}-${String(gm).padStart(2, "0")}-${String(gd).padStart(2, "0")}`;
|
||||||
cells.push({ d, iso, isToday: iso === tIso });
|
const isDisabled = !!(maxDateIso && iso > maxDateIso);
|
||||||
|
cells.push({ d, iso, isToday: iso === tIso, disabled: isDisabled });
|
||||||
}
|
}
|
||||||
return cells;
|
return cells;
|
||||||
}, [curJ]);
|
}, [curJ, maxDateIso]);
|
||||||
|
|
||||||
const nav = (dir: string) => {
|
const nav = (dir: string) => {
|
||||||
setCurJ(([jy, jm]) => {
|
setCurJ(([jy, jm]) => {
|
||||||
let ny = jy;
|
let ny = jy;
|
||||||
let nm = jm;
|
let nm = jm;
|
||||||
if (dir === "m-1") nm = nm === 12 ? 1 : nm + 1;
|
if (dir === "m-1") {
|
||||||
|
if (!canGoNextMonth) return [jy, jm, 1];
|
||||||
|
nm = nm === 12 ? 1 : nm + 1;
|
||||||
|
}
|
||||||
if (dir === "m+1") nm = nm === 1 ? 12 : nm - 1;
|
if (dir === "m+1") nm = nm === 1 ? 12 : nm - 1;
|
||||||
if (dir === "y-1") ny += 1;
|
if (dir === "y-1") {
|
||||||
|
if (!canGoNextYear) return [jy, jm, 1];
|
||||||
|
ny += 1;
|
||||||
|
}
|
||||||
if (dir === "y+1") ny -= 1;
|
if (dir === "y+1") ny -= 1;
|
||||||
if (nm < 1) {
|
if (nm < 1) {
|
||||||
nm = 12;
|
nm = 12;
|
||||||
@@ -171,15 +236,27 @@ export function JalaliDatePicker({
|
|||||||
nm = 1;
|
nm = 1;
|
||||||
ny += 1;
|
ny += 1;
|
||||||
}
|
}
|
||||||
|
if (maxJalaliParts) {
|
||||||
|
if (ny > maxJalaliParts[0] || (ny === maxJalaliParts[0] && nm > maxJalaliParts[1])) {
|
||||||
|
ny = maxJalaliParts[0];
|
||||||
|
nm = maxJalaliParts[1];
|
||||||
|
}
|
||||||
|
}
|
||||||
return [ny, nm, 1];
|
return [ny, nm, 1];
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
const selectDay = (jy: number, jm: number, jd: number) => {
|
const selectDay = (jy: number, jm: number, jd: number) => {
|
||||||
|
const [gy, gm, gd] = jalaliToGregorian(jy, jm, jd);
|
||||||
|
const dayIso = `${gy}-${String(gm).padStart(2, "0")}-${String(gd).padStart(2, "0")}`;
|
||||||
|
if (maxDateIso && dayIso > maxDateIso) return;
|
||||||
|
|
||||||
const currentH = parseInt(toAsciiDigits(hourText) || "0", 10);
|
const currentH = parseInt(toAsciiDigits(hourText) || "0", 10);
|
||||||
const currentM = parseInt(toAsciiDigits(minuteText) || "0", 10);
|
const currentM = parseInt(toAsciiDigits(minuteText) || "0", 10);
|
||||||
const validH = Math.min(23, Math.max(0, currentH));
|
const { h: validH, m: validM } = getClampedTime(currentH, currentM, jy, jm, jd);
|
||||||
const validM = Math.min(59, Math.max(0, currentM));
|
setHourText(faNum(String(validH).padStart(2, "0")));
|
||||||
|
setMinuteText(faNum(String(validM).padStart(2, "0")));
|
||||||
|
|
||||||
const val = withTime ? buildIso(jy, jm, jd, validH, validM) : buildDateOnly(jy, jm, jd);
|
const val = withTime ? buildIso(jy, jm, jd, validH, validM) : buildDateOnly(jy, jm, jd);
|
||||||
onChange(val);
|
onChange(val);
|
||||||
setText(
|
setText(
|
||||||
@@ -200,30 +277,28 @@ export function JalaliDatePicker({
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const n = parseInt(digits, 10);
|
const n = parseInt(digits, 10);
|
||||||
const clamped = Math.min(23, Math.max(0, n));
|
|
||||||
const textToShow = digits.length === 2 && n > 23 ? String(clamped) : digits;
|
|
||||||
setHourText(faNum(textToShow));
|
|
||||||
|
|
||||||
const [jy, jm, jd] = curJ;
|
const [jy, jm, jd] = curJ;
|
||||||
const currentM = parseInt(toAsciiDigits(minuteText) || "0", 10);
|
const currentM = parseInt(toAsciiDigits(minuteText) || "0", 10);
|
||||||
const validM = Math.min(59, Math.max(0, currentM));
|
const { h: clampedH, m: validM } = getClampedTime(n, currentM, jy, jm, jd);
|
||||||
onChange(buildIso(jy, jm, jd, clamped, validM));
|
const textToShow = digits.length === 2 && n > 23 ? String(clampedH) : digits;
|
||||||
const j = value ? isoToJalaliStr(value) : isoToJalaliStr(buildIso(jy, jm, jd, clamped, validM));
|
setHourText(faNum(textToShow));
|
||||||
setText(`${j} ${faNum(String(clamped).padStart(2, "0") + ":" + String(validM).padStart(2, "0"))}`);
|
|
||||||
|
onChange(buildIso(jy, jm, jd, clampedH, validM));
|
||||||
|
const j = value ? isoToJalaliStr(value) : isoToJalaliStr(buildIso(jy, jm, jd, clampedH, validM));
|
||||||
|
setText(`${j} ${faNum(String(clampedH).padStart(2, "0") + ":" + String(validM).padStart(2, "0"))}`);
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleHourBlur = () => {
|
const handleHourBlur = () => {
|
||||||
const digits = toAsciiDigits(hourText).replace(/\D/g, "");
|
const digits = toAsciiDigits(hourText).replace(/\D/g, "");
|
||||||
const n = digits ? parseInt(digits, 10) : 0;
|
const n = digits ? parseInt(digits, 10) : 0;
|
||||||
const clamped = Math.min(23, Math.max(0, n));
|
|
||||||
setHourText(faNum(String(clamped).padStart(2, "0")));
|
|
||||||
|
|
||||||
const [jy, jm, jd] = curJ;
|
const [jy, jm, jd] = curJ;
|
||||||
const currentM = parseInt(toAsciiDigits(minuteText) || "0", 10);
|
const currentM = parseInt(toAsciiDigits(minuteText) || "0", 10);
|
||||||
const validM = Math.min(59, Math.max(0, currentM));
|
const { h: clampedH, m: validM } = getClampedTime(n, currentM, jy, jm, jd);
|
||||||
onChange(buildIso(jy, jm, jd, clamped, validM));
|
setHourText(faNum(String(clampedH).padStart(2, "0")));
|
||||||
const j = value ? isoToJalaliStr(value) : isoToJalaliStr(buildIso(jy, jm, jd, clamped, validM));
|
|
||||||
setText(`${j} ${faNum(String(clamped).padStart(2, "0") + ":" + String(validM).padStart(2, "0"))}`);
|
onChange(buildIso(jy, jm, jd, clampedH, validM));
|
||||||
|
const j = value ? isoToJalaliStr(value) : isoToJalaliStr(buildIso(jy, jm, jd, clampedH, validM));
|
||||||
|
setText(`${j} ${faNum(String(clampedH).padStart(2, "0") + ":" + String(validM).padStart(2, "0"))}`);
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleMinuteChange = (raw: string) => {
|
const handleMinuteChange = (raw: string) => {
|
||||||
@@ -238,37 +313,46 @@ export function JalaliDatePicker({
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const n = parseInt(digits, 10);
|
const n = parseInt(digits, 10);
|
||||||
const clamped = Math.min(59, Math.max(0, n));
|
|
||||||
const textToShow = digits.length === 2 && n > 59 ? String(clamped) : digits;
|
|
||||||
setMinuteText(faNum(textToShow));
|
|
||||||
|
|
||||||
const [jy, jm, jd] = curJ;
|
const [jy, jm, jd] = curJ;
|
||||||
const currentH = parseInt(toAsciiDigits(hourText) || "0", 10);
|
const currentH = parseInt(toAsciiDigits(hourText) || "0", 10);
|
||||||
const validH = Math.min(23, Math.max(0, currentH));
|
const { h: validH, m: clampedM } = getClampedTime(currentH, n, jy, jm, jd);
|
||||||
onChange(buildIso(jy, jm, jd, validH, clamped));
|
const textToShow = digits.length === 2 && n > 59 ? String(clampedM) : digits;
|
||||||
const j = value ? isoToJalaliStr(value) : isoToJalaliStr(buildIso(jy, jm, jd, validH, clamped));
|
setMinuteText(faNum(textToShow));
|
||||||
setText(`${j} ${faNum(String(validH).padStart(2, "0") + ":" + String(clamped).padStart(2, "0"))}`);
|
|
||||||
|
onChange(buildIso(jy, jm, jd, validH, clampedM));
|
||||||
|
const j = value ? isoToJalaliStr(value) : isoToJalaliStr(buildIso(jy, jm, jd, validH, clampedM));
|
||||||
|
setText(`${j} ${faNum(String(validH).padStart(2, "0") + ":" + String(clampedM).padStart(2, "0"))}`);
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleMinuteBlur = () => {
|
const handleMinuteBlur = () => {
|
||||||
const digits = toAsciiDigits(minuteText).replace(/\D/g, "");
|
const digits = toAsciiDigits(minuteText).replace(/\D/g, "");
|
||||||
const n = digits ? parseInt(digits, 10) : 0;
|
const n = digits ? parseInt(digits, 10) : 0;
|
||||||
const clamped = Math.min(59, Math.max(0, n));
|
|
||||||
setMinuteText(faNum(String(clamped).padStart(2, "0")));
|
|
||||||
|
|
||||||
const [jy, jm, jd] = curJ;
|
const [jy, jm, jd] = curJ;
|
||||||
const currentH = parseInt(toAsciiDigits(hourText) || "0", 10);
|
const currentH = parseInt(toAsciiDigits(hourText) || "0", 10);
|
||||||
const validH = Math.min(23, Math.max(0, currentH));
|
const { h: validH, m: clampedM } = getClampedTime(currentH, n, jy, jm, jd);
|
||||||
onChange(buildIso(jy, jm, jd, validH, clamped));
|
setMinuteText(faNum(String(clampedM).padStart(2, "0")));
|
||||||
const j = value ? isoToJalaliStr(value) : isoToJalaliStr(buildIso(jy, jm, jd, validH, clamped));
|
|
||||||
setText(`${j} ${faNum(String(validH).padStart(2, "0") + ":" + String(clamped).padStart(2, "0"))}`);
|
onChange(buildIso(jy, jm, jd, validH, clampedM));
|
||||||
|
const j = value ? isoToJalaliStr(value) : isoToJalaliStr(buildIso(jy, jm, jd, validH, clampedM));
|
||||||
|
setText(`${j} ${faNum(String(validH).padStart(2, "0") + ":" + String(clampedM).padStart(2, "0"))}`);
|
||||||
};
|
};
|
||||||
|
|
||||||
const pickToday = () => {
|
const pickToday = () => {
|
||||||
const now = new Date();
|
const now = new Date();
|
||||||
const [jy, jm, jd] = todayJalali();
|
const [jy, jm, jd] = todayJalali();
|
||||||
const nh = now.getHours();
|
let nh = now.getHours();
|
||||||
const nm = now.getMinutes();
|
let nm = now.getMinutes();
|
||||||
|
if (maxDateObj) {
|
||||||
|
const [gy, gm, gd] = jalaliToGregorian(jy, jm, jd);
|
||||||
|
const todayIso = `${gy}-${String(gm).padStart(2, "0")}-${String(gd).padStart(2, "0")}`;
|
||||||
|
if (maxDateIso && todayIso > maxDateIso) return;
|
||||||
|
if (todayIso === maxDateIso) {
|
||||||
|
if (nh > maxDateObj.getHours() || (nh === maxDateObj.getHours() && nm > maxDateObj.getMinutes())) {
|
||||||
|
nh = maxDateObj.getHours();
|
||||||
|
nm = maxDateObj.getMinutes();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
setHourText(faNum(String(nh).padStart(2, "0")));
|
setHourText(faNum(String(nh).padStart(2, "0")));
|
||||||
setMinuteText(faNum(String(nm).padStart(2, "0")));
|
setMinuteText(faNum(String(nm).padStart(2, "0")));
|
||||||
const val = withTime
|
const val = withTime
|
||||||
@@ -300,20 +384,23 @@ export function JalaliDatePicker({
|
|||||||
}
|
}
|
||||||
const iso = jalaliStrToIso(v);
|
const iso = jalaliStrToIso(v);
|
||||||
if (iso) {
|
if (iso) {
|
||||||
|
const validIso = clampIfFuture(iso) || iso;
|
||||||
if (!withTime) {
|
if (!withTime) {
|
||||||
const nums = String(v)
|
const nums = String(v)
|
||||||
.split(/[/\-.]/)
|
.split(/[/\-.]/)
|
||||||
.map((x) => parseInt(toAsciiDigits(x), 10));
|
.map((x) => parseInt(toAsciiDigits(x), 10));
|
||||||
if (nums.length >= 3 && !nums.some((n) => Number.isNaN(n))) {
|
if (nums.length >= 3 && !nums.some((n) => Number.isNaN(n))) {
|
||||||
const [gy, gm, gd] = jalaliToGregorian(nums[0], nums[1], nums[2]);
|
const [gy, gm, gd] = jalaliToGregorian(nums[0], nums[1], nums[2]);
|
||||||
onChange(`${gy}-${String(gm).padStart(2, "0")}-${String(gd).padStart(2, "0")}`);
|
let dOnly = `${gy}-${String(gm).padStart(2, "0")}-${String(gd).padStart(2, "0")}`;
|
||||||
|
if (maxDateIso && dOnly > maxDateIso) dOnly = maxDateIso;
|
||||||
|
onChange(dOnly);
|
||||||
} else {
|
} else {
|
||||||
onChange(iso.slice(0, 10));
|
onChange(validIso.slice(0, 10));
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
onChange(iso);
|
onChange(validIso);
|
||||||
}
|
}
|
||||||
const j = isoToJalali(iso);
|
const j = isoToJalali(validIso);
|
||||||
if (j) setCurJ([j[0], j[1], j[2]]);
|
if (j) setCurJ([j[0], j[1], j[2]]);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@@ -325,27 +412,32 @@ export function JalaliDatePicker({
|
|||||||
}
|
}
|
||||||
const iso = jalaliStrToIso(text);
|
const iso = jalaliStrToIso(text);
|
||||||
if (iso) {
|
if (iso) {
|
||||||
|
const validIso = clampIfFuture(iso) || iso;
|
||||||
if (!withTime) {
|
if (!withTime) {
|
||||||
const nums = String(text)
|
const nums = String(text)
|
||||||
.split(/[/\-.]/)
|
.split(/[/\-.]/)
|
||||||
.map((x) => parseInt(toAsciiDigits(x), 10));
|
.map((x) => parseInt(toAsciiDigits(x), 10));
|
||||||
if (nums.length >= 3 && !nums.some((n) => Number.isNaN(n))) {
|
if (nums.length >= 3 && !nums.some((n) => Number.isNaN(n))) {
|
||||||
const [gy, gm, gd] = jalaliToGregorian(nums[0], nums[1], nums[2]);
|
const [gy, gm, gd] = jalaliToGregorian(nums[0], nums[1], nums[2]);
|
||||||
const dOnly = `${gy}-${String(gm).padStart(2, "0")}-${String(gd).padStart(2, "0")}`;
|
let dOnly = `${gy}-${String(gm).padStart(2, "0")}-${String(gd).padStart(2, "0")}`;
|
||||||
|
if (maxDateIso && dOnly > maxDateIso) dOnly = maxDateIso;
|
||||||
onChange(dOnly);
|
onChange(dOnly);
|
||||||
setText(isoToJalaliStr(dOnly));
|
setText(isoToJalaliStr(dOnly));
|
||||||
} else {
|
} else {
|
||||||
onChange(iso.slice(0, 10));
|
const dOnly = validIso.slice(0, 10);
|
||||||
setText(isoToJalaliStr(iso));
|
onChange(dOnly);
|
||||||
|
setText(isoToJalaliStr(dOnly));
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
onChange(iso);
|
onChange(validIso);
|
||||||
const j = isoToJalaliStr(iso);
|
const j = isoToJalaliStr(validIso);
|
||||||
const d = new Date(iso);
|
const d = new Date(validIso);
|
||||||
if (!Number.isNaN(d.getTime())) {
|
if (!Number.isNaN(d.getTime())) {
|
||||||
const hh = String(d.getHours()).padStart(2, "0");
|
const hh = String(d.getHours()).padStart(2, "0");
|
||||||
const mm = String(d.getMinutes()).padStart(2, "0");
|
const mm = String(d.getMinutes()).padStart(2, "0");
|
||||||
setText(`${j} ${faNum(hh + ":" + mm)}`);
|
setText(`${j} ${faNum(hh + ":" + mm)}`);
|
||||||
|
setHourText(faNum(hh));
|
||||||
|
setMinuteText(faNum(mm));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else if (value) {
|
} else if (value) {
|
||||||
@@ -397,10 +489,22 @@ export function JalaliDatePicker({
|
|||||||
<span className="text-[13px] font-bold">
|
<span className="text-[13px] font-bold">
|
||||||
{MONTHS[curJ[1] - 1]} {toFa(curJ[0])}
|
{MONTHS[curJ[1] - 1]} {toFa(curJ[0])}
|
||||||
</span>
|
</span>
|
||||||
<button type="button" className="cursor-pointer rounded px-1.5 text-sm hover:bg-slate-bg" onClick={() => nav("m-1")}>
|
<button
|
||||||
|
type="button"
|
||||||
|
disabled={!canGoNextMonth}
|
||||||
|
className={cn("rounded px-1.5 text-sm", canGoNextMonth ? "cursor-pointer hover:bg-slate-bg" : "opacity-25 cursor-not-allowed text-muted")}
|
||||||
|
onClick={() => canGoNextMonth && nav("m-1")}
|
||||||
|
title={canGoNextMonth ? "ماه بعد" : "امکان انتخاب تاریخ آینده وجود ندارد"}
|
||||||
|
>
|
||||||
›
|
›
|
||||||
</button>
|
</button>
|
||||||
<button type="button" className="cursor-pointer rounded px-1.5 text-sm hover:bg-slate-bg" onClick={() => nav("y-1")}>
|
<button
|
||||||
|
type="button"
|
||||||
|
disabled={!canGoNextYear}
|
||||||
|
className={cn("rounded px-1.5 text-sm", canGoNextYear ? "cursor-pointer hover:bg-slate-bg" : "opacity-25 cursor-not-allowed text-muted")}
|
||||||
|
onClick={() => canGoNextYear && nav("y-1")}
|
||||||
|
title={canGoNextYear ? "سال بعد" : "امکان انتخاب تاریخ آینده وجود ندارد"}
|
||||||
|
>
|
||||||
»
|
»
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
@@ -415,6 +519,16 @@ export function JalaliDatePicker({
|
|||||||
{grid.map((cell, i) =>
|
{grid.map((cell, i) =>
|
||||||
cell.d === 0 ? (
|
cell.d === 0 ? (
|
||||||
<div key={i} />
|
<div key={i} />
|
||||||
|
) : cell.disabled ? (
|
||||||
|
<button
|
||||||
|
key={i}
|
||||||
|
type="button"
|
||||||
|
disabled
|
||||||
|
className="rounded py-0.5 text-[12px] opacity-25 text-muted cursor-not-allowed max-md:py-1.5"
|
||||||
|
title="امکان انتخاب تاریخ آینده وجود ندارد"
|
||||||
|
>
|
||||||
|
{toFa(cell.d)}
|
||||||
|
</button>
|
||||||
) : (
|
) : (
|
||||||
<button
|
<button
|
||||||
key={i}
|
key={i}
|
||||||
|
|||||||
@@ -6,6 +6,8 @@ import { cn } from "../lib/utils";
|
|||||||
export interface MenuItem {
|
export interface MenuItem {
|
||||||
label?: string;
|
label?: string;
|
||||||
to?: string;
|
to?: string;
|
||||||
|
// لینک خارجی (اپ جداگانه، مثل سامانه PM) — در تب جدید باز میشود
|
||||||
|
href?: string;
|
||||||
active?: boolean;
|
active?: boolean;
|
||||||
divider?: boolean;
|
divider?: boolean;
|
||||||
onClick?: () => void;
|
onClick?: () => void;
|
||||||
@@ -112,6 +114,21 @@ export function PanelMenu({ items, title }: { items: MenuItem[]; title?: string
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
) : it.href ? (
|
||||||
|
<a
|
||||||
|
key={i}
|
||||||
|
href={it.href}
|
||||||
|
target="_blank"
|
||||||
|
rel="noopener noreferrer"
|
||||||
|
onClick={() => setOpen(false)}
|
||||||
|
className={cn(
|
||||||
|
"flex items-center justify-between gap-3 rounded-lg px-3 py-2 text-[13px] no-underline",
|
||||||
|
it.active ? "bg-accent font-bold text-white" : "text-ink hover:bg-slate-bg",
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{it.label}
|
||||||
|
<span aria-hidden className="text-[10px] opacity-60">↗</span>
|
||||||
|
</a>
|
||||||
) : it.to ? (
|
) : it.to ? (
|
||||||
<Link
|
<Link
|
||||||
key={i}
|
key={i}
|
||||||
|
|||||||
@@ -16,11 +16,13 @@ export function RequirePmProjects({ children }: { children: ReactNode }) {
|
|||||||
const setProjects = useAuthStore((s) => s.setProjects);
|
const setProjects = useAuthStore((s) => s.setProjects);
|
||||||
const logout = useLogout();
|
const logout = useLogout();
|
||||||
|
|
||||||
const isPm = user?.role === "pm";
|
// پنل انبار limited هم مثل سرپرست: پروژههای فعالش از عضویتها اعتبارسنجی میشود
|
||||||
const [state, setState] = useState<"loading" | "ok" | "empty">(isPm ? "loading" : "ok");
|
const isSupervisor = user?.role === "supervisor" || user?.panels?.inventory === "limited";
|
||||||
|
const [state, setState] = useState<"loading" | "ok" | "empty">(isSupervisor ? "loading" : "ok");
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!user || user.role !== "pm") {
|
const scoped = user?.role === "supervisor" || user?.panels?.inventory === "limited";
|
||||||
|
if (!user || !scoped) {
|
||||||
setState("ok");
|
setState("ok");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -45,7 +47,7 @@ export function RequirePmProjects({ children }: { children: ReactNode }) {
|
|||||||
alive = false;
|
alive = false;
|
||||||
};
|
};
|
||||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
}, [user?.id, user?.role, isDev]);
|
}, [user?.id, user?.role, user?.panels, isDev]);
|
||||||
|
|
||||||
if (state === "loading") {
|
if (state === "loading") {
|
||||||
return (
|
return (
|
||||||
|
|||||||
@@ -2,6 +2,23 @@ import type { ReactNode } from "react";
|
|||||||
import { useLocation, useNavigate } from "react-router-dom";
|
import { useLocation, useNavigate } from "react-router-dom";
|
||||||
import { ChevronRight, ClipboardList } from "lucide-react";
|
import { ChevronRight, ClipboardList } from "lucide-react";
|
||||||
import { cn } from "../../lib/utils";
|
import { cn } from "../../lib/utils";
|
||||||
|
import { useAuthStore, type AuthUser } from "../../store/auth";
|
||||||
|
|
||||||
|
const ROLE_LABELS: Record<string, string> = {
|
||||||
|
admin: "ادمین",
|
||||||
|
procurement_manager: "مدیر تدارکات",
|
||||||
|
pm: "مدیر پروژه",
|
||||||
|
supervisor: "سرپرست پروژه",
|
||||||
|
};
|
||||||
|
|
||||||
|
export function userSubtitle(user: AuthUser | null | undefined): string {
|
||||||
|
if (!user) return "";
|
||||||
|
const fullName = `${user.first_name || ""} ${user.last_name || ""}`.trim() || user.display_name || "کاربر";
|
||||||
|
const username = user.username || user.casdoor_id || "-";
|
||||||
|
const role = user.role_label || (user.role ? ROLE_LABELS[user.role] : "بدون نقش");
|
||||||
|
const proj = user.role === "supervisor" && user.project_name ? ` – پروژه: ${user.project_name}` : "";
|
||||||
|
return `${fullName} | نام کاربری: ${username} | نقش: ${role}${proj}`;
|
||||||
|
}
|
||||||
|
|
||||||
interface HeaderProps {
|
interface HeaderProps {
|
||||||
title: string;
|
title: string;
|
||||||
@@ -18,6 +35,10 @@ interface HeaderProps {
|
|||||||
export function Header({ title, sub, backTo, backLabel = "بازگشت", actions, brand, icon, menu }: HeaderProps) {
|
export function Header({ title, sub, backTo, backLabel = "بازگشت", actions, brand, icon, menu }: HeaderProps) {
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
const location = useLocation();
|
const location = useLocation();
|
||||||
|
const user = useAuthStore((s) => s.user);
|
||||||
|
|
||||||
|
const userSub = userSubtitle(user);
|
||||||
|
const displaySub = sub !== undefined ? sub : userSub;
|
||||||
|
|
||||||
// اگر کاربر از داخل برنامه به این صفحه آمده، یک قدم برمیگردیم؛
|
// اگر کاربر از داخل برنامه به این صفحه آمده، یک قدم برمیگردیم؛
|
||||||
// اگر مستقیم باز شده (بدون سابقهی داخلی)، به backTo میرویم.
|
// اگر مستقیم باز شده (بدون سابقهی داخلی)، به backTo میرویم.
|
||||||
@@ -47,7 +68,7 @@ export function Header({ title, sub, backTo, backLabel = "بازگشت", actions
|
|||||||
<div className="flex min-w-0 items-center gap-2.5">
|
<div className="flex min-w-0 items-center gap-2.5">
|
||||||
<div className="min-w-0">
|
<div className="min-w-0">
|
||||||
<h1 className="text-[17px] font-extrabold leading-6">{title}</h1>
|
<h1 className="text-[17px] font-extrabold leading-6">{title}</h1>
|
||||||
{sub && <div className="text-[11px] text-muted">{sub}</div>}
|
{displaySub && <div className="text-[11.5px] text-muted font-normal mt-0.5">{displaySub}</div>}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="ms-auto flex flex-wrap items-center gap-2">{actions}</div>
|
<div className="ms-auto flex flex-wrap items-center gap-2">{actions}</div>
|
||||||
|
|||||||
@@ -8,7 +8,6 @@ import {
|
|||||||
PackageSearch,
|
PackageSearch,
|
||||||
Scale,
|
Scale,
|
||||||
Truck,
|
Truck,
|
||||||
UsersRound,
|
|
||||||
type LucideIcon,
|
type LucideIcon,
|
||||||
} from "lucide-react";
|
} from "lucide-react";
|
||||||
import { cn } from "../../lib/utils";
|
import { cn } from "../../lib/utils";
|
||||||
@@ -37,12 +36,12 @@ const PM_INV_TABS: TabDef[] = [
|
|||||||
{ to: "/inventory/arrivals", label: "کالاهای در راه", icon: PackageSearch },
|
{ to: "/inventory/arrivals", label: "کالاهای در راه", icon: PackageSearch },
|
||||||
];
|
];
|
||||||
|
|
||||||
// تبهای پنل انبار برای ادمین / مدیر تدارکات (آینهی ناوبری بالای دسکتاپ)
|
// تبهای پنل انبار برای ادمین / مدیر تدارکات / مدیر پروژه (آینهی ناوبری بالای دسکتاپ)
|
||||||
const ADMIN_INV_TABS: TabDef[] = [
|
const ADMIN_INV_TABS: TabDef[] = [
|
||||||
{ to: "/inventory", label: "انبار", icon: Boxes, end: true },
|
{ to: "/inventory", label: "انبار", icon: Boxes, end: true },
|
||||||
{ to: "/inventory/daily", label: "کنترل روزانه", icon: CalendarDays },
|
{ to: "/inventory/daily", label: "کنترل روزانه", icon: CalendarDays },
|
||||||
|
{ to: "/inventory/warehouses", label: "انبارها", icon: Building2 },
|
||||||
{ to: "/inventory/arrivals", label: "کالاهای در راه", icon: PackageSearch },
|
{ to: "/inventory/arrivals", label: "کالاهای در راه", icon: PackageSearch },
|
||||||
{ to: "/inventory/org", label: "سازماندهی", icon: UsersRound },
|
|
||||||
];
|
];
|
||||||
|
|
||||||
function TabBar({ tabs }: { tabs: TabDef[] }) {
|
function TabBar({ tabs }: { tabs: TabDef[] }) {
|
||||||
@@ -81,14 +80,24 @@ export function MobileTabBar() {
|
|||||||
const { pathname } = useLocation();
|
const { pathname } = useLocation();
|
||||||
|
|
||||||
if (pathname === "/login" || pathname === "/admin") return null;
|
if (pathname === "/login" || pathname === "/admin") return null;
|
||||||
|
// خانه حداقلی استعلام (تدارکات limited): بدون تب ERP — PM هم تببار خودش را دارد
|
||||||
|
if (pathname === "/requester" || pathname === "/panel/pm") return null;
|
||||||
|
// کاربر فقطِ تدارکات-limited: تبهای انبار/دفتر ندارد
|
||||||
|
const panels = useAuthStore.getState().user?.panels ?? {};
|
||||||
|
if (panels.procurement === "limited" && !panels.inventory && !panels.pm) return null;
|
||||||
|
// پنل مدیریت پروژه: iframe تمامصفحهی PM است و خودش تببار داخلی دارد
|
||||||
|
if (pathname === "/panel/pm") return null;
|
||||||
const isPM = role === "pm";
|
const isPM = role === "pm";
|
||||||
|
const isSupervisor = role === "supervisor";
|
||||||
const isOffice = role === "admin" || role === "procurement_manager";
|
const isOffice = role === "admin" || role === "procurement_manager";
|
||||||
|
|
||||||
if (pathname.startsWith("/inventory")) {
|
if (pathname.startsWith("/inventory")) {
|
||||||
if (isPM) return <TabBar tabs={PM_INV_TABS} />;
|
if (isPM) return <TabBar tabs={PM_INV_TABS} />;
|
||||||
if (isOffice) return <TabBar tabs={ADMIN_INV_TABS} />;
|
if (isOffice || isSupervisor) return <TabBar tabs={ADMIN_INV_TABS} />;
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
// سرپرست پروژه به بخشهای تدارکات/دفتر دسترسی ندارد
|
||||||
|
if (isSupervisor) return null;
|
||||||
if (pathname === "/wizard" || pathname.startsWith("/review")) return null;
|
if (pathname === "/wizard" || pathname.startsWith("/review")) return null;
|
||||||
const onOfficePage =
|
const onOfficePage =
|
||||||
pathname === "/" ||
|
pathname === "/" ||
|
||||||
|
|||||||
@@ -2,5 +2,5 @@ export { useStoreData, useInvalidateStore, refreshProcurementStore } from "./use
|
|||||||
export { useQuotes, useCreateQuote, useUpdateQuote, useDeleteQuote } from "./useQuotes";
|
export { useQuotes, useCreateQuote, useUpdateQuote, useDeleteQuote } from "./useQuotes";
|
||||||
export { useSuppliers, useAddSupplier, useUpdateSupplier, useRemoveSupplier } from "./useSuppliers";
|
export { useSuppliers, useAddSupplier, useUpdateSupplier, useRemoveSupplier } from "./useSuppliers";
|
||||||
export { useMaterials, useAddMaterial } from "./useMaterials";
|
export { useMaterials, useAddMaterial } from "./useMaterials";
|
||||||
export { useProjects, useAddProject } from "./useProjects";
|
export { useProjects, useAddProject, useDeleteProject } from "./useProjects";
|
||||||
export { useUnits, useSaveStandardConversion, useDeleteStandardConversion } from "./useUnits";
|
export { useUnits, useSaveStandardConversion, useDeleteStandardConversion } from "./useUnits";
|
||||||
|
|||||||
@@ -21,3 +21,15 @@ export function useAddProject() {
|
|||||||
onSettled: () => invalidate(),
|
onSettled: () => invalidate(),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function useDeleteProject() {
|
||||||
|
const deleteProject = useAppStore((s) => s.deleteProject);
|
||||||
|
const invalidate = useInvalidateStore();
|
||||||
|
return useMutation({
|
||||||
|
mutationFn: (id: string) => api.projects.delete(id),
|
||||||
|
onMutate: (id) => deleteProject(id),
|
||||||
|
onSettled: () => invalidate(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
+187
-19
@@ -30,6 +30,10 @@ import type {
|
|||||||
Supplier,
|
Supplier,
|
||||||
TransactionType,
|
TransactionType,
|
||||||
Warehouse,
|
Warehouse,
|
||||||
|
ProjectTransfer,
|
||||||
|
ProjectTransferCreateIn,
|
||||||
|
ProjectTransferUpdateIn,
|
||||||
|
ProjectTransferReceiveIn,
|
||||||
} from "./types";
|
} from "./types";
|
||||||
|
|
||||||
const BASE_URL = (import.meta.env?.VITE_API_BASE_URL as string | undefined)?.trim() || "/api/v1";
|
const BASE_URL = (import.meta.env?.VITE_API_BASE_URL as string | undefined)?.trim() || "/api/v1";
|
||||||
@@ -87,7 +91,7 @@ function handle401(path: string, res: Response): void {
|
|||||||
// ادمین/مدیر تدارکات بدون پارامتر (همهی پروژهها) باقی میماند.
|
// ادمین/مدیر تدارکات بدون پارامتر (همهی پروژهها) باقی میماند.
|
||||||
function activeProjectId(): string | null {
|
function activeProjectId(): string | null {
|
||||||
const { user } = useAuthStore.getState();
|
const { user } = useAuthStore.getState();
|
||||||
return user?.role === "pm" ? user.project_id : null;
|
return user?.role === "supervisor" || user?.role === "pm" ? user.project_id : null;
|
||||||
}
|
}
|
||||||
|
|
||||||
function projectQuery(projectId?: string | null): string {
|
function projectQuery(projectId?: string | null): string {
|
||||||
@@ -239,20 +243,36 @@ async function request<T>(path: string, init?: RequestInit): Promise<T> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function getData<T>(path: string): Promise<T> {
|
async function getData<T>(path: string): Promise<T> {
|
||||||
const res = await request<{ data: T }>(path);
|
const res = await request<any>(path);
|
||||||
return res.data;
|
if (res && typeof res === "object" && "data" in res) {
|
||||||
|
return res.data as T;
|
||||||
|
}
|
||||||
|
return res as T;
|
||||||
}
|
}
|
||||||
async function postData<T>(path: string, body: unknown): Promise<T> {
|
async function postData<T>(path: string, body: unknown): Promise<T> {
|
||||||
const res = await request<{ data: T }>(path, { method: "POST", body: JSON.stringify(body) });
|
const res = await request<any>(path, { method: "POST", body: JSON.stringify(body) });
|
||||||
return res.data;
|
if (res && typeof res === "object" && "data" in res) {
|
||||||
|
return res.data as T;
|
||||||
|
}
|
||||||
|
return res as T;
|
||||||
}
|
}
|
||||||
async function patchData<T>(path: string, body: unknown): Promise<T> {
|
async function patchData<T>(path: string, body: unknown): Promise<T> {
|
||||||
const res = await request<{ data: T }>(path, { method: "PATCH", body: JSON.stringify(body) });
|
const res = await request<any>(path, { method: "PATCH", body: JSON.stringify(body) });
|
||||||
|
if (res && typeof res === "object" && "data" in res) {
|
||||||
|
return res.data as T;
|
||||||
|
}
|
||||||
|
return res as T;
|
||||||
|
}
|
||||||
|
async function putData<T>(path: string, body: unknown): Promise<T> {
|
||||||
|
const res = await request<{ data: T }>(path, { method: "PUT", body: JSON.stringify(body) });
|
||||||
return res.data;
|
return res.data;
|
||||||
}
|
}
|
||||||
async function deleteData<T>(path: string): Promise<T> {
|
async function deleteData<T>(path: string): Promise<T> {
|
||||||
const res = await request<{ data: T }>(path, { method: "DELETE" });
|
const res = await request<any>(path, { method: "DELETE" });
|
||||||
return res.data;
|
if (res && typeof res === "object" && "data" in res) {
|
||||||
|
return res.data as T;
|
||||||
|
}
|
||||||
|
return res as T;
|
||||||
}
|
}
|
||||||
|
|
||||||
// آپلود چندبخشی (multipart) — بدون هدر Content-Type دستی تا مرورگر
|
// آپلود چندبخشی (multipart) — بدون هدر Content-Type دستی تا مرورگر
|
||||||
@@ -323,6 +343,12 @@ interface RawSupplier {
|
|||||||
interface RawProject {
|
interface RawProject {
|
||||||
id: string;
|
id: string;
|
||||||
name: string;
|
name: string;
|
||||||
|
location?: string | null;
|
||||||
|
project_manager?: string | null;
|
||||||
|
description?: string | null;
|
||||||
|
start_date?: string | null;
|
||||||
|
status?: string | null;
|
||||||
|
progress?: number | null;
|
||||||
}
|
}
|
||||||
interface RawSpec {
|
interface RawSpec {
|
||||||
attribute_key: string;
|
attribute_key: string;
|
||||||
@@ -458,6 +484,39 @@ function adaptBrandLink(raw: RawBrandLink): BrandLinkRow {
|
|||||||
return { id: raw.id, brand_id: raw.brand_id, brand_name: raw.brand?.name || "" };
|
return { id: raw.id, brand_id: raw.brand_id, brand_name: raw.brand?.name || "" };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// تأمینکنندگان متصل به یک متریال — پاسخ GET /materials/{id}/suppliers
|
||||||
|
// Raw shape mirrors the backend dict exactly: clean supplier objects produced
|
||||||
|
// by an atomic JOIN (select(Supplier).join(SupplierMaterial)…) — the name
|
||||||
|
// always comes from the suppliers table, never from the material row.
|
||||||
|
interface RawMaterialSupplier {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
phone: string | null;
|
||||||
|
contact_person: string | null;
|
||||||
|
location: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Clean UI-facing type for one supplier linked to a material. */
|
||||||
|
export interface MaterialSupplier {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
phone: string | null;
|
||||||
|
contact_person: string | null;
|
||||||
|
location: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function adaptMaterialSupplier(raw: RawMaterialSupplier): MaterialSupplier {
|
||||||
|
return {
|
||||||
|
id: raw.id,
|
||||||
|
// Bound straight from the supplier object in the API response — there is
|
||||||
|
// no fallback, so a supplier row can never render the material's name.
|
||||||
|
name: raw.name,
|
||||||
|
phone: raw.phone,
|
||||||
|
contact_person: raw.contact_person,
|
||||||
|
location: raw.location,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
// فایل پیوست — پاسخ بکاند (metadata؛ بایتها از endpoint دانلود میآیند)
|
// فایل پیوست — پاسخ بکاند (metadata؛ بایتها از endpoint دانلود میآیند)
|
||||||
interface RawAttachment {
|
interface RawAttachment {
|
||||||
id: string;
|
id: string;
|
||||||
@@ -927,15 +986,30 @@ export const api = {
|
|||||||
|
|
||||||
if (becomingAccepted) {
|
if (becomingAccepted) {
|
||||||
const acceptedTs = (patch.termsheets || []).filter((t) => t.status === "accepted");
|
const acceptedTs = (patch.termsheets || []).filter((t) => t.status === "accepted");
|
||||||
// پروژهی واحدِ انتخابشده برای هر قلم (item_decisions.project_id)
|
// پروژهی واحدِ انتخابشده یا تخصیصهای چندپروژهای برای هر قلم
|
||||||
const targetProjByLine = new Map<string, string>();
|
const targetProjByLine = new Map<string, string>();
|
||||||
|
const allocationsByLine = new Map<string, { project_id: string; quantity: number }[]>();
|
||||||
for (const li of patch.line_items || []) {
|
for (const li of patch.line_items || []) {
|
||||||
|
if (li.allocations && li.allocations.length > 0) {
|
||||||
|
const resolvedAllocs: { project_id: string; quantity: number }[] = [];
|
||||||
|
for (const a of li.allocations) {
|
||||||
|
const pid = looksLikeUuid(a.project_id) ? a.project_id! : await projectIdByNameOrCreate(a.project_name);
|
||||||
|
if (pid && a.quantity > 0) {
|
||||||
|
resolvedAllocs.push({ project_id: pid, quantity: Number(a.quantity) });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (resolvedAllocs.length) {
|
||||||
|
allocationsByLine.set(li.id, resolvedAllocs);
|
||||||
|
targetProjByLine.set(li.id, resolvedAllocs[0].project_id);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
const tp = li.target_project;
|
const tp = li.target_project;
|
||||||
if (tp && tp.name) {
|
if (tp && tp.name) {
|
||||||
const pid = looksLikeUuid(tp.id) ? tp.id : await projectIdByNameOrCreate(tp.name);
|
const pid = looksLikeUuid(tp.id) ? tp.id : await projectIdByNameOrCreate(tp.name);
|
||||||
if (pid) targetProjByLine.set(li.id, pid);
|
if (pid) targetProjByLine.set(li.id, pid);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const payload = {
|
const payload = {
|
||||||
accepted_termsheets: acceptedTs.map((t) => ({
|
accepted_termsheets: acceptedTs.map((t) => ({
|
||||||
@@ -953,11 +1027,13 @@ export const api = {
|
|||||||
const idx = li.accepted_ts_id ? acceptedTs.findIndex((t) => t.id === li.accepted_ts_id) : -1;
|
const idx = li.accepted_ts_id ? acceptedTs.findIndex((t) => t.id === li.accepted_ts_id) : -1;
|
||||||
const chosen = !li.rejected && idx >= 0;
|
const chosen = !li.rejected && idx >= 0;
|
||||||
const chosenProjId = targetProjByLine.get(li.id);
|
const chosenProjId = targetProjByLine.get(li.id);
|
||||||
|
const lineAllocs = allocationsByLine.get(li.id);
|
||||||
return {
|
return {
|
||||||
line_item_id: li.id,
|
line_item_id: li.id,
|
||||||
status: chosen ? "chosen" : "rejected",
|
status: chosen ? "chosen" : "rejected",
|
||||||
...(chosen ? { accepted_termsheet_index: idx } : {}),
|
...(chosen ? { accepted_termsheet_index: idx } : {}),
|
||||||
...(chosen && chosenProjId ? { project_id: chosenProjId } : {}),
|
...(chosen && chosenProjId ? { project_id: chosenProjId } : {}),
|
||||||
|
...(chosen && lineAllocs && lineAllocs.length ? { allocations: lineAllocs } : {}),
|
||||||
...(li.unit_price != null ? { adjusted_unit_price: li.unit_price } : {}),
|
...(li.unit_price != null ? { adjusted_unit_price: li.unit_price } : {}),
|
||||||
};
|
};
|
||||||
}),
|
}),
|
||||||
@@ -1193,16 +1269,51 @@ export const api = {
|
|||||||
updateCanonicalUnit: async (id: string, canonical_unit_id: number): Promise<void> => {
|
updateCanonicalUnit: async (id: string, canonical_unit_id: number): Promise<void> => {
|
||||||
await patchData(`/materials/${id}`, { canonical_unit_id });
|
await patchData(`/materials/${id}`, { canonical_unit_id });
|
||||||
},
|
},
|
||||||
|
// فهرست تأمینکنندههای متصل به یک متریال (GET /materials/{id}/suppliers)
|
||||||
|
listSuppliers: async (materialId: string): Promise<MaterialSupplier[]> => {
|
||||||
|
// The backend returns { data: [...clean supplier objects] } from an
|
||||||
|
// atomic JOIN; getData<T> unwraps the envelope. No fallback data —
|
||||||
|
// an empty array means the material genuinely has no suppliers.
|
||||||
|
const raw = await getData<RawMaterialSupplier[]>(
|
||||||
|
`/materials/${materialId}/suppliers`,
|
||||||
|
);
|
||||||
|
return raw.map(adaptMaterialSupplier);
|
||||||
|
},
|
||||||
},
|
},
|
||||||
|
|
||||||
projects: {
|
projects: {
|
||||||
list: async (): Promise<Project[]> => {
|
list: async (): Promise<Project[]> => {
|
||||||
const raw = await getData<RawProject[]>(`/projects?page_size=${PAGE_SIZE}`);
|
const raw = await getData<RawProject[]>(`/projects?page_size=${PAGE_SIZE}`);
|
||||||
return raw.map((p) => ({ id: p.id, name: p.name }));
|
return raw.map((p) => ({
|
||||||
|
id: p.id,
|
||||||
|
name: p.name,
|
||||||
|
location: p.location || "",
|
||||||
|
project_manager: p.project_manager || "",
|
||||||
|
description: p.description || "",
|
||||||
|
start_date: p.start_date,
|
||||||
|
status: p.status || "ACTIVE",
|
||||||
|
progress: p.progress != null ? Number(p.progress) : 0,
|
||||||
|
}));
|
||||||
},
|
},
|
||||||
create: async (p: Project): Promise<Project> => {
|
create: async (p: Project): Promise<Project> => {
|
||||||
const raw = await postData<RawProject>("/projects", { name: p.name });
|
const raw = await postData<RawProject>("/projects", {
|
||||||
return { id: raw.id, name: raw.name };
|
name: p.name,
|
||||||
|
location: p.location || "",
|
||||||
|
project_manager: p.project_manager || "",
|
||||||
|
description: p.description || "",
|
||||||
|
});
|
||||||
|
return {
|
||||||
|
id: raw.id,
|
||||||
|
name: raw.name,
|
||||||
|
location: raw.location || "",
|
||||||
|
project_manager: raw.project_manager || "",
|
||||||
|
description: raw.description || "",
|
||||||
|
status: raw.status || "ACTIVE",
|
||||||
|
progress: raw.progress != null ? Number(raw.progress) : 0,
|
||||||
|
};
|
||||||
|
},
|
||||||
|
delete: async (id: string): Promise<void> => {
|
||||||
|
await deleteData(`/projects/${id}`);
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
|
||||||
@@ -1592,11 +1703,16 @@ interface RawUnitL { id: number; code: string; name_fa: string | null; }
|
|||||||
export interface UserRow {
|
export interface UserRow {
|
||||||
id: string;
|
id: string;
|
||||||
casdoor_id: string;
|
casdoor_id: string;
|
||||||
|
username?: string | null;
|
||||||
first_name: string;
|
first_name: string;
|
||||||
last_name: string;
|
last_name: string;
|
||||||
phone: string | null;
|
phone: string | null;
|
||||||
role: "pm" | "procurement_manager" | "admin" | null;
|
role: "pm" | "procurement_manager" | "admin" | "supervisor" | null;
|
||||||
role_label: string | null;
|
role_label: string | null;
|
||||||
|
// لایه پنلها (جایگزین نقشها): {'procurement': 'full'|'limited', ...}
|
||||||
|
panels?: Record<string, string>;
|
||||||
|
// عضویت M:N پروژهای — محدوده داده سطح limited
|
||||||
|
member_project_ids?: string[];
|
||||||
project_id: string | null;
|
project_id: string | null;
|
||||||
project_name: string | null;
|
project_name: string | null;
|
||||||
// 1:N — every project this PM manages (oldest first).
|
// 1:N — every project this PM manages (oldest first).
|
||||||
@@ -1620,10 +1736,11 @@ export const apiV26 = {
|
|||||||
user: {
|
user: {
|
||||||
id: string;
|
id: string;
|
||||||
casdoor_id: string;
|
casdoor_id: string;
|
||||||
|
username?: string;
|
||||||
first_name: string;
|
first_name: string;
|
||||||
last_name: string;
|
last_name: string;
|
||||||
phone: string | null;
|
phone: string | null;
|
||||||
role: "pm" | "procurement_manager" | "admin" | null;
|
role: "pm" | "procurement_manager" | "admin" | "supervisor" | null;
|
||||||
role_label: string | null;
|
role_label: string | null;
|
||||||
project_id: string | null;
|
project_id: string | null;
|
||||||
project_name: string | null;
|
project_name: string | null;
|
||||||
@@ -1637,6 +1754,7 @@ export const apiV26 = {
|
|||||||
expires_in: res.data.expires_in,
|
expires_in: res.data.expires_in,
|
||||||
user: {
|
user: {
|
||||||
...u,
|
...u,
|
||||||
|
username: u.username || u.casdoor_id,
|
||||||
display_name: `${u.first_name} ${u.last_name}`.trim() || u.casdoor_id,
|
display_name: `${u.first_name} ${u.last_name}`.trim() || u.casdoor_id,
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
@@ -1656,14 +1774,15 @@ export const apiV26 = {
|
|||||||
users: {
|
users: {
|
||||||
me: async (): Promise<import("../store/auth").AuthUser> => {
|
me: async (): Promise<import("../store/auth").AuthUser> => {
|
||||||
const data = await getData<{
|
const data = await getData<{
|
||||||
id: string; casdoor_id: string; first_name: string; last_name: string; phone: string | null;
|
id: string; casdoor_id: string; username?: string; first_name: string; last_name: string; phone: string | null;
|
||||||
role: "pm" | "procurement_manager" | "admin" | null; role_label: string | null;
|
role: "pm" | "procurement_manager" | "admin" | "supervisor" | null; role_label: string | null;
|
||||||
project_id: string | null; project_name: string | null;
|
project_id: string | null; project_name: string | null;
|
||||||
projects?: { id: string; name: string }[];
|
projects?: { id: string; name: string }[];
|
||||||
}>("/users/me");
|
}>("/users/me");
|
||||||
return {
|
return {
|
||||||
id: data.id,
|
id: data.id,
|
||||||
casdoor_id: data.casdoor_id,
|
casdoor_id: data.casdoor_id,
|
||||||
|
username: data.username || data.casdoor_id,
|
||||||
first_name: data.first_name,
|
first_name: data.first_name,
|
||||||
last_name: data.last_name,
|
last_name: data.last_name,
|
||||||
phone: data.phone,
|
phone: data.phone,
|
||||||
@@ -1687,8 +1806,13 @@ export const apiV26 = {
|
|||||||
first_name: string; last_name?: string; phone?: string | null;
|
first_name: string; last_name?: string; phone?: string | null;
|
||||||
casdoor_id?: string | null; role?: "pm" | "procurement_manager" | "admin" | null;
|
casdoor_id?: string | null; role?: "pm" | "procurement_manager" | "admin" | null;
|
||||||
}): Promise<UserRow> => postData<UserRow>("/users", body),
|
}): Promise<UserRow> => postData<UserRow>("/users", body),
|
||||||
updateRole: async (id: string, role: "pm" | "procurement_manager" | "admin" | null): Promise<UserRow> =>
|
updateRole: async (id: string, role: "pm" | "procurement_manager" | "admin" | "supervisor" | null): Promise<UserRow> =>
|
||||||
patchData<UserRow>(`/users/${id}`, { role }),
|
patchData<UserRow>(`/users/${id}`, { role }),
|
||||||
|
// لایه پنلها — تخصیص پنل + سطح دسترسی و عضویت پروژهای (فقط ادمین)
|
||||||
|
setPanels: async (id: string, panels: Record<string, string>): Promise<UserRow> =>
|
||||||
|
putData<UserRow>(`/users/${id}/panels`, { panels }),
|
||||||
|
setPanelProjects: async (id: string, project_ids: string[]): Promise<UserRow> =>
|
||||||
|
putData<UserRow>(`/users/${id}/panel-projects`, { project_ids }),
|
||||||
assignProject: async (id: string, projectId: string | null): Promise<UserRow> =>
|
assignProject: async (id: string, projectId: string | null): Promise<UserRow> =>
|
||||||
postData<UserRow>(`/users/${id}/project`, { project_id: projectId }),
|
postData<UserRow>(`/users/${id}/project`, { project_id: projectId }),
|
||||||
// همگامسازی هویتها از Casdoor (ادمین/مدیر تدارکات) — نقشها دستنخورده میمانند
|
// همگامسازی هویتها از Casdoor (ادمین/مدیر تدارکات) — نقشها دستنخورده میمانند
|
||||||
@@ -1736,16 +1860,23 @@ export const apiV26 = {
|
|||||||
const data = await getData<Parameters<typeof rawInventory>[0][]>(`/inventory?${qs}`);
|
const data = await getData<Parameters<typeof rawInventory>[0][]>(`/inventory?${qs}`);
|
||||||
return data.map(rawInventory);
|
return data.map(rawInventory);
|
||||||
},
|
},
|
||||||
transactions: async (params: { project_id?: string; warehouse_id?: string; transaction_type?: string; date_from?: string; date_to?: string; sort?: string } = {}): Promise<InventoryTransaction[]> => {
|
transactions: async (params: { project_id?: string; warehouse_id?: string; transaction_type?: string; date_from?: string; date_to?: string; sort?: string; page?: number } = {}): Promise<InventoryTransaction[]> => {
|
||||||
const pid = params.project_id ?? activeProjectId() ?? undefined;
|
const pid = params.project_id ?? activeProjectId() ?? undefined;
|
||||||
const qs = new URLSearchParams({ page_size: "100", ...cleanParams({ ...params, project_id: pid }) }).toString();
|
const qs = new URLSearchParams({ page_size: "100", ...cleanParams({ ...params, project_id: pid }) }).toString();
|
||||||
return getData<InventoryTransaction[]>(`/inventory/transactions?${qs}`);
|
return getData<InventoryTransaction[]>(`/inventory/transactions?${qs}`);
|
||||||
},
|
},
|
||||||
|
// همان transactions با meta.total برای صفحهبندی «نمایش بیشتر»
|
||||||
|
transactionsPaged: async (params: { project_id?: string; warehouse_id?: string; transaction_type?: string; date_from?: string; date_to?: string; sort?: string; page?: number } = {}): Promise<{ rows: InventoryTransaction[]; total: number }> => {
|
||||||
|
const pid = params.project_id ?? activeProjectId() ?? undefined;
|
||||||
|
const qs = new URLSearchParams({ page_size: "100", ...cleanParams({ ...params, project_id: pid }) }).toString();
|
||||||
|
const res = await request<{ data: InventoryTransaction[]; meta?: { total?: number } }>(`/inventory/transactions?${qs}`);
|
||||||
|
return { rows: res.data ?? [], total: res.meta?.total ?? res.data?.length ?? 0 };
|
||||||
|
},
|
||||||
createTransaction: async (body: {
|
createTransaction: async (body: {
|
||||||
transaction_type: TransactionType; warehouse_id: string; dest_warehouse_id?: string | null;
|
transaction_type: TransactionType; warehouse_id: string; dest_warehouse_id?: string | null;
|
||||||
material_id: string; brand_id?: string | null; quantity?: number | null;
|
material_id: string; brand_id?: string | null; quantity?: number | null;
|
||||||
physical_qty?: number | null; unit_id?: number | null; specs?: Record<string, string> | null;
|
physical_qty?: number | null; unit_id?: number | null; specs?: Record<string, string> | null;
|
||||||
note?: string | null; transaction_date?: string | null;
|
note?: string | null; delivered_to?: string | null; transaction_date?: string | null;
|
||||||
}): Promise<InventoryTransaction[]> => {
|
}): Promise<InventoryTransaction[]> => {
|
||||||
return postData<InventoryTransaction[]>(`/inventory/transactions${projectQuery()}`, body);
|
return postData<InventoryTransaction[]>(`/inventory/transactions${projectQuery()}`, body);
|
||||||
},
|
},
|
||||||
@@ -1796,4 +1927,41 @@ export const apiV26 = {
|
|||||||
attributes: [],
|
attributes: [],
|
||||||
}),
|
}),
|
||||||
},
|
},
|
||||||
|
|
||||||
|
projectTransfers: {
|
||||||
|
list: async (projectId?: string | null, direction: "outgoing" | "incoming" | "all" = "all", status?: string): Promise<ProjectTransfer[]> => {
|
||||||
|
const q = new URLSearchParams();
|
||||||
|
if (projectId) q.set("project_id", projectId);
|
||||||
|
if (direction) q.set("direction", direction);
|
||||||
|
if (status) q.set("status", status);
|
||||||
|
const qs = q.toString() ? `?${q.toString()}` : "";
|
||||||
|
try {
|
||||||
|
const res = await getData<ProjectTransfer[]>(`/inventory/project-transfers${qs}`);
|
||||||
|
return Array.isArray(res) ? res : [];
|
||||||
|
} catch (err) {
|
||||||
|
console.error("Failed to fetch project transfers:", err);
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
},
|
||||||
|
get: async (id: string, projectId?: string | null): Promise<ProjectTransfer> =>
|
||||||
|
getData<ProjectTransfer>(projectId ? `/inventory/project-transfers/${id}?project_id=${projectId}` : `/inventory/project-transfers/${id}`),
|
||||||
|
create: async (body: ProjectTransferCreateIn, projectId?: string | null): Promise<ProjectTransfer> =>
|
||||||
|
postData<ProjectTransfer>(projectId ? `/inventory/project-transfers?project_id=${projectId}` : `/inventory/project-transfers`, body),
|
||||||
|
update: async (id: string, patch: ProjectTransferUpdateIn, projectId?: string | null): Promise<ProjectTransfer> =>
|
||||||
|
patchData<ProjectTransfer>(projectId ? `/inventory/project-transfers/${id}?project_id=${projectId}` : `/inventory/project-transfers/${id}`, patch),
|
||||||
|
delete: async (id: string, projectId?: string | null): Promise<{ ok: boolean; message: string }> =>
|
||||||
|
deleteData(projectId ? `/inventory/project-transfers/${id}?project_id=${projectId}` : `/inventory/project-transfers/${id}`),
|
||||||
|
onTheWay: async (projectId?: string | null): Promise<ProjectTransfer[]> => {
|
||||||
|
try {
|
||||||
|
const res = await getData<ProjectTransfer[]>(projectId ? `/pm/transfers/on-the-way?project_id=${projectId}` : `/pm/transfers/on-the-way`);
|
||||||
|
return Array.isArray(res) ? res : [];
|
||||||
|
} catch (err) {
|
||||||
|
console.error("Failed to fetch on-the-way transfers:", err);
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
},
|
||||||
|
receive: async (id: string, body: ProjectTransferReceiveIn, projectId?: string | null): Promise<ProjectTransfer> =>
|
||||||
|
postData<ProjectTransfer>(projectId ? `/inventory/project-transfers/${id}/receive?project_id=${projectId}` : `/inventory/project-transfers/${id}/receive`, body),
|
||||||
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -115,6 +115,27 @@ export function isoToJalaliStr(iso: string | null | undefined): string {
|
|||||||
return `${toFa(jy)}/${toFa(String(jm).padStart(2, "0"))}/${toFa(String(jd).padStart(2, "0"))}`;
|
return `${toFa(jy)}/${toFa(String(jm).padStart(2, "0"))}/${toFa(String(jd).padStart(2, "0"))}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// format an ISO string to "۱۴۰۳/۰۵/۱۲ ۱۴:۳۰"
|
||||||
|
export function isoToJalaliDateTime(iso: string | null | undefined): string {
|
||||||
|
if (!iso) return "";
|
||||||
|
const d = new Date(iso);
|
||||||
|
if (Number.isNaN(d.getTime())) return "";
|
||||||
|
const [jy, jm, jd] = gregorianToJalali(d.getFullYear(), d.getMonth() + 1, d.getDate());
|
||||||
|
const hh = String(d.getHours()).padStart(2, "0");
|
||||||
|
const mm = String(d.getMinutes()).padStart(2, "0");
|
||||||
|
return `${toFa(jy)}/${toFa(String(jm).padStart(2, "0"))}/${toFa(String(jd).padStart(2, "0"))} ${toFa(hh)}:${toFa(mm)}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
// format time only: "۱۴:۳۰"
|
||||||
|
export function isoToTimeStr(iso: string | null | undefined): string {
|
||||||
|
if (!iso) return "";
|
||||||
|
const d = new Date(iso);
|
||||||
|
if (Number.isNaN(d.getTime())) return "";
|
||||||
|
const hh = String(d.getHours()).padStart(2, "0");
|
||||||
|
const mm = String(d.getMinutes()).padStart(2, "0");
|
||||||
|
return `${toFa(hh)}:${toFa(mm)}`;
|
||||||
|
}
|
||||||
|
|
||||||
// format with month name: "۱۸ مرداد ۱۴۰۴"
|
// format with month name: "۱۸ مرداد ۱۴۰۴"
|
||||||
export function isoToJalaliLong(iso: string | null | undefined): string {
|
export function isoToJalaliLong(iso: string | null | undefined): string {
|
||||||
if (!iso) return "";
|
if (!iso) return "";
|
||||||
|
|||||||
@@ -31,6 +31,12 @@ export interface Material {
|
|||||||
export interface Project {
|
export interface Project {
|
||||||
id: string;
|
id: string;
|
||||||
name: string;
|
name: string;
|
||||||
|
location?: string;
|
||||||
|
project_manager?: string;
|
||||||
|
description?: string;
|
||||||
|
start_date?: string | null;
|
||||||
|
status?: string;
|
||||||
|
progress?: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
// مرحلهی پرداخت
|
// مرحلهی پرداخت
|
||||||
@@ -73,6 +79,7 @@ export interface LineItem {
|
|||||||
projects?: { id: string; name: string }[]; // پروژههای کاندیدای تخصیصیافته به این قلم (line_item_projects)
|
projects?: { id: string; name: string }[]; // پروژههای کاندیدای تخصیصیافته به این قلم (line_item_projects)
|
||||||
target_project?: { id: string; name: string } | null; // پروژهی نهایی انتخابشده در هنگام خرید (item_decisions.project_id)
|
target_project?: { id: string; name: string } | null; // پروژهی نهایی انتخابشده در هنگام خرید (item_decisions.project_id)
|
||||||
target_project_id?: string | null;
|
target_project_id?: string | null;
|
||||||
|
allocations?: { project_id?: string; project_name: string; quantity: number }[]; // تخصیص چندپروژهای در پذیرش
|
||||||
}
|
}
|
||||||
|
|
||||||
// پیشنهاد خرید (اصلیترین entity)
|
// پیشنهاد خرید (اصلیترین entity)
|
||||||
@@ -163,7 +170,9 @@ export interface InventoryTransaction {
|
|||||||
physical_qty?: number | null;
|
physical_qty?: number | null;
|
||||||
transfer_pair_id?: string | null;
|
transfer_pair_id?: string | null;
|
||||||
performed_by?: string | null;
|
performed_by?: string | null;
|
||||||
|
delivered_to?: string | null;
|
||||||
transaction_date: string;
|
transaction_date: string;
|
||||||
|
created_at?: string;
|
||||||
note?: string | null;
|
note?: string | null;
|
||||||
material?: { id: string; name: string } | null;
|
material?: { id: string; name: string } | null;
|
||||||
brand?: { id: string; name: string } | null;
|
brand?: { id: string; name: string } | null;
|
||||||
@@ -199,3 +208,52 @@ export interface ConfirmedReceipt {
|
|||||||
quality_note: string | null;
|
quality_note: string | null;
|
||||||
allocations: { warehouse_id: string; warehouse_name: string; quantity: string }[];
|
allocations: { warehouse_id: string; warehouse_name: string; quantity: string }[];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface ProjectTransfer {
|
||||||
|
id: string;
|
||||||
|
from_project: { id: string; name: string };
|
||||||
|
from_warehouse: { id: string; name: string };
|
||||||
|
to_project: { id: string; name: string };
|
||||||
|
to_warehouse?: { id: string; name: string } | null;
|
||||||
|
material: { id: string; name: string };
|
||||||
|
brand?: { id: string; name: string } | null;
|
||||||
|
unit: { id: number; code: string; name_fa?: string | null };
|
||||||
|
quantity: number;
|
||||||
|
specs: Record<string, string>;
|
||||||
|
specs_hash: string;
|
||||||
|
note?: string | null;
|
||||||
|
status: "in_transit" | "received" | "cancelled";
|
||||||
|
transfer_date: string;
|
||||||
|
transferred_by?: string | null;
|
||||||
|
received_at?: string | null;
|
||||||
|
received_by?: string | null;
|
||||||
|
receipt_allocations?: { warehouse_id: string; quantity: string | number }[] | null;
|
||||||
|
created_at: string;
|
||||||
|
updated_at: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ProjectTransferCreateIn {
|
||||||
|
from_warehouse_id: string;
|
||||||
|
to_project_id: string;
|
||||||
|
material_id: string;
|
||||||
|
brand_id?: string | null;
|
||||||
|
unit_id: number;
|
||||||
|
quantity: number;
|
||||||
|
specs?: Record<string, string>;
|
||||||
|
note?: string | null;
|
||||||
|
transfer_date?: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ProjectTransferUpdateIn {
|
||||||
|
to_project_id?: string;
|
||||||
|
quantity?: number;
|
||||||
|
note?: string | null;
|
||||||
|
transfer_date?: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ProjectTransferReceiveIn {
|
||||||
|
allocations: { warehouse_id: string; quantity: number }[];
|
||||||
|
received_at?: string | null;
|
||||||
|
note?: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ const ROLE_LABELS: Record<string, string> = {
|
|||||||
pm: "مدیر پروژه",
|
pm: "مدیر پروژه",
|
||||||
procurement_manager: "مدیر تدارکات",
|
procurement_manager: "مدیر تدارکات",
|
||||||
admin: "ادمین",
|
admin: "ادمین",
|
||||||
|
supervisor: "سرپرست پروژه",
|
||||||
};
|
};
|
||||||
|
|
||||||
// پنل مدیریت ادمین (فقط ادمین) — همگامسازی کاربران از Casdoor و
|
// پنل مدیریت ادمین (فقط ادمین) — همگامسازی کاربران از Casdoor و
|
||||||
@@ -80,6 +81,26 @@ export function AdminPanel() {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// اعطا/لغو نقش «سرپرست پروژه» — کاربر فقطِ پنل مدیریت پروژه (PM)
|
||||||
|
const toggleSupervisor = async (u: UserRow) => {
|
||||||
|
setBusyId(u.id);
|
||||||
|
const target = u.role === "supervisor" ? null : "supervisor";
|
||||||
|
try {
|
||||||
|
await apiV26.users.updateRole(u.id, target as "supervisor" | null);
|
||||||
|
toast.success(
|
||||||
|
target === "supervisor"
|
||||||
|
? `«${u.first_name} ${u.last_name}» سرپرست پروژه شد ✓`
|
||||||
|
: `نقش سرپرست پروژه از «${u.first_name} ${u.last_name}» گرفته شد`,
|
||||||
|
);
|
||||||
|
await load();
|
||||||
|
refreshProcurementStore();
|
||||||
|
} catch (err) {
|
||||||
|
toast.error(err instanceof Error ? err.message : "خطا در تغییر نقش");
|
||||||
|
} finally {
|
||||||
|
setBusyId(null);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
if (!isAdmin) {
|
if (!isAdmin) {
|
||||||
return (
|
return (
|
||||||
<div className="min-h-screen">
|
<div className="min-h-screen">
|
||||||
@@ -129,12 +150,13 @@ export function AdminPanel() {
|
|||||||
<th className="py-2 pe-3">نام کامل</th>
|
<th className="py-2 pe-3">نام کامل</th>
|
||||||
<th className="py-2 pe-3">شناسه Casdoor</th>
|
<th className="py-2 pe-3">شناسه Casdoor</th>
|
||||||
<th className="py-2 pe-3">نقش فعلی</th>
|
<th className="py-2 pe-3">نقش فعلی</th>
|
||||||
<th className="py-2">مدیریت مدیر تدارکات</th>
|
<th className="py-2">مدیریت نقشها</th>
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
{users.map((u) => {
|
{users.map((u) => {
|
||||||
const isPMgr = u.role === "procurement_manager";
|
const isPMgr = u.role === "procurement_manager";
|
||||||
|
const isSup = u.role === "supervisor";
|
||||||
return (
|
return (
|
||||||
<tr key={u.id} className="border-b border-line/50">
|
<tr key={u.id} className="border-b border-line/50">
|
||||||
<td className="py-2 pe-3 font-semibold">
|
<td className="py-2 pe-3 font-semibold">
|
||||||
@@ -147,6 +169,7 @@ export function AdminPanel() {
|
|||||||
</span>
|
</span>
|
||||||
</td>
|
</td>
|
||||||
<td className="py-2">
|
<td className="py-2">
|
||||||
|
<div className="flex flex-wrap items-center gap-1.5">
|
||||||
<button
|
<button
|
||||||
disabled={busyId === u.id}
|
disabled={busyId === u.id}
|
||||||
onClick={() => void toggleProcurementManager(u)}
|
onClick={() => void toggleProcurementManager(u)}
|
||||||
@@ -158,6 +181,18 @@ export function AdminPanel() {
|
|||||||
>
|
>
|
||||||
{busyId === u.id ? "…" : isPMgr ? "لغو نقش مدیر تدارکات" : "اعطای نقش مدیر تدارکات"}
|
{busyId === u.id ? "…" : isPMgr ? "لغو نقش مدیر تدارکات" : "اعطای نقش مدیر تدارکات"}
|
||||||
</button>
|
</button>
|
||||||
|
<button
|
||||||
|
disabled={busyId === u.id}
|
||||||
|
onClick={() => void toggleSupervisor(u)}
|
||||||
|
className={`rounded-lg border px-3 py-1 text-[11.5px] font-bold ${
|
||||||
|
isSup
|
||||||
|
? "border-red/30 bg-red/5 text-red hover:bg-red/10"
|
||||||
|
: "border-green/30 bg-green/5 text-green hover:bg-green/10"
|
||||||
|
} disabled:opacity-50`}
|
||||||
|
>
|
||||||
|
{busyId === u.id ? "…" : isSup ? "لغو نقش سرپرست پروژه" : "اعطای نقش سرپرست پروژه"}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -79,6 +79,13 @@ export function LoginPage() {
|
|||||||
toast.error("نقش شما هنوز در سیستم تعیین نشده است — با مدیر سیستم تماس بگیرید");
|
toast.error("نقش شما هنوز در سیستم تعیین نشده است — با مدیر سیستم تماس بگیرید");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
const hasProjects =
|
||||||
|
(Boolean(user.projects && user.projects.length > 0)) ||
|
||||||
|
(Boolean(user.member_project_ids && user.member_project_ids.length > 0));
|
||||||
|
if (user.role === "supervisor" && !hasProjects) {
|
||||||
|
toast.error("پروژه تخصیص داده نشده است — تا زمان تخصیص پروژه اجازه ورود ندارید");
|
||||||
|
return;
|
||||||
|
}
|
||||||
setToken(access_token);
|
setToken(access_token);
|
||||||
setUser(user);
|
setUser(user);
|
||||||
// تحلیل رفتار (no-op بدون تنظیمات VITE_OPENPANEL_*)
|
// تحلیل رفتار (no-op بدون تنظیمات VITE_OPENPANEL_*)
|
||||||
@@ -88,8 +95,23 @@ export function LoginPage() {
|
|||||||
if (returnUrl) {
|
if (returnUrl) {
|
||||||
navigate(decodeURIComponent(returnUrl));
|
navigate(decodeURIComponent(returnUrl));
|
||||||
} else {
|
} else {
|
||||||
// مدیر پروژه → پنل انبار؛ مدیر تدارکات/ادمین → دفتر پیشنهادهای خرید
|
// هدایت پس از ورود بر اساس پنلها یا نقش:
|
||||||
navigate(user.role === "pm" ? "/inventory" : "/");
|
const panels = user.panels ?? {};
|
||||||
|
if (panels.procurement === "full") {
|
||||||
|
navigate("/");
|
||||||
|
} else if (panels.procurement === "limited") {
|
||||||
|
navigate("/requester");
|
||||||
|
} else if (panels.inventory) {
|
||||||
|
navigate("/inventory");
|
||||||
|
} else if (panels.pm) {
|
||||||
|
navigate("/panel/pm");
|
||||||
|
} else if (user.role === "supervisor") {
|
||||||
|
navigate("/panel/pm");
|
||||||
|
} else if (user.role === "pm") {
|
||||||
|
navigate("/inventory");
|
||||||
|
} else {
|
||||||
|
navigate("/");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
toast.error(err instanceof Error ? err.message : "خطا در ورود");
|
toast.error(err instanceof Error ? err.message : "خطا در ورود");
|
||||||
@@ -280,10 +302,21 @@ export function LoginPage() {
|
|||||||
<ClipboardList className="h-6 w-6" strokeWidth={2} />
|
<ClipboardList className="h-6 w-6" strokeWidth={2} />
|
||||||
</span>
|
</span>
|
||||||
<div>
|
<div>
|
||||||
<h1 className="text-[19px] font-extrabold leading-7">سامانه تدارکات و انبار</h1>
|
<h1 className="text-[19px] font-extrabold leading-7">سامانه جامع مدیریت پروژه، تدارکات و انبار</h1>
|
||||||
<p className="mt-1 text-[12.5px] leading-6 text-muted">
|
<p className="mt-1.5 text-[12.5px] leading-6 text-muted">
|
||||||
برای ورود، نام کاربری و رمز عبور سازمانی خود را وارد کنید
|
درگاه یکپارچه ورود به سامانه مدیریت عملیات پروژه، تدارکات و انبارداری
|
||||||
</p>
|
</p>
|
||||||
|
<div className="mt-2.5 flex items-center justify-center gap-1.5 flex-wrap">
|
||||||
|
<span className="inline-flex items-center rounded-full bg-sky-50 px-2.5 py-0.5 text-[11px] font-semibold text-sky-700 border border-sky-200">
|
||||||
|
مدیریت پروژه
|
||||||
|
</span>
|
||||||
|
<span className="inline-flex items-center rounded-full bg-indigo-50 px-2.5 py-0.5 text-[11px] font-semibold text-indigo-700 border border-indigo-200">
|
||||||
|
تدارکات
|
||||||
|
</span>
|
||||||
|
<span className="inline-flex items-center rounded-full bg-emerald-50 px-2.5 py-0.5 text-[11px] font-semibold text-emerald-700 border border-emerald-200">
|
||||||
|
انبارداری
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|||||||
@@ -23,12 +23,134 @@ import {
|
|||||||
import { MilestoneRow } from "../../components/MilestoneRow";
|
import { MilestoneRow } from "../../components/MilestoneRow";
|
||||||
import { FileList } from "../../components/FileList";
|
import { FileList } from "../../components/FileList";
|
||||||
import { JalaliDatePicker } from "../../components/JalaliDatePicker";
|
import { JalaliDatePicker } from "../../components/JalaliDatePicker";
|
||||||
|
import { Building2, Plus, Trash2, CheckCircle2, AlertCircle } from "lucide-react";
|
||||||
|
|
||||||
|
// تبدیل عدد به حروف فارسی جهت نمایش زیر باکس مقدار
|
||||||
|
const ONES = ["", "یک", "دو", "سه", "چهار", "پنج", "شش", "هفت", "هشت", "نه"];
|
||||||
|
const TEENS = [
|
||||||
|
"ده",
|
||||||
|
"یازده",
|
||||||
|
"دوازده",
|
||||||
|
"سیزده",
|
||||||
|
"چهارده",
|
||||||
|
"پانزده",
|
||||||
|
"شانزده",
|
||||||
|
"هفده",
|
||||||
|
"هجده",
|
||||||
|
"نوزده",
|
||||||
|
];
|
||||||
|
const TENS = [
|
||||||
|
"",
|
||||||
|
"",
|
||||||
|
"بیست",
|
||||||
|
"سی",
|
||||||
|
"چهل",
|
||||||
|
"پنجاه",
|
||||||
|
"شصت",
|
||||||
|
"هفتاد",
|
||||||
|
"هشتاد",
|
||||||
|
"نود",
|
||||||
|
];
|
||||||
|
const HUNDREDS = [
|
||||||
|
"",
|
||||||
|
"صد",
|
||||||
|
"دویست",
|
||||||
|
"سیصد",
|
||||||
|
"چهارصد",
|
||||||
|
"پانصد",
|
||||||
|
"ششصد",
|
||||||
|
"هفتصد",
|
||||||
|
"هشتصد",
|
||||||
|
"نهصد",
|
||||||
|
];
|
||||||
|
const SCALES = ["", "هزار", "میلیون", "میلیارد", "تریلیون"];
|
||||||
|
const DECIMAL_SCALES: Record<number, string> = {
|
||||||
|
1: "دهم",
|
||||||
|
2: "صدم",
|
||||||
|
3: "هزارم",
|
||||||
|
4: "دههزارم",
|
||||||
|
};
|
||||||
|
|
||||||
|
function convertThreeDigits(n: number): string {
|
||||||
|
if (n === 0) return "";
|
||||||
|
const parts: string[] = [];
|
||||||
|
const h = Math.floor(n / 100);
|
||||||
|
const rem = n % 100;
|
||||||
|
if (h > 0) parts.push(HUNDREDS[h]);
|
||||||
|
if (rem >= 10 && rem <= 19) {
|
||||||
|
parts.push(TEENS[rem - 10]);
|
||||||
|
} else {
|
||||||
|
const t = Math.floor(rem / 10);
|
||||||
|
const u = rem % 10;
|
||||||
|
if (t > 0) parts.push(TENS[t]);
|
||||||
|
if (u > 0) parts.push(ONES[u]);
|
||||||
|
}
|
||||||
|
return parts.join(" و ");
|
||||||
|
}
|
||||||
|
|
||||||
|
function toEnglishDigits(str: string): string {
|
||||||
|
return str
|
||||||
|
.replace(/[۰-۹]/g, (d) => String(d.charCodeAt(0) - 1776))
|
||||||
|
.replace(/[٠-٩]/g, (d) => String(d.charCodeAt(0) - 1632));
|
||||||
|
}
|
||||||
|
|
||||||
|
function numberToPersianWords(val: number | string | null | undefined): string {
|
||||||
|
if (val == null || val === "") return "";
|
||||||
|
const numStr = toEnglishDigits(String(val).trim());
|
||||||
|
const num = parseFloat(numStr);
|
||||||
|
if (isNaN(num)) return "";
|
||||||
|
if (num === 0) return "صفر";
|
||||||
|
|
||||||
|
const isNeg = num < 0;
|
||||||
|
const parts = Math.abs(num).toString().split(".");
|
||||||
|
const intStr = parts[0];
|
||||||
|
const decStr = parts[1];
|
||||||
|
|
||||||
|
let intNum = parseInt(intStr, 10);
|
||||||
|
let intResult = "";
|
||||||
|
|
||||||
|
if (intNum === 0) {
|
||||||
|
intResult = "صفر";
|
||||||
|
} else {
|
||||||
|
const chunks: number[] = [];
|
||||||
|
while (intNum > 0) {
|
||||||
|
chunks.push(intNum % 1000);
|
||||||
|
intNum = Math.floor(intNum / 1000);
|
||||||
|
}
|
||||||
|
const chunkWords: string[] = [];
|
||||||
|
for (let i = chunks.length - 1; i >= 0; i--) {
|
||||||
|
const c = chunks[i];
|
||||||
|
if (c > 0) {
|
||||||
|
const w = convertThreeDigits(c);
|
||||||
|
const s = SCALES[i];
|
||||||
|
chunkWords.push(s ? `${w} ${s}` : w);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
intResult = chunkWords.join(" و ");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (decStr && parseInt(decStr, 10) > 0) {
|
||||||
|
const cleanDecStr = decStr.slice(0, 4);
|
||||||
|
const decNum = parseInt(cleanDecStr, 10);
|
||||||
|
const decWord = numberToPersianWords(decNum);
|
||||||
|
const scale = DECIMAL_SCALES[cleanDecStr.length];
|
||||||
|
if (scale) {
|
||||||
|
if (intNum === 0) {
|
||||||
|
return `${isNeg ? "منفی " : ""}${decWord} ${scale}`;
|
||||||
|
}
|
||||||
|
return `${isNeg ? "منفی " : ""}${intResult} و ${decWord} ${scale}`;
|
||||||
|
}
|
||||||
|
return `${isNeg ? "منفی " : ""}${intResult} ممیز ${decWord}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
return isNeg ? `منفی ${intResult}` : intResult;
|
||||||
|
}
|
||||||
|
|
||||||
interface CardDraft {
|
interface CardDraft {
|
||||||
domId: string;
|
domId: string;
|
||||||
isNew: boolean;
|
isNew: boolean;
|
||||||
milestones: Milestone[];
|
milestones: Milestone[];
|
||||||
label: string | null; // null = پیشفرض «گزینه N»
|
label: string | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface AcceptModalProps {
|
export interface AcceptModalProps {
|
||||||
@@ -51,6 +173,9 @@ export function AcceptModal({ quoteId, onClose }: AcceptModalProps) {
|
|||||||
const [removedItems, setRemovedItems] = useState<Set<string>>(new Set());
|
const [removedItems, setRemovedItems] = useState<Set<string>>(new Set());
|
||||||
const [assignments, setAssignments] = useState<Record<string, string>>({});
|
const [assignments, setAssignments] = useState<Record<string, string>>({});
|
||||||
const [itemProjectsSel, setItemProjectsSel] = useState<Record<string, string>>({});
|
const [itemProjectsSel, setItemProjectsSel] = useState<Record<string, string>>({});
|
||||||
|
const [itemAllocations, setItemAllocations] = useState<
|
||||||
|
Record<string, { rowId: string; project_name: string; quantity: number | string }[]>
|
||||||
|
>({});
|
||||||
const [acceptDate, setAcceptDate] = useState<string | null>(() => new Date().toISOString());
|
const [acceptDate, setAcceptDate] = useState<string | null>(() => new Date().toISOString());
|
||||||
const [ready, setReady] = useState(false);
|
const [ready, setReady] = useState(false);
|
||||||
|
|
||||||
@@ -67,17 +192,35 @@ export function AcceptModal({ quoteId, onClose }: AcceptModalProps) {
|
|||||||
setRemovedItems(rem);
|
setRemovedItems(rem);
|
||||||
setAssignments({});
|
setAssignments({});
|
||||||
const projSel: Record<string, string> = {};
|
const projSel: Record<string, string> = {};
|
||||||
|
const allocs: Record<string, { rowId: string; project_name: string; quantity: number | string }[]> = {};
|
||||||
q.line_items.forEach((li) => {
|
q.line_items.forEach((li) => {
|
||||||
const names = (li.projects || []).map((p) => p.name).filter(Boolean);
|
const names = (li.projects || []).map((p) => p.name).filter(Boolean);
|
||||||
projSel[li.id] = li.target_project?.name
|
const defaultProj = li.target_project?.name
|
||||||
? li.target_project.name
|
? li.target_project.name
|
||||||
: names.length
|
: names.length
|
||||||
? names[0]
|
? names[0]
|
||||||
: q.projects && q.projects.length
|
: q.projects && q.projects.length
|
||||||
? q.projects[0]
|
? q.projects[0]
|
||||||
: q.project || "";
|
: q.project || "";
|
||||||
|
projSel[li.id] = defaultProj;
|
||||||
|
if (li.allocations && li.allocations.length) {
|
||||||
|
allocs[li.id] = li.allocations.map((a, idx) => ({
|
||||||
|
rowId: `alloc-${li.id}-${idx}`,
|
||||||
|
project_name: a.project_name,
|
||||||
|
quantity: a.quantity,
|
||||||
|
}));
|
||||||
|
} else {
|
||||||
|
allocs[li.id] = [
|
||||||
|
{
|
||||||
|
rowId: `alloc-${li.id}-0`,
|
||||||
|
project_name: defaultProj,
|
||||||
|
quantity: li.quantity ?? 1,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
}
|
||||||
});
|
});
|
||||||
setItemProjectsSel(projSel);
|
setItemProjectsSel(projSel);
|
||||||
|
setItemAllocations(allocs);
|
||||||
setReady(true);
|
setReady(true);
|
||||||
}, [q]);
|
}, [q]);
|
||||||
|
|
||||||
@@ -137,6 +280,44 @@ export function AcceptModal({ quoteId, onClose }: AcceptModalProps) {
|
|||||||
setAssignments((a) => ({ ...a, [liId]: domId }));
|
setAssignments((a) => ({ ...a, [liId]: domId }));
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const addAllocationRow = (liId: string, totalQty: number) => {
|
||||||
|
setItemAllocations((prev) => {
|
||||||
|
const currentList = prev[liId] || [];
|
||||||
|
const currentSum = currentList.reduce((sum, a) => sum + (parseFloat(String(a.quantity)) || 0), 0);
|
||||||
|
const remaining = Math.max(0, Math.round((totalQty - currentSum) * 10000) / 10000);
|
||||||
|
const usedProjects = new Set(currentList.map((a) => a.project_name).filter(Boolean));
|
||||||
|
const firstAvailable = projectOptions.find((p) => !usedProjects.has(p)) || "";
|
||||||
|
const newRow = {
|
||||||
|
rowId: `alloc-${liId}-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`,
|
||||||
|
project_name: firstAvailable,
|
||||||
|
quantity: remaining > 0 ? remaining : "",
|
||||||
|
};
|
||||||
|
return { ...prev, [liId]: [...currentList, newRow] };
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const removeAllocationRow = (liId: string, rowId: string) => {
|
||||||
|
setItemAllocations((prev) => {
|
||||||
|
const currentList = prev[liId] || [];
|
||||||
|
if (currentList.length <= 1) return prev;
|
||||||
|
return { ...prev, [liId]: currentList.filter((a) => a.rowId !== rowId) };
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const updateAllocationRow = (
|
||||||
|
liId: string,
|
||||||
|
rowId: string,
|
||||||
|
patch: Partial<{ project_name: string; quantity: number | string }>,
|
||||||
|
) => {
|
||||||
|
setItemAllocations((prev) => {
|
||||||
|
const currentList = prev[liId] || [];
|
||||||
|
return {
|
||||||
|
...prev,
|
||||||
|
[liId]: currentList.map((a) => (a.rowId === rowId ? { ...a, ...patch } : a)),
|
||||||
|
};
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
const confirm = () => {
|
const confirm = () => {
|
||||||
if (!q) return;
|
if (!q) return;
|
||||||
|
|
||||||
@@ -162,6 +343,7 @@ export function AcceptModal({ quoteId, onClose }: AcceptModalProps) {
|
|||||||
next.line_items.forEach((li) => {
|
next.line_items.forEach((li) => {
|
||||||
if (removedItems.has(li.id)) li.rejected = true;
|
if (removedItems.has(li.id)) li.rejected = true;
|
||||||
});
|
});
|
||||||
|
|
||||||
const active = activeItems(next);
|
const active = activeItems(next);
|
||||||
if (!active.length) {
|
if (!active.length) {
|
||||||
toast.error("همهی قلمها رد شدهاند؛ حداقل یک قلم لازم است.");
|
toast.error("همهی قلمها رد شدهاند؛ حداقل یک قلم لازم است.");
|
||||||
@@ -206,13 +388,60 @@ export function AcceptModal({ quoteId, onClose }: AcceptModalProps) {
|
|||||||
if (t.status === "accepted" && !usedIds.has(t.id)) t.status = "offered";
|
if (t.status === "accepted" && !usedIds.has(t.id)) t.status = "offered";
|
||||||
});
|
});
|
||||||
|
|
||||||
// پروژهی هر قلم (تکی هدف خرید) — فقط target_project تنظیم میشود؛
|
for (const li of active) {
|
||||||
// li.projects و next.projects دستنخورده باقی میمانند تا پروژههای کاندیدای اولیه حفظ شوند
|
const allocs = itemAllocations[li.id] || [];
|
||||||
|
const m = materialById(materials, li.material_id);
|
||||||
|
const title = formatMaterialTitle(m);
|
||||||
|
const targetQty = Number(li.quantity ?? 0);
|
||||||
|
|
||||||
|
if (!allocs.length) {
|
||||||
|
toast.error(`برای قلم «${title}» حداقل یک ردیف تخصیص به پروژه لازم است.`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const a of allocs) {
|
||||||
|
if (!a.project_name.trim()) {
|
||||||
|
toast.error(`برای قلم «${title}»، لطفاً پروژهٔ تمام ردیفهای تخصیص را مشخص کنید.`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const qVal = parseFloat(String(a.quantity));
|
||||||
|
if (isNaN(qVal) || qVal <= 0) {
|
||||||
|
toast.error(`برای قلم «${title}»، مقدار تخصیص باید عددی بزرگتر از صفر باشد.`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const pNames = allocs.map((a) => a.project_name.trim());
|
||||||
|
if (new Set(pNames).size !== pNames.length) {
|
||||||
|
toast.error(`برای قلم «${title}»، پروژهٔ تکراری در ردیفهای تخصیص انتخاب شده است.`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const sumQty = allocs.reduce((sum, a) => sum + (parseFloat(String(a.quantity)) || 0), 0);
|
||||||
|
const diff = Math.abs(sumQty - targetQty);
|
||||||
|
if (diff > 0.0001) {
|
||||||
|
toast.error(
|
||||||
|
`مجموع مقادیر تخصیصیافته برای «${title}» (${fmtNum(sumQty)} ${li.unit}) با مقدار کل قلم (${fmtNum(targetQty)} ${li.unit}) برابر نیست.`
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
next.line_items.forEach((li) => {
|
next.line_items.forEach((li) => {
|
||||||
if (li.rejected) return;
|
if (li.rejected) return;
|
||||||
|
const allocs = itemAllocations[li.id];
|
||||||
|
if (allocs && allocs.length) {
|
||||||
|
li.allocations = allocs.map((a) => ({
|
||||||
|
project_name: a.project_name.trim(),
|
||||||
|
quantity: parseFloat(String(a.quantity)) || 0,
|
||||||
|
}));
|
||||||
|
li.target_project = { id: "", name: allocs[0].project_name.trim() };
|
||||||
|
} else {
|
||||||
const name = itemProjectsSel[li.id];
|
const name = itemProjectsSel[li.id];
|
||||||
if (name === undefined) return;
|
if (name !== undefined) {
|
||||||
li.target_project = name ? { id: "", name } : null;
|
li.target_project = name ? { id: "", name } : null;
|
||||||
|
}
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
const now = new Date().toISOString();
|
const now = new Date().toISOString();
|
||||||
@@ -232,7 +461,7 @@ export function AcceptModal({ quoteId, onClose }: AcceptModalProps) {
|
|||||||
<DialogContent className="max-w-3xl p-0 gap-0 overflow-hidden bg-slate-50 border-none shadow-2xl rounded-xl">
|
<DialogContent className="max-w-3xl p-0 gap-0 overflow-hidden bg-slate-50 border-none shadow-2xl rounded-xl">
|
||||||
<div className="flex flex-col max-h-[85vh] w-full">
|
<div className="flex flex-col max-h-[85vh] w-full">
|
||||||
|
|
||||||
{/* هدر ثابت و همتراز */}
|
{/* هدر ثابت */}
|
||||||
<div className="px-6 py-4 bg-white border-b border-line shrink-0 z-10 text-right">
|
<div className="px-6 py-4 bg-white border-b border-line shrink-0 z-10 text-right">
|
||||||
<DialogHeader className="p-0 text-right">
|
<DialogHeader className="p-0 text-right">
|
||||||
<DialogTitle className="text-right text-lg font-bold text-slate-800">
|
<DialogTitle className="text-right text-lg font-bold text-slate-800">
|
||||||
@@ -343,53 +572,196 @@ export function AcceptModal({ quoteId, onClose }: AcceptModalProps) {
|
|||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
{/* بخش ۳: تخصیص اقلام به پروژه */}
|
{/* بخش ۳: تخصیص اقلام به پروژهها */}
|
||||||
<section className="bg-white rounded-xl shadow-sm border border-line p-4 md:p-5">
|
<section className="bg-white rounded-xl shadow-sm border border-line p-4 md:p-5">
|
||||||
<h3 className="mb-1 text-[14px] font-bold text-slate-800">۳. تخصیص اقلام به پروژهها</h3>
|
<div className="flex items-center justify-between mb-1">
|
||||||
<div className="mb-4 text-[12px] text-muted">
|
<h3 className="text-[14px] font-bold text-slate-800">۳. تخصیص اقلام به پروژهها</h3>
|
||||||
برای هر متریال خریداری شده، میتوانید پروژه مربوط به آن را مشخص کنید.
|
|
||||||
</div>
|
</div>
|
||||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-3">
|
<div className="mb-4 text-[12px] text-muted">
|
||||||
|
مشخص کنید چه مقداری از هر قلم به کدام پروژه اختصاص داده میشود. در صورت خرید یک کالا برای چند پروژه، میتوانید آن را به چند سطر تفکیک کنید.
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{projectOptions.length === 0 ? (
|
||||||
|
<div className="text-[12px] text-amber-700 bg-amber-50 border border-amber-200 p-3 rounded-md text-center">
|
||||||
|
⚠️ هیچ پروژهای در سیستم ثبت نشده است. لطفاً ابتدا از بخش پروژهها، حداقل یک پروژه ایجاد کنید.
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div className="flex flex-col gap-4">
|
||||||
{allItems
|
{allItems
|
||||||
.filter((li) => !removedItems.has(li.id))
|
.filter((li) => !removedItems.has(li.id))
|
||||||
.map((li) => {
|
.map((li) => {
|
||||||
const m = materialById(materials, li.material_id);
|
const m = materialById(materials, li.material_id);
|
||||||
|
const targetQty = Number(li.quantity ?? 0);
|
||||||
|
const allocs = itemAllocations[li.id] || [];
|
||||||
|
const allocSum = allocs.reduce(
|
||||||
|
(sum, a) => sum + (parseFloat(String(a.quantity)) || 0),
|
||||||
|
0
|
||||||
|
);
|
||||||
|
const diff = Math.round((targetQty - allocSum) * 10000) / 10000;
|
||||||
|
const isComplete = Math.abs(diff) < 0.0001;
|
||||||
|
const isOver = diff < -0.0001;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div key={li.id} className="rounded-lg border border-line p-3 flex flex-col justify-between hover:border-primary/30 transition-colors">
|
<div
|
||||||
<div className="mb-3 flex items-center justify-between">
|
key={li.id}
|
||||||
<span className="text-[13px] font-semibold text-slate-800 truncate">
|
className="rounded-xl border border-line bg-slate-50/50 p-4 transition-all hover:border-primary/30"
|
||||||
|
>
|
||||||
|
{/* هدر کارت قلم */}
|
||||||
|
<div className="flex flex-wrap items-center justify-between gap-2 mb-3 pb-2.5 border-b border-line/60">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<Building2 className="w-4 h-4 text-primary shrink-0" />
|
||||||
|
<span className="text-[13.5px] font-bold text-slate-800">
|
||||||
{formatMaterialTitle(m)}
|
{formatMaterialTitle(m)}
|
||||||
</span>
|
</span>
|
||||||
<span className="ms-2 text-[11px] text-muted bg-slate-100 px-2 py-0.5 rounded-full whitespace-nowrap">
|
|
||||||
{fmtNum(li.quantity)} {li.unit}
|
|
||||||
</span>
|
|
||||||
</div>
|
</div>
|
||||||
{projectOptions.length ? (
|
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<span className="text-[11px] font-medium text-slate-600 bg-white border border-line px-2.5 py-0.5 rounded-full">
|
||||||
|
کل: {fmtNum(targetQty)} {li.unit}
|
||||||
|
</span>
|
||||||
|
|
||||||
|
{isComplete ? (
|
||||||
|
<span className="inline-flex items-center gap-1 text-[11px] font-semibold text-emerald-700 bg-emerald-50 border border-emerald-200 px-2.5 py-0.5 rounded-full">
|
||||||
|
<CheckCircle2 className="w-3 h-3" />
|
||||||
|
تخصیص کامل ({fmtNum(allocSum)} {li.unit})
|
||||||
|
</span>
|
||||||
|
) : isOver ? (
|
||||||
|
<span className="inline-flex items-center gap-1 text-[11px] font-semibold text-red-700 bg-red-50 border border-red-200 px-2.5 py-0.5 rounded-full">
|
||||||
|
<AlertCircle className="w-3 h-3" />
|
||||||
|
مازاد تخصیص: {fmtNum(Math.abs(diff))} {li.unit}
|
||||||
|
</span>
|
||||||
|
) : (
|
||||||
|
<span className="inline-flex items-center gap-1 text-[11px] font-semibold text-amber-700 bg-amber-50 border border-amber-200 px-2.5 py-0.5 rounded-full">
|
||||||
|
<AlertCircle className="w-3 h-3" />
|
||||||
|
باقیمانده: {fmtNum(diff)} {li.unit}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* ردیفهای تخصیص — تراز افقی یکپارچه بدون جابجایی دکمهها */}
|
||||||
|
<div className="flex flex-col gap-2.5 mb-3">
|
||||||
|
{allocs.map((alloc) => {
|
||||||
|
const otherUsedProjects = new Set(
|
||||||
|
allocs
|
||||||
|
.filter((a) => a.rowId !== alloc.rowId)
|
||||||
|
.map((a) => a.project_name.trim())
|
||||||
|
.filter(Boolean)
|
||||||
|
);
|
||||||
|
|
||||||
|
const words = numberToPersianWords(alloc.quantity);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
key={alloc.rowId}
|
||||||
|
className="flex flex-col sm:flex-row items-start gap-2.5 bg-white p-3 rounded-lg border border-line shadow-xs"
|
||||||
|
>
|
||||||
|
{/* انتخاب پروژه و دکمه حذف موبایل */}
|
||||||
|
<div className="flex items-center gap-2 flex-1 w-full sm:w-auto">
|
||||||
|
<div className="flex-1 min-w-0">
|
||||||
<select
|
<select
|
||||||
className="w-full h-9 rounded-md border border-line bg-panel px-2.5 py-1.5 font-inherit text-[12px] outline-none focus:border-primary focus:ring-1 focus:ring-primary transition-all"
|
className="w-full h-9 rounded-md border border-line bg-panel px-2.5 py-1 font-inherit text-[12px] outline-none focus:border-primary focus:ring-1 focus:ring-primary transition-all text-slate-700"
|
||||||
value={itemProjectsSel[li.id] ?? ""}
|
value={alloc.project_name}
|
||||||
onChange={(e) =>
|
onChange={(e) =>
|
||||||
setItemProjectsSel((s) => ({ ...s, [li.id]: e.target.value }))
|
updateAllocationRow(li.id, alloc.rowId, {
|
||||||
|
project_name: e.target.value,
|
||||||
|
})
|
||||||
}
|
}
|
||||||
>
|
>
|
||||||
{(itemProjectsSel[li.id] ? [] : [{ name: "" }]).map((_, i) => (
|
<option value="">انتخاب پروژه...</option>
|
||||||
<option key={i} value="">
|
{projectOptions.map((p) => {
|
||||||
انتخاب پروژه...
|
const isUsed = otherUsedProjects.has(p);
|
||||||
|
return (
|
||||||
|
<option key={p} value={p} disabled={isUsed}>
|
||||||
|
{p} {isUsed ? "(در ردیف دیگر انتخاب شده)" : ""}
|
||||||
</option>
|
</option>
|
||||||
))}
|
);
|
||||||
{projectOptions.map((n) => (
|
})}
|
||||||
<option key={n} value={n}>
|
|
||||||
{n}
|
|
||||||
</option>
|
|
||||||
))}
|
|
||||||
</select>
|
</select>
|
||||||
) : (
|
</div>
|
||||||
<div className="text-[12px] text-muted bg-slate-50 p-2 rounded-md text-center">پروژهای در سیستم ثبت نشده است.</div>
|
|
||||||
)}
|
{/* دکمه حذف موبایل */}
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
disabled={allocs.length <= 1}
|
||||||
|
onClick={() => removeAllocationRow(li.id, alloc.rowId)}
|
||||||
|
className="sm:hidden h-9 w-9 flex items-center justify-center rounded-md border border-line text-slate-400 hover:text-red-600 hover:bg-red-50 hover:border-red-200 transition-colors disabled:opacity-30 disabled:pointer-events-none shrink-0"
|
||||||
|
title="حذف این ردیف تخصیص"
|
||||||
|
>
|
||||||
|
<Trash2 className="w-3.5 h-3.5" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* فیلد مقدار بدون اسپینر + واحد ثابت + متن حروفی */}
|
||||||
|
<div className="flex flex-col w-full sm:w-44 shrink-0">
|
||||||
|
<div className="flex items-stretch h-9 rounded-md border border-line bg-panel overflow-hidden focus-within:border-primary focus-within:ring-1 focus-within:ring-primary transition-all">
|
||||||
|
<input
|
||||||
|
type="number"
|
||||||
|
step="any"
|
||||||
|
min="0"
|
||||||
|
placeholder="مقدار"
|
||||||
|
className="flex-1 min-w-0 h-full bg-transparent px-2.5 py-1 font-inherit text-[12px] outline-none text-left font-mono [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"
|
||||||
|
style={{ MozAppearance: "textfield" }}
|
||||||
|
dir="ltr"
|
||||||
|
value={alloc.quantity}
|
||||||
|
onChange={(e) =>
|
||||||
|
updateAllocationRow(li.id, alloc.rowId, {
|
||||||
|
quantity: e.target.value,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
<div
|
||||||
|
className="px-2.5 bg-slate-100 border-s border-line text-slate-600 text-[12px] font-medium flex items-center justify-center shrink-0 select-none min-w-[42px]"
|
||||||
|
title={`واحد: ${li.unit}`}
|
||||||
|
>
|
||||||
|
{li.unit}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{words ? (
|
||||||
|
<div className="mt-1 text-[11px] text-slate-500 font-medium px-0.5 leading-tight text-right truncate" title={`${words} ${li.unit}`}>
|
||||||
|
{words} {li.unit}
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* دکمه حذف دسکتاپ — تراز شده با لبه بالای دراپداون و اینپوت */}
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
disabled={allocs.length <= 1}
|
||||||
|
onClick={() => removeAllocationRow(li.id, alloc.rowId)}
|
||||||
|
className="hidden sm:flex h-9 w-9 items-center justify-center rounded-md border border-line text-slate-400 hover:text-red-600 hover:bg-red-50 hover:border-red-200 transition-colors disabled:opacity-30 disabled:pointer-events-none shrink-0"
|
||||||
|
title="حذف این ردیف تخصیص"
|
||||||
|
>
|
||||||
|
<Trash2 className="w-3.5 h-3.5" />
|
||||||
|
</button>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
})}
|
})}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{/* فوتر کارت قلم */}
|
||||||
|
<div className="flex items-center justify-between pt-1">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => addAllocationRow(li.id, targetQty)}
|
||||||
|
disabled={
|
||||||
|
allocs.length >= projectOptions.length && projectOptions.length > 0
|
||||||
|
}
|
||||||
|
className="inline-flex items-center gap-1.5 text-[12px] font-medium text-primary hover:text-primary/80 transition-colors disabled:opacity-40 disabled:cursor-not-allowed"
|
||||||
|
>
|
||||||
|
<Plus className="w-3.5 h-3.5" />
|
||||||
|
<span>افزودن ردیف تخصیص (پروژه دیگر)</span>
|
||||||
|
</button>
|
||||||
|
<span className="text-[11px] text-muted">
|
||||||
|
مجموع: {fmtNum(allocSum)} از {fmtNum(targetQty)} {li.unit}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
{/* بخش ۴: فاکتورها، پیشفاکتورها و تاریخ */}
|
{/* بخش ۴: فاکتورها، پیشفاکتورها و تاریخ */}
|
||||||
|
|||||||
@@ -18,12 +18,16 @@ import { LedgerTable } from "./LedgerTable";
|
|||||||
import { AppSwitcherMenu } from "../../components/AppSwitcherMenu";
|
import { AppSwitcherMenu } from "../../components/AppSwitcherMenu";
|
||||||
import { AcceptModal } from "./AcceptModal";
|
import { AcceptModal } from "./AcceptModal";
|
||||||
import { EditModal } from "./EditModal";
|
import { EditModal } from "./EditModal";
|
||||||
|
import { useAuthStore } from "../../store/auth";
|
||||||
|
|
||||||
const EMPTY_FILTERS: Filters = { supplier: "", status: "", search: "" };
|
const EMPTY_FILTERS: Filters = { supplier: "", status: "", search: "" };
|
||||||
|
|
||||||
export function DashboardPage() {
|
export function DashboardPage() {
|
||||||
useStoreData();
|
useStoreData();
|
||||||
|
|
||||||
|
const user = useAuthStore((s) => s.user);
|
||||||
|
const canWrite = user?.role === "admin" || user?.role === "procurement_manager";
|
||||||
|
|
||||||
const quotes = useQuotes();
|
const quotes = useQuotes();
|
||||||
const suppliers = useSuppliers();
|
const suppliers = useSuppliers();
|
||||||
const materials = useMaterials();
|
const materials = useMaterials();
|
||||||
@@ -85,7 +89,7 @@ export function DashboardPage() {
|
|||||||
return (
|
return (
|
||||||
<div className="min-h-screen pb-20 md:pb-6">
|
<div className="min-h-screen pb-20 md:pb-6">
|
||||||
<Header
|
<Header
|
||||||
title="دفتر پیشنهادهای خرید"
|
title="مدیریت تدارکات"
|
||||||
brand
|
brand
|
||||||
menu={<AppSwitcherMenu activeModule="procurement" />}
|
menu={<AppSwitcherMenu activeModule="procurement" />}
|
||||||
actions={
|
actions={
|
||||||
@@ -114,6 +118,7 @@ export function DashboardPage() {
|
|||||||
</Link>
|
</Link>
|
||||||
|
|
||||||
{/* دکمه اصلی: افزودن پیشنهاد جدید */}
|
{/* دکمه اصلی: افزودن پیشنهاد جدید */}
|
||||||
|
{canWrite && (
|
||||||
<Link
|
<Link
|
||||||
to="/wizard"
|
to="/wizard"
|
||||||
className="inline-flex items-center gap-1.5 px-4 py-2 rounded-xl bg-blue-600 hover:bg-blue-700 active:bg-blue-800 text-white text-xs font-semibold shadow-sm hover:shadow transition-all no-underline"
|
className="inline-flex items-center gap-1.5 px-4 py-2 rounded-xl bg-blue-600 hover:bg-blue-700 active:bg-blue-800 text-white text-xs font-semibold shadow-sm hover:shadow transition-all no-underline"
|
||||||
@@ -121,6 +126,7 @@ export function DashboardPage() {
|
|||||||
<Plus className="h-4 w-4" />
|
<Plus className="h-4 w-4" />
|
||||||
<span>افزودن پیشنهاد جدید</span>
|
<span>افزودن پیشنهاد جدید</span>
|
||||||
</Link>
|
</Link>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
@@ -148,10 +154,12 @@ export function DashboardPage() {
|
|||||||
onToggleExpand={toggleExpand}
|
onToggleExpand={toggleExpand}
|
||||||
onAccept={setAcceptId}
|
onAccept={setAcceptId}
|
||||||
onEdit={setEditId}
|
onEdit={setEditId}
|
||||||
|
canWrite={canWrite}
|
||||||
/>
|
/>
|
||||||
</PageLayout>
|
</PageLayout>
|
||||||
|
|
||||||
{/* دکمه شناور اکشن (FAB) مخصوص نسخه موبایل */}
|
{/* دکمه شناور اکشن (FAB) مخصوص نسخه موبایل */}
|
||||||
|
{canWrite && (
|
||||||
<Link
|
<Link
|
||||||
to="/wizard"
|
to="/wizard"
|
||||||
aria-label="افزودن پیشنهاد جدید"
|
aria-label="افزودن پیشنهاد جدید"
|
||||||
@@ -159,6 +167,7 @@ export function DashboardPage() {
|
|||||||
>
|
>
|
||||||
<Plus className="h-7 w-7" />
|
<Plus className="h-7 w-7" />
|
||||||
</Link>
|
</Link>
|
||||||
|
)}
|
||||||
|
|
||||||
<AcceptModal quoteId={acceptId} onClose={() => setAcceptId(null)} />
|
<AcceptModal quoteId={acceptId} onClose={() => setAcceptId(null)} />
|
||||||
<EditModal quoteId={editId} onClose={() => setEditId(null)} />
|
<EditModal quoteId={editId} onClose={() => setEditId(null)} />
|
||||||
|
|||||||
@@ -438,7 +438,26 @@ export function EditModal({ quoteId, onClose }: EditModalProps) {
|
|||||||
li.accepted_ts_id = null;
|
li.accepted_ts_id = null;
|
||||||
li.target_project = null;
|
li.target_project = null;
|
||||||
li.target_project_id = null;
|
li.target_project_id = null;
|
||||||
|
li.allocations = undefined;
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// ادغام سطرهای تفکیکشده حاصل از تخصیص چندپروژهای (الزام ۲)
|
||||||
|
const mergedMap = new Map<string, LineItem>();
|
||||||
|
for (const li of next.line_items) {
|
||||||
|
const key = `${li.material_id}__${li.unit || ""}__${li.unit_price ?? ""}`;
|
||||||
|
const existing = mergedMap.get(key);
|
||||||
|
if (existing) {
|
||||||
|
const q1 = Number(existing.quantity ?? 0);
|
||||||
|
const q2 = Number(li.quantity ?? 0);
|
||||||
|
existing.quantity = Math.round((q1 + q2) * 10000) / 10000;
|
||||||
|
if (existing.unit_price != null && existing.quantity != null) {
|
||||||
|
existing.total_price = existing.unit_price * existing.quantity;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
mergedMap.set(key, { ...li });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
next.line_items = Array.from(mergedMap.values());
|
||||||
} else if (next.status === "accepted") {
|
} else if (next.status === "accepted") {
|
||||||
next.arrived_date = null;
|
next.arrived_date = null;
|
||||||
next.line_items.forEach((li) => {
|
next.line_items.forEach((li) => {
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ export interface LedgerTableProps {
|
|||||||
onToggleExpand: (id: string) => void;
|
onToggleExpand: (id: string) => void;
|
||||||
onAccept: (id: string) => void;
|
onAccept: (id: string) => void;
|
||||||
onEdit: (id: string) => void;
|
onEdit: (id: string) => void;
|
||||||
|
canWrite?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
// دفتر پیشنهادها — فهرست کارتها (واکنشگرا و بهینه برای موبایل)
|
// دفتر پیشنهادها — فهرست کارتها (واکنشگرا و بهینه برای موبایل)
|
||||||
@@ -20,6 +21,7 @@ export function LedgerTable({
|
|||||||
onToggleExpand,
|
onToggleExpand,
|
||||||
onAccept,
|
onAccept,
|
||||||
onEdit,
|
onEdit,
|
||||||
|
canWrite = true,
|
||||||
}: LedgerTableProps) {
|
}: LedgerTableProps) {
|
||||||
if (!quotes.length) {
|
if (!quotes.length) {
|
||||||
return (
|
return (
|
||||||
@@ -40,6 +42,7 @@ export function LedgerTable({
|
|||||||
onToggleExpand={() => onToggleExpand(q.id)}
|
onToggleExpand={() => onToggleExpand(q.id)}
|
||||||
onAccept={() => onAccept(q.id)}
|
onAccept={() => onAccept(q.id)}
|
||||||
onEdit={() => onEdit(q.id)}
|
onEdit={() => onEdit(q.id)}
|
||||||
|
canWrite={canWrite}
|
||||||
/>
|
/>
|
||||||
))}
|
))}
|
||||||
<div className="px-2 py-3 text-center text-[10.5px] leading-5 text-muted sm:py-1 sm:text-[11px]">
|
<div className="px-2 py-3 text-center text-[10.5px] leading-5 text-muted sm:py-1 sm:text-[11px]">
|
||||||
|
|||||||
@@ -24,6 +24,7 @@ export interface QuoteCardProps {
|
|||||||
onToggleExpand: () => void;
|
onToggleExpand: () => void;
|
||||||
onAccept: () => void;
|
onAccept: () => void;
|
||||||
onEdit: () => void;
|
onEdit: () => void;
|
||||||
|
canWrite?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
function InfoCell({ label, children, className }: { label: string; children: React.ReactNode; className?: string }) {
|
function InfoCell({ label, children, className }: { label: string; children: React.ReactNode; className?: string }) {
|
||||||
@@ -35,7 +36,7 @@ function InfoCell({ label, children, className }: { label: string; children: Rea
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function QuoteCard({ store, q, expanded, onToggleExpand, onAccept, onEdit }: QuoteCardProps) {
|
export function QuoteCard({ store, q, expanded, onToggleExpand, onAccept, onEdit, canWrite = true }: QuoteCardProps) {
|
||||||
const sup = supplierById(store.suppliers, q.supplier_id);
|
const sup = supplierById(store.suppliers, q.supplier_id);
|
||||||
const expired = isExpired(q);
|
const expired = isExpired(q);
|
||||||
const total = quoteTotal(q);
|
const total = quoteTotal(q);
|
||||||
@@ -46,7 +47,7 @@ export function QuoteCard({ store, q, expanded, onToggleExpand, onAccept, onEdit
|
|||||||
// ستون / دکمه پذیرش
|
// ستون / دکمه پذیرش
|
||||||
let acceptedCell: React.ReactNode;
|
let acceptedCell: React.ReactNode;
|
||||||
if (q.status === "offered") {
|
if (q.status === "offered") {
|
||||||
acceptedCell = (
|
acceptedCell = canWrite ? (
|
||||||
<button
|
<button
|
||||||
onClick={(e) => {
|
onClick={(e) => {
|
||||||
e.stopPropagation();
|
e.stopPropagation();
|
||||||
@@ -57,6 +58,8 @@ export function QuoteCard({ store, q, expanded, onToggleExpand, onAccept, onEdit
|
|||||||
<Check className="h-3.5 w-3.5" />
|
<Check className="h-3.5 w-3.5" />
|
||||||
<span>پذیرش</span>
|
<span>پذیرش</span>
|
||||||
</button>
|
</button>
|
||||||
|
) : (
|
||||||
|
<span className="text-muted text-xs font-medium">در انتظار پذیرش</span>
|
||||||
);
|
);
|
||||||
} else if (q.accepted_date) {
|
} else if (q.accepted_date) {
|
||||||
acceptedCell = <span className="tabular-nums font-medium">{fmtDateTime(q.accepted_date)}</span>;
|
acceptedCell = <span className="tabular-nums font-medium">{fmtDateTime(q.accepted_date)}</span>;
|
||||||
@@ -185,6 +188,7 @@ export function QuoteCard({ store, q, expanded, onToggleExpand, onAccept, onEdit
|
|||||||
)}
|
)}
|
||||||
|
|
||||||
{/* دکمه ویرایش */}
|
{/* دکمه ویرایش */}
|
||||||
|
{canWrite && (
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
className="inline-flex h-7 items-center justify-center gap-1 rounded-md border border-line bg-panel px-2 text-xs font-medium text-ink hover:bg-slate-50 dark:hover:bg-zinc-800 transition-colors sm:h-8 sm:px-2.5"
|
className="inline-flex h-7 items-center justify-center gap-1 rounded-md border border-line bg-panel px-2 text-xs font-medium text-ink hover:bg-slate-50 dark:hover:bg-zinc-800 transition-colors sm:h-8 sm:px-2.5"
|
||||||
@@ -198,6 +202,7 @@ export function QuoteCard({ store, q, expanded, onToggleExpand, onAccept, onEdit
|
|||||||
<Pencil className="h-3 w-3 text-muted" />
|
<Pencil className="h-3 w-3 text-muted" />
|
||||||
<span className="hidden sm:inline">ویرایش</span>
|
<span className="hidden sm:inline">ویرایش</span>
|
||||||
</button>
|
</button>
|
||||||
|
)}
|
||||||
|
|
||||||
{/* دکمه فلش اکسپند در هدر */}
|
{/* دکمه فلش اکسپند در هدر */}
|
||||||
<button
|
<button
|
||||||
|
|||||||
@@ -0,0 +1,106 @@
|
|||||||
|
import { useMemo } from "react";
|
||||||
|
import { Link } from "react-router-dom";
|
||||||
|
import { FilePlus2, Info } from "lucide-react";
|
||||||
|
import { Header, PageLayout } from "../../components/layout/Header";
|
||||||
|
import { AppSwitcherMenu } from "../../components/AppSwitcherMenu";
|
||||||
|
import { useAuthStore } from "../../store/auth";
|
||||||
|
import { useProjects } from "../../hooks";
|
||||||
|
import { faNum } from "../../lib/formatters";
|
||||||
|
|
||||||
|
// خانه کاربرِ «تدارکات — سطح limited»: افزودن استعلام برای پروژههای تخصیصیافته
|
||||||
|
export function RequesterHome() {
|
||||||
|
const user = useAuthStore((s) => s.user);
|
||||||
|
const projects = useProjects();
|
||||||
|
|
||||||
|
// پروژههای کاربر از همه منابع موجود در سیستم (user.projects، user.project_id، member_project_ids و پروژههای عمومی)
|
||||||
|
const myProjects = useMemo(() => {
|
||||||
|
const list: { id: string; name: string }[] = [];
|
||||||
|
const seen = new Set<string>();
|
||||||
|
|
||||||
|
// ۱. پروژههای موجود در آرایه user.projects
|
||||||
|
for (const p of user?.projects ?? []) {
|
||||||
|
if (p.id && !seen.has(p.id)) {
|
||||||
|
seen.add(p.id);
|
||||||
|
list.push({ id: p.id, name: p.name });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ۲. پروژهی اختصاصی فعال (project_id)
|
||||||
|
if (user?.project_id && !seen.has(user.project_id)) {
|
||||||
|
seen.add(user.project_id);
|
||||||
|
list.push({ id: user.project_id, name: user.project_name || "پروژه تخصیصیافته" });
|
||||||
|
}
|
||||||
|
|
||||||
|
// ۳. پروژههای عضویت member_project_ids تطبیقیافته با لیست پروژهها
|
||||||
|
const memberIdSet = new Set(user?.member_project_ids ?? []);
|
||||||
|
for (const p of projects) {
|
||||||
|
if (memberIdSet.has(p.id) && !seen.has(p.id)) {
|
||||||
|
seen.add(p.id);
|
||||||
|
list.push({ id: p.id, name: p.name });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ۴. تطبیق نام پروژه در صورتی که فقط نام در نشست باشد
|
||||||
|
if (list.length === 0 && user?.project_name) {
|
||||||
|
const match = projects.find((p) => p.name === user.project_name);
|
||||||
|
if (match && !seen.has(match.id)) {
|
||||||
|
list.push({ id: match.id, name: match.name });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return list;
|
||||||
|
}, [user, projects]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="min-h-screen">
|
||||||
|
<Header
|
||||||
|
title="افزودن استعلام"
|
||||||
|
brand
|
||||||
|
menu={<AppSwitcherMenu activeModule="procurement" />}
|
||||||
|
/>
|
||||||
|
<PageLayout className="flex flex-col gap-4">
|
||||||
|
<div className="rounded-lg border border-blue/20 bg-blue/5 px-3 py-2 text-[12px] leading-6 text-muted">
|
||||||
|
<span className="inline-flex items-center gap-1.5">
|
||||||
|
<Info className="h-3.5 w-3.5" />
|
||||||
|
شما مجاز به ثبت استعلام برای پروژههای تخصیصیافتهی خود هستید.
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{myProjects.length === 0 ? (
|
||||||
|
<div className="rounded-xl border border-dashed border-line bg-panel px-4 py-8 text-center text-[12.5px] text-muted">
|
||||||
|
هنوز پروژهای به شما تخصیص داده نشده است — با مدیر سیستم تماس بگیرید.
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<div className="grid grid-cols-1 gap-3 md:grid-cols-2">
|
||||||
|
{myProjects.map((p) => (
|
||||||
|
<Link
|
||||||
|
key={p.id}
|
||||||
|
to={`/wizard?project=${encodeURIComponent(p.name)}`}
|
||||||
|
className="flex items-center justify-between rounded-xl border border-line bg-panel p-4 no-underline transition-colors hover:border-accent/50 hover:bg-canvas/40"
|
||||||
|
>
|
||||||
|
<div>
|
||||||
|
<b className="text-[13.5px]">🏢 {p.name}</b>
|
||||||
|
<p className="mt-0.5 text-[11.5px] text-muted">ثبت استعلام خرید برای این پروژه</p>
|
||||||
|
</div>
|
||||||
|
<span className="flex h-10 w-10 shrink-0 items-center justify-center rounded-full bg-accent/10 text-accent">
|
||||||
|
<FilePlus2 className="h-5 w-5" />
|
||||||
|
</span>
|
||||||
|
</Link>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Link
|
||||||
|
to="/wizard"
|
||||||
|
className="btn-line-file inline-flex items-center justify-center gap-2 no-underline"
|
||||||
|
>
|
||||||
|
<FilePlus2 className="h-3.5 w-3.5" />
|
||||||
|
افزودن استعلام جدید ({faNum(myProjects.length)} پروژه فعال)
|
||||||
|
</Link>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</PageLayout>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
@@ -8,7 +8,7 @@ import { useAuthStore } from "../../store/auth";
|
|||||||
import { inventorySubheader } from "./panelMenu";
|
import { inventorySubheader } from "./panelMenu";
|
||||||
import { apiV26 } from "../../lib/api";
|
import { apiV26 } from "../../lib/api";
|
||||||
import { refreshProcurementStore } from "../../hooks";
|
import { refreshProcurementStore } from "../../hooks";
|
||||||
import type { PendingArrival, Warehouse } from "../../lib/types";
|
import type { PendingArrival, Warehouse, ProjectTransfer } from "../../lib/types";
|
||||||
import { faNum, fmtDate } from "../../lib/formatters";
|
import { faNum, fmtDate } from "../../lib/formatters";
|
||||||
|
|
||||||
// کالاهای در راه — داشبورد متصل به سیستم تدارکات (مرحله رسید)
|
// کالاهای در راه — داشبورد متصل به سیستم تدارکات (مرحله رسید)
|
||||||
@@ -23,36 +23,45 @@ export function ArrivalsPage() {
|
|||||||
const user = useAuthStore((s) => s.user);
|
const user = useAuthStore((s) => s.user);
|
||||||
const isAdmin = user?.role === "admin" || user?.role === "procurement_manager";
|
const isAdmin = user?.role === "admin" || user?.role === "procurement_manager";
|
||||||
const isPM = user?.role === "pm";
|
const isPM = user?.role === "pm";
|
||||||
|
const isSupervisor = user?.role === "supervisor";
|
||||||
|
const canAccess = isAdmin || isPM || isSupervisor;
|
||||||
|
|
||||||
const [items, setItems] = useState<PendingArrival[]>([]);
|
const [items, setItems] = useState<PendingArrival[]>([]);
|
||||||
|
const [incomingTransfers, setIncomingTransfers] = useState<ProjectTransfer[]>([]);
|
||||||
const [warehouses, setWarehouses] = useState<Warehouse[]>([]);
|
const [warehouses, setWarehouses] = useState<Warehouse[]>([]);
|
||||||
const [loading, setLoading] = useState(true);
|
const [loading, setLoading] = useState(true);
|
||||||
const [saving, setSaving] = useState<string | null>(null); // quoteId
|
const [saving, setSaving] = useState<string | null>(null); // quoteId
|
||||||
|
const [transferSaving, setTransferSaving] = useState<string | null>(null); // transferId
|
||||||
const [expanded, setExpanded] = useState<Set<string>>(new Set());
|
const [expanded, setExpanded] = useState<Set<string>>(new Set());
|
||||||
const [drafts, setDrafts] = useState<Record<string, ItemDraft>>({});
|
const [drafts, setDrafts] = useState<Record<string, ItemDraft>>({});
|
||||||
|
const [transferDrafts, setTransferDrafts] = useState<Record<string, AllocRow[]>>({});
|
||||||
|
|
||||||
const load = useCallback(async () => {
|
const load = useCallback(async () => {
|
||||||
try {
|
try {
|
||||||
const activeProject = isPM ? user?.project_id || undefined : undefined;
|
const activeProject = (isPM || isSupervisor) ? user?.project_id || undefined : undefined;
|
||||||
const [arr, whs] = await Promise.all([
|
const [arr, whs, incoming] = await Promise.all([
|
||||||
// پروژهی فعال صریحاً ارسال میشود؛ بکاند تخصیص PM را بررسی میکند
|
// پروژهی فعال صریحاً ارسال میشود؛ بکاند تخصیص PM / سرپرست را بررسی میکند
|
||||||
apiV26.pm.onTheWay(activeProject),
|
apiV26.pm.onTheWay(activeProject),
|
||||||
apiV26.warehouses.list(activeProject),
|
apiV26.warehouses.list(activeProject),
|
||||||
|
apiV26.projectTransfers.onTheWay(activeProject),
|
||||||
]);
|
]);
|
||||||
setItems(arr);
|
setItems(Array.isArray(arr) ? arr : []);
|
||||||
setWarehouses(whs);
|
setWarehouses(Array.isArray(whs) ? whs : []);
|
||||||
|
setIncomingTransfers(Array.isArray(incoming) ? incoming : []);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
toast.error(err instanceof Error ? err.message : "خطا در دریافت کالاهای در راه");
|
toast.error(err instanceof Error ? err.message : "خطا در دریافت کالاهای در راه");
|
||||||
|
setItems([]);
|
||||||
|
setIncomingTransfers([]);
|
||||||
} finally {
|
} finally {
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
}
|
}
|
||||||
}, [isPM, user?.project_id]);
|
}, [isPM, isSupervisor, user?.project_id]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!isAdmin && !isPM) return;
|
if (!canAccess) return;
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
void load();
|
void load();
|
||||||
}, [isAdmin, isPM, load]);
|
}, [canAccess, load]);
|
||||||
|
|
||||||
// سفارشها: گروهبندی اقلام بهازای هر پیشنهاد (فقط سفارشهای دارای قلمِ در راه/ناقص)
|
// سفارشها: گروهبندی اقلام بهازای هر پیشنهاد (فقط سفارشهای دارای قلمِ در راه/ناقص)
|
||||||
const orders = useMemo(() => {
|
const orders = useMemo(() => {
|
||||||
@@ -212,12 +221,60 @@ export function ArrivalsPage() {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
if (!isAdmin && !isPM) {
|
// ---------- transfer helpers ----------
|
||||||
|
|
||||||
|
const transferDraftOf = (t: ProjectTransfer): AllocRow[] => {
|
||||||
|
if (transferDrafts[t.id] && transferDrafts[t.id].length > 0) {
|
||||||
|
return transferDrafts[t.id];
|
||||||
|
}
|
||||||
|
const defaultWh = warehouses.find((w) => String(w.project_id) === String(t.to_project.id))?.id || warehouses[0]?.id || "";
|
||||||
|
return [{ key: 1, qty: String(t.quantity), whId: defaultWh }];
|
||||||
|
};
|
||||||
|
|
||||||
|
const setTransferAlloc = (transferId: string, rows: AllocRow[]) => {
|
||||||
|
setTransferDrafts((prev) => ({ ...prev, [transferId]: rows }));
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleReceiveTransfer = async (transfer: ProjectTransfer, allocs: AllocRow[]) => {
|
||||||
|
const activeProject = isPM ? user?.project_id || undefined : undefined;
|
||||||
|
const allocSum = round4(allocs.reduce((s, a) => s + (parseFloat(a.qty) || 0), 0));
|
||||||
|
const targetQty = parseFloat(String(transfer.quantity));
|
||||||
|
|
||||||
|
if (allocSum !== targetQty) {
|
||||||
|
toast.error(`مجموع تخصیص انبارها (${faNum(allocSum)}) باید دقیقاً برابر کل بار ارسالی (${faNum(targetQty)}) باشد.`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (allocs.some((a) => (parseFloat(a.qty) || 0) > 0 && !a.whId)) {
|
||||||
|
toast.error("لطفاً برای تمامی ردیفهای دارای مقدار، انبار مقصد را انتخاب کنید.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
setTransferSaving(transfer.id);
|
||||||
|
try {
|
||||||
|
const payloadAllocs = allocs
|
||||||
|
.filter((a) => (parseFloat(a.qty) || 0) > 0 && a.whId)
|
||||||
|
.map((a) => ({ warehouse_id: a.whId, quantity: parseFloat(a.qty) }));
|
||||||
|
|
||||||
|
await apiV26.projectTransfers.receive(transfer.id, {
|
||||||
|
allocations: payloadAllocs,
|
||||||
|
}, activeProject);
|
||||||
|
|
||||||
|
toast.success("تحویل انتقال بین کارگاهی ۱۰۰٪ تأیید شد و به انبار پروژه وارد گردید ✓");
|
||||||
|
await load();
|
||||||
|
} catch (err) {
|
||||||
|
toast.error(err instanceof Error ? err.message : "خطا در تأیید تحویل انتقال");
|
||||||
|
} finally {
|
||||||
|
setTransferSaving(null);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
if (!canAccess) {
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="min-h-screen">
|
<div className="min-h-screen">
|
||||||
<Header title="کالاهای در راه" backTo="/inventory" backLabel="بازگشت به داشبورد" />
|
<Header title="کالاهای در راه" backTo="/inventory" backLabel="بازگشت به داشبورد" />
|
||||||
<PageLayout>
|
<PageLayout>
|
||||||
<EmptyState emoji="🔒" text="این بخش فقط برای مدیر پروژه و مدیر تدارکات است." />
|
<EmptyState emoji="🔒" text="این بخش برای نقش کاربری شما مجاز نیست." />
|
||||||
</PageLayout>
|
</PageLayout>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
@@ -233,19 +290,171 @@ export function ArrivalsPage() {
|
|||||||
/>
|
/>
|
||||||
<PageLayout className="flex flex-col gap-4">
|
<PageLayout className="flex flex-col gap-4">
|
||||||
<div className="rounded-lg border border-blue/20 bg-blue/5 px-3 py-2 text-[12px] leading-6 text-muted">
|
<div className="rounded-lg border border-blue/20 bg-blue/5 px-3 py-2 text-[12px] leading-6 text-muted">
|
||||||
🚚 این بخش به مرحله «رسید» سفارشهای خرید متصل است: تأیید پیشنهاد و پذیرش در سیستم تدارکات انجام شده و
|
🚚 این بخش به مرحله «رسید» سفارشهای خرید و «انتقال بین کارگاهی» متصل است: اقلام ارسالی از سایر پروژهها به صورت ۱۰۰٪ تحویل و بین انبارهای پروژه تخصیص داده میشوند؛ سفارشهای خرید نیز قابلیت رسید کامل یا جزیی دارند.
|
||||||
اینجا فقط رسید و تقسیم بین انبارها ثبت میشود. <b>رسید جزیی (قلمی و مقداری) مجاز است</b> — هر سفارش را باز
|
|
||||||
کنید، تعداد واقعیِ رسیده هر قلم را وارد کنید و آن را بین انبارهای پروژه تقسیم کنید؛ قلمهایی که مقداری برایشان
|
|
||||||
وارد نشود در صف «در راه» میمانند. مجموع تخصیص هر قلم باید دقیقاً با تعداد رسیدهی همان قلم برابر باشد و از
|
|
||||||
ماندهی سفارش بیشتر نشود.
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{loading ? (
|
{loading ? (
|
||||||
<div className="py-6 text-center text-[12.5px] text-muted">در حال بارگذاری…</div>
|
<div className="py-6 text-center text-[12.5px] text-muted">در حال بارگذاری…</div>
|
||||||
) : !orders.length ? (
|
) : !(orders || []).length && !(incomingTransfers || []).length ? (
|
||||||
<EmptyState emoji="🚚" text="کالای در راهی برای دریافت وجود ندارد." />
|
<EmptyState emoji="🚚" text="کالای در راهی برای دریافت وجود ندارد." />
|
||||||
) : (
|
) : (
|
||||||
orders.map(([quoteId, its]) => {
|
<>
|
||||||
|
{/* بخش انتقالهای بین کارگاهی در راه */}
|
||||||
|
{(incomingTransfers || []).length > 0 && (
|
||||||
|
<div className="flex flex-col gap-3">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<h3 className="text-[14px] font-bold text-foreground">🔁 انتقالهای بین کارگاهی در راه ({faNum((incomingTransfers || []).length)})</h3>
|
||||||
|
<span className="text-[11.5px] text-muted">— تحویل ۱۰۰٪ کامل مصالح ارسالی از سایر پروژهها</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{(incomingTransfers || []).map((t) => {
|
||||||
|
const draftAllocs = transferDraftOf(t);
|
||||||
|
const allocSum = round4(draftAllocs.reduce((s, a) => s + (parseFloat(a.qty) || 0), 0));
|
||||||
|
const targetQty = parseFloat(String(t.quantity));
|
||||||
|
const isExactMatch = allocSum === targetQty;
|
||||||
|
const hasEmptyWh = draftAllocs.some((a) => (parseFloat(a.qty) || 0) > 0 && !a.whId);
|
||||||
|
const isValid = isExactMatch && !hasEmptyWh && allocSum > 0;
|
||||||
|
const days = daysElapsed(t.transfer_date);
|
||||||
|
const projectWhs = warehouses.filter((w) => String(w.project_id) === String(t.to_project.id));
|
||||||
|
const destWhOptions = projectWhs.length > 0 ? projectWhs : warehouses;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div key={t.id} className="overflow-hidden rounded-xl border border-line bg-panel shadow-sm">
|
||||||
|
{/* سربرگ انتقال */}
|
||||||
|
<div className="flex flex-wrap items-center justify-between gap-2 border-b border-line bg-panel px-4 py-3">
|
||||||
|
<div className="flex flex-wrap items-center gap-2">
|
||||||
|
<span className="text-[14px] font-bold text-foreground">🔁 انتقال از {t.from_project?.name || "پروژه مبدأ"}</span>
|
||||||
|
<Badge variant="offered">در راه</Badge>
|
||||||
|
{days !== null && (
|
||||||
|
<Badge variant={days >= 7 ? "offered" : "muted"}>
|
||||||
|
روز گذشته: {faNum(days)} روز
|
||||||
|
</Badge>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<div className="flex flex-wrap items-center gap-3 text-[11.5px] text-muted">
|
||||||
|
<span>ارسالکننده: <b className="text-foreground">{t.transferred_by || "—"}</b></span>
|
||||||
|
<span>تاریخ ارسال: <b className="text-foreground">{fmtDate(t.transfer_date)}</b></span>
|
||||||
|
<span>پروژه مقصد: <b className="text-foreground">{t.to_project?.name || "—"}</b></span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="px-4 py-3">
|
||||||
|
<div className="flex flex-wrap items-center gap-2">
|
||||||
|
<span className="text-[13px] font-bold">{t.material?.name}</span>
|
||||||
|
{t.brand?.name && <Badge variant="outline">{t.brand.name}</Badge>}
|
||||||
|
<Badge variant="outline">
|
||||||
|
مقدار ارسالی: {faNum(t.quantity)} {t.unit?.name_fa || t.unit?.code || ""}
|
||||||
|
</Badge>
|
||||||
|
{t.specs && Object.keys(t.specs).length > 0 && (
|
||||||
|
<span className="text-[11.5px] text-muted">
|
||||||
|
مشخصات: {Object.entries(t.specs).map(([k, v]) => `${k}: ${v}`).join(" · ")}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{t.note && (
|
||||||
|
<div className="mt-1 text-[11.5px] text-muted">
|
||||||
|
یادداشت ارسال: <span className="text-foreground">{t.note}</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div className="mt-3 rounded-lg border border-line/70 bg-bg/50 p-3">
|
||||||
|
<div className="text-[12px] font-semibold text-muted mb-2">
|
||||||
|
تخصیص ۱۰۰٪ به انبار(های) پروژه (مجموع باید دقیقاً {faNum(t.quantity)} {t.unit?.name_fa || t.unit?.code || ""} باشد):
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex flex-col gap-2">
|
||||||
|
{draftAllocs.map((a) => (
|
||||||
|
<div key={a.key} className="flex flex-wrap items-center gap-2">
|
||||||
|
<input
|
||||||
|
type="number"
|
||||||
|
inputMode="decimal"
|
||||||
|
className="h-8 w-28 rounded-lg border border-line bg-panel px-2 text-sm ltr"
|
||||||
|
placeholder="تعداد"
|
||||||
|
value={a.qty}
|
||||||
|
onChange={(e) => {
|
||||||
|
const next = draftAllocs.map((x) => (x.key === a.key ? { ...x, qty: e.target.value } : x));
|
||||||
|
setTransferAlloc(t.id, next);
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
<select
|
||||||
|
className="h-8 min-w-[200px] flex-1 rounded-lg border border-line bg-panel px-2 text-xs"
|
||||||
|
value={a.whId}
|
||||||
|
onChange={(e) => {
|
||||||
|
const next = draftAllocs.map((x) => (x.key === a.key ? { ...x, whId: e.target.value } : x));
|
||||||
|
setTransferAlloc(t.id, next);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<option value="">— انتخاب انبار پروژه مقصد —</option>
|
||||||
|
{destWhOptions.map((w) => (
|
||||||
|
<option key={w.id} value={w.id}>{w.name}</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
{draftAllocs.length > 1 && (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="h-8 px-2 text-muted hover:text-red transition-colors"
|
||||||
|
onClick={() => {
|
||||||
|
const next = draftAllocs.filter((x) => x.key !== a.key);
|
||||||
|
setTransferAlloc(t.id, next);
|
||||||
|
}}
|
||||||
|
title="حذف این ردیف تخصیص"
|
||||||
|
>
|
||||||
|
✕
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="w-fit rounded-lg border border-dashed border-accent/50 px-3 py-1 text-[11.5px] text-accent mt-1 hover:bg-accent-bg/40 transition-colors"
|
||||||
|
onClick={() => {
|
||||||
|
const next = [...draftAllocs, { key: Date.now() + Math.random(), qty: "", whId: destWhOptions[0]?.id || "" }];
|
||||||
|
setTransferAlloc(t.id, next);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
+ افزودن انبار دیگر برای تقسیم بار
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="mt-3 flex flex-wrap items-center justify-between gap-2 border-t border-line/60 pt-2 text-[12px]">
|
||||||
|
<div>
|
||||||
|
{isExactMatch ? (
|
||||||
|
<span className="font-semibold text-emerald-600">
|
||||||
|
✓ تخصیص کامل ۱۰۰٪ ({faNum(allocSum)} از {faNum(targetQty)}) آماده تحویل
|
||||||
|
</span>
|
||||||
|
) : (
|
||||||
|
<span className="font-bold text-rose-600">
|
||||||
|
اختلاف تخصیص: مجموع تخصیص ({faNum(allocSum)}) باید دقیقاً با مقدار کل ({faNum(targetQty)}) برابر باشد.
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
{hasEmptyWh && (
|
||||||
|
<span className="ms-2 font-bold text-rose-600">
|
||||||
|
— لطفاً انبار مقصد را انتخاب کنید
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Button
|
||||||
|
size="sm"
|
||||||
|
variant="green"
|
||||||
|
disabled={!isValid || transferSaving === t.id}
|
||||||
|
onClick={() => void handleReceiveTransfer(t, draftAllocs)}
|
||||||
|
>
|
||||||
|
{transferSaving === t.id ? "در حال ثبت تحویل…" : "✓ تأیید تحویل ۱۰۰٪ و ورود به انبار"}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* بخش سفارشهای خرید در راه */}
|
||||||
|
{orders.map(([quoteId, its]) => {
|
||||||
const first = its[0];
|
const first = its[0];
|
||||||
const open = expanded.has(quoteId);
|
const open = expanded.has(quoteId);
|
||||||
const hasSubmittable = orderHasSubmittable(quoteId);
|
const hasSubmittable = orderHasSubmittable(quoteId);
|
||||||
@@ -401,7 +610,8 @@ export function ArrivalsPage() {
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
})
|
})}
|
||||||
|
</>
|
||||||
)}
|
)}
|
||||||
</PageLayout>
|
</PageLayout>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -41,10 +41,12 @@ export function DailyControlPage() {
|
|||||||
|
|
||||||
const txByDay = useMemo(() => {
|
const txByDay = useMemo(() => {
|
||||||
const map = new Map<string, InventoryTransaction[]>();
|
const map = new Map<string, InventoryTransaction[]>();
|
||||||
|
const allowedWhIds = new Set(data.warehouses.map((w) => w.id));
|
||||||
const projWhIds = projFilter
|
const projWhIds = projFilter
|
||||||
? new Set(data.warehouses.filter((w) => String(w.project_id) === String(projFilter)).map((w) => w.id))
|
? new Set(data.warehouses.filter((w) => String(w.project_id) === String(projFilter)).map((w) => w.id))
|
||||||
: null;
|
: null;
|
||||||
data.transactions.forEach((t) => {
|
data.transactions.forEach((t) => {
|
||||||
|
if (!isAdmin && !allowedWhIds.has(t.warehouse_id)) return;
|
||||||
if (projWhIds && !projWhIds.has(t.warehouse_id)) return;
|
if (projWhIds && !projWhIds.has(t.warehouse_id)) return;
|
||||||
const k = gregKey(new Date(t.transaction_date));
|
const k = gregKey(new Date(t.transaction_date));
|
||||||
const arr = map.get(k) || [];
|
const arr = map.get(k) || [];
|
||||||
@@ -53,7 +55,7 @@ export function DailyControlPage() {
|
|||||||
});
|
});
|
||||||
map.forEach((arr) => arr.sort((a, b) => new Date(a.transaction_date).getTime() - new Date(b.transaction_date).getTime()));
|
map.forEach((arr) => arr.sort((a, b) => new Date(a.transaction_date).getTime() - new Date(b.transaction_date).getTime()));
|
||||||
return map;
|
return map;
|
||||||
}, [data.transactions, data.warehouses, projFilter]);
|
}, [data.transactions, data.warehouses, projFilter, isAdmin]);
|
||||||
|
|
||||||
const cells = useMemo(() => {
|
const cells = useMemo(() => {
|
||||||
const [ty, tm] = gregorianToJalali(anchor.getFullYear(), anchor.getMonth() + 1, anchor.getDate());
|
const [ty, tm] = gregorianToJalali(anchor.getFullYear(), anchor.getMonth() + 1, anchor.getDate());
|
||||||
@@ -129,15 +131,16 @@ export function DailyControlPage() {
|
|||||||
const wGroups = useMemo(() => {
|
const wGroups = useMemo(() => {
|
||||||
const gmap = new Map<string, { recId: string; q: number; last: string; tx: InventoryTransaction }>();
|
const gmap = new Map<string, { recId: string; q: number; last: string; tx: InventoryTransaction }>();
|
||||||
withdrawals.forEach((t) => {
|
withdrawals.forEach((t) => {
|
||||||
const g = gmap.get(t.inventory_id);
|
const gKey = `${t.inventory_id}__${t.delivered_to || ""}`;
|
||||||
|
const g = gmap.get(gKey);
|
||||||
if (!g) {
|
if (!g) {
|
||||||
gmap.set(t.inventory_id, { recId: t.inventory_id, q: Math.abs(t.quantity_number || 0), last: t.transaction_date, tx: t });
|
gmap.set(gKey, { recId: gKey, q: Math.abs(t.quantity_number || 0), last: t.transaction_date, tx: t });
|
||||||
} else {
|
} else {
|
||||||
g.q += Math.abs(t.quantity_number || 0);
|
g.q += Math.abs(t.quantity_number || 0);
|
||||||
if (t.transaction_date > g.last) g.last = t.transaction_date;
|
if (t.transaction_date > g.last) g.last = t.transaction_date;
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
return [...gmap.values()];
|
return [...gmap.values()].sort((a, b) => new Date(b.last).getTime() - new Date(a.last).getTime());
|
||||||
}, [withdrawals]);
|
}, [withdrawals]);
|
||||||
|
|
||||||
const isToday = sel === todayKey();
|
const isToday = sel === todayKey();
|
||||||
@@ -172,11 +175,15 @@ export function DailyControlPage() {
|
|||||||
))}
|
))}
|
||||||
</select>
|
</select>
|
||||||
) : (
|
) : (
|
||||||
<span className="font-semibold text-slate-800">پروژه فعال</span>
|
<span className="font-semibold text-slate-800">
|
||||||
|
{user?.project_name ? `پروژه: ${user.project_name}` : "پروژه فعال"}
|
||||||
|
</span>
|
||||||
)}
|
)}
|
||||||
|
{isAdmin && (
|
||||||
<span className="text-[11.5px] text-slate-400">
|
<span className="text-[11.5px] text-slate-400">
|
||||||
{projFilter ? "نمایش برای پروژه انتخابی" : "نمایش تمام پروژهها"}
|
{projFilter ? "نمایش برای پروژه انتخابی" : "نمایش تمام پروژهها"}
|
||||||
</span>
|
</span>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<Link
|
<Link
|
||||||
@@ -324,6 +331,12 @@ export function DailyControlPage() {
|
|||||||
whName(data.warehouses, g.tx.warehouse_id)
|
whName(data.warehouses, g.tx.warehouse_id)
|
||||||
].filter(Boolean).join(" · ")}
|
].filter(Boolean).join(" · ")}
|
||||||
</span>
|
</span>
|
||||||
|
{g.tx.delivered_to && (
|
||||||
|
<span className="inline-flex items-center gap-1 mt-1.5 text-[11px] font-semibold text-blue-700 bg-blue-50/80 border border-blue-200/60 rounded px-1.5 py-0.5 w-fit">
|
||||||
|
<span className="text-slate-500 font-normal">تحویل به:</span>
|
||||||
|
<span>{g.tx.delivered_to}</span>
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
</span>
|
</span>
|
||||||
<span className="text-xs font-bold text-rose-600 tabular-nums">
|
<span className="text-xs font-bold text-rose-600 tabular-nums">
|
||||||
{faNum(g.q)} {unitName(data.lookup.units, g.tx.unit?.id)}
|
{faNum(g.q)} {unitName(data.lookup.units, g.tx.unit?.id)}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { useMemo, useState } from "react";
|
import { useMemo, useState } from "react";
|
||||||
import { Link, useLocation, useSearchParams } from "react-router-dom";
|
import { Link, useLocation, useSearchParams } from "react-router-dom";
|
||||||
import { Plus, Warehouse as WarehouseIcon, SlidersHorizontal, ArrowUpDown, X, ChevronDown } from "lucide-react";
|
import { Plus, Warehouse as WarehouseIcon, SlidersHorizontal, ArrowUpDown, X, ChevronDown, ChevronUp, Clock } from "lucide-react";
|
||||||
import { Header, PageLayout } from "../../components/layout/Header";
|
import { Header, PageLayout } from "../../components/layout/Header";
|
||||||
import { EmptyState } from "../../components/EmptyState";
|
import { EmptyState } from "../../components/EmptyState";
|
||||||
import { useAuthStore } from "../../store/auth";
|
import { useAuthStore } from "../../store/auth";
|
||||||
@@ -10,8 +10,24 @@ import { InventoryTopNav } from "./InventoryTopNav";
|
|||||||
import { useInventoryData, brandName, materialName, unitName, whName } from "./useInventoryData";
|
import { useInventoryData, brandName, materialName, unitName, whName } from "./useInventoryData";
|
||||||
import type { InventoryRow, InventoryTransaction, TransactionType } from "../../lib/types";
|
import type { InventoryRow, InventoryTransaction, TransactionType } from "../../lib/types";
|
||||||
import { faNum } from "../../lib/formatters";
|
import { faNum } from "../../lib/formatters";
|
||||||
import { isoToJalaliStr } from "../../lib/jalali";
|
import { isoToJalaliStr, isoToJalaliDateTime, isoToTimeStr } from "../../lib/jalali";
|
||||||
import { cn } from "../../lib/utils";
|
import { cn } from "../../lib/utils";
|
||||||
|
import { JalaliDatePicker } from "../../components/JalaliDatePicker";
|
||||||
|
|
||||||
|
const TX_TYPE_OPTIONS: { type: string; label: string }[] = [
|
||||||
|
{ type: "", label: "همه عملیاتها" },
|
||||||
|
{ type: "PURCHASE", label: "موجودی اولیه / خرید" },
|
||||||
|
{ type: "WITHDRAWAL", label: "خروج / مصرف" },
|
||||||
|
{ type: "PROJECT_TRANSFER", label: "انتقال بین کارگاهی" },
|
||||||
|
{ type: "RETURN", label: "برگشت به انبار" },
|
||||||
|
{ type: "TRANSFER_OUT", label: "انتقال بین انبارها (خروجی)" },
|
||||||
|
{ type: "TRANSFER_IN", label: "انتقال بین انبارها (ورودی)" },
|
||||||
|
{ type: "DAMAGE", label: "خرابی" },
|
||||||
|
{ type: "WASTE", label: "ضایعات" },
|
||||||
|
{ type: "LOSS", label: "مفقودی" },
|
||||||
|
{ type: "FOUND", label: "پیدا شده" },
|
||||||
|
{ type: "STOCK_COUNT", label: "انبارگردانی / شمارش" },
|
||||||
|
];
|
||||||
|
|
||||||
// رنگبندی معنایی تراکنشها
|
// رنگبندی معنایی تراکنشها
|
||||||
const TX_META: Record<TransactionType, { label: string; color: string; icon: string }> = {
|
const TX_META: Record<TransactionType, { label: string; color: string; icon: string }> = {
|
||||||
@@ -51,14 +67,27 @@ export function InventoryPage() {
|
|||||||
const location = useLocation();
|
const location = useLocation();
|
||||||
const user = useAuthStore((s) => s.user);
|
const user = useAuthStore((s) => s.user);
|
||||||
const { warehouses, inventory, transactions, lookup, loading } = useInventoryData();
|
const { warehouses, inventory, transactions, lookup, loading } = useInventoryData();
|
||||||
const isAdmin = user?.role === "admin" || user?.role === "procurement_manager";
|
const isManager = user?.role === "admin" || user?.role === "procurement_manager" || user?.role === "pm";
|
||||||
const isPM = user?.role === "pm";
|
const isSupervisor = user?.role === "supervisor";
|
||||||
|
const isAdmin = user?.role === "admin";
|
||||||
|
// پنل انبار limited: تغییر موجودی مجاز است؛ full: طبق طراحی ممنوع
|
||||||
|
const canModify = isSupervisor || isAdmin || user?.panels?.inventory === "limited";
|
||||||
const [params] = useSearchParams();
|
const [params] = useSearchParams();
|
||||||
|
|
||||||
const [filters, setFilters] = useState<{ warehouse: string; material: string; project: string }>({
|
const [filters, setFilters] = useState<{
|
||||||
|
warehouse: string;
|
||||||
|
material: string;
|
||||||
|
project: string;
|
||||||
|
transactionType: string;
|
||||||
|
dateFrom: string | null;
|
||||||
|
dateTo: string | null;
|
||||||
|
}>({
|
||||||
warehouse: params.get("warehouse") || "",
|
warehouse: params.get("warehouse") || "",
|
||||||
material: "",
|
material: "",
|
||||||
project: "",
|
project: "",
|
||||||
|
transactionType: "",
|
||||||
|
dateFrom: null,
|
||||||
|
dateTo: null,
|
||||||
});
|
});
|
||||||
const [sort, setSort] = useState<"asc" | "desc" | "">("");
|
const [sort, setSort] = useState<"asc" | "desc" | "">("");
|
||||||
const [showMobileFilters, setShowMobileFilters] = useState(false);
|
const [showMobileFilters, setShowMobileFilters] = useState(false);
|
||||||
@@ -67,21 +96,47 @@ export function InventoryPage() {
|
|||||||
const [expBrand, setExpBrand] = useState<string | null>(null);
|
const [expBrand, setExpBrand] = useState<string | null>(null);
|
||||||
|
|
||||||
const visibleWarehouses = useMemo(() => {
|
const visibleWarehouses = useMemo(() => {
|
||||||
if (isAdmin && filters.project) return warehouses.filter((w) => w.project_id === filters.project);
|
if (isManager && filters.project) return warehouses.filter((w) => w.project_id === filters.project);
|
||||||
if (isAdmin) return warehouses;
|
if (isManager) return warehouses;
|
||||||
return warehouses.filter((w) => String(w.project_id) === String(user?.project_id || ""));
|
return warehouses.filter((w) => String(w.project_id) === String(user?.project_id || ""));
|
||||||
}, [warehouses, isAdmin, filters.project, user?.project_id]);
|
}, [warehouses, isManager, filters.project, user?.project_id]);
|
||||||
|
|
||||||
const visibleIds = useMemo(() => new Set(visibleWarehouses.map((w) => w.id)), [visibleWarehouses]);
|
const visibleIds = useMemo(() => new Set(visibleWarehouses.map((w) => w.id)), [visibleWarehouses]);
|
||||||
|
|
||||||
|
// فیلتر تراکنشها بر اساس نوع و بازه زمانی روزانه (۰۰:۰۰:۰۰ تا ۲۳:۵۹:۵۹)
|
||||||
|
const filteredTransactions = useMemo(() => {
|
||||||
|
let list = transactions;
|
||||||
|
if (filters.transactionType) {
|
||||||
|
list = list.filter((t) => t.transaction_type === filters.transactionType);
|
||||||
|
}
|
||||||
|
if (filters.dateFrom) {
|
||||||
|
const dFrom = new Date(filters.dateFrom);
|
||||||
|
const startOfDay = new Date(dFrom.getFullYear(), dFrom.getMonth(), dFrom.getDate(), 0, 0, 0, 0);
|
||||||
|
list = list.filter((t) => new Date(t.transaction_date).getTime() >= startOfDay.getTime());
|
||||||
|
}
|
||||||
|
if (filters.dateTo) {
|
||||||
|
const dTo = new Date(filters.dateTo);
|
||||||
|
const endOfDay = new Date(dTo.getFullYear(), dTo.getMonth(), dTo.getDate(), 23, 59, 59, 999);
|
||||||
|
list = list.filter((t) => new Date(t.transaction_date).getTime() <= endOfDay.getTime());
|
||||||
|
}
|
||||||
|
return list;
|
||||||
|
}, [transactions, filters.transactionType, filters.dateFrom, filters.dateTo]);
|
||||||
|
|
||||||
|
const hasTxFilter = !!(filters.transactionType || filters.dateFrom || filters.dateTo);
|
||||||
|
|
||||||
const groups = useMemo<Group[]>(() => {
|
const groups = useMemo<Group[]>(() => {
|
||||||
const gmap = new Map<string, Group>();
|
const gmap = new Map<string, Group>();
|
||||||
const order: string[] = [];
|
const order: string[] = [];
|
||||||
|
|
||||||
|
// اگر فیلتر تراکنش فعال است، فقط اقلام دارای تراکنش منطبق در خروجی ظاهر میشوند
|
||||||
|
const activeInvIds = hasTxFilter ? new Set(filteredTransactions.map((t) => t.inventory_id)) : null;
|
||||||
|
|
||||||
inventory.forEach((r) => {
|
inventory.forEach((r) => {
|
||||||
const whId = r.warehouse?.id;
|
const whId = r.warehouse?.id;
|
||||||
if (!whId || !visibleIds.has(whId)) return;
|
if (!whId || !visibleIds.has(whId)) return;
|
||||||
if (filters.warehouse && whId !== filters.warehouse) return;
|
if (filters.warehouse && whId !== filters.warehouse) return;
|
||||||
if (filters.material && !r.material.name.includes(filters.material.trim())) return;
|
if (filters.material && !r.material.name.includes(filters.material.trim())) return;
|
||||||
|
if (activeInvIds && !activeInvIds.has(r.id)) return;
|
||||||
const gk = `${whId}|${r.material.id}|${specsHash(r.specs)}`;
|
const gk = `${whId}|${r.material.id}|${specsHash(r.specs)}`;
|
||||||
let g = gmap.get(gk);
|
let g = gmap.get(gk);
|
||||||
if (!g) {
|
if (!g) {
|
||||||
@@ -101,7 +156,6 @@ export function InventoryPage() {
|
|||||||
order.push(gk);
|
order.push(gk);
|
||||||
}
|
}
|
||||||
g.qty += r.quantity_number || 0;
|
g.qty += r.quantity_number || 0;
|
||||||
if (r.updated_at > g.updatedAt) g.updatedAt = r.updated_at;
|
|
||||||
g.recs.push(r);
|
g.recs.push(r);
|
||||||
if (r.brand) {
|
if (r.brand) {
|
||||||
if (!(r.brand.id in g.brands)) {
|
if (!(r.brand.id in g.brands)) {
|
||||||
@@ -111,34 +165,69 @@ export function InventoryPage() {
|
|||||||
g.brands[r.brand.id] += r.quantity_number || 0;
|
g.brands[r.brand.id] += r.quantity_number || 0;
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// استخراج آخرین تاریخ تراکنش واقعی کاربر برای هر گروه و انتساب به updatedAt
|
||||||
|
order.forEach((k) => {
|
||||||
|
const g = gmap.get(k);
|
||||||
|
if (!g) return;
|
||||||
|
const groupAllTxs = transactions.filter((t) => g.recs.some((r) => r.id === t.inventory_id));
|
||||||
|
if (groupAllTxs.length > 0) {
|
||||||
|
const latestTx = groupAllTxs.reduce((latest, t) => {
|
||||||
|
return new Date(t.transaction_date).getTime() > new Date(latest.transaction_date).getTime() ? t : latest;
|
||||||
|
}, groupAllTxs[0]);
|
||||||
|
g.updatedAt = latestTx.transaction_date;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
const out = order.map((k) => gmap.get(k)!);
|
const out = order.map((k) => gmap.get(k)!);
|
||||||
if (sort === "asc") out.sort((a, b) => a.qty - b.qty);
|
if (sort === "asc") out.sort((a, b) => a.qty - b.qty);
|
||||||
else if (sort === "desc") out.sort((a, b) => b.qty - a.qty);
|
else if (sort === "desc") out.sort((a, b) => b.qty - a.qty);
|
||||||
else out.sort((a, b) => new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime());
|
else out.sort((a, b) => new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime());
|
||||||
return out;
|
return out;
|
||||||
}, [inventory, visibleIds, filters, sort]);
|
}, [inventory, visibleIds, filters, sort, hasTxFilter, filteredTransactions, transactions]);
|
||||||
|
|
||||||
const groupTxs = (g: Group) =>
|
const groupTxs = (g: Group) =>
|
||||||
transactions
|
filteredTransactions
|
||||||
.filter((t) => g.recs.some((r) => r.id === t.inventory_id))
|
.filter((t) => g.recs.some((r) => r.id === t.inventory_id))
|
||||||
.slice()
|
.slice()
|
||||||
.sort((a, b) => new Date(a.transaction_date).getTime() - new Date(b.transaction_date).getTime());
|
.sort((a, b) => {
|
||||||
|
const da = new Date(a.transaction_date).getTime();
|
||||||
|
const db = new Date(b.transaction_date).getTime();
|
||||||
|
if (da !== db) return da - db;
|
||||||
|
const ca = a.created_at ? new Date(a.created_at).getTime() : 0;
|
||||||
|
const cb = b.created_at ? new Date(b.created_at).getTime() : 0;
|
||||||
|
return ca - cb;
|
||||||
|
});
|
||||||
|
|
||||||
const brandTxs = (g: Group, bid: string) =>
|
const brandTxs = (g: Group, bid: string) =>
|
||||||
transactions
|
filteredTransactions
|
||||||
.filter((t) => t.brand?.id === bid && g.recs.some((r) => r.id === t.inventory_id))
|
.filter((t) => t.brand?.id === bid && g.recs.some((r) => r.id === t.inventory_id))
|
||||||
.slice()
|
.slice()
|
||||||
.sort((a, b) => new Date(a.transaction_date).getTime() - new Date(b.transaction_date).getTime());
|
.sort((a, b) => {
|
||||||
|
const da = new Date(a.transaction_date).getTime();
|
||||||
|
const db = new Date(b.transaction_date).getTime();
|
||||||
|
if (da !== db) return da - db;
|
||||||
|
const ca = a.created_at ? new Date(a.created_at).getTime() : 0;
|
||||||
|
const cb = b.created_at ? new Date(b.created_at).getTime() : 0;
|
||||||
|
return ca - cb;
|
||||||
|
});
|
||||||
|
|
||||||
const hasFilter = !!(filters.warehouse || (isAdmin && filters.project));
|
const hasFilter = !!(
|
||||||
|
filters.warehouse ||
|
||||||
|
(isAdmin && filters.project) ||
|
||||||
|
filters.material ||
|
||||||
|
filters.transactionType ||
|
||||||
|
filters.dateFrom ||
|
||||||
|
filters.dateTo
|
||||||
|
);
|
||||||
|
|
||||||
if (loading) return <div className="min-h-screen" />;
|
if (loading) return <div className="min-h-screen" />;
|
||||||
if (!user || (!isAdmin && !isPM)) {
|
if (!user) {
|
||||||
return (
|
return (
|
||||||
<div className="min-h-screen">
|
<div className="min-h-screen">
|
||||||
<Header title="داشبورد انبار" backTo="/inventory" backLabel="بازگشت به داشبورد" />
|
<Header title="داشبورد انبار" backTo="/" backLabel="بازگشت" />
|
||||||
<PageLayout>
|
<PageLayout>
|
||||||
<EmptyState emoji="🔒" text="دسترسی به انبار فقط برای مدیر پروژه یا ادمین است." />
|
<EmptyState emoji="🔒" text="لطفاً برای دسترسی به سامانه انبار وارد شوید." />
|
||||||
</PageLayout>
|
</PageLayout>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
@@ -150,10 +239,10 @@ export function InventoryPage() {
|
|||||||
title="سامانه مدیریت انبار"
|
title="سامانه مدیریت انبار"
|
||||||
sub={inventorySubheader(user)}
|
sub={inventorySubheader(user)}
|
||||||
icon={<WarehouseIcon className="h-4.5 w-4.5" strokeWidth={2} />}
|
icon={<WarehouseIcon className="h-4.5 w-4.5" strokeWidth={2} />}
|
||||||
menu={<AppSwitcherMenu activeModule="warehouse" canSwitchToProcurement={isAdmin} />}
|
menu={<AppSwitcherMenu activeModule="warehouse" />}
|
||||||
actions={
|
actions={
|
||||||
<div className="hidden md:flex items-center gap-2">
|
<div className="hidden md:flex items-center gap-2">
|
||||||
<InventoryTopNav pathname={location.pathname} variant={isAdmin ? "admin" : "pm"} />
|
<InventoryTopNav pathname={location.pathname} />
|
||||||
</div>
|
</div>
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
@@ -246,8 +335,8 @@ export function InventoryPage() {
|
|||||||
{/* فیلترهای پیشرفته — برچسبهای لمسی بدون سلکت و بدون بیرونزدگی */}
|
{/* فیلترهای پیشرفته — برچسبهای لمسی بدون سلکت و بدون بیرونزدگی */}
|
||||||
{showMobileFilters && (
|
{showMobileFilters && (
|
||||||
<div className="mt-2.5 border-t border-line/60 pt-2.5 flex flex-col gap-2.5">
|
<div className="mt-2.5 border-t border-line/60 pt-2.5 flex flex-col gap-2.5">
|
||||||
{/* پروژهها (مخصوص ادمین) */}
|
{/* پروژهها (مدیران و ادمین) */}
|
||||||
{isAdmin && lookup.projects.length > 0 && (
|
{isManager && lookup.projects.length > 0 && (
|
||||||
<div>
|
<div>
|
||||||
<div className="mb-1.5 text-[11px] font-bold text-muted">پروژه:</div>
|
<div className="mb-1.5 text-[11px] font-bold text-muted">پروژه:</div>
|
||||||
<div className="flex flex-wrap gap-1.5">
|
<div className="flex flex-wrap gap-1.5">
|
||||||
@@ -282,13 +371,72 @@ export function InventoryPage() {
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{/* نوع عملیات / بخش */}
|
||||||
|
<div>
|
||||||
|
<div className="mb-1.5 text-[11px] font-bold text-muted">نوع عملیات / بخش:</div>
|
||||||
|
<div className="flex flex-wrap gap-1.5">
|
||||||
|
{TX_TYPE_OPTIONS.map((opt) => (
|
||||||
|
<button
|
||||||
|
key={opt.type}
|
||||||
|
type="button"
|
||||||
|
onClick={() => setFilters((f) => ({ ...f, transactionType: f.transactionType === opt.type ? "" : opt.type }))}
|
||||||
|
className={cn(
|
||||||
|
"rounded-lg px-2.5 py-1 text-[11.5px] transition-colors",
|
||||||
|
filters.transactionType === opt.type
|
||||||
|
? "bg-accent text-white font-bold"
|
||||||
|
: "border border-line bg-bg/40 text-ink hover:bg-panel"
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{opt.label}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* فیلتر بازه تاریخ یا روز مشخص */}
|
||||||
|
<div>
|
||||||
|
<div className="mb-1.5 flex items-center justify-between">
|
||||||
|
<span className="text-[11px] font-bold text-muted">فیلتر بازه روزانه (بازه کامل ۰۰:۰۰ تا ۲۳:۵۹):</span>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => {
|
||||||
|
const todayIso = new Date().toISOString().slice(0, 10);
|
||||||
|
setFilters((f) => ({ ...f, dateFrom: todayIso, dateTo: todayIso }));
|
||||||
|
}}
|
||||||
|
className="text-[11px] text-accent font-semibold hover:underline cursor-pointer"
|
||||||
|
>
|
||||||
|
امروز
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<div className="grid gap-2 sm:grid-cols-2 max-w-md">
|
||||||
|
<div>
|
||||||
|
<label className="mb-0.5 block text-[10.5px] text-muted">از تاریخ (یا روز مشخص):</label>
|
||||||
|
<JalaliDatePicker
|
||||||
|
value={filters.dateFrom}
|
||||||
|
onChange={(val) => setFilters((f) => ({ ...f, dateFrom: val, dateTo: f.dateTo || val }))}
|
||||||
|
placeholder="از تاریخ…"
|
||||||
|
maxDate={new Date()}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label className="mb-0.5 block text-[10.5px] text-muted">تا تاریخ:</label>
|
||||||
|
<JalaliDatePicker
|
||||||
|
value={filters.dateTo}
|
||||||
|
onChange={(val) => setFilters((f) => ({ ...f, dateTo: val }))}
|
||||||
|
placeholder="تا تاریخ…"
|
||||||
|
maxDate={new Date()}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
{/* دکمه پاک کردن فیلترها */}
|
{/* دکمه پاک کردن فیلترها */}
|
||||||
{hasFilter && (
|
{hasFilter && (
|
||||||
<div className="pt-1 flex items-center justify-between">
|
<div className="pt-1 flex items-center justify-between">
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
className="text-xs text-red font-medium hover:underline inline-flex items-center gap-1"
|
className="text-xs text-red font-medium hover:underline inline-flex items-center gap-1 cursor-pointer"
|
||||||
onClick={() => setFilters({ warehouse: "", material: "", project: "" })}
|
onClick={() => setFilters({ warehouse: "", material: "", project: "", transactionType: "", dateFrom: null, dateTo: null })}
|
||||||
>
|
>
|
||||||
<X className="h-3 w-3" />
|
<X className="h-3 w-3" />
|
||||||
پاک کردن فیلترها
|
پاک کردن فیلترها
|
||||||
@@ -360,7 +508,6 @@ export function InventoryPage() {
|
|||||||
<tr className="border-b border-line bg-bg/40 text-right text-muted">
|
<tr className="border-b border-line bg-bg/40 text-right text-muted">
|
||||||
<th className="w-8 py-2.5" />
|
<th className="w-8 py-2.5" />
|
||||||
<th className="py-2.5 pe-3 font-semibold">متریال</th>
|
<th className="py-2.5 pe-3 font-semibold">متریال</th>
|
||||||
<th className="py-2.5 pe-3 font-semibold">دستهبندی</th>
|
|
||||||
<th className="py-2.5 pe-3 font-semibold">انبار</th>
|
<th className="py-2.5 pe-3 font-semibold">انبار</th>
|
||||||
<th className="py-2.5 pe-3 font-semibold">مشخصه فنی</th>
|
<th className="py-2.5 pe-3 font-semibold">مشخصه فنی</th>
|
||||||
<th className="py-2.5 pe-3 font-semibold">تعداد</th>
|
<th className="py-2.5 pe-3 font-semibold">تعداد</th>
|
||||||
@@ -415,7 +562,7 @@ export function InventoryPage() {
|
|||||||
</PageLayout>
|
</PageLayout>
|
||||||
|
|
||||||
{/* دکمه شناور تغییر موجودی */}
|
{/* دکمه شناور تغییر موجودی */}
|
||||||
{isPM && (
|
{canModify && (
|
||||||
<Link
|
<Link
|
||||||
to="/inventory/change"
|
to="/inventory/change"
|
||||||
className="fixed bottom-20 left-5 z-40 flex h-14 w-14 items-center justify-center rounded-full bg-blue-600 text-white shadow-xl shadow-blue-600/40 transition-all duration-200 hover:bg-blue-700 hover:scale-105 active:scale-90 md:bottom-8 md:left-8"
|
className="fixed bottom-20 left-5 z-40 flex h-14 w-14 items-center justify-center rounded-full bg-blue-600 text-white shadow-xl shadow-blue-600/40 transition-all duration-200 hover:bg-blue-700 hover:scale-105 active:scale-90 md:bottom-8 md:left-8"
|
||||||
@@ -512,8 +659,9 @@ function InventoryMobileCard({
|
|||||||
<span className="text-muted/60">—</span>
|
<span className="text-muted/60">—</span>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
<span className="shrink-0 tabular-nums">
|
<span className="shrink-0 tabular-nums flex items-center gap-1">
|
||||||
{isoToJalaliStr(g.updatedAt)}
|
<Clock className="w-3 h-3 text-muted/70" />
|
||||||
|
<span>{isoToJalaliDateTime(g.updatedAt)}</span>
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -551,13 +699,23 @@ function GroupRow({ g, isExp, isAdmin, matName, wh, projName, unit, onToggle, ti
|
|||||||
{Object.entries(g.specs || {}).map(([k, v]) => `${k}: ${v}`).join(" · ") || "—"}
|
{Object.entries(g.specs || {}).map(([k, v]) => `${k}: ${v}`).join(" · ") || "—"}
|
||||||
</td>
|
</td>
|
||||||
<td className="py-2.5 pe-3 font-extrabold text-ink tabular-nums">{faNum(g.qty)}</td>
|
<td className="py-2.5 pe-3 font-extrabold text-ink tabular-nums">{faNum(g.qty)}</td>
|
||||||
<td className="py-2.5 pe-3">{unit}</td>
|
<td className="py-2.5 pe-3 font-medium text-ink/80">{unit}</td>
|
||||||
<td className="py-2.5 pe-3 text-muted tabular-nums">{isoToJalaliStr(g.updatedAt)}</td>
|
<td className="py-2.5 pe-3 text-muted tabular-nums">
|
||||||
<td className="py-2.5 text-muted">🕘</td>
|
<div className="font-semibold text-ink">{isoToJalaliStr(g.updatedAt)}</div>
|
||||||
|
<div className="text-[10.5px] text-muted flex items-center gap-1 mt-0.5">
|
||||||
|
<Clock className="w-3 h-3 text-muted/70 shrink-0" />
|
||||||
|
<span>{isoToTimeStr(g.updatedAt)}</span>
|
||||||
|
</div>
|
||||||
|
</td>
|
||||||
|
<td className="py-2.5 text-center text-muted">
|
||||||
|
<span className="p-1 inline-flex items-center justify-center rounded hover:text-accent">
|
||||||
|
{isExp ? <ChevronUp className="w-4 h-4" /> : <ChevronDown className="w-4 h-4" />}
|
||||||
|
</span>
|
||||||
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
{isExp && (
|
{isExp && (
|
||||||
<tr className="border-b border-line/40 bg-accent-bg/10">
|
<tr className="border-b border-line/40 bg-accent-bg/10">
|
||||||
<td colSpan={9} className="p-3.5">{timeline}</td>
|
<td colSpan={8} className="p-3.5">{timeline}</td>
|
||||||
</tr>
|
</tr>
|
||||||
)}
|
)}
|
||||||
</>
|
</>
|
||||||
@@ -589,14 +747,29 @@ function Timeline({ g, txs, allTxs, brandTxs, selTx, setSelTx, expBrand, setExpB
|
|||||||
key={t.id}
|
key={t.id}
|
||||||
type="button"
|
type="button"
|
||||||
onClick={() => setSelTx(sel ? null : t.id)}
|
onClick={() => setSelTx(sel ? null : t.id)}
|
||||||
className={`flex min-w-[120px] flex-col gap-0.5 rounded-lg border p-2 text-start transition-all ${sel ? "border-accent bg-accent/10 shadow-xs" : "border-line bg-panel hover:border-accent/40"}`}
|
className={`flex min-w-[135px] flex-col gap-1 rounded-lg border p-2 text-start transition-all ${sel ? "border-accent bg-accent/10 shadow-xs" : "border-line bg-panel hover:border-accent/40"}`}
|
||||||
style={{ borderTop: `3px solid ${meta.color}` }}
|
style={{ borderTop: `3px solid ${meta.color}` }}
|
||||||
>
|
>
|
||||||
<span className="text-[11px] font-bold" style={{ color: meta.color }}>{meta.icon} {meta.label}</span>
|
<div className="flex items-center justify-between gap-1">
|
||||||
<span className="text-[12px] font-bold tabular-nums" style={{ color: meta.color }}>
|
<span className="text-[11px] font-bold" style={{ color: meta.color }}>
|
||||||
{faNum(Math.abs(t.quantity_number))} {unit}
|
{meta.icon} {meta.label}
|
||||||
</span>
|
</span>
|
||||||
<span className="text-[10.5px] text-muted">مانده: <b className="tabular-nums">{faNum(bal)}</b> {unit}</span>
|
</div>
|
||||||
|
<span className="text-[12.5px] font-extrabold tabular-nums" style={{ color: meta.color }}>
|
||||||
|
{t.quantity_number > 0 ? "+" : ""}{faNum(t.quantity_number)} {unit}
|
||||||
|
</span>
|
||||||
|
<div className="flex items-center justify-between gap-1 text-[10px] text-muted border-t border-line/40 pt-1">
|
||||||
|
<span>مانده: <b className="tabular-nums font-semibold">{faNum(bal)}</b></span>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-1 text-[9.5px] text-muted/90 tabular-nums">
|
||||||
|
<Clock className="w-2.5 h-2.5 text-muted shrink-0" />
|
||||||
|
<span>{isoToJalaliDateTime(t.transaction_date)}</span>
|
||||||
|
</div>
|
||||||
|
{t.delivered_to && (
|
||||||
|
<div className="text-[9.5px] text-ink/80 font-medium truncate max-w-[125px]" title={t.delivered_to}>
|
||||||
|
تحویل: {t.delivered_to}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
</button>
|
</button>
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
@@ -620,7 +793,11 @@ function Timeline({ g, txs, allTxs, brandTxs, selTx, setSelTx, expBrand, setExpB
|
|||||||
<div className="mt-2 rounded-lg border p-2.5 text-[12px] bg-panel shadow-2xs" style={{ borderTop: `3px solid ${meta.color}` }}>
|
<div className="mt-2 rounded-lg border p-2.5 text-[12px] bg-panel shadow-2xs" style={{ borderTop: `3px solid ${meta.color}` }}>
|
||||||
<b style={{ color: meta.color }}>{meta.label}</b>
|
<b style={{ color: meta.color }}>{meta.label}</b>
|
||||||
<div className="mt-1 flex flex-wrap gap-x-4 gap-y-1 text-muted">
|
<div className="mt-1 flex flex-wrap gap-x-4 gap-y-1 text-muted">
|
||||||
<span>تاریخ و ساعت: <b className="text-ink">{isoToJalaliStr(t.transaction_date)}</b></span>
|
<span>زمان وقوع: <b className="text-ink font-bold">{isoToJalaliDateTime(t.transaction_date)}</b></span>
|
||||||
|
{t.delivered_to && <span>تحویل به: <b className="text-ink font-bold">{t.delivered_to}</b></span>}
|
||||||
|
{t.created_at && (
|
||||||
|
<span>زمان ثبت در سیستم: <b className="text-ink/80">{isoToJalaliDateTime(t.created_at)}</b></span>
|
||||||
|
)}
|
||||||
{t.transaction_type === "TRANSFER_OUT" || t.transaction_type === "TRANSFER_IN" ? (
|
{t.transaction_type === "TRANSFER_OUT" || t.transaction_type === "TRANSFER_IN" ? (
|
||||||
<>
|
<>
|
||||||
<span>از انبار: <b className="text-ink">{t.transaction_type === "TRANSFER_OUT" ? whNameFn(t.warehouse_id) : whNameFn(pairTx?.warehouse_id)}</b></span>
|
<span>از انبار: <b className="text-ink">{t.transaction_type === "TRANSFER_OUT" ? whNameFn(t.warehouse_id) : whNameFn(pairTx?.warehouse_id)}</b></span>
|
||||||
|
|||||||
@@ -1,26 +1,27 @@
|
|||||||
import { Link } from "react-router-dom";
|
import { Link } from "react-router-dom";
|
||||||
import { Button } from "../../components/ui/button";
|
import { Button } from "../../components/ui/button";
|
||||||
|
|
||||||
|
import { useAuthStore } from "../../store/auth";
|
||||||
|
|
||||||
// ناوبری بالای صفحه در پنل انبار — هماهنگ با دیزاینسیستم دکمهها
|
// ناوبری بالای صفحه در پنل انبار — هماهنگ با دیزاینسیستم دکمهها
|
||||||
export function InventoryTopNav({
|
export function InventoryTopNav({
|
||||||
pathname,
|
pathname,
|
||||||
variant = "pm",
|
|
||||||
}: {
|
}: {
|
||||||
pathname: string;
|
pathname: string;
|
||||||
variant?: "pm" | "admin";
|
|
||||||
}) {
|
}) {
|
||||||
const items =
|
const user = useAuthStore((s) => s.user);
|
||||||
variant === "admin"
|
const isAdmin = user?.role === "admin";
|
||||||
? [
|
const isManager = user?.role === "procurement_manager" || user?.role === "pm" || isAdmin;
|
||||||
{ label: "کنترل روزانه", to: "/inventory/daily", active: pathname.startsWith("/inventory/daily") },
|
const isSupervisor = user?.role === "supervisor";
|
||||||
{ label: "کالاهای در راه", to: "/inventory/arrivals", active: pathname.startsWith("/inventory/arrivals") },
|
const canViewTabs = isManager || isSupervisor;
|
||||||
{ label: "سازماندهی", to: "/inventory/org", active: pathname.startsWith("/inventory/org") },
|
|
||||||
]
|
const items: { label: string; to: string; active: boolean }[] = [];
|
||||||
: [
|
// برای تغییر موجودی از همان دکمه شناور دایرهای آبی (+) استفاده میشود و دکمه مستطیلی در بالای صفحه حذف شد
|
||||||
{ label: "کنترل روزانه", to: "/inventory/daily", active: pathname.startsWith("/inventory/daily") },
|
if (canViewTabs) {
|
||||||
{ label: "انبارها", to: "/inventory/warehouses", active: pathname.startsWith("/inventory/warehouses") },
|
items.push({ label: "کنترل روزانه", to: "/inventory/daily", active: pathname.startsWith("/inventory/daily") });
|
||||||
{ label: "کالاهای در راه", to: "/inventory/arrivals", active: pathname.startsWith("/inventory/arrivals") },
|
items.push({ label: "انبارها", to: "/inventory/warehouses", active: pathname.startsWith("/inventory/warehouses") });
|
||||||
];
|
items.push({ label: "کالاهای در راه", to: "/inventory/arrivals", active: pathname.startsWith("/inventory/arrivals") });
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
|
|||||||
@@ -1,354 +0,0 @@
|
|||||||
import { useCallback, useEffect, useState } from "react";
|
|
||||||
import { useNavigate } from "react-router-dom";
|
|
||||||
import { toast } from "sonner";
|
|
||||||
import { Header, PageLayout } from "../../components/layout/Header";
|
|
||||||
import { useAuthStore } from "../../store/auth";
|
|
||||||
import { inventorySubheader } from "./panelMenu";
|
|
||||||
import { apiV26, type UserRow } from "../../lib/api";
|
|
||||||
import { refreshProcurementStore } from "../../hooks";
|
|
||||||
import { useInventoryData } from "./useInventoryData";
|
|
||||||
import { faNum } from "../../lib/formatters";
|
|
||||||
import { ProjectMultiSelect } from "../../components/ProjectMultiSelect";
|
|
||||||
|
|
||||||
type Role = "pm" | "procurement_manager" | "admin" | null;
|
|
||||||
|
|
||||||
const ROLE_LABELS: Record<string, string> = {
|
|
||||||
pm: "مدیر پروژه",
|
|
||||||
procurement_manager: "مدیر تدارکات",
|
|
||||||
admin: "ادمین",
|
|
||||||
};
|
|
||||||
|
|
||||||
// سازماندهی (فقط ادمین / مدیر تدارکات) — کاربران، مدیران پروژه و انبارهای هر پروژه
|
|
||||||
export function OrganizationPage() {
|
|
||||||
const navigate = useNavigate();
|
|
||||||
const user = useAuthStore((s) => s.user);
|
|
||||||
const data = useInventoryData();
|
|
||||||
|
|
||||||
const [users, setUsers] = useState<UserRow[]>([]);
|
|
||||||
const [loadingUsers, setLoadingUsers] = useState(true);
|
|
||||||
const [syncing, setSyncing] = useState(false);
|
|
||||||
const [busyId, setBusyId] = useState<string | null>(null);
|
|
||||||
|
|
||||||
const [newWh, setNewWh] = useState<Record<string, string>>({});
|
|
||||||
const [newWhDesc, setNewWhDesc] = useState<Record<string, string>>({});
|
|
||||||
|
|
||||||
const canManage = user?.role === "admin" || user?.role === "procurement_manager";
|
|
||||||
// فقط ادمین میتواند نقشها را تغییر دهد/ارتقا دهد (RBAC) — مدیر تدارکات فقط
|
|
||||||
// پروژهی مدیران پروژه را تعیین/جابهجا میکند.
|
|
||||||
const canChangeRoles = user?.role === "admin";
|
|
||||||
|
|
||||||
const loadUsers = useCallback(async () => {
|
|
||||||
try {
|
|
||||||
const list = await apiV26.users.list();
|
|
||||||
setUsers(list);
|
|
||||||
} catch (err) {
|
|
||||||
toast.error(err instanceof Error ? err.message : "خطا در دریافت کاربران");
|
|
||||||
} finally {
|
|
||||||
setLoadingUsers(false);
|
|
||||||
}
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (canManage) void loadUsers();
|
|
||||||
}, [canManage, loadUsers]);
|
|
||||||
|
|
||||||
const syncUsers = async () => {
|
|
||||||
setSyncing(true);
|
|
||||||
try {
|
|
||||||
const { users: synced, created } = await apiV26.users.sync();
|
|
||||||
setUsers(synced);
|
|
||||||
toast.success(
|
|
||||||
created > 0
|
|
||||||
? `همگامسازی انجام شد — ${faNum(created)} کاربر جدید از Casdoor اضافه شد ✓`
|
|
||||||
: "همگامسازی انجام شد — کاربر جدیدی یافت نشد",
|
|
||||||
);
|
|
||||||
await data.refresh();
|
|
||||||
} catch (err) {
|
|
||||||
toast.error(err instanceof Error ? err.message : "خطا در همگامسازی با Casdoor");
|
|
||||||
} finally {
|
|
||||||
setSyncing(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
if (!canManage) {
|
|
||||||
return (
|
|
||||||
<div className="min-h-screen">
|
|
||||||
<Header title="سازماندهی" backTo="/inventory" backLabel="بازگشت به داشبورد" />
|
|
||||||
<PageLayout>
|
|
||||||
<div className="text-[13px] text-muted">این بخش فقط برای ادمین / مدیر تدارکات است.</div>
|
|
||||||
</PageLayout>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---------- actions: users ----------
|
|
||||||
|
|
||||||
const changeRole = async (u: UserRow, role: Role) => {
|
|
||||||
setBusyId(u.id);
|
|
||||||
try {
|
|
||||||
await apiV26.users.updateRole(u.id, role);
|
|
||||||
toast.success(`نقش «${ROLE_LABELS[role ?? ""] ?? "بدون نقش"}» برای ${u.first_name} ${u.last_name} ثبت شد ✓`);
|
|
||||||
await loadUsers();
|
|
||||||
refreshProcurementStore();
|
|
||||||
} catch (err) {
|
|
||||||
toast.error(err instanceof Error ? err.message : "خطا در تغییر نقش");
|
|
||||||
} finally {
|
|
||||||
setBusyId(null);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
// پروژههای متصل به یک کاربر (1:N) — با پشتیبانی از شکل قدیمیِ تکپروژهای
|
|
||||||
const assignedProjectsOf = (u: UserRow) =>
|
|
||||||
u.projects ?? (u.project_id ? [{ id: u.project_id, name: u.project_name ?? "" }] : []);
|
|
||||||
|
|
||||||
// همگامسازی چند-انتخابیِ پروژهها: افزودن/حذف هر اختلاف با یک PATCH
|
|
||||||
// (pm_user_id = کاربر برای اتصال، null برای جداسازی؛ مدیر قبلی جایگزین میشود)
|
|
||||||
const syncUserProjects = async (u: UserRow, nextIds: string[]) => {
|
|
||||||
const current = assignedProjectsOf(u).map((p) => p.id);
|
|
||||||
const added = nextIds.filter((id) => !current.includes(id));
|
|
||||||
const removed = current.filter((id) => !nextIds.includes(id));
|
|
||||||
if (!added.length && !removed.length) return;
|
|
||||||
setBusyId(u.id);
|
|
||||||
try {
|
|
||||||
for (const pid of added) await apiV26.projects.setPm(pid, u.id);
|
|
||||||
for (const pid of removed) await apiV26.projects.setPm(pid, null);
|
|
||||||
const names = nextIds
|
|
||||||
.map((id) => data.lookup.projects.find((p) => p.id === id)?.name)
|
|
||||||
.filter(Boolean)
|
|
||||||
.join("، ");
|
|
||||||
toast.success(
|
|
||||||
nextIds.length
|
|
||||||
? `پروژههای «${u.first_name} ${u.last_name}» بهروزرسانی شد: ${names} ✓`
|
|
||||||
: `«${u.first_name} ${u.last_name}» از همهی پروژهها جدا شد`,
|
|
||||||
);
|
|
||||||
await loadUsers();
|
|
||||||
await data.refresh();
|
|
||||||
refreshProcurementStore();
|
|
||||||
} catch (err) {
|
|
||||||
toast.error(err instanceof Error ? err.message : "خطا در بهروزرسانی پروژهها");
|
|
||||||
await loadUsers(); // وضعیت واقعی سرور را برگردان
|
|
||||||
} finally {
|
|
||||||
setBusyId(null);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
// ---------- actions: warehouses ----------
|
|
||||||
|
|
||||||
const addWarehouse = async (projectId: string) => {
|
|
||||||
const name = (newWh[projectId] || "").trim();
|
|
||||||
if (!name) return toast.error("نام انبار الزامی است");
|
|
||||||
try {
|
|
||||||
await apiV26.warehouses.create({ project_id: projectId, name, description: (newWhDesc[projectId] || "").trim() || null });
|
|
||||||
setNewWh((s) => ({ ...s, [projectId]: "" }));
|
|
||||||
setNewWhDesc((s) => ({ ...s, [projectId]: "" }));
|
|
||||||
toast.success(`انبار «${name}» اضافه شد ✓`);
|
|
||||||
await data.refresh();
|
|
||||||
} catch (err) {
|
|
||||||
toast.error(err instanceof Error ? err.message : "خطا در افزودن انبار");
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
// انبار برای همیشه به پروژهی والدش تعلق دارد — انتقال به پروژهی دیگر وجود ندارد؛
|
|
||||||
// انبار فقط با حذف و ساخت دوباره زیر پروژهی موردنظر جابهجا میشود.
|
|
||||||
const removeWarehouse = async (id: string) => {
|
|
||||||
if (!confirm("انبار حذف شود؟ (انبارهای دارای سابقه تراکنش قابل حذف نیستند)")) return;
|
|
||||||
try {
|
|
||||||
await apiV26.warehouses.delete(id);
|
|
||||||
toast.success("انبار حذف شد");
|
|
||||||
await data.refresh();
|
|
||||||
} catch (err) {
|
|
||||||
toast.error(err instanceof Error ? err.message : "خطا در حذف انبار");
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
// مدیرِ مسئول یک پروژه (1:N — کاربر ممکن است مدیر چند پروژه باشد)
|
|
||||||
const pmOf = (projectId: string) =>
|
|
||||||
users.find(
|
|
||||||
(u) =>
|
|
||||||
u.role === "pm" &&
|
|
||||||
(u.projects?.some((p) => p.id === projectId) || u.project_id === projectId),
|
|
||||||
) || null;
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="min-h-screen">
|
|
||||||
<Header
|
|
||||||
title="سازماندهی"
|
|
||||||
sub={inventorySubheader(user)}
|
|
||||||
backTo="/inventory"
|
|
||||||
backLabel="بازگشت به داشبورد"
|
|
||||||
/>
|
|
||||||
<PageLayout className="flex flex-col gap-3">
|
|
||||||
<div className="rounded-lg border border-blue/20 bg-blue/5 px-3 py-2 text-[12px] leading-6 text-muted">
|
|
||||||
ℹ️ کاربران از Casdoor همگام میشوند و نقشها اینجا (فقط توسط ادمین) تعیین میشوند؛
|
|
||||||
مدیر تدارکات فقط پروژهی مدیران پروژه را تعیین/جابهجا میکند. پروژهها از سیستم تدارکات میآیند و
|
|
||||||
هر مدیر پروژه به همه انبارهای پروژه خودش دسترسی دارد. همه تغییرات فوراً در داشبورد و فرمها اعمال میشود.
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* ---------- کاربران و مدیران پروژه ---------- */}
|
|
||||||
<div className="rounded-xl border border-line bg-panel p-4">
|
|
||||||
<div className="mb-2 flex flex-wrap items-center justify-between gap-2">
|
|
||||||
<h3 className="text-[14px] font-bold">👥 کاربران و مدیران پروژه</h3>
|
|
||||||
<button
|
|
||||||
onClick={() => void syncUsers()}
|
|
||||||
disabled={syncing}
|
|
||||||
className="rounded-lg border border-accent/40 bg-accent/5 px-3 py-1.5 text-[12px] font-bold text-accent disabled:opacity-50"
|
|
||||||
>
|
|
||||||
{syncing ? "در حال همگامسازی…" : "🔄 همگامسازی از Casdoor"}
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{loadingUsers ? (
|
|
||||||
<div className="py-3 text-[12.5px] text-muted">در حال بارگذاری کاربران…</div>
|
|
||||||
) : !users.length ? (
|
|
||||||
<div className="rounded-lg border border-dashed border-line px-3 py-3 text-[12px] text-muted">
|
|
||||||
کاربری ثبت نشده است — کاربران پس از اولین ورود (Casdoor) بهصورت خودکار ساخته میشوند؛
|
|
||||||
یا دکمهی «همگامسازی از Casdoor» را بزنید.
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<div className="overflow-x-auto">
|
|
||||||
<table className="w-full text-[12.5px]">
|
|
||||||
<thead>
|
|
||||||
<tr className="border-b border-line text-right text-muted">
|
|
||||||
<th className="py-2 pe-3">نام</th>
|
|
||||||
<th className="py-2 pe-3">نقش</th>
|
|
||||||
<th className="py-2 pe-3">پروژه (مدیر پروژه)</th>
|
|
||||||
<th className="py-2">عملیات</th>
|
|
||||||
</tr>
|
|
||||||
</thead>
|
|
||||||
<tbody>
|
|
||||||
{users.map((u) => (
|
|
||||||
<tr key={u.id} className="border-b border-line/50">
|
|
||||||
<td className="py-1.5 pe-3">
|
|
||||||
<b>{u.first_name} {u.last_name}</b>
|
|
||||||
<small className="block text-[10.5px] text-muted ltr">{u.casdoor_id}</small>
|
|
||||||
</td>
|
|
||||||
<td className="py-1.5 pe-3">
|
|
||||||
{canChangeRoles ? (
|
|
||||||
<select
|
|
||||||
className="h-7 rounded-lg border border-line bg-panel px-2 text-[12px]"
|
|
||||||
value={u.role ?? ""}
|
|
||||||
disabled={busyId === u.id}
|
|
||||||
onChange={(e) => void changeRole(u, (e.target.value || null) as Role)}
|
|
||||||
>
|
|
||||||
<option value="">— بدون نقش —</option>
|
|
||||||
<option value="pm">مدیر پروژه</option>
|
|
||||||
<option value="procurement_manager">مدیر تدارکات</option>
|
|
||||||
<option value="admin">ادمین</option>
|
|
||||||
</select>
|
|
||||||
) : (
|
|
||||||
<span className={`rounded-lg px-2 py-1 text-[11px] font-bold ${u.role ? "bg-accent-bg text-accent" : "bg-slate-bg text-muted"}`}>
|
|
||||||
{u.role ? ROLE_LABELS[u.role] : "بدون نقش"}
|
|
||||||
</span>
|
|
||||||
)}
|
|
||||||
{!canChangeRoles && u.role && (
|
|
||||||
<small className="block text-[10px] text-muted">(تغییر نقش فقط توسط ادمین)</small>
|
|
||||||
)}
|
|
||||||
</td>
|
|
||||||
<td className="min-w-[240px] py-1.5 pe-3 align-top">
|
|
||||||
{u.role === "pm" ? (
|
|
||||||
<ProjectMultiSelect
|
|
||||||
options={data.lookup.projects.map((p) => ({ id: p.id, name: p.name }))}
|
|
||||||
values={assignedProjectsOf(u).map((p) => p.id)}
|
|
||||||
onChange={(ids) => void syncUserProjects(u, ids)}
|
|
||||||
disabled={busyId === u.id}
|
|
||||||
/>
|
|
||||||
) : (
|
|
||||||
<span className="text-[11.5px] text-muted">—</span>
|
|
||||||
)}
|
|
||||||
</td>
|
|
||||||
<td className="py-1.5">
|
|
||||||
{u.role === "pm" && u.project_id && (
|
|
||||||
<span className="rounded-lg bg-green/10 px-2 py-1 text-[10.5px] font-bold text-green">فعال</span>
|
|
||||||
)}
|
|
||||||
</td>
|
|
||||||
</tr>
|
|
||||||
))}
|
|
||||||
</tbody>
|
|
||||||
</table>
|
|
||||||
<div className="mt-1 text-[11px] text-muted">
|
|
||||||
«بدون نقش» = حذف مدیر پروژه (از همهی پروژهها هم جدا میشود). هر مدیر پروژه میتواند به
|
|
||||||
چند پروژه متصل باشد؛ حذف هر چیپ (×)، فقط همان پروژه را جدا میکند و اتصال به یک پروژه، مدیرِ
|
|
||||||
قبلیِ آن پروژه را جابهجا میکند.
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* ---------- پروژهها و انبارها ---------- */}
|
|
||||||
<div className="grid grid-cols-1 gap-3 lg:grid-cols-2">
|
|
||||||
{data.lookup.projects.map((p) => {
|
|
||||||
const whs = data.warehouses.filter((w) => w.project_id === p.id);
|
|
||||||
const pm = pmOf(p.id);
|
|
||||||
return (
|
|
||||||
<div key={p.id} className="rounded-xl border border-line bg-panel p-4">
|
|
||||||
<div className="mb-2 flex items-center justify-between">
|
|
||||||
<h3 className="text-[14px] font-bold">🏢 {p.name}</h3>
|
|
||||||
<span className="rounded-lg bg-panel px-2 py-1 text-[11px] text-muted">
|
|
||||||
{faNum(whs.length)} انبار
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="mb-3">
|
|
||||||
<h4 className="mb-1 text-[12px] font-bold text-muted">👤 مدیر پروژه</h4>
|
|
||||||
{pm ? (
|
|
||||||
<div className="flex items-center gap-2 rounded-lg border border-line px-3 py-2 text-[12.5px]">
|
|
||||||
<span className="font-semibold">{pm.first_name} {pm.last_name}</span>
|
|
||||||
<span className="text-[10.5px] text-muted">(مدیر مسئول پروژه)</span>
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<div className="rounded-lg border border-dashed border-line px-3 py-2 text-[11.5px] text-muted">
|
|
||||||
مدیری تعیین نشده است — از جدول «کاربران و مدیران پروژه» بالا، نقش مدیر پروژه را بدهید و به این پروژه متصل کنید.
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<h4 className="mb-1 text-[12px] font-bold text-muted">🏬 انبارهای پروژه</h4>
|
|
||||||
{!whs.length ? (
|
|
||||||
<div className="rounded-lg border border-dashed border-line px-3 py-2 text-[11.5px] text-muted">انباری ندارد — از فرم زیر اضافه کنید.</div>
|
|
||||||
) : (
|
|
||||||
<div className="mb-2 flex flex-col gap-1.5">
|
|
||||||
{whs.map((w) => (
|
|
||||||
<div key={w.id} className="flex items-center justify-between gap-2 rounded-lg border border-line px-3 py-2 text-[12.5px]">
|
|
||||||
<div className="min-w-0 flex-1">
|
|
||||||
<b>{w.name}</b>
|
|
||||||
<small className="block truncate text-muted">{w.description || ""}</small>
|
|
||||||
</div>
|
|
||||||
<div className="flex flex-wrap items-center justify-end gap-1.5">
|
|
||||||
<button
|
|
||||||
className="rounded-lg border border-accent/40 bg-accent/5 px-2 py-1 text-[10.5px] font-bold text-accent"
|
|
||||||
onClick={() => navigate(`/inventory?warehouse=${w.id}`)}
|
|
||||||
title="داشبورد این انبار"
|
|
||||||
>
|
|
||||||
📊 داشبورد
|
|
||||||
</button>
|
|
||||||
<button className="text-muted hover:text-red" onClick={() => void removeWarehouse(w.id)} title="حذف انبار">✕</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
<div className="flex flex-col gap-2 sm:flex-row sm:items-center">
|
|
||||||
<input
|
|
||||||
className="h-8 w-full rounded-lg border border-line bg-panel px-2 text-sm sm:w-44"
|
|
||||||
placeholder="نام انبار جدید"
|
|
||||||
value={newWh[p.id] || ""}
|
|
||||||
onChange={(e) => setNewWh((s) => ({ ...s, [p.id]: e.target.value }))}
|
|
||||||
/>
|
|
||||||
<input
|
|
||||||
className="h-8 w-full rounded-lg border border-line bg-panel px-2 text-sm sm:w-52"
|
|
||||||
placeholder="توضیحات (اختیاری)"
|
|
||||||
value={newWhDesc[p.id] || ""}
|
|
||||||
onChange={(e) => setNewWhDesc((s) => ({ ...s, [p.id]: e.target.value }))}
|
|
||||||
/>
|
|
||||||
<button className="w-full rounded-lg bg-accent px-3 py-2 text-[12px] font-bold text-white sm:w-auto sm:py-1.5" onClick={() => void addWarehouse(p.id)}>
|
|
||||||
+ افزودن انبار
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
})}
|
|
||||||
</div>
|
|
||||||
</PageLayout>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -9,52 +9,42 @@ import { useInventoryData, projName } from "./useInventoryData";
|
|||||||
import { faNum } from "../../lib/formatters";
|
import { faNum } from "../../lib/formatters";
|
||||||
import { isoToJalaliStr } from "../../lib/jalali";
|
import { isoToJalaliStr } from "../../lib/jalali";
|
||||||
|
|
||||||
// انبارها — مدیر پروژه: مشاهده انبارهای پروژه خودش + افزودن/ویرایش/حذف (ادمین دسترسی ندارد)
|
// انبارها — مدیریت انبارها برای مدیران (ادمین، مدیر تدارکات، مدیر پروژه)
|
||||||
export function WarehousesPage() {
|
export function WarehousesPage() {
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
const user = useAuthStore((s) => s.user);
|
const user = useAuthStore((s) => s.user);
|
||||||
const data = useInventoryData();
|
const data = useInventoryData();
|
||||||
const isAdmin = user?.role === "admin" || user?.role === "procurement_manager";
|
const isSupervisor = user?.role === "supervisor";
|
||||||
const isPM = user?.role === "pm";
|
const canManage = user?.role === "admin" || user?.role === "procurement_manager" || user?.role === "pm" || isSupervisor;
|
||||||
|
|
||||||
const [newName, setNewName] = useState("");
|
const [newName, setNewName] = useState("");
|
||||||
const [newDesc, setNewDesc] = useState("");
|
const [newDesc, setNewDesc] = useState("");
|
||||||
|
const [selectedProjectId, setSelectedProjectId] = useState<string>("");
|
||||||
const [editId, setEditId] = useState<string | null>(null);
|
const [editId, setEditId] = useState<string | null>(null);
|
||||||
const [editName, setEditName] = useState("");
|
const [editName, setEditName] = useState("");
|
||||||
const [editDesc, setEditDesc] = useState("");
|
const [editDesc, setEditDesc] = useState("");
|
||||||
|
|
||||||
// ادمین / مدیر تدارکات به بخش «انبارها» دسترسی ندارد — مدیریت انبارها از «سازماندهی»
|
if (!canManage) {
|
||||||
if (isAdmin) {
|
|
||||||
return (
|
return (
|
||||||
<div className="min-h-screen">
|
<div className="min-h-screen">
|
||||||
<Header title="انبارها" backTo="/inventory" backLabel="بازگشت به داشبورد" />
|
<Header title="انبارها" backTo="/inventory" backLabel="بازگشت به داشبورد" />
|
||||||
<PageLayout>
|
<PageLayout>
|
||||||
<div className="rounded-xl border border-line bg-panel p-8 text-center">
|
<div className="rounded-xl border border-line bg-panel p-8 text-center">
|
||||||
<div className="text-3xl">🔒</div>
|
<div className="text-3xl">🔒</div>
|
||||||
<h3 className="mt-2 text-[15px] font-bold">دسترسی ندارد</h3>
|
<h3 className="mt-2 text-[15px] font-bold">دسترسی محدود</h3>
|
||||||
<p className="mt-1 text-[12.5px] text-muted">
|
<p className="mt-1 text-[12.5px] text-muted">
|
||||||
بخش «انبارها» مخصوص مدیران پروژه است. مدیریت انبارها از بخش «سازماندهی» انجام میشود.
|
دسترسی به این بخش برای حساب کاربری شما فعال نیست.
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
</PageLayout>
|
</PageLayout>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
if (!isPM) {
|
|
||||||
return (
|
|
||||||
<div className="min-h-screen">
|
|
||||||
<Header title="انبارها" backTo="/inventory" backLabel="بازگشت به داشبورد" />
|
|
||||||
<PageLayout>
|
|
||||||
<div className="text-[13px] text-muted">این بخش فقط برای مدیر پروژه است.</div>
|
|
||||||
</PageLayout>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
const addWarehouse = async () => {
|
const addWarehouse = async () => {
|
||||||
const name = newName.trim();
|
const name = newName.trim();
|
||||||
if (!name) return toast.error("نام انبار الزامی است");
|
if (!name) return toast.error("نام انبار الزامی است");
|
||||||
const projectId = user?.project_id;
|
const projectId = isSupervisor ? user?.project_id : (selectedProjectId || user?.project_id || data.lookup.projects[0]?.id);
|
||||||
if (!projectId) return toast.error("پروژه انبار را انتخاب کنید");
|
if (!projectId) return toast.error("پروژه انبار را انتخاب کنید");
|
||||||
try {
|
try {
|
||||||
await apiV26.warehouses.create({ project_id: projectId, name, description: newDesc.trim() || null });
|
await apiV26.warehouses.create({ project_id: projectId, name, description: newDesc.trim() || null });
|
||||||
@@ -99,13 +89,26 @@ export function WarehousesPage() {
|
|||||||
backLabel="بازگشت به داشبورد"
|
backLabel="بازگشت به داشبورد"
|
||||||
/>
|
/>
|
||||||
<PageLayout className="flex flex-col gap-3">
|
<PageLayout className="flex flex-col gap-3">
|
||||||
{isPM && (
|
{canManage && (
|
||||||
<div className="rounded-xl border border-line bg-panel p-3">
|
<div className="rounded-xl border border-line bg-panel p-3">
|
||||||
<h3 className="mb-2 text-[13px] font-bold">+ افزودن انبار جدید</h3>
|
<h3 className="mb-2 text-[13px] font-bold">+ افزودن انبار جدید</h3>
|
||||||
<div className="flex flex-wrap gap-2">
|
<div className="flex flex-wrap items-center gap-2">
|
||||||
|
{!isSupervisor && data.lookup.projects.length > 1 && (
|
||||||
|
<select
|
||||||
|
className="h-9 rounded-lg border border-line bg-panel px-3 text-sm"
|
||||||
|
value={selectedProjectId || user?.project_id || data.lookup.projects[0]?.id || ""}
|
||||||
|
onChange={(e) => setSelectedProjectId(e.target.value)}
|
||||||
|
>
|
||||||
|
{data.lookup.projects.map((p) => (
|
||||||
|
<option key={p.id} value={p.id}>
|
||||||
|
پروژه: {p.name}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
)}
|
||||||
<input
|
<input
|
||||||
className="h-9 w-52 rounded-lg border border-line bg-panel px-3 text-sm"
|
className="h-9 w-52 rounded-lg border border-line bg-panel px-3 text-sm"
|
||||||
placeholder="نام انبار (مثلاً انبار موقت)"
|
placeholder="نام انبار (مثلاً انبار مرکزی)"
|
||||||
value={newName}
|
value={newName}
|
||||||
onChange={(e) => setNewName(e.target.value)}
|
onChange={(e) => setNewName(e.target.value)}
|
||||||
/>
|
/>
|
||||||
@@ -148,7 +151,7 @@ export function WarehousesPage() {
|
|||||||
>
|
>
|
||||||
📊 مشاهده داشبورد انبار
|
📊 مشاهده داشبورد انبار
|
||||||
</button>
|
</button>
|
||||||
{isPM && (
|
{canManage && (
|
||||||
<>
|
<>
|
||||||
<button
|
<button
|
||||||
className="rounded-lg border border-line px-3 py-1 text-[11.5px]"
|
className="rounded-lg border border-line px-3 py-1 text-[11.5px]"
|
||||||
@@ -162,7 +165,7 @@ export function WarehousesPage() {
|
|||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
{editId === w.id && isPM && (
|
{editId === w.id && canManage && (
|
||||||
<div className="mt-2 flex flex-col gap-1.5 rounded-lg border border-dashed border-accent/40 p-2" onClick={(e) => e.stopPropagation()}>
|
<div className="mt-2 flex flex-col gap-1.5 rounded-lg border border-dashed border-accent/40 p-2" onClick={(e) => e.stopPropagation()}>
|
||||||
<input
|
<input
|
||||||
className="h-8 rounded-lg border border-line bg-panel px-2 text-sm"
|
className="h-8 rounded-lg border border-line bg-panel px-2 text-sm"
|
||||||
|
|||||||
@@ -0,0 +1,145 @@
|
|||||||
|
// ============================================================
|
||||||
|
// جدول «پیدا شده» — مفقودیهای باقیماندهی انبار (LOSS − FOUND)
|
||||||
|
// با انتخاب انبار همهی مفقودیها میآیند و نام متریال فقط فیلتر است.
|
||||||
|
// ============================================================
|
||||||
|
|
||||||
|
import type { InventoryTransaction } from "../../../lib/types";
|
||||||
|
import { faNum } from "../../../lib/formatters";
|
||||||
|
import { cn } from "../../../lib/utils";
|
||||||
|
import { specsLine, type RowDraft } from "./StockTable";
|
||||||
|
|
||||||
|
export interface LossItem { tx: InventoryTransaction; remaining: number; }
|
||||||
|
|
||||||
|
interface FoundTableProps {
|
||||||
|
items: LossItem[];
|
||||||
|
rows: RowDraft[];
|
||||||
|
setRows: (r: RowDraft[]) => void;
|
||||||
|
unitNameFn: (id: number | null | undefined) => string;
|
||||||
|
emptyMsg: string;
|
||||||
|
loading?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseLocal(s: string): number {
|
||||||
|
const v = parseFloat(String(s).replace(/[۰-۹]/g, (d) => String("۰۱۲۳۴۵۶۷۸۹".indexOf(d))).replace(/[،,]/g, ""));
|
||||||
|
return isFinite(v) ? v : 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function FoundTable({ items, rows, setRows, unitNameFn, emptyMsg, loading }: FoundTableProps) {
|
||||||
|
if (loading) {
|
||||||
|
return <div className="rounded-lg border border-dashed border-line p-4 text-[12.5px] text-muted">در حال بارگذاری مفقودیها…</div>;
|
||||||
|
}
|
||||||
|
if (emptyMsg) {
|
||||||
|
return <div className="rounded-lg border border-dashed border-line p-4 text-[12.5px] text-muted">{emptyMsg}</div>;
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
{/* دسکتاپ */}
|
||||||
|
<div className="hidden sm:block">
|
||||||
|
<div className="max-h-[min(560px,calc(100vh-320px))] overflow-y-auto overflow-x-auto rounded-lg border border-line">
|
||||||
|
<table className="w-full text-[12.5px] min-w-[620px]">
|
||||||
|
<thead className="sticky top-0 z-10 border-b border-line bg-panel text-right text-muted shadow-2xs">
|
||||||
|
<tr>
|
||||||
|
<th className="py-2.5 px-3">متریال</th>
|
||||||
|
<th className="py-2.5 px-3">مشخصهها</th>
|
||||||
|
<th className="py-2.5 px-3">برند</th>
|
||||||
|
<th className="py-2.5 px-3">واحد</th>
|
||||||
|
<th className="py-2.5 px-3">مانده مفقودی</th>
|
||||||
|
<th className="py-2.5 px-3">تعداد پیداشده</th>
|
||||||
|
<th className="py-2.5 px-3">یادداشت</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody className="divide-y divide-line/40">
|
||||||
|
{items.map(({ tx, remaining }, i) => {
|
||||||
|
const over = parseLocal(rows[i]?.qty || "") > remaining;
|
||||||
|
return (
|
||||||
|
<tr key={tx.id + "|" + i} className={cn("hover:bg-bg/40 transition-colors", over && "bg-rose-50/40")}>
|
||||||
|
<td className="py-2 px-3 font-semibold text-ink">{tx.material?.name || "—"}</td>
|
||||||
|
<td className="py-2 px-3 text-muted">{specsLine(tx.specs)}</td>
|
||||||
|
<td className="py-2 px-3">{tx.brand?.name || "—"}</td>
|
||||||
|
<td className="py-2 px-3">{unitNameFn(tx.unit?.id)}</td>
|
||||||
|
<td className="py-2 px-3 font-bold text-rose-600">{faNum(remaining)}</td>
|
||||||
|
<td className="py-2 px-3">
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
inputMode="decimal"
|
||||||
|
pattern="[0-9]*"
|
||||||
|
className={cn(
|
||||||
|
"h-8 w-24 rounded-lg border bg-panel px-2 text-sm ltr focus:border-accent",
|
||||||
|
over ? "border-red-500 bg-rose-50 text-rose-700" : "border-line",
|
||||||
|
)}
|
||||||
|
placeholder="۰"
|
||||||
|
value={rows[i]?.qty || ""}
|
||||||
|
onChange={(e) => setRows(rows.map((x, xi) => (xi === i ? { ...x, qty: e.target.value } : x)))}
|
||||||
|
/>
|
||||||
|
{over && <div className="mt-0.5 text-[10px] font-bold text-rose-700">بیشتر از مفقودی!</div>}
|
||||||
|
</td>
|
||||||
|
<td className="py-2 px-3">
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
className="h-8 w-32 rounded-lg border border-line bg-panel px-2 text-sm focus:border-accent"
|
||||||
|
placeholder="توضیح"
|
||||||
|
value={rows[i]?.note || ""}
|
||||||
|
onChange={(e) => setRows(rows.map((x, xi) => (xi === i ? { ...x, note: e.target.value } : x)))}
|
||||||
|
/>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* موبایل: کارتها */}
|
||||||
|
<div className="sm:hidden">
|
||||||
|
<div className="max-h-[min(560px,calc(100vh-320px))] space-y-2 overflow-y-auto pl-1">
|
||||||
|
{items.map(({ tx, remaining }, i) => {
|
||||||
|
const over = parseLocal(rows[i]?.qty || "") > remaining;
|
||||||
|
return (
|
||||||
|
<div key={tx.id + "|" + i} className={cn("rounded-xl border bg-panel p-3", over ? "border-red-400" : "border-line")}>
|
||||||
|
<div className="flex items-start justify-between gap-2">
|
||||||
|
<div className="min-w-0">
|
||||||
|
<div className="truncate text-[13.5px] font-bold text-ink">{tx.material?.name || "—"}</div>
|
||||||
|
<div className="mt-0.5 text-[11.5px] text-muted">
|
||||||
|
{tx.brand?.name || "بدون برند"} · {unitNameFn(tx.unit?.id)}
|
||||||
|
</div>
|
||||||
|
{tx.specs && Object.keys(tx.specs).length > 0 && (
|
||||||
|
<div className="mt-1 text-[11px] leading-4 text-muted">{specsLine(tx.specs)}</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<div className="shrink-0 rounded-lg bg-bg px-2 py-1 text-center">
|
||||||
|
<div className="text-[10px] text-muted">مانده مفقودی</div>
|
||||||
|
<div className="text-[14px] font-black text-rose-600">{faNum(remaining)}</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="mt-2 grid grid-cols-[1fr_1.2fr] gap-2">
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
inputMode="decimal"
|
||||||
|
pattern="[0-9]*"
|
||||||
|
className={cn(
|
||||||
|
"h-11 w-full rounded-lg border bg-panel px-3 text-[15px] font-bold ltr focus:border-accent",
|
||||||
|
over ? "border-red-500 bg-rose-50 text-rose-700" : "border-line",
|
||||||
|
)}
|
||||||
|
placeholder="تعداد پیداشده"
|
||||||
|
value={rows[i]?.qty || ""}
|
||||||
|
onChange={(e) => setRows(rows.map((x, xi) => (xi === i ? { ...x, qty: e.target.value } : x)))}
|
||||||
|
/>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
className="h-11 w-full rounded-lg border border-line bg-panel px-3 text-[13px] focus:border-accent"
|
||||||
|
placeholder="توضیح"
|
||||||
|
value={rows[i]?.note || ""}
|
||||||
|
onChange={(e) => setRows(rows.map((x, xi) => (xi === i ? { ...x, note: e.target.value } : x)))}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
{over && <div className="mt-1 text-[11px] font-bold text-rose-700">بیشتر از مانده مفقودی!</div>}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,132 @@
|
|||||||
|
// ============================================================
|
||||||
|
// لیست اقلام «انتقال بین کارگاهی» — همان الگوی برداشت:
|
||||||
|
// انتخاب انبار مبدأ → لیست همهی اقلام موجود → ورودی تعداد هر ردیف.
|
||||||
|
// پروژه مقصد و یادداشت بار، بالای لیست برای کل اقلام انتخاب میشوند.
|
||||||
|
// ردیفهای ناموفق هنگام ثبت متوالی، با پیام خطا در لیست میمانند و
|
||||||
|
// ردیفهای موفق حذف میشوند (ورودیها کلید-محورند تا جابهجا نشوند).
|
||||||
|
// ============================================================
|
||||||
|
|
||||||
|
import { faNum } from "../../../lib/formatters";
|
||||||
|
import { cn } from "../../../lib/utils";
|
||||||
|
import { specsLine, type StockRecord } from "./StockTable";
|
||||||
|
|
||||||
|
interface ProjectTransferListProps {
|
||||||
|
records: StockRecord[];
|
||||||
|
qtyOf: (id: string) => string;
|
||||||
|
onQty: (id: string, v: string) => void;
|
||||||
|
unitNameFn: (id: number | null | undefined) => string;
|
||||||
|
/** پیام خطای هر ردیف ناموفق (کلید = id رکورد انبار) */
|
||||||
|
errors: Record<string, string>;
|
||||||
|
emptyMsg: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseNum(s: string): number {
|
||||||
|
const v = parseFloat(String(s).replace(/[۰-۹]/g, (d) => String("۰۱۲۳۴۵۶۷۸۹".indexOf(d))).replace(/[،,]/g, ""));
|
||||||
|
return isFinite(v) ? v : 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ProjectTransferList({ records, qtyOf, onQty, unitNameFn, errors, emptyMsg }: ProjectTransferListProps) {
|
||||||
|
if (emptyMsg) {
|
||||||
|
return <div className="rounded-lg border border-dashed border-line p-4 text-[12.5px] text-muted">{emptyMsg}</div>;
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
{/* دسکتاپ */}
|
||||||
|
<div className="hidden sm:block">
|
||||||
|
<div className="max-h-[min(560px,calc(100vh-320px))] overflow-y-auto overflow-x-auto rounded-lg border border-line">
|
||||||
|
<table className="w-full text-[12.5px] min-w-[600px]">
|
||||||
|
<thead className="sticky top-0 z-10 border-b border-line bg-panel text-right text-muted shadow-2xs">
|
||||||
|
<tr>
|
||||||
|
<th className="py-2.5 px-3">متریال</th>
|
||||||
|
<th className="py-2.5 px-3">مشخصهها</th>
|
||||||
|
<th className="py-2.5 px-3">برند</th>
|
||||||
|
<th className="py-2.5 px-3">واحد</th>
|
||||||
|
<th className="py-2.5 px-3">موجودی فعلی</th>
|
||||||
|
<th className="py-2.5 px-3">تعداد انتقال</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody className="divide-y divide-line/40">
|
||||||
|
{records.map((r) => {
|
||||||
|
const err = errors[r.id];
|
||||||
|
const over = parseNum(qtyOf(r.id)) > r.quantity_number;
|
||||||
|
return (
|
||||||
|
<tr key={r.id} className={cn("hover:bg-bg/40 transition-colors", (over || err) && "bg-rose-50/40")}>
|
||||||
|
<td className="px-3 py-2 font-bold text-ink">{r.material?.name || "—"}</td>
|
||||||
|
<td className="px-3 py-2 text-muted">{specsLine(r.specs)}</td>
|
||||||
|
<td className="px-3 py-2">{r.brand?.name || "—"}</td>
|
||||||
|
<td className="px-3 py-2">{unitNameFn(r.unit?.id)}</td>
|
||||||
|
<td className="px-3 py-2 font-bold text-ink">{faNum(r.quantity_number)}</td>
|
||||||
|
<td className="px-3 py-2">
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
inputMode="decimal"
|
||||||
|
pattern="[0-9]*"
|
||||||
|
className={cn(
|
||||||
|
"h-8 w-24 rounded-lg border bg-panel px-2 text-sm ltr focus:border-accent",
|
||||||
|
over ? "border-red-500 bg-rose-50 text-rose-700" : "border-line",
|
||||||
|
)}
|
||||||
|
placeholder="۰"
|
||||||
|
value={qtyOf(r.id)}
|
||||||
|
onChange={(e) => onQty(r.id, e.target.value)}
|
||||||
|
/>
|
||||||
|
{over && <div className="mt-0.5 text-[10px] font-bold text-rose-700">بیشتر از موجودی!</div>}
|
||||||
|
{err && <div className="mt-0.5 text-[10px] font-bold text-rose-700">{err}</div>}
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
<div className="mt-2 flex items-center justify-between text-[11px] text-muted">
|
||||||
|
<span>پس از ثبت، موجودی همان لحظه از انبار مبدأ کسر و کالا «در راه» پروژه مقصد میشود.</span>
|
||||||
|
<span>{faNum(records.length)} قلم کالا</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* موبایل: کارتها */}
|
||||||
|
<div className="sm:hidden">
|
||||||
|
<div className="max-h-[min(560px,calc(100vh-320px))] space-y-2 overflow-y-auto pl-1">
|
||||||
|
{records.map((r) => {
|
||||||
|
const err = errors[r.id];
|
||||||
|
const over = parseNum(qtyOf(r.id)) > r.quantity_number;
|
||||||
|
return (
|
||||||
|
<div key={r.id} className={cn("rounded-xl border bg-panel p-3", (over || err) ? "border-red-400" : "border-line")}>
|
||||||
|
<div className="flex items-start justify-between gap-2">
|
||||||
|
<div className="min-w-0">
|
||||||
|
<div className="truncate text-[13.5px] font-bold text-ink">{r.material?.name || "—"}</div>
|
||||||
|
<div className="mt-0.5 text-[11.5px] text-muted">
|
||||||
|
{r.brand?.name || "بدون برند"} · {unitNameFn(r.unit?.id)}
|
||||||
|
</div>
|
||||||
|
{r.specs && Object.keys(r.specs).length > 0 && (
|
||||||
|
<div className="mt-1 text-[11px] leading-4 text-muted">{specsLine(r.specs)}</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<div className="shrink-0 rounded-lg bg-bg px-2 py-1 text-center">
|
||||||
|
<div className="text-[10px] text-muted">موجودی</div>
|
||||||
|
<div className="text-[14px] font-black text-ink">{faNum(r.quantity_number)}</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
inputMode="decimal"
|
||||||
|
pattern="[0-9]*"
|
||||||
|
className={cn(
|
||||||
|
"mt-2 h-11 w-full rounded-lg border bg-panel px-3 text-[15px] font-bold ltr focus:border-accent",
|
||||||
|
over ? "border-red-500 bg-rose-50 text-rose-700" : "border-line",
|
||||||
|
)}
|
||||||
|
placeholder="تعداد انتقال"
|
||||||
|
value={qtyOf(r.id)}
|
||||||
|
onChange={(e) => onQty(r.id, e.target.value)}
|
||||||
|
/>
|
||||||
|
{over && <div className="mt-1 text-[11px] font-bold text-rose-700">بیشتر از موجودی!</div>}
|
||||||
|
{err && <div className="mt-1 text-[11px] font-bold text-rose-700">{err}</div>}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,88 @@
|
|||||||
|
// ============================================================
|
||||||
|
// جدول «اقلام ثبتشده در این نشست» برای موجودی اولیه
|
||||||
|
// بازخورد دیداری برای جلوگیری از ثبت تکراری — فقط حافظهی همان صفحه.
|
||||||
|
// ============================================================
|
||||||
|
|
||||||
|
import { faNum } from "../../../lib/formatters";
|
||||||
|
import { specsLine } from "./StockTable";
|
||||||
|
|
||||||
|
export interface PurchaseSessionEntry {
|
||||||
|
material: string;
|
||||||
|
brand: string;
|
||||||
|
specs: Record<string, string>;
|
||||||
|
qty: number;
|
||||||
|
unitLabel: string;
|
||||||
|
time: string; // HH:MM آمادهی نمایش
|
||||||
|
whName: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface PurchaseSessionLogProps {
|
||||||
|
entries: PurchaseSessionEntry[];
|
||||||
|
onClear: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function PurchaseSessionLog({ entries, onClear }: PurchaseSessionLogProps) {
|
||||||
|
if (!entries.length) return null;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="rounded-xl border border-line bg-panel p-3 sm:p-4">
|
||||||
|
<div className="mb-2 flex items-center justify-between gap-2 border-b border-line pb-2">
|
||||||
|
<h3 className="text-[13px] font-bold">
|
||||||
|
🧾 اقلام ثبتشده در این نشست <span className="text-muted font-normal">({faNum(entries.length)} قلم)</span>
|
||||||
|
</h3>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={onClear}
|
||||||
|
className="rounded-lg border border-line px-2.5 py-1.5 text-[11.5px] text-muted hover:bg-bg"
|
||||||
|
>
|
||||||
|
پاک کردن لیست
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* دسکتاپ: جدول فشرده */}
|
||||||
|
<div className="hidden sm:block">
|
||||||
|
<div className="max-h-56 overflow-y-auto rounded-lg border border-line">
|
||||||
|
<table className="w-full text-[12px]">
|
||||||
|
<thead className="sticky top-0 bg-panel text-right text-muted shadow-2xs">
|
||||||
|
<tr>
|
||||||
|
<th className="py-2 px-3">متریال</th>
|
||||||
|
<th className="py-2 px-3">برند</th>
|
||||||
|
<th className="py-2 px-3">مشخصهها</th>
|
||||||
|
<th className="py-2 px-3">تعداد</th>
|
||||||
|
<th className="py-2 px-3">ساعت</th>
|
||||||
|
<th className="py-2 px-3">انبار</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody className="divide-y divide-line/40">
|
||||||
|
{[...entries].reverse().map((e, i) => (
|
||||||
|
<tr key={i}>
|
||||||
|
<td className="py-1.5 px-3 font-semibold text-ink">{e.material}</td>
|
||||||
|
<td className="py-1.5 px-3 text-muted">{e.brand || "—"}</td>
|
||||||
|
<td className="py-1.5 px-3 text-muted">{specsLine(e.specs)}</td>
|
||||||
|
<td className="py-1.5 px-3 font-bold">{faNum(e.qty)} <span className="font-normal text-muted">{e.unitLabel}</span></td>
|
||||||
|
<td className="py-1.5 px-3 text-muted">{e.time}</td>
|
||||||
|
<td className="py-1.5 px-3 text-muted">{e.whName}</td>
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* موبایل: ردیفهای فشرده */}
|
||||||
|
<div className="sm:hidden max-h-64 space-y-1.5 overflow-y-auto">
|
||||||
|
{[...entries].reverse().map((e, i) => (
|
||||||
|
<div key={i} className="rounded-lg border border-line/70 bg-bg/40 px-3 py-2 text-[12px]">
|
||||||
|
<div className="flex items-center justify-between gap-2">
|
||||||
|
<span className="min-w-0 truncate font-bold text-ink">{e.material}</span>
|
||||||
|
<span className="shrink-0 font-bold">{faNum(e.qty)} <span className="font-normal text-muted">{e.unitLabel}</span></span>
|
||||||
|
</div>
|
||||||
|
<div className="mt-0.5 text-[11px] text-muted">
|
||||||
|
{e.brand || "بدون برند"} · {specsLine(e.specs)} · {e.time} · {e.whName}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
// ============================================================
|
||||||
|
// نوار فیلتر بازهی روز بخش «برگشت»
|
||||||
|
// پیشفرضهای لمسی (امروز/دیروز/۷ روز/۳۰ روز) + بازهی دلخواه با تقویم جلالی.
|
||||||
|
// چیپها در موبایل افقی اسکرولپذیرند (no-scrollbar) با ارتفاع تاچ.
|
||||||
|
// ============================================================
|
||||||
|
|
||||||
|
import { JalaliDatePicker } from "../../../components/JalaliDatePicker";
|
||||||
|
import { cn } from "../../../lib/utils";
|
||||||
|
import { DATE_PRESETS, type DatePreset } from "./returnLogic";
|
||||||
|
|
||||||
|
interface ReturnFilterBarProps {
|
||||||
|
preset: DatePreset;
|
||||||
|
onPreset: (p: DatePreset) => void;
|
||||||
|
customFrom: string | null;
|
||||||
|
customTo: string | null;
|
||||||
|
onCustomFrom: (iso: string | null) => void;
|
||||||
|
onCustomTo: (iso: string | null) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ReturnFilterBar({ preset, onPreset, customFrom, customTo, onCustomFrom, onCustomTo }: ReturnFilterBarProps) {
|
||||||
|
return (
|
||||||
|
<div className="space-y-2">
|
||||||
|
<div className="no-scrollbar -mx-1 flex gap-1.5 overflow-x-auto px-1 pb-0.5">
|
||||||
|
{DATE_PRESETS.map((p) => (
|
||||||
|
<button
|
||||||
|
key={p.id}
|
||||||
|
type="button"
|
||||||
|
onClick={() => onPreset(p.id)}
|
||||||
|
className={cn(
|
||||||
|
"h-11 shrink-0 whitespace-nowrap rounded-lg px-3.5 text-[12.5px] transition-colors",
|
||||||
|
preset === p.id
|
||||||
|
? "bg-accent font-bold text-white shadow-xs"
|
||||||
|
: "border border-line bg-panel text-ink hover:bg-bg",
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{p.label}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
{preset === "custom" && (
|
||||||
|
<div className="grid grid-cols-2 gap-2">
|
||||||
|
<div>
|
||||||
|
<label className="mb-1 block text-[11px] font-semibold text-muted">از تاریخ</label>
|
||||||
|
<JalaliDatePicker value={customFrom} onChange={onCustomFrom} placeholder="از تاریخ…" />
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label className="mb-1 block text-[11px] font-semibold text-muted">تا تاریخ</label>
|
||||||
|
<JalaliDatePicker value={customTo} onChange={onCustomTo} placeholder="تا تاریخ…" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,164 @@
|
|||||||
|
// ============================================================
|
||||||
|
// جدول برداشتهای بازه برای بخش «برگشت»
|
||||||
|
// هر ردیف = یک تراکنش برداشت واقعی (Immutable Ledger) با مانده قابل
|
||||||
|
// برگشت محاسبهشده؛ ورودی مقدار برگشت به همان مانده سقف دارد.
|
||||||
|
// ورودیها کلید-محورند (کلید = tx-id) تا حذف ردیفهای موفق، بقیه را
|
||||||
|
// بههم نریزد.
|
||||||
|
// ============================================================
|
||||||
|
|
||||||
|
import type { InventoryTransaction } from "../../../lib/types";
|
||||||
|
import { faNum, fmtDateTime } from "../../../lib/formatters";
|
||||||
|
import { cn } from "../../../lib/utils";
|
||||||
|
import { specsLine } from "./StockTable";
|
||||||
|
|
||||||
|
interface ReturnTableProps {
|
||||||
|
withdrawals: InventoryTransaction[];
|
||||||
|
qtyOf: (id: string) => string;
|
||||||
|
noteOf: (id: string) => string;
|
||||||
|
onQty: (id: string, v: string) => void;
|
||||||
|
onNote: (id: string, v: string) => void;
|
||||||
|
remainders: Map<string, number>;
|
||||||
|
unitNameFn: (id: number | null | undefined) => string;
|
||||||
|
emptyMsg: string;
|
||||||
|
loading?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseNum(s: string): number {
|
||||||
|
const v = parseFloat(String(s).replace(/[۰-۹]/g, (d) => String("۰۱۲۳۴۵۶۷۸۹".indexOf(d))).replace(/[،,]/g, ""));
|
||||||
|
return isFinite(v) ? v : 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ReturnTable({ withdrawals, qtyOf, noteOf, onQty, onNote, remainders, unitNameFn, emptyMsg, loading }: ReturnTableProps) {
|
||||||
|
if (loading) {
|
||||||
|
return <div className="rounded-lg border border-dashed border-line p-4 text-[12.5px] text-muted">در حال بارگذاری برداشتها…</div>;
|
||||||
|
}
|
||||||
|
if (emptyMsg) {
|
||||||
|
return <div className="rounded-lg border border-dashed border-line p-4 text-[12.5px] text-muted">{emptyMsg}</div>;
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
{/* دسکتاپ */}
|
||||||
|
<div className="hidden sm:block">
|
||||||
|
<div className="max-h-[min(560px,calc(100vh-320px))] overflow-y-auto overflow-x-auto rounded-lg border border-line">
|
||||||
|
<table className="w-full text-[12.5px] min-w-[760px]">
|
||||||
|
<thead className="sticky top-0 z-10 border-b border-line bg-panel text-right text-muted shadow-2xs">
|
||||||
|
<tr>
|
||||||
|
<th className="py-2.5 px-3">تاریخ</th>
|
||||||
|
<th className="py-2.5 px-3">متریال</th>
|
||||||
|
<th className="py-2.5 px-3">مشخصهها</th>
|
||||||
|
<th className="py-2.5 px-3">برند</th>
|
||||||
|
<th className="py-2.5 px-3">واحد</th>
|
||||||
|
<th className="py-2.5 px-3">برداشت</th>
|
||||||
|
<th className="py-2.5 px-3">مانده قابل برگشت</th>
|
||||||
|
<th className="py-2.5 px-3">مقدار برگشت / توضیح</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody className="divide-y divide-line/40">
|
||||||
|
{withdrawals.map((w) => {
|
||||||
|
const cap = remainders.get(w.id) ?? 0;
|
||||||
|
const q = parseNum(qtyOf(w.id));
|
||||||
|
const over = q > cap + 1e-9;
|
||||||
|
return (
|
||||||
|
<tr key={w.id} className={cn("hover:bg-bg/40 transition-colors", over && "bg-rose-50/40")}>
|
||||||
|
<td className="whitespace-nowrap px-3 py-2 text-muted">{fmtDateTime(w.transaction_date)}</td>
|
||||||
|
<td className="px-3 py-2 font-bold text-ink">{w.material?.name || "—"}</td>
|
||||||
|
<td className="px-3 py-2 text-muted">{specsLine(w.specs)}</td>
|
||||||
|
<td className="px-3 py-2">{w.brand?.name || "—"}</td>
|
||||||
|
<td className="px-3 py-2">{unitNameFn(w.unit?.id)}</td>
|
||||||
|
<td className="px-3 py-2 font-bold">{faNum(Math.abs(w.quantity_number || 0))}</td>
|
||||||
|
<td className={cn("px-3 py-2 font-black", cap <= 0 ? "text-muted" : "text-emerald-700")}>{faNum(cap)}</td>
|
||||||
|
<td className="px-3 py-2">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
inputMode="decimal"
|
||||||
|
pattern="[0-9]*"
|
||||||
|
className={cn(
|
||||||
|
"h-8 w-20 rounded-lg border bg-panel px-2 text-sm ltr focus:border-accent",
|
||||||
|
over ? "border-red-500 bg-rose-50 text-rose-700" : "border-line",
|
||||||
|
)}
|
||||||
|
placeholder="۰"
|
||||||
|
value={qtyOf(w.id)}
|
||||||
|
onChange={(e) => onQty(w.id, e.target.value)}
|
||||||
|
/>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
className="h-8 w-28 rounded-lg border border-line bg-panel px-2 text-sm focus:border-accent"
|
||||||
|
placeholder="توضیح (اختیاری)"
|
||||||
|
value={noteOf(w.id)}
|
||||||
|
onChange={(e) => onNote(w.id, e.target.value)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
{over && <div className="mt-0.5 text-[10px] font-bold text-rose-700">بیشتر از مانده قابل برگشت!</div>}
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
<div className="mt-2 text-[11px] text-muted">
|
||||||
|
«مانده قابل برگشت» = مقدار برداشت − برگشتهای ثبتشده همان ردیف. سقف ورودی همین مانده است.
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* موبایل: کارتها */}
|
||||||
|
<div className="sm:hidden">
|
||||||
|
<div className="max-h-[min(560px,calc(100vh-320px))] space-y-2 overflow-y-auto pl-1">
|
||||||
|
{withdrawals.map((w) => {
|
||||||
|
const cap = remainders.get(w.id) ?? 0;
|
||||||
|
const q = parseNum(qtyOf(w.id));
|
||||||
|
const over = q > cap + 1e-9;
|
||||||
|
return (
|
||||||
|
<div key={w.id} className={cn("rounded-xl border bg-panel p-3", over ? "border-red-400" : "border-line")}>
|
||||||
|
<div className="flex items-start justify-between gap-2">
|
||||||
|
<div className="min-w-0">
|
||||||
|
<div className="truncate text-[13.5px] font-bold text-ink">{w.material?.name || "—"}</div>
|
||||||
|
<div className="mt-0.5 text-[11.5px] text-muted">
|
||||||
|
{w.brand?.name || "بدون برند"} · {unitNameFn(w.unit?.id)}
|
||||||
|
</div>
|
||||||
|
{w.specs && Object.keys(w.specs).length > 0 && (
|
||||||
|
<div className="mt-1 text-[11px] leading-4 text-muted">{specsLine(w.specs)}</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<div className="shrink-0 rounded-lg bg-bg px-2 py-1 text-center">
|
||||||
|
<div className="text-[10px] text-muted">مانده قابل برگشت</div>
|
||||||
|
<div className={cn("text-[14px] font-black", cap <= 0 ? "text-muted" : "text-emerald-700")}>{faNum(cap)}</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="mt-1.5 flex flex-wrap items-center gap-x-2 gap-y-0.5 text-[11px] text-muted">
|
||||||
|
<span>{fmtDateTime(w.transaction_date)}</span>
|
||||||
|
<span>· برداشت: <b className="text-ink">{faNum(Math.abs(w.quantity_number || 0))}</b></span>
|
||||||
|
{w.delivered_to && <span>· تحویل به: <b className="text-ink">{w.delivered_to}</b></span>}
|
||||||
|
</div>
|
||||||
|
<div className="mt-2 grid grid-cols-[1fr_1.2fr] gap-2">
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
inputMode="decimal"
|
||||||
|
pattern="[0-9]*"
|
||||||
|
className={cn(
|
||||||
|
"h-11 w-full rounded-lg border bg-panel px-3 text-[15px] font-bold ltr focus:border-accent",
|
||||||
|
over ? "border-red-500 bg-rose-50 text-rose-700" : "border-line",
|
||||||
|
)}
|
||||||
|
placeholder="مقدار برگشت"
|
||||||
|
value={qtyOf(w.id)}
|
||||||
|
onChange={(e) => onQty(w.id, e.target.value)}
|
||||||
|
/>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
className="h-11 w-full rounded-lg border border-line bg-panel px-3 text-[13px] focus:border-accent"
|
||||||
|
placeholder="توضیح (اختیاری)"
|
||||||
|
value={noteOf(w.id)}
|
||||||
|
onChange={(e) => onNote(w.id, e.target.value)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
{over && <div className="mt-1 text-[11px] font-bold text-rose-700">بیشتر از مانده قابل برگشت!</div>}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,72 @@
|
|||||||
|
// ============================================================
|
||||||
|
// ویرایشگر مشخصههای فنی Key-Value (موجودی اولیه)
|
||||||
|
// خروجی: jsonb استاندارد {عنوان: مقدار} همخوان با specs_hash بکاند.
|
||||||
|
// مشخصات کاملاً اختیاری است؛ ردیف بدون عنوان دور ریخته میشود.
|
||||||
|
// ============================================================
|
||||||
|
|
||||||
|
import { faNum } from "../../../lib/formatters";
|
||||||
|
|
||||||
|
export interface SpecKvRow { key: string; value: string; }
|
||||||
|
|
||||||
|
export function specsKvToObject(rows: SpecKvRow[]): Record<string, string> {
|
||||||
|
const out: Record<string, string> = {};
|
||||||
|
for (const r of rows) {
|
||||||
|
const k = r.key.trim();
|
||||||
|
if (k) out[k] = r.value.trim();
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface SpecsKvEditorProps {
|
||||||
|
rows: SpecKvRow[];
|
||||||
|
onChange: (rows: SpecKvRow[]) => void;
|
||||||
|
disabled?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function SpecsKvEditor({ rows, onChange, disabled }: SpecsKvEditorProps) {
|
||||||
|
const update = (i: number, patch: Partial<SpecKvRow>) =>
|
||||||
|
onChange(rows.map((r, ri) => (ri === i ? { ...r, ...patch } : r)));
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-2">
|
||||||
|
{rows.map((r, i) => (
|
||||||
|
<div key={i} className="flex items-center gap-2">
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
disabled={disabled}
|
||||||
|
className="h-10 w-full rounded-lg border border-line bg-panel px-3 text-[13px] focus:border-accent"
|
||||||
|
placeholder="عنوان مشخصه (مثلاً ضخامت)"
|
||||||
|
value={r.key}
|
||||||
|
onChange={(e) => update(i, { key: e.target.value })}
|
||||||
|
/>
|
||||||
|
<span className="shrink-0 text-[12px] text-muted">:</span>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
disabled={disabled}
|
||||||
|
className="h-10 w-full rounded-lg border border-line bg-panel px-3 text-[13px] focus:border-accent"
|
||||||
|
placeholder="مقدار (مثلاً ۲ میلیمتر)"
|
||||||
|
value={r.value}
|
||||||
|
onChange={(e) => update(i, { value: e.target.value })}
|
||||||
|
/>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
disabled={disabled}
|
||||||
|
onClick={() => onChange(rows.filter((_, ri) => ri !== i))}
|
||||||
|
className="shrink-0 rounded-lg border border-line px-2.5 py-2 text-[13px] text-rose-600 hover:bg-rose-50 disabled:opacity-40"
|
||||||
|
title="حذف این مشخصه"
|
||||||
|
>
|
||||||
|
✕
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
disabled={disabled}
|
||||||
|
onClick={() => onChange([...rows, { key: "", value: "" }])}
|
||||||
|
className="rounded-lg border border-dashed border-line px-3 py-2 text-[12px] font-medium text-muted hover:bg-bg disabled:opacity-40"
|
||||||
|
>
|
||||||
|
+ افزودن مشخصه {rows.length > 0 && `(${faNum(rows.length)})`}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,154 @@
|
|||||||
|
// ============================================================
|
||||||
|
// هستهی نمایش مشترک لیست متریالهای انبار برای بخشهای لیستمحور
|
||||||
|
// (برداشت / ضایعات / اتلاف / مفقودی / انتقال داخلی / شمارش موجودی)
|
||||||
|
//
|
||||||
|
// دسکتاپ (sm+): جدول فشرده با هدر چسبان و ارتفاع بهینه.
|
||||||
|
// موبایل (<640px): کارتهای عمودی لمسی با فیلد بزرگ ورود مقدار.
|
||||||
|
// هر بخش ستونهای نمایش یکسان را از اینجا میگیرد و فقط رفتار ورودی
|
||||||
|
// (تعداد ساده یا شمارششده) را با isCount انتخاب میکند.
|
||||||
|
// ============================================================
|
||||||
|
|
||||||
|
import { faNum } from "../../../lib/formatters";
|
||||||
|
|
||||||
|
export interface StockRecord {
|
||||||
|
id: string;
|
||||||
|
material: { id: string; name: string };
|
||||||
|
brand: { id: string; name: string } | null;
|
||||||
|
unit: { id: number; code: string; name_fa: string | null } | null;
|
||||||
|
quantity_number: number;
|
||||||
|
specs: Record<string, string>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface RowDraft { key: string; qty: string; note: string; }
|
||||||
|
|
||||||
|
export function specsLine(specs: Record<string, string> | undefined): string {
|
||||||
|
return (
|
||||||
|
Object.entries(specs || {})
|
||||||
|
.map(([k, v]) => `${k}: ${v}`)
|
||||||
|
.join(" · ") || "—"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
interface StockTableProps {
|
||||||
|
records: StockRecord[];
|
||||||
|
rows: RowDraft[];
|
||||||
|
setRows: (r: RowDraft[]) => void;
|
||||||
|
/** شمارش موجودی: placeholder «شمارششده» و پیشنمایش مقدار فعلی هنگام خالی بودن */
|
||||||
|
isCount?: boolean;
|
||||||
|
/** نمایش ستون متریال در دسکتاپ — وقتی فیلتر نام فعال است میتوان پنهان کرد */
|
||||||
|
showMaterial?: boolean;
|
||||||
|
emptyMsg: string;
|
||||||
|
unitNameFn: (id: number | null | undefined) => string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function StockTable({ records, rows, setRows, isCount = false, showMaterial = true, emptyMsg, unitNameFn }: StockTableProps) {
|
||||||
|
if (emptyMsg) {
|
||||||
|
return <div className="rounded-lg border border-dashed border-line p-4 text-[12.5px] text-muted">{emptyMsg}</div>;
|
||||||
|
}
|
||||||
|
|
||||||
|
const qtyPlaceholder = isCount ? "شمارششده" : "۰";
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
{/* دسکتاپ: جدول فشرده با هدر چسبان */}
|
||||||
|
<div className="hidden sm:block">
|
||||||
|
<div className="max-h-[min(560px,calc(100vh-320px))] overflow-y-auto overflow-x-auto rounded-lg border border-line">
|
||||||
|
<table className="w-full text-[12.5px] min-w-[560px]">
|
||||||
|
<thead className="sticky top-0 z-10 border-b border-line bg-panel shadow-2xs">
|
||||||
|
<tr className="text-right text-muted">
|
||||||
|
{showMaterial && <th className="py-2.5 px-3">متریال</th>}
|
||||||
|
<th className="py-2.5 px-3">مشخصهها</th>
|
||||||
|
<th className="py-2.5 px-3">برند</th>
|
||||||
|
<th className="py-2.5 px-3">واحد</th>
|
||||||
|
<th className="py-2.5 px-3">موجودی فعلی</th>
|
||||||
|
<th className="py-2.5 px-3">{isCount ? "شمارششده" : "تعداد"}</th>
|
||||||
|
<th className="py-2.5 px-3">یادداشت</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody className="divide-y divide-line/40">
|
||||||
|
{records.map((r, i) => (
|
||||||
|
<tr key={r.id} className="hover:bg-bg/40 transition-colors">
|
||||||
|
{showMaterial && (
|
||||||
|
<td className="py-2 px-3 font-bold text-ink">{r.material?.name || "—"}</td>
|
||||||
|
)}
|
||||||
|
<td className="py-2 px-3 text-muted">{specsLine(r.specs)}</td>
|
||||||
|
<td className="py-2 px-3">{r.brand?.name || "—"}</td>
|
||||||
|
<td className="py-2 px-3">{unitNameFn(r.unit?.id)}</td>
|
||||||
|
<td className="py-2 px-3 font-bold text-ink">{faNum(r.quantity_number)}</td>
|
||||||
|
<td className="py-2 px-3">
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
inputMode="decimal"
|
||||||
|
pattern="[0-9]*"
|
||||||
|
className="h-8 w-24 rounded-lg border border-line bg-panel px-2 text-sm ltr focus:border-accent"
|
||||||
|
placeholder={qtyPlaceholder}
|
||||||
|
value={isCount && rows[i]?.qty === "" ? String(r.quantity_number) : (rows[i]?.qty || "")}
|
||||||
|
onChange={(e) => setRows(rows.map((x, xi) => (xi === i ? { ...x, qty: e.target.value } : x)))}
|
||||||
|
/>
|
||||||
|
</td>
|
||||||
|
<td className="py-2 px-3">
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
className="h-8 w-32 rounded-lg border border-line bg-panel px-2 text-sm focus:border-accent"
|
||||||
|
placeholder="توضیح (اختیاری)"
|
||||||
|
value={rows[i]?.note || ""}
|
||||||
|
onChange={(e) => setRows(rows.map((x, xi) => (xi === i ? { ...x, note: e.target.value } : x)))}
|
||||||
|
/>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
<div className="mt-2 flex items-center justify-between text-[11px] text-muted">
|
||||||
|
<span>ستون «موجودی فعلی» مقدار موجود هر رکورد است. برای هر ردیف تعداد و یادداشت وارد کنید.</span>
|
||||||
|
<span>{faNum(records.length)} قلم کالا</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* موبایل: کارتهای عمودی لمسی */}
|
||||||
|
<div className="sm:hidden">
|
||||||
|
<div className="max-h-[min(560px,calc(100vh-320px))] space-y-2 overflow-y-auto pl-1">
|
||||||
|
{records.map((r, i) => (
|
||||||
|
<div key={r.id} className="rounded-xl border border-line bg-panel p-3">
|
||||||
|
<div className="flex items-start justify-between gap-2">
|
||||||
|
<div className="min-w-0">
|
||||||
|
<div className="truncate text-[13.5px] font-bold text-ink">{r.material?.name || "—"}</div>
|
||||||
|
<div className="mt-0.5 text-[11.5px] text-muted">
|
||||||
|
{r.brand?.name || "بدون برند"} · {unitNameFn(r.unit?.id)}
|
||||||
|
</div>
|
||||||
|
{r.specs && Object.keys(r.specs).length > 0 && (
|
||||||
|
<div className="mt-1 text-[11px] leading-4 text-muted">{specsLine(r.specs)}</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<div className="shrink-0 rounded-lg bg-bg px-2 py-1 text-center">
|
||||||
|
<div className="text-[10px] text-muted">موجودی</div>
|
||||||
|
<div className="text-[14px] font-black text-ink">{faNum(r.quantity_number)}</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="mt-2 grid grid-cols-[1fr_1.2fr] gap-2">
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
inputMode="decimal"
|
||||||
|
pattern="[0-9]*"
|
||||||
|
className="h-11 w-full rounded-lg border border-line bg-panel px-3 text-[15px] font-bold ltr focus:border-accent"
|
||||||
|
placeholder={qtyPlaceholder}
|
||||||
|
value={isCount && rows[i]?.qty === "" ? String(r.quantity_number) : (rows[i]?.qty || "")}
|
||||||
|
onChange={(e) => setRows(rows.map((x, xi) => (xi === i ? { ...x, qty: e.target.value } : x)))}
|
||||||
|
/>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
className="h-11 w-full rounded-lg border border-line bg-panel px-3 text-[13px] focus:border-accent"
|
||||||
|
placeholder="توضیح (اختیاری)"
|
||||||
|
value={rows[i]?.note || ""}
|
||||||
|
onChange={(e) => setRows(rows.map((x, xi) => (xi === i ? { ...x, note: e.target.value } : x)))}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
<div className="mt-2 text-[11px] text-muted">{faNum(records.length)} قلم کالا — برای هر قلم، مقدار را وارد کنید.</div>
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,244 @@
|
|||||||
|
// ============================================================
|
||||||
|
// منطق بخش «برگشت» — واکشی برداشتها/برگشتها و محاسبه مانده قابل برگشت
|
||||||
|
//
|
||||||
|
// اصل تغییرناپذیری دفتر (Immutable Ledger): هیچ تراکنشی ویرایش/حذف نمیشود؛
|
||||||
|
// مانده هر برداشت = مقدار برداشت − مجموع برگشتهای متصل به آن.
|
||||||
|
// اتصال دو راه دارد:
|
||||||
|
// ۱) برگشتهای جدید note شان [REF:<tx-id>] دارد → اتصال دقیق.
|
||||||
|
// ۲) برگشتهای قدیمی بدون REF (ثبتشده در همان انبار مبدأ) → تخصیص FIFO
|
||||||
|
// بین برداشتهای همان ردیف انبار (متریال+برند+مشخصات+واحد).
|
||||||
|
// همهی جمع/تفریقها با round4 گرد میشوند تا خطای اعشار جاوااسکریپت
|
||||||
|
// (مثل 0.30000000000000004) در ماندهها و سقفها نشت نکند.
|
||||||
|
// ============================================================
|
||||||
|
|
||||||
|
import { apiV26 } from "../../../lib/api";
|
||||||
|
import type { InventoryTransaction } from "../../../lib/types";
|
||||||
|
|
||||||
|
/** گرد کردن به ۴ رقم اعشار — مرجع واحد برای همهی محاسبات مانده */
|
||||||
|
export function round4(n: number): number {
|
||||||
|
return Math.round(n * 10000) / 10000;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------
|
||||||
|
// تاریخ — کلید روز میلادی محلی و بازههای پیشفرض
|
||||||
|
// ------------------------------------------------------------
|
||||||
|
|
||||||
|
export function gregKey(d: Date): string {
|
||||||
|
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function addDays(d: Date, n: number): Date {
|
||||||
|
const x = new Date(d);
|
||||||
|
x.setDate(x.getDate() + n);
|
||||||
|
return x;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type DatePreset = "today" | "yesterday" | "7d" | "30d" | "custom";
|
||||||
|
|
||||||
|
export const DATE_PRESETS: { id: DatePreset; label: string }[] = [
|
||||||
|
{ id: "today", label: "امروز" },
|
||||||
|
{ id: "yesterday", label: "دیروز" },
|
||||||
|
{ id: "7d", label: "۷ روز اخیر" },
|
||||||
|
{ id: "30d", label: "۳۰ روز اخیر" },
|
||||||
|
{ id: "custom", label: "بازه دلخواه" },
|
||||||
|
];
|
||||||
|
|
||||||
|
/** بازهی سرور-ساید برای هر پیشفرض؛ date_to روزِ (inclusive بکاند: < date_to + 24h) */
|
||||||
|
export function presetRange(
|
||||||
|
preset: DatePreset,
|
||||||
|
customFrom?: string,
|
||||||
|
customTo?: string,
|
||||||
|
): { date_from: string; date_to: string } {
|
||||||
|
const today = new Date();
|
||||||
|
switch (preset) {
|
||||||
|
case "today":
|
||||||
|
return { date_from: gregKey(today), date_to: gregKey(today) };
|
||||||
|
case "yesterday": {
|
||||||
|
const y = gregKey(addDays(today, -1));
|
||||||
|
return { date_from: y, date_to: y };
|
||||||
|
}
|
||||||
|
case "7d":
|
||||||
|
return { date_from: gregKey(addDays(today, -6)), date_to: gregKey(today) };
|
||||||
|
case "30d":
|
||||||
|
return { date_from: gregKey(addDays(today, -29)), date_to: gregKey(today) };
|
||||||
|
case "custom":
|
||||||
|
return {
|
||||||
|
date_from: customFrom || gregKey(today),
|
||||||
|
date_to: customTo || customFrom || gregKey(today),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------
|
||||||
|
// تگ رفرنس [REF:<uuid>]
|
||||||
|
// ------------------------------------------------------------
|
||||||
|
|
||||||
|
const REF_RE = /\[REF:([0-9a-fA-F-]{36})\]/;
|
||||||
|
|
||||||
|
export function parseRef(note?: string | null): string | null {
|
||||||
|
if (!note) return null;
|
||||||
|
const m = note.match(REF_RE);
|
||||||
|
return m ? m[1] : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** یادداشت نهایی برگشت = یادداشت کاربر + تگ رفرنس برداشت */
|
||||||
|
export function buildReturnNote(userNote: string | undefined, withdrawalTxId: string): string {
|
||||||
|
const tag = `[REF:${withdrawalTxId}]`;
|
||||||
|
const note = (userNote || "").trim();
|
||||||
|
return note ? `${note} ${tag}` : tag;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------
|
||||||
|
// واکشی صفحهبندیشده (هر صفحه ۱۰۰ — سقف بکاند)
|
||||||
|
// ------------------------------------------------------------
|
||||||
|
|
||||||
|
const MAX_PAGES = 10; // سقف محافظهکارانه: ۱۰۰۰ رکورد
|
||||||
|
|
||||||
|
export async function fetchWithdrawalsPage(
|
||||||
|
sourceWhId: string,
|
||||||
|
dateFrom: string,
|
||||||
|
dateTo: string,
|
||||||
|
page: number,
|
||||||
|
): Promise<{ rows: InventoryTransaction[]; total: number }> {
|
||||||
|
return apiV26.inventory.transactionsPaged({
|
||||||
|
warehouse_id: sourceWhId,
|
||||||
|
transaction_type: "WITHDRAWAL",
|
||||||
|
date_from: dateFrom,
|
||||||
|
date_to: dateTo,
|
||||||
|
sort: "transaction_date",
|
||||||
|
page,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** همهی برگشتهای پروژه از ابتدای بازه (برای تطبیق REF) — صفحهبهصفحه تا سقف */
|
||||||
|
export async function fetchProjectReturns(
|
||||||
|
dateFrom: string,
|
||||||
|
): Promise<InventoryTransaction[]> {
|
||||||
|
const out: InventoryTransaction[] = [];
|
||||||
|
for (let page = 1; page <= MAX_PAGES; page++) {
|
||||||
|
const { rows, total } = await apiV26.inventory.transactionsPaged({
|
||||||
|
transaction_type: "RETURN",
|
||||||
|
date_from: dateFrom,
|
||||||
|
sort: "transaction_date",
|
||||||
|
page,
|
||||||
|
});
|
||||||
|
out.push(...rows);
|
||||||
|
if (out.length >= total || rows.length === 0) break;
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** همهی تراکنشهای یک نوع در یک انبار (برای محاسبه مانده مفقودیها) */
|
||||||
|
export async function fetchAllTypeInWarehouse(
|
||||||
|
warehouseId: string,
|
||||||
|
transactionType: string,
|
||||||
|
): Promise<InventoryTransaction[]> {
|
||||||
|
const out: InventoryTransaction[] = [];
|
||||||
|
for (let page = 1; page <= MAX_PAGES; page++) {
|
||||||
|
const { rows, total } = await apiV26.inventory.transactionsPaged({
|
||||||
|
warehouse_id: warehouseId,
|
||||||
|
transaction_type: transactionType,
|
||||||
|
sort: "transaction_date",
|
||||||
|
page,
|
||||||
|
});
|
||||||
|
out.push(...rows);
|
||||||
|
if (out.length >= total || rows.length === 0) break;
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------
|
||||||
|
// مانده قابل برگشت
|
||||||
|
// ------------------------------------------------------------
|
||||||
|
|
||||||
|
/** کلید ردیف انبار: متریال + برند + مشخصات (مرتبشده) + واحد — همارز specs_hash بکاند */
|
||||||
|
function rowKey(t: InventoryTransaction): string {
|
||||||
|
const specs = Object.keys(t.specs || {})
|
||||||
|
.sort()
|
||||||
|
.map((k) => `${k}=${String((t.specs || {})[k])}`)
|
||||||
|
.join("&");
|
||||||
|
return [t.material?.id || "", t.brand?.id || "", specs, t.unit?.id ?? ""].join("|");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* مانده قابل برگشت هر برداشت را حساب میکند.
|
||||||
|
* - برگشتهای REF-دار: مستقیماً از برداشت مقصد کم میشوند (حتی اگر خارج از بازه/انبار ثبت شده باشند).
|
||||||
|
* - برگشتهای REF-دار که برداشت مقصدشان در لیست نیست: نادیده گرفته میشوند (به برداشت خودشان تعلق دارند).
|
||||||
|
* - برگشتهای قدیمی بدون REF (همان انبار مبدأ): FIFO بین برداشتهای همردیف تخصیص مییابند.
|
||||||
|
*/
|
||||||
|
export function computeRemainders(
|
||||||
|
withdrawals: InventoryTransaction[],
|
||||||
|
returns: InventoryTransaction[],
|
||||||
|
sourceWhId: string,
|
||||||
|
): Map<string, number> {
|
||||||
|
const rem = new Map<string, number>();
|
||||||
|
for (const w of withdrawals) rem.set(w.id, round4(Math.abs(w.quantity_number || 0)));
|
||||||
|
|
||||||
|
const inList = new Set(withdrawals.map((w) => w.id));
|
||||||
|
const legacy: InventoryTransaction[] = [];
|
||||||
|
|
||||||
|
for (const r of returns) {
|
||||||
|
const qty = round4(Math.abs(r.quantity_number || 0));
|
||||||
|
if (qty <= 0) continue;
|
||||||
|
const ref = parseRef(r.note);
|
||||||
|
if (ref) {
|
||||||
|
if (inList.has(ref)) {
|
||||||
|
rem.set(ref, round4((rem.get(ref) ?? 0) - qty));
|
||||||
|
}
|
||||||
|
// ref خارج از لیست → به برداشت خودش (خارج از بازه) تعلق دارد؛ نادیده
|
||||||
|
} else {
|
||||||
|
legacy.push(r);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// تخصیص FIFO برگشتهای قدیمیِ همانبار مبدأ بین برداشتهای همردیف (قدیمی→جدید)
|
||||||
|
const buckets = new Map<string, InventoryTransaction[]>();
|
||||||
|
for (const w of withdrawals) {
|
||||||
|
const k = rowKey(w);
|
||||||
|
const list = buckets.get(k);
|
||||||
|
if (list) list.push(w);
|
||||||
|
else buckets.set(k, [w]);
|
||||||
|
}
|
||||||
|
for (const list of buckets.values()) {
|
||||||
|
list.sort(
|
||||||
|
(a, b) => new Date(a.transaction_date).getTime() - new Date(b.transaction_date).getTime(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
for (const r of legacy) {
|
||||||
|
if (r.warehouse_id !== sourceWhId) continue; // برگشت قدیمی به انبار دیگر قابل انتساب نیست
|
||||||
|
const list = buckets.get(rowKey(r));
|
||||||
|
if (!list) continue;
|
||||||
|
let q = round4(Math.abs(r.quantity_number || 0));
|
||||||
|
for (const w of list) {
|
||||||
|
if (q <= 0) break;
|
||||||
|
const cur = rem.get(w.id) ?? 0;
|
||||||
|
if (cur <= 0) continue;
|
||||||
|
const take = Math.min(cur, q);
|
||||||
|
rem.set(w.id, round4(cur - take));
|
||||||
|
q = round4(q - take);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// کف صفر (محافظت در برابر دادههای ناسازگار قدیمی)
|
||||||
|
for (const [k, v] of rem) if (v < 0) rem.set(k, 0);
|
||||||
|
return rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** مانده مفقودیِ باقیمانده هر LOSS = Σ|LOSS| − ΣFOUND روی همان ردیف انبار */
|
||||||
|
export function computeLossRemainders(
|
||||||
|
losses: InventoryTransaction[],
|
||||||
|
founds: InventoryTransaction[],
|
||||||
|
): { tx: InventoryTransaction; remaining: number }[] {
|
||||||
|
const foundByKey = new Map<string, number>();
|
||||||
|
for (const f of founds) {
|
||||||
|
const k = rowKey(f);
|
||||||
|
foundByKey.set(k, round4((foundByKey.get(k) || 0) + Math.abs(f.quantity_number || 0)));
|
||||||
|
}
|
||||||
|
return losses
|
||||||
|
.map((tx) => {
|
||||||
|
const loss = Math.abs(tx.quantity_number || 0);
|
||||||
|
const found = foundByKey.get(rowKey(tx)) || 0;
|
||||||
|
return { tx, remaining: Math.max(0, round4(loss - found)) };
|
||||||
|
})
|
||||||
|
.filter((x) => x.remaining > 0);
|
||||||
|
}
|
||||||
@@ -10,20 +10,22 @@ export function useLogout() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const ROLE_LABELS: Record<string, string> = {
|
const ROLE_LABELS: Record<string, string> = {
|
||||||
pm: "مدیر پروژه",
|
|
||||||
procurement_manager: "مدیر تدارکات",
|
|
||||||
admin: "ادمین",
|
admin: "ادمین",
|
||||||
|
procurement_manager: "مدیر تدارکات",
|
||||||
|
pm: "مدیر پروژه",
|
||||||
|
supervisor: "سرپرست پروژه",
|
||||||
};
|
};
|
||||||
|
|
||||||
// زیرعنوان پویای سربرگ پنل انبار:
|
// زیرعنوان پویای سربرگ پنل انبار:
|
||||||
// [نام کاربر] | [نقش] – [پروژه / همه پروژهها]
|
// [نام کاربر] | [نقش] – [پروژه / همه پروژهها]
|
||||||
// مدیر پروژه → نام پروژهی خودش؛ مدیر تدارکات/ادمین → «همه پروژهها».
|
// سرپرست پروژه → نام پروژهی خودش؛ مدیران/ادمین → «همه پروژهها».
|
||||||
export function inventorySubheader(user: { display_name?: string; first_name: string; last_name: string; role: string | null; role_label: string | null; project_name: string | null } | null | undefined): string {
|
export function inventorySubheader(user: { username?: string; casdoor_id?: string; display_name?: string; first_name: string; last_name: string; role: string | null; role_label: string | null; project_name: string | null } | null | undefined): string {
|
||||||
if (!user) return "در حال بارگذاری…";
|
if (!user) return "در حال بارگذاری…";
|
||||||
const name = user.display_name || `${user.first_name} ${user.last_name}`.trim() || "کاربر";
|
const name = `${user.first_name || ""} ${user.last_name || ""}`.trim() || user.display_name || "کاربر";
|
||||||
|
const uname = user.username || user.casdoor_id || "-";
|
||||||
const role = user.role_label || (user.role ? ROLE_LABELS[user.role] : "بدون نقش");
|
const role = user.role_label || (user.role ? ROLE_LABELS[user.role] : "بدون نقش");
|
||||||
const proj = user.role === "pm" ? user.project_name || "پروژه نامشخص" : "همه پروژهها";
|
const proj = user.role === "supervisor" && user.project_name ? ` – پروژه: ${user.project_name}` : "";
|
||||||
return `${name} | ${role} – ${proj}`;
|
return `${name} | نام کاربری: ${uname} | نقش: ${role}${proj}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
// منوی همبرگریِ مختصر برای مدیر تدارکات/ادمین: بخشها بالای صفحه هستند و
|
// منوی همبرگریِ مختصر برای مدیر تدارکات/ادمین: بخشها بالای صفحه هستند و
|
||||||
@@ -37,8 +39,7 @@ export function accountMenuItems(onLogout?: () => void): MenuItem[] {
|
|||||||
return items;
|
return items;
|
||||||
}
|
}
|
||||||
|
|
||||||
// منوی همبرگری مدیر پروژه در پنل انبار — فقط «خروج از حساب»
|
// منوی همبرگری سرپرست پروژه در پنل انبار
|
||||||
// (مدیر پروژه به دفتر تدارکات دسترسی ندارد و دکمهی خروجِ تکی هم حذف شده).
|
|
||||||
export function pmMenuItems(onLogout?: () => void): MenuItem[] {
|
export function pmMenuItems(onLogout?: () => void): MenuItem[] {
|
||||||
const items: MenuItem[] = [];
|
const items: MenuItem[] = [];
|
||||||
if (onLogout) {
|
if (onLogout) {
|
||||||
@@ -47,33 +48,24 @@ export function pmMenuItems(onLogout?: () => void): MenuItem[] {
|
|||||||
return items;
|
return items;
|
||||||
}
|
}
|
||||||
|
|
||||||
// آیتمهای منوی همبرگری پنل مدیریت انبار — با نشانگر پنل فعلی + «بازگشت به دفتر» + خروج
|
// آیتمهای بخشهای داخلی انبار
|
||||||
//
|
|
||||||
// دسترسیها (v2.6):
|
|
||||||
// - ادمین / مدیر تدارکات (یک نفر): داشبورد، کنترل روزانه، کالاهای در راه، سازماندهی —
|
|
||||||
// بدون «تغییر موجودی» و بدون «انبارها».
|
|
||||||
// - مدیر پروژه: داشبورد، تغییر موجودی، کنترل روزانه، انبارها، کالاهای در راه —
|
|
||||||
// بدون «سازماندهی».
|
|
||||||
export function panelMenuItems(pathname: string, role: string | null | undefined, onLogout?: () => void): MenuItem[] {
|
export function panelMenuItems(pathname: string, role: string | null | undefined, onLogout?: () => void): MenuItem[] {
|
||||||
const isAdmin = role === "admin" || role === "procurement_manager";
|
const isAdmin = role === "admin";
|
||||||
const isPM = role === "pm";
|
const isManager = role === "procurement_manager" || role === "pm" || isAdmin;
|
||||||
|
const isSupervisor = role === "supervisor" || isAdmin;
|
||||||
|
|
||||||
const items: MenuItem[] = [
|
const items: MenuItem[] = [
|
||||||
{ label: "داشبورد انبار", to: "/inventory", active: pathname === "/inventory" },
|
{ label: "داشبورد انبار", to: "/inventory", active: pathname === "/inventory" },
|
||||||
];
|
];
|
||||||
if (isPM) {
|
// فقط سرپرست پروژه و ادمین میتوانند تغییر موجودی بدهند
|
||||||
|
if (isSupervisor) {
|
||||||
items.push({ label: "تغییر موجودی", to: "/inventory/change", active: pathname.startsWith("/inventory/change") });
|
items.push({ label: "تغییر موجودی", to: "/inventory/change", active: pathname.startsWith("/inventory/change") });
|
||||||
}
|
}
|
||||||
|
// کنترل روزانه و انبارها و کالاهای در راه برای مدیران و سرپرست پروژه
|
||||||
|
if (isManager || isSupervisor) {
|
||||||
items.push({ label: "کنترل روزانه", to: "/inventory/daily", active: pathname.startsWith("/inventory/daily") });
|
items.push({ label: "کنترل روزانه", to: "/inventory/daily", active: pathname.startsWith("/inventory/daily") });
|
||||||
if (isPM) {
|
|
||||||
items.push({ label: "انبارها", to: "/inventory/warehouses", active: pathname.startsWith("/inventory/warehouses") });
|
items.push({ label: "انبارها", to: "/inventory/warehouses", active: pathname.startsWith("/inventory/warehouses") });
|
||||||
}
|
|
||||||
items.push({ label: "کالاهای در راه", to: "/inventory/arrivals", active: pathname.startsWith("/inventory/arrivals") });
|
items.push({ label: "کالاهای در راه", to: "/inventory/arrivals", active: pathname.startsWith("/inventory/arrivals") });
|
||||||
if (isAdmin) {
|
|
||||||
items.push({ label: "سازماندهی", to: "/inventory/org", active: pathname.startsWith("/inventory/org") });
|
|
||||||
}
|
|
||||||
if (isAdmin) {
|
|
||||||
items.push({ divider: true });
|
|
||||||
items.push({ label: "بازگشت به دفتر", to: "/" });
|
|
||||||
}
|
}
|
||||||
if (onLogout) {
|
if (onLogout) {
|
||||||
items.push({ divider: true });
|
items.push({ divider: true });
|
||||||
|
|||||||
@@ -26,8 +26,8 @@ export interface InventoryData {
|
|||||||
|
|
||||||
export function useInventoryData(): InventoryData {
|
export function useInventoryData(): InventoryData {
|
||||||
const user = useAuthStore((s) => s.user);
|
const user = useAuthStore((s) => s.user);
|
||||||
const isPM = user?.role === "pm";
|
const isSupervisor = user?.role === "supervisor";
|
||||||
const projectId = isPM ? user.project_id || undefined : undefined;
|
const projectId = isSupervisor || user?.role === "pm" ? user?.project_id || undefined : undefined;
|
||||||
|
|
||||||
const [warehouses, setWarehouses] = useState<Warehouse[]>([]);
|
const [warehouses, setWarehouses] = useState<Warehouse[]>([]);
|
||||||
const [inventory, setInventory] = useState<InventoryRow[]>([]);
|
const [inventory, setInventory] = useState<InventoryRow[]>([]);
|
||||||
|
|||||||
@@ -0,0 +1,599 @@
|
|||||||
|
import { useCallback, useEffect, useState } from "react";
|
||||||
|
import { toast } from "sonner";
|
||||||
|
import { Header, PageLayout } from "../../components/layout/Header";
|
||||||
|
import { useAuthStore } from "../../store/auth";
|
||||||
|
import { api, apiV26, type UserRow } from "../../lib/api";
|
||||||
|
import type { Project } from "../../lib/types";
|
||||||
|
import { refreshProcurementStore, useProjects } from "../../hooks";
|
||||||
|
import { faNum } from "../../lib/formatters";
|
||||||
|
import { ProjectMultiSelect } from "../../components/ProjectMultiSelect";
|
||||||
|
import { AppSwitcherMenu } from "../../components/AppSwitcherMenu";
|
||||||
|
|
||||||
|
type Role = "pm" | "procurement_manager" | "admin" | "supervisor" | null;
|
||||||
|
|
||||||
|
const ROLE_LABELS: Record<string, string> = {
|
||||||
|
admin: "ادمین",
|
||||||
|
procurement_manager: "مدیر تدارکات",
|
||||||
|
pm: "مدیر پروژه",
|
||||||
|
supervisor: "سرپرست پروژه",
|
||||||
|
};
|
||||||
|
|
||||||
|
// پنل مستقل سازماندهی (ادمین، مدیر تدارکات، مدیر پروژه) — مدیریت کاربران، نقشها و تخصیص پروژهها و پنلها
|
||||||
|
export function OrganizationPage() {
|
||||||
|
const user = useAuthStore((s) => s.user);
|
||||||
|
const storeProjects = useProjects();
|
||||||
|
const [directProjects, setDirectProjects] = useState<Project[]>([]);
|
||||||
|
const [loadingProjects, setLoadingProjects] = useState(false);
|
||||||
|
|
||||||
|
const [users, setUsers] = useState<UserRow[]>([]);
|
||||||
|
const [loadingUsers, setLoadingUsers] = useState(true);
|
||||||
|
const [syncing, setSyncing] = useState(false);
|
||||||
|
const [busyId, setBusyId] = useState<string | null>(null);
|
||||||
|
|
||||||
|
const canManage = user?.role === "admin" || user?.role === "procurement_manager" || user?.role === "pm";
|
||||||
|
const canChangeRoles = canManage;
|
||||||
|
|
||||||
|
const fetchProjects = useCallback(async () => {
|
||||||
|
try {
|
||||||
|
setLoadingProjects(true);
|
||||||
|
const list = await api.projects.list();
|
||||||
|
if (list && Array.isArray(list)) {
|
||||||
|
setDirectProjects(list);
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// fallback silently
|
||||||
|
} finally {
|
||||||
|
setLoadingProjects(false);
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const loadUsers = useCallback(async () => {
|
||||||
|
try {
|
||||||
|
setLoadingUsers(true);
|
||||||
|
const list = await apiV26.users.list();
|
||||||
|
setUsers(list);
|
||||||
|
} catch (err) {
|
||||||
|
toast.error(err instanceof Error ? err.message : "خطا در دریافت کاربران");
|
||||||
|
} finally {
|
||||||
|
setLoadingUsers(false);
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (canManage) {
|
||||||
|
void loadUsers();
|
||||||
|
void fetchProjects();
|
||||||
|
}
|
||||||
|
}, [canManage, loadUsers, fetchProjects]);
|
||||||
|
|
||||||
|
const projects = storeProjects.length > 0 ? storeProjects : directProjects;
|
||||||
|
|
||||||
|
const syncUsers = async () => {
|
||||||
|
setSyncing(true);
|
||||||
|
try {
|
||||||
|
const { users: synced, created } = await apiV26.users.sync();
|
||||||
|
setUsers(synced);
|
||||||
|
toast.success(
|
||||||
|
created > 0
|
||||||
|
? `همگامسازی انجام شد — ${faNum(created)} کاربر جدید از Casdoor اضافه شد ✓`
|
||||||
|
: "همگامسازی انجام شد — کاربر جدیدی یافت نشد",
|
||||||
|
);
|
||||||
|
refreshProcurementStore();
|
||||||
|
void fetchProjects();
|
||||||
|
} catch (err) {
|
||||||
|
toast.error(err instanceof Error ? err.message : "خطا در همگامسازی با Casdoor");
|
||||||
|
} finally {
|
||||||
|
setSyncing(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
if (!canManage) {
|
||||||
|
return (
|
||||||
|
<div className="min-h-screen">
|
||||||
|
<Header title="سازماندهی" backTo="/" backLabel="بازگشت به دفتر" />
|
||||||
|
<PageLayout>
|
||||||
|
<div className="text-[13px] text-muted">این بخش فقط برای ادمین، مدیر تدارکات و مدیر پروژه است.</div>
|
||||||
|
</PageLayout>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- actions: users ----------
|
||||||
|
|
||||||
|
const changeRole = async (u: UserRow, role: Role) => {
|
||||||
|
setBusyId(u.id);
|
||||||
|
try {
|
||||||
|
await apiV26.users.updateRole(u.id, role);
|
||||||
|
toast.success(`نقش «${ROLE_LABELS[role ?? ""] ?? "بدون نقش"}» برای ${u.first_name} ${u.last_name} ثبت شد ✓`);
|
||||||
|
await loadUsers();
|
||||||
|
refreshProcurementStore();
|
||||||
|
} catch (err) {
|
||||||
|
toast.error(err instanceof Error ? err.message : "خطا در تغییر نقش");
|
||||||
|
} finally {
|
||||||
|
setBusyId(null);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// ---------- لایه پنلها: تخصیص پنل + سطح دسترسی و عضویت پروژهای ----------
|
||||||
|
const setPanel = async (u: UserRow, panel: "procurement" | "inventory" | "pm", level: "" | "full" | "limited") => {
|
||||||
|
setBusyId(u.id);
|
||||||
|
const next = { ...(u.panels ?? {}) };
|
||||||
|
if (level) next[panel] = level;
|
||||||
|
else delete next[panel];
|
||||||
|
try {
|
||||||
|
await apiV26.users.setPanels(u.id, next);
|
||||||
|
toast.success(`دسترسی «${u.first_name} ${u.last_name}» بهروزرسانی شد ✓`);
|
||||||
|
await loadUsers();
|
||||||
|
refreshProcurementStore();
|
||||||
|
} catch (err) {
|
||||||
|
toast.error(err instanceof Error ? err.message : "خطا در ثبت دسترسی پنل");
|
||||||
|
} finally {
|
||||||
|
setBusyId(null);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const setMemberProjects = async (u: UserRow, nextIds: string[]) => {
|
||||||
|
setBusyId(u.id);
|
||||||
|
try {
|
||||||
|
await apiV26.users.setPanelProjects(u.id, nextIds);
|
||||||
|
toast.success(`عضویت پروژهای «${u.first_name} ${u.last_name}» بهروزرسانی شد ✓`);
|
||||||
|
await loadUsers();
|
||||||
|
refreshProcurementStore();
|
||||||
|
} catch (err) {
|
||||||
|
toast.error(err instanceof Error ? err.message : "خطا در ثبت عضویت پروژهها");
|
||||||
|
} finally {
|
||||||
|
setBusyId(null);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const panelLabel = (level: string | undefined) =>
|
||||||
|
level === "full" ? "کامل" : level === "limited" ? "محدود" : "—";
|
||||||
|
|
||||||
|
// سرپرستان و مسئولان تخصیصیافته به یک پروژه
|
||||||
|
const supervisorsOf = (projectId: string) =>
|
||||||
|
users.filter(
|
||||||
|
(u) =>
|
||||||
|
(u.role === "supervisor" || u.role === "pm" || Boolean(u.panels?.pm)) &&
|
||||||
|
(u.projects?.some((p) => p.id === projectId) ||
|
||||||
|
u.project_id === projectId ||
|
||||||
|
u.member_project_ids?.includes(projectId)),
|
||||||
|
);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="min-h-screen">
|
||||||
|
<Header
|
||||||
|
title="سازماندهی"
|
||||||
|
brand
|
||||||
|
menu={<AppSwitcherMenu activeModule="organization" />}
|
||||||
|
/>
|
||||||
|
<PageLayout className="flex flex-col gap-5">
|
||||||
|
<div className="rounded-lg border border-blue/20 bg-blue/5 px-3.5 py-2.5 text-[12px] leading-6 text-muted">
|
||||||
|
ℹ️ کاربران در سامانه احراز هویت (Casdoor) تعریف شده و با کلیک بر روی دکمه «همگامسازی» اضافه میشوند. نقشهای سازمانی و سطوح دسترسی هر پنل در جدول زیر توسط ادمین تعیین میگردد.
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* ---------- بخش ۱: جدول یکپارچه کاربران، نقشها و سطوح دسترسی پنلها ---------- */}
|
||||||
|
<div className="rounded-xl border border-line bg-panel p-4">
|
||||||
|
<div className="mb-3 flex flex-wrap items-center justify-between gap-2">
|
||||||
|
<div>
|
||||||
|
<h3 className="text-[14px] font-bold">👥 کاربران، نقشها و سطوح دسترسی پنلها</h3>
|
||||||
|
<p className="mt-0.5 text-[11.5px] text-muted">
|
||||||
|
تعیین نقش سازمانی، تخصیص پنلها (تدارکات، انبار، PM) و مشخص نمودن پروژههای عضویت کاربر
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
onClick={() => void syncUsers()}
|
||||||
|
disabled={syncing}
|
||||||
|
className="rounded-lg border border-accent/40 bg-accent/5 px-3 py-1.5 text-[12px] font-bold text-accent hover:bg-accent/10 transition-colors disabled:opacity-50"
|
||||||
|
>
|
||||||
|
{syncing ? "در حال همگامسازی…" : "🔄 همگامسازی از Casdoor"}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{loadingUsers ? (
|
||||||
|
<div className="py-8 text-center text-[12.5px] text-muted">در حال بارگذاری کاربران…</div>
|
||||||
|
) : !users.length ? (
|
||||||
|
<div className="rounded-lg border border-dashed border-line px-3 py-6 text-center text-[12px] text-muted">
|
||||||
|
کاربری ثبت نشده است — دکمهی «همگامسازی از Casdoor» را بزنید.
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div className="overflow-x-auto">
|
||||||
|
<table className="w-full text-[12.5px]">
|
||||||
|
<thead>
|
||||||
|
<tr className="border-b border-line text-right text-muted">
|
||||||
|
<th className="py-2.5 pe-3">نام و مشخصات</th>
|
||||||
|
<th className="py-2.5 pe-3">نقش سازمانی</th>
|
||||||
|
<th className="py-2.5 pe-3">پنل تدارکات</th>
|
||||||
|
<th className="py-2.5 pe-3">پنل انبار</th>
|
||||||
|
<th className="py-2.5 pe-3">پنل مدیریت پروژه (PM)</th>
|
||||||
|
<th className="py-2.5">پروژههای عضویت (محدوده سطح محدود)</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{users.map((u) => {
|
||||||
|
const isAdmin = u.role === "admin";
|
||||||
|
const hasPanel = Boolean(u.panels?.procurement || u.panels?.inventory || u.panels?.pm);
|
||||||
|
// سرپرست/مدیر پروژه بدون پنل هم عضویت پروژهای میخواهد —
|
||||||
|
// ورود سرپرست بدون پروژه مسدود است، پس ویرایشگر باید باز باشد
|
||||||
|
const canAssignProjects = hasPanel || u.role === "supervisor" || u.role === "pm";
|
||||||
|
|
||||||
|
return (
|
||||||
|
<tr key={u.id} className="border-b border-line/50 transition-colors hover:bg-canvas/30">
|
||||||
|
{/* ۱. نام و نام کاربری */}
|
||||||
|
<td className="py-2.5 pe-3">
|
||||||
|
<div className="flex flex-col">
|
||||||
|
<div className="flex items-center gap-1.5">
|
||||||
|
<span className="font-bold text-foreground">
|
||||||
|
{u.first_name} {u.last_name}
|
||||||
|
</span>
|
||||||
|
<span className="font-mono text-[10px] text-muted">
|
||||||
|
({u.username || "—"})
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
{busyId === u.id && (
|
||||||
|
<span className="text-[10px] text-accent animate-pulse font-medium">
|
||||||
|
در حال ذخیره تغییرات…
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</td>
|
||||||
|
|
||||||
|
{/* ۲. نقش سازمانی */}
|
||||||
|
<td className="py-2.5 pe-3">
|
||||||
|
{canChangeRoles ? (
|
||||||
|
<select
|
||||||
|
className="h-7 rounded-lg border border-line bg-panel px-2 text-[12px] focus:outline-none focus:ring-1 focus:ring-accent"
|
||||||
|
value={u.role ?? ""}
|
||||||
|
disabled={busyId === u.id}
|
||||||
|
onChange={(e) => void changeRole(u, (e.target.value || null) as Role)}
|
||||||
|
>
|
||||||
|
<option value="">— بدون نقش —</option>
|
||||||
|
<option value="admin">ادمین</option>
|
||||||
|
<option value="procurement_manager">مدیر تدارکات</option>
|
||||||
|
<option value="pm">مدیر پروژه</option>
|
||||||
|
<option value="supervisor">سرپرست پروژه</option>
|
||||||
|
</select>
|
||||||
|
) : (
|
||||||
|
<span className="rounded bg-panel px-2 py-0.5 text-[11px] font-semibold text-muted">
|
||||||
|
{ROLE_LABELS[u.role ?? ""] ?? "بدون نقش"}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</td>
|
||||||
|
|
||||||
|
{/* ۳. پنل تدارکات */}
|
||||||
|
<td className="py-2.5 pe-3">
|
||||||
|
{isAdmin ? (
|
||||||
|
<span className="text-[11px] text-muted">کامل (ادمین)</span>
|
||||||
|
) : canChangeRoles ? (
|
||||||
|
<select
|
||||||
|
className="h-7 rounded-lg border border-line bg-panel px-2 text-[12px] focus:outline-none focus:ring-1 focus:ring-accent"
|
||||||
|
value={u.panels?.procurement ?? ""}
|
||||||
|
disabled={busyId === u.id}
|
||||||
|
onChange={(e) => void setPanel(u, "procurement", e.target.value as "" | "full" | "limited")}
|
||||||
|
>
|
||||||
|
<option value="">— بدون تخصیص —</option>
|
||||||
|
<option value="full">کامل</option>
|
||||||
|
<option value="limited">محدود (فقط استعلام)</option>
|
||||||
|
</select>
|
||||||
|
) : (
|
||||||
|
<span className="text-[11px]">{panelLabel(u.panels?.procurement)}</span>
|
||||||
|
)}
|
||||||
|
</td>
|
||||||
|
|
||||||
|
{/* ۴. پنل انبار */}
|
||||||
|
<td className="py-2.5 pe-3">
|
||||||
|
{isAdmin ? (
|
||||||
|
<span className="text-[11px] text-muted">کامل (ادمین)</span>
|
||||||
|
) : canChangeRoles ? (
|
||||||
|
<select
|
||||||
|
className="h-7 rounded-lg border border-line bg-panel px-2 text-[12px] focus:outline-none focus:ring-1 focus:ring-accent"
|
||||||
|
value={u.panels?.inventory ?? ""}
|
||||||
|
disabled={busyId === u.id}
|
||||||
|
onChange={(e) => void setPanel(u, "inventory", e.target.value as "" | "full" | "limited")}
|
||||||
|
>
|
||||||
|
<option value="">— بدون تخصیص —</option>
|
||||||
|
<option value="full">کامل (بدون تغییر موجودی)</option>
|
||||||
|
<option value="limited">محدود (با تغییر موجودی)</option>
|
||||||
|
</select>
|
||||||
|
) : (
|
||||||
|
<span className="text-[11px]">{panelLabel(u.panels?.inventory)}</span>
|
||||||
|
)}
|
||||||
|
</td>
|
||||||
|
|
||||||
|
{/* ۵. پنل مدیریت پروژه (PM) */}
|
||||||
|
<td className="py-2.5 pe-3">
|
||||||
|
{isAdmin ? (
|
||||||
|
<span className="text-[11px] text-muted">کامل (ادمین)</span>
|
||||||
|
) : canChangeRoles ? (
|
||||||
|
<select
|
||||||
|
className="h-7 rounded-lg border border-line bg-panel px-2 text-[12px] focus:outline-none focus:ring-1 focus:ring-accent"
|
||||||
|
value={u.panels?.pm ?? ""}
|
||||||
|
disabled={busyId === u.id}
|
||||||
|
onChange={(e) => void setPanel(u, "pm", e.target.value as "" | "full" | "limited")}
|
||||||
|
>
|
||||||
|
<option value="">— بدون تخصیص —</option>
|
||||||
|
<option value="full">کامل</option>
|
||||||
|
<option value="limited">محدود</option>
|
||||||
|
</select>
|
||||||
|
) : (
|
||||||
|
<span className="text-[11px]">{panelLabel(u.panels?.pm)}</span>
|
||||||
|
)}
|
||||||
|
</td>
|
||||||
|
|
||||||
|
{/* ۶. پروژههای عضویت */}
|
||||||
|
<td className="py-2.5">
|
||||||
|
{isAdmin ? (
|
||||||
|
<span className="text-[11px] text-muted">دسترسی خودکار به تمام پروژهها</span>
|
||||||
|
) : canAssignProjects ? (
|
||||||
|
<div className="w-72">
|
||||||
|
<ProjectMultiSelect
|
||||||
|
options={projects.map((p) => ({ id: p.id, name: p.name }))}
|
||||||
|
values={u.member_project_ids ?? []}
|
||||||
|
onChange={(nextIds) => void setMemberProjects(u, nextIds)}
|
||||||
|
disabled={busyId === u.id}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<span className="text-[11px] text-muted">— ابتدا پنل تخصیص دهید —</span>
|
||||||
|
)}
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* ---------- بخش ۲: کارتهای پروژهها و سرپرستان مسئول ---------- */}
|
||||||
|
<div>
|
||||||
|
<div className="mb-2 flex items-center justify-between">
|
||||||
|
<div>
|
||||||
|
<h3 className="text-[14px] font-bold">🏢 پروژهها و سرپرستان مسئول</h3>
|
||||||
|
<p className="text-[11.5px] text-muted">
|
||||||
|
مشاهده وضعیت پروژهها و سرپرستان یا اعضای تخصیصیافته به هر پروژه
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
{loadingProjects && (
|
||||||
|
<span className="text-[11px] text-muted animate-pulse">در حال بهروزرسانی پروژهها…</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{loadingProjects && !projects.length ? (
|
||||||
|
<div className="rounded-xl border border-line bg-panel p-6 text-center text-xs text-muted">
|
||||||
|
در حال دریافت اطلاعات پروژهها…
|
||||||
|
</div>
|
||||||
|
) : !projects.length ? (
|
||||||
|
<div className="rounded-xl border border-dashed border-line bg-panel p-6 text-center text-xs text-muted flex flex-col items-center gap-2">
|
||||||
|
<span>پروژهای برای نمایش یافت نشد یا در دسترس نیست.</span>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => void fetchProjects()}
|
||||||
|
className="rounded-lg bg-accent/10 px-3 py-1 text-xs font-semibold text-accent hover:bg-accent/20 transition-colors"
|
||||||
|
>
|
||||||
|
🔄 تلاش مجدد برای دریافت پروژهها
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div className="grid grid-cols-1 gap-3 md:grid-cols-2 lg:grid-cols-3">
|
||||||
|
{projects.map((p) => {
|
||||||
|
const sups = supervisorsOf(p.id);
|
||||||
|
return (
|
||||||
|
<div key={p.id} className="rounded-xl border border-line bg-panel p-4 flex flex-col justify-between">
|
||||||
|
<div>
|
||||||
|
<div className="mb-2 flex items-center justify-between">
|
||||||
|
<h4 className="text-[14px] font-bold text-foreground">🏢 {p.name}</h4>
|
||||||
|
<span className="rounded-lg bg-canvas px-2 py-0.5 text-[11px] text-muted font-medium border border-line">
|
||||||
|
{p.status || "پروژه فعال"}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
{p.description && (
|
||||||
|
<p className="mb-3 text-[12px] text-muted line-clamp-2">{p.description}</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="pt-2 border-t border-line/50">
|
||||||
|
<h5 className="mb-1.5 text-[11.5px] font-bold text-muted">👤 سرپرست(های) مسئول:</h5>
|
||||||
|
{!sups.length ? (
|
||||||
|
<div className="rounded-lg border border-dashed border-line px-3 py-2 text-[11.5px] text-amber-600 dark:text-amber-400 bg-amber-500/5">
|
||||||
|
⚠️ سرپرستی تعیین نشده است — از جدول بالا، این پروژه را به عنوان عضویت تخصیص دهید.
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div className="flex flex-col gap-1">
|
||||||
|
{sups.map((s) => (
|
||||||
|
<div key={s.id} className="flex items-center justify-between rounded-lg border border-line bg-canvas/40 px-2.5 py-1.5 text-[12px]">
|
||||||
|
<span className="font-semibold text-foreground">{s.first_name} {s.last_name}</span>
|
||||||
|
<span className="text-[10px] text-muted font-mono">({s.username || ROLE_LABELS[s.role ?? ""] || "عضو"})</span>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* ---------- بخش ۴: راهنما و توضیحات سطوح دسترسی پنلها ---------- */}
|
||||||
|
<div className="rounded-xl border border-line bg-panel p-5">
|
||||||
|
<div className="mb-4 flex items-center justify-between border-b border-line pb-3">
|
||||||
|
<div>
|
||||||
|
<h3 className="flex items-center gap-2 text-[15px] font-bold">
|
||||||
|
<span className="flex h-7 w-7 items-center justify-center rounded-lg bg-accent/10 text-accent">
|
||||||
|
📖
|
||||||
|
</span>
|
||||||
|
توضیحات پنلها و راهنمای سطوح دسترسی
|
||||||
|
</h3>
|
||||||
|
<p className="mt-1 text-[12px] text-muted">
|
||||||
|
مفهوم، اختیارات و محدوده کاری هر سطح دسترسی (کامل / محدود) در هر یک از پنلهای سامانه
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<div className="hidden sm:flex items-center gap-2 text-[11px] text-muted bg-panel border border-line px-3 py-1.5 rounded-lg">
|
||||||
|
<span className="h-2 w-2 rounded-full bg-emerald-500 animate-pulse" />
|
||||||
|
مدل دسترسی ماژولار مبتنی بر پنل
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="grid grid-cols-1 gap-4 lg:grid-cols-3">
|
||||||
|
{/* کارت پنل تدارکات */}
|
||||||
|
<div className="flex flex-col rounded-xl border border-line bg-canvas/40 p-4 transition-all hover:border-sky-500/40">
|
||||||
|
<div className="mb-3 flex items-center justify-between">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<span className="flex h-8 w-8 items-center justify-center rounded-lg bg-sky-500/10 text-[18px]">
|
||||||
|
🛒
|
||||||
|
</span>
|
||||||
|
<div>
|
||||||
|
<h4 className="text-[13.5px] font-bold text-foreground">پنل تدارکات</h4>
|
||||||
|
<span className="text-[10.5px] text-muted font-mono">Procurement</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<span className="rounded-md bg-sky-500/10 px-2 py-0.5 text-[11px] font-medium text-sky-600 dark:text-sky-400">
|
||||||
|
خرید و بازرگانی
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex-1 space-y-3">
|
||||||
|
<div className="rounded-lg border border-line/60 bg-panel/70 p-3">
|
||||||
|
<div className="mb-1 flex items-center gap-1.5">
|
||||||
|
<span className="inline-block h-2 w-2 rounded-full bg-emerald-500" />
|
||||||
|
<span className="text-[12px] font-bold text-emerald-600 dark:text-emerald-400">سطح کامل (Full)</span>
|
||||||
|
</div>
|
||||||
|
<ul className="space-y-1 pe-2 text-[11.5px] leading-relaxed text-muted list-disc list-inside">
|
||||||
|
<li>دسترسی کامل مدیریتی به تمامی بخشهای تدارکات</li>
|
||||||
|
<li>ثبت و ویرایش پیشفاکتورها، شرایط پرداخت و فاکتورها</li>
|
||||||
|
<li>مدیریت تأمینکنندگان، اقلام و تصمیمگیری خرید در همه پروژهها</li>
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="rounded-lg border border-line/60 bg-panel/70 p-3">
|
||||||
|
<div className="mb-1 flex items-center gap-1.5">
|
||||||
|
<span className="inline-block h-2 w-2 rounded-full bg-amber-500" />
|
||||||
|
<span className="text-[12px] font-bold text-amber-600 dark:text-amber-400">سطح محدود (Limited - متقاضی)</span>
|
||||||
|
</div>
|
||||||
|
<ul className="space-y-1 pe-2 text-[11.5px] leading-relaxed text-muted list-disc list-inside">
|
||||||
|
<li>فقط امکان ثبت درخواست استعلام قیمت و پیشفاکتور اولیه</li>
|
||||||
|
<li>محدود منحصراً به پروژههایی که کاربر در آنها عضویت دارد</li>
|
||||||
|
<li>عدم دسترسی به تأییدات نهایی، تغییر قیمتها یا پروژههای غیرعضو</li>
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* کارت پنل انبار */}
|
||||||
|
<div className="flex flex-col rounded-xl border border-line bg-canvas/40 p-4 transition-all hover:border-amber-500/40">
|
||||||
|
<div className="mb-3 flex items-center justify-between">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<span className="flex h-8 w-8 items-center justify-center rounded-lg bg-amber-500/10 text-[18px]">
|
||||||
|
📦
|
||||||
|
</span>
|
||||||
|
<div>
|
||||||
|
<h4 className="text-[13.5px] font-bold text-foreground">پنل انبار</h4>
|
||||||
|
<span className="text-[10.5px] text-muted font-mono">Inventory</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<span className="rounded-md bg-amber-500/10 px-2 py-0.5 text-[11px] font-medium text-amber-600 dark:text-amber-400">
|
||||||
|
انبارداری و موجودی
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex-1 space-y-3">
|
||||||
|
<div className="rounded-lg border border-line/60 bg-panel/70 p-3">
|
||||||
|
<div className="mb-1 flex items-center gap-1.5">
|
||||||
|
<span className="inline-block h-2 w-2 rounded-full bg-emerald-500" />
|
||||||
|
<span className="text-[12px] font-bold text-emerald-600 dark:text-emerald-400">سطح کامل (Full - مدیر/ناظر)</span>
|
||||||
|
</div>
|
||||||
|
<ul className="space-y-1 pe-2 text-[11.5px] leading-relaxed text-muted list-disc list-inside">
|
||||||
|
<li>مشاهده موجودی و کاردکس کالا در تمامی انبارها و پروژهها</li>
|
||||||
|
<li>پایش و نظارت بر گردش کالا در کل سازمان و گزارشگیری کلان</li>
|
||||||
|
<li className="font-semibold text-amber-700 dark:text-amber-300">بدون امکان تغییر مستقیم موجودی (جهت حفظ سلامت داده و کنترل نظارتی)</li>
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="rounded-lg border border-line/60 bg-panel/70 p-3">
|
||||||
|
<div className="mb-1 flex items-center gap-1.5">
|
||||||
|
<span className="inline-block h-2 w-2 rounded-full bg-amber-500" />
|
||||||
|
<span className="text-[12px] font-bold text-amber-600 dark:text-amber-400">سطح محدود (Limited - انباردار کارگاه)</span>
|
||||||
|
</div>
|
||||||
|
<ul className="space-y-1 pe-2 text-[11.5px] leading-relaxed text-muted list-disc list-inside">
|
||||||
|
<li>دسترسی فقط به انبارهای پروژههای عضویت کاربر</li>
|
||||||
|
<li>امکان ثبت و تغییر موجودی، رسید کالا، حواله مصرف و تطبیق فیزیکی</li>
|
||||||
|
<li>تفکیک دقیق موجودی و تراکنشهای انبار بر اساس پروژه</li>
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* کارت پنل مدیریت پروژه (PM) */}
|
||||||
|
<div className="flex flex-col rounded-xl border border-line bg-canvas/40 p-4 transition-all hover:border-indigo-500/40">
|
||||||
|
<div className="mb-3 flex items-center justify-between">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<span className="flex h-8 w-8 items-center justify-center rounded-lg bg-indigo-500/10 text-[18px]">
|
||||||
|
📊
|
||||||
|
</span>
|
||||||
|
<div>
|
||||||
|
<h4 className="text-[13.5px] font-bold text-foreground">پنل مدیریت پروژه (PM)</h4>
|
||||||
|
<span className="text-[10.5px] text-muted font-mono">Project Management</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<span className="rounded-md bg-indigo-500/10 px-2 py-0.5 text-[11px] font-medium text-indigo-600 dark:text-indigo-400">
|
||||||
|
کنترل پروژه و اجرا
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex-1 space-y-3">
|
||||||
|
<div className="rounded-lg border border-line/60 bg-panel/70 p-3">
|
||||||
|
<div className="mb-1 flex items-center gap-1.5">
|
||||||
|
<span className="inline-block h-2 w-2 rounded-full bg-emerald-500" />
|
||||||
|
<span className="text-[12px] font-bold text-emerald-600 dark:text-emerald-400">سطح کامل (Full - مدیر پروژه)</span>
|
||||||
|
</div>
|
||||||
|
<ul className="space-y-1 pe-2 text-[11.5px] leading-relaxed text-muted list-disc list-inside">
|
||||||
|
<li>مدیریت جامع ساختار شکست کار (WBS)، زمانبندی و گانت چارت تعاملی</li>
|
||||||
|
<li>تعریف و ویرایش فعالیتها، ثبت خط مبنا (Baseline)، کنترل هزینه و منابع</li>
|
||||||
|
<li>پایش شاخصهای پیشرفت زمانی و مالی (EVM) و گزارشهای تحلیلی</li>
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="rounded-lg border border-line/60 bg-panel/70 p-3">
|
||||||
|
<div className="mb-1 flex items-center gap-1.5">
|
||||||
|
<span className="inline-block h-2 w-2 rounded-full bg-amber-500" />
|
||||||
|
<span className="text-[12px] font-bold text-amber-600 dark:text-amber-400">سطح محدود (Limited - سرپرست/کارشناس)</span>
|
||||||
|
</div>
|
||||||
|
<ul className="space-y-1 pe-2 text-[11.5px] leading-relaxed text-muted list-disc list-inside">
|
||||||
|
<li>مشاهده فعالیتها و تسکهای مربوط به پروژههای عضویت کاربر</li>
|
||||||
|
<li>بهروزرسانی درصد پیشرفت فیزیکی و وضعیت انجام تسکها</li>
|
||||||
|
<li>تکمیل چکلیستهای کنترل کیفیت (QC) و ثبت گزارشهای اجرایی روزانه</li>
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* نوار توضیحات تکمیلی و راهنمای عمومی */}
|
||||||
|
<div className="mt-4 grid grid-cols-1 md:grid-cols-2 gap-3 pt-3 border-t border-line text-[11.5px]">
|
||||||
|
<div className="flex items-start gap-2.5 rounded-lg border border-line/60 bg-canvas/30 p-2.5">
|
||||||
|
<span className="text-[16px] leading-none">👑</span>
|
||||||
|
<div>
|
||||||
|
<span className="font-bold text-foreground">دسترسی ادمین (Admin):</span>
|
||||||
|
<p className="mt-0.5 text-muted leading-relaxed">
|
||||||
|
کاربر با نقش ادمین بالاترین سطح دسترسی سیستمی را داشته و به تمامی پنلها و پروژهها دسترسی کامل دارد و نیازی به تخصیص جداگانه پنلها ندارد.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex items-start gap-2.5 rounded-lg border border-line/60 bg-canvas/30 p-2.5">
|
||||||
|
<span className="text-[16px] leading-none">🎯</span>
|
||||||
|
<div>
|
||||||
|
<span className="font-bold text-foreground">کارکرد «پروژههای عضویت»:</span>
|
||||||
|
<p className="mt-0.5 text-muted leading-relaxed">
|
||||||
|
هرگاه برای کاربری در هر پنلی سطح «محدود» انتخاب شود، دامنه دادهها و اختیارات وی دقیقاً به پروژههای انتخابی در ستون «پروژههای عضویت» محدود خواهد شد.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</PageLayout>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,11 +1,11 @@
|
|||||||
import { useState } from "react";
|
import { useState } from "react";
|
||||||
import { Link } from "react-router-dom";
|
import { Link } from "react-router-dom";
|
||||||
import { toast } from "sonner";
|
import { toast } from "sonner";
|
||||||
import { Building2, Inbox, CheckCircle2, Truck, Phone, FolderKanban } from "lucide-react";
|
import { Building2, Inbox, CheckCircle2, Truck, Phone, FolderKanban, MapPin, UserCircle2, Trash2, Plus, X } from "lucide-react";
|
||||||
import type { Project, Quote, Store } from "../../lib/types";
|
import type { Project, Quote, Store } from "../../lib/types";
|
||||||
import { nextId } from "../../lib/api";
|
|
||||||
import {
|
import {
|
||||||
useAddProject,
|
useAddProject,
|
||||||
|
useDeleteProject,
|
||||||
useMaterials,
|
useMaterials,
|
||||||
useProjects,
|
useProjects,
|
||||||
useQuotes,
|
useQuotes,
|
||||||
@@ -25,6 +25,7 @@ import { faNum, fmtDate } from "../../lib/formatters";
|
|||||||
import { Header, PageLayout } from "../../components/layout/Header";
|
import { Header, PageLayout } from "../../components/layout/Header";
|
||||||
import { EmptyState } from "../../components/EmptyState";
|
import { EmptyState } from "../../components/EmptyState";
|
||||||
import { Button } from "../../components/ui/button";
|
import { Button } from "../../components/ui/button";
|
||||||
|
import { useAuthStore } from "../../store/auth";
|
||||||
|
|
||||||
function projectQuotes(quotes: Quote[], name: string): Quote[] {
|
function projectQuotes(quotes: Quote[], name: string): Quote[] {
|
||||||
return quotes.filter(
|
return quotes.filter(
|
||||||
@@ -39,23 +40,14 @@ function projectQuotes(quotes: Quote[], name: string): Quote[] {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
// آیا این پیشنهاد برای «این» پروژه پذیرفته شده است؟
|
|
||||||
// ملاک، پروژهی هدفِ تصمیم خریدِ اقلام است (item_decisions.project_id) — نه
|
|
||||||
// وضعیت سراسری پیشنهاد؛ پیشنهادی که فقط برای پروژهی دیگری پذیرفته شده،
|
|
||||||
// برای این پروژه همچنان «پیشنهاد شده» است.
|
|
||||||
function acceptedForProject(q: Quote, name: string): boolean {
|
function acceptedForProject(q: Quote, name: string): boolean {
|
||||||
return (q.line_items || []).some((li) => !li.rejected && li.target_project?.name === name);
|
return (q.line_items || []).some((li) => !li.rejected && li.target_project?.name === name);
|
||||||
}
|
}
|
||||||
|
|
||||||
// آیا اصلاً برای این پیشنهاد پروژهی هدفی ثبت شده؟ (پیشنهادهای قدیمیِ
|
|
||||||
// پیش از era تصمیمپروژه، طبق وضعیت سراسری دستهبندی میشوند)
|
|
||||||
function hasTargets(q: Quote): boolean {
|
function hasTargets(q: Quote): boolean {
|
||||||
return (q.line_items || []).some((li) => !!li.target_project);
|
return (q.line_items || []).some((li) => !!li.target_project);
|
||||||
}
|
}
|
||||||
|
|
||||||
// اقلام مربوط به این پروژه در یک quote:
|
|
||||||
// اولویت با اقلامِ پذیرفتهشده برای همین پروژه (تصمیم خرید)؛ سپس کاندیداهای
|
|
||||||
// همین پروژه؛ و اگر هیچ اتصال قلمبهقلمی نبود، همهی اقلام فعال.
|
|
||||||
function itemsForProject(q: Quote, name: string): Quote["line_items"] {
|
function itemsForProject(q: Quote, name: string): Quote["line_items"] {
|
||||||
const items = (q.line_items || []).filter((li) => !li.rejected);
|
const items = (q.line_items || []).filter((li) => !li.rejected);
|
||||||
const targeted = items.filter((li) => li.target_project?.name === name);
|
const targeted = items.filter((li) => li.target_project?.name === name);
|
||||||
@@ -73,6 +65,97 @@ function daysSince(iso: string | null): number | null {
|
|||||||
return Math.floor((Date.now() - d.getTime()) / 86400000);
|
return Math.floor((Date.now() - d.getTime()) / 86400000);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ----- مودال افزودن پروژه -----
|
||||||
|
function AddProjectModal({
|
||||||
|
open,
|
||||||
|
onClose,
|
||||||
|
onSubmit,
|
||||||
|
loading,
|
||||||
|
}: {
|
||||||
|
open: boolean;
|
||||||
|
onClose: () => void;
|
||||||
|
onSubmit: (p: Omit<Project, "id">) => void;
|
||||||
|
loading: boolean;
|
||||||
|
}) {
|
||||||
|
const [name, setName] = useState("");
|
||||||
|
const [location, setLocation] = useState("");
|
||||||
|
const [projectManager, setProjectManager] = useState("");
|
||||||
|
const [description, setDescription] = useState("");
|
||||||
|
const [error, setError] = useState("");
|
||||||
|
|
||||||
|
const inputCls =
|
||||||
|
"w-full rounded-lg border border-line bg-surface px-3 py-2 text-sm shadow-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent/40";
|
||||||
|
|
||||||
|
const reset = () => {
|
||||||
|
setName(""); setLocation(""); setProjectManager(""); setDescription(""); setError("");
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleClose = () => { reset(); onClose(); };
|
||||||
|
|
||||||
|
const handleSubmit = () => {
|
||||||
|
if (!name.trim()) { setError("نام پروژه الزامی است"); return; }
|
||||||
|
setError("");
|
||||||
|
onSubmit({ name: name.trim(), location: location.trim(), project_manager: projectManager.trim(), description: description.trim() });
|
||||||
|
};
|
||||||
|
|
||||||
|
if (!open) return null;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-sm" onClick={handleClose}>
|
||||||
|
<div
|
||||||
|
className="w-full max-w-lg rounded-2xl bg-panel shadow-2xl border border-line p-6"
|
||||||
|
onClick={(e) => e.stopPropagation()}
|
||||||
|
>
|
||||||
|
<div className="flex items-center justify-between mb-4">
|
||||||
|
<h2 className="text-base font-bold">افزودن پروژه جدید</h2>
|
||||||
|
<button type="button" onClick={handleClose} className="text-muted hover:text-on-surface transition-colors">
|
||||||
|
<X size={18} />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-3">
|
||||||
|
{error && <p className="rounded-lg bg-red-50 border border-red-200 text-red-700 px-3 py-2 text-xs">{error}</p>}
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label className="mb-1 block text-xs font-semibold text-muted">نام پروژه *</label>
|
||||||
|
<input
|
||||||
|
value={name}
|
||||||
|
onChange={(e) => setName(e.target.value)}
|
||||||
|
onKeyDown={(e) => { if (e.key === "Enter") handleSubmit(); }}
|
||||||
|
placeholder="مثلاً: برج مسکونی آسمان"
|
||||||
|
className={inputCls}
|
||||||
|
autoFocus
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="grid grid-cols-2 gap-2">
|
||||||
|
<div>
|
||||||
|
<label className="mb-1 block text-xs font-semibold text-muted">محل پروژه</label>
|
||||||
|
<input value={location} onChange={(e) => setLocation(e.target.value)} placeholder="شهر / منطقه" className={inputCls} />
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label className="mb-1 block text-xs font-semibold text-muted">مدیر / سرپرست پروژه</label>
|
||||||
|
<input value={projectManager} onChange={(e) => setProjectManager(e.target.value)} placeholder="نام سرپرست" className={inputCls} />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label className="mb-1 block text-xs font-semibold text-muted">توضیحات</label>
|
||||||
|
<textarea value={description} onChange={(e) => setDescription(e.target.value)} rows={2} placeholder="توضیحات تکمیلی پروژه..." className={`${inputCls} resize-none`} />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex justify-end gap-2 pt-2">
|
||||||
|
<button type="button" onClick={handleClose} className="h-9 rounded-lg border border-line px-4 text-sm text-muted hover:bg-surface transition-colors">انصراف</button>
|
||||||
|
<button type="button" disabled={loading} onClick={handleSubmit} className="h-9 rounded-lg bg-accent px-4 text-sm font-semibold text-white hover:bg-accent/90 disabled:opacity-50 transition-colors">
|
||||||
|
{loading ? "در حال ذخیره..." : "افزودن پروژه"}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
// صفحهی پروژهها — لیست + پنل جزئیات ۳ ستونه
|
// صفحهی پروژهها — لیست + پنل جزئیات ۳ ستونه
|
||||||
export function ProjectsPage() {
|
export function ProjectsPage() {
|
||||||
useStoreData();
|
useStoreData();
|
||||||
@@ -82,54 +165,53 @@ export function ProjectsPage() {
|
|||||||
const materials = useMaterials();
|
const materials = useMaterials();
|
||||||
const { standardConversions } = useUnits();
|
const { standardConversions } = useUnits();
|
||||||
const addProject = useAddProject();
|
const addProject = useAddProject();
|
||||||
|
const deleteProject = useDeleteProject();
|
||||||
const topics = useAppStore((s) => s.topics);
|
const topics = useAppStore((s) => s.topics);
|
||||||
|
const user = useAuthStore((s) => s.user);
|
||||||
|
const canManage = user?.role === "admin" || user?.role === "procurement_manager";
|
||||||
|
|
||||||
const store: Store = { quotes, suppliers, materials, projects, standardConversions, topics };
|
const store: Store = { quotes, suppliers, materials, projects, standardConversions, topics };
|
||||||
|
|
||||||
const [openProject, setOpenProject] = useState<string | null>(null);
|
const [openProject, setOpenProject] = useState<string | null>(null);
|
||||||
const [newName, setNewName] = useState("");
|
const [showAddModal, setShowAddModal] = useState(false);
|
||||||
|
|
||||||
const addProj = () => {
|
const handleAddProject = async (data: Omit<Project, "id">) => {
|
||||||
const name = newName.trim();
|
const dup = projects.some((p) => normalize(p.name) === normalize(data.name));
|
||||||
if (!name) return;
|
if (dup) { toast.error("این پروژه قبلاً ثبت شده است."); return; }
|
||||||
const dup = projects.some((p) => normalize(p.name) === normalize(name));
|
try {
|
||||||
if (dup) {
|
await addProject.mutateAsync({ id: "", ...data });
|
||||||
toast.error("این پروژه قبلاً ثبت شده است.");
|
setShowAddModal(false);
|
||||||
return;
|
setOpenProject(data.name);
|
||||||
|
toast.success("پروژه با موفقیت اضافه شد.");
|
||||||
|
} catch {
|
||||||
|
toast.error("خطا در ثبت پروژه");
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleDeleteProject = async (p: Project, e: React.MouseEvent) => {
|
||||||
|
e.stopPropagation();
|
||||||
|
if (!confirm(`آیا از حذف پروژه «${p.name}» مطمئن هستید؟`)) return;
|
||||||
|
try {
|
||||||
|
await deleteProject.mutateAsync(p.id);
|
||||||
|
toast.success("پروژه حذف شد.");
|
||||||
|
if (openProject === p.name) setOpenProject(null);
|
||||||
|
} catch (err: any) {
|
||||||
|
toast.error(err?.message || "این پروژه دارای پیشنهاد است و قابل حذف نیست");
|
||||||
}
|
}
|
||||||
const p: Project = { id: nextId("p", projects), name };
|
|
||||||
void addProject.mutateAsync(p);
|
|
||||||
setNewName("");
|
|
||||||
setOpenProject(name);
|
|
||||||
toast.success("پروژه افزوده شد.");
|
|
||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="min-h-screen">
|
<div className="min-h-screen">
|
||||||
<Header title="پروژهها" sub="روی یک پروژه کلیک کنید تا جزئیات آن باز شود" backTo="/" backLabel="بازگشت به دفتر" />
|
<Header title="پروژهها" sub="مدیریت پروژههای مشترک سامانه" backTo="/" backLabel="بازگشت به دفتر" />
|
||||||
<PageLayout className="flex flex-col gap-4">
|
<PageLayout className="flex flex-col gap-4">
|
||||||
<div className="add-panel">
|
<div className="add-panel flex items-center justify-between">
|
||||||
<h4>+ افزودن پروژهی جدید</h4>
|
<h4>پروژههای سامانه</h4>
|
||||||
<div className="grid max-w-md grid-cols-[1fr_auto] items-end gap-2">
|
{canManage && (
|
||||||
<div className="field">
|
<Button onClick={() => setShowAddModal(true)} className="flex items-center gap-1.5">
|
||||||
<label>نام پروژه *</label>
|
<Plus size={15} />
|
||||||
<input
|
افزودن پروژه
|
||||||
type="text"
|
</Button>
|
||||||
className="h-9 w-full rounded-lg border border-line bg-panel px-3 text-sm shadow-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent/40"
|
)}
|
||||||
placeholder="مثلاً برج آیتا - فاز ۳"
|
|
||||||
autoComplete="off"
|
|
||||||
value={newName}
|
|
||||||
onChange={(e) => setNewName(e.target.value)}
|
|
||||||
onKeyDown={(e) => {
|
|
||||||
if (e.key === "Enter") {
|
|
||||||
e.preventDefault();
|
|
||||||
addProj();
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<Button onClick={addProj}>افزودن پروژه</Button>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{!projects.length && !quotes.length ? (
|
{!projects.length && !quotes.length ? (
|
||||||
@@ -141,16 +223,37 @@ export function ProjectsPage() {
|
|||||||
const open = openProject === p.name;
|
const open = openProject === p.name;
|
||||||
return (
|
return (
|
||||||
<div key={p.id} className="flex flex-col gap-1.5">
|
<div key={p.id} className="flex flex-col gap-1.5">
|
||||||
|
<div className={`proj-item flex items-center gap-2 ${open ? "open" : ""}`}>
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
className={`proj-item ${open ? "open" : ""}`}
|
className="flex flex-1 items-center gap-2 min-w-0 text-right"
|
||||||
onClick={() => setOpenProject(open ? null : p.name)}
|
onClick={() => setOpenProject(open ? null : p.name)}
|
||||||
>
|
>
|
||||||
<span className={open ? "text-accent" : "text-muted"}>{open ? "▾" : "▸"}</span>
|
<span className={open ? "text-accent" : "text-muted"}>{open ? "▾" : "▸"}</span>
|
||||||
<span className="font-medium">{p.name}</span>
|
<span className="font-medium truncate">{p.name}</span>
|
||||||
<span className="proj-count">{faNum(count)} پیشنهاد</span>
|
{p.location && (
|
||||||
|
<span className="flex items-center gap-0.5 text-[11px] text-muted shrink-0">
|
||||||
|
<MapPin size={10} />{p.location}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
{p.project_manager && (
|
||||||
|
<span className="flex items-center gap-0.5 text-[11px] text-muted shrink-0">
|
||||||
|
<UserCircle2 size={10} />{p.project_manager}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
<span className="proj-count ms-auto shrink-0">{faNum(count)} پیشنهاد</span>
|
||||||
</button>
|
</button>
|
||||||
{/* جزئیات دقیقاً زیر همان پروژه باز میشود */}
|
{canManage && (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={(e) => handleDeleteProject(p, e)}
|
||||||
|
title="حذف پروژه"
|
||||||
|
className="text-muted hover:text-red-600 transition-colors p-1 rounded shrink-0"
|
||||||
|
>
|
||||||
|
<Trash2 size={13} />
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
{open && <div className="ms-2">{renderProjectDetail(store, p.name)}</div>}
|
{open && <div className="ms-2">{renderProjectDetail(store, p.name)}</div>}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
@@ -158,6 +261,13 @@ export function ProjectsPage() {
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</PageLayout>
|
</PageLayout>
|
||||||
|
|
||||||
|
<AddProjectModal
|
||||||
|
open={showAddModal}
|
||||||
|
onClose={() => setShowAddModal(false)}
|
||||||
|
onSubmit={handleAddProject}
|
||||||
|
loading={addProject.isPending}
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -166,7 +276,6 @@ export function ProjectsPage() {
|
|||||||
function renderProjectDetail(store: Store, name: string): React.ReactElement {
|
function renderProjectDetail(store: Store, name: string): React.ReactElement {
|
||||||
const quotes = projectQuotes(store.quotes, name);
|
const quotes = projectQuotes(store.quotes, name);
|
||||||
|
|
||||||
// جمع مبلغ هر ستون فقط روی اقلامِ همین پروژه
|
|
||||||
const itemsTotal = (q: Quote) =>
|
const itemsTotal = (q: Quote) =>
|
||||||
itemsForProject(q, name).reduce((s, li) => s + (lineItemTotal(li) || 0), 0);
|
itemsForProject(q, name).reduce((s, li) => s + (lineItemTotal(li) || 0), 0);
|
||||||
const sumBy = (list: Quote[]) => list.reduce((s, q) => s + itemsTotal(q), 0);
|
const sumBy = (list: Quote[]) => list.reduce((s, q) => s + itemsTotal(q), 0);
|
||||||
@@ -196,10 +305,6 @@ function renderProjectDetail(store: Store, name: string): React.ReactElement {
|
|||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
// دستهبندی ایزوله per-project:
|
|
||||||
// - پذیرفته/رسیده فقط وقتی حداقل یک قلمِ غیرردشده برای «این» پروژه پذیرفته شده باشد؛
|
|
||||||
// - پیشنهادی که صرفاً کاندیداست (یا فقط برای پروژهی دیگری پذیرفته شده) → پیشنهاد شده.
|
|
||||||
// - پیشنهادهای قدیمیِ بدون پروژهی هدف، طبق وضعیت سراسری میمانند.
|
|
||||||
const offered = quotes
|
const offered = quotes
|
||||||
.filter(
|
.filter(
|
||||||
(q) =>
|
(q) =>
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ import { Combobox } from "../../components/Combobox";
|
|||||||
import { SupplierCard, suppliersOfCategory } from "./supplierUtils";
|
import { SupplierCard, suppliersOfCategory } from "./supplierUtils";
|
||||||
import { materialLabel } from "../../lib/quoteUtils";
|
import { materialLabel } from "../../lib/quoteUtils";
|
||||||
import { Button } from "../../components/ui/button";
|
import { Button } from "../../components/ui/button";
|
||||||
|
import { useAuthStore } from "../../store/auth";
|
||||||
|
|
||||||
// صفحهی تأمینکنندههای یک دسته + فرم افزودن تأمینکننده
|
// صفحهی تأمینکنندههای یک دسته + فرم افزودن تأمینکننده
|
||||||
export function CategoryPage() {
|
export function CategoryPage() {
|
||||||
@@ -26,6 +27,8 @@ export function CategoryPage() {
|
|||||||
const addSupplier = useAddSupplier();
|
const addSupplier = useAddSupplier();
|
||||||
const removeSupplier = useRemoveSupplier();
|
const removeSupplier = useRemoveSupplier();
|
||||||
const topics = useAppStore((s) => s.topics);
|
const topics = useAppStore((s) => s.topics);
|
||||||
|
const user = useAuthStore((s) => s.user);
|
||||||
|
const canManage = user?.role === "admin" || user?.role === "procurement_manager";
|
||||||
|
|
||||||
const cat = useMemo(() => topicByName(catParam, topics)?.name ?? null, [catParam, topics]);
|
const cat = useMemo(() => topicByName(catParam, topics)?.name ?? null, [catParam, topics]);
|
||||||
|
|
||||||
@@ -121,7 +124,7 @@ export function CategoryPage() {
|
|||||||
key={s.id}
|
key={s.id}
|
||||||
s={s}
|
s={s}
|
||||||
topic={cat}
|
topic={cat}
|
||||||
deletable
|
deletable={canManage}
|
||||||
onDelete={removeSup}
|
onDelete={removeSup}
|
||||||
materials={supMats.get(s.id) || []}
|
materials={supMats.get(s.id) || []}
|
||||||
avgLeadTime={supLeadTimes.get(s.id)}
|
avgLeadTime={supLeadTimes.get(s.id)}
|
||||||
@@ -130,6 +133,7 @@ export function CategoryPage() {
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{canManage && (
|
||||||
<div className="add-panel">
|
<div className="add-panel">
|
||||||
<h4>
|
<h4>
|
||||||
<Plus className="me-1 inline h-4 w-4 text-accent" /> افزودن تأمینکنندهی جدید
|
<Plus className="me-1 inline h-4 w-4 text-accent" /> افزودن تأمینکنندهی جدید
|
||||||
@@ -182,6 +186,7 @@ export function CategoryPage() {
|
|||||||
ذخیره تأمینکننده
|
ذخیره تأمینکننده
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
|
)}
|
||||||
</PageLayout>
|
</PageLayout>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ import { MultiSelectCombobox } from "../../components/MultiSelectCombobox";
|
|||||||
import { ConfirmDeleteDialog } from "../../components/ConfirmDeleteDialog";
|
import { ConfirmDeleteDialog } from "../../components/ConfirmDeleteDialog";
|
||||||
import { normalize } from "../../lib/normalize";
|
import { normalize } from "../../lib/normalize";
|
||||||
import { PurchaseHistory } from "./PurchaseHistory";
|
import { PurchaseHistory } from "./PurchaseHistory";
|
||||||
|
import { useAuthStore } from "../../store/auth";
|
||||||
|
|
||||||
// تمیزکاری و استانداردسازی شماره برای شمارهگیر خودکار موبایل (اندروید و iOS)
|
// تمیزکاری و استانداردسازی شماره برای شمارهگیر خودکار موبایل (اندروید و iOS)
|
||||||
function cleanPhoneForTel(phone?: string | null): string {
|
function cleanPhoneForTel(phone?: string | null): string {
|
||||||
@@ -32,6 +33,8 @@ export function SupplierDetailPage() {
|
|||||||
const quotes = useQuotes();
|
const quotes = useQuotes();
|
||||||
const materials = useMaterials();
|
const materials = useMaterials();
|
||||||
const topics = useAppStore((s) => s.topics);
|
const topics = useAppStore((s) => s.topics);
|
||||||
|
const user = useAuthStore((s) => s.user);
|
||||||
|
const canManage = user?.role === "admin" || user?.role === "procurement_manager";
|
||||||
|
|
||||||
const s = useMemo(() => suppliers.find((x) => x.id === id) || null, [suppliers, id]);
|
const s = useMemo(() => suppliers.find((x) => x.id === id) || null, [suppliers, id]);
|
||||||
const [pendingRemove, setPendingRemove] = useState<string | null>(null);
|
const [pendingRemove, setPendingRemove] = useState<string | null>(null);
|
||||||
@@ -184,6 +187,7 @@ export function SupplierDetailPage() {
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="mt-4 flex items-center gap-2">
|
<div className="mt-4 flex items-center gap-2">
|
||||||
|
{canManage && (
|
||||||
<Link
|
<Link
|
||||||
to={`/wizard?topic=${encodeURIComponent(topicName)}&supplier=${encodeURIComponent(s.id)}`}
|
to={`/wizard?topic=${encodeURIComponent(topicName)}&supplier=${encodeURIComponent(s.id)}`}
|
||||||
className="btn-line-file no-underline bg-accent text-white hover:bg-accent-dark"
|
className="btn-line-file no-underline bg-accent text-white hover:bg-accent-dark"
|
||||||
@@ -191,6 +195,7 @@ export function SupplierDetailPage() {
|
|||||||
<Plus className="h-3.5 w-3.5" />
|
<Plus className="h-3.5 w-3.5" />
|
||||||
پیشنهاد جدید
|
پیشنهاد جدید
|
||||||
</Link>
|
</Link>
|
||||||
|
)}
|
||||||
{firstCat ? (
|
{firstCat ? (
|
||||||
<Link to={`/suppliers/category/${encodeURIComponent(firstCat)}`} className="btn-line-file no-underline">
|
<Link to={`/suppliers/category/${encodeURIComponent(firstCat)}`} className="btn-line-file no-underline">
|
||||||
‹ بازگشت به دسته
|
‹ بازگشت به دسته
|
||||||
@@ -216,19 +221,23 @@ export function SupplierDetailPage() {
|
|||||||
{linked.map((c) => (
|
{linked.map((c) => (
|
||||||
<span key={c} className="spec-chip">
|
<span key={c} className="spec-chip">
|
||||||
{c}
|
{c}
|
||||||
|
{canManage && (
|
||||||
<button type="button" className="spec-chip-x" title="حذف متریال" onClick={() => setPendingRemove(c)}>
|
<button type="button" className="spec-chip-x" title="حذف متریال" onClick={() => setPendingRemove(c)}>
|
||||||
<X className="h-3 w-3" />
|
<X className="h-3 w-3" />
|
||||||
</button>
|
</button>
|
||||||
|
)}
|
||||||
</span>
|
</span>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
{canManage && (
|
||||||
<MultiSelectCombobox
|
<MultiSelectCombobox
|
||||||
values={[]}
|
values={[]}
|
||||||
onChange={(cats) => saveCategories(cats)}
|
onChange={(cats) => saveCategories(cats)}
|
||||||
options={materialOptions}
|
options={materialOptions}
|
||||||
placeholder="افزودن متریال..."
|
placeholder="افزودن متریال..."
|
||||||
/>
|
/>
|
||||||
|
)}
|
||||||
{purchased.length > 0 && (
|
{purchased.length > 0 && (
|
||||||
<div className="mt-3 border-t border-line pt-2">
|
<div className="mt-3 border-t border-line pt-2">
|
||||||
<div className="mb-1 text-[11px] font-semibold text-muted">متریالهای خریداریشده (از پیشنهادها):</div>
|
<div className="mb-1 text-[11px] font-semibold text-muted">متریالهای خریداریشده (از پیشنهادها):</div>
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||||
import { toast } from "sonner";
|
import { toast } from "sonner";
|
||||||
import {
|
import {
|
||||||
|
Building2,
|
||||||
ChevronDown,
|
ChevronDown,
|
||||||
Link2,
|
Link2,
|
||||||
Pencil,
|
Pencil,
|
||||||
@@ -12,7 +13,7 @@ import {
|
|||||||
TriangleAlert,
|
TriangleAlert,
|
||||||
} from "lucide-react";
|
} from "lucide-react";
|
||||||
import type { StandardConversion } from "../../lib/types";
|
import type { StandardConversion } from "../../lib/types";
|
||||||
import { api, apiV26, nextId, type BrandLinkRow, type MaterialUnitRow } from "../../lib/api";
|
import { api, apiV26, nextId, type BrandLinkRow, type MaterialSupplier, type MaterialUnitRow } from "../../lib/api";
|
||||||
import {
|
import {
|
||||||
refreshProcurementStore,
|
refreshProcurementStore,
|
||||||
useDeleteStandardConversion,
|
useDeleteStandardConversion,
|
||||||
@@ -102,6 +103,11 @@ export function UnitsPage() {
|
|||||||
const [rowsLoading, setRowsLoading] = useState(false);
|
const [rowsLoading, setRowsLoading] = useState(false);
|
||||||
const [brandLinks, setBrandLinks] = useState<BrandLinkRow[]>([]);
|
const [brandLinks, setBrandLinks] = useState<BrandLinkRow[]>([]);
|
||||||
|
|
||||||
|
// تأمینکنندههای متریال انتخابشده — type imported from api.ts
|
||||||
|
const [materialSuppliers, setMaterialSuppliers] = useState<MaterialSupplier[]>([]);
|
||||||
|
const [suppliersLoading, setSuppliersLoading] = useState(false);
|
||||||
|
const [suppliersLoadedId, setSuppliersLoadedId] = useState<string | null>(null);
|
||||||
|
|
||||||
// واحدها و برندهای سراسری (فهرست دیتابیس)
|
// واحدها و برندهای سراسری (فهرست دیتابیس)
|
||||||
const [units, setUnits] = useState<UnitLite[]>([]);
|
const [units, setUnits] = useState<UnitLite[]>([]);
|
||||||
const [allBrands, setAllBrands] = useState<string[]>([]);
|
const [allBrands, setAllBrands] = useState<string[]>([]);
|
||||||
@@ -253,6 +259,7 @@ export function UnitsPage() {
|
|||||||
if (!materialId) {
|
if (!materialId) {
|
||||||
setRows([]);
|
setRows([]);
|
||||||
setBrandLinks([]);
|
setBrandLinks([]);
|
||||||
|
setMaterialSuppliers([]);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
void loadRows(materialId);
|
void loadRows(materialId);
|
||||||
@@ -263,6 +270,35 @@ export function UnitsPage() {
|
|||||||
setFormBrand("");
|
setFormBrand("");
|
||||||
}, [materialId, loadRows]);
|
}, [materialId, loadRows]);
|
||||||
|
|
||||||
|
// واکشی تأمینکنندههای متصل به متریال انتخابشده
|
||||||
|
useEffect(() => {
|
||||||
|
if (!materialId) {
|
||||||
|
setMaterialSuppliers([]);
|
||||||
|
setSuppliersLoadedId(null);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let alive = true;
|
||||||
|
setSuppliersLoading(true);
|
||||||
|
api.materials
|
||||||
|
.listSuppliers(materialId)
|
||||||
|
.then((list) => {
|
||||||
|
if (alive) {
|
||||||
|
setMaterialSuppliers(list);
|
||||||
|
setSuppliersLoadedId(materialId);
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.catch((err: unknown) => {
|
||||||
|
if (!alive) return;
|
||||||
|
setMaterialSuppliers([]);
|
||||||
|
setSuppliersLoadedId(materialId);
|
||||||
|
// Surface the real error so backend issues are not silently hidden
|
||||||
|
const msg = err instanceof Error ? err.message : "خواندن تأمینکنندههای متریال ناموفق بود";
|
||||||
|
toast.error(msg);
|
||||||
|
})
|
||||||
|
.finally(() => { if (alive) setSuppliersLoading(false); });
|
||||||
|
return () => { alive = false; };
|
||||||
|
}, [materialId]);
|
||||||
|
|
||||||
const brandNameFor = (row: MaterialUnitRow): string => {
|
const brandNameFor = (row: MaterialUnitRow): string => {
|
||||||
if (!row.brand_material_id) return "";
|
if (!row.brand_material_id) return "";
|
||||||
return brandLinks.find((b) => b.id === row.brand_material_id)?.brand_name || "";
|
return brandLinks.find((b) => b.id === row.brand_material_id)?.brand_name || "";
|
||||||
@@ -546,6 +582,48 @@ export function UnitsPage() {
|
|||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
<>
|
<>
|
||||||
|
{/* تامینکنندگان متریال — پاسخ GET /materials/{id}/suppliers */}
|
||||||
|
<div className="mb-6 flex flex-col overflow-hidden rounded-xl border border-line bg-panel shadow-sm">
|
||||||
|
<div className="shrink-0 border-b border-line bg-panel px-4 py-3">
|
||||||
|
<h4 className="flex items-center gap-2 text-[14px] font-bold text-accent">
|
||||||
|
<Building2 className="h-4 w-4" /> تامینکنندگان متریال
|
||||||
|
</h4>
|
||||||
|
</div>
|
||||||
|
<div className="flex w-full flex-1 flex-col p-4 transition-opacity duration-300 ease-in-out opacity-100 min-h-[80px] md:min-h-[100px]">
|
||||||
|
{suppliersLoading || materialId !== suppliersLoadedId ? (
|
||||||
|
<div className="flex flex-1 flex-col items-center justify-center text-center text-sm text-muted">
|
||||||
|
<div className="h-5 w-5 animate-spin rounded-full border-2 border-muted border-t-transparent"></div>
|
||||||
|
</div>
|
||||||
|
) : materialSuppliers.length === 0 ? (
|
||||||
|
<div className="flex flex-1 flex-col items-center justify-center text-center text-sm text-gray-400 md:text-base">
|
||||||
|
تامینکنندهای برای این متریال ثبت نشده است
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div className="flex flex-col gap-2 max-h-[200px] overflow-y-auto custom-scrollbar pr-1">
|
||||||
|
{materialSuppliers.map((s) => (
|
||||||
|
<div
|
||||||
|
key={s.id}
|
||||||
|
className="rounded-lg border border-line bg-slate-bg px-3 py-2.5 text-sm shrink-0"
|
||||||
|
>
|
||||||
|
{/* نام تأمینکننده — مستقیم از پاسخ API، بدون fallback */}
|
||||||
|
<div className="flex items-center gap-1.5 text-[13px] font-semibold">
|
||||||
|
<Building2 className="h-3.5 w-3.5 shrink-0 text-accent" />
|
||||||
|
{s.name}
|
||||||
|
</div>
|
||||||
|
{(s.location || s.phone || s.contact_person) && (
|
||||||
|
<div className="mt-0.5 flex flex-wrap items-center gap-x-3 gap-y-0.5 text-[11.5px] text-muted">
|
||||||
|
{s.location && <span>{s.location}</span>}
|
||||||
|
{s.phone && <span dir="ltr">{s.phone}</span>}
|
||||||
|
{s.contact_person && <span>{s.contact_person}</span>}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
{/* واحد مرجع متریال */}
|
{/* واحد مرجع متریال */}
|
||||||
<div className="ref-unit-box">
|
<div className="ref-unit-box">
|
||||||
<div className="ref-title">
|
<div className="ref-title">
|
||||||
@@ -587,119 +665,6 @@ export function UnitsPage() {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* ضرایب متریال */}
|
|
||||||
<h4 className="sec-title">
|
|
||||||
<Repeat className="me-1 inline h-4 w-4 text-accent" /> ضریبهای تبدیل
|
|
||||||
</h4>
|
|
||||||
{rowsLoading ? (
|
|
||||||
<div className="conv-empty">در حال بارگذاری…</div>
|
|
||||||
) : !rows.length ? (
|
|
||||||
<div className="conv-empty">هنوز ضریبی برای این متریال ثبت نشده است.</div>
|
|
||||||
) : (
|
|
||||||
rows.map((r) => (
|
|
||||||
<div key={r.id}>
|
|
||||||
<div className="cg-head">
|
|
||||||
{unitDisplay(r.unit) || `واحد #${r.unit_id}`} ← {ref}
|
|
||||||
</div>
|
|
||||||
<div className="conv-row">
|
|
||||||
<span className="cv-brand">{brandNameFor(r) || "همه برندها"}</span>
|
|
||||||
<span className="cv-factor">{faNum(r.conversion_factor)}</span>
|
|
||||||
<span className="cv-arrow">×</span>
|
|
||||||
<span className="cv-unit">{ref}</span>
|
|
||||||
<span className="conv-actions">
|
|
||||||
<button type="button" title="ویرایش" onClick={() => startEdit(r)}>
|
|
||||||
<Pencil className="h-3.5 w-3.5" />
|
|
||||||
</button>
|
|
||||||
<button type="button" title="حذف" onClick={() => void deleteMu(r)}>
|
|
||||||
<Trash2 className="h-3.5 w-3.5" />
|
|
||||||
</button>
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
))
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* فرم افزودن ضریب */}
|
|
||||||
<div className="add-conv">
|
|
||||||
<h4 className="mb-2 text-[13.5px] font-bold">
|
|
||||||
{editingId ? (
|
|
||||||
<>
|
|
||||||
<Pencil className="me-1 inline h-3.5 w-3.5" /> ویرایش ضریب تبدیل
|
|
||||||
</>
|
|
||||||
) : (
|
|
||||||
<>
|
|
||||||
<Plus className="me-1 inline h-3.5 w-3.5" /> افزودن ضریب تبدیل
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
</h4>
|
|
||||||
<div className="grid grid-cols-1 gap-2 sm:grid-cols-[1.2fr_0.6fr_1fr_0.8fr_auto] sm:items-end">
|
|
||||||
<div className="field">
|
|
||||||
<label>واحد پیشنهادشده</label>
|
|
||||||
<Combobox
|
|
||||||
value={formUnit}
|
|
||||||
onChange={(it) => setFormUnit(it.label)}
|
|
||||||
items={units.map((u) => unitDisplay(u)).filter(Boolean)}
|
|
||||||
allowAdd
|
|
||||||
addSuffix="به عنوان واحد جدید"
|
|
||||||
placeholder="مثلاً حلقه"
|
|
||||||
onInputChange={setFormUnit}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<div className="field">
|
|
||||||
<label>ضریب</label>
|
|
||||||
<NumberInput
|
|
||||||
value={factorNum()}
|
|
||||||
onChange={(n) => setFormFactor(n != null ? String(n) : "")}
|
|
||||||
placeholder="مثلاً 0.98"
|
|
||||||
inputMode="decimal"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<div className="field">
|
|
||||||
<label>برند (خالی = همه برندها)</label>
|
|
||||||
<Combobox
|
|
||||||
value={formBrand}
|
|
||||||
onChange={(it) => setFormBrand(it.label)}
|
|
||||||
items={allBrands}
|
|
||||||
allowAdd
|
|
||||||
disabled={!!editingId}
|
|
||||||
addSuffix="به عنوان برند جدید"
|
|
||||||
placeholder="مثلاً راجین"
|
|
||||||
onInputChange={setFormBrand}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<div className="field">
|
|
||||||
<label>به واحد (مرجع)</label>
|
|
||||||
<input
|
|
||||||
type="text"
|
|
||||||
className="h-9 w-full rounded-lg border border-line bg-slate-bg px-3 text-sm text-muted"
|
|
||||||
value={ref || "مرجع"}
|
|
||||||
placeholder="مرجع"
|
|
||||||
readOnly
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<div className="flex items-center gap-1.5">
|
|
||||||
<Button size="sm" onClick={() => void saveConv()}>
|
|
||||||
{editingId ? "ذخیره تغییرات" : "افزودن"}
|
|
||||||
</Button>
|
|
||||||
{editingId && (
|
|
||||||
<Button
|
|
||||||
size="sm"
|
|
||||||
variant="slate"
|
|
||||||
onClick={() => {
|
|
||||||
setEditingId(null);
|
|
||||||
setFormUnit("");
|
|
||||||
setFormFactor("");
|
|
||||||
setFormBrand("");
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
انصراف
|
|
||||||
</Button>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div className="conv-live">{convLive}</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* واحدهای ناشناخته */}
|
{/* واحدهای ناشناخته */}
|
||||||
{unknownUnits.length > 0 && (
|
{unknownUnits.length > 0 && (
|
||||||
<>
|
<>
|
||||||
@@ -829,6 +794,121 @@ export function UnitsPage() {
|
|||||||
تبدیل ثابت برای همهی متریالها اعمال میشود؛ ضریب یعنی: ۱ از واحد = ضریب × به واحد
|
تبدیل ثابت برای همهی متریالها اعمال میشود؛ ضریب یعنی: ۱ از واحد = ضریب × به واحد
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|
||||||
|
{/* ضرایب متریال */}
|
||||||
|
<h4 className="sec-title">
|
||||||
|
<Repeat className="me-1 inline h-4 w-4 text-accent" /> ضریبهای تبدیل
|
||||||
|
</h4>
|
||||||
|
{rowsLoading ? (
|
||||||
|
<div className="conv-empty">در حال بارگذاری…</div>
|
||||||
|
) : !rows.length ? (
|
||||||
|
<div className="conv-empty">هنوز ضریبی برای این متریال ثبت نشده است.</div>
|
||||||
|
) : (
|
||||||
|
rows.map((r) => (
|
||||||
|
<div key={r.id}>
|
||||||
|
<div className="cg-head">
|
||||||
|
{unitDisplay(r.unit) || `واحد #${r.unit_id}`} ← {ref}
|
||||||
|
</div>
|
||||||
|
<div className="conv-row">
|
||||||
|
<span className="cv-brand">{brandNameFor(r) || "همه برندها"}</span>
|
||||||
|
<span className="cv-factor">{faNum(r.conversion_factor)}</span>
|
||||||
|
<span className="cv-arrow">×</span>
|
||||||
|
<span className="cv-unit">{ref}</span>
|
||||||
|
<span className="conv-actions">
|
||||||
|
<button type="button" title="ویرایش" onClick={() => startEdit(r)}>
|
||||||
|
<Pencil className="h-3.5 w-3.5" />
|
||||||
|
</button>
|
||||||
|
<button type="button" title="حذف" onClick={() => void deleteMu(r)}>
|
||||||
|
<Trash2 className="h-3.5 w-3.5" />
|
||||||
|
</button>
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
))
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* فرم افزودن ضریب */}
|
||||||
|
<div className="add-conv">
|
||||||
|
<h4 className="mb-2 text-[13.5px] font-bold">
|
||||||
|
{editingId ? (
|
||||||
|
<>
|
||||||
|
<Pencil className="me-1 inline h-3.5 w-3.5" /> ویرایش ضریب تبدیل
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<Plus className="me-1 inline h-3.5 w-3.5" /> افزودن ضریب تبدیل
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</h4>
|
||||||
|
<div className="grid grid-cols-1 gap-2 sm:grid-cols-[1.2fr_0.6fr_1fr_0.8fr_auto] sm:items-end">
|
||||||
|
<div className="field">
|
||||||
|
<label>واحد پیشنهادشده</label>
|
||||||
|
<Combobox
|
||||||
|
value={formUnit}
|
||||||
|
onChange={(it) => setFormUnit(it.label)}
|
||||||
|
items={units.map((u) => unitDisplay(u)).filter(Boolean)}
|
||||||
|
allowAdd
|
||||||
|
addSuffix="به عنوان واحد جدید"
|
||||||
|
placeholder="مثلاً حلقه"
|
||||||
|
onInputChange={setFormUnit}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="field">
|
||||||
|
<label>ضریب</label>
|
||||||
|
<NumberInput
|
||||||
|
value={factorNum()}
|
||||||
|
onChange={(n) => setFormFactor(n != null ? String(n) : "")}
|
||||||
|
placeholder="مثلاً 0.98"
|
||||||
|
inputMode="decimal"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="field">
|
||||||
|
<label>برند (خالی = همه برندها)</label>
|
||||||
|
<Combobox
|
||||||
|
value={formBrand}
|
||||||
|
onChange={(it) => setFormBrand(it.label)}
|
||||||
|
items={allBrands}
|
||||||
|
allowAdd
|
||||||
|
disabled={!!editingId}
|
||||||
|
addSuffix="به عنوان برند جدید"
|
||||||
|
placeholder="مثلاً راجین"
|
||||||
|
onInputChange={setFormBrand}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="field">
|
||||||
|
<label>به واحد (مرجع)</label>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
className="h-9 w-full rounded-lg border border-line bg-slate-bg px-3 text-sm text-muted"
|
||||||
|
value={ref || "مرجع"}
|
||||||
|
placeholder="مرجع"
|
||||||
|
readOnly
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-1.5">
|
||||||
|
<Button size="sm" onClick={() => void saveConv()}>
|
||||||
|
{editingId ? "ذخیره تغییرات" : "افزودن"}
|
||||||
|
</Button>
|
||||||
|
{editingId && (
|
||||||
|
<Button
|
||||||
|
size="sm"
|
||||||
|
variant="slate"
|
||||||
|
onClick={() => {
|
||||||
|
setEditingId(null);
|
||||||
|
setFormUnit("");
|
||||||
|
setFormFactor("");
|
||||||
|
setFormBrand("");
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
انصراف
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="conv-live">{convLive}</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
</section>
|
</section>
|
||||||
|
|||||||
@@ -14,6 +14,8 @@ export interface Step4Props {
|
|||||||
onAssign: (tempId: string, proj: string) => void;
|
onAssign: (tempId: string, proj: string) => void;
|
||||||
onUnassign: (tempId: string, proj: string) => void;
|
onUnassign: (tempId: string, proj: string) => void;
|
||||||
onAddProject: (name: string) => void;
|
onAddProject: (name: string) => void;
|
||||||
|
/** سطح limited تدارکات: افزودن پروژه جدید ممنوع */
|
||||||
|
canAddProject?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
const ALL_KEY = "__all__";
|
const ALL_KEY = "__all__";
|
||||||
@@ -111,7 +113,7 @@ function DroppableProject({
|
|||||||
}
|
}
|
||||||
|
|
||||||
// مرحله ۴ — تخصیص پروژهها با درگاندروپ (یا کلیک-قلم بعد کلیک-پروژه)
|
// مرحله ۴ — تخصیص پروژهها با درگاندروپ (یا کلیک-قلم بعد کلیک-پروژه)
|
||||||
export function Step4Projects({ items, projects, assignment, onAssign, onUnassign, onAddProject }: Step4Props) {
|
export function Step4Projects({ items, projects, assignment, onAssign, onUnassign, onAddProject, canAddProject = true }: Step4Props) {
|
||||||
const [picked, setPicked] = useState<string | null>(null);
|
const [picked, setPicked] = useState<string | null>(null);
|
||||||
const [newProj, setNewProj] = useState("");
|
const [newProj, setNewProj] = useState("");
|
||||||
|
|
||||||
@@ -211,10 +213,14 @@ export function Step4Projects({ items, projects, assignment, onAssign, onUnassig
|
|||||||
/>
|
/>
|
||||||
))}
|
))}
|
||||||
{!projects.length && (
|
{!projects.length && (
|
||||||
<div className="dd-empty">هنوز پروژهای تعریف نشده است — از پایین یک پروژه اضافه کنید.</div>
|
<div className="dd-empty">
|
||||||
|
{canAddProject
|
||||||
|
? "هنوز پروژهای تعریف نشده است — از پایین یک پروژه اضافه کنید."
|
||||||
|
: "هنوز پروژهای به شما تخصیص داده نشده است — با مدیر سیستم تماس بگیرید."}
|
||||||
|
</div>
|
||||||
)}
|
)}
|
||||||
{/* افزودن پروژه بهصورت درجا — زیر لیست پروژهها */}
|
{/* افزودن پروژه بهصورت درجا — زیر لیست پروژهها (سطح limited: ممنوع) */}
|
||||||
<div className="mt-3 rounded-md border border-dashed border-line p-2">
|
<div className="mt-3 rounded-md border border-dashed border-line p-2" hidden={!canAddProject}>
|
||||||
<div className="mb-1.5 text-[11.5px] font-semibold text-muted">افزودن پروژهی جدید:</div>
|
<div className="mb-1.5 text-[11.5px] font-semibold text-muted">افزودن پروژهی جدید:</div>
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
<input
|
<input
|
||||||
|
|||||||
@@ -22,6 +22,7 @@ import { normalize } from "../../lib/normalize";
|
|||||||
import { faNum } from "../../lib/formatters";
|
import { faNum } from "../../lib/formatters";
|
||||||
import { matchMaterial } from "../../lib/quoteUtils";
|
import { matchMaterial } from "../../lib/quoteUtils";
|
||||||
import { Header, PageLayout } from "../../components/layout/Header";
|
import { Header, PageLayout } from "../../components/layout/Header";
|
||||||
|
import { AppSwitcherMenu } from "../../components/AppSwitcherMenu";
|
||||||
import { Stepper } from "./Stepper";
|
import { Stepper } from "./Stepper";
|
||||||
import { Step1TopicSupplier } from "./Step1TopicSupplier";
|
import { Step1TopicSupplier } from "./Step1TopicSupplier";
|
||||||
import { Step2LineItems, type ItemDraft, type MaterialRec } from "./Step2LineItems";
|
import { Step2LineItems, type ItemDraft, type MaterialRec } from "./Step2LineItems";
|
||||||
@@ -36,6 +37,7 @@ import {
|
|||||||
DialogHeader,
|
DialogHeader,
|
||||||
DialogTitle,
|
DialogTitle,
|
||||||
} from "../../components/ui/dialog";
|
} from "../../components/ui/dialog";
|
||||||
|
import { useAuthStore } from "../../store/auth";
|
||||||
|
|
||||||
const TOTAL_STEPS = 5;
|
const TOTAL_STEPS = 5;
|
||||||
|
|
||||||
@@ -149,6 +151,23 @@ export function WizardPage({ isStandalone = false }: { isStandalone?: boolean })
|
|||||||
const suppliers = useSuppliers();
|
const suppliers = useSuppliers();
|
||||||
const materials = useMaterials();
|
const materials = useMaterials();
|
||||||
const projects = useProjects();
|
const projects = useProjects();
|
||||||
|
// سطح limited تدارکات: استعلام فقط برای پروژههای عضویت — بدون افزودن پروژه جدید
|
||||||
|
const user = useAuthStore((s) => s.user);
|
||||||
|
const isLimitedProcurement =
|
||||||
|
user?.panels?.procurement === "limited" && user?.role !== "admin";
|
||||||
|
const memberProjectNames = useMemo(() => {
|
||||||
|
const allowedIds = new Set([
|
||||||
|
...(user?.member_project_ids ?? []),
|
||||||
|
...(user?.projects ?? []).map((p) => p.id),
|
||||||
|
...(user?.project_id ? [user.project_id] : []),
|
||||||
|
]);
|
||||||
|
const matched = projects
|
||||||
|
.filter((p) => allowedIds.has(p.id))
|
||||||
|
.map((p) => p.name);
|
||||||
|
const directNames = (user?.projects ?? []).map((p) => p.name);
|
||||||
|
if (user?.project_name) directNames.push(user.project_name);
|
||||||
|
return [...new Set([...matched, ...directNames])];
|
||||||
|
}, [projects, user]);
|
||||||
const topics = useAppStore((s) => s.topics);
|
const topics = useAppStore((s) => s.topics);
|
||||||
const createQuote = useCreateQuote();
|
const createQuote = useCreateQuote();
|
||||||
const addSupplier = useAddSupplier();
|
const addSupplier = useAddSupplier();
|
||||||
@@ -297,12 +316,12 @@ export function WizardPage({ isStandalone = false }: { isStandalone?: boolean })
|
|||||||
[suppliers, materials, topics, items],
|
[suppliers, materials, topics, items],
|
||||||
);
|
);
|
||||||
|
|
||||||
// ---------- prefill از لینکها (?topic=&supplier=) ----------
|
// ---------- prefill از لینکها (?topic=&supplier=&project=) ----------
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const t = params.get("topic");
|
const t = params.get("topic");
|
||||||
if (!t) return;
|
if (t) {
|
||||||
const topic = topicByName(t, topics);
|
const topic = topicByName(t, topics);
|
||||||
if (!topic) return;
|
if (topic) {
|
||||||
setSelectedTopic(topic.name);
|
setSelectedTopic(topic.name);
|
||||||
const sid = params.get("supplier");
|
const sid = params.get("supplier");
|
||||||
if (sid) {
|
if (sid) {
|
||||||
@@ -312,7 +331,22 @@ export function WizardPage({ isStandalone = false }: { isStandalone?: boolean })
|
|||||||
setSupplierInvalid(false);
|
setSupplierInvalid(false);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}, [params, suppliers, topics]);
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const proj = params.get("project");
|
||||||
|
if (proj) {
|
||||||
|
setAssignment((cur) => {
|
||||||
|
const next = { ...cur };
|
||||||
|
for (const it of items) {
|
||||||
|
if (!next[it.tempId]?.length) {
|
||||||
|
next[it.tempId] = [proj];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return next;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}, [params, suppliers, topics, items]);
|
||||||
|
|
||||||
// ---------- بارگذاری اولیه پیشنویس ربات بله (?token= یا ?draft=) ----------
|
// ---------- بارگذاری اولیه پیشنویس ربات بله (?token= یا ?draft=) ----------
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -504,13 +538,34 @@ export function WizardPage({ isStandalone = false }: { isStandalone?: boolean })
|
|||||||
|
|
||||||
// ---------- پروژهها ----------
|
// ---------- پروژهها ----------
|
||||||
const projectNames = useMemo(() => {
|
const projectNames = useMemo(() => {
|
||||||
|
if (isLimitedProcurement) {
|
||||||
|
return memberProjectNames;
|
||||||
|
}
|
||||||
const names = new Set<string>(projects.map((p) => p.name));
|
const names = new Set<string>(projects.map((p) => p.name));
|
||||||
quotes.forEach((q) => {
|
quotes.forEach((q) => {
|
||||||
if (q.project) names.add(q.project);
|
if (q.project) names.add(q.project);
|
||||||
(q.projects || []).forEach((n) => names.add(n));
|
(q.projects || []).forEach((n) => names.add(n));
|
||||||
});
|
});
|
||||||
return [...names];
|
return [...names];
|
||||||
}, [projects, quotes]);
|
}, [projects, quotes, isLimitedProcurement, memberProjectNames]);
|
||||||
|
|
||||||
|
// سطح محدود: در صورت داشتن یک پروژه، خودکار اقلام به آن پروژه تخصیص مییابند
|
||||||
|
useEffect(() => {
|
||||||
|
if (isLimitedProcurement && memberProjectNames.length === 1) {
|
||||||
|
const sole = memberProjectNames[0];
|
||||||
|
setAssignment((cur) => {
|
||||||
|
let changed = false;
|
||||||
|
const next = { ...cur };
|
||||||
|
for (const it of items) {
|
||||||
|
if (!next[it.tempId]?.length) {
|
||||||
|
next[it.tempId] = [sole];
|
||||||
|
changed = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return changed ? next : cur;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}, [isLimitedProcurement, memberProjectNames, items]);
|
||||||
|
|
||||||
const assign = (tempId: string, proj: string) => {
|
const assign = (tempId: string, proj: string) => {
|
||||||
setAssignment((a) => {
|
setAssignment((a) => {
|
||||||
@@ -882,8 +937,9 @@ export function WizardPage({ isStandalone = false }: { isStandalone?: boolean })
|
|||||||
<Header
|
<Header
|
||||||
title="افزودن پیشنهاد جدید"
|
title="افزودن پیشنهاد جدید"
|
||||||
sub="اطلاعات را از تماس با تأمینکننده وارد کنید"
|
sub="اطلاعات را از تماس با تأمینکننده وارد کنید"
|
||||||
backTo="/"
|
backTo={isLimitedProcurement ? "/requester" : "/"}
|
||||||
backLabel="بازگشت به دفتر"
|
backLabel={isLimitedProcurement ? "بازگشت به استعلامها" : "بازگشت به دفتر"}
|
||||||
|
menu={<AppSwitcherMenu activeModule="procurement" />}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
<PageLayout>
|
<PageLayout>
|
||||||
@@ -950,6 +1006,7 @@ export function WizardPage({ isStandalone = false }: { isStandalone?: boolean })
|
|||||||
assignment={assignment}
|
assignment={assignment}
|
||||||
onAssign={assign}
|
onAssign={assign}
|
||||||
onUnassign={unassign}
|
onUnassign={unassign}
|
||||||
|
canAddProject={!isLimitedProcurement}
|
||||||
onAddProject={(name) => {
|
onAddProject={(name) => {
|
||||||
void addProject.mutateAsync({ id: nextId("p", projects), name });
|
void addProject.mutateAsync({ id: nextId("p", projects), name });
|
||||||
}}
|
}}
|
||||||
|
|||||||
@@ -11,11 +11,15 @@ import { persist } from "zustand/middleware";
|
|||||||
export interface AuthUser {
|
export interface AuthUser {
|
||||||
id: string;
|
id: string;
|
||||||
casdoor_id: string;
|
casdoor_id: string;
|
||||||
|
username?: string;
|
||||||
first_name: string;
|
first_name: string;
|
||||||
last_name: string;
|
last_name: string;
|
||||||
phone: string | null;
|
phone: string | null;
|
||||||
role: "pm" | "procurement_manager" | "admin" | null;
|
role: "pm" | "procurement_manager" | "admin" | "supervisor" | null;
|
||||||
role_label: string | null;
|
role_label: string | null;
|
||||||
|
// لایه پنلها (جایگزین نقشها)
|
||||||
|
panels?: Record<string, string>;
|
||||||
|
member_project_ids?: string[];
|
||||||
project_id: string | null; // پروژهی فعال (PM) — با سوییچر عوض میشود
|
project_id: string | null; // پروژهی فعال (PM) — با سوییچر عوض میشود
|
||||||
project_name: string | null;
|
project_name: string | null;
|
||||||
projects?: { id: string; name: string }[]; // همهی پروژههای تخصیصیافته (1:N)
|
projects?: { id: string; name: string }[]; // همهی پروژههای تخصیصیافته (1:N)
|
||||||
|
|||||||
@@ -41,6 +41,7 @@ interface AppStore {
|
|||||||
deleteSupplier: (id: string) => void;
|
deleteSupplier: (id: string) => void;
|
||||||
addMaterial: (m: Material) => void;
|
addMaterial: (m: Material) => void;
|
||||||
addProject: (p: Project) => void;
|
addProject: (p: Project) => void;
|
||||||
|
deleteProject: (id: string) => void;
|
||||||
setStandardConversion: (sc: StandardConversion) => void;
|
setStandardConversion: (sc: StandardConversion) => void;
|
||||||
deleteStandardConversion: (id: string) => void;
|
deleteStandardConversion: (id: string) => void;
|
||||||
|
|
||||||
@@ -85,6 +86,7 @@ export const useAppStore = create<AppStore>()((set) => ({
|
|||||||
deleteSupplier: (id) => set((s) => ({ suppliers: s.suppliers.filter((x) => x.id !== id) })),
|
deleteSupplier: (id) => set((s) => ({ suppliers: s.suppliers.filter((x) => x.id !== id) })),
|
||||||
addMaterial: (m) => set((s) => ({ materials: [...s.materials, m] })),
|
addMaterial: (m) => set((s) => ({ materials: [...s.materials, m] })),
|
||||||
addProject: (p) => set((s) => ({ projects: [...s.projects, p] })),
|
addProject: (p) => set((s) => ({ projects: [...s.projects, p] })),
|
||||||
|
deleteProject: (id) => set((s) => ({ projects: s.projects.filter((p) => p.id !== id) })),
|
||||||
setStandardConversion: (sc) =>
|
setStandardConversion: (sc) =>
|
||||||
set((s) => {
|
set((s) => {
|
||||||
const idx = s.standardConversions.findIndex((x) => x.id === sc.id);
|
const idx = s.standardConversions.findIndex((x) => x.id === sc.id);
|
||||||
|
|||||||
@@ -786,3 +786,12 @@ button:disabled {
|
|||||||
padding: 0.45rem;
|
padding: 0.45rem;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* اسکرول افقی بدون نوار اسکرول (چیپهای لمسی موبایل) */
|
||||||
|
.no-scrollbar {
|
||||||
|
-ms-overflow-style: none;
|
||||||
|
scrollbar-width: none;
|
||||||
|
}
|
||||||
|
.no-scrollbar::-webkit-scrollbar {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,10 +1,11 @@
|
|||||||
{
|
{
|
||||||
"compilerOptions": {
|
"compilerOptions": {
|
||||||
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
|
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
|
||||||
"target": "es2023",
|
"target": "ESNext",
|
||||||
"lib": ["ES2023", "DOM"],
|
"lib": ["ESNext", "DOM"],
|
||||||
"module": "esnext",
|
"module": "esnext",
|
||||||
"types": ["vite/client"],
|
"types": ["vite/client"],
|
||||||
|
"strict": true,
|
||||||
"allowArbitraryExtensions": true,
|
"allowArbitraryExtensions": true,
|
||||||
"skipLibCheck": true,
|
"skipLibCheck": true,
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,19 @@
|
|||||||
|
# PM — Construction Project Management Platform
|
||||||
|
# Copy to .env and customize as needed (never commit .env)
|
||||||
|
|
||||||
|
# Database credentials
|
||||||
|
PM_DB_PASSWORD=pm_secret_2026
|
||||||
|
|
||||||
|
# Session secret (random 32+ bytes hex string)
|
||||||
|
PM_SESSION_SECRET=change-me-32-bytes-hex
|
||||||
|
|
||||||
|
# Initial admin account
|
||||||
|
PM_ADMIN_USER=admin
|
||||||
|
PM_ADMIN_PASSWORD=pm123456
|
||||||
|
|
||||||
|
# ERP service account (Casdoor org `inventory` - for materials/warehouse integration)
|
||||||
|
PM_ERP_CASDOOR_CLIENT_ID=inventory-app-client
|
||||||
|
PM_ERP_CASDOOR_CLIENT_SECRET=inventory-app-secret-2026
|
||||||
|
PM_ERP_SERVICE_USERNAME=pm-service
|
||||||
|
PM_ERP_SERVICE_PASSWORD=pm-service-2026
|
||||||
|
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
# Normalize line endings to LF (mirrors the ERP repo convention)
|
||||||
|
* text=auto eol=lf
|
||||||
|
|
||||||
|
*.png binary
|
||||||
|
*.jpg binary
|
||||||
|
*.webp binary
|
||||||
|
*.ico binary
|
||||||
|
*.dump binary
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
# secrets & local state — never commit
|
||||||
|
.env
|
||||||
|
.env.local
|
||||||
|
|
||||||
|
# python
|
||||||
|
__pycache__/
|
||||||
|
*.pyc
|
||||||
|
.venv/
|
||||||
|
venv/
|
||||||
|
|
||||||
|
# node
|
||||||
|
node_modules/
|
||||||
|
dist/
|
||||||
|
*.local
|
||||||
|
|
||||||
|
# editor / OS
|
||||||
|
.vscode/
|
||||||
|
.idea/
|
||||||
|
Thumbs.db
|
||||||
|
.DS_Store
|
||||||
|
|
||||||
|
# uploaded defect photos (runtime volume)
|
||||||
|
files/
|
||||||
@@ -0,0 +1,102 @@
|
|||||||
|
# PM API Contract (v3) — Standalone Native Platform — پایه: /api/v1
|
||||||
|
|
||||||
|
پلتفرم مدیریت پروژه ساختمانی بومی (Standalone)، مستقل و بدون وابستگی به هیچ سیستم خارجی.
|
||||||
|
|
||||||
|
## Auth
|
||||||
|
- `POST /auth/login` `{username, password}` → `{data:{token, user:{id, username, display_name, role}}}`
|
||||||
|
- `GET /auth/dev-roles` (در حالت توسعه) → لیست نقشهای آماده جهت ورود سریع
|
||||||
|
- `POST /auth/dev-login` `{role}` (در حالت توسعه) → دریافت سریع توکن نقش انتخابی
|
||||||
|
- همه endpointها (جز لاگین و فایلهای عمومی) هدر `Authorization: Bearer <token>` میخواهند.
|
||||||
|
- خطاها: `{"error": {"code", "message", "field"?}}` — کدها: `VALIDATION_ERROR` (400)،
|
||||||
|
`UNAUTHORIZED` (401)، `FORBIDDEN` (403)، `NOT_FOUND` (404)، `CONFLICT` (409)،
|
||||||
|
`UPSTREAM_UNAVAILABLE` (503).
|
||||||
|
|
||||||
|
## تاریخ جلالی
|
||||||
|
- **همه تاریخهای قابل مشاهده در UI شمسیاند.** API هم ISO میپذیرد/میدهد و هم شمسی.
|
||||||
|
- هر تسک علاوه بر `start_date`/`due_date` (ISO) فیلدهای `start_date_jalali`/
|
||||||
|
`due_date_jalali` را هم برمیگرداند («1405/06/23»).
|
||||||
|
- `PATCH /tasks/{id}/dates` هر دو قالب را میپذیرد: `1405/06/23` یا `2026-09-14`
|
||||||
|
(سال ≥ 1700 میلادی، کمتر از آن شمسی تفسیر میشود). روز نامعتبر → 400.
|
||||||
|
- تبدیلها در `backend/app/utils/jalali.py` و `frontend/src/lib/jalali.ts` انجام میشوند.
|
||||||
|
|
||||||
|
## Dashboard
|
||||||
|
- `GET /dashboard/today` → `{data:{summary:{problems,warnings,ok}, sections:{overdue,due_today,awaiting_qc,failed_qc,blocked,upcoming}}}`
|
||||||
|
- `awaiting_qc` = وضعیتهای `pre_qc_pending|exec_qc_pending|ready`
|
||||||
|
- `failed_qc` = وضعیتهای `pre_qc_failed|qc_failed_rework`
|
||||||
|
|
||||||
|
## Projects
|
||||||
|
- `GET /projects` → `[...{id, name, identifier, description, active, erp_project_id, created_at, stats:{total, awaiting_qc, failed_qc, overdue}}]`
|
||||||
|
- `POST /projects` → ساخت پروژه جدید
|
||||||
|
- `GET /projects/{id}` → جزئیات پروژه به همراه آمارهای تسکها
|
||||||
|
- `PUT /projects/{id}` | `DELETE /projects/{id}`
|
||||||
|
- `GET /projects/{id}/gantt` → دادههای گانت چارت پروژه
|
||||||
|
- `PATCH /projects/{id}/erp-mapping {erp_project_id}`
|
||||||
|
|
||||||
|
## Tasks
|
||||||
|
- `GET /tasks?project_id=&search=&qc_status=&status=&page=&page_size=`
|
||||||
|
- `POST /tasks` → ثبت فعالیت/تسک جدید
|
||||||
|
- `GET /tasks/{id}` → تسک + `relations` + `children` + **`qc`** + **`qc_definitions`** + `defects` + `open_defects`
|
||||||
|
- `PUT /tasks/{id}` → ویرایش اطلاعات تسک
|
||||||
|
- `DELETE /tasks/{id}` → حذف تسک
|
||||||
|
- `PATCH /tasks/{id}/progress {percentage: 0..100}`
|
||||||
|
- **قاعده ۱:** اگر `percentage > 0` و بازرسی پیش از اجرا تأیید نشده باشد → 400
|
||||||
|
«بازرسی پیش از اجرا تأیید نشده است (N سؤال باقیمانده)»
|
||||||
|
- **قاعده ۲:** اگر `percentage >= 100` و هر سؤال الزامی تأییدنشده/مردود باشد → 400
|
||||||
|
«تا زمانی که همه بازرسیهای الزامی تأیید نشوند پیشرفت ۱۰۰٪ مجاز نیست (…)»
|
||||||
|
- `PATCH /tasks/{id}/dates {start_date?, due_date?}` (ISO یا شمسی)
|
||||||
|
- `POST /tasks/relations` | `DELETE /tasks/relations/{id}` → مدیریت روابط وابستگی تسکها (FS, SS, FF, SF)
|
||||||
|
|
||||||
|
### شکل بلوک `qc` در جزئیات تسک
|
||||||
|
```json
|
||||||
|
{"pre": {"total":3,"passed":3,"failed":0,"pending":0,"na":0,"required_unresolved":0,"status":"passed"},
|
||||||
|
"exec": {"total":6,"passed":2,"failed":1,"pending":3,"na":0,"required_unresolved":4,"status":"pending"},
|
||||||
|
"all": { /* مجموع */ },
|
||||||
|
"status": "exec_qc_pending",
|
||||||
|
"can_start": true, "can_complete": false,
|
||||||
|
"block_reasons": ["تا زمانی که همه بازرسیهای الزامی تأیید نشوند پیشرفت ۱۰۰٪ مجاز نیست (۴ سؤال باقیمانده، ۱ مورد مردود)"]}
|
||||||
|
```
|
||||||
|
|
||||||
|
### وضعیتهای `qc_status` روی تسک
|
||||||
|
`none` · `pre_qc_pending` · `pre_qc_failed` · `ready` · `exec_qc_pending` ·
|
||||||
|
`in_progress` · `qc_failed_rework` · `final_passed`
|
||||||
|
|
||||||
|
## QC — تعریف (Definition)
|
||||||
|
### قالبهای سراسری (قابل استفاده مجدد)
|
||||||
|
- `GET /qc/templates` → `[{id,name,activity_type,description,questions:[{id,phase,text,sort_order,required}]}]`
|
||||||
|
- `POST /qc/templates {name, activity_type?, description?, questions?:[…]}` → `{data:{id}}`
|
||||||
|
- `PATCH /qc/templates/{id} {name?,activity_type?,description?}`
|
||||||
|
- `DELETE /qc/templates/{id}`
|
||||||
|
- `POST /qc/templates/{id}/questions {phase,text,required?,sort_order?}`
|
||||||
|
- `PATCH /qc/questions/{qid} {text?,phase?,required?,sort_order?}`
|
||||||
|
- `DELETE /qc/questions/{qid}`
|
||||||
|
- `PUT /qc/templates/{id}/questions {questions:[…]}` — جایگزینی گروهی (برای ادیتور)
|
||||||
|
|
||||||
|
`phase` ∈ `"pre"` (پیش از اجرا) · `"during"` (هنگام اجرا) · `"after"` (پس از اجرا)
|
||||||
|
|
||||||
|
### تعریف مخصوص تسک (کپی مستقل — ویرایش آن قالب سراسری را تغییر نمیدهد)
|
||||||
|
- `GET /qc/tasks/{task_id}` → `{data:{task, definitions:[{id,name,source_template_id,created_at,questions:[{…,result,history_count}],summary}], readiness}}`
|
||||||
|
- `POST /qc/tasks/{task_id}/definition {name?, template_id?}` → **کپی عمیق** سؤالات قالب
|
||||||
|
- `PATCH /qc/definitions/{id} {name}` | `DELETE /qc/definitions/{id}`
|
||||||
|
- `POST /qc/definitions/{id}/questions {text,phase,required?,sort_order?}`
|
||||||
|
- `PATCH /qc/task-questions/{qid} {text?,phase?,required?,sort_order?}`
|
||||||
|
- `DELETE /qc/task-questions/{qid}`
|
||||||
|
|
||||||
|
## QC — اجرا (Execution)
|
||||||
|
- `PUT /qc/task-questions/{qid}/result {answer:"pass"|"fail"|"na", comment?}`
|
||||||
|
→ `{data:{question_id, answer, task_qc_status, readiness}}`
|
||||||
|
- پاسخها **append-only** هستند (تاریخچه میماند؛ بازرسی مجدد پس از رفع عیب ممکن است)
|
||||||
|
- تعریف و اجرا کاملاً جدا هستند: هنگام ساخت/کپی سؤال هیچ پاس/ردی ثبت نمیشود.
|
||||||
|
- عیبها:
|
||||||
|
- `POST /qc/defects {task_id, question_id?, title, description?, severity?, corrective_action?, photo_id?}`
|
||||||
|
- `POST /qc/defects/{id}/resolve {resolution_notes?}`
|
||||||
|
- عکس عیب: `POST /files` (multipart) → `{data:{id, url}}` سپس `photo_id`
|
||||||
|
|
||||||
|
## فایلها
|
||||||
|
- `POST /files` multipart (jpg/png/webp تا ۱۰MB) → `{data:{id,url,filename}}`
|
||||||
|
- `GET /files/{id}`
|
||||||
|
|
||||||
|
## Materials / Resources (یکپارچگی ERP)
|
||||||
|
- `GET/POST /tasks/{task_id}/materials` · `PATCH/DELETE /materials/{req_id}`
|
||||||
|
- `GET /erp/materials?search=` · `GET /erp/projects`
|
||||||
|
- `POST /materials/{req_id}/reserve|purchase-request` · `GET /reservations` · `POST /reservations/{id}/release`
|
||||||
|
- `GET/PATCH /purchase-requests` · `POST /projects/{project_id}/erp-mapping`
|
||||||
@@ -0,0 +1,174 @@
|
|||||||
|
# راهنمای جامع معماری و مدل داده پایگاهداده سیستم مدیریت پروژه عمرانی (Construction PM)
|
||||||
|
|
||||||
|
> **دستورالعمل برای هوش مصنوعی (AI Prompt / Context):**
|
||||||
|
> این سند، مشخصات دقیق معماری، موجودیتها (Entities)، فیلدها، روابط و قواعد تجاری یک سیستم بومی مدیریت پروژه عمرانی (Construction Project Management) است.
|
||||||
|
> لطفاً این راهنما را مطالعه کرده و بر اساس آن، ساختار سیستم، نحوه ذخیرهسازی دادهها، جریان کار (Workflow) و روابط میان جداول را برای کاربر تحلیل و تشریح نما.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## ۱. نمای کلی سیستم و فناوریها (Architecture Overview)
|
||||||
|
|
||||||
|
- **ماهیت سامانه:** پلتفرم یکپارچه و بومی مدیریت پروژههای عمرانی و ساختمانی (Native Construction PM Platform).
|
||||||
|
- **لایههای نرمافزاری:**
|
||||||
|
- **فرانتاند:** React + TypeScript + TailwindCSS + TanStack Query (رابط کاربری مدرن با پشتیبانی تقویم شمسی و نمودار گانت تعاملی).
|
||||||
|
- **بکاند:** Python 3.10+ با فریمورک FastAPI و SQLAlchemy 2.0 (Async ORM با درایور aiosqlite / asyncpg).
|
||||||
|
- **پایگاهداده:** SQLite / PostgreSQL با ساختار کاملاً رابطهای (Relational) و فیلدهای ساختیافته JSON.
|
||||||
|
- **شناسههای یکتا (Primary Keys):** تمامی جداول از کلیدهای اصلی ۱۰۰٪ بومی از نوع `UUID v4` استفاده میکنند. هیچگونه شناسه یا وابستگی به سیستمهای قدیمی (Legacy) وجود ندارد.
|
||||||
|
- **منطق تاریخها:** تاریخها در پایگاهداده به صورت استاندارد میلادی (`Date` و `DateTime`) ذخیره میشوند و تبدیلهای شمسی بهصورت لایهای و لحظهای برای نمایش به کاربر انجام میگیرد.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## ۲. نمودار رابطه موجودیتها (ERD)
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
erDiagram
|
||||||
|
PROJECTS ||--o{ TASKS : "شامل میشود (1:N)"
|
||||||
|
PROJECTS ||--o{ PROJECT_MEMBERS : "تخصیص اعضا (1:N)"
|
||||||
|
PM_USERS ||--o{ PROJECT_MEMBERS : "عضویت کاربر (1:N)"
|
||||||
|
PM_USERS ||--o{ PROJECT_ASSIGNMENTS : "دسترسی پروژه (1:N)"
|
||||||
|
PROJECTS ||--o{ PROJECT_ASSIGNMENTS : "محدوده دسترسی (1:N)"
|
||||||
|
PM_USERS ||--o{ TASKS : "مسئول وظیفه (Assignee)"
|
||||||
|
|
||||||
|
TASKS ||--o{ TASKS : "ساختار درختی WBS (والد/فرزند)"
|
||||||
|
TASKS ||--o{ TASK_RELATIONS : "وظیفه پیشنیاز (from_task)"
|
||||||
|
TASKS ||--o{ TASK_RELATIONS : "وظیفه پسنیاز (to_task)"
|
||||||
|
PROJECTS ||--o{ TASK_RELATIONS : "روابط گانت پروژه"
|
||||||
|
|
||||||
|
TASKS ||--o{ TASK_QC_DEFINITIONS : "چکلیستهای کنترلی"
|
||||||
|
TASK_QC_DEFINITIONS ||--o{ TASK_QC_QUESTIONS : "آیتمهای کنترلی"
|
||||||
|
TASK_QC_QUESTIONS ||--o{ TASK_QC_RESULTS : "تاریخچه بازرسیها"
|
||||||
|
|
||||||
|
TASKS ||--o{ DEFECTS : "عیوب و عدم انطباقها"
|
||||||
|
TASK_QC_QUESTIONS ||--o{ DEFECTS : "علت ریشهای عیب (اختیاری)"
|
||||||
|
|
||||||
|
QC_TEMPLATES ||--o{ QC_QUESTIONS : "قالبهای عمومی بازرسی"
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## ۳. شرح تفصیلی جداول و موجودیتها (Data Dictionary)
|
||||||
|
|
||||||
|
### ۱. جدول پروژهها (`projects`)
|
||||||
|
موجودیت ریشه سامانه که اطلاعات اصلی کارگاههای عمرانی را نگهداری میکند.
|
||||||
|
|
||||||
|
| نام فیلد | نوع داده | کلید / ایندکس | توضیحات |
|
||||||
|
|---|---|---|---|
|
||||||
|
| `id` | `UUID` | **PK** | شناسه یکتای پروژه |
|
||||||
|
| `name` | `VARCHAR(255)` | Index | نام پروژه (مانند «پروژه برج بهارستان») |
|
||||||
|
| `description` | `TEXT` | - | شرح پروژه، الزامات و مشخصات فنی |
|
||||||
|
| `location` | `VARCHAR(255)` | - | موقعیت جغرافیایی / نشانی کارگاه |
|
||||||
|
| `project_manager` | `VARCHAR(255)` | - | نام مدیر یا سرپرست کارگاه |
|
||||||
|
| `status` | `VARCHAR(32)` | Index | وضعیت: `PLANNED`, `ACTIVE`, `ON_HOLD`, `COMPLETED`, `CANCELLED` |
|
||||||
|
| `planned_start` | `DATE` | - | تاریخ شروع مصوب (محاسبه و تجمیع خودکار از کمترین تاریخ شروع تسکها) |
|
||||||
|
| `planned_end` | `DATE` | - | تاریخ پایان مصوب (محاسبه و تجمیع خودکار از بیشترین تاریخ پایان تسکها) |
|
||||||
|
| `actual_start` | `DATE` | - | تاریخ شروع واقعی (محاسبه خودکار از زمان آغاز اولین تسک) |
|
||||||
|
| `actual_end` | `DATE` | - | تاریخ پایان واقعی (محاسبه خودکار با اتمام ۱۰۰٪ تمام تسکها) |
|
||||||
|
| `progress` | `FLOAT` | - | درصد پیشرفت فیزیکی پروژه (میانگین وزنی درصد پیشرفت تسکها از ۰ تا ۱۰۰) |
|
||||||
|
| `created_at` | `TIMESTAMP` | - | زمان ثبت رکورد |
|
||||||
|
| `updated_at` | `TIMESTAMP` | - | زمان آخرین ویرایش رکورد |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### ۲. جدول وظایف و فعالیتها (`tasks`)
|
||||||
|
اصلیترین موجودیت سامانه برای ساختار شکست کار (WBS)، گانت، تخصیص منابع و کنترل کیفی.
|
||||||
|
|
||||||
|
| نام فیلد | نوع داده | کلید / ایندکس | توضیحات |
|
||||||
|
|---|---|---|---|
|
||||||
|
| `id` | `UUID` | **PK** | شناسه یکتای وظیفه |
|
||||||
|
| `project_id` | `UUID` | **FK** -> `projects.id` | پروژهای که وظیفه به آن تعلق دارد (Cascade Delete) |
|
||||||
|
| `parent_id` | `UUID` (Nullable) | **FK** -> `tasks.id` | والد در ساختار درختی WBS با عمق نامحدود (فاز ➔ فعالیت ➔ زیرتسک) |
|
||||||
|
| `title` | `VARCHAR(512)` | - | عنوان وظیفه (مانند «بتنریزی سقف طبقه ۲») |
|
||||||
|
| `description` | `TEXT` | - | مشخصات و الزامات کار |
|
||||||
|
| `status` | `VARCHAR(32)` | Index | وضعیت: `TODO`, `IN_PROGRESS`, `BLOCKED`, `COMPLETED`, `CANCELLED` |
|
||||||
|
| `priority` | `VARCHAR(32)` | - | اولویت: `low`, `medium`, `high`, `urgent` |
|
||||||
|
| `assignee_id` | `UUID` (Nullable) | **FK** -> `pm_users.id` | کاربر سیستم مسئول اجرای وظیفه |
|
||||||
|
| `assignee_name` | `VARCHAR(255)` | - | نام متنی کاربر جهت نمایش سریع |
|
||||||
|
| `planned_start` | `DATE` | - | تاریخ شروع برنامهریزیشده |
|
||||||
|
| `planned_end` | `DATE` | - | تاریخ پایان برنامهریزیشده |
|
||||||
|
| `actual_start` | `DATE` (Nullable) | - | شروع واقعی (ثبت خودکار هنگام تغییر پیشرفت به بیشتر از صفر) |
|
||||||
|
| `actual_end` | `DATE` (Nullable) | - | پایان واقعی (ثبت خودکار در زمان تکمیل ۱۰۰٪) |
|
||||||
|
| `duration` | `INTEGER` | - | مدت زمان برآورد شده بر حسب روز کاری |
|
||||||
|
| `progress` | `INTEGER` | - | درصد پیشرفت واقعی از ۰ تا ۱۰۰ |
|
||||||
|
| `qc_status` | `VARCHAR(32)` | - | وضعیت کنترل کیفی: `none`, `pre_qc_pending`, `pre_qc_failed`, `ready`, `exec_qc_pending`, `in_progress`, `qc_failed_rework`, `final_passed` |
|
||||||
|
| `human_resources` | `JSON` | - | لیست نقشها و نفرات: `[{"role": "آرماتوربند", "count": 4}]` |
|
||||||
|
| `materials` | `JSON` | - | لیست مصالح و تجهیزات/ماشینآلات: `[{"name": "سیمان تیپ ۲", "unit": "تن", "specifications": ["عیار ۳۵۰"], "count": 10}, {"name": "تاور کرین", "unit": "دستگاه", "specifications": ["ظرفیت ۸ تن"], "count": 1}]` |
|
||||||
|
| `created_at` | `TIMESTAMP` | - | تاریخ ایجاد رکورد |
|
||||||
|
| `updated_at` | `TIMESTAMP` | - | تاریخ آخرین بهروزرسانی |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### ۳. جدول روابط وابستگی و گانت (`task_relations`)
|
||||||
|
پایهگذار روش مسیر بحرانی (CPM Scheduling) و شبکه فعالیتهای گانت.
|
||||||
|
|
||||||
|
| نام فیلد | نوع داده | کلید / ایندکس | توضیحات |
|
||||||
|
|---|---|---|---|
|
||||||
|
| `id` | `UUID` | **PK** | شناسه رابطه |
|
||||||
|
| `project_id` | `UUID` | **FK** -> `projects.id` | پروژه مربوطه |
|
||||||
|
| `from_task_id` | `UUID` | **FK** -> `tasks.id` | فعالیت پیشنیاز (Predecessor) |
|
||||||
|
| `to_task_id` | `UUID` | **FK** -> `tasks.id` | فعالیت وابسته / پسنیاز (Successor) |
|
||||||
|
| `relation_type` | `VARCHAR(8)` | - | نوع وابستگی: `FS` (پایان به شروع)، `SS` (شروع به شروع)، `FF` (پایان به پایان)، `SF` (شروع به پایان) |
|
||||||
|
| `lag_days` | `INTEGER` | - | فاصله زمانی مجاز (تاخیر یا تقدم) بر حسب روز |
|
||||||
|
| `created_at` | `TIMESTAMP` | - | زمان ثبت رابطه |
|
||||||
|
|
||||||
|
*محدودیت (Constraint):* زوج `(from_task_id, to_task_id)` یکتا بوده و از ایجاد حلقه (Cycle) در الگوریتم CPM جلوگیری میشود.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### ۴. حوزه کنترل کیفیت و بازرسی فنی (QC Domain)
|
||||||
|
|
||||||
|
این بخش تضمین میکند کلیه اقدامات اجرایی کارگاه دارای تاییدیههای استاندارد باشند:
|
||||||
|
|
||||||
|
#### الف) قالبهای سراسری بازرسی (`qc_templates` و `qc_questions`)
|
||||||
|
- **`qc_templates`:** کتابخانه فرمهای استاندارد کیفی (مثلاً قالب بازرسی بتنریزی، قالب سفتکاری).
|
||||||
|
- **`qc_questions`:** سوالات و ضوابط کنترلی در سه فاز اجرایی:
|
||||||
|
- `pre`: پیش از اجرا (آمادگی کارگاه، تایید نقشهها، مصالح ورودی).
|
||||||
|
- `during`: حین اجرا (دمای بتن، ویبره مناسب، ایمنی).
|
||||||
|
- `after`: پس از اجرا (عملآوری، مقاومت فشاری نمونهها).
|
||||||
|
|
||||||
|
#### ب) فرمهای کیفی اختصاصیافته به وظایف (`task_qc_definitions` و `task_qc_questions`)
|
||||||
|
- با تخصیص چکلیست به یک تسک، یک نسخه مستقل از قالب بر روی وظیفه ایجاد میشود تا هرگونه تغییر روی قالب سراسری به تاریخچه بازرسیهای ثبتشده آسیب نزند.
|
||||||
|
|
||||||
|
#### ج) نتایج و تاریخچه بازرسی (`task_qc_results`)
|
||||||
|
- سیستم ثبت پیوسته (Append-Only Log) بدون امکان حذف؛ هر ارزیابی بازرس شامل:
|
||||||
|
- `question_id`: شناسه آیتم بازرسی.
|
||||||
|
- `answer`: پاسخ بازرس (`pass` تایید، `fail` عدم انطباق، `na` عدم کاربرد).
|
||||||
|
- `comment`: توضیحات فنی و نواقص مشاهدهشده.
|
||||||
|
- `evaluated_by`: نام بازرس ناظر.
|
||||||
|
- `evaluated_at`: زمان دقیق بازرسی.
|
||||||
|
|
||||||
|
#### د) جدول عیوب و عدم انطباقها (`defects`)
|
||||||
|
- ثبت رخدادهای نامنطبق در جریان اجرای کار:
|
||||||
|
- `id` (UUID - PK): شناسه عیب.
|
||||||
|
- `task_id` (UUID - FK -> `tasks.id`): وظیفه مربوطه.
|
||||||
|
- `question_id` (UUID - FK اختیاری): سوال بازرسی که منجر به رد شدن شده است.
|
||||||
|
- `title`: عنوان عدم انطباق (مثلاً: «کرموشدگی بتن ستون جنوبی»).
|
||||||
|
- `description`: شرح دقیق ایراد.
|
||||||
|
- `severity`: درجه شدت عیب (`minor`, `medium`, `major`, `critical`).
|
||||||
|
- `status`: وضعیت رفع (`open`, `in_progress`, `resolved`).
|
||||||
|
- `corrective_action`: دستور اقدام اصلاحی صادرشده توسط مهندس ناظر.
|
||||||
|
- `resolution_notes`: شرح نحوه رفع عیب.
|
||||||
|
- `photo_path`: مسیر ذخیره تصویر مستند عیب در سرور.
|
||||||
|
- `resolved_at`: زمان تایید رفع عیب.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### ۵. احراز هویت و دسترسیها (`pm_users`, `project_members`, `project_assignments`)
|
||||||
|
|
||||||
|
- **`pm_users`:** کاربران سازمانی سیستم (`username`, `password_hash`, `display_name`, `role`).
|
||||||
|
- نقشهای سیستمی: `project_manager` (دسترسی نامحدود به تمام پروژهها)، `project_supervisor` (دسترسی محدود به پروژههای مشخص).
|
||||||
|
- **`project_members`:** اعضای منتسب به هر پروژه با نقش کارگاهی:
|
||||||
|
- `role`: `project_manager`, `site_engineer`, `qc_inspector`, `member`.
|
||||||
|
- **`project_assignments`:** جدول دامنه دسترسی برای ناظران و سرپرستان دارای دسترسی محدود (Scoped Roles).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## ۴. قواعد و منطقهای تجاری نهفته در سیستم (Business Invariants)
|
||||||
|
|
||||||
|
1. **گیتینگ کنترل کیفی (QC Gating Rule):**
|
||||||
|
اگر وظیفهای دارای چکلیست بازرسی فاز `pre` (پیش از اجرا) باشد، تا زمانی که تمامی این سوالات وضعیت `pass` یا `na` دریافت نکنند، سیستم اجازه شروع کار (`IN_PROGRESS`) و افزایش پیشرفت را نمیدهد.
|
||||||
|
2. **محاسبات پیشبینی مسیر بحرانی (CPM Logic):**
|
||||||
|
محاسبات زمانبندی با عبور رفت و برگشت (Forward & Backward Pass) تاریخهای زودهنگام و دیرهنگام را استخراج کرده و فعالیتهای با شناوری صفر (`Total Float = 0`) را به عنوان مسیر بحرانی مشخص میکند.
|
||||||
|
3. **چرخه حیات خودکار تاریخهای واقعی:**
|
||||||
|
با اولین تغییر در پیشرفت تسک (`progress > 0`)، فیلد `actual_start` به تاریخ جاری تنظیم میگردد. با رسیدن پیشرفت به `100%`، فیلد `actual_end` تنظیم و وضعیت وظیفه خودکار به `COMPLETED` تغییر مییابد.
|
||||||
|
4. **تجمیع پروژه (Rollup Logic):**
|
||||||
|
تاریخ شروع، پایان و درصد پیشرفت فیزیکی کل پروژه همواره حاصل تجمیع و میانگینگیری پویای وظایف موجود در پروژه است.
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user