"""项目主档:列表、详情、创建、成员、阶段、删除与恢复。 列表一律先过数据权限再分页,计数也用同一个条件,否则会出现"总数 500 但只列得出来 3 条"。 """ from __future__ import annotations from datetime import date, datetime from typing import Any from fastapi import APIRouter, Query, Request from pydantic import BaseModel, Field from sqlalchemy import func, or_, select from .. import dicts as dict_store from ..deps import DbSession, Principal, PrincipalOf, assert_project_visible from ..envelope import conflict, forbidden, not_found, ok, page from ..models import ( Account, ApprovalInstance, ApprovalRecord, Attachment, BudgetFundMonth, BudgetIncomeLine, BudgetIncomePlanLine, BudgetManageLine, BudgetOtherCostLine, BudgetPayPlanLine, BudgetPurchaseLine, CalcSnapshot, EstimateCostLine, EstimateIncomeLine, EstimateOtherLine, InstanceStatus, Project, ProjectMember, ProjectMemberRole, ProjectSource, ProjectStage, ProjectStageLog, SaleStage, ProjectVisibleRole, Revision, RevisionModule, RevisionStatus, to_decimal, ) from ..service import audit, biz from ..service.calc.money import money_str router = APIRouter(prefix="/projects", tags=["projects"]) class ProjectBody(BaseModel): name: str = Field(min_length=1, max_length=1000) otherName: str = "" type: int = 0 projectNo: str = "" customer: str = "" terminalCustomer: str = "" planStart: str = "" planEnd: str = "" contractTime: str = "" bidsTime: str = "" underwrittenMode: int | None = None cooperateType: int | None = None collaborator: str = "" certainty: int | None = None isSecond: int | None = None isHuizhiBid: int | None = None saleStage: int | None = None stage: int | None = None signType: int | None = None resolvePlan: int | None = None industryScene: int = 0 industrySceneDesc: str = "" principalId: int | None = None mainContractCollectionTerms: str = "" mainContractResolvePlan: str = "" calculationCollection: str = "" valueRisk: str = "" advanceInterestRate: str = "" stageRemark: str = "" nextPlan: str = "" memberIds: list[int] = Field(default_factory=list) # 立项表上可以直接录入的金额。录了测算明细之后,这几个数改由计算投影覆盖 # (见 biz.apply_projection:有明细行才投影),手填值只在没明细时生效。 contractAmount: str = "" grossProfit: str = "" grossProfitRate: str = "" huizhiAmount: str = "" huazhiAmount: str = "" h3cAmount: str = "" otherProductAmount: str = "" class MemberBody(BaseModel): accountIds: list[int] = Field(default_factory=list) memberRole: str = ProjectMemberRole.PARTICIPANT @router.get("") def list_projects( db: DbSession, current: PrincipalOf, keyword: str = "", type: int | None = None, stage: int | None = None, orgUnitId: int | None = None, underwrittenMode: int | None = None, initiationStatus: str = "", onlyMine: bool = False, deletedOnly: bool = False, pageNo: int = Query(1, ge=1), pageSize: int = Query(20, ge=1, le=200), orderBy: str = "-updated_at", ) -> dict[str, Any]: if not current.permission.can_any(("project:project:view", "project:project:edit")): raise forbidden("缺少权限:project:project:view") from ..service.data_scope import descendant_unit_ids, evaluate # deletedOnly 是回收站:同一个数据权限条件,只把"有效/已删除"这一维翻过来, # 不能因为换了个视图就让人看到别人删掉的项目。 statement = select(Project).where( Project.is_deleted.is_(True) if deletedOnly else Project.is_deleted.is_(False) ) decision = evaluate(db, "project", current.scope) statement = decision.apply_to(statement) if keyword: like = f"%{keyword}%" statement = statement.where(or_(Project.name.like(like), Project.project_no.like(like), Project.customer.like(like), Project.other_name.like(like))) if type is not None: statement = statement.where(Project.type == type) if stage is not None: statement = statement.where(Project.stage == stage) if orgUnitId: statement = statement.where(Project.org_unit_id.in_(descendant_unit_ids(db, [orgUnitId]))) if underwrittenMode is not None: statement = statement.where(Project.underwritten_mode == underwrittenMode) if onlyMine: 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)), )) if initiationStatus: # 两个模块列表共用这一条查询:立项列表看全部,预算列表看 approved。 # "none" 是还没建过立项版本的项目——老系统迁过来的八百多个项目就是这么一大片, # 新系统里它们算"还没立项",得能在界面上筛出来。 wanted = [item.strip() for item in initiationStatus.split(",") if item.strip()] if "none" in wanted: statement = statement.where(Project.id.notin_( select(Revision.project_id).where(Revision.module == RevisionModule.ESTIMATE, Revision.is_deleted.is_(False)))) else: statement = statement.where(Project.id.in_( select(Revision.project_id).where( Revision.module == RevisionModule.ESTIMATE, Revision.is_deleted.is_(False), Revision.status.in_([item for item in wanted if item != "none"])))) total = db.execute(select(func.count()).select_from(statement.subquery())).scalar() or 0 order_column = _order_column(orderBy) rows = db.execute(statement.order_by(order_column).offset((pageNo - 1) * pageSize).limit(pageSize) ).scalars().all() states = _initiation_states(db, [row.id for row in rows]) result = page([_project_view(db, row, states.get(row.id)) for row in rows], total, pageNo, pageSize) # 把"你看到的是哪个范围"一起返回,用户不用猜为什么少了几条 result["data"]["scope"] = decision.to_dict() return result def _order_column(order_by: str): mapping = { "updated_at": Project.updated_at, "created_at": Project.created_at, "contract_amount": Project.contract_amount, "project_no": Project.project_no, "contribution_profit_rate": Project.contribution_profit_rate, } descending = order_by.startswith("-") column = mapping.get(order_by.lstrip("-"), Project.updated_at) return column.desc() if descending else column.asc() def _s(value: Any) -> str: return money_str(value) def _t(value: datetime | None) -> str: return value.isoformat(sep=" ", timespec="seconds") if value else "" def _initiation_states(db, project_ids: list[int]) -> dict[int, dict[str, Any]]: """一次把这一页项目的立项状态捞回来。 逐行走 :func:`biz.initiation_state` 会变成每行两条 SQL,一页 20 行就是 40 条查询; 这里改成一条:把这一页项目的立项版本全捞出来,在内存里挑"最近一版"与"最近通过版"。 """ if not project_ids: return {} rows = db.execute( select(Revision.project_id, Revision.id, Revision.version, Revision.status, Revision.decided_at) .where(Revision.project_id.in_(project_ids), Revision.module == RevisionModule.ESTIMATE, Revision.is_deleted.is_(False)) .order_by(Revision.version.desc()) ).all() latest: dict[int, tuple] = {} approved: dict[int, tuple] = {} for row in rows: latest.setdefault(row.project_id, row) if row.status == RevisionStatus.APPROVED: approved.setdefault(row.project_id, row) out: dict[int, dict[str, Any]] = {} for project_id in project_ids: head, passed = latest.get(project_id), approved.get(project_id) out[project_id] = { "status": head.status if head else "", "statusLabel": dict_store.label(db, "revisionStatus", head.status, head.status) if head else "未立项", "version": head.version if head else 0, "revisionId": head.id if head else None, "approvedVersion": passed.version if passed else 0, "approvedRevisionId": passed.id if passed else None, "approvedAt": _t(passed.decided_at) if passed else "", "budgetReady": passed is not None, } return out def _project_view(db, row: Project, initiation: dict[str, Any] | None = None) -> dict[str, Any]: return { "id": row.id, "projectNo": row.project_no, "name": row.name, "otherName": row.other_name, "type": row.type, "stage": row.stage, "stageLabel": row.stage_label, "customer": row.customer, "terminalCustomer": row.terminal_customer, "orgUnitId": row.org_unit_id, "orgUnitName": row.org_unit_name, "creatorId": row.creator_id, "creatorName": row.creator_name, "principal": row.principal, "principalId": row.principal_id, "underwrittenMode": row.underwritten_mode, "contractAmount": _s(row.contract_amount), "grossProfitA": _s(row.gross_profit_a), "grossProfitARate": _s(row.gross_profit_a_rate), "grossProfit": _s(row.gross_profit), "grossProfitRate": _s(row.gross_profit_rate), "contributionProfit": _s(row.contribution_profit), "contributionProfitRate": _s(row.contribution_profit_rate), "advancePeakAmount": _s(row.advance_peak_value), "advancePeakMonth": row.advance_peak_month, "advanceInterestAmount": _s(row.advance_interest_amount), "calcVersion": row.calc_version, "source": row.source, "sourceLabel": ProjectSource.LABELS.get(row.source, row.source), "saleStage": row.sale_stage, "saleStageLabel": dict_store.label(db, "saleStage", row.sale_stage, "未填写"), "isHuizhiBid": row.is_huizhi_bid, "certainty": row.certainty, "certaintyLabel": dict_store.label(db, "certainty", row.certainty, ""), "industrySceneLabel": dict_store.label(db, "industryScene", row.industry_scene, ""), "initiation": initiation or {}, "createdAt": _t(row.created_at), "updatedAt": _t(row.updated_at), "deletedAt": _t(row.deleted_at), "deletedByName": row.deleted_by_name, "deleteReason": row.delete_reason, } def _project_detail(db, row: Project, initiation: dict[str, Any] | None = None) -> dict[str, Any]: data = _project_view(db, row, initiation) data.update({ "planStart": row.plan_start.isoformat() if row.plan_start else "", "planEnd": row.plan_end.isoformat() if row.plan_end else "", "contractTime": _t(row.contract_time), "bidsTime": _t(row.bids_time), "cooperateType": row.cooperate_type, "collaborator": row.collaborator, "collaboratorAttachment": row.collaborator_attachment, "certainty": row.certainty, "isSecond": row.is_second, "signType": row.sign_type, "isHuizhiBid": row.is_huizhi_bid, "saleStage": row.sale_stage, "saleStageLabel": dict_store.label(db, "saleStage", row.sale_stage, "未填写"), "certaintyLabel": dict_store.label(db, "certainty", row.certainty, ""), "isSecondLabel": dict_store.label(db, "yesNo", row.is_second, ""), "isHuizhiBidLabel": dict_store.label(db, "yesNo", row.is_huizhi_bid, ""), "industrySceneLabel": dict_store.label(db, "industryScene", row.industry_scene, ""), "grossProfit": _s(row.gross_profit), "grossProfitRate": _s(row.gross_profit_rate), "resolvePlan": row.resolve_plan, "industryScene": row.industry_scene, "industrySceneDesc": row.industry_scene_desc, "mainContractCollectionTerms": row.main_contract_collection_terms, "mainContractResolvePlan": row.main_contract_resolve_plan, "calculationCollection": row.calculation_collection, "valueRisk": row.value_risk, "stageRemark": row.stage_remark, "nextPlan": row.next_plan, "advanceInterestRate": _s(row.advance_interest_rate), "advancePlanTotal": _s(row.advance_plan_total), "huazhiAmount": _s(row.huazhi_amount), "huizhiAmount": _s(row.huizhi_amount), "h3cAmount": _s(row.h3c_amount), "otherProductAmount": _s(row.other_product_amount), "calcSnapshotId": row.calc_snapshot_id, "calcAt": _t(row.calc_at), }) return data @router.get("/options") def project_options(db: DbSession, current: PrincipalOf) -> dict[str, Any]: """项目类型/阶段/垫资模式这些枚举统一从数据字典取,前后端都不再自己抄一份。""" return ok({ "types": dict_store.options(db, "projectType"), "stages": dict_store.options(db, "projectStage"), "underwrittenModes": dict_store.options(db, "underwrittenMode"), "memberRoles": dict_store.options(db, "projectMemberRole"), "certainties": dict_store.options(db, "certainty"), "industryScenes": dict_store.options(db, "industryScene"), "saleStages": dict_store.options(db, "saleStage"), "yesNo": dict_store.options(db, "yesNo"), }) @router.post("") def create_project(body: ProjectBody, request: Request, db: DbSession, current: PrincipalOf) -> dict[str, Any]: if not current.permission.can("project:project:create"): raise forbidden("缺少权限:project:project:create") account = current.account unit = account.org_unit project = Project( name=body.name, other_name=body.otherName, type=body.type or 0, project_no=body.projectNo.strip() or next_project_no(db), creator_id=account.id, creator_name=account.display_name or account.account, org_unit_id=account.org_unit_id, org_unit_name=unit.name if unit else "", stage=body.stage if body.stage in ProjectStage.LABELS else ProjectStage.S0_INITIATION, customer=body.customer, terminal_customer=body.terminalCustomer, plan_start=_date(body.planStart), plan_end=_date(body.planEnd), contract_time=_datetime(body.contractTime), bids_time=_datetime(body.bidsTime), underwritten_mode=body.underwrittenMode, cooperate_type=body.cooperateType, collaborator=body.collaborator, certainty=body.certainty, is_second=body.isSecond, is_huizhi_bid=body.isHuizhiBid, sale_stage=body.saleStage if body.saleStage is not None else SaleStage.UNSET, sign_type=body.signType, resolve_plan=body.resolvePlan, industry_scene=body.industryScene or 0, industry_scene_desc=body.industrySceneDesc, principal_id=body.principalId or account.id, main_contract_collection_terms=body.mainContractCollectionTerms, main_contract_resolve_plan=body.mainContractResolvePlan, calculation_collection=body.calculationCollection, value_risk=body.valueRisk, advance_interest_rate=to_decimal(body.advanceInterestRate), stage_remark=body.stageRemark, next_plan=body.nextPlan, source=ProjectSource.LOCAL, ) _apply_manual_amounts(project, body) # 负责人没点名就是创建人:姓名与账号一起落,别只留 principal_id。 # 只留 id 会让主档上那一列一直是空串,立项表的"项目负责人"必填就永远卡着, # 列表页那列也是空的。 if not project.principal and project.principal_id: owner = account if project.principal_id == account.id else db.get(Account, project.principal_id) project.principal = (owner.display_name or owner.account) if owner else "" db.add(project) db.flush() # 负责人没点名就是创建人:姓名与账号一起落,别只留 principal_id—— # 主档那列空着,立项表的"项目负责人"必填就永远卡着,列表页这一列也是空的。 if project.principal_id and not project.principal: owner = account if project.principal_id == account.id else db.get(Account, project.principal_id) if owner is not None: project.principal = owner.display_name or owner.account # 负责人先落成员表(sync_owner_member 内部会去重),创建人只有在不是负责人时才另记一条, # 否则同一个人会被插两次,撞上 uk_project_member 唯一键。 biz.sync_owner_member(db, project) member_ids = {account.id} | set(body.memberIds or []) if project.principal_id: member_ids.add(project.principal_id) existing_members = {project.principal_id} if project.principal_id else set() for account_id in member_ids: if account_id in existing_members: continue target = account if account_id == account.id else db.get(Account, account_id) if target is None or target.is_deleted: continue db.add(ProjectMember(project_id=project.id, account_id=account_id, account_name=target.display_name or target.account, member_role=ProjectMemberRole.PARTICIPANT)) existing_members.add(account_id) db.add(ProjectStageLog(project_id=project.id, stage=project.stage, stage_label=project.stage_label, account_id=account.id, account_name=account.display_name or account.account, remark="创建项目")) db.commit() audit.enrich(request, object_name=project.name, projectNo=project.project_no) return ok({"id": project.id}) def next_project_no(db) -> str: """生成项目编号:``前缀 + 年份 + 当年四位流水``(例:FS26-0007)。 立项表上这一栏写的是"保存后默认提供",所以编号得在保存那一刻就有,不能指望 事后再补。取当年已有最大流水 +1,不锁表:两个人同时建项目撞上同一个号的概率 极低,真撞了 ``uk_project_no``……库里并没有这个唯一键,所以这里只做一次存在性 重试,比加表锁合适。 """ from ..models import SystemConfig prefix = (db.execute(select(SystemConfig.value).where( SystemConfig.code == "project.no_prefix")).scalars().first() or "FS").strip() or "FS" year = datetime.now().year head = f"{prefix}{year % 100:02d}-" like = f"{head}%" numbers = [int(no[len(head):]) for (no,) in db.execute( select(Project.project_no).where(Project.project_no.like(like)) ) if no[len(head):].isdigit()] candidate_index = (max(numbers) + 1) if numbers else 1 existing = {row[0] for row in db.execute( select(Project.project_no).where(Project.project_no.like(like))).all()} while f"{head}{candidate_index:04d}" in existing: candidate_index += 1 return f"{head}{candidate_index:04d}" def _apply_manual_amounts(project: Project, body: "ProjectBody") -> None: """立项表上手填的那几个金额。空串表示"这一栏没动",不是"清零"。""" pairs = ( (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"), ) for text, column in pairs: if text not in (None, ""): setattr(project, column, to_decimal(text)) def _date(value: str | None) -> date | None: if not value: return None try: text = value.strip() if len(text) == 7: # 日期选择器可能只给到月(YYYY-MM),补成当月 1 号 text += "-01" return date.fromisoformat(text[:10]) except ValueError: return None def _datetime(value: str | None) -> datetime | None: if not value: return None try: return datetime.fromisoformat(value.strip().replace("Z", "")) except ValueError: return None @router.get("/{project_id}") def get_project(project_id: int, db: DbSession, current: PrincipalOf) -> dict[str, Any]: project = assert_project_visible(db, current, project_id) members = db.execute(select(ProjectMember).where(ProjectMember.project_id == project_id) .order_by(ProjectMember.id)).scalars().all() stage_logs = db.execute(select(ProjectStageLog).where(ProjectStageLog.project_id == project_id) .order_by(ProjectStageLog.id.desc())).scalars().all() data = _project_detail(db, project, biz.initiation_state(db, project_id)) data["members"] = [{"id": row.id, "accountId": row.account_id, "accountName": row.account_name, "memberRole": row.member_role, "memberRoleLabel": dict_store.label( db, "projectMemberRole", row.member_role, row.member_role)} for row in members] data["stageLogs"] = [{"id": row.id, "stage": row.stage, "stageLabel": row.stage_label, "accountName": row.account_name, "remark": row.remark, "createdAt": _t(row.created_at)} for row in stage_logs] return ok(data) @router.put("/{project_id}") def update_project(project_id: int, body: ProjectBody, request: Request, db: DbSession, current: PrincipalOf) -> dict[str, Any]: project = assert_project_visible(db, current, project_id) if not current.permission.can("project:project:edit"): raise forbidden("缺少权限:project:project:edit") _assert_project_owner(current, project, "修改项目信息") project.name = body.name project.other_name = body.otherName project.type = body.type or project.type project.project_no = body.projectNo project.customer = body.customer project.terminal_customer = body.terminalCustomer project.plan_start = _date(body.planStart) project.plan_end = _date(body.planEnd) project.contract_time = _datetime(body.contractTime) project.bids_time = _datetime(body.bidsTime) project.underwritten_mode = body.underwrittenMode project.cooperate_type = body.cooperateType project.collaborator = body.collaborator project.certainty = body.certainty project.is_second = body.isSecond project.is_huizhi_bid = body.isHuizhiBid if body.saleStage is not None: project.sale_stage = body.saleStage if body.stage in ProjectStage.LABELS: project.stage = body.stage project.sign_type = body.signType project.resolve_plan = body.resolvePlan project.industry_scene = body.industryScene or 0 project.industry_scene_desc = body.industrySceneDesc project.main_contract_collection_terms = body.mainContractCollectionTerms project.main_contract_resolve_plan = body.mainContractResolvePlan project.calculation_collection = body.calculationCollection project.value_risk = body.valueRisk project.advance_interest_rate = to_decimal(body.advanceInterestRate) project.stage_remark = body.stageRemark project.next_plan = body.nextPlan _apply_manual_amounts(project, body) if body.principalId: project.principal_id = body.principalId owner = db.get(Account, body.principalId) project.principal = (owner.display_name or owner.account) if owner else project.principal biz.sync_owner_member(db, project) db.commit() audit.enrich(request, object_name=project.name, projectNo=project.project_no) return ok({"id": project.id}) # --------------------------------------------------------------------------- # 删除与恢复:软删除,回收站走同一条数据权限 # --------------------------------------------------------------------------- #: 合同期及其之后的阶段。删掉这一档的项目要额外提醒一句——合同、结算都挂在上面, #: 而"项目丢失"(S9) 虽然编号更靠后,恰恰是最该允许清掉的那类,所以不在这个名单里。 LATE_STAGES = (ProjectStage.S5_CONTRACT, ProjectStage.S6_DELIVERY, ProjectStage.S7_SETTLEMENT, ProjectStage.S8_FINAL) class DeleteBody(BaseModel): reason: str = Field(default="", max_length=500) def _assert_project_owner(current: Principal, project: Project, action: str) -> None: """主档级改动(改、删、恢复)的归属判定:系统管理员,或创建人、项目负责人。 数据权限管"看得见",这条管"动得了"——财务能看全公司项目,不等于能把别人的项目删掉。 """ if not (current.permission.is_system_admin or project.creator_id == current.account.id or project.principal_id == current.account.id): raise forbidden(f"只有创建人或项目负责人可以{action}") def _count(db, statement) -> int: return db.execute(statement).scalar() or 0 def _delete_report(db, project: Project) -> dict[str, Any]: """删除前的影响面清单。 只有**审批还在流转**这一条真挡删除:实例活着、待办挂在别人名下,项目一消失, 那些人手里就剩一条点不开的待办。已通过的版本、附件、历史审批都只是"连带藏起来", 恢复即全部回来,所以只列出来让人看清楚,不拦。 """ revision_statuses = db.execute( select(Revision.status).where(Revision.project_id == project.id, Revision.is_deleted.is_(False)) ).scalars().all() approved = sum(1 for status in revision_statuses if status == RevisionStatus.APPROVED) reviewing = _count(db, select(func.count(ApprovalInstance.id)).where( ApprovalInstance.project_id == project.id, ApprovalInstance.status == InstanceStatus.REVIEWING)) instances = _count(db, select(func.count(ApprovalInstance.id)).where( ApprovalInstance.project_id == project.id)) attachments = _count(db, select(func.count(Attachment.id)).where( Attachment.object_id == project.id, Attachment.is_deleted.is_(False))) members = _count(db, select(func.count(ProjectMember.id)).where( ProjectMember.project_id == project.id)) blockers: list[dict[str, str]] = [] warnings: list[dict[str, str]] = [] if reviewing: blockers.append({ "code": "approval_in_progress", "message": f"有 {reviewing} 个审批正在流转,请先撤回送审或等审批出结果", }) if approved: warnings.append({ "code": "has_approved_revision", "message": f"已有 {approved} 个审批通过的版本,删除后这些口径在列表里查不到", }) if project.stage in LATE_STAGES: warnings.append({ "code": "late_stage", "message": f"项目已进入「{project.stage_label}」,删除前请确认合同与结算已经了结", }) if attachments: warnings.append({"code": "has_attachment", "message": f"项目还挂着 {attachments} 个附件"}) if instances and not reviewing: warnings.append({"code": "has_approval_history", "message": f"有 {instances} 条历史审批记录"}) return { "projectName": project.name, "projectNo": project.project_no, "stage": project.stage, "stageLabel": project.stage_label, "deletable": not blockers, "blockers": blockers, "warnings": warnings, "stats": { "members": members, "attachments": attachments, "revisions": len(revision_statuses), "approvedRevisions": approved, "approvalInstances": instances, "reviewingInstances": reviewing, }, } @router.get("/{project_id}/delete-check") def check_project_deletion(project_id: int, db: DbSession, current: PrincipalOf) -> dict[str, Any]: """删除确认框要显示的东西:能不能删、牵连多少。前端不自己猜规则。""" project = assert_project_visible(db, current, project_id) _assert_project_owner(current, project, "删除项目") return ok(_delete_report(db, project)) @router.delete("/{project_id}") def delete_project(project_id: int, request: Request, db: DbSession, current: PrincipalOf, body: DeleteBody | None = None) -> dict[str, Any]: """软删除。项目连同概算、预算、成员、附件一起从业务视图里消失,数据一行不少。""" project = assert_project_visible(db, current, project_id) if not current.permission.can("project:project:delete"): raise forbidden("缺少权限:project:project:delete") _assert_project_owner(current, project, "删除项目") report = _delete_report(db, project) if report["blockers"]: first = report["blockers"][0] raise conflict(first["code"], first["message"]) reason = (body.reason.strip() if body else "")[:500] project.is_deleted = True project.deleted_at = datetime.now() project.deleted_by_id = current.account.id project.deleted_by_name = current.account.display_name or current.account.account project.delete_reason = reason # 审计行由中间件统一写;这里只补"为什么删"和业务口径,不另开一条。 audit.enrich(request, action="delete", object_name=project.name, reason=reason, stage=project.stage, stageLabel=project.stage_label, projectNo=project.project_no, stats=report["stats"]) db.commit() return ok({"deleted": True, "id": project.id, "deletedAt": _t(project.deleted_at)}) @router.post("/{project_id}/restore") def restore_project(project_id: int, request: Request, db: DbSession, current: PrincipalOf) -> dict[str, Any]: """回收站里捞回来。删除留痕一并清掉,别拿上一次的原因冒充这一次的。""" project = assert_project_visible(db, current, project_id, allow_deleted=True) if not project.is_deleted: raise conflict("not_deleted", "这个项目没有被删除") if not current.permission.can("project:project:delete"): raise forbidden("缺少权限:project:project:delete") _assert_project_owner(current, project, "恢复项目") previous_reason = project.delete_reason project.is_deleted = False project.deleted_at = None project.deleted_by_id = None project.deleted_by_name = "" project.delete_reason = "" audit.enrich(request, action="restore", object_name=project.name, previousDeleteReason=previous_reason) db.commit() return ok({"restored": True, "id": project.id}) # --------------------------------------------------------------------------- # 彻底删除:把回收站里的项目连同业务数据一起销毁,不可恢复 # --------------------------------------------------------------------------- #: 销毁顺序(叶子在前)与界面上的说法。不依赖 MySQL 的外键级联:级联是这台库的配置, #: 不是这套代码的约束,写清楚每张表既能在任何后端删干净,也能把"删了多少"讲明白。 PURGE_PLAN: tuple[tuple[str, tuple[type, ...]], ...] = ( ("概算明细", (EstimateIncomeLine, EstimateCostLine, EstimateOtherLine)), ("预算明细", (BudgetIncomeLine, BudgetIncomePlanLine, BudgetPurchaseLine, BudgetPayPlanLine, BudgetManageLine, BudgetOtherCostLine, BudgetFundMonth)), ("计算快照", (CalcSnapshot,)), ("概算/预算版本", (Revision,)), ("项目成员", (ProjectMember,)), ("可见角色授权", (ProjectVisibleRole,)), ("阶段流水", (ProjectStageLog,)), ) #: 附件是按 (object_type, object_id) 挂的多态表,只认项目这一族的挂法; #: 回收站/项目页能列出来的附件,和这里要销毁的附件,必须是同一批。 PROJECT_ATTACHMENT_TYPES = ("project", "estimate", "budget", "settlement", "final") class PurgeBody(BaseModel): confirmName: str = Field(default="", max_length=1000) def _purge_counts(db, project: Project) -> dict[str, int]: """数一遍销毁会带走多少行;附件按项目的挂点算。""" counts = {label: 0 for label, _ in PURGE_PLAN} for label, models in PURGE_PLAN: for model in models: counts[label] += _count(db, select(func.count(model.id)).where( model.project_id == project.id)) counts["审批记录"] = _count(db, select(func.count(ApprovalRecord.id)).where( ApprovalRecord.project_id == project.id)) counts["附件"] = _count(db, select(func.count(Attachment.id)).where( Attachment.object_id == project.id, Attachment.object_type.in_(PROJECT_ATTACHMENT_TYPES))) return counts def _purge_blockers(db, project: Project) -> list[dict[str, str]]: blockers: list[dict[str, str]] = [] if not project.is_deleted: blockers.append({ "code": "not_in_bin", "message": "只能销毁回收站里的项目,请先删除再彻底删除", }) instances = _count(db, select(func.count(ApprovalInstance.id)).where( ApprovalInstance.project_id == project.id)) records = _count(db, select(func.count(ApprovalRecord.id)).where( ApprovalRecord.project_id == project.id)) if instances or records: # 审批留痕是合规资产:谁批的、什么时候批的、按什么数批的。项目可以作废, # 这条链不能跟着销毁,否则审计就断在"曾经有个项目批过 800 万但查不到了"。 blockers.append({ "code": "has_approval_history", "message": f"项目留有审批痕迹({instances} 个实例 / {records} 条记录)," "按审计要求不能物理销毁,请保留在回收站", }) return blockers def _assert_project_purgable(db, current: Principal, project: Project) -> list[dict[str, str]]: if not current.permission.can("project:project:purge"): raise forbidden("缺少权限:project:project:purge") _assert_project_owner(current, project, "彻底删除项目") blockers = _purge_blockers(db, project) if blockers: first = blockers[0] raise conflict(first["code"], first["message"]) return blockers @router.get("/{project_id}/purge-check") def check_project_purge(project_id: int, db: DbSession, current: PrincipalOf) -> dict[str, Any]: """彻底删除前把"会毁掉什么"和要回敲的确认词一起给出去。""" project = assert_project_visible(db, current, project_id, allow_deleted=True) if not current.permission.can("project:project:purge"): raise forbidden("缺少权限:project:project:purge") _assert_project_owner(current, project, "彻底删除项目") blockers = _purge_blockers(db, project) return ok({ "projectName": project.name, "projectNo": project.project_no, "deletedAt": _t(project.deleted_at), "deletedByName": project.deleted_by_name, "deletable": not blockers, "blockers": blockers, "confirmName": project.project_no or project.name, "counts": _purge_counts(db, project), }) @router.delete("/{project_id}/purge") def purge_project(project_id: int, request: Request, db: DbSession, current: PrincipalOf, body: PurgeBody | None = None) -> dict[str, Any]: """物理销毁。执行完只剩审计行,业务数据一行不剩,没有回头路。""" project = assert_project_visible(db, current, project_id, allow_deleted=True) _assert_project_purgable(db, current, project) wanted = (project.project_no or project.name).strip() if (body.confirmName if body else "").strip() != wanted: raise conflict("confirm_mismatch", f"请输入项目编号「{wanted}」确认销毁") # 销毁之前先把现场留进审计:这条日志是这件事在这个世界上剩下的唯一痕迹。 counts = _purge_counts(db, project) snapshot = { "projectNo": project.project_no, "name": project.name, "stage": project.stage, "stageLabel": project.stage_label, "creatorName": project.creator_name, "orgUnitName": project.org_unit_name, "principal": project.principal, "contractAmount": money_str(project.contract_amount), "deletedAt": _t(project.deleted_at), "deletedByName": project.deleted_by_name, "deleteReason": project.delete_reason, "destroyed": counts, } for _, models in PURGE_PLAN: for model in models: db.query(model).filter(model.project_id == project.id).delete( synchronize_session=False) db.query(Attachment).filter( Attachment.object_id == project.id, Attachment.object_type.in_(PROJECT_ATTACHMENT_TYPES)).delete(synchronize_session=False) db.query(Project).filter(Project.id == project.id).delete(synchronize_session=False) audit.enrich(request, action="purge", object_name=snapshot["name"], **snapshot) db.commit() return ok({"purged": True, "id": project_id, "destroyed": counts}) class StageBody(BaseModel): stage: int remark: str = "" @router.post("/{project_id}/stage") def change_stage(project_id: int, body: StageBody, request: Request, *, db: DbSession, current: PrincipalOf) -> dict[str, Any]: stage = body.stage project = assert_project_visible(db, current, project_id) if not current.permission.can("project:project:edit"): raise forbidden("缺少权限:project:project:edit") if stage not in ProjectStage.LABELS: raise conflict("unknown_stage", f"未知的项目阶段:{stage}") biz.set_project_stage(db, project, stage, current.account, body.remark) audit.enrich(request, object_name=project.name, stage=stage, stageLabel=project.stage_label, remark=body.remark) db.commit() return ok({"stage": stage, "stageLabel": dict_store.label(db, "projectStage", stage, ProjectStage.LABELS[stage])}) @router.get("/{project_id}/members") def list_members(project_id: int, db: DbSession, current: PrincipalOf) -> dict[str, Any]: assert_project_visible(db, current, project_id) rows = db.execute(select(ProjectMember).where(ProjectMember.project_id == project_id) .order_by(ProjectMember.id)).scalars().all() return ok([{"id": row.id, "accountId": row.account_id, "accountName": row.account_name, "memberRole": row.member_role, "memberRoleLabel": dict_store.label( db, "projectMemberRole", row.member_role, row.member_role)} for row in rows]) @router.post("/{project_id}/members") def add_members(project_id: int, body: MemberBody, db: DbSession, current: PrincipalOf) -> dict[str, Any]: assert_project_visible(db, current, project_id) if not current.permission.can("project:project:edit"): raise forbidden("缺少权限:project:project:edit") existing = set(db.execute(select(ProjectMember.account_id).where( ProjectMember.project_id == project_id)).scalars().all()) added = 0 for account_id in body.accountIds or []: if account_id in existing: continue target = db.get(Account, account_id) if target is None or target.is_deleted: continue db.add(ProjectMember(project_id=project_id, account_id=account_id, account_name=target.display_name or target.account, member_role=body.memberRole)) added += 1 db.commit() return ok({"added": added, "projectId": project_id}) @router.delete("/{project_id}/members/{account_id}") def remove_member(project_id: int, account_id: int, db: DbSession, current: PrincipalOf) -> dict[str, Any]: assert_project_visible(db, current, project_id) if not current.permission.can("project:project:edit"): raise forbidden("缺少权限:project:project:edit") row = db.execute(select(ProjectMember).where( ProjectMember.project_id == project_id, ProjectMember.account_id == account_id )).scalars().first() if row is None: raise not_found("该成员不在项目里") if row.member_role == ProjectMemberRole.OWNER: raise conflict("owner_protected", "项目负责人不能移除,请先移交项目负责人") db.delete(row) db.commit() return ok({"deleted": True}) @router.get("/{project_id}/visible-roles") def list_visible_roles(project_id: int, db: DbSession, current: PrincipalOf) -> dict[str, Any]: assert_project_visible(db, current, project_id) from ..models import PermRole rows = db.execute(select(ProjectVisibleRole).where( ProjectVisibleRole.project_id == project_id)).scalars().all() roles = dict(db.execute(select(PermRole.id, PermRole.name)).all()) return ok([{"id": row.id, "roleId": row.role_id, "roleName": roles.get(row.role_id, "")} for row in rows]) class VisibleRoleBody(BaseModel): roleIds: list[int] = Field(default_factory=list) @router.put("/{project_id}/visible-roles") def set_visible_roles(project_id: int, body: VisibleRoleBody, db: DbSession, current: PrincipalOf) -> dict[str, Any]: """逐项目的"哪些角色能看这个项目",兼容老 project_visible 的 type=1。""" assert_project_visible(db, current, project_id) if not current.permission.can("project:project:edit"): raise forbidden("缺少权限:project:project:edit") existing = set(db.execute(select(ProjectVisibleRole.role_id).where( ProjectVisibleRole.project_id == project_id)).scalars().all()) wanted = set(body.roleIds or []) for role_id in existing - wanted: for row in db.execute(select(ProjectVisibleRole).where( ProjectVisibleRole.project_id == project_id, ProjectVisibleRole.role_id == role_id)).scalars(): db.delete(row) for role_id in wanted - existing: db.add(ProjectVisibleRole(project_id=project_id, role_id=role_id)) db.commit() return ok({"count": len(wanted)}) @router.get("/{project_id}/attachments") def list_attachments(project_id: int, db: DbSession, current: PrincipalOf, objectType: str = "") -> dict[str, Any]: assert_project_visible(db, current, project_id) statement = select(Attachment).where(Attachment.object_id == project_id, Attachment.is_deleted.is_(False)) if objectType: statement = statement.where(Attachment.object_type == objectType) rows = db.execute(statement.order_by(Attachment.id.desc())).scalars().all() return ok([{"id": row.id, "objectType": row.object_type, "objectId": row.object_id, "field": row.field, "fileName": row.file_name, "url": row.url, "size": row.size, "ext": row.ext, "uploaderName": row.uploader_name, "createdAt": _t(row.created_at)} for row in rows])