"""项目计划:阶段推进板、里程碑、WBS 分解。 这三样从前都不存在——项目上只有一个 ``stage`` 整数和一段"当前进度描述",于是 "这个项目走到哪了"只能靠人写小作文。现在拆成三层各管一件事: * **阶段**(``project.stage``):公司统一口径的 S0..S8,一次只能在一个阶段上,推进留流水。 * **里程碑**:这个项目上要盯的几个日子,可以有多个,可逾期。 * **WBS**:怎么把活拆开、谁做、做到几成,一棵树。 阶段板 :func:`stage_board` 刻意不新造一张"阶段表":口径仍然只有一份(``ProjectStage``), 板子只是把项目按 stage 摊开看,避免又长出一个会和 ``stage`` 漂移的字段。 """ from __future__ import annotations from datetime import date, datetime from typing import Any from fastapi import APIRouter from pydantic import BaseModel, Field from sqlalchemy import func, select from .. import dicts as dict_store from ..deps import DbSession, PrincipalOf, assert_project_visible from ..envelope import conflict, forbidden, not_found, ok from ..models import ( Account, MilestoneStatus, Project, ProjectMilestone, ProjectStage, ProjectStageEvent, ProjectStageLog, WbsTask, WbsTaskStatus, to_decimal, ) from ..service import biz from ..service.calc.money import money_str router = APIRouter(prefix="/plan", tags=["plan"]) WRITE_CODES = { "milestone": "project:milestone:edit", "wbs": "project:wbs:edit", "stage": "project:stage:edit", } def _t(value: datetime | None) -> str: return value.isoformat(sep=" ", timespec="seconds") if value else "" def _d(value: date | None) -> str: return value.isoformat() if value else "" def _today() -> date: return date.today() def _require(current: PrincipalOf, kind: str, write: bool = True) -> None: code = WRITE_CODES[kind] if write else f"{WRITE_CODES[kind][:-5]}:view" if not current.permission.can(code): raise forbidden(f"缺少权限:{code}") def _account_name(db, account_id: int | None, fallback: str = "") -> str: if not account_id: return fallback account = db.get(Account, account_id) if account is None: return fallback return account.display_name or account.account or fallback # --------------------------------------------------------------------------- # 阶段板 # --------------------------------------------------------------------------- @router.get("/stage-board") def stage_board(db: DbSession, current: PrincipalOf, onlyMine: bool = False) -> dict[str, Any]: """按项目阶段摊开的项目看板:每个阶段多少个项目、哪些项目。 数据权限和 :func:`app.api.projects.list_projects` 完全同一条 :func:`evaluate`, 所以不会出现"列表看不见的项目在看板上数得出来"。 """ from ..service.data_scope import evaluate _require(current, "stage", write=False) decision = evaluate(db, "project", current.scope) statement = select(Project).where(Project.is_deleted.is_(False)) statement = decision.apply_to(statement) if onlyMine: from sqlalchemy import or_ from ..models import ProjectMember statement = statement.where(or_( Project.creator_id == current.account.id, Project.principal_id == current.account.id, Project.id.in_(select(ProjectMember.project_id).where( ProjectMember.account_id == current.account.id)), )) rows = db.execute(statement.order_by(Project.stage, Project.updated_at.desc())).scalars().all() buckets: dict[int, list[dict[str, Any]]] = {} for row in rows: buckets.setdefault(int(row.stage or 0), []).append({ "id": row.id, "name": row.name, "projectNo": row.project_no, "principal": row.principal, "orgUnitName": row.org_unit_name, "contractAmount": money_str(row.contract_amount), "updatedAt": _t(row.updated_at), "stageRemark": row.stage_remark, }) stages = [{ "stage": stage, "stageLabel": dict_store.label(db, "projectStage", stage, ProjectStage.LABELS[stage]), "count": len(buckets.get(stage, [])), "items": buckets.get(stage, [])[:50], } for stage in ProjectStage.LABELS] return ok({"stages": stages, "scope": decision.to_dict(), "total": len(rows)}) class StageAdvanceBody(BaseModel): stage: int remark: str = "" @router.post("/projects/{project_id}/stage") def advance_stage(project_id: int, body: StageAdvanceBody, db: DbSession, current: PrincipalOf) -> dict[str, Any]: """推进阶段。写 ``project.stage`` 与流水,和 ``POST /projects/{id}/stage`` 同一套落库。""" _require(current, "stage") project = assert_project_visible(db, current, project_id) if body.stage not in ProjectStage.LABELS: raise conflict("unknown_stage", f"未知的项目阶段:{body.stage}") pending = db.execute( select(func.count(ProjectStageEvent.id)).where( ProjectStageEvent.project_id == project_id, ProjectStageEvent.stage == project.stage, ProjectStageEvent.done.is_(False), ) ).scalar() or 0 if pending: raise conflict("stage_items_open", f"当前阶段还有 {pending} 项检查项没勾完,先勾完或把它删掉再推进") biz.set_project_stage(db, project, body.stage, current.account, body.remark) db.commit() return ok({"stage": body.stage, "stageLabel": dict_store.label(db, "projectStage", body.stage, ProjectStage.LABELS[body.stage])}) # --------------------------------------------------------------------------- # 阶段检查项 # --------------------------------------------------------------------------- class StageItemBody(BaseModel): stage: int | None = None name: str = Field(default="", max_length=255) done: bool | None = None ownerName: str = "" dueDate: str = "" remark: str = "" sort: int | None = None def _stage_item_view(db, row: ProjectStageEvent) -> dict[str, Any]: return {"id": row.id, "stage": row.stage, "stageLabel": dict_store.label(db, "projectStage", row.stage, str(row.stage)), "name": row.name, "done": bool(row.done), "ownerName": row.owner_name, "dueDate": _d(row.due_date), "remark": row.remark, "sort": row.sort} @router.get("/projects/{project_id}/stage-items") def list_stage_items(project_id: int, db: DbSession, current: PrincipalOf, stage: int | None = None) -> dict[str, Any]: _require(current, "stage", write=False) assert_project_visible(db, current, project_id) statement = select(ProjectStageEvent).where(ProjectStageEvent.project_id == project_id) if stage is not None: statement = statement.where(ProjectStageEvent.stage == stage) rows = db.execute(statement.order_by(ProjectStageEvent.sort, ProjectStageEvent.id) ).scalars().all() return ok([_stage_item_view(db, row) for row in rows]) @router.post("/projects/{project_id}/stage-items") def create_stage_item(project_id: int, body: StageItemBody, db: DbSession, current: PrincipalOf) -> dict[str, Any]: _require(current, "stage") project = assert_project_visible(db, current, project_id) if not body.name.strip(): raise conflict("name_required", "检查项名称不能为空") row = ProjectStageEvent( project_id=project_id, stage=body.stage if body.stage in ProjectStage.LABELS else project.stage, name=body.name.strip(), owner_name=_account_name(db, None, body.ownerName), due_date=_date(body.dueDate), remark=body.remark, sort=body.sort if body.sort is not None else 100, ) db.add(row) db.commit() return ok({"id": row.id}) @router.put("/stage-items/{item_id}") def update_stage_item(item_id: int, body: StageItemBody, db: DbSession, current: PrincipalOf) -> dict[str, Any]: _require(current, "stage") row = db.get(ProjectStageEvent, item_id) if row is None: raise not_found("检查项不存在") assert_project_visible(db, current, row.project_id) if body.stage in ProjectStage.LABELS: row.stage = body.stage if body.name.strip(): row.name = body.name.strip() if body.done is not None: row.done = body.done if body.ownerName: row.owner_name = body.ownerName if body.dueDate is not None: row.due_date = _date(body.dueDate) if body.remark: row.remark = body.remark if body.sort is not None: row.sort = body.sort db.commit() return ok(_stage_item_view(db, row)) @router.delete("/stage-items/{item_id}") def delete_stage_item(item_id: int, db: DbSession, current: PrincipalOf) -> dict[str, Any]: _require(current, "stage") row = db.get(ProjectStageEvent, item_id) if row is None: raise not_found("检查项不存在") assert_project_visible(db, current, row.project_id) db.delete(row) db.commit() return ok({"deleted": True}) # --------------------------------------------------------------------------- # 里程碑 # --------------------------------------------------------------------------- class MilestoneBody(BaseModel): name: str = Field(default="", max_length=255) stage: int | None = None planDate: str = "" actualDate: str = "" ownerId: int | None = None amount: str = "" receivePoint: str = "" status: str = "" remark: str = "" sort: int | None = None def _date(value: str | None) -> date | None: if not value: return None try: return date.fromisoformat(value.strip()[:10]) except ValueError: return None def _milestone_view(db, row: ProjectMilestone) -> dict[str, Any]: status = row.status if status != MilestoneStatus.DONE and row.plan_date and row.plan_date < _today(): status = MilestoneStatus.OVERDUE return { "id": row.id, "projectId": row.project_id, "name": row.name, "stage": row.stage, "stageLabel": dict_store.label(db, "projectStage", row.stage, "") if row.stage else "", "planDate": _d(row.plan_date), "actualDate": _d(row.actual_date), "ownerId": row.owner_id, "ownerName": row.owner_name, "amount": money_str(row.amount), "receivePoint": row.receive_point, "status": status, "statusLabel": dict_store.label(db, "milestoneStatus", status, MilestoneStatus.LABELS.get(status, status)), "overdue": status == MilestoneStatus.OVERDUE, "remark": row.remark, "sort": row.sort, "createdAt": _t(row.created_at), } @router.get("/projects/{project_id}/milestones") def list_milestones(project_id: int, db: DbSession, current: PrincipalOf) -> dict[str, Any]: _require(current, "milestone", write=False) assert_project_visible(db, current, project_id) rows = db.execute( select(ProjectMilestone) .where(ProjectMilestone.project_id == project_id, ProjectMilestone.is_deleted.is_(False)) .order_by(ProjectMilestone.plan_date.is_(None), ProjectMilestone.plan_date, ProjectMilestone.sort) ).scalars().all() items = [_milestone_view(db, row) for row in rows] return ok({ "items": items, "summary": { "total": len(items), "done": sum(1 for item in items if item["status"] == MilestoneStatus.DONE), "overdue": sum(1 for item in items if item["overdue"]), }, }) @router.get("/milestones") def list_all_milestones(db: DbSession, current: PrincipalOf, keyword: str = "", status: str = "", pageNo: int = 1, pageSize: int = 50) -> dict[str, Any]: """跨项目的里程碑台账:逾期在前、按计划日期排。""" from sqlalchemy import or_ from ..service.data_scope import evaluate _require(current, "milestone", write=False) visible = evaluate(db, "project", current.scope).apply_to( select(Project.id).where(Project.is_deleted.is_(False))) visible_ids = [row[0] for row in db.execute(visible).all()] if not visible_ids: return ok({"items": [], "total": 0}) statement = select(ProjectMilestone).where( ProjectMilestone.project_id.in_(visible_ids), ProjectMilestone.is_deleted.is_(False)) if keyword: like = f"%{keyword}%" statement = statement.where(or_(ProjectMilestone.name.like(like), ProjectMilestone.receive_point.like(like))) rows = db.execute(statement.order_by(ProjectMilestone.plan_date.is_(None), ProjectMilestone.plan_date)).scalars().all() projects = dict(db.execute(select(Project.id, Project.name, Project.project_no) .where(Project.id.in_(visible_ids))).all()) items = [] for row in rows: item = _milestone_view(db, row) name_no = projects.get(row.project_id, ("", "")) item["projectName"], item["projectNo"] = name_no[0], name_no[1] items.append(item) if status == "overdue": items = [item for item in items if item["overdue"]] elif status == "open": items = [item for item in items if item["status"] != MilestoneStatus.DONE] # 逾期顶到最前:跨项目台账上真正要人动手的就是这几条 items.sort(key=lambda item: (not item["overdue"], item["planDate"] or "9999-12-31")) start = (max(pageNo, 1) - 1) * pageSize return ok({"items": items[start:start + pageSize], "total": len(items)}) @router.post("/projects/{project_id}/milestones") def create_milestone(project_id: int, body: MilestoneBody, db: DbSession, current: PrincipalOf) -> dict[str, Any]: _require(current, "milestone") assert_project_visible(db, current, project_id) if not body.name.strip(): raise conflict("name_required", "里程碑名称不能为空") row = ProjectMilestone( project_id=project_id, name=body.name.strip(), stage=body.stage, plan_date=_date(body.planDate), actual_date=_date(body.actualDate), owner_id=body.ownerId, owner_name=_account_name(db, body.ownerId), amount=to_decimal(body.amount or 0), receive_point=body.receivePoint, status=body.status if body.status in MilestoneStatus.LABELS else MilestoneStatus.PENDING, remark=body.remark, sort=body.sort if body.sort is not None else 100, ) db.add(row) db.commit() return ok({"id": row.id}) @router.put("/milestones/{milestone_id}") def update_milestone(milestone_id: int, body: MilestoneBody, db: DbSession, current: PrincipalOf) -> dict[str, Any]: _require(current, "milestone") row = db.get(ProjectMilestone, milestone_id) if row is None or row.is_deleted: raise not_found("里程碑不存在") assert_project_visible(db, current, row.project_id) if body.name.strip(): row.name = body.name.strip() if body.stage is not None: row.stage = body.stage if body.planDate is not None and body.planDate != "": row.plan_date = _date(body.planDate) if body.actualDate is not None and body.actualDate != "": row.actual_date = _date(body.actualDate) if body.ownerId is not None: row.owner_id = body.ownerId row.owner_name = _account_name(db, body.ownerId) if body.amount != "": row.amount = to_decimal(body.amount or 0) if body.receivePoint is not None: row.receive_point = body.receivePoint if body.status in MilestoneStatus.LABELS: row.status = body.status # 勾成已完成却没写日期时补今天,否则台账上"已完成但没有完成时间"没法复盘 if body.status == MilestoneStatus.DONE and row.actual_date is None: row.actual_date = _today() if body.remark is not None: row.remark = body.remark if body.sort is not None: row.sort = body.sort db.commit() return ok(_milestone_view(db, row)) @router.delete("/milestones/{milestone_id}") def delete_milestone(milestone_id: int, db: DbSession, current: PrincipalOf) -> dict[str, Any]: _require(current, "milestone") row = db.get(ProjectMilestone, milestone_id) if row is None or row.is_deleted: raise not_found("里程碑不存在") assert_project_visible(db, current, row.project_id) row.is_deleted = True db.commit() return ok({"deleted": True}) # --------------------------------------------------------------------------- # WBS # --------------------------------------------------------------------------- class WbsBody(BaseModel): name: str = Field(default="", max_length=255) parentId: int | None = None milestoneId: int | None = None ownerId: int | None = None planStart: str = "" planEnd: str = "" actualStart: str = "" actualEnd: str = "" weight: str = "" progress: int | None = None status: str = "" budgetAmount: str = "" actualAmount: str = "" remark: str = "" def _wbs_code(db, parent: WbsTask | None, sibling_index: int) -> str: if parent is None: return str(sibling_index) return f"{parent.code or '1'}.{sibling_index}" def _wbs_view(row: WbsTask, rollup: dict[int, dict[str, Any]] | None = None) -> dict[str, Any]: data = { "id": row.id, "projectId": row.project_id, "parentId": row.parent_id, "code": row.code, "name": row.name, "level": row.level, "path": row.path, "milestoneId": row.milestone_id, "ownerId": row.owner_id, "ownerName": row.owner_name, "planStart": _d(row.plan_start), "planEnd": _d(row.plan_end), "actualStart": _d(row.actual_start), "actualEnd": _d(row.actual_end), "weight": f"{row.weight}", "progress": row.progress, "status": row.status, "statusLabel": WbsTaskStatus.LABELS.get(row.status, row.status), "budgetAmount": money_str(row.budget_amount), "actualAmount": money_str(row.actual_amount), "remark": row.remark, "sort": row.sort, } data.update((rollup or {}).get(row.id, {})) return data def _rollup(rows: list[WbsTask]) -> dict[int, dict[str, Any]]: """子树汇总:进度按权重加权、金额直接相加、完成数数叶子。 只存一份"自身进度",汇总读时算——存两份迟早会有一份没人更新,那比没有更难看。 """ children: dict[int | None, list[WbsTask]] = {} for row in rows: children.setdefault(row.parent_id, []).append(row) def descendants(task_id: int) -> list[WbsTask]: out: list[WbsTask] = [] for child in children.get(task_id, []): out.append(child) out.extend(descendants(child.id)) return out out: dict[int, dict[str, Any]] = {} for row in rows: subtree = descendants(row.id) if subtree: weights = [to_decimal(child.weight or 1) for child in subtree] total_weight = sum(weights) or to_decimal(1) progress = sum((to_decimal(child.progress) * weight for child, weight in zip(subtree, weights)), to_decimal(0)) / total_weight else: progress = to_decimal(row.progress) out[row.id] = { "rollupProgress": f"{progress:.1f}", "childCount": len(children.get(row.id, [])), "descendantCount": len(subtree), "budgetRollup": money_str(sum((child.budget_amount for child in subtree), to_decimal(0)) + row.budget_amount), "actualRollup": money_str(sum((child.actual_amount for child in subtree), to_decimal(0)) + row.actual_amount), "doneCount": sum(1 for child in subtree if child.status == WbsTaskStatus.DONE), "isLeaf": not children.get(row.id), } return out @router.get("/projects/{project_id}/wbs") def list_wbs(project_id: int, db: DbSession, current: PrincipalOf) -> dict[str, Any]: _require(current, "wbs", write=False) assert_project_visible(db, current, project_id) rows = db.execute( select(WbsTask).where(WbsTask.project_id == project_id, WbsTask.is_deleted.is_(False)) .order_by(WbsTask.path, WbsTask.sort, WbsTask.id) ).scalars().all() rollup = _rollup(list(rows)) items = [_wbs_view(row, rollup) for row in rows] tops = [item for item in items if not item["parentId"]] summary = { "tasks": len(items), "done": sum(1 for item in items if item["status"] == WbsTaskStatus.DONE), "blocked": sum(1 for item in items if item["status"] == WbsTaskStatus.BLOCKED), "budget": money_str(sum((row.budget_amount for row in rows), to_decimal(0))), "actual": money_str(sum((row.actual_amount for row in rows), to_decimal(0))), "progress": tops[0]["rollupProgress"] if tops and len(tops) == 1 else (f"{sum(float(item['rollupProgress']) for item in tops) / len(tops):.1f}" if tops else "0.0"), } return ok({"items": items, "summary": summary}) @router.post("/projects/{project_id}/wbs") def create_wbs(project_id: int, body: WbsBody, db: DbSession, current: PrincipalOf) -> dict[str, Any]: _require(current, "wbs") assert_project_visible(db, current, project_id) if not body.name.strip(): raise conflict("name_required", "任务名称不能为空") parent: WbsTask | None = None if body.parentId: parent = db.get(WbsTask, body.parentId) if parent is None or parent.project_id != project_id: raise not_found("父任务不存在") siblings = db.execute( select(func.count(WbsTask.id)).where( WbsTask.project_id == project_id, WbsTask.is_deleted.is_(False), WbsTask.parent_id == (parent.id if parent else None)) ).scalar() or 0 row = WbsTask( project_id=project_id, parent_id=parent.id if parent else None, level=(parent.level + 1) if parent else 1, code=_wbs_code(db, parent, int(siblings) + 1), name=body.name.strip(), milestone_id=body.milestoneId, owner_id=body.ownerId, owner_name=_account_name(db, body.ownerId), plan_start=_date(body.planStart), plan_end=_date(body.planEnd), actual_start=_date(body.actualStart), actual_end=_date(body.actualEnd), weight=to_decimal(body.weight or 1), progress=body.progress or 0, status=body.status if body.status in WbsTaskStatus.LABELS else WbsTaskStatus.NOT_STARTED, budget_amount=to_decimal(body.budgetAmount or 0), actual_amount=to_decimal(body.actualAmount or 0), remark=body.remark, sort=(int(siblings) + 1) * 10, ) db.add(row) db.flush() row.path = f"{parent.path if parent else '/'}{row.id}/" db.commit() return ok({"id": row.id, "code": row.code, "path": row.path}) @router.put("/wbs/{task_id}") def update_wbs(task_id: int, body: WbsBody, db: DbSession, current: PrincipalOf) -> dict[str, Any]: _require(current, "wbs") row = db.get(WbsTask, task_id) if row is None or row.is_deleted: raise not_found("任务不存在") assert_project_visible(db, current, row.project_id) if body.name.strip(): row.name = body.name.strip() if body.milestoneId is not None: row.milestone_id = body.milestoneId if body.ownerId is not None: row.owner_id = body.ownerId row.owner_name = _account_name(db, body.ownerId) for text, column in ((body.planStart, "plan_start"), (body.planEnd, "plan_end"), (body.actualStart, "actual_start"), (body.actualEnd, "actual_end")): if text: setattr(row, column, _date(text)) if body.weight: row.weight = to_decimal(body.weight) if body.progress is not None: row.progress = max(0, min(100, int(body.progress))) if row.progress >= 100 and body.status not in WbsTaskStatus.LABELS: row.status = WbsTaskStatus.DONE if body.status in WbsTaskStatus.LABELS: row.status = body.status if body.budgetAmount != "": row.budget_amount = to_decimal(body.budgetAmount or 0) if body.actualAmount != "": row.actual_amount = to_decimal(body.actualAmount or 0) if body.remark is not None: row.remark = body.remark db.commit() return ok(_wbs_view(row)) @router.delete("/wbs/{task_id}") def delete_wbs(task_id: int, db: DbSession, current: PrincipalOf) -> dict[str, Any]: """删任务连同子树一起软删:留一堆父节点已没了的孤儿子在树上,界面上没法摆。""" _require(current, "wbs") row = db.get(WbsTask, task_id) if row is None or row.is_deleted: raise not_found("任务不存在") assert_project_visible(db, current, row.project_id) subtree = db.execute( select(WbsTask).where(WbsTask.project_id == row.project_id, WbsTask.is_deleted.is_(False), WbsTask.path.like(f"{row.path}%")) ).scalars().all() for item in subtree: item.is_deleted = True db.commit() return ok({"deleted": True, "count": len(subtree)})