feat(db): 地磅、操作日志与工作流补全数据权限过滤

DB 列表/仪表盘 scoped 聚合,操作日志按 user_id 过滤,工作流实例详情与审批前校验 scope。

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
zlwuandCursor committed 2026-06-28 21:00:19 +08:00
1 parent 2905dc3d5f
commit 66d5a8714b
8 files changed
+284 -92

No files matched your search

+84 -70
View File
@@ -1,9 +1,10 @@
from __future__ import annotations
from datetime import date
from typing import Dict
from fastapi import APIRouter, Depends
from sqlalchemy import func, text
from sqlalchemy import func
from sqlalchemy.orm import Session
from app.core.database import get_db
@@ -15,10 +16,28 @@ from app.schemas.db.dashboard import (
DashboardPartnerCargoStat,
DashboardStats,
)
from app.services.db_data_scope import apply_db_scope
router = APIRouter(prefix="/dashboard", tags=["dashboard"])
def _scoped_inventory_query(db: Session, tenant_no: str, user: DbUserContext):
query = db.query(DbInboundOutbound).filter(
DbInboundOutbound.del_flag == 0,
DbInboundOutbound.tenant_no == tenant_no,
)
return apply_db_scope(query, DbInboundOutbound, user, db, tenant_no)
def _scoped_weighing_query(db: Session, tenant_no: str, user: DbUserContext):
query = db.query(DbWeighingSlip).filter(
DbWeighingSlip.is_voided == 0,
DbWeighingSlip.del_flag == 0,
DbWeighingSlip.tenant_no == tenant_no,
)
return apply_db_scope(query, DbWeighingSlip, user, db, tenant_no)
@router.get("/stats", response_model=DashboardStats)
def get_dashboard_stats(
db: Session = Depends(get_db),
@@ -28,36 +47,30 @@ def get_dashboard_stats(
today = date.today()
today_inbound = float(
db.query(func.coalesce(func.sum(DbInboundOutbound.quantity), 0))
_scoped_inventory_query(db, tenant_no, user)
.filter(
DbInboundOutbound.date == today,
DbInboundOutbound.business_type == "入库",
DbInboundOutbound.del_flag == 0,
DbInboundOutbound.tenant_no == tenant_no,
)
.with_entities(func.coalesce(func.sum(DbInboundOutbound.quantity), 0))
.scalar()
or 0
)
today_outbound = float(
db.query(func.coalesce(func.sum(DbInboundOutbound.quantity), 0))
_scoped_inventory_query(db, tenant_no, user)
.filter(
DbInboundOutbound.date == today,
DbInboundOutbound.business_type == "出库",
DbInboundOutbound.del_flag == 0,
DbInboundOutbound.tenant_no == tenant_no,
)
.with_entities(func.coalesce(func.sum(DbInboundOutbound.quantity), 0))
.scalar()
or 0
)
abnormal_orders = int(
db.query(func.count(DbWeighingSlip.id))
.filter(
DbWeighingSlip.is_voided == 0,
DbWeighingSlip.del_flag == 0,
DbWeighingSlip.tenant_no == tenant_no,
)
_scoped_weighing_query(db, tenant_no, user)
.with_entities(func.count(DbWeighingSlip.id))
.scalar()
or 0
)
@@ -101,36 +114,49 @@ def get_outbound_by_partner_cargo(
return _partner_cargo_stats(db, user, business_type="出库")
def _weighing_actual_map(
db: Session, tenant_no: str, user: DbUserContext, inventory_ids: list[str]
) -> Dict[str, float]:
if not inventory_ids:
return {}
rows = (
_scoped_weighing_query(db, tenant_no, user)
.filter(DbWeighingSlip.inbound_outbound_id.in_(inventory_ids))
.all()
)
actual_map: Dict[str, float] = {}
for row in rows:
if not row.inbound_outbound_id:
continue
actual_map[row.inbound_outbound_id] = actual_map.get(row.inbound_outbound_id, 0.0) + (
float(row.net_weight or 0) / 1000.0
)
return actual_map
def _cargo_stats(db: Session, user: DbUserContext, *, business_type: str) -> list[DashboardCargoStat]:
tenant_no = get_tenant_no(db, user.to_tenant_user_dict())
today = date.today()
query = text(
"""
SELECT
COALESCE(io.product, ws.cargo_name, '未填写货物') AS label,
COALESCE(SUM(io.quantity), 0) AS planned,
COALESCE(SUM(ws.net_weight) / 1000.0, 0) AS actual
FROM db_inbound_outbound io
LEFT JOIN db_weighing_slip ws
ON ws.inbound_outbound_id = io.id
AND ws.is_voided = 0
AND ws.del_flag = 0
AND ws.tenant_no = io.tenant_no
WHERE io.date = :today
AND io.business_type = :business_type
AND io.del_flag = 0
AND io.tenant_no = :tenant_no
GROUP BY COALESCE(io.product, ws.cargo_name, '未填写货物')
ORDER BY planned DESC
"""
inventories = (
_scoped_inventory_query(db, tenant_no, user)
.filter(
DbInboundOutbound.date == today,
DbInboundOutbound.business_type == business_type,
)
.all()
)
rows = db.execute(
query,
{"today": today, "business_type": business_type, "tenant_no": tenant_no},
).all()
actual_map = _weighing_actual_map(db, tenant_no, user, [inv.id for inv in inventories])
agg: Dict[str, Dict[str, float]] = {}
for inv in inventories:
label = (inv.product or "").strip() or "未填写货物"
bucket = agg.setdefault(label, {"planned": 0.0, "actual": 0.0})
bucket["planned"] += float(inv.quantity or 0)
bucket["actual"] += actual_map.get(inv.id, 0.0)
return [
DashboardCargoStat(label=row.label, planned=float(row.planned), actual=float(row.actual))
for row in rows
DashboardCargoStat(label=label, planned=values["planned"], actual=values["actual"])
for label, values in sorted(agg.items(), key=lambda item: item[1]["planned"], reverse=True)
]
@@ -142,39 +168,27 @@ def _partner_cargo_stats(
) -> list[DashboardPartnerCargoStat]:
tenant_no = get_tenant_no(db, user.to_tenant_user_dict())
today = date.today()
query = text(
"""
SELECT
CONCAT(
COALESCE(io.partner_company, ''),
' - ',
COALESCE(io.product, ws.cargo_name, '未填写货物')
) AS label,
COALESCE(SUM(io.quantity), 0) AS planned,
COALESCE(SUM(ws.net_weight) / 1000.0, 0) AS actual
FROM db_inbound_outbound io
LEFT JOIN db_weighing_slip ws
ON ws.inbound_outbound_id = io.id
AND ws.is_voided = 0
AND ws.del_flag = 0
AND ws.tenant_no = io.tenant_no
WHERE io.date = :today
AND io.business_type = :business_type
AND io.del_flag = 0
AND io.tenant_no = :tenant_no
GROUP BY io.partner_company, io.product, ws.cargo_name
ORDER BY io.partner_company, planned DESC
"""
inventories = (
_scoped_inventory_query(db, tenant_no, user)
.filter(
DbInboundOutbound.date == today,
DbInboundOutbound.business_type == business_type,
)
.all()
)
rows = db.execute(
query,
{"today": today, "business_type": business_type, "tenant_no": tenant_no},
).all()
actual_map = _weighing_actual_map(db, tenant_no, user, [inv.id for inv in inventories])
agg: Dict[str, Dict[str, float]] = {}
for inv in inventories:
product = (inv.product or "").strip() or "未填写货物"
label = f"{inv.partner_company or ''} - {product}"
bucket = agg.setdefault(label, {"planned": 0.0, "actual": 0.0})
bucket["planned"] += float(inv.quantity or 0)
bucket["actual"] += actual_map.get(inv.id, 0.0)
return [
DashboardPartnerCargoStat(
label=row.label,
planned=float(row.planned),
actual=float(row.actual),
DashboardPartnerCargoStat(label=label, planned=values["planned"], actual=values["actual"])
for label, values in sorted(
agg.items(), key=lambda item: (item[0].split(" - ", 1)[0], -item[1]["planned"])
)
for row in rows
]
+8 -3
View File
@@ -11,6 +11,7 @@ from sqlalchemy.orm import Session
from app.core.database import get_db
from app.core.db_auth import DbUserContext, get_db_current_user, get_db_current_user_optional
from app.core.tenant_context import get_tenant_no
from app.services.db_data_scope import apply_db_scope, assert_db_row_in_scope
from app.services.db.inventory_id import next_inbound_outbound_id
from app.models.db_models import DbInboundOutbound, DbPurchasePlan, DbWeighingSlip
from app.schemas.db.inventory import (
@@ -101,7 +102,9 @@ def _get_inventory_by_id(db: Session, inventory_id: str) -> DbInboundOutbound:
return row
def _get_inventory(db: Session, tenant_no: str, inventory_id: str) -> DbInboundOutbound:
def _get_inventory(
db: Session, tenant_no: str, inventory_id: str, user: DbUserContext
) -> DbInboundOutbound:
row = (
_base_query(db, tenant_no)
.filter(DbInboundOutbound.id == inventory_id)
@@ -112,6 +115,7 @@ def _get_inventory(db: Session, tenant_no: str, inventory_id: str) -> DbInboundO
status_code=status.HTTP_404_NOT_FOUND,
detail=f"Inventory {inventory_id} not found",
)
assert_db_row_in_scope(db, row, DbInboundOutbound, user, tenant_no)
return row
@@ -227,6 +231,7 @@ def list_inventory(
if business_type:
query = query.filter(DbInboundOutbound.business_type == business_type)
query = apply_db_scope(query, DbInboundOutbound, user, db, tenant_no)
inventories = query.all()
inventory_ids = [inv.id for inv in inventories]
weighing_map: dict[str, DbWeighingSlip] = {}
@@ -369,7 +374,7 @@ def get_inventory_site_url(
user: DbUserContext = Depends(get_db_current_user),
) -> InventorySiteUrlRead:
tenant_no = get_tenant_no(db, user.to_tenant_user_dict())
row = _get_inventory(db, tenant_no, id)
row = _get_inventory(db, tenant_no, id, user)
token = ensure_site_access_token(row)
db.commit()
return InventorySiteUrlRead(site_url=build_site_inventory_url(token))
@@ -420,7 +425,7 @@ def delete_inventory(
user: DbUserContext = Depends(get_db_current_user),
) -> None:
tenant_no = get_tenant_no(db, user.to_tenant_user_dict())
row = _get_inventory(db, tenant_no, id)
row = _get_inventory(db, tenant_no, id, user)
row.del_flag = 1
row.update_by = user.id
db.commit()
+10 -5
View File
@@ -11,6 +11,7 @@ from app.core.database import get_db
from app.core.db_auth import DbUserContext, get_db_current_user
from app.core.tenant_context import get_tenant_no
from app.core.utils import generate_uuid
from app.services.db_data_scope import apply_db_scope, assert_db_row_in_scope
from app.models.db_models import DbInboundOutbound, DbPurchasePlan, DbWeighingSlip
from app.schemas.db.inventory import InboundOutboundRead
from app.schemas.db.plans import (
@@ -117,6 +118,7 @@ def list_plans(
if start_to:
query = query.filter(DbPurchasePlan.start_date <= start_to)
query = apply_db_scope(query, DbPurchasePlan, user, db, tenant_no)
plans = query.all()
if not plans:
return []
@@ -263,7 +265,7 @@ def get_plan(
user: DbUserContext = Depends(get_db_current_user),
) -> PurchasePlanRead:
tenant_no = get_tenant_no(db, user.to_tenant_user_dict())
plan = _get_plan(db, tenant_no, id)
plan = _get_plan(db, tenant_no, id, user)
return plan_to_read(plan)
@@ -275,7 +277,7 @@ def update_plan(
user: DbUserContext = Depends(get_db_current_user),
) -> PurchasePlanRead:
tenant_no = get_tenant_no(db, user.to_tenant_user_dict())
plan = _get_plan(db, tenant_no, id)
plan = _get_plan(db, tenant_no, id, user)
payload_dict = payload.model_dump(exclude_unset=True)
_apply_plan_product_update(db, tenant_no, plan, payload_dict)
_apply_plan_update(plan, payload_dict)
@@ -292,13 +294,15 @@ def delete_plan(
user: DbUserContext = Depends(get_db_current_user),
) -> None:
tenant_no = get_tenant_no(db, user.to_tenant_user_dict())
plan = _get_plan(db, tenant_no, id)
plan = _get_plan(db, tenant_no, id, user)
plan.del_flag = 1
plan.update_by = user.id
db.commit()
def _get_plan(db: Session, tenant_no: str, plan_id: str) -> DbPurchasePlan:
def _get_plan(
db: Session, tenant_no: str, plan_id: str, user: DbUserContext
) -> DbPurchasePlan:
plan = (
_base_query(db, tenant_no)
.filter(DbPurchasePlan.id == plan_id)
@@ -309,6 +313,7 @@ def _get_plan(db: Session, tenant_no: str, plan_id: str) -> DbPurchasePlan:
status_code=status.HTTP_404_NOT_FOUND,
detail=f"Plan {plan_id} not found",
)
assert_db_row_in_scope(db, plan, DbPurchasePlan, user, tenant_no)
return plan
@@ -375,7 +380,7 @@ def get_plan_related(
user: DbUserContext = Depends(get_db_current_user),
) -> PlanRelatedData:
tenant_no = get_tenant_no(db, user.to_tenant_user_dict())
plan = _get_plan(db, tenant_no, id)
plan = _get_plan(db, tenant_no, id, user)
inventories = (
db.query(DbInboundOutbound)
+11 -6
View File
@@ -11,6 +11,7 @@ from app.core.database import get_db
from app.core.db_auth import DbUserContext, get_db_current_user
from app.core.tenant_context import get_tenant_no
from app.core.utils import generate_uuid
from app.services.db_data_scope import apply_db_scope, assert_db_row_in_scope
from app.models.db_models import DbInboundOutbound, DbPurchasePlan, DbWeighingSlip
from app.schemas.db.inventory import InboundOutboundRead
from app.schemas.db.plans import PurchasePlanRead
@@ -43,7 +44,9 @@ def _base_query(db: Session, tenant_no: str):
)
def _get_weighing(db: Session, tenant_no: str, weighing_id: str) -> DbWeighingSlip:
def _get_weighing(
db: Session, tenant_no: str, weighing_id: str, user: DbUserContext
) -> DbWeighingSlip:
row = (
db.query(DbWeighingSlip)
.filter(
@@ -58,6 +61,7 @@ def _get_weighing(db: Session, tenant_no: str, weighing_id: str) -> DbWeighingSl
status_code=status.HTTP_404_NOT_FOUND,
detail=f"Weighing {weighing_id} not found",
)
assert_db_row_in_scope(db, row, DbWeighingSlip, user, tenant_no)
return row
@@ -162,6 +166,7 @@ def list_weighing(
if business_type:
query = query.filter(DbWeighingSlip.business_type == business_type)
query = apply_db_scope(query, DbWeighingSlip, user, db, tenant_no)
weighings = query.all()
inventory_ids = [w.inbound_outbound_id for w in weighings if w.inbound_outbound_id]
inventory_date_map: dict[str, str] = {}
@@ -294,7 +299,7 @@ def get_weighing(
user: DbUserContext = Depends(get_db_current_user),
) -> WeighingSlipRead:
tenant_no = get_tenant_no(db, user.to_tenant_user_dict())
row = _get_weighing(db, tenant_no, id)
row = _get_weighing(db, tenant_no, id, user)
return weighing_to_read(row)
@@ -306,7 +311,7 @@ def update_weighing(
user: DbUserContext = Depends(get_db_current_user),
) -> WeighingSlipRead:
tenant_no = get_tenant_no(db, user.to_tenant_user_dict())
row = _get_weighing(db, tenant_no, id)
row = _get_weighing(db, tenant_no, id, user)
if row.is_voided == 1:
raise HTTPException(
@@ -333,7 +338,7 @@ def void_weighing(
user: DbUserContext = Depends(get_db_current_user),
) -> None:
tenant_no = get_tenant_no(db, user.to_tenant_user_dict())
row = _get_weighing(db, tenant_no, id)
row = _get_weighing(db, tenant_no, id, user)
if row.is_voided == 1:
raise HTTPException(
@@ -354,7 +359,7 @@ def delete_weighing(
user: DbUserContext = Depends(get_db_current_user),
) -> None:
tenant_no = get_tenant_no(db, user.to_tenant_user_dict())
row = _get_weighing(db, tenant_no, id)
row = _get_weighing(db, tenant_no, id, user)
row.is_voided = 1
row.update_by = user.id
db.commit()
@@ -373,7 +378,7 @@ def get_weighing_related(
user: DbUserContext = Depends(get_db_current_user),
) -> WeighingRelatedData:
tenant_no = get_tenant_no(db, user.to_tenant_user_dict())
row = _get_weighing(db, tenant_no, id)
row = _get_weighing(db, tenant_no, id, user)
plan = None
if row.purchase_plan_id: