feat(dashboard): 工作台四区块实时聚合与风险预警参数
- 后端 /api/v1/dashboard 单端点返回四区块:经营总览(绩效/应付/人数/团队数/月结状态/近 6 个月趋势)、待办(待审批 + 回款未指定批次 + 同步显式降级)、风险预警(回款逾期/审批超时,阈值参数化)、最近动态(操作日志) - dashboard_service 实时派生(不落表、不引调度器);参数快照一次解析;总览只做 SQL 聚合,不复用报表的重查询 - V10 迁移新增预警参数三项(warning.enabled / warning.receipt.overdue.days=90 / warning.approval.timeout.days=3),参数注册表 19→22,init-dev 与 V10 SQL 双轨同步 - 测试:test_dashboard 5 例(权限文案/总览对账+非法月份 400/待办三类/预警命中与参数关闭/动态来源);全量 852 passed - 依赖闭包并入:core/month.py 月份校验、api/v1/base/business_roles.py(router 已挂载的岗位只读端点)、test_month_validation - 修复:alembic --sql 在 Windows 按控制台 GBK 输出,V10 SQL 以 UTF-8 重新导出(README 已记) Co-Authored-By: Claude Code <noreply@anthropic.com>
This commit is contained in:
1 parent
b7cfdfa50a
commit
6ff202d637
18 files changed
+1262
-25
No files matched your search
@@ -8,6 +8,7 @@ from fastapi import APIRouter
|
||||
|
||||
from app.api import health
|
||||
from app.api.v1 import auth
|
||||
from app.api.v1.base import business_roles as base_business_roles
|
||||
from app.api.v1.base import customers as base_customers
|
||||
from app.api.v1.base import personnel as base_personnel
|
||||
from app.api.v1.base import products as base_products
|
||||
@@ -16,6 +17,7 @@ from app.api.v1.business import ratings as business_ratings
|
||||
from app.api.v1.business import receipts as business_receipts
|
||||
from app.api.v1.business import shipments as business_shipments
|
||||
from app.api.v1.calc import router as calc_router
|
||||
from app.api.v1.dashboard import router as dashboard_router
|
||||
from app.api.v1.reports import router as reports_router
|
||||
from app.api.v1.settlements import router as settlements_router
|
||||
from app.api.v1.system import approvals as system_approvals
|
||||
@@ -52,6 +54,7 @@ base_router = APIRouter(prefix="/base")
|
||||
base_router.include_router(base_personnel.router)
|
||||
base_router.include_router(base_products.router)
|
||||
base_router.include_router(base_customers.router)
|
||||
base_router.include_router(base_business_roles.router)
|
||||
v1_router.include_router(base_router)
|
||||
|
||||
# 业务数据(需求 2.2):/api/v1/business/*,业务操作登录即可访问
|
||||
@@ -68,5 +71,7 @@ v1_router.include_router(calc_router)
|
||||
v1_router.include_router(settlements_router)
|
||||
# 报表统计(M4 ⑤):/api/v1/reports/*,只读,限管理员/财务/领导
|
||||
v1_router.include_router(reports_router)
|
||||
# 工作台(M4 ⑧):/api/v1/dashboard,四区块只读聚合,限管理员/财务/领导
|
||||
v1_router.include_router(dashboard_router)
|
||||
|
||||
api_router.include_router(v1_router)
|
||||
@@ -0,0 +1,40 @@
|
||||
"""岗位下拉选项(基础数据与报表筛选共用)。
|
||||
|
||||
岗位管理本身仅管理员可用(FR-006),但报表的「岗位」筛选对财务/领导
|
||||
开放(FR-029)。为避免把管理接口整体放开,这里提供只读、登录即可的
|
||||
启用岗位选项;写操作仍走 `/system/business-roles` 的管理员端点。
|
||||
"""
|
||||
|
||||
from typing import Annotated
|
||||
|
||||
from fastapi import APIRouter, Depends
|
||||
|
||||
from app.api.deps import DbSession, get_current_user
|
||||
from app.core.response import ApiResponse, ok
|
||||
from app.models import User
|
||||
from app.repositories import business_role_repository
|
||||
|
||||
router = APIRouter(prefix="/business-roles", tags=["人员管理"])
|
||||
|
||||
# 基础数据是业务操作:登录即可,不要求管理员
|
||||
CurrentUser = Annotated[User, Depends(get_current_user)]
|
||||
|
||||
|
||||
@router.get("/options", response_model=ApiResponse[list[dict]], summary="岗位下拉选项")
|
||||
def list_options(session: DbSession, _: CurrentUser) -> ApiResponse[list[dict]]:
|
||||
"""岗位选项(登录即可;含停用——人员档案可能仍引用停用岗位)。
|
||||
|
||||
岗位规模有限(内置 + 自定义),一次取足够上限,不做分页。
|
||||
"""
|
||||
roles = business_role_repository.list_roles(session, offset=0, limit=1000)
|
||||
return ok(
|
||||
[
|
||||
{
|
||||
"id": role.id,
|
||||
"role_code": role.role_code,
|
||||
"role_name": role.role_name,
|
||||
"status": role.status,
|
||||
}
|
||||
for role in roles
|
||||
]
|
||||
)
|
||||
@@ -0,0 +1,39 @@
|
||||
"""工作台接口(M4 ⑧):四区块一次性聚合。
|
||||
|
||||
准入:管理员/财务/领导(与报表、审批接口一致;FR-033/036 的「全部用户」
|
||||
待业务权限清单 #6 答复后再放宽)。只读接口,不写操作日志。
|
||||
"""
|
||||
|
||||
from typing import Annotated
|
||||
|
||||
from fastapi import APIRouter, Depends, Query
|
||||
|
||||
from app.api.deps import DbSession, require_roles
|
||||
from app.core.constants import ROLE_ADMIN, ROLE_FINANCE, ROLE_LEADER
|
||||
from app.core.response import ApiResponse, ok
|
||||
from app.models import User
|
||||
from app.schemas.dashboard import DashboardOut
|
||||
from app.services import dashboard_service
|
||||
|
||||
router = APIRouter(prefix="/dashboard", tags=["工作台"])
|
||||
|
||||
_DashboardUser = Annotated[
|
||||
User,
|
||||
Depends(
|
||||
require_roles(
|
||||
ROLE_ADMIN, ROLE_FINANCE, ROLE_LEADER, message="无权访问工作台"
|
||||
)
|
||||
),
|
||||
]
|
||||
|
||||
|
||||
@router.get("", response_model=ApiResponse[DashboardOut], summary="工作台四区块")
|
||||
def get_dashboard(
|
||||
session: DbSession,
|
||||
_: _DashboardUser,
|
||||
month: Annotated[
|
||||
str | None, Query(max_length=7, description="统计月份 YYYY-MM,默认当月")
|
||||
] = None,
|
||||
) -> ApiResponse[DashboardOut]:
|
||||
"""一次返回经营总览/待办/风险预警/最近动态(待办与预警实时派生)。"""
|
||||
return ok(dashboard_service.get_dashboard(session, month))
|
||||
@@ -0,0 +1,26 @@
|
||||
"""月份参数校验(YYYY-MM)——叶子模块。
|
||||
|
||||
报表、月结与调整单共用同一套校验:只校验长度会放过 `2026-13` 这类
|
||||
非法月份,一路传到 `calendar.monthrange` 才抛 ValueError,最终被全局
|
||||
处理器当成服务端异常(500)。月份范围必须在入口处拦住,才能返回 400。
|
||||
"""
|
||||
|
||||
import re
|
||||
|
||||
_MONTH_RE = re.compile(r"^\d{4}-(0[1-9]|1[0-2])$")
|
||||
|
||||
|
||||
def validate_month(value: str) -> str:
|
||||
"""校验 YYYY-MM 且月份 01-12;非法抛 ValueError(Pydantic 友好)。
|
||||
|
||||
年份 0000 也拒绝:`date(0, ...)` 同样会抛 ValueError,且业务上不存在。
|
||||
"""
|
||||
if not _MONTH_RE.match(value) or int(value[:4]) == 0:
|
||||
raise ValueError("月份格式须为 YYYY-MM(01-12)")
|
||||
return value
|
||||
|
||||
|
||||
def parse_month(value: str) -> tuple[int, int]:
|
||||
"""校验并返回 (year, month),供服务层计算月末等使用。"""
|
||||
validate_month(value)
|
||||
return int(value[:4]), int(value[5:7])
|
||||
@@ -0,0 +1,209 @@
|
||||
"""工作台仓储:四区块的只读聚合查询;不 commit、不抛业务异常。
|
||||
|
||||
总览只做 SQL 聚合(SUM/COUNT DISTINCT),不复用报表的
|
||||
``department_summary``——后者会加载整月台账并逐团队查人员,适合报表页,
|
||||
不适合每次打开工作台。
|
||||
"""
|
||||
|
||||
from datetime import date, datetime
|
||||
|
||||
from sqlalchemy import exists, func, select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.models import (
|
||||
ApprovalOrder,
|
||||
Business,
|
||||
BusinessRole,
|
||||
MonthlySettlement,
|
||||
PerformanceLedger,
|
||||
Personnel,
|
||||
Receipt,
|
||||
Shipment,
|
||||
)
|
||||
from app.models.approval import (
|
||||
APPROVAL_STATUS_PENDING_FINANCE,
|
||||
APPROVAL_STATUS_PENDING_LEADER,
|
||||
)
|
||||
|
||||
_ACTIVE_SINGLE = (PerformanceLedger.calc_type == 1, PerformanceLedger.is_active == 1)
|
||||
_PENDING_STATUSES = (
|
||||
APPROVAL_STATUS_PENDING_FINANCE,
|
||||
APPROVAL_STATUS_PENDING_LEADER,
|
||||
)
|
||||
|
||||
|
||||
# ==== 经营绩效总览 ====
|
||||
|
||||
def sum_month_performance(session: Session, month: str) -> dict:
|
||||
"""当月单笔生效行合计与人员数(拆行求和不失真,人数需 DISTINCT)。"""
|
||||
return session.execute(
|
||||
select(
|
||||
func.coalesce(func.sum(PerformanceLedger.performance_amount), 0).label(
|
||||
"performance_total"
|
||||
),
|
||||
func.coalesce(func.sum(PerformanceLedger.payable_amount), 0).label("payable_total"),
|
||||
func.count(func.distinct(PerformanceLedger.personnel_id)).label("person_count"),
|
||||
).where(
|
||||
PerformanceLedger.settlement_month == month,
|
||||
*_ACTIVE_SINGLE,
|
||||
)
|
||||
).mappings().one()
|
||||
|
||||
|
||||
def performance_trend(session: Session, months: list[str]) -> dict[str, object]:
|
||||
"""近 N 个月绩效合计(按台账归属月)。"""
|
||||
rows = session.execute(
|
||||
select(
|
||||
PerformanceLedger.settlement_month,
|
||||
func.coalesce(func.sum(PerformanceLedger.performance_amount), 0),
|
||||
)
|
||||
.where(
|
||||
PerformanceLedger.settlement_month.in_(months),
|
||||
*_ACTIVE_SINGLE,
|
||||
)
|
||||
.group_by(PerformanceLedger.settlement_month)
|
||||
).all()
|
||||
return dict(rows)
|
||||
|
||||
|
||||
def receipt_trend(session: Session, months: list[str]) -> dict[str, object]:
|
||||
"""近 N 个月回款合计(按到账月,含未核算回款——与台账口径不同,页面注明)。"""
|
||||
month_expr = func.date_format(Receipt.receipt_date, "%Y-%m")
|
||||
rows = session.execute(
|
||||
select(month_expr, func.coalesce(func.sum(Receipt.amount), 0))
|
||||
.where(month_expr.in_(months))
|
||||
.group_by(month_expr)
|
||||
).all()
|
||||
return dict(rows)
|
||||
|
||||
|
||||
def count_active_managers(session: Session) -> int:
|
||||
"""在职营销经理数(团队数口径,与部门汇总的团队枚举一致)。"""
|
||||
return int(
|
||||
session.execute(
|
||||
select(func.count())
|
||||
.select_from(Personnel)
|
||||
.join(BusinessRole, Personnel.business_role_id == BusinessRole.id)
|
||||
.where(
|
||||
BusinessRole.role_code == "sales_manager",
|
||||
Personnel.status == 1,
|
||||
)
|
||||
).scalar_one()
|
||||
)
|
||||
|
||||
|
||||
def get_month_settlement(session: Session, month: str) -> MonthlySettlement | None:
|
||||
"""当月月结头(状态与锁定时间角标)。"""
|
||||
return session.execute(
|
||||
select(MonthlySettlement).where(MonthlySettlement.settlement_month == month)
|
||||
).scalar_one_or_none()
|
||||
|
||||
|
||||
# ==== 待办事项 ====
|
||||
|
||||
def list_pending_approvals(session: Session, *, limit: int) -> list[ApprovalOrder]:
|
||||
"""待处理审批单(按提交时间升序——最久的排前面)。"""
|
||||
return list(
|
||||
session.execute(
|
||||
select(ApprovalOrder)
|
||||
.where(ApprovalOrder.status.in_(_PENDING_STATUSES))
|
||||
.order_by(ApprovalOrder.create_time.asc(), ApprovalOrder.id.asc())
|
||||
.limit(limit)
|
||||
).scalars()
|
||||
)
|
||||
|
||||
|
||||
def count_pending_approvals(session: Session) -> int:
|
||||
return int(
|
||||
session.execute(
|
||||
select(func.count())
|
||||
.select_from(ApprovalOrder)
|
||||
.where(ApprovalOrder.status.in_(_PENDING_STATUSES))
|
||||
).scalar_one()
|
||||
)
|
||||
|
||||
|
||||
def list_unassigned_receipts(session: Session, *, limit: int) -> list:
|
||||
"""回款未指定发货批次(shipment_id IS NULL,核算前置缺失)。"""
|
||||
return list(
|
||||
session.execute(
|
||||
select(
|
||||
Receipt,
|
||||
Business.business_no.label("business_no"),
|
||||
)
|
||||
.outerjoin(Business, Business.id == Receipt.business_id)
|
||||
.where(Receipt.shipment_id.is_(None))
|
||||
.order_by(Receipt.receipt_date.asc(), Receipt.id.asc())
|
||||
.limit(limit)
|
||||
).all()
|
||||
)
|
||||
|
||||
|
||||
def count_unassigned_receipts(session: Session) -> int:
|
||||
return int(
|
||||
session.execute(
|
||||
select(func.count())
|
||||
.select_from(Receipt)
|
||||
.where(Receipt.shipment_id.is_(None))
|
||||
).scalar_one()
|
||||
)
|
||||
|
||||
|
||||
# ==== 风险预警 ====
|
||||
|
||||
def list_overdue_shipments(session: Session, *, cutoff: date, limit: int) -> list:
|
||||
"""发货后超过阈值且该批次无任何回款的发货单(回款逾期规则)。"""
|
||||
has_receipt = exists().where(Receipt.shipment_id == Shipment.id)
|
||||
return list(
|
||||
session.execute(
|
||||
select(
|
||||
Shipment,
|
||||
Business.business_no.label("business_no"),
|
||||
)
|
||||
.outerjoin(Business, Business.id == Shipment.business_id)
|
||||
.where(Shipment.ship_date <= cutoff, ~has_receipt)
|
||||
.order_by(Shipment.ship_date.asc())
|
||||
.limit(limit)
|
||||
).all()
|
||||
)
|
||||
|
||||
|
||||
def count_overdue_shipments(session: Session, *, cutoff: date) -> int:
|
||||
has_receipt = exists().where(Receipt.shipment_id == Shipment.id)
|
||||
return int(
|
||||
session.execute(
|
||||
select(func.count())
|
||||
.select_from(Shipment)
|
||||
.where(Shipment.ship_date <= cutoff, ~has_receipt)
|
||||
).scalar_one()
|
||||
)
|
||||
|
||||
|
||||
def list_overdue_approvals(
|
||||
session: Session, *, cutoff: datetime, limit: int
|
||||
) -> list[ApprovalOrder]:
|
||||
"""提交后超过阈值仍未处理的审批单(审批超时规则)。"""
|
||||
return list(
|
||||
session.execute(
|
||||
select(ApprovalOrder)
|
||||
.where(
|
||||
ApprovalOrder.status.in_(_PENDING_STATUSES),
|
||||
ApprovalOrder.create_time < cutoff,
|
||||
)
|
||||
.order_by(ApprovalOrder.create_time.asc())
|
||||
.limit(limit)
|
||||
).scalars()
|
||||
)
|
||||
|
||||
|
||||
def count_overdue_approvals(session: Session, *, cutoff: datetime) -> int:
|
||||
return int(
|
||||
session.execute(
|
||||
select(func.count())
|
||||
.select_from(ApprovalOrder)
|
||||
.where(
|
||||
ApprovalOrder.status.in_(_PENDING_STATUSES),
|
||||
ApprovalOrder.create_time < cutoff,
|
||||
)
|
||||
).scalar_one()
|
||||
)
|
||||
@@ -0,0 +1,125 @@
|
||||
"""工作台的请求/响应模型(M4 ⑧)。
|
||||
|
||||
四区块一次返回(前端一次请求渲染整页,避免 6-10 次往返):
|
||||
经营绩效总览 / 待办事项 / 风险预警 / 最近动态。金额一律 Decimal
|
||||
(序列化为字符串),前端不做数值运算。
|
||||
|
||||
待办与预警为**查询时实时派生**(不落库、不引调度器,见计划决策);
|
||||
⑥ T+ 同步未建前,同步相关条目用 `sync_available=false` 显式降级,
|
||||
不返回伪造的 0 条。
|
||||
"""
|
||||
|
||||
from datetime import date, datetime
|
||||
from decimal import Decimal
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
|
||||
class TrendPoint(BaseModel):
|
||||
"""近 6 个月趋势点(绩效按台账归属月,回款按到账月)。"""
|
||||
|
||||
month: str
|
||||
performance_total: Decimal | None = None
|
||||
receipt_total: Decimal | None = None
|
||||
|
||||
|
||||
class SettlementBrief(BaseModel):
|
||||
"""当月月结状态(工作台总览角标)。"""
|
||||
|
||||
exists: bool = False
|
||||
status: int | None = Field(default=None, description="1草稿 2待审批 3已审定 4已驳回")
|
||||
total_performance: Decimal | None = None
|
||||
total_payable: Decimal | None = None
|
||||
locked_at: datetime | None = None
|
||||
|
||||
|
||||
class OverviewBlock(BaseModel):
|
||||
"""经营绩效总览(FR-033):口径与台账/月结一致。"""
|
||||
|
||||
month: str
|
||||
performance_total: Decimal | None = Field(default=None, description="当月单笔绩效合计")
|
||||
payable_total: Decimal | None = Field(default=None, description="当月应付绩效合计")
|
||||
person_count: int = Field(default=0, description="当月有台账的人员数(拆行去重)")
|
||||
team_count: int = Field(default=0, description="在职营销经理数(团队数)")
|
||||
settlement: SettlementBrief
|
||||
trend: list[TrendPoint] = Field(default_factory=list, description="近 6 个月")
|
||||
note: str = Field(default="", description="口径说明(页面展示)")
|
||||
|
||||
|
||||
class ApprovalTodoItem(BaseModel):
|
||||
"""待审批条目。"""
|
||||
|
||||
order_id: int
|
||||
order_no: str
|
||||
order_type: int
|
||||
submitter_name: str | None = None
|
||||
create_time: datetime
|
||||
|
||||
|
||||
class ReceiptTodoItem(BaseModel):
|
||||
"""回款未指定发货批次条目。"""
|
||||
|
||||
receipt_id: int
|
||||
receipt_batch_no: str
|
||||
business_id: int
|
||||
business_no: str | None = None
|
||||
amount: Decimal
|
||||
receipt_date: date
|
||||
|
||||
|
||||
class TodoBlock(BaseModel):
|
||||
"""待办事项(FR-034,澄清 #11 起步范围)。"""
|
||||
|
||||
pending_approval_total: int = 0
|
||||
pending_approvals: list[ApprovalTodoItem] = Field(default_factory=list)
|
||||
unassigned_receipt_total: int = 0
|
||||
unassigned_receipts: list[ReceiptTodoItem] = Field(default_factory=list)
|
||||
sync_available: bool = Field(default=False, description="⑥ 同步模块是否已启用")
|
||||
sync_failure_total: int = 0
|
||||
|
||||
|
||||
class WarningItem(BaseModel):
|
||||
"""风险预警条目(实时派生,不改变业务数据)。"""
|
||||
|
||||
code: str = Field(description="规则编码:receipt_overdue / approval_timeout")
|
||||
level: str = Field(description="级别:warning / danger")
|
||||
object_type: str
|
||||
object_id: int
|
||||
title: str
|
||||
detail: str
|
||||
suggest: str
|
||||
link: str | None = Field(default=None, description="前端跳转路径")
|
||||
|
||||
|
||||
class WarningBlock(BaseModel):
|
||||
"""风险预警(FR-035,首批两条可算规则;同步规则待 ⑥)。"""
|
||||
|
||||
enabled: bool = True
|
||||
receipt_overdue_days: int = 90
|
||||
approval_timeout_days: int = 3
|
||||
items: list[WarningItem] = Field(default_factory=list)
|
||||
receipt_overdue_total: int = 0
|
||||
approval_timeout_total: int = 0
|
||||
sync_available: bool = False
|
||||
|
||||
|
||||
class ActivityItem(BaseModel):
|
||||
"""最近动态条目(来源 operation_logs,只读聚合)。"""
|
||||
|
||||
id: int
|
||||
module: str
|
||||
action: str
|
||||
summary: str
|
||||
username: str | None = None
|
||||
success: int
|
||||
create_time: datetime
|
||||
|
||||
|
||||
class DashboardOut(BaseModel):
|
||||
"""工作台四区块一次性响应。"""
|
||||
|
||||
month: str
|
||||
overview: OverviewBlock
|
||||
todos: TodoBlock
|
||||
warnings: WarningBlock
|
||||
activities: list[ActivityItem] = Field(default_factory=list)
|
||||
@@ -0,0 +1,245 @@
|
||||
"""工作台服务(M4 ⑧):四区块实时聚合编排。
|
||||
|
||||
设计决策(2026-10-19):
|
||||
- **只读**:不落库、不写审计(读操作不入操作日志);总览只做 SQL 聚合,
|
||||
不复用报表的部门汇总(后者会加载整月台账,过重)
|
||||
- **待办与预警实时派生**:不建待办/预警表、不引调度器;处置动作本身
|
||||
已有操作日志可追溯。与 FR-035「预警产生/消除留痕」的差距记录在
|
||||
计划开放项,待业务确认是否物化
|
||||
- **⑥ 同步模块未启用**:同步失败待办、同步连续失败预警以
|
||||
``sync_available=false`` 显式降级,不返回伪造的 0 条
|
||||
- 预警阈值走参数体系(``warning.*``),一次请求只解析一次快照
|
||||
"""
|
||||
|
||||
from datetime import date, datetime, timedelta
|
||||
from decimal import Decimal
|
||||
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.core.exceptions import BadRequestError
|
||||
from app.core.month import validate_month
|
||||
from app.repositories import dashboard_repository, operation_log_repository
|
||||
from app.repositories.query_utils import LogFilters
|
||||
|
||||
# 工作台只展示摘要,完整列表跳转对应管理页
|
||||
_TODO_LIMIT = 5
|
||||
_WARNING_LIMIT = 20
|
||||
_ACTIVITY_LIMIT = 20
|
||||
_TREND_MONTHS = 6
|
||||
|
||||
_ORDER_TYPE_LABELS = {1: "二次分配方案", 2: "月度结算", 3: "调整单"}
|
||||
|
||||
|
||||
def get_dashboard(session: Session, month: str | None = None) -> dict:
|
||||
"""四区块一次性出数(前端一次请求渲染整页)。"""
|
||||
resolved = _normalize_month(month)
|
||||
warning_params = _warning_params(session)
|
||||
return {
|
||||
"month": resolved,
|
||||
"overview": _overview(session, resolved),
|
||||
"todos": _todos(session),
|
||||
"warnings": _warnings(session, warning_params),
|
||||
"activities": _activities(session),
|
||||
}
|
||||
|
||||
|
||||
def _normalize_month(month: str | None) -> str:
|
||||
"""未传月份按当月;非法月份在入口拦成 400(避免 500)。"""
|
||||
if not month:
|
||||
today = date.today()
|
||||
return f"{today.year:04d}-{today.month:02d}"
|
||||
try:
|
||||
return validate_month(month)
|
||||
except ValueError as exc:
|
||||
raise BadRequestError(str(exc)) from exc
|
||||
|
||||
|
||||
def _shift_month(month: str, delta: int) -> str:
|
||||
"""YYYY-MM 平移 delta 个月(用于近 N 个月窗口)。"""
|
||||
year, mon = int(month[:4]), int(month[5:7])
|
||||
index = year * 12 + (mon - 1) + delta
|
||||
return f"{index // 12:04d}-{index % 12 + 1:02d}"
|
||||
|
||||
|
||||
def _trend_months(month: str) -> list[str]:
|
||||
"""窗口为「当月及之前共 6 个月」,升序返回便于前端画图。"""
|
||||
return [_shift_month(month, offset) for offset in range(-(_TREND_MONTHS - 1), 1)]
|
||||
|
||||
|
||||
def _overview(session: Session, month: str) -> dict:
|
||||
"""经营绩效总览(FR-033):口径与台账/月结一致。"""
|
||||
sums = dashboard_repository.sum_month_performance(session, month)
|
||||
settlement = dashboard_repository.get_month_settlement(session, month)
|
||||
months = _trend_months(month)
|
||||
performance = dashboard_repository.performance_trend(session, months)
|
||||
receipts = dashboard_repository.receipt_trend(session, months)
|
||||
return {
|
||||
"month": month,
|
||||
"performance_total": _dec(sums["performance_total"]),
|
||||
"payable_total": _dec(sums["payable_total"]),
|
||||
"person_count": int(sums["person_count"]),
|
||||
"team_count": dashboard_repository.count_active_managers(session),
|
||||
"settlement": {
|
||||
"exists": settlement is not None,
|
||||
"status": settlement.status if settlement else None,
|
||||
"total_performance": settlement.total_performance if settlement else None,
|
||||
"total_payable": settlement.total_payable if settlement else None,
|
||||
"locked_at": settlement.locked_at if settlement else None,
|
||||
},
|
||||
"trend": [
|
||||
{
|
||||
"month": item,
|
||||
"performance_total": _dec(performance.get(item)),
|
||||
"receipt_total": _dec(receipts.get(item)),
|
||||
}
|
||||
for item in months
|
||||
],
|
||||
"note": "绩效按台账归属月(单笔生效行,二次分摊拆行求和不失真);回款按到账月(含未核算回款);不含调整单",
|
||||
}
|
||||
|
||||
|
||||
def _todos(session: Session) -> dict:
|
||||
"""待办事项(FR-034,澄清 #11 起步范围)。"""
|
||||
orders = dashboard_repository.list_pending_approvals(session, limit=_TODO_LIMIT)
|
||||
receipts = dashboard_repository.list_unassigned_receipts(session, limit=_TODO_LIMIT)
|
||||
return {
|
||||
"pending_approval_total": dashboard_repository.count_pending_approvals(session),
|
||||
"pending_approvals": [
|
||||
{
|
||||
"order_id": order.id,
|
||||
"order_no": order.order_no,
|
||||
"order_type": order.order_type,
|
||||
"submitter_name": order.submitter_name,
|
||||
"create_time": order.create_time,
|
||||
}
|
||||
for order in orders
|
||||
],
|
||||
"unassigned_receipt_total": dashboard_repository.count_unassigned_receipts(session),
|
||||
"unassigned_receipts": [
|
||||
{
|
||||
"receipt_id": row[0].id,
|
||||
"receipt_batch_no": row[0].receipt_batch_no,
|
||||
"business_id": row[0].business_id,
|
||||
"business_no": row.business_no,
|
||||
"amount": row[0].amount,
|
||||
"receipt_date": row[0].receipt_date,
|
||||
}
|
||||
for row in receipts
|
||||
],
|
||||
# ⑥ T+ 同步未建:显式降级,不伪造「无失败」
|
||||
"sync_available": False,
|
||||
"sync_failure_total": 0,
|
||||
}
|
||||
|
||||
|
||||
def _warning_params(session: Session) -> dict:
|
||||
"""预警参数一次解析(阈值参数化,澄清 #10)。"""
|
||||
from app.services.param_service import parse_fraction, resolve_snapshot
|
||||
|
||||
snapshot = resolve_snapshot(session, date.today())
|
||||
return {
|
||||
"enabled": snapshot.get("warning.enabled") == "1",
|
||||
"receipt_overdue_days": int(parse_fraction(snapshot.get("warning.receipt.overdue.days"))),
|
||||
"approval_timeout_days": int(
|
||||
parse_fraction(snapshot.get("warning.approval.timeout.days"))
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
def _warnings(session: Session, params: dict) -> dict:
|
||||
"""风险预警(FR-035):首批两条可算规则;同步规则待 ⑥。"""
|
||||
if not params["enabled"]:
|
||||
return {
|
||||
"enabled": False,
|
||||
"receipt_overdue_days": params["receipt_overdue_days"],
|
||||
"approval_timeout_days": params["approval_timeout_days"],
|
||||
"items": [],
|
||||
"receipt_overdue_total": 0,
|
||||
"approval_timeout_total": 0,
|
||||
"sync_available": False,
|
||||
}
|
||||
|
||||
receipt_cutoff = date.today() - timedelta(days=params["receipt_overdue_days"])
|
||||
approval_cutoff = datetime.now() - timedelta(days=params["approval_timeout_days"])
|
||||
shipments = dashboard_repository.list_overdue_shipments(
|
||||
session, cutoff=receipt_cutoff, limit=_WARNING_LIMIT
|
||||
)
|
||||
orders = dashboard_repository.list_overdue_approvals(
|
||||
session, cutoff=approval_cutoff, limit=_WARNING_LIMIT
|
||||
)
|
||||
|
||||
items = [
|
||||
{
|
||||
"code": "receipt_overdue",
|
||||
"level": "danger",
|
||||
"object_type": "shipment",
|
||||
"object_id": row[0].id,
|
||||
"title": f"发货批次 {row[0].shipment_no} 逾期未回款",
|
||||
"detail": (
|
||||
f"业务 {row.business_no or row[0].business_id} 发货日 {row[0].ship_date},"
|
||||
f"超过 {params['receipt_overdue_days']} 天无回款记录"
|
||||
),
|
||||
"suggest": "联系客户催收,或核对回款批次指定关系",
|
||||
"link": "/business/shipments",
|
||||
}
|
||||
for row in shipments
|
||||
]
|
||||
items += [
|
||||
{
|
||||
"code": "approval_timeout",
|
||||
"level": "warning",
|
||||
"object_type": "approval_order",
|
||||
"object_id": order.id,
|
||||
"title": f"审批单 {order.order_no} 超时未处理",
|
||||
"detail": (
|
||||
f"{_ORDER_TYPE_LABELS.get(order.order_type, '审批')}由 "
|
||||
f"{order.submitter_name or '—'} 提交于 {order.create_time:%Y-%m-%d %H:%M},"
|
||||
f"已超过 {params['approval_timeout_days']} 天"
|
||||
),
|
||||
"suggest": "在审批管理中复核或退回",
|
||||
"link": "/system/approvals",
|
||||
}
|
||||
for order in orders
|
||||
]
|
||||
return {
|
||||
"enabled": True,
|
||||
"receipt_overdue_days": params["receipt_overdue_days"],
|
||||
"approval_timeout_days": params["approval_timeout_days"],
|
||||
"items": items,
|
||||
"receipt_overdue_total": dashboard_repository.count_overdue_shipments(
|
||||
session, cutoff=receipt_cutoff
|
||||
),
|
||||
"approval_timeout_total": dashboard_repository.count_overdue_approvals(
|
||||
session, cutoff=approval_cutoff
|
||||
),
|
||||
"sync_available": False,
|
||||
}
|
||||
|
||||
|
||||
def _activities(session: Session) -> list[dict]:
|
||||
"""最近动态(FR-036):以操作日志为唯一来源(写操作即留痕)。"""
|
||||
logs = operation_log_repository.list_logs(
|
||||
session,
|
||||
offset=0,
|
||||
limit=_ACTIVITY_LIMIT,
|
||||
filters=LogFilters(),
|
||||
)
|
||||
return [
|
||||
{
|
||||
"id": log.id,
|
||||
"module": log.module,
|
||||
"action": log.action,
|
||||
"summary": log.summary,
|
||||
"username": log.username,
|
||||
"success": log.success,
|
||||
"create_time": log.create_time,
|
||||
}
|
||||
for log in logs
|
||||
]
|
||||
|
||||
|
||||
def _dec(value) -> Decimal | None:
|
||||
"""SQL 聚合结果转 Decimal(SUM 可能返回 int,None 原样返回)。"""
|
||||
if value is None:
|
||||
return None
|
||||
return value if isinstance(value, Decimal) else Decimal(str(value))
|
||||
@@ -314,6 +314,54 @@ PARAM_REGISTRY: dict[str, ParamSpec] = {
|
||||
),
|
||||
sort_order=20,
|
||||
),
|
||||
# ===== 预警规则(M4 ⑧ 工作台,澄清 #10「做成参数化规则便于调整」)=====
|
||||
# 首批三条中「同步连续失败」依赖 ⑥ T+ 同步,模块未建前不设参数、不产生条目
|
||||
ParamSpec(
|
||||
code="warning.enabled",
|
||||
name="风险预警总开关",
|
||||
group="预警规则",
|
||||
value_type="BOOL",
|
||||
unit=None,
|
||||
dimension_type="NONE",
|
||||
options=None,
|
||||
default_value="1",
|
||||
value_min=None,
|
||||
value_max=None,
|
||||
description="工作台风险预警区块总开关:0=关闭(不扫描不展示) 1=开启(默认)",
|
||||
sort_order=21,
|
||||
),
|
||||
ParamSpec(
|
||||
code="warning.receipt.overdue.days",
|
||||
name="回款逾期天数阈值",
|
||||
group="预警规则",
|
||||
value_type="INT",
|
||||
unit="天",
|
||||
dimension_type="NONE",
|
||||
options=None,
|
||||
default_value="90",
|
||||
value_min="1",
|
||||
value_max=None,
|
||||
description=(
|
||||
"发货后超过该天数仍未回款的发货批次触发预警(澄清 #10 建议默认 90 天)"
|
||||
),
|
||||
sort_order=22,
|
||||
),
|
||||
ParamSpec(
|
||||
code="warning.approval.timeout.days",
|
||||
name="审批超时天数阈值",
|
||||
group="预警规则",
|
||||
value_type="INT",
|
||||
unit="天",
|
||||
dimension_type="NONE",
|
||||
options=None,
|
||||
default_value="3",
|
||||
value_min="1",
|
||||
value_max=None,
|
||||
description=(
|
||||
"待审批单提交后超过该天数未处理触发预警(澄清 #10 建议默认 3 天)"
|
||||
),
|
||||
sort_order=23,
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user