refactor(backend): 仓储层散参数收敛为查询 DTO
仓储层的 list_*/count_* 此前以 keyword/status/offset/limit 四五个散参数 传参,调用点重复铺开、易漏传且不可扩展;按项目「参数 >4 封装 DTO」的 约定统一收敛为各模块的 Query 对象(如 RoleQuery、BusinessQuery), 服务层与测试调用同步调整,行为不变。 - repositories 层查询方法签名改为 (session, query),分页与筛选条件 由 Query 承载,_apply_filters 同步收口 - schemas 层补齐各模块 Query 模型(approval/business_role/report 等) - services 层调用点同步改为传 Query - tests 随之调整;新增用例:待办角色流转(财务通过后领导出现待办)、 参数预览顺序稳定 验证:全量 pytest 900 passed(11:08);单元 526 passed;ruff check 绿。 Co-Authored-By: Claude Code <noreply@anthropic.com>
This commit is contained in:
1 parent
c48d24ab6d
commit
5ece9f6dab
45 files changed
+1045
-1028
No files matched your search
@@ -37,12 +37,14 @@ def _record(
|
||||
"""写登录日志并立即提交。单独提交是刻意为之,见模块 docstring。"""
|
||||
login_log_repository.add(
|
||||
session,
|
||||
user_id=user_id,
|
||||
username=username,
|
||||
ip=ip,
|
||||
user_agent=user_agent,
|
||||
success=success,
|
||||
fail_reason=fail_reason,
|
||||
login_log_repository.LoginLogEntry(
|
||||
user_id=user_id,
|
||||
username=username,
|
||||
ip=ip,
|
||||
user_agent=user_agent,
|
||||
success=success,
|
||||
fail_reason=fail_reason,
|
||||
),
|
||||
)
|
||||
session.commit()
|
||||
|
||||
|
||||
@@ -31,6 +31,7 @@ from app.models import BusinessRole, User
|
||||
from app.repositories import business_role_repository
|
||||
from app.schemas.business_role import (
|
||||
BusinessRoleCreateIn,
|
||||
BusinessRoleOptionOut,
|
||||
BusinessRoleOut,
|
||||
BusinessRoleQuery,
|
||||
BusinessRoleUpdateIn,
|
||||
@@ -67,16 +68,8 @@ def _ensure_template(calc_template: str) -> None:
|
||||
|
||||
def list_roles(session: Session, query: BusinessRoleQuery) -> PageResult[BusinessRoleOut]:
|
||||
"""分页查询岗位(含停用)。"""
|
||||
roles = business_role_repository.list_roles(
|
||||
session,
|
||||
offset=query.offset,
|
||||
limit=query.page_size,
|
||||
keyword=query.keyword,
|
||||
status=query.status,
|
||||
)
|
||||
total = business_role_repository.count_roles(
|
||||
session, keyword=query.keyword, status=query.status
|
||||
)
|
||||
roles = business_role_repository.list_roles(session, query)
|
||||
total = business_role_repository.count_roles(session, query)
|
||||
return PageResult[BusinessRoleOut](
|
||||
records=[_to_out(role) for role in roles],
|
||||
total=total,
|
||||
@@ -85,6 +78,23 @@ def list_roles(session: Session, query: BusinessRoleQuery) -> PageResult[Busines
|
||||
)
|
||||
|
||||
|
||||
def list_options(session: Session) -> list[BusinessRoleOptionOut]:
|
||||
"""岗位下拉选项(含停用,不分页)。
|
||||
|
||||
含停用是因为人员档案可能仍引用停用岗位(停用只是禁止新增引用,
|
||||
不改历史归属);岗位规模有限(内置 + 自定义),一次取全量。
|
||||
"""
|
||||
return [
|
||||
BusinessRoleOptionOut(
|
||||
id=role.id,
|
||||
role_code=role.role_code,
|
||||
role_name=role.role_name,
|
||||
status=role.status,
|
||||
)
|
||||
for role in business_role_repository.list_all(session)
|
||||
]
|
||||
|
||||
|
||||
def get_role(session: Session, role_id: int) -> BusinessRoleOut:
|
||||
"""岗位详情。
|
||||
|
||||
|
||||
@@ -15,6 +15,8 @@
|
||||
"""
|
||||
|
||||
import logging
|
||||
from collections.abc import Callable
|
||||
from dataclasses import dataclass
|
||||
from datetime import date
|
||||
from decimal import ROUND_HALF_UP, Decimal
|
||||
from fractions import Fraction
|
||||
@@ -234,26 +236,8 @@ def _is_duplicate_entry(exc: IntegrityError) -> bool:
|
||||
|
||||
def list_businesses(session: Session, query: BusinessQuery) -> PageResult[BusinessOut]:
|
||||
"""分页查询业务(附客户名与归属人名)。"""
|
||||
rows = business_repository.list_businesses(
|
||||
session,
|
||||
offset=query.offset,
|
||||
limit=query.page_size,
|
||||
keyword=query.keyword,
|
||||
status=query.status,
|
||||
customer_id=query.customer_id,
|
||||
owner_personnel_id=query.owner_personnel_id,
|
||||
date_from=query.date_from,
|
||||
date_to=query.date_to,
|
||||
)
|
||||
total = business_repository.count_businesses(
|
||||
session,
|
||||
keyword=query.keyword,
|
||||
status=query.status,
|
||||
customer_id=query.customer_id,
|
||||
owner_personnel_id=query.owner_personnel_id,
|
||||
date_from=query.date_from,
|
||||
date_to=query.date_to,
|
||||
)
|
||||
rows = business_repository.list_businesses(session, query)
|
||||
total = business_repository.count_businesses(session, query)
|
||||
return PageResult[BusinessOut](
|
||||
records=[_to_out(row) for row in rows],
|
||||
total=total,
|
||||
@@ -748,6 +732,67 @@ def change_status(
|
||||
return out
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class _BusinessOwnershipResolution:
|
||||
"""业务归属变更的解析结果(新归属人行 + 变更前固化 ID)。"""
|
||||
|
||||
owner: Personnel | None
|
||||
assistant: Personnel | None
|
||||
old_owner_id: int | None
|
||||
old_assistant_id: int | None
|
||||
|
||||
|
||||
def _resolve_business_ownership(
|
||||
session: Session, business: Business, payload: BusinessOwnershipIn
|
||||
) -> _BusinessOwnershipResolution:
|
||||
"""校验新归属人(须在职)并判定归属是否真的变化。
|
||||
|
||||
校验在审计上下文内执行 —— 失败也留痕。两者均未变化 → 400「归属未变化」。
|
||||
"""
|
||||
# 归属变更的出参姓名来自校验函数的返回行(锁定读):首查姓名是变更前
|
||||
# 固化标量,新归属人名必须按新 ID 重取
|
||||
owner = (
|
||||
_ensure_personnel_active(session, payload.new_owner_personnel_id, "负责")
|
||||
if payload.new_owner_personnel_id is not None
|
||||
else None
|
||||
)
|
||||
assistant = (
|
||||
_ensure_personnel_active(session, payload.new_assistant_personnel_id, "协助")
|
||||
if payload.new_assistant_personnel_id is not None
|
||||
else None
|
||||
)
|
||||
owner_changed = business.owner_personnel_id != payload.new_owner_personnel_id
|
||||
assistant_changed = business.assistant_personnel_id != payload.new_assistant_personnel_id
|
||||
if not owner_changed and not assistant_changed:
|
||||
raise BadRequestError("归属未变化")
|
||||
return _BusinessOwnershipResolution(
|
||||
owner=owner,
|
||||
assistant=assistant,
|
||||
old_owner_id=business.owner_personnel_id,
|
||||
old_assistant_id=business.assistant_personnel_id,
|
||||
)
|
||||
|
||||
|
||||
def _business_ownership_log(
|
||||
business: Business,
|
||||
payload: BusinessOwnershipIn,
|
||||
resolution: _BusinessOwnershipResolution,
|
||||
operator: User,
|
||||
) -> OwnershipChangeLog:
|
||||
"""归属变更留痕行(负责/协助两个字段的前后值都记)。"""
|
||||
return OwnershipChangeLog(
|
||||
owner_type=OWNER_TYPE_BUSINESS,
|
||||
business_id=business.id,
|
||||
old_owner_personnel_id=resolution.old_owner_id,
|
||||
new_owner_personnel_id=payload.new_owner_personnel_id,
|
||||
old_assistant_personnel_id=resolution.old_assistant_id,
|
||||
new_assistant_personnel_id=payload.new_assistant_personnel_id,
|
||||
change_reason=payload.reason,
|
||||
operator_id=operator.id,
|
||||
operator_name=operator.username,
|
||||
)
|
||||
|
||||
|
||||
def change_ownership(
|
||||
session: Session,
|
||||
business_id: int,
|
||||
@@ -779,41 +824,12 @@ def change_ownership(
|
||||
if row is None:
|
||||
raise NotFoundError("业务不存在")
|
||||
business, _, old_owner_name, old_assistant_name = row
|
||||
# 归属变更的出参姓名来自校验函数的返回行(锁定读):首查姓名是变更前
|
||||
# 固化标量,新归属人名必须按新 ID 重取
|
||||
new_owner = (
|
||||
_ensure_personnel_active(session, payload.new_owner_personnel_id, "负责")
|
||||
if payload.new_owner_personnel_id is not None
|
||||
else None
|
||||
)
|
||||
new_assistant = (
|
||||
_ensure_personnel_active(session, payload.new_assistant_personnel_id, "协助")
|
||||
if payload.new_assistant_personnel_id is not None
|
||||
else None
|
||||
)
|
||||
resolution = _resolve_business_ownership(session, business, payload)
|
||||
|
||||
owner_changed = business.owner_personnel_id != payload.new_owner_personnel_id
|
||||
assistant_changed = business.assistant_personnel_id != payload.new_assistant_personnel_id
|
||||
if not owner_changed and not assistant_changed:
|
||||
raise BadRequestError("归属未变化")
|
||||
|
||||
old_owner_id = business.owner_personnel_id
|
||||
old_assistant_id = business.assistant_personnel_id
|
||||
business.owner_personnel_id = payload.new_owner_personnel_id
|
||||
business.assistant_personnel_id = payload.new_assistant_personnel_id
|
||||
business_repository.add_ownership_log(
|
||||
session,
|
||||
OwnershipChangeLog(
|
||||
owner_type=OWNER_TYPE_BUSINESS,
|
||||
business_id=business_id,
|
||||
old_owner_personnel_id=old_owner_id,
|
||||
new_owner_personnel_id=payload.new_owner_personnel_id,
|
||||
old_assistant_personnel_id=old_assistant_id,
|
||||
new_assistant_personnel_id=payload.new_assistant_personnel_id,
|
||||
change_reason=payload.reason,
|
||||
operator_id=operator.id,
|
||||
operator_name=operator.username,
|
||||
),
|
||||
session, _business_ownership_log(business, payload, resolution, operator)
|
||||
)
|
||||
# 出参组装:ID 在锁定行上已赋值(_to_out 读内存值即反映新值),姓名
|
||||
# 一侧「变更项用新 ID 的人名、未变项沿用首查名」——首查名是变更前快照
|
||||
@@ -821,17 +837,19 @@ def change_ownership(
|
||||
(
|
||||
business,
|
||||
row[1],
|
||||
new_owner.personnel_name if new_owner is not None else old_owner_name,
|
||||
new_assistant.personnel_name if new_assistant is not None else old_assistant_name,
|
||||
resolution.owner.personnel_name if resolution.owner is not None else old_owner_name,
|
||||
resolution.assistant.personnel_name
|
||||
if resolution.assistant is not None
|
||||
else old_assistant_name,
|
||||
)
|
||||
)
|
||||
session.commit()
|
||||
logger.info(
|
||||
"调整业务归属 | business_id=%s | owner %s->%s | assistant %s->%s",
|
||||
business_id,
|
||||
old_owner_id,
|
||||
resolution.old_owner_id,
|
||||
payload.new_owner_personnel_id,
|
||||
old_assistant_id,
|
||||
resolution.old_assistant_id,
|
||||
payload.new_assistant_personnel_id,
|
||||
)
|
||||
return out
|
||||
@@ -897,6 +915,94 @@ def list_status_logs(
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class _GrossProfitScan:
|
||||
"""毛利润逐行扫描结果(行 DTO、类别聚合桶、成本缺失计数)。"""
|
||||
|
||||
rows: list[GrossProfitRowOut]
|
||||
category_agg: dict[str, list[Decimal]]
|
||||
missing_count: int
|
||||
|
||||
|
||||
def _gross_profit_row(
|
||||
item: BusinessItem, threshold: Fraction
|
||||
) -> tuple[GrossProfitRowOut, tuple[Decimal, Decimal] | None]:
|
||||
"""单行毛利润派生值(行 DTO + 类别聚合桶)。
|
||||
|
||||
聚合桶为 None 表示成本缺失行 —— 这类行不计入类别汇总,但仍要输出
|
||||
派生列为 None 的行与缺失原因。阈值对两类行都要取(成本缺失也展示阈值)。
|
||||
"""
|
||||
row_kwargs: dict = {
|
||||
"item_id": item.id,
|
||||
"product_category": item.product_category,
|
||||
"product_name": item.product_name,
|
||||
"spec_model": item.spec_model,
|
||||
"quantity": str(item.quantity),
|
||||
"sale_amount": str(item.sale_amount),
|
||||
"threshold": str(threshold),
|
||||
}
|
||||
if item.cost_amount is None:
|
||||
row_kwargs.update(
|
||||
cost_amount=None,
|
||||
profit_amount=None,
|
||||
profit_rate=None,
|
||||
converted_profit=None,
|
||||
missing_reason="成本缺失,无法计算毛利润",
|
||||
)
|
||||
return GrossProfitRowOut(**row_kwargs), None
|
||||
|
||||
profit = item.sale_amount - item.cost_amount
|
||||
rate = profit_rate(profit, item.sale_amount)
|
||||
conv = converted_profit(item.sale_amount, rate, threshold)
|
||||
row_kwargs.update(
|
||||
cost_amount=str(item.cost_amount),
|
||||
profit_amount=str(profit),
|
||||
profit_rate=str(rate),
|
||||
converted_profit=str(conv),
|
||||
missing_reason=None,
|
||||
)
|
||||
return GrossProfitRowOut(**row_kwargs), (item.sale_amount, item.cost_amount)
|
||||
|
||||
|
||||
def _scan_gross_profit_rows(
|
||||
session: Session, business_id: int, threshold_of: Callable[[str], Fraction]
|
||||
) -> _GrossProfitScan:
|
||||
"""逐行扫描业务明细:出行 DTO、类别聚合桶与成本缺失计数。
|
||||
|
||||
类别顺序沿用明细行的首次出现顺序(不排序)—— 前端汇总展示依赖该顺序。
|
||||
"""
|
||||
rows: list[GrossProfitRowOut] = []
|
||||
agg: dict[str, list[Decimal]] = {}
|
||||
missing_count = 0
|
||||
for item in business_repository.list_items(session, business_id):
|
||||
row, bucket = _gross_profit_row(item, threshold_of(item.product_category))
|
||||
rows.append(row)
|
||||
if bucket is None:
|
||||
missing_count += 1
|
||||
continue
|
||||
current = agg.setdefault(item.product_category, [Decimal("0"), Decimal("0")])
|
||||
current[0] += bucket[0]
|
||||
current[1] += bucket[1]
|
||||
return _GrossProfitScan(rows=rows, category_agg=agg, missing_count=missing_count)
|
||||
|
||||
|
||||
def _gross_profit_category(
|
||||
category: str, sale: Decimal, cost: Decimal, threshold: Fraction
|
||||
) -> GrossProfitCategoryOut:
|
||||
"""类别汇总行(派生口径与行级一致:利润率/折算复用 formula 纯函数)。"""
|
||||
profit = sale - cost
|
||||
rate = profit_rate(profit, sale)
|
||||
return GrossProfitCategoryOut(
|
||||
product_category=category,
|
||||
sale_amount=str(sale),
|
||||
cost_amount=str(cost),
|
||||
profit_amount=str(profit),
|
||||
profit_rate=str(rate),
|
||||
threshold=str(threshold),
|
||||
converted_profit=str(converted_profit(sale, rate, threshold)),
|
||||
)
|
||||
|
||||
|
||||
def gross_profit(session: Session, business_id: int, as_of: date | None) -> GrossProfitOut:
|
||||
"""毛利润数据视图(需求 2.2.4):行级派生值 + 类别汇总,实时计算不落库。
|
||||
|
||||
@@ -915,64 +1021,15 @@ def gross_profit(session: Session, business_id: int, as_of: date | None) -> Gros
|
||||
def threshold_of(category: str) -> Fraction:
|
||||
return snapshot.fraction("product.threshold", product_category=category)
|
||||
|
||||
rows_out: list[GrossProfitRowOut] = []
|
||||
missing_count = 0
|
||||
# 类别聚合容器:{类别: [sale, cost]},成本缺失行不计入该类别聚合
|
||||
agg: dict[str, list[Decimal]] = {}
|
||||
for item in business_repository.list_items(session, business_id):
|
||||
threshold = threshold_of(item.product_category)
|
||||
row_kwargs: dict = {
|
||||
"item_id": item.id,
|
||||
"product_category": item.product_category,
|
||||
"product_name": item.product_name,
|
||||
"spec_model": item.spec_model,
|
||||
"quantity": str(item.quantity),
|
||||
"sale_amount": str(item.sale_amount),
|
||||
"threshold": str(threshold),
|
||||
}
|
||||
if item.cost_amount is None:
|
||||
missing_count += 1
|
||||
row_kwargs.update(
|
||||
cost_amount=None,
|
||||
profit_amount=None,
|
||||
profit_rate=None,
|
||||
converted_profit=None,
|
||||
missing_reason="成本缺失,无法计算毛利润",
|
||||
)
|
||||
else:
|
||||
profit = item.sale_amount - item.cost_amount
|
||||
rate = profit_rate(profit, item.sale_amount)
|
||||
conv = converted_profit(item.sale_amount, rate, threshold)
|
||||
row_kwargs.update(
|
||||
cost_amount=str(item.cost_amount),
|
||||
profit_amount=str(profit),
|
||||
profit_rate=str(rate),
|
||||
converted_profit=str(conv),
|
||||
missing_reason=None,
|
||||
)
|
||||
bucket = agg.setdefault(item.product_category, [Decimal("0"), Decimal("0")])
|
||||
bucket[0] += item.sale_amount
|
||||
bucket[1] += item.cost_amount
|
||||
rows_out.append(GrossProfitRowOut(**row_kwargs))
|
||||
|
||||
scan = _scan_gross_profit_rows(session, business_id, threshold_of)
|
||||
categories = [
|
||||
GrossProfitCategoryOut(
|
||||
product_category=category,
|
||||
sale_amount=str(sale),
|
||||
cost_amount=str(cost),
|
||||
profit_amount=str(sale - cost),
|
||||
profit_rate=str(profit_rate(sale - cost, sale)),
|
||||
threshold=str(threshold_of(category)),
|
||||
converted_profit=str(
|
||||
converted_profit(sale, profit_rate(sale - cost, sale), threshold_of(category))
|
||||
),
|
||||
)
|
||||
for category, [sale, cost] in agg.items()
|
||||
_gross_profit_category(category, sale, cost, threshold_of(category))
|
||||
for category, [sale, cost] in scan.category_agg.items()
|
||||
]
|
||||
return GrossProfitOut(
|
||||
business_id=business_id,
|
||||
as_of=as_of,
|
||||
rows=rows_out,
|
||||
rows=scan.rows,
|
||||
categories=categories,
|
||||
missing_count=missing_count,
|
||||
missing_count=scan.missing_count,
|
||||
)
|
||||
@@ -14,6 +14,7 @@
|
||||
"""
|
||||
|
||||
import logging
|
||||
from dataclasses import dataclass
|
||||
|
||||
from sqlalchemy import Row
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
@@ -107,20 +108,8 @@ def _is_duplicate_entry(exc: IntegrityError) -> bool:
|
||||
|
||||
def list_customers(session: Session, query: CustomerQuery) -> PageResult[CustomerOut]:
|
||||
"""分页查询客户(附归属人员姓名)。"""
|
||||
rows = customer_repository.list_customers(
|
||||
session,
|
||||
offset=query.offset,
|
||||
limit=query.page_size,
|
||||
keyword=query.keyword,
|
||||
customer_type=query.customer_type,
|
||||
owner_personnel_id=query.owner_personnel_id,
|
||||
)
|
||||
total = customer_repository.count_customers(
|
||||
session,
|
||||
keyword=query.keyword,
|
||||
customer_type=query.customer_type,
|
||||
owner_personnel_id=query.owner_personnel_id,
|
||||
)
|
||||
rows = customer_repository.list_customers(session, query)
|
||||
total = customer_repository.count_customers(session, query)
|
||||
return PageResult[CustomerOut](
|
||||
records=[_to_out(customer, owner_name) for customer, owner_name in rows],
|
||||
total=total,
|
||||
@@ -317,6 +306,71 @@ def delete_customer(
|
||||
logger.info("删除客户 | customer_id=%s | company=%s", customer_id, company_name)
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class _CustomerOwnershipPrefetch:
|
||||
"""客户归属变更的审计前只读预取(摘要要客户名与新旧归属人名)。"""
|
||||
|
||||
row: Row | None
|
||||
new_person: Personnel | None
|
||||
old_label: str
|
||||
new_label: str
|
||||
customer_name: str
|
||||
|
||||
|
||||
def _prefetch_customer_ownership(
|
||||
session: Session, customer_id: int, payload: CustomerOwnershipIn
|
||||
) -> _CustomerOwnershipPrefetch:
|
||||
"""审计上下文之前的只读预取(预取不写库,失败路径也要有可读摘要)。"""
|
||||
row = customer_repository.get_with_owner_name(session, customer_id)
|
||||
old_person = (
|
||||
personnel_repository.get_by_id(session, row[0].owner_personnel_id)
|
||||
if row is not None and row[0].owner_personnel_id is not None
|
||||
else None
|
||||
)
|
||||
new_person = (
|
||||
personnel_repository.get_by_id(session, payload.new_owner_personnel_id)
|
||||
if payload.new_owner_personnel_id is not None
|
||||
else None
|
||||
)
|
||||
return _CustomerOwnershipPrefetch(
|
||||
row=row,
|
||||
new_person=new_person,
|
||||
old_label=old_person.personnel_name if old_person else "无",
|
||||
new_label=new_person.personnel_name if new_person else "无",
|
||||
customer_name=row[0].company_name if row else f"#{customer_id}",
|
||||
)
|
||||
|
||||
|
||||
def _validate_customer_ownership(
|
||||
session: Session, customer: Customer, payload: CustomerOwnershipIn
|
||||
) -> int | None:
|
||||
"""校验新归属人(须在职)并判定归属是否变化,返回变更前归属人 ID。"""
|
||||
if payload.new_owner_personnel_id is not None:
|
||||
_ensure_owner_personnel(session, payload.new_owner_personnel_id)
|
||||
old_owner_id = customer.owner_personnel_id
|
||||
if old_owner_id == payload.new_owner_personnel_id:
|
||||
raise BadRequestError("归属未变化")
|
||||
return old_owner_id
|
||||
|
||||
|
||||
def _customer_ownership_log(
|
||||
customer: Customer,
|
||||
payload: CustomerOwnershipIn,
|
||||
old_owner_id: int | None,
|
||||
operator: User,
|
||||
) -> OwnershipChangeLog:
|
||||
"""客户归属变更留痕行。"""
|
||||
return OwnershipChangeLog(
|
||||
owner_type=OWNER_TYPE_CUSTOMER,
|
||||
customer_id=customer.id,
|
||||
old_owner_personnel_id=old_owner_id,
|
||||
new_owner_personnel_id=payload.new_owner_personnel_id,
|
||||
change_reason=payload.reason,
|
||||
operator_id=operator.id,
|
||||
operator_name=operator.username,
|
||||
)
|
||||
|
||||
|
||||
def change_ownership(
|
||||
session: Session,
|
||||
customer_id: int,
|
||||
@@ -335,57 +389,34 @@ def change_ownership(
|
||||
"""
|
||||
# 只读预取在审计上下文之前:摘要需要客户名与新旧归属人名;校验仍在
|
||||
# 上下文内进行,失败同样要留下可追溯的记录
|
||||
row = customer_repository.get_with_owner_name(session, customer_id)
|
||||
old_person = (
|
||||
personnel_repository.get_by_id(session, row[0].owner_personnel_id)
|
||||
if row is not None and row[0].owner_personnel_id is not None
|
||||
else None
|
||||
)
|
||||
new_person = (
|
||||
personnel_repository.get_by_id(session, payload.new_owner_personnel_id)
|
||||
if payload.new_owner_personnel_id is not None
|
||||
else None
|
||||
)
|
||||
old_label = old_person.personnel_name if old_person else "无"
|
||||
new_label = new_person.personnel_name if new_person else "无"
|
||||
customer_name = row[0].company_name if row else f"#{customer_id}"
|
||||
prefetch = _prefetch_customer_ownership(session, customer_id, payload)
|
||||
with audit_service.audit(
|
||||
session,
|
||||
operator=operator,
|
||||
record=AuditRecord(
|
||||
module=MODULE_CUSTOMER,
|
||||
action=ACTION_UPDATE,
|
||||
summary=f"调整客户归属 {customer_name}:{old_label} → {new_label}",
|
||||
summary=(
|
||||
f"调整客户归属 {prefetch.customer_name}:"
|
||||
f"{prefetch.old_label} → {prefetch.new_label}"
|
||||
),
|
||||
request_data=payload.model_dump(exclude_none=True),
|
||||
),
|
||||
meta=meta,
|
||||
):
|
||||
if row is None:
|
||||
if prefetch.row is None:
|
||||
raise NotFoundError("客户不存在")
|
||||
customer, _ = row
|
||||
customer, _ = prefetch.row
|
||||
|
||||
if payload.new_owner_personnel_id is not None:
|
||||
_ensure_owner_personnel(session, payload.new_owner_personnel_id)
|
||||
old_owner_id = customer.owner_personnel_id
|
||||
if old_owner_id == payload.new_owner_personnel_id:
|
||||
raise BadRequestError("归属未变化")
|
||||
old_owner_id = _validate_customer_ownership(session, customer, payload)
|
||||
|
||||
# 主表更新与留痕插入同事务:只在本方法内一次 commit(见模块 docstring)
|
||||
customer.owner_personnel_id = payload.new_owner_personnel_id
|
||||
customer_repository.add_ownership_log(
|
||||
session,
|
||||
OwnershipChangeLog(
|
||||
owner_type=OWNER_TYPE_CUSTOMER,
|
||||
customer_id=customer.id,
|
||||
old_owner_personnel_id=old_owner_id,
|
||||
new_owner_personnel_id=payload.new_owner_personnel_id,
|
||||
change_reason=payload.reason,
|
||||
operator_id=operator.id,
|
||||
operator_name=operator.username,
|
||||
),
|
||||
session, _customer_ownership_log(customer, payload, old_owner_id, operator)
|
||||
)
|
||||
# 响应在 commit 之前构造(同 user_service 顶部说明);归属人名以新值为准
|
||||
out = _to_out(customer, new_person.personnel_name if new_person else None)
|
||||
out = _to_out(customer, prefetch.new_person.personnel_name if prefetch.new_person else None)
|
||||
session.commit()
|
||||
logger.info(
|
||||
"调整客户归属 | customer_id=%s | old=%s | new=%s",
|
||||
|
||||
@@ -168,9 +168,7 @@ def _warning_params(session: Session) -> dict:
|
||||
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"))
|
||||
),
|
||||
"approval_timeout_days": int(parse_fraction(snapshot.get("warning.approval.timeout.days"))),
|
||||
}
|
||||
|
||||
|
||||
@@ -253,9 +251,11 @@ def _activities(session: Session) -> list[dict]:
|
||||
"""最近动态(FR-036):以操作日志为唯一来源(写操作即留痕)。"""
|
||||
logs = operation_log_repository.list_logs(
|
||||
session,
|
||||
offset=0,
|
||||
limit=_ACTIVITY_LIMIT,
|
||||
filters=LogFilters(),
|
||||
operation_log_repository.OperationLogListQuery(
|
||||
filters=LogFilters(),
|
||||
offset=0,
|
||||
limit=_ACTIVITY_LIMIT,
|
||||
),
|
||||
)
|
||||
return [
|
||||
{
|
||||
|
||||
@@ -22,18 +22,15 @@ from app.schemas.log import (
|
||||
|
||||
def list_operation_logs(session: Session, query: OperationLogQuery) -> PageResult[OperationLogOut]:
|
||||
"""分页查询操作日志(列表不含 request_data,详情走 `get_operation_log`)。"""
|
||||
filters = _filters_from(query)
|
||||
logs = operation_log_repository.list_logs(
|
||||
session,
|
||||
repo_query = operation_log_repository.OperationLogListQuery(
|
||||
filters=_filters_from(query),
|
||||
offset=query.offset,
|
||||
limit=query.page_size,
|
||||
filters=filters,
|
||||
module=query.module,
|
||||
action=query.action,
|
||||
)
|
||||
total = operation_log_repository.count_logs(
|
||||
session, filters=filters, module=query.module, action=query.action
|
||||
)
|
||||
logs = operation_log_repository.list_logs(session, repo_query)
|
||||
total = operation_log_repository.count_logs(session, repo_query)
|
||||
return PageResult[OperationLogOut](
|
||||
records=[OperationLogOut.model_validate(log) for log in logs],
|
||||
total=total,
|
||||
@@ -55,15 +52,14 @@ def get_operation_log(session: Session, log_id: int) -> OperationLogDetailOut:
|
||||
|
||||
def list_login_logs(session: Session, query: LoginLogQuery) -> PageResult[LoginLogOut]:
|
||||
"""分页查询登录日志。"""
|
||||
filters = _filters_from(query)
|
||||
logs = login_log_repository.list_logs(
|
||||
session,
|
||||
repo_query = login_log_repository.LoginLogListQuery(
|
||||
filters=_filters_from(query),
|
||||
offset=query.offset,
|
||||
limit=query.page_size,
|
||||
filters=filters,
|
||||
ip=query.ip,
|
||||
)
|
||||
total = login_log_repository.count_logs(session, filters=filters, ip=query.ip)
|
||||
logs = login_log_repository.list_logs(session, repo_query)
|
||||
total = login_log_repository.count_logs(session, repo_query)
|
||||
return PageResult[LoginLogOut](
|
||||
records=[LoginLogOut.model_validate(log) for log in logs],
|
||||
total=total,
|
||||
|
||||
@@ -341,9 +341,7 @@ PARAM_REGISTRY: dict[str, ParamSpec] = {
|
||||
default_value="90",
|
||||
value_min="1",
|
||||
value_max=None,
|
||||
description=(
|
||||
"发货后超过该天数仍未回款的发货批次触发预警(澄清 #10 建议默认 90 天)"
|
||||
),
|
||||
description=("发货后超过该天数仍未回款的发货批次触发预警(澄清 #10 建议默认 90 天)"),
|
||||
sort_order=22,
|
||||
),
|
||||
ParamSpec(
|
||||
@@ -357,9 +355,7 @@ PARAM_REGISTRY: dict[str, ParamSpec] = {
|
||||
default_value="3",
|
||||
value_min="1",
|
||||
value_max=None,
|
||||
description=(
|
||||
"待审批单提交后超过该天数未处理触发预警(澄清 #10 建议默认 3 天)"
|
||||
),
|
||||
description=("待审批单提交后超过该天数未处理触发预警(澄清 #10 建议默认 3 天)"),
|
||||
sort_order=23,
|
||||
),
|
||||
]
|
||||
|
||||
@@ -6,7 +6,7 @@ ParamSnapshot 是 M3 核算与计算预览共用的输入契约:按业务日
|
||||
"""
|
||||
|
||||
import logging
|
||||
from collections.abc import Iterable
|
||||
from collections.abc import Callable, Iterable
|
||||
from dataclasses import dataclass
|
||||
from datetime import date
|
||||
from decimal import Decimal
|
||||
@@ -379,16 +379,8 @@ def get_history(
|
||||
definition = param_repository.get_definition_by_code(session, param_code)
|
||||
if definition is None:
|
||||
raise NotFoundError("参数不存在")
|
||||
rows = param_repository.list_history(
|
||||
session,
|
||||
definition.id,
|
||||
offset=query.offset,
|
||||
limit=query.page_size,
|
||||
dimension_value=query.dimension_value,
|
||||
)
|
||||
total = param_repository.count_history(
|
||||
session, definition.id, dimension_value=query.dimension_value
|
||||
)
|
||||
rows = param_repository.list_history(session, definition.id, query)
|
||||
total = param_repository.count_history(session, definition.id, query)
|
||||
return PageResult[ParamHistoryOut](
|
||||
records=[
|
||||
ParamHistoryOut(
|
||||
@@ -410,16 +402,8 @@ def get_history(
|
||||
|
||||
def list_batches(session: Session, query: ParamBatchQuery) -> PageResult[ParamBatchOut]:
|
||||
"""变更批次分页(按创建时间倒序)。"""
|
||||
batches = param_repository.list_batches(
|
||||
session,
|
||||
offset=query.offset,
|
||||
limit=query.page_size,
|
||||
start_date=query.start_date,
|
||||
end_date=query.end_date,
|
||||
)
|
||||
total = param_repository.count_batches(
|
||||
session, start_date=query.start_date, end_date=query.end_date
|
||||
)
|
||||
batches = param_repository.list_batches(session, query)
|
||||
total = param_repository.count_batches(session, query)
|
||||
return PageResult[ParamBatchOut](
|
||||
records=[
|
||||
ParamBatchOut(
|
||||
@@ -509,19 +493,66 @@ def compare(session: Session, *, from_date: date, to_date: date) -> list[ParamDi
|
||||
return out
|
||||
|
||||
|
||||
def _preview_rate(
|
||||
session: Session,
|
||||
payload: ParamPreviewIn,
|
||||
snapshot: ParamSnapshot,
|
||||
days: int,
|
||||
take,
|
||||
) -> tuple[Fraction, str, Decimal | None]:
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class _PreviewContext:
|
||||
"""预览上下文(会话、入参、参数取值闭包)。
|
||||
|
||||
``take`` 闭包同时负责取数与记录「用了哪些参数」——**调用顺序即
|
||||
``params_used`` 的展示顺序**,拆分时不得调换各段的先后。
|
||||
"""
|
||||
|
||||
session: Session
|
||||
payload: ParamPreviewIn
|
||||
take: Callable[[str], Fraction]
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class _PreviewRateDecision:
|
||||
"""计提比例判定(回款天数、纯比例、人读说明、绩效基数覆盖值)。"""
|
||||
|
||||
days: int
|
||||
rate: Fraction
|
||||
rate_text: str
|
||||
base_override: Decimal | None
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class _PreviewEarning:
|
||||
"""折算与绩效(毛利润率、折算额、绩效额)。"""
|
||||
|
||||
profit_rate: Fraction
|
||||
converted: Decimal
|
||||
performance: Decimal
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class _PreviewBarter:
|
||||
"""以物抵顶(是否适用、折算后绩效、计发基数)。"""
|
||||
|
||||
applied: bool
|
||||
after_barter: Decimal | None
|
||||
base_amount: Decimal
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class _PreviewPayment:
|
||||
"""支付环节(起付判定、R 权重、权重、应付金额)。"""
|
||||
|
||||
start_ok: bool
|
||||
weight_r: int
|
||||
weight: Fraction
|
||||
payable: Decimal
|
||||
|
||||
|
||||
def _preview_rate(ctx: _PreviewContext, days: int) -> tuple[Fraction, str, Decimal | None]:
|
||||
"""按岗位模板分派计提比例,返回(纯比例, 人读说明, 绩效基数覆盖值)。
|
||||
|
||||
基数覆盖值非 None 表示该模板的绩效基数不是折算毛利润额(如信息员按
|
||||
「本人销售额」计提),预览层直接采用并跳过折算与阈值。
|
||||
聚合模板(营销经理 12.5%+5%)依赖月度团队数据,不支持单笔预览。
|
||||
"""
|
||||
payload = ctx.payload
|
||||
take = ctx.take
|
||||
if payload.customer_type == "enterprise":
|
||||
# 存储口径为 ‰ 数(如 "3"),除以 1000 转纯比例 —— performance_amount
|
||||
# 按纯比例相乘,漏换算会把绩效金额放大 1000 倍(与业务员分支同防线)
|
||||
@@ -531,7 +562,7 @@ def _preview_rate(
|
||||
role_code = payload.business_role
|
||||
template = "TPL_SALESPERSON_DECAY"
|
||||
if role_code:
|
||||
role = business_role_repository.get_by_code(session, role_code)
|
||||
role = business_role_repository.get_by_code(ctx.session, role_code)
|
||||
if role is None:
|
||||
raise BadRequestError(f"岗位 {role_code!r} 不存在")
|
||||
template = role.calc_template
|
||||
@@ -561,12 +592,73 @@ def _preview_rate(
|
||||
raise BadRequestError(f"公式模板 {template} 暂不支持预览")
|
||||
|
||||
|
||||
def _preview_rate_decision(ctx: _PreviewContext) -> _PreviewRateDecision:
|
||||
"""产品类别校验 + 回款天数 + 计提比例判定。"""
|
||||
payload = ctx.payload
|
||||
if payload.product_category and payload.product_category not in PRODUCT_CATEGORIES:
|
||||
raise BadRequestError(
|
||||
f"产品类别 {payload.product_category!r} 不存在,可选:municipal_water / rail_transit"
|
||||
)
|
||||
days = formula.payment_days(payload.ship_date, payload.receipt_date)
|
||||
rate, rate_text, base_override = _preview_rate(ctx, days)
|
||||
return _PreviewRateDecision(
|
||||
days=days, rate=rate, rate_text=rate_text, base_override=base_override
|
||||
)
|
||||
|
||||
|
||||
def _preview_earning(ctx: _PreviewContext, decision: _PreviewRateDecision) -> _PreviewEarning:
|
||||
"""毛利润率 → 折算额(阈值)→ 绩效额(比例)。"""
|
||||
payload = ctx.payload
|
||||
revenue = Decimal(payload.revenue)
|
||||
profit = Decimal(payload.profit)
|
||||
profit_rate = formula.profit_rate(profit, revenue)
|
||||
if decision.base_override is not None:
|
||||
# 基数覆盖(信息员按本人销售额计提):不走折算与阈值
|
||||
converted = decision.base_override
|
||||
else:
|
||||
threshold = ctx.take("product.threshold")
|
||||
converted = formula.converted_profit(revenue, profit_rate, threshold)
|
||||
performance = formula.performance_amount(converted, decision.rate)
|
||||
return _PreviewEarning(profit_rate=profit_rate, converted=converted, performance=performance)
|
||||
|
||||
|
||||
def _preview_barter(ctx: _PreviewContext, performance: Decimal) -> _PreviewBarter:
|
||||
"""以物抵顶折算(按应发绩效的固定比例折算,比例来自参数)。"""
|
||||
applied = ctx.payload.barter
|
||||
after_barter: Decimal | None = None
|
||||
if applied:
|
||||
discount = ctx.take("barter.discount")
|
||||
after_barter = formula.apply_barter(performance, discount)
|
||||
base_amount = after_barter if applied else performance
|
||||
return _PreviewBarter(applied=applied, after_barter=after_barter, base_amount=base_amount)
|
||||
|
||||
|
||||
def _preview_payment(
|
||||
ctx: _PreviewContext, received: Decimal, revenue: Decimal, base_amount: Decimal
|
||||
) -> _PreviewPayment:
|
||||
"""起付比例判定 + R 权重 + 应付金额。"""
|
||||
start_ratio = ctx.take("payment.start.ratio")
|
||||
start_ok = formula.start_payment_ok(received, revenue, start_ratio)
|
||||
# R 钳制已提取为纯函数 clamp_weight_r(④ 核算与预览共用同一实现)
|
||||
weight_r = formula.clamp_weight_r(received, revenue)
|
||||
weight = formula.payment_weight(weight_r)
|
||||
payable = to_decimal(Fraction(base_amount) * weight)
|
||||
return _PreviewPayment(start_ok=start_ok, weight_r=weight_r, weight=weight, payable=payable)
|
||||
|
||||
|
||||
def _preview_probation_note(ctx: _PreviewContext) -> str | None:
|
||||
"""试用期说明(绩效照算不发放,年累计超阈值的部分年底一次性结算)。"""
|
||||
if not ctx.payload.probation:
|
||||
return None
|
||||
annual = ctx.take("probation.annual.threshold")
|
||||
return f"试用期绩效照算不发放;年累计超 {to_decimal(annual)} 元部分年底一次性结算"
|
||||
|
||||
|
||||
def preview(session: Session, payload: ParamPreviewIn) -> ParamPreviewOut:
|
||||
"""计算预览:入参(发货/回款/金额/岗位)→ 公式纯函数 → 出参(含所用参数)。"""
|
||||
# 参数按回款到账日取值(对照表 #11)
|
||||
snapshot = resolve_snapshot(session, payload.receipt_date)
|
||||
revenue = Decimal(payload.revenue)
|
||||
profit = Decimal(payload.profit)
|
||||
received = Decimal(payload.received_amount)
|
||||
used: list[ParamUsedOut] = []
|
||||
|
||||
@@ -589,55 +681,29 @@ def preview(session: Session, payload: ParamPreviewIn) -> ParamPreviewOut:
|
||||
)
|
||||
return parse_fraction(raw)
|
||||
|
||||
if payload.product_category and payload.product_category not in PRODUCT_CATEGORIES:
|
||||
raise BadRequestError(
|
||||
f"产品类别 {payload.product_category!r} 不存在,可选:municipal_water / rail_transit"
|
||||
)
|
||||
|
||||
days = formula.payment_days(payload.ship_date, payload.receipt_date)
|
||||
rate, rate_text, base_override = _preview_rate(session, payload, snapshot, days, take)
|
||||
|
||||
profit_rate = formula.profit_rate(profit, revenue)
|
||||
if base_override is not None:
|
||||
# 基数覆盖(信息员按本人销售额计提):不走折算与阈值
|
||||
converted = base_override
|
||||
else:
|
||||
threshold = take("product.threshold")
|
||||
converted = formula.converted_profit(revenue, profit_rate, threshold)
|
||||
performance = formula.performance_amount(converted, rate)
|
||||
|
||||
barter_applied = payload.barter
|
||||
after_barter: Decimal | None = None
|
||||
if barter_applied:
|
||||
discount = take("barter.discount")
|
||||
after_barter = formula.apply_barter(performance, discount)
|
||||
|
||||
start_ratio = take("payment.start.ratio")
|
||||
start_ok = formula.start_payment_ok(received, revenue, start_ratio)
|
||||
# R 钳制已提取为纯函数 clamp_weight_r(④ 核算与预览共用同一实现)
|
||||
weight_r = formula.clamp_weight_r(received, revenue)
|
||||
weight = formula.payment_weight(weight_r)
|
||||
base_amount = after_barter if barter_applied else performance
|
||||
payable = to_decimal(Fraction(base_amount) * weight)
|
||||
|
||||
probation_note: str | None = None
|
||||
if payload.probation:
|
||||
annual = take("probation.annual.threshold")
|
||||
probation_note = f"试用期绩效照算不发放;年累计超 {to_decimal(annual)} 元部分年底一次性结算"
|
||||
ctx = _PreviewContext(session=session, payload=payload, take=take)
|
||||
# 各段顺序固定 —— take 的调用顺序即 params_used 的展示顺序
|
||||
decision = _preview_rate_decision(ctx)
|
||||
earning = _preview_earning(ctx, decision)
|
||||
barter = _preview_barter(ctx, earning.performance)
|
||||
payment = _preview_payment(ctx, received, revenue, barter.base_amount)
|
||||
probation_note = _preview_probation_note(ctx)
|
||||
|
||||
return ParamPreviewOut(
|
||||
payment_days=days,
|
||||
rate=str(rate),
|
||||
rate_text=rate_text,
|
||||
profit_rate=str(profit_rate),
|
||||
converted_profit=str(converted),
|
||||
performance_amount=str(performance),
|
||||
barter_applied=barter_applied,
|
||||
performance_after_barter=str(after_barter) if after_barter is not None else None,
|
||||
start_payment_ok=start_ok,
|
||||
payment_weight_r=weight_r,
|
||||
payment_weight=str(weight),
|
||||
payable_amount=str(payable),
|
||||
payment_days=decision.days,
|
||||
rate=str(decision.rate),
|
||||
rate_text=decision.rate_text,
|
||||
profit_rate=str(earning.profit_rate),
|
||||
converted_profit=str(earning.converted),
|
||||
performance_amount=str(earning.performance),
|
||||
barter_applied=barter.applied,
|
||||
performance_after_barter=(
|
||||
str(barter.after_barter) if barter.after_barter is not None else None
|
||||
),
|
||||
start_payment_ok=payment.start_ok,
|
||||
payment_weight_r=payment.weight_r,
|
||||
payment_weight=str(payment.weight),
|
||||
payable_amount=str(payment.payable),
|
||||
probation_note=probation_note,
|
||||
params_used=used,
|
||||
)
|
||||
|
||||
@@ -70,20 +70,8 @@ def ensure_active(session: Session, personnel_id: int, *, label: str) -> Personn
|
||||
|
||||
def list_personnel(session: Session, query: PersonnelQuery) -> PageResult[PersonnelOut]:
|
||||
"""分页查询人员(含离职)。"""
|
||||
rows = personnel_repository.list_personnel(
|
||||
session,
|
||||
offset=query.offset,
|
||||
limit=query.page_size,
|
||||
keyword=query.keyword,
|
||||
status=query.status,
|
||||
business_role_id=query.business_role_id,
|
||||
)
|
||||
total = personnel_repository.count_personnel(
|
||||
session,
|
||||
keyword=query.keyword,
|
||||
status=query.status,
|
||||
business_role_id=query.business_role_id,
|
||||
)
|
||||
rows = personnel_repository.list_personnel(session, query)
|
||||
total = personnel_repository.count_personnel(session, query)
|
||||
return PageResult[PersonnelOut](
|
||||
records=[
|
||||
_to_out(personnel, role_name, manager_name)
|
||||
|
||||
@@ -99,20 +99,8 @@ def _raise_if_duplicate(exc: IntegrityError) -> None:
|
||||
|
||||
def list_products(session: Session, query: ProductQuery) -> PageResult[ProductOut]:
|
||||
"""分页查询产品(含停用)。"""
|
||||
products = product_repository.list_products(
|
||||
session,
|
||||
offset=query.offset,
|
||||
limit=query.page_size,
|
||||
keyword=query.keyword,
|
||||
product_category=query.product_category,
|
||||
status=query.status,
|
||||
)
|
||||
total = product_repository.count_products(
|
||||
session,
|
||||
keyword=query.keyword,
|
||||
product_category=query.product_category,
|
||||
status=query.status,
|
||||
)
|
||||
products = product_repository.list_products(session, query)
|
||||
total = product_repository.count_products(session, query)
|
||||
return PageResult[ProductOut](
|
||||
records=[_to_out(product) for product in products],
|
||||
total=total,
|
||||
|
||||
@@ -23,6 +23,7 @@
|
||||
"""
|
||||
|
||||
import logging
|
||||
from dataclasses import dataclass
|
||||
from datetime import date
|
||||
from decimal import Decimal
|
||||
|
||||
@@ -39,7 +40,7 @@ from app.core.constants import (
|
||||
from app.core.db_errors import is_duplicate_entry
|
||||
from app.core.exceptions import BadRequestError, NotFoundError
|
||||
from app.core.response import PageResult
|
||||
from app.models import Receipt
|
||||
from app.models import Business, Receipt
|
||||
from app.models.business import BUSINESS_STATUS_ACTIVE
|
||||
from app.models.receipt import SETTLEMENT_DONE, SETTLEMENT_PENDING
|
||||
from app.repositories import business_repository, receipt_repository
|
||||
@@ -129,24 +130,8 @@ def _ensure_business_writable(session: Session, business_id: int, action: str):
|
||||
|
||||
def list_receipts(session: Session, query: ReceiptQuery) -> PageResult[ReceiptOut]:
|
||||
"""分页查询回款(附业务号/发货单号与 payment_days 派生值)。"""
|
||||
rows = receipt_repository.list_receipts(
|
||||
session,
|
||||
offset=query.offset,
|
||||
limit=query.page_size,
|
||||
business_id=query.business_id,
|
||||
date_from=query.date_from,
|
||||
date_to=query.date_to,
|
||||
is_barter=query.is_barter,
|
||||
settlement_status=query.settlement_status,
|
||||
)
|
||||
total = receipt_repository.count_receipts(
|
||||
session,
|
||||
business_id=query.business_id,
|
||||
date_from=query.date_from,
|
||||
date_to=query.date_to,
|
||||
is_barter=query.is_barter,
|
||||
settlement_status=query.settlement_status,
|
||||
)
|
||||
rows = receipt_repository.list_receipts(session, query)
|
||||
total = receipt_repository.count_receipts(session, query)
|
||||
return PageResult[ReceiptOut](
|
||||
records=[_to_out(row) for row in rows],
|
||||
total=total,
|
||||
@@ -166,6 +151,57 @@ def get_detail(session: Session, receipt_id: int) -> ReceiptOut:
|
||||
return _to_out(row)
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class _CreatedReceipt:
|
||||
"""建行结果(出参 + 固化的 ID/批次号,commit 后不再触碰 ORM 属性)。"""
|
||||
|
||||
out: ReceiptOut
|
||||
receipt_id: int
|
||||
batch_no: str
|
||||
|
||||
|
||||
def _create_receipt_once(
|
||||
session: Session,
|
||||
payload: ReceiptCreateIn,
|
||||
business: Business | None,
|
||||
batch_no: str,
|
||||
) -> _CreatedReceipt:
|
||||
"""一次建行尝试:准入校验 → 建行 → 重算合计 → 出参。
|
||||
|
||||
**不 commit**:提交与回滚由调用方(重试循环)统一控制,保证「一次尝试
|
||||
= 一个事务边界」。
|
||||
"""
|
||||
if business is None:
|
||||
raise NotFoundError("业务不存在")
|
||||
if business.status != BUSINESS_STATUS_ACTIVE:
|
||||
raise BadRequestError("业务已完成或已终止,禁止新增回款")
|
||||
# 月结锁定拦截(2026-10-15 补充需求):比需求原文「提示」取硬,
|
||||
# 一期安全侧(策略点注释);未指定日期时以当天月近似
|
||||
from app.services import settlement_service
|
||||
|
||||
_lock_month = (payload.receipt_date or date.today()).strftime("%Y-%m")
|
||||
settlement_service.ensure_month_not_locked(session, _lock_month)
|
||||
shipment_no, ship_date = _ensure_shipment_of_business(
|
||||
session, payload.shipment_id, payload.business_id
|
||||
)
|
||||
receipt = receipt_repository.create(
|
||||
session,
|
||||
Receipt(
|
||||
receipt_batch_no=batch_no,
|
||||
business_id=payload.business_id,
|
||||
shipment_id=payload.shipment_id,
|
||||
receipt_date=payload.receipt_date,
|
||||
amount=Decimal(payload.amount),
|
||||
is_barter=payload.is_barter,
|
||||
settlement_status=SETTLEMENT_PENDING,
|
||||
remark=payload.remark,
|
||||
),
|
||||
)
|
||||
_recalc_totals(session, business)
|
||||
out = _to_out((receipt, business.business_no, shipment_no, ship_date))
|
||||
return _CreatedReceipt(out=out, receipt_id=receipt.id, batch_no=batch_no)
|
||||
|
||||
|
||||
def create_receipt(
|
||||
session: Session,
|
||||
payload: ReceiptCreateIn,
|
||||
@@ -206,35 +242,7 @@ def create_receipt(
|
||||
# 锁业务行与生成批次号——成功/最终失败各只记一条审计,无递归
|
||||
for attempt in range(_NO_RETRY + 1):
|
||||
try:
|
||||
if business is None:
|
||||
raise NotFoundError("业务不存在")
|
||||
if business.status != BUSINESS_STATUS_ACTIVE:
|
||||
raise BadRequestError("业务已完成或已终止,禁止新增回款")
|
||||
# 月结锁定拦截(2026-10-15 补充需求):比需求原文「提示」取硬,
|
||||
# 一期安全侧(策略点注释);未指定日期时以当天月近似
|
||||
from app.services import settlement_service
|
||||
|
||||
_lock_month = (payload.receipt_date or date.today()).strftime("%Y-%m")
|
||||
settlement_service.ensure_month_not_locked(session, _lock_month)
|
||||
shipment_no, ship_date = _ensure_shipment_of_business(
|
||||
session, payload.shipment_id, payload.business_id
|
||||
)
|
||||
receipt = receipt_repository.create(
|
||||
session,
|
||||
Receipt(
|
||||
receipt_batch_no=batch_no,
|
||||
business_id=payload.business_id,
|
||||
shipment_id=payload.shipment_id,
|
||||
receipt_date=payload.receipt_date,
|
||||
amount=Decimal(payload.amount),
|
||||
is_barter=payload.is_barter,
|
||||
settlement_status=SETTLEMENT_PENDING,
|
||||
remark=payload.remark,
|
||||
),
|
||||
)
|
||||
_recalc_totals(session, business)
|
||||
out = _to_out((receipt, business.business_no, shipment_no, ship_date))
|
||||
new_id, new_no = receipt.id, batch_no # 固化:commit 后不碰 ORM
|
||||
created = _create_receipt_once(session, payload, business, batch_no)
|
||||
session.commit()
|
||||
break
|
||||
except IntegrityError as exc:
|
||||
@@ -249,11 +257,11 @@ def create_receipt(
|
||||
|
||||
logger.info(
|
||||
"新增回款 | receipt_id=%s | no=%s | business_id=%s",
|
||||
new_id,
|
||||
new_no,
|
||||
created.receipt_id,
|
||||
created.batch_no,
|
||||
payload.business_id,
|
||||
)
|
||||
return out
|
||||
return created.out
|
||||
|
||||
|
||||
def update_receipt(
|
||||
|
||||
@@ -36,7 +36,6 @@ _DATE_FORMAT = "YYYY-MM-DD"
|
||||
_FORMULA_PREFIXES = ("=", "+", "-", "@", "\t")
|
||||
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class _Column:
|
||||
"""列定义:key 取行 dict 字段,kind 决定单元格类型与格式。"""
|
||||
@@ -403,7 +402,13 @@ def _write_department_document(
|
||||
company_share_count = int(company.get("company_share_count") or 0)
|
||||
|
||||
_write_document_header(
|
||||
sheet, len(_DEPARTMENT_WIDTHS), company_name, title, filters, template_version, operator_name
|
||||
sheet,
|
||||
len(_DEPARTMENT_WIDTHS),
|
||||
company_name,
|
||||
title,
|
||||
filters,
|
||||
template_version,
|
||||
operator_name,
|
||||
)
|
||||
|
||||
_write_block(
|
||||
@@ -439,16 +444,12 @@ def _write_department_document(
|
||||
"manager_name": "合计",
|
||||
"member_count": sum(team["member_count"] for team in teams),
|
||||
"team_base": _sum_amount(team["team_base"] for team in teams),
|
||||
"team_share_amount": _sum_amount(
|
||||
team["team_share_amount"] for team in teams
|
||||
),
|
||||
"team_share_amount": _sum_amount(team["team_share_amount"] for team in teams),
|
||||
"team_subtotal": _sum_amount(team["team_subtotal"] for team in teams),
|
||||
# 未生成月结时全部为 None,合计也留空(不能显示 0.00 误导)
|
||||
"frozen_amount": (
|
||||
_sum_amount(
|
||||
team["frozen_amount"]
|
||||
for team in teams
|
||||
if team["frozen_amount"] is not None
|
||||
team["frozen_amount"] for team in teams if team["frozen_amount"] is not None
|
||||
)
|
||||
if any(team["frozen_amount"] is not None for team in teams)
|
||||
else None
|
||||
|
||||
@@ -103,10 +103,7 @@ def _person_row(row: PerformanceLedger, role_names: dict[str, str]) -> dict:
|
||||
|
||||
def _role_names(session) -> dict[str, str]:
|
||||
"""岗位编码 → 名称一次查询(明细与部门行共用,避免 N+1)。"""
|
||||
return {
|
||||
r.role_code: r.role_name
|
||||
for r in session.execute(select(BusinessRole)).scalars()
|
||||
}
|
||||
return {r.role_code: r.role_name for r in session.execute(select(BusinessRole)).scalars()}
|
||||
|
||||
|
||||
def _dec(value) -> Decimal | None:
|
||||
@@ -178,11 +175,7 @@ def department_summary(session, query) -> dict:
|
||||
extra_ids = {
|
||||
target
|
||||
for pid in adjustments
|
||||
if (
|
||||
target := _adjustment_target(
|
||||
pid, member_map, manager_of, manager_role, include_mp
|
||||
)
|
||||
)
|
||||
if (target := _adjustment_target(pid, member_map, manager_of, manager_role, include_mp))
|
||||
is not None
|
||||
} - set(manager_ids)
|
||||
if extra_ids:
|
||||
@@ -193,9 +186,7 @@ def department_summary(session, query) -> dict:
|
||||
for team in teams_all
|
||||
if query.manager_id is None or team["manager_id"] == query.manager_id
|
||||
]
|
||||
unassigned_all = _unassigned_rows(
|
||||
member_map, manager_of, manager_role, adjustments, include_mp
|
||||
)
|
||||
unassigned_all = _unassigned_rows(member_map, manager_of, manager_role, adjustments, include_mp)
|
||||
# 「仅看某经理团队」时未分配桶不随展示:全公司无经理人员与该团队无关
|
||||
unassigned = [] if query.manager_id is not None else unassigned_all
|
||||
company_share_amount = _company_share(company_base, share.company_pct)
|
||||
@@ -335,9 +326,7 @@ def _reconciliation(
|
||||
(m["adjust_net"] for team in teams for m in team["members"]), Decimal("0")
|
||||
) + sum((row["adjust_net"] for row in unassigned), Decimal("0"))
|
||||
team_base_total = sum((team["team_base"] for team in teams), Decimal("0"))
|
||||
unassigned_performance = sum(
|
||||
(row["performance_sum"] for row in unassigned), Decimal("0")
|
||||
)
|
||||
unassigned_performance = sum((row["performance_sum"] for row in unassigned), Decimal("0"))
|
||||
payable_total = (
|
||||
team_member_payable + unassigned_payable + aggregate_payable_total + adjust_net_total
|
||||
)
|
||||
@@ -378,9 +367,7 @@ def _reconciliation(
|
||||
|
||||
def _team_share(team_base: Decimal, team_pct: Fraction) -> Decimal:
|
||||
"""12.5% 团队分成:全公司部分传 0,仅取 team_pct 项。"""
|
||||
return manager_team_share(
|
||||
team_base, Decimal("0"), team_pct=team_pct, company_pct=Fraction(0)
|
||||
)
|
||||
return manager_team_share(team_base, Decimal("0"), team_pct=team_pct, company_pct=Fraction(0))
|
||||
|
||||
|
||||
def _company_share(company_base: Decimal, company_pct: Fraction) -> Decimal:
|
||||
@@ -483,12 +470,8 @@ def _team_relations(
|
||||
referenced = {p.manager_id for p in people if p.manager_id is not None}
|
||||
missing = referenced - seed
|
||||
if missing:
|
||||
people.extend(
|
||||
session.execute(select(Personnel).where(Personnel.id.in_(missing))).scalars()
|
||||
)
|
||||
role_by_id = {
|
||||
r.id: r.role_code for r in session.execute(select(BusinessRole)).scalars()
|
||||
}
|
||||
people.extend(session.execute(select(Personnel).where(Personnel.id.in_(missing))).scalars())
|
||||
role_by_id = {r.id: r.role_code for r in session.execute(select(BusinessRole)).scalars()}
|
||||
manager_of = {p.id: p.manager_id for p in people}
|
||||
manager_role = {p.id: role_by_id.get(p.business_role_id, "") for p in people}
|
||||
person_info = {
|
||||
@@ -619,9 +602,7 @@ def _member_rows(
|
||||
)
|
||||
)
|
||||
personal_in_team = (
|
||||
pid == manager_id
|
||||
and include_manager_personal
|
||||
and member["has_manager_personal"]
|
||||
pid == manager_id and include_manager_personal and member["has_manager_personal"]
|
||||
)
|
||||
if personal_in_team:
|
||||
rows.append(
|
||||
@@ -893,9 +874,7 @@ def _group_rows(rows) -> list[dict]:
|
||||
def payment_detail(session, query) -> dict:
|
||||
"""区间下钻分页(bucket 未注册 → 400)。"""
|
||||
bucket = _bucket_by_code(query.bucket)
|
||||
rows = report_repository.list_payment_detail(
|
||||
session, query, bucket, offset=query.offset, limit=query.page_size
|
||||
)
|
||||
rows = report_repository.list_payment_detail(session, query, bucket)
|
||||
return {
|
||||
"list": [_payment_row(r) for r in rows],
|
||||
"total": report_repository.count_payment_detail(session, query, bucket),
|
||||
|
||||
@@ -68,14 +68,8 @@ def list_roles(session: Session, query: RoleQuery) -> PageResult[RoleManageOut]:
|
||||
与用户表单下拉(`/users/meta/roles`)口径不同:**管理列表含停用角色**,
|
||||
下拉只给启用项。
|
||||
"""
|
||||
roles = role_repository.list_roles(
|
||||
session,
|
||||
offset=query.offset,
|
||||
limit=query.page_size,
|
||||
keyword=query.keyword,
|
||||
status=query.status,
|
||||
)
|
||||
total = role_repository.count_roles(session, keyword=query.keyword, status=query.status)
|
||||
roles = role_repository.list_roles(session, query)
|
||||
total = role_repository.count_roles(session, query)
|
||||
counts = role_repository.count_users_by_role(session, [role.id for role in roles])
|
||||
return PageResult[RoleManageOut](
|
||||
records=[_to_out(role, counts.get(role.id, 0)) for role in roles],
|
||||
|
||||
@@ -157,20 +157,8 @@ def _is_duplicate_entry(exc: IntegrityError) -> bool:
|
||||
|
||||
def list_shipments(session: Session, query: ShipmentQuery) -> PageResult[ShipmentOut]:
|
||||
"""分页查询发货单(附业务号;business_id 可空=全量,一期按业务维度查看为主)。"""
|
||||
rows = shipment_repository.list_shipments(
|
||||
session,
|
||||
offset=query.offset,
|
||||
limit=query.page_size,
|
||||
business_id=query.business_id,
|
||||
ship_date_from=query.ship_date_from,
|
||||
ship_date_to=query.ship_date_to,
|
||||
)
|
||||
total = shipment_repository.count_shipments(
|
||||
session,
|
||||
business_id=query.business_id,
|
||||
ship_date_from=query.ship_date_from,
|
||||
ship_date_to=query.ship_date_to,
|
||||
)
|
||||
rows = shipment_repository.list_shipments(session, query)
|
||||
total = shipment_repository.count_shipments(session, query)
|
||||
return PageResult[ShipmentOut](
|
||||
records=[_to_out(row) for row in rows],
|
||||
total=total,
|
||||
|
||||
@@ -68,22 +68,8 @@ def _to_out(user: User) -> UserOut:
|
||||
|
||||
def list_users(session: Session, query: UserQuery) -> PageResult[UserOut]:
|
||||
"""分页查询用户列表。"""
|
||||
users = user_repository.list_users(
|
||||
session,
|
||||
offset=query.offset,
|
||||
limit=query.page_size,
|
||||
username=query.username,
|
||||
real_name=query.real_name,
|
||||
status=query.status,
|
||||
role_code=query.role_code,
|
||||
)
|
||||
total = user_repository.count_users(
|
||||
session,
|
||||
username=query.username,
|
||||
real_name=query.real_name,
|
||||
status=query.status,
|
||||
role_code=query.role_code,
|
||||
)
|
||||
users = user_repository.list_users(session, query)
|
||||
total = user_repository.count_users(session, query)
|
||||
return PageResult[UserOut](
|
||||
records=[_to_out(user) for user in users],
|
||||
total=total,
|
||||
|
||||
Reference in new issue
Block a user