549 lines
25 KiB
Python
549 lines
25 KiB
Python
"""项目立项与项目预算:版本、明细、计算预览、送审。
|
||
|
||
路由形状固定成 ``/finance/{module}/projects/{project_id}/...``,立项与预算共用一套代码,
|
||
两个模块只是换了 ``module`` 参数——这正好反映了两者共用同一个利润内核的事实。
|
||
内部编码仍叫 ``estimate``:它是 ``biz_revision.module``、审批流程的 ``business_module``
|
||
与数据权限模块键的取值,改这个字符串要连着改库里的历史数据,换来的只是少一个词;
|
||
界面上则统一叫**项目立项**,不再出现"概算"。
|
||
|
||
两道闸口在这里:
|
||
1. 立项送审前必须把立项表的必填项填完(``submit`` 里的 ``initiation_missing_fields``)。
|
||
2. 预算侧"第一次生成版本"必须立项已批准——拦在 ``biz.get_or_create_revision`` 里,
|
||
本文件另外提供显式的 ``generate`` 接口,界面上点「生成预算」才调它。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import json
|
||
from datetime import datetime
|
||
from decimal import Decimal
|
||
from typing import Any
|
||
|
||
from fastapi import APIRouter, Query
|
||
from pydantic import BaseModel, Field
|
||
from sqlalchemy import select
|
||
from sqlalchemy.orm import Session
|
||
|
||
from .. import dicts as dict_store
|
||
from ..deps import DbSession, PrincipalOf, assert_project_visible
|
||
from ..envelope import bad_request, conflict, forbidden, not_found, ok
|
||
from ..models import (
|
||
Account,
|
||
CalcSnapshot,
|
||
Project,
|
||
ProjectStage,
|
||
Revision,
|
||
RevisionModule,
|
||
RevisionStatus,
|
||
to_decimal,
|
||
)
|
||
from ..service import biz
|
||
from ..service.approval import engine as approval_engine
|
||
|
||
router = APIRouter(prefix="/finance", tags=["finance"])
|
||
|
||
MODULES = {RevisionModule.ESTIMATE: "项目立项", RevisionModule.BUDGET: "项目预算"}
|
||
|
||
LINE_KEYS = {
|
||
"income", "cost", "other",
|
||
"income_plan", "purchase", "pay_plan", "manage", "other_cost", "fund_month",
|
||
}
|
||
|
||
|
||
class LineBody(BaseModel):
|
||
data: dict[str, Any]
|
||
|
||
|
||
class LinesBody(BaseModel):
|
||
rows: list[dict[str, Any]] = Field(default_factory=list)
|
||
|
||
|
||
class SubmitBody(BaseModel):
|
||
comment: str = ""
|
||
selfSelected: dict[str, list[int]] = Field(default_factory=dict)
|
||
|
||
|
||
class InitiationBody(BaseModel):
|
||
"""立项表(= 项目信息表)的一次保存。``None`` 表示这一栏没提交,不是"清空"。"""
|
||
|
||
name: str | None = None
|
||
projectNo: str | None = None
|
||
type: int | None = None
|
||
underwrittenMode: int | None = None
|
||
certainty: int | None = None
|
||
industryScene: int | None = None
|
||
industrySceneDesc: str | None = None
|
||
customer: str | None = None
|
||
terminalCustomer: str | None = None
|
||
valueRisk: str | None = None
|
||
principalId: int | None = None
|
||
contractTime: str | None = None
|
||
bidsTime: str | None = None
|
||
isSecond: int | None = None
|
||
isHuizhiBid: int | None = None
|
||
calculationCollection: str | None = None
|
||
stage: int | None = None
|
||
saleStage: int | None = None
|
||
stageRemark: str | None = None
|
||
planStart: str | None = None
|
||
planEnd: str | None = None
|
||
contractAmount: str | None = None
|
||
grossProfit: str | None = None
|
||
grossProfitRate: str | None = None
|
||
huizhiAmount: str | None = None
|
||
huazhiAmount: str | None = None
|
||
h3cAmount: str | None = None
|
||
otherProductAmount: str | None = None
|
||
advanceInterestRate: str | None = None
|
||
header: dict[str, Any] | None = None
|
||
|
||
|
||
def _module_or_404(module: str) -> str:
|
||
if module not in MODULES:
|
||
raise not_found(f"未知的业务模块:{module}")
|
||
return module
|
||
|
||
|
||
def _permission(module: str, action: str) -> str:
|
||
return f"project:{module}:{action}"
|
||
|
||
|
||
def _revision_context(db, current: PrincipalOf, project_id: int, module: str, *,
|
||
write: bool = False) -> tuple[Project, Revision]:
|
||
project = assert_project_visible(db, current, project_id, module=module)
|
||
action = "edit" if write else "view"
|
||
if not current.permission.can(_permission(module, action)):
|
||
raise forbidden(f"缺少权限:{_permission(module, action)}")
|
||
revision = biz.get_or_create_revision(db, project_id, module, current.account)
|
||
return project, revision
|
||
|
||
|
||
@router.get("/{module}/projects/{project_id}/revision")
|
||
def get_revision(module: str, project_id: int, db: DbSession, current: PrincipalOf) -> dict[str, Any]:
|
||
"""一个版本的完整视图:明细 + 最新快照 + 审批状态 + 立项表。页面首屏只要这一个请求。"""
|
||
_module_or_404(module)
|
||
project, revision = _revision_context(db, current, project_id, module)
|
||
lines = biz.revision_lines(db, revision)
|
||
snapshot = biz.current_snapshot(db, revision)
|
||
payload = biz.snapshot_payload(snapshot)
|
||
|
||
versions = db.execute(
|
||
select(Revision).where(Revision.project_id == project_id, Revision.module == module,
|
||
Revision.is_deleted.is_(False)).order_by(Revision.version.desc())
|
||
).scalars().all()
|
||
|
||
return ok({
|
||
"module": module,
|
||
"moduleLabel": MODULES[module],
|
||
"project": {"id": project.id, "name": project.name, "projectNo": project.project_no,
|
||
"stage": project.stage, "stageLabel": project.stage_label,
|
||
"advanceInterestRate": f"{project.advance_interest_rate}"},
|
||
"initiation": _initiation_view(db, project, revision, module),
|
||
"revision": _revision_view(db, revision),
|
||
"versions": [_revision_view(db, row) for row in versions],
|
||
"lines": {key: [biz.serialize_line(row) for row in rows] for key, rows in lines.items()},
|
||
"snapshot": {
|
||
"id": snapshot.id if snapshot else None,
|
||
"calcVersion": snapshot.calc_version if snapshot else "",
|
||
"createdAt": snapshot.created_at.isoformat(sep=" ", timespec="seconds") if snapshot else "",
|
||
"payload": payload,
|
||
},
|
||
})
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# 立项表:一张能存草稿的项目信息表
|
||
# ---------------------------------------------------------------------------
|
||
|
||
#: 立项表上要让前端读到、也能写回的列
|
||
INITIATION_FIELDS = (
|
||
"project_no", "name", "type", "underwritten_mode", "certainty", "industry_scene",
|
||
"industry_scene_desc", "customer", "terminal_customer", "value_risk", "principal",
|
||
"principal_id", "contract_time", "bids_time", "is_second", "is_huizhi_bid",
|
||
"calculation_collection", "stage", "sale_stage", "stage_remark", "plan_start", "plan_end",
|
||
"contract_amount", "gross_profit", "gross_profit_rate", "huizhi_amount", "huazhi_amount",
|
||
"h3c_amount", "other_product_amount", "advance_interest_rate", "org_unit_name",
|
||
)
|
||
|
||
#: 日期列:回给前端一律折成 YYYY-MM-DD,带 T00:00:00 的字符串日期输入框回填不进去
|
||
DATE_FIELDS = ("contract_time", "bids_time", "plan_start", "plan_end")
|
||
|
||
#: 表头里允许前端写的键(合同名称、解决方案协同…),别的键只读
|
||
HEADER_FIELDS = ("contract_name", "resolve_plan_synergy", "income_detail_attr",
|
||
"cost_detail_attr", "remark")
|
||
|
||
|
||
def _initiation_view(db: Session, project: Project, revision: Revision, module: str) -> dict[str, Any]:
|
||
data: dict[str, Any] = {}
|
||
for column in INITIATION_FIELDS:
|
||
value = getattr(project, column, None)
|
||
if column in DATE_FIELDS:
|
||
data[column] = value.date().isoformat() if isinstance(value, datetime) else (
|
||
value.isoformat() if hasattr(value, "isoformat") else "")
|
||
elif isinstance(value, Decimal):
|
||
data[column] = f"{value}"
|
||
else:
|
||
data[column] = value if value is not None else ""
|
||
data.update({
|
||
"id": project.id,
|
||
"orgUnitId": project.org_unit_id,
|
||
"typeLabel": dict_store.label(db, "projectType", project.type, ""),
|
||
"underwrittenModeLabel": dict_store.label(db, "underwrittenMode", project.underwritten_mode, ""),
|
||
"certaintyLabel": dict_store.label(db, "certainty", project.certainty, ""),
|
||
"industrySceneLabel": dict_store.label(db, "industryScene", project.industry_scene, ""),
|
||
"saleStageLabel": dict_store.label(db, "saleStage", project.sale_stage, "未填写"),
|
||
"stageLabel": project.stage_label,
|
||
"isSecondLabel": dict_store.label(db, "yesNo", project.is_second, ""),
|
||
"isHuizhiBidLabel": dict_store.label(db, "yesNo", project.is_huizhi_bid, ""),
|
||
"source": project.source,
|
||
# 送审前要拦的必填项:草稿不拦,界面上用它把缺的栏标出来
|
||
"missingRequired": biz.initiation_missing_fields(project)
|
||
if module == RevisionModule.ESTIMATE else [],
|
||
# 有测算明细时这几个金额由计算投影覆盖,表单里就该显示成"跟着测算走"
|
||
"amountDrivenByLines": bool(revision.snapshot_id),
|
||
"header": biz.header_of(revision),
|
||
})
|
||
return data
|
||
|
||
|
||
def _parse_date(column: str, text: str):
|
||
from .projects import _date, _datetime
|
||
|
||
if not text:
|
||
return None
|
||
if column in ("contract_time", "bids_time"):
|
||
return _datetime(text)
|
||
return _date(text)
|
||
|
||
|
||
@router.get("/{module}/projects/{project_id}/initiation")
|
||
def get_initiation(module: str, project_id: int, db: DbSession,
|
||
current: PrincipalOf) -> dict[str, Any]:
|
||
_module_or_404(module)
|
||
project, revision = _revision_context(db, current, project_id, module)
|
||
return ok({"initiation": _initiation_view(db, project, revision, module),
|
||
"state": biz.initiation_state(db, project_id)})
|
||
|
||
|
||
@router.put("/{module}/projects/{project_id}/initiation")
|
||
def save_initiation(module: str, project_id: int, body: InitiationBody, db: DbSession,
|
||
current: PrincipalOf) -> dict[str, Any]:
|
||
"""保存立项表(项目信息)。
|
||
|
||
这条接口**只保存、不送审**,也不卡必填:立项表就是一张能反复存草稿的表,
|
||
"录到一半"是常态。必填在 ``submit`` 里统一校验。
|
||
"""
|
||
_module_or_404(module)
|
||
project, revision = _revision_context(db, current, project_id, module, write=True)
|
||
for text, column in (
|
||
(body.name, "name"), (body.customer, "customer"), (body.terminalCustomer, "terminal_customer"),
|
||
(body.valueRisk, "value_risk"), (body.calculationCollection, "calculation_collection"),
|
||
(body.stageRemark, "stage_remark"), (body.industrySceneDesc, "industry_scene_desc"),
|
||
(body.projectNo, "project_no"),
|
||
):
|
||
if text is not None:
|
||
setattr(project, column, text if column == "name" else text.strip())
|
||
for value, column in (
|
||
(body.type, "type"), (body.underwrittenMode, "underwritten_mode"), (body.certainty, "certainty"),
|
||
(body.industryScene, "industry_scene"), (body.isSecond, "is_second"),
|
||
(body.isHuizhiBid, "is_huizhi_bid"), (body.saleStage, "sale_stage"),
|
||
(body.principalId, "principal_id"),
|
||
):
|
||
if value is not None:
|
||
setattr(project, column, value)
|
||
if body.stage in ProjectStage.LABELS:
|
||
project.stage = body.stage
|
||
for text, column in (
|
||
(body.contractTime, "contract_time"), (body.bidsTime, "bids_time"),
|
||
(body.planStart, "plan_start"), (body.planEnd, "plan_end"),
|
||
):
|
||
if text is not None:
|
||
setattr(project, column, _parse_date(column, text))
|
||
for text, column in (
|
||
(body.contractAmount, "contract_amount"), (body.grossProfit, "gross_profit"),
|
||
(body.grossProfitRate, "gross_profit_rate"), (body.huizhiAmount, "huizhi_amount"),
|
||
(body.huazhiAmount, "huazhi_amount"), (body.h3cAmount, "h3c_amount"),
|
||
(body.otherProductAmount, "other_product_amount"),
|
||
(body.advanceInterestRate, "advance_interest_rate"),
|
||
):
|
||
if text not in (None, ""):
|
||
setattr(project, column, to_decimal(text))
|
||
if body.principalId:
|
||
owner = db.get(Account, body.principalId)
|
||
if owner is not None:
|
||
project.principal = owner.display_name or owner.account
|
||
biz.sync_owner_member(db, project)
|
||
if body.header:
|
||
biz.save_header(revision, body.header)
|
||
db.commit()
|
||
return ok({"initiation": _initiation_view(db, project, revision, module)})
|
||
|
||
|
||
@router.post("/budget/projects/{project_id}/generate")
|
||
def generate_budget(project_id: int, db: DbSession, current: PrincipalOf) -> dict[str, Any]:
|
||
"""立项批准后,按批准那一版生成预算草稿版本。
|
||
|
||
这是"预算数据从哪来"的唯一入口:界面上点「按立项生成预算」才调它,
|
||
工作台不会偷偷替人建版本。
|
||
"""
|
||
project = assert_project_visible(db, current, project_id, module=RevisionModule.BUDGET)
|
||
if not current.permission.can("project:budget:edit"):
|
||
raise forbidden("缺少权限:project:budget:edit")
|
||
result = biz.generate_budget_from_initiation(db, project, current.account)
|
||
db.commit()
|
||
return ok({
|
||
"revision": _revision_view(db, result["revision"]),
|
||
"copied": result["copied"],
|
||
"skippedOtherLines": result["skippedOtherLines"],
|
||
"note": result["note"],
|
||
})
|
||
|
||
|
||
@router.get("/{module}/projects/{project_id}/gate")
|
||
def gate(module: str, project_id: int, db: DbSession, current: PrincipalOf) -> dict[str, Any]:
|
||
"""给列表页与按钮用的一句回答:这个项目现在能不能编预算、进展到哪一步。"""
|
||
_module_or_404(module)
|
||
assert_project_visible(db, current, project_id, module=module)
|
||
return ok(biz.initiation_state(db, project_id))
|
||
|
||
|
||
def _revision_view(db: Session, row: Revision) -> dict[str, Any]:
|
||
return {
|
||
"id": row.id, "version": row.version, "status": row.status,
|
||
"statusLabel": dict_store.label(db, "revisionStatus", row.status, row.status),
|
||
"editable": row.status in RevisionStatus.EDITABLE,
|
||
"title": row.title, "basedOnId": row.based_on_id, "snapshotId": row.snapshot_id,
|
||
"calcVersion": row.calc_version, "creatorName": row.creator_name,
|
||
"header": biz.header_of(row),
|
||
"submittedAt": row.submitted_at.isoformat(sep=" ", timespec="seconds") if row.submitted_at else "",
|
||
"decidedAt": row.decided_at.isoformat(sep=" ", timespec="seconds") if row.decided_at else "",
|
||
"createdAt": row.created_at.isoformat(sep=" ", timespec="seconds"),
|
||
}
|
||
|
||
|
||
@router.get("/{module}/projects/{project_id}/versions/{revision_id}")
|
||
def get_version(module: str, project_id: int, revision_id: int, db: DbSession,
|
||
current: PrincipalOf) -> dict[str, Any]:
|
||
"""翻历史版本:只读,用来对照"上一版和这一版差在哪"。"""
|
||
_module_or_404(module)
|
||
assert_project_visible(db, current, project_id, module=module)
|
||
revision = db.get(Revision, revision_id)
|
||
if revision is None or revision.project_id != project_id or revision.module != module:
|
||
raise not_found("版本不存在")
|
||
lines = biz.revision_lines(db, revision)
|
||
return ok({
|
||
"revision": _revision_view(db, revision),
|
||
"lines": {key: [biz.serialize_line(row) for row in rows] for key, rows in lines.items()},
|
||
"snapshot": biz.snapshot_payload(biz.current_snapshot(db, revision)),
|
||
})
|
||
|
||
|
||
@router.post("/{module}/projects/{project_id}/lines/{line_key}")
|
||
def upsert_line(module: str, project_id: int, line_key: str, body: LineBody,
|
||
db: DbSession, current: PrincipalOf) -> dict[str, Any]:
|
||
_module_or_404(module)
|
||
_assert_line_key(line_key)
|
||
project, revision = _revision_context(db, current, project_id, module, write=True)
|
||
row = biz.upsert_line(db, revision, f"{module}.{line_key}", body.data, current.account)
|
||
snapshot = biz.current_snapshot(db, revision)
|
||
db.commit()
|
||
return ok({"line": biz.serialize_line(row),
|
||
"snapshot": biz.snapshot_payload(snapshot),
|
||
"revision": _revision_view(db, revision)})
|
||
|
||
|
||
@router.put("/{module}/projects/{project_id}/lines/{line_key}")
|
||
def replace_lines(module: str, project_id: int, line_key: str, body: LinesBody,
|
||
db: DbSession, current: PrincipalOf) -> dict[str, Any]:
|
||
_module_or_404(module)
|
||
_assert_line_key(line_key)
|
||
project, revision = _revision_context(db, current, project_id, module, write=True)
|
||
removed = biz.replace_lines(db, revision, f"{module}.{line_key}", body.rows, current.account)
|
||
snapshot = biz.current_snapshot(db, revision)
|
||
db.commit()
|
||
return ok({"removed": removed, "snapshot": biz.snapshot_payload(snapshot),
|
||
"revision": _revision_view(db, revision)})
|
||
|
||
|
||
def _assert_line_key(line_key: str) -> None:
|
||
if line_key not in LINE_KEYS:
|
||
raise not_found(f"未知的明细类型:{line_key}")
|
||
|
||
|
||
@router.delete("/{module}/projects/{project_id}/lines/{line_key}/{line_id}")
|
||
def delete_line(module: str, project_id: int, line_key: str, line_id: int,
|
||
db: DbSession, current: PrincipalOf) -> dict[str, Any]:
|
||
_module_or_404(module)
|
||
_assert_line_key(line_key)
|
||
project, revision = _revision_context(db, current, project_id, module, write=True)
|
||
biz.delete_line(db, revision, f"{module}.{line_key}", line_id, current.account)
|
||
snapshot = biz.current_snapshot(db, revision)
|
||
db.commit()
|
||
return ok({"deleted": True, "snapshot": biz.snapshot_payload(snapshot)})
|
||
|
||
|
||
@router.post("/{module}/projects/{project_id}/calculate")
|
||
def calculate(module: str, project_id: int, db: DbSession, current: PrincipalOf) -> dict[str, Any]:
|
||
"""计算预览。前端字段变化时调它,浏览器不自己算(``TO-BE-REACT-002``)。"""
|
||
_module_or_404(module)
|
||
project, revision = _revision_context(db, current, project_id, module)
|
||
snapshot = biz.recompute(db, revision, current.account, trigger="preview",
|
||
persist_projection=revision.status == RevisionStatus.DRAFT)
|
||
db.commit()
|
||
return ok(biz.snapshot_payload(snapshot))
|
||
|
||
|
||
@router.get("/{module}/projects/{project_id}/snapshots")
|
||
def list_snapshots(module: str, project_id: int, db: DbSession, current: PrincipalOf,
|
||
revisionId: int | None = None, limit: int = Query(20, ge=1, le=100)) -> dict[str, Any]:
|
||
_module_or_404(module)
|
||
assert_project_visible(db, current, project_id, module=module)
|
||
statement = select(CalcSnapshot).where(CalcSnapshot.project_id == project_id,
|
||
CalcSnapshot.module == module)
|
||
if revisionId:
|
||
statement = statement.where(CalcSnapshot.revision_id == revisionId)
|
||
rows = db.execute(statement.order_by(CalcSnapshot.id.desc()).limit(limit)).scalars().all()
|
||
return ok([{"id": row.id, "revisionId": row.revision_id, "calcVersion": row.calc_version,
|
||
"trigger": row.trigger, "accountName": row.account_name,
|
||
"createdAt": row.created_at.isoformat(sep=" ", timespec="seconds")} for row in rows])
|
||
|
||
|
||
@router.get("/{module}/snapshots/{snapshot_id}")
|
||
def get_snapshot(module: str, snapshot_id: int, db: DbSession, current: PrincipalOf) -> dict[str, Any]:
|
||
"""审批页与对账页读快照的入口:给一个 id,拿到当时那份完整结果。"""
|
||
_module_or_404(module)
|
||
snapshot = db.get(CalcSnapshot, snapshot_id)
|
||
if snapshot is None or snapshot.module != module:
|
||
raise not_found("快照不存在")
|
||
assert_project_visible(db, current, snapshot.project_id, module=module)
|
||
return ok({"id": snapshot.id, "calcVersion": snapshot.calc_version, "trigger": snapshot.trigger,
|
||
"payload": biz.snapshot_payload(snapshot),
|
||
"createdAt": snapshot.created_at.isoformat(sep=" ", timespec="seconds")})
|
||
|
||
|
||
@router.post("/{module}/projects/{project_id}/submit")
|
||
def submit(module: str, project_id: int, body: SubmitBody, db: DbSession,
|
||
current: PrincipalOf) -> dict[str, Any]:
|
||
"""送审:卡必填 -> 强制重算 -> 冻结 -> 起流程。"""
|
||
_module_or_404(module)
|
||
project, revision = _revision_context(db, current, project_id, module, write=True)
|
||
if revision.status == RevisionStatus.REVIEWING:
|
||
raise conflict("already_reviewing", "该版本已经在审批中")
|
||
|
||
# 立项送审先卡立项表必填:截图里那十来栏全是必填,缺一项就退回去,
|
||
# 别让审批人批一张连客户都没填的立项单。预算侧不卡——那是立项的表。
|
||
if module == RevisionModule.ESTIMATE:
|
||
missing = biz.initiation_missing_fields(project)
|
||
if missing:
|
||
raise bad_request(
|
||
"initiation_incomplete",
|
||
f"立项表还有 {len(missing)} 项必填没填完",
|
||
{"issues": [{"field": item["field"],
|
||
"message": f"立项表必填项「{item['label']}」还没填"} for item in missing]},
|
||
)
|
||
|
||
snapshot = biz.recompute(db, revision, current.account, trigger="submit")
|
||
payload = biz.snapshot_payload(snapshot)
|
||
validation = payload.get("validation") or {}
|
||
blocking = validation.get("errors") or []
|
||
if blocking:
|
||
# 校验不通过就把结构化错误原样抛回去,前端能在对应段落上标红
|
||
raise bad_request("validation_failed", "送审前还有 "
|
||
f"{len(blocking)} 项校验没有通过", {"issues": blocking})
|
||
|
||
# 冻结送审时刻的关键数据:审批人看的永远是这一份,之后改草稿不影响在途审批
|
||
revision.freeze_json = json.dumps({
|
||
"submittedProjectName": project.name,
|
||
"contractAmount": payload.get("contract_amount"),
|
||
"profit": payload.get("profit"),
|
||
"calcVersion": payload.get("calc_version"),
|
||
}, ensure_ascii=False)
|
||
|
||
instance = approval_engine.submit(
|
||
db,
|
||
module=module,
|
||
project=project,
|
||
revision=revision,
|
||
snapshot_id=snapshot.id,
|
||
submitter=current.account,
|
||
variables={
|
||
"contract_amount": float(_num(payload.get("contract_amount"))),
|
||
"contribution_profit_rate": float(_num(
|
||
((payload.get("profit") or {}).get("contribution_rate") or {}).get("value") or 0)),
|
||
"income_total": float(_num((payload.get("profit") or {}).get("income_total"))),
|
||
},
|
||
comment=body.comment,
|
||
self_selected=body.selfSelected or None,
|
||
)
|
||
|
||
if module == RevisionModule.BUDGET:
|
||
biz.set_project_stage(db, project, ProjectStage.S3_BUDGET, current.account, "提交预算审批")
|
||
db.commit()
|
||
return ok({
|
||
"instanceId": instance.id,
|
||
"status": instance.status,
|
||
"currentNode": instance.current_node_name,
|
||
"revision": _revision_view(db, revision),
|
||
})
|
||
|
||
|
||
def _num(value: Any) -> Any:
|
||
try:
|
||
return float(str(value or 0))
|
||
except (TypeError, ValueError):
|
||
return 0.0
|
||
|
||
|
||
@router.post("/{module}/projects/{project_id}/new-version")
|
||
def new_version(module: str, project_id: int, db: DbSession, current: PrincipalOf) -> dict[str, Any]:
|
||
"""显式基于最新版开新版本(已通过之后再改就走这里)。"""
|
||
_module_or_404(module)
|
||
project, _existing = _revision_context(db, current, project_id, module, write=True)
|
||
latest = db.execute(
|
||
select(Revision).where(Revision.project_id == project_id, Revision.module == module,
|
||
Revision.is_deleted.is_(False)).order_by(Revision.version.desc()).limit(1)
|
||
).scalars().first()
|
||
if latest is None or latest.status not in RevisionStatus.EFFECTIVE:
|
||
raise conflict("no_base", "只有已批准的版本才能派生新版本;草稿直接编辑即可")
|
||
revision = biz.get_or_create_revision(db, project_id, module, current.account)
|
||
biz.recompute(db, revision, current.account, trigger="edit")
|
||
db.commit()
|
||
return ok({"revision": _revision_view(db, revision)})
|
||
|
||
|
||
@router.get("/{module}/projects/{project_id}/approval")
|
||
def approval_of(module: str, project_id: int, db: DbSession, current: PrincipalOf) -> dict[str, Any]:
|
||
"""项目详情里的"审核记录":按模块取最近若干次审批实例与流水。"""
|
||
_module_or_404(module)
|
||
assert_project_visible(db, current, project_id, module=module)
|
||
from ..models import ApprovalInstance, ApprovalRecord
|
||
|
||
instances = db.execute(
|
||
select(ApprovalInstance).where(ApprovalInstance.project_id == project_id,
|
||
ApprovalInstance.business_module == module)
|
||
.order_by(ApprovalInstance.id.desc()).limit(10)
|
||
).scalars().all()
|
||
if not instances:
|
||
return ok({"instances": [], "records": []})
|
||
|
||
ids = [row.id for row in instances]
|
||
records = db.execute(
|
||
select(ApprovalRecord).where(ApprovalRecord.instance_id.in_(ids)).order_by(ApprovalRecord.id)
|
||
).scalars().all()
|
||
return ok({
|
||
"instances": [{
|
||
"id": row.id, "status": row.status, "flowName": row.flow_name,
|
||
"submitterName": row.submitter_name, "currentNode": row.current_node_name,
|
||
"revisionId": row.revision_id, "snapshotId": row.snapshot_id,
|
||
"submittedAt": row.submitted_at.isoformat(sep=" ", timespec="seconds"),
|
||
"finishedAt": row.finished_at.isoformat(sep=" ", timespec="seconds") if row.finished_at else "",
|
||
} for row in instances],
|
||
"records": [{
|
||
"id": row.id, "instanceId": row.instance_id, "nodeName": row.node_name,
|
||
"action": row.action, "actionLabel": row.action_label,
|
||
"operatorName": row.operator_name, "targetNames": row.target_names,
|
||
"comment": row.comment, "rollbackToNode": row.rollback_to_node,
|
||
"createdAt": row.created_at.isoformat(sep=" ", timespec="seconds"),
|
||
} for row in records],
|
||
})
|