356 lines
13 KiB
Python
356 lines
13 KiB
Python
"""额度台账接口 -- 额度定义维护、额度与流水查询、手工调整、表单下拉取额度。
|
||
|
||
与设计字典同一个分寸:**改规则要权限,读额度只要登录**——运行时得把表单渲染得出来,
|
||
「选哪笔备用金、还剩多少」这一格在填单页面上就要能选。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import re
|
||
|
||
from fastapi import APIRouter, Depends, Query
|
||
from sqlalchemy import select
|
||
from sqlalchemy.orm import Session
|
||
|
||
from .. import models, schemas
|
||
from ..db import get_db
|
||
from ..deps import CurrentUser, current_user, require_permission
|
||
from ..envelope import bad_request, not_found, ok
|
||
from ..service import quota, quota_source
|
||
|
||
router = APIRouter(tags=["quota"])
|
||
|
||
CODE_RE = re.compile(r"^[A-Za-z0-9_-]{1,64}$")
|
||
|
||
|
||
def _def_view(row: models.QuotaDef, can_manage: bool = True) -> dict:
|
||
return {
|
||
|
||
"code": row.code,
|
||
"name": row.name,
|
||
"labelTemplate": row.label_template,
|
||
"description": row.description,
|
||
"enabled": row.enabled,
|
||
"source": row.source,
|
||
"dims": list(row.dims or []),
|
||
"issueProcess": row.issue_process,
|
||
"issueAmount": row.issue_amount,
|
||
"issueDims": dict(row.issue_dims or {}),
|
||
"totalSource": dict(row.total_source or {}),
|
||
"consumeSources": list(row.consume_sources or []),
|
||
"syncMinutes": row.sync_minutes,
|
||
"autoProvision": row.auto_provision,
|
||
"basis": row.basis,
|
||
"over": row.over,
|
||
"needNote": row.need_note,
|
||
"scope": row.scope,
|
||
"remindDays": row.remind_days,
|
||
"blockNewWhenOpen": row.block_new_when_open,
|
||
"creatorName": row.creator_name,
|
||
# 表单设计器里的「改取数」按钮认这个:能不能改由服务端说,不由前端猜
|
||
"canManage": can_manage,
|
||
}
|
||
|
||
|
||
@router.get("/design/quotas/defs")
|
||
def list_definitions(
|
||
db: Session = Depends(get_db),
|
||
user: CurrentUser = Depends(current_user),
|
||
keyword: str = Query(""),
|
||
enabled: str = Query(""),
|
||
) -> dict:
|
||
# 读定义只要登录:表单设计器要能把额度定义列成下拉选项给用户挑。
|
||
rows = quota.list_defs(db, keyword, enabled.lower() in ("1", "true", "yes"))
|
||
can = user.can("design:quota")
|
||
return ok([_def_view(row, can) for row in rows])
|
||
|
||
|
||
@router.post("/design/quotas/defs", dependencies=[Depends(require_permission("design:quota"))])
|
||
def create_definition(
|
||
body: schemas.QuotaDefBody, user: CurrentUser = Depends(current_user), db: Session = Depends(get_db)
|
||
) -> dict:
|
||
code = (body.code or "").strip()
|
||
if not CODE_RE.match(code):
|
||
raise bad_request("额度编码只能用字母、数字、下划线和中划线,且不能为空")
|
||
if not (body.name or "").strip():
|
||
raise bad_request("额度名称不能为空")
|
||
if not body.dims:
|
||
raise bad_request("至少要有一个额度维度(比如预算科目、年度)")
|
||
if quota.get_def(db, code) is not None:
|
||
raise bad_request(f"额度编码已存在: {code}")
|
||
|
||
row = models.QuotaDef(
|
||
code=code,
|
||
name=body.name.strip(),
|
||
label_template=body.label_template.strip(),
|
||
description=body.description,
|
||
enabled=body.enabled,
|
||
source=body.source,
|
||
dims=list(body.dims),
|
||
issue_process=body.issue_process,
|
||
issue_amount=body.issue_amount,
|
||
issue_dims=dict(body.issue_dims),
|
||
total_source=dict(body.total_source),
|
||
consume_sources=[dict(item) for item in body.consume_sources],
|
||
sync_minutes=int(body.sync_minutes or 0),
|
||
auto_provision=body.auto_provision,
|
||
basis=body.basis,
|
||
over=body.over,
|
||
need_note=body.need_note,
|
||
scope=body.scope,
|
||
remind_days=body.remind_days,
|
||
block_new_when_open=body.block_new_when_open,
|
||
creator=user.person_id,
|
||
creator_name=user.display_name,
|
||
)
|
||
if problems := quota_source.problems(row, db):
|
||
raise bad_request(problems[0])
|
||
db.add(row)
|
||
db.commit()
|
||
return ok(_def_view(row))
|
||
|
||
|
||
@router.patch(
|
||
"/design/quotas/defs/{code}", dependencies=[Depends(require_permission("design:quota"))]
|
||
)
|
||
def update_definition(
|
||
code: str,
|
||
body: schemas.QuotaDefBody,
|
||
db: Session = Depends(get_db),
|
||
_: CurrentUser = Depends(current_user),
|
||
) -> dict:
|
||
row = quota.get_def(db, code)
|
||
if row is None:
|
||
raise not_found("额度定义不存在")
|
||
for field, value in (
|
||
|
||
("name", body.name.strip() or row.name),
|
||
# 显示模板允许清成空(清空=回到用来源单据标题),所以不做「空值就不动」那套
|
||
("label_template", body.label_template.strip()),
|
||
("description", body.description),
|
||
("enabled", body.enabled),
|
||
("source", body.source),
|
||
("issue_process", body.issue_process),
|
||
("issue_amount", body.issue_amount),
|
||
("total_source", dict(body.total_source)),
|
||
("consume_sources", [dict(item) for item in body.consume_sources]),
|
||
("sync_minutes", int(body.sync_minutes or 0)),
|
||
("auto_provision", body.auto_provision),
|
||
("basis", body.basis),
|
||
("over", body.over),
|
||
("need_note", body.need_note),
|
||
("scope", body.scope),
|
||
("remind_days", body.remind_days),
|
||
("block_new_when_open", body.block_new_when_open),
|
||
):
|
||
setattr(row, field, value)
|
||
if body.dims:
|
||
row.dims = list(body.dims)
|
||
if body.issue_dims:
|
||
row.issue_dims = dict(body.issue_dims)
|
||
if problems := quota_source.problems(row, db):
|
||
raise bad_request(problems[0])
|
||
db.commit()
|
||
return ok(_def_view(row))
|
||
|
||
|
||
@router.post(
|
||
"/design/quotas/defs/{code}/totals",
|
||
dependencies=[Depends(require_permission("design:quota"))],
|
||
)
|
||
def import_totals(
|
||
code: str,
|
||
body: schemas.QuotaTotalsBody,
|
||
user: CurrentUser = Depends(current_user),
|
||
db: Session = Depends(get_db),
|
||
) -> dict:
|
||
"""批量落总额:年初预算导入、以及以后外部同步落地都走这一个入口。
|
||
|
||
一行一个结论:维度少一个键、总额写成"待定"、归属人查无此人,都只挡那一行,
|
||
``rejected`` 带回行号与原因。表格解析在前端做完,两边读的是同一份结构化行,
|
||
口径都在 ``service/quota.import_totals``(界面预览说什么,落库就是什么)。
|
||
"""
|
||
def_row = quota.get_def(db, code)
|
||
if def_row is None:
|
||
raise not_found("额度定义不存在")
|
||
if not body.items:
|
||
raise bad_request("没有要导入的额度")
|
||
mode = str(body.mode or "overwrite").strip()
|
||
if mode not in ("skip", "overwrite"):
|
||
raise bad_request("导入方式只支持 skip(跳过已有)或 overwrite(改成这个数)")
|
||
return ok(quota.import_totals(
|
||
db,
|
||
def_row,
|
||
items=[item.model_dump() for item in body.items],
|
||
reason=(body.reason or "").strip(),
|
||
mode=mode,
|
||
actor=user,
|
||
))
|
||
|
||
|
||
@router.get(
|
||
"/design/quotas/owners", dependencies=[Depends(require_permission("design:quota"))]
|
||
)
|
||
def read_owners(
|
||
db: Session = Depends(get_db),
|
||
_: CurrentUser = Depends(current_user),
|
||
values: str = Query(""),
|
||
) -> dict:
|
||
"""导入前预检:这几格"归属人"认不认得出人。逐条回结论,认不出的带上原因。
|
||
|
||
与 ``import_totals`` 用的是同一份匹配,所以界面预览能把「查无此人」「重名」这两类
|
||
在点导入之前就说到位——不然预览报「新增 3 笔」、导完变「新增 2 笔」,
|
||
财务看到的永远是最后那个数,前面那句白说了。
|
||
"""
|
||
wanted = [item.strip() for item in str(values or "").split(",") if item.strip()]
|
||
return ok(quota.resolve_owners(db, wanted[:200]))
|
||
|
||
|
||
@router.post(
|
||
"/design/quotas/defs/{code}/trial", dependencies=[Depends(require_permission("design:quota"))]
|
||
)
|
||
def trial_definition(
|
||
code: str,
|
||
body: schemas.QuotaTrialBody,
|
||
db: Session = Depends(get_db),
|
||
_: CurrentUser = Depends(current_user),
|
||
) -> dict:
|
||
|
||
"""试算:配完取数当场看「取了哪几张单、加起来多少、这次报完还剩多少」。只读不改。"""
|
||
row = quota.get_def(db, code)
|
||
if row is None:
|
||
raise not_found("额度定义不存在")
|
||
return ok(quota_source.trial(db, row, body.dims, body.amount))
|
||
|
||
|
||
@router.get(
|
||
"/design/quotas/defs/{code}/labels",
|
||
dependencies=[Depends(require_permission("design:quota"))],
|
||
)
|
||
def preview_labels(
|
||
code: str,
|
||
db: Session = Depends(get_db),
|
||
_: CurrentUser = Depends(current_user),
|
||
labelTemplate: str = "", # noqa: N803 - 对外保持驼峰
|
||
limit: int = Query(5, ge=1, le=20),
|
||
) -> dict:
|
||
"""额度定义页的「下拉里会是这样」:拿真台账按草稿模板渲染几条。只读,不写库。
|
||
|
||
故意不传 ``actor``:``scope=self`` 的额度(备用金)在下拉里只认本人,而配显示模板的
|
||
通常是管理员——照 ``options`` 的填报口径预览就永远是空列表,模板等于没得调。
|
||
这一条走 ``design:quota``,能看到的行与同页的 ``GET /design/quotas`` 一模一样,
|
||
不会因为预览多露出别人的额度。
|
||
"""
|
||
if quota.get_def(db, code) is None:
|
||
raise not_found("额度定义不存在")
|
||
return ok(quota.options(db, code, label_template=labelTemplate, limit=limit))
|
||
|
||
|
||
@router.post(
|
||
"/design/quotas/defs/{code}/rebuild", dependencies=[Depends(require_permission("design:quota"))]
|
||
)
|
||
def rebuild_definition(
|
||
code: str,
|
||
body: schemas.QuotaRebuildBody,
|
||
user: CurrentUser = Depends(current_user),
|
||
db: Session = Depends(get_db),
|
||
) -> dict:
|
||
"""按取数配置重建台账(长额度行、刷总额、把历史单据记进占用与核销)。
|
||
|
||
``apply=false`` 先干跑看差异;上线时那笔「在途单不会自动进占用账」的初始化就是这一指。
|
||
"""
|
||
row = quota.get_def(db, code)
|
||
if row is None:
|
||
raise not_found("额度定义不存在")
|
||
report = quota_source.rebuild(
|
||
db, row, dims=body.dims or None, apply=body.apply, actor=user
|
||
)
|
||
if body.apply:
|
||
db.commit()
|
||
else:
|
||
db.rollback()
|
||
return ok(report)
|
||
|
||
|
||
@router.get("/design/quotas/defs/{code}/usages", dependencies=[Depends(require_permission("design:quota"))])
|
||
def definition_usages(code: str, db: Session = Depends(get_db), _: CurrentUser = Depends(current_user)) -> dict:
|
||
"""哪些表单引用了这个额度定义:改取数配置前先给个人数。"""
|
||
if quota.get_def(db, code) is None:
|
||
raise not_found("额度定义不存在")
|
||
return ok(quota_source.usages(db, code))
|
||
|
||
|
||
@router.get("/design/quotas", dependencies=[Depends(require_permission("design:quota"))])
|
||
def list_quota_rows(
|
||
db: Session = Depends(get_db),
|
||
_: CurrentUser = Depends(current_user),
|
||
defCode: str = Query(""), # noqa: N803 - 对外保持驼峰
|
||
keyword: str = Query(""),
|
||
status: str = Query(""),
|
||
person: str = Query(""),
|
||
) -> dict:
|
||
rows = quota.list_quotas(db, defCode, keyword, status, person)
|
||
cache: dict[str, models.QuotaDef | None] = {}
|
||
items = []
|
||
for row in rows:
|
||
if row.quota_def not in cache:
|
||
cache[row.quota_def] = quota.get_def(db, row.quota_def)
|
||
items.append(quota.quota_view(db, row, cache[row.quota_def]))
|
||
# 可用为负的排最前:那是上游把总额调下来了,等着有人去看。
|
||
items.sort(key=lambda item: item["available"])
|
||
return ok(items)
|
||
|
||
|
||
@router.get(
|
||
"/design/quotas/{quota_id}/ledger", dependencies=[Depends(require_permission("design:quota"))]
|
||
)
|
||
def read_ledger(
|
||
quota_id: str, db: Session = Depends(get_db), _: CurrentUser = Depends(current_user)
|
||
) -> dict:
|
||
if quota.find_quota(db, quota_id) is None:
|
||
raise not_found("额度不存在")
|
||
rows = db.execute(
|
||
select(models.QuotaLedger)
|
||
.where(models.QuotaLedger.quota == quota_id)
|
||
.order_by(models.QuotaLedger.created_at.desc(), models.QuotaLedger.id.desc())
|
||
).scalars().all()
|
||
return ok([quota.ledger_view(row) for row in rows])
|
||
|
||
|
||
@router.post("/design/quotas/{quota_id}/adjust", dependencies=[Depends(require_permission("design:quota"))])
|
||
def adjust_quota(
|
||
quota_id: str,
|
||
body: schemas.QuotaAdjustBody,
|
||
user: CurrentUser = Depends(current_user),
|
||
db: Session = Depends(get_db),
|
||
) -> dict:
|
||
"""手工调整总额(追加预算、备用金多冲后现金归还)。**必须写原因**,流水全程留痕。"""
|
||
if not (body.reason or "").strip():
|
||
raise bad_request("调整额度必须填写原因")
|
||
delta = quota.to_cents(body.delta)
|
||
if delta is None or delta == 0:
|
||
raise bad_request("调整金额得是一个不等于 0 的数字(单位:元)")
|
||
row = quota.adjust_total(db, quota_id, delta, body.reason.strip(), actor=user)
|
||
if row is None:
|
||
raise not_found("额度不存在")
|
||
db.commit()
|
||
return ok(quota.quota_view(db, row))
|
||
|
||
|
||
@router.get("/quota/options")
|
||
def quota_options(
|
||
db: Session = Depends(get_db),
|
||
user: CurrentUser = Depends(current_user),
|
||
|
||
|
||
defCode: str = Query(..., alias="defCode"), # noqa: N803
|
||
keyword: str = Query(""),
|
||
work: str = Query(""),
|
||
) -> dict:
|
||
"""表单下拉用:只回本人名下、还没核销完的额度,并带着三个数(选中即带出)。
|
||
|
||
``work`` 传当前单号时,这张单已经占过、哪怕已经被自己占到关闭的额度也一起回出来,
|
||
免得退回补正时选不回来。
|
||
"""
|
||
return ok(quota.options(db, defCode, actor=user, keyword=keyword, work_id=work))
|