Compare commits
2
Commits
a181a8753d
...
65758b5e78
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
65758b5e78 | ||
|
|
b1edf6eed3 |
@@ -271,12 +271,13 @@ async def update_warehouse(
|
||||
wh.name = payload.name
|
||||
if payload.description is not None:
|
||||
wh.description = payload.description
|
||||
# پروژهی انبار تغییرناپذیر است — انبار برای همیشه به پروژهی والدش تعلق
|
||||
# دارد و فقط با حذف و ساخت دوباره میتواند جابهجا شود.
|
||||
if payload.project_id is not None and str(payload.project_id) != str(wh.project_id):
|
||||
if await db.get(Project, payload.project_id) is None:
|
||||
raise NotFoundError("پروژه مقصد یافت نشد", field="project_id")
|
||||
if scope.role == ROLE_PM and payload.project_id != scope.project_id:
|
||||
raise ForbiddenError("PM فقط میتواند انبار را در پروژه خودش جابهجا کند", field="project_id")
|
||||
wh.project_id = payload.project_id
|
||||
raise ValidationError(
|
||||
"پروژهی انبار قابل تغییر نیست — انبار برای همیشه به پروژهی والدش تعلق دارد",
|
||||
field="project_id",
|
||||
)
|
||||
await db.flush()
|
||||
return {"data": warehouse_to_dict(wh, await db.get(Project, wh.project_id))}
|
||||
|
||||
|
||||
@@ -10,7 +10,16 @@ from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.db.engine import get_db
|
||||
from app.models.catalog import Material
|
||||
from app.models.procurement import ItemDecision, LineItem, Project, Quote, Supplier, Termsheet
|
||||
from app.models.procurement import (
|
||||
ItemDecision,
|
||||
LineItem,
|
||||
LineItemProjects,
|
||||
Project,
|
||||
Quote,
|
||||
QuoteProjects,
|
||||
Supplier,
|
||||
Termsheet,
|
||||
)
|
||||
from app.schemas.procurement import (
|
||||
AcceptQuoteIn,
|
||||
ArriveItemsIn,
|
||||
@@ -111,7 +120,23 @@ async def list_quotes(
|
||||
if supplier_id:
|
||||
stmt = stmt.where(Quote.supplier_id == supplier_id)
|
||||
if project_id:
|
||||
stmt = stmt.where(Quote.project_id == project_id)
|
||||
# any relevant link: legacy mirror, quote-level junction, line-item
|
||||
# candidates, or an accepted (decision) target — NOT just the mirror
|
||||
stmt = stmt.where(
|
||||
Quote.id.in_(
|
||||
select(Quote.id)
|
||||
.outerjoin(QuoteProjects, QuoteProjects.quote_id == Quote.id)
|
||||
.outerjoin(LineItem, LineItem.quote_id == Quote.id)
|
||||
.outerjoin(LineItemProjects, LineItemProjects.line_item_id == LineItem.id)
|
||||
.outerjoin(ItemDecision, ItemDecision.line_item_id == LineItem.id)
|
||||
.where(
|
||||
(Quote.project_id == project_id)
|
||||
| (QuoteProjects.project_id == project_id)
|
||||
| (LineItemProjects.project_id == project_id)
|
||||
| (ItemDecision.project_id == project_id)
|
||||
)
|
||||
)
|
||||
)
|
||||
if category_id:
|
||||
stmt = stmt.where(_quote_category_exists(category_id))
|
||||
if quote_date_from is not None:
|
||||
|
||||
@@ -30,6 +30,13 @@ class WarehouseCreate(APIModel):
|
||||
|
||||
|
||||
class WarehouseUpdate(APIModel):
|
||||
"""Rename/re-describe a warehouse.
|
||||
|
||||
`project_id` is accepted only to be rejected: a warehouse belongs
|
||||
permanently to its parent project and cannot be reassigned (the router
|
||||
answers 400 unless the value equals the current project).
|
||||
"""
|
||||
|
||||
name: str | None = Field(default=None, min_length=1, max_length=255)
|
||||
description: str | None = None
|
||||
project_id: UUID | None = None
|
||||
|
||||
@@ -915,22 +915,45 @@ def _quote_has_category(category_id: UUID):
|
||||
|
||||
|
||||
async def project_stats(db: AsyncSession, project_id: UUID) -> dict:
|
||||
"""Counts + total value per quote status for one project.
|
||||
"""Counts + total value per quote status for ONE project, isolated per project.
|
||||
|
||||
total_value: SUM(quantity × unit_price) over line items using the chosen
|
||||
termsheet link first, else the first link. Rejected line items are
|
||||
excluded from value sums (contract P1-14).
|
||||
A quote lands in this project's «accepted»/«arrived» bucket ONLY if at
|
||||
least one non-rejected line item's decision targets this project
|
||||
(item_decisions.project_id). A quote merely linked to the project as a
|
||||
candidate (quote-level link, line-item candidates, or accepted for a
|
||||
DIFFERENT project) stays in «offered» — this project never accepted it.
|
||||
|
||||
total_value: SUM(quantity × unit_price) over the bucket's line items,
|
||||
using the chosen termsheet link first, else the first link. Rejected
|
||||
line items are excluded from value sums (contract P1-14).
|
||||
"""
|
||||
project = await db.get(Project, project_id)
|
||||
if project is None:
|
||||
raise NotFoundError("پروژه یافت نشد")
|
||||
# the route passes the raw path string — normalize for the Python-side
|
||||
# UUID comparisons below (decision.project_id == project_id etc.)
|
||||
project_id = UUID(str(project_id))
|
||||
|
||||
quotes = (await db.execute(select(Quote).where(Quote.project_id == project_id))).scalars().all()
|
||||
if not quotes:
|
||||
# --- every quote RELEVANT to this project (any kind of link) ---
|
||||
quote_id_rows = await db.execute(
|
||||
select(Quote.id)
|
||||
.outerjoin(QuoteProjects, QuoteProjects.quote_id == Quote.id)
|
||||
.outerjoin(LineItem, LineItem.quote_id == Quote.id)
|
||||
.outerjoin(LineItemProjects, LineItemProjects.line_item_id == LineItem.id)
|
||||
.outerjoin(ItemDecision, ItemDecision.line_item_id == LineItem.id)
|
||||
.where(
|
||||
(Quote.project_id == project_id)
|
||||
| (QuoteProjects.project_id == project_id)
|
||||
| (LineItemProjects.project_id == project_id)
|
||||
| (ItemDecision.project_id == project_id)
|
||||
)
|
||||
)
|
||||
quote_ids = [row[0] for row in quote_id_rows.all()]
|
||||
if not quote_ids:
|
||||
empty = {status: {"count": 0, "total_value": 0} for status in QUOTE_STATUSES}
|
||||
return {"project_id": str(project_id), "total_quotes": 0, **empty}
|
||||
|
||||
quote_ids = [q.id for q in quotes]
|
||||
quotes = (await db.execute(select(Quote).where(Quote.id.in_(quote_ids)))).scalars().all()
|
||||
line_items = (await db.execute(select(LineItem).where(LineItem.quote_id.in_(quote_ids)))).scalars().all()
|
||||
li_ids = [li.id for li in line_items]
|
||||
|
||||
@@ -938,6 +961,18 @@ async def project_stats(db: AsyncSession, project_id: UUID) -> dict:
|
||||
d.line_item_id: d
|
||||
for d in (await db.execute(select(ItemDecision).where(ItemDecision.line_item_id.in_(li_ids)))).scalars().all()
|
||||
} if li_ids else {}
|
||||
# line items explicitly linked to this project as candidates
|
||||
candidate_li_ids = set(
|
||||
(
|
||||
await db.execute(
|
||||
select(LineItemProjects.line_item_id).where(
|
||||
LineItemProjects.line_item_id.in_(li_ids),
|
||||
LineItemProjects.project_id == project_id,
|
||||
)
|
||||
)
|
||||
).scalars().all()
|
||||
) if li_ids else set()
|
||||
|
||||
item_termsheets = (
|
||||
(await db.execute(select(ItemTermsheet).where(ItemTermsheet.line_item_id.in_(li_ids)))).scalars().all()
|
||||
) if li_ids else []
|
||||
@@ -946,12 +981,56 @@ async def project_stats(db: AsyncSession, project_id: UUID) -> dict:
|
||||
for it in item_termsheets:
|
||||
its_by_line.setdefault(it.line_item_id, []).append(it)
|
||||
|
||||
def _items_of(quote: Quote) -> list[LineItem]:
|
||||
return [li for li in line_items if li.quote_id == quote.id]
|
||||
|
||||
def _accepted_for_project(quote: Quote) -> bool:
|
||||
"""≥1 non-rejected line item whose decision targets THIS project."""
|
||||
return any(
|
||||
(decision := decisions.get(li.id)) is not None
|
||||
and decision.status == "chosen"
|
||||
and decision.project_id == project_id
|
||||
for li in _items_of(quote)
|
||||
)
|
||||
|
||||
def _has_any_target(quote: Quote) -> bool:
|
||||
"""Whether any decision of this quote carries a target project at all
|
||||
(legacy quotes accepted before the decision-project era have none —
|
||||
they keep the old global-status classification)."""
|
||||
return any(
|
||||
(decisions.get(li.id) is not None and decisions[li.id].project_id is not None)
|
||||
for li in _items_of(quote)
|
||||
)
|
||||
|
||||
per_status = {status: {"count": 0, "total_value": 0.0} for status in QUOTE_STATUSES}
|
||||
for q in quotes:
|
||||
per_status[q.status]["count"] += 1
|
||||
if q.status in ("accepted", "arrived") and _has_any_target(q) and not _accepted_for_project(q):
|
||||
per_status["offered"]["count"] += 1 # linked, but never accepted for THIS project
|
||||
else:
|
||||
per_status[q.status]["count"] += 1
|
||||
|
||||
for li in line_items:
|
||||
quote = next(q for q in quotes if q.id == li.quote_id)
|
||||
decision = decisions.get(li.id)
|
||||
|
||||
# --- which status bucket does this line item's value belong to? ---
|
||||
accepted_here = (
|
||||
decision is not None
|
||||
and decision.status == "chosen"
|
||||
and decision.project_id == project_id
|
||||
)
|
||||
if quote.status in ("accepted", "arrived") and _has_any_target(quote):
|
||||
if accepted_here:
|
||||
bucket = quote.status
|
||||
elif li.id in candidate_li_ids:
|
||||
# the quote is still just a proposal for this project — the
|
||||
# item's candidate value stays in the offered bucket
|
||||
bucket = "offered"
|
||||
else:
|
||||
continue # this item targets another project entirely
|
||||
else:
|
||||
bucket = quote.status
|
||||
|
||||
if decision is not None and decision.status == "rejected":
|
||||
continue # rejected items excluded from value sums
|
||||
if decision is not None and decision.chosen_item_termsheet_id is not None:
|
||||
@@ -961,8 +1040,7 @@ async def project_stats(db: AsyncSession, project_id: UUID) -> dict:
|
||||
price_it = links[0] if links else None
|
||||
if price_it is None:
|
||||
continue
|
||||
quote = next(q for q in quotes if q.id == li.quote_id)
|
||||
per_status[quote.status]["total_value"] += float(price_it.unit_price * li.quantity)
|
||||
per_status[bucket]["total_value"] += float(price_it.unit_price * li.quantity)
|
||||
|
||||
result = {"project_id": str(project_id), "total_quotes": len(quotes)}
|
||||
for status, values in per_status.items():
|
||||
|
||||
@@ -1675,7 +1675,8 @@ export const apiV26 = {
|
||||
const d = await postData<Parameters<typeof rawWarehouse>[0]>(`/inventory/warehouses${projectQuery()}`, body);
|
||||
return rawWarehouse(d);
|
||||
},
|
||||
update: async (id: string, body: { name?: string; description?: string | null; project_id?: string }): Promise<Warehouse> => {
|
||||
// project_id عمداً در تایپ نیست — انبار برای همیشه به پروژهی والدش تعلق دارد
|
||||
update: async (id: string, body: { name?: string; description?: string | null }): Promise<Warehouse> => {
|
||||
const d = await patchData<Parameters<typeof rawWarehouse>[0]>(`/inventory/warehouses/${id}${projectQuery()}`, body);
|
||||
return rawWarehouse(d);
|
||||
},
|
||||
|
||||
@@ -148,16 +148,8 @@ export function OrganizationPage() {
|
||||
}
|
||||
};
|
||||
|
||||
const moveWarehouse = async (id: string, projectId: string) => {
|
||||
try {
|
||||
await apiV26.warehouses.update(id, { project_id: projectId });
|
||||
toast.success("انبار منتقل شد ✓");
|
||||
await data.refresh();
|
||||
} catch (err) {
|
||||
toast.error(err instanceof Error ? err.message : "خطا در انتقال انبار");
|
||||
}
|
||||
};
|
||||
|
||||
// انبار برای همیشه به پروژهی والدش تعلق دارد — انتقال به پروژهی دیگر وجود ندارد؛
|
||||
// انبار فقط با حذف و ساخت دوباره زیر پروژهی موردنظر جابهجا میشود.
|
||||
const removeWarehouse = async (id: string) => {
|
||||
if (!confirm("انبار حذف شود؟ (انبارهای دارای سابقه تراکنش قابل حذف نیستند)")) return;
|
||||
try {
|
||||
@@ -329,16 +321,6 @@ export function OrganizationPage() {
|
||||
>
|
||||
📊 داشبورد
|
||||
</button>
|
||||
<select
|
||||
className="h-7 rounded-lg border border-line bg-panel px-2 text-[11px]"
|
||||
value={w.project_id}
|
||||
onChange={(e) => void moveWarehouse(w.id, e.target.value)}
|
||||
title="انتقال به پروژه دیگر"
|
||||
>
|
||||
{data.lookup.projects.map((p2) => (
|
||||
<option key={p2.id} value={p2.id}>{p2.name}</option>
|
||||
))}
|
||||
</select>
|
||||
<button className="text-muted hover:text-red" onClick={() => void removeWarehouse(w.id)} title="حذف انبار">✕</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -16,7 +16,6 @@ import {
|
||||
import { normalize } from "../../lib/normalize";
|
||||
import { useAppStore } from "../../store";
|
||||
import {
|
||||
activeItems,
|
||||
lineItemTotal,
|
||||
materialById,
|
||||
materialLabel,
|
||||
@@ -29,25 +28,45 @@ import { EmptyState } from "../../components/EmptyState";
|
||||
import { Button } from "../../components/ui/button";
|
||||
|
||||
function projectQuotes(quotes: Quote[], name: string): Quote[] {
|
||||
return quotes.filter((q) => (q.projects || []).includes(name) || q.project === name);
|
||||
return quotes.filter(
|
||||
(q) =>
|
||||
(q.projects || []).includes(name) ||
|
||||
q.project === name ||
|
||||
(q.line_items || []).some(
|
||||
(li) =>
|
||||
li.target_project?.name === name ||
|
||||
(li.projects || []).some((p) => (typeof p === "string" ? p : p.name) === name),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// اقلام مربوط به این پروژه در یک quote
|
||||
// آیا این پیشنهاد برای «این» پروژه پذیرفته شده است؟
|
||||
// ملاک، پروژهی هدفِ تصمیم خریدِ اقلام است (item_decisions.project_id) — نه
|
||||
// وضعیت سراسری پیشنهاد؛ پیشنهادی که فقط برای پروژهی دیگری پذیرفته شده،
|
||||
// برای این پروژه همچنان «پیشنهاد شده» است.
|
||||
function acceptedForProject(q: Quote, name: string): boolean {
|
||||
return (q.line_items || []).some((li) => !li.rejected && li.target_project?.name === name);
|
||||
}
|
||||
|
||||
// آیا اصلاً برای این پیشنهاد پروژهی هدفی ثبت شده؟ (پیشنهادهای قدیمیِ
|
||||
// پیش از era تصمیمپروژه، طبق وضعیت سراسری دستهبندی میشوند)
|
||||
function hasTargets(q: Quote): boolean {
|
||||
return (q.line_items || []).some((li) => !!li.target_project);
|
||||
}
|
||||
|
||||
// اقلام مربوط به این پروژه در یک quote:
|
||||
// اولویت با اقلامِ پذیرفتهشده برای همین پروژه (تصمیم خرید)؛ سپس کاندیداهای
|
||||
// همین پروژه؛ و اگر هیچ اتصال قلمبهقلمی نبود، همهی اقلام فعال.
|
||||
function itemsForProject(q: Quote, name: string): Quote["line_items"] {
|
||||
const items = (q.line_items || []).filter((li) => !li.rejected);
|
||||
const targeted = items.filter((li) => li.target_project?.name === name);
|
||||
if (targeted.length) return targeted;
|
||||
if (items.some((li) => li.projects && li.projects.length)) {
|
||||
return items.filter((li) => (li.projects || []).some((p) => p.name === name));
|
||||
}
|
||||
return items;
|
||||
}
|
||||
|
||||
function qTotal(q: Quote): number {
|
||||
return activeItems(q).reduce((sum, li) => {
|
||||
const t = lineItemTotal(li);
|
||||
return sum + (t || 0);
|
||||
}, 0);
|
||||
}
|
||||
|
||||
function daysSince(iso: string | null): number | null {
|
||||
if (!iso) return null;
|
||||
const d = new Date(iso);
|
||||
@@ -147,10 +166,11 @@ export function ProjectsPage() {
|
||||
// ---------- پنل جزئیات یک پروژه ----------
|
||||
function renderProjectDetail(store: Store, name: string): React.ReactElement {
|
||||
const quotes = projectQuotes(store.quotes, name);
|
||||
const sumBy = (st: Quote["status"]) =>
|
||||
quotes
|
||||
.filter((q) => q.status === st)
|
||||
.reduce((s, q) => s + qTotal(q), 0);
|
||||
|
||||
// جمع مبلغ هر ستون فقط روی اقلامِ همین پروژه
|
||||
const itemsTotal = (q: Quote) =>
|
||||
itemsForProject(q, name).reduce((s, li) => s + (lineItemTotal(li) || 0), 0);
|
||||
const sumBy = (list: Quote[]) => list.reduce((s, q) => s + itemsTotal(q), 0);
|
||||
|
||||
const matName = (mid: string) => {
|
||||
const m = materialById(store.materials, mid);
|
||||
@@ -184,11 +204,19 @@ function renderProjectDetail(store: Store, name: string): React.ReactElement {
|
||||
);
|
||||
};
|
||||
|
||||
// دستهبندی ایزوله per-project:
|
||||
// - پذیرفته/رسیده فقط وقتی حداقل یک قلمِ غیرردشده برای «این» پروژه پذیرفته شده باشد؛
|
||||
// - پیشنهادی که صرفاً کاندیداست (یا فقط برای پروژهی دیگری پذیرفته شده) → پیشنهاد شده.
|
||||
// - پیشنهادهای قدیمیِ بدون پروژهی هدف، طبق وضعیت سراسری میمانند.
|
||||
const offered = quotes
|
||||
.filter((q) => q.status === "offered")
|
||||
.filter(
|
||||
(q) =>
|
||||
q.status === "offered" ||
|
||||
((q.status === "accepted" || q.status === "arrived") && hasTargets(q) && !acceptedForProject(q, name)),
|
||||
)
|
||||
.sort((a, b) => new Date(a.expiry_date || 0).getTime() - new Date(b.expiry_date || 0).getTime());
|
||||
const accepted = quotes.filter((q) => q.status === "accepted");
|
||||
const arrived = quotes.filter((q) => q.status === "arrived");
|
||||
const accepted = quotes.filter((q) => q.status === "accepted" && acceptedForProject(q, name));
|
||||
const arrived = quotes.filter((q) => q.status === "arrived" && acceptedForProject(q, name));
|
||||
|
||||
const offeredRow = (q: Quote) => {
|
||||
const days = q.expiry_date ? Math.ceil((new Date(q.expiry_date).getTime() - Date.now()) / 86400000) : null;
|
||||
@@ -199,7 +227,7 @@ function renderProjectDetail(store: Store, name: string): React.ReactElement {
|
||||
</div>
|
||||
<div className="pj-meta">{itemsForProject(q, name).map(itemLine)}</div>
|
||||
<div className="pj-side">
|
||||
جمع: <b>{faNum(qTotal(q))} تومان</b>
|
||||
جمع: <b>{faNum(itemsTotal(q))} تومان</b>
|
||||
</div>
|
||||
<div className="pj-side">
|
||||
اعتبار تا {fmtDate(q.expiry_date)}<br />
|
||||
@@ -240,7 +268,7 @@ function renderProjectDetail(store: Store, name: string): React.ReactElement {
|
||||
</div>
|
||||
<div className="pj-meta">{itemsForProject(q, name).map(itemLine)}</div>
|
||||
<div className="pj-side">
|
||||
هزینه: <b>{faNum(qTotal(q))} تومان</b>
|
||||
هزینه: <b>{faNum(itemsTotal(q))} تومان</b>
|
||||
</div>
|
||||
<div className="pj-side">رسید: {fmtDate(q.arrived_date)}</div>
|
||||
</div>
|
||||
@@ -255,13 +283,13 @@ function renderProjectDetail(store: Store, name: string): React.ReactElement {
|
||||
<div className="mb-3 flex flex-wrap gap-1.5">
|
||||
<span className="pj-chip">کل پیشنهادها: {faNum(quotes.length)}</span>
|
||||
<span className="pj-chip" style={{ background: "#dbeafe", color: "#1d4ed8" }}>
|
||||
ارزش باز: {faNum(sumBy("offered"))} تومان
|
||||
ارزش باز: {faNum(sumBy(offered))} تومان
|
||||
</span>
|
||||
<span className="pj-chip" style={{ background: "#fef3c7", color: "#d97706" }}>
|
||||
ارزش پذیرفته: {faNum(sumBy("accepted"))} تومان
|
||||
ارزش پذیرفته: {faNum(sumBy(accepted))} تومان
|
||||
</span>
|
||||
<span className="pj-chip" style={{ background: "#dcfce7", color: "#16a34a" }}>
|
||||
ارزش رسیده: {faNum(sumBy("arrived"))} تومان
|
||||
ارزش رسیده: {faNum(sumBy(arrived))} تومان
|
||||
</span>
|
||||
</div>
|
||||
<div className="grid grid-cols-1 gap-3 md:grid-cols-3">
|
||||
|
||||
Reference in New Issue
Block a user