195 lines
11 KiB
Python
195 lines
11 KiB
Python
"""正式业务与额度共用事务;操作号覆盖整个业务载荷,死锁只重跑完整事务。"""
|
|
import hashlib
|
|
import inspect
|
|
import json
|
|
from functools import wraps
|
|
from uuid import uuid4
|
|
from fastapi import HTTPException
|
|
from fastapi.encoders import jsonable_encoder
|
|
from sqlalchemy.exc import OperationalError, IntegrityError
|
|
from app.models.pl_quota_models import PlCertOperation, PlPlanCertUsage
|
|
from app.schemas.pl.quota_planning import PlanQuotaOperation
|
|
from app.services.pl_quota_planning import _plan, build_usage_request, validate_conditions, plan_fingerprint
|
|
from app.services.pl_quota_cert_service import _audit, _get_row
|
|
from app.services.pl_quota_usage_service import execute_usage
|
|
from app.services.pl_quota_allocation import AllocationIncomplete
|
|
|
|
|
|
def business_hash(action, plan_id, payload):
|
|
return hashlib.sha256(json.dumps(jsonable_encoder([action, plan_id, payload]), sort_keys=True,
|
|
ensure_ascii=False, separators=(',', ':')).encode()).hexdigest()
|
|
|
|
|
|
def retry_transaction(db, work):
|
|
for attempt in range(3):
|
|
try:
|
|
return work()
|
|
except OperationalError as exc:
|
|
db.rollback()
|
|
if not exc.orig.args or exc.orig.args[0] != 1213 or attempt == 2:
|
|
raise
|
|
except Exception:
|
|
db.rollback()
|
|
raise
|
|
|
|
|
|
def atomic_plan_operation(action):
|
|
"""被装饰路由只能flush,最终提交连同业务结果一起完成。"""
|
|
def decorate(fn):
|
|
signature = inspect.signature(fn)
|
|
@wraps(fn)
|
|
def wrapped(*args, **kwargs):
|
|
values = signature.bind(*args, **kwargs).arguments
|
|
db, user = values['db'], values['user']
|
|
plan_id = values.get('plan_id', values.get('id'))
|
|
payload = values.get('payload', values.get('body'))
|
|
operation_id = getattr(payload, 'operation_id', None) or str(uuid4())
|
|
digest = business_hash(action, plan_id, payload)
|
|
def work():
|
|
if action == 'approval':
|
|
from app.models.pl_models import PlTransportApproval, PlPlan, PlTransport
|
|
from app.services.pl_data_scope import assert_pl_row_in_scope
|
|
approval = db.query(PlTransportApproval).filter_by(id=plan_id, tenant_no=user.tenant_no, del_flag=0).first()
|
|
if approval is None:
|
|
raise HTTPException(404, '审批记录不存在')
|
|
transport = db.query(PlTransport).filter_by(id=approval.transport_id, tenant_no=user.tenant_no, del_flag=0).first()
|
|
if transport is None:
|
|
raise HTTPException(404, '运输不存在')
|
|
assert_pl_row_in_scope(db, transport, PlTransport, user, user.tenant_no)
|
|
ids = db.query(PlPlan.id).filter_by(transport_id=transport.id, tenant_no=user.tenant_no, del_flag=0).order_by(PlPlan.id).all()
|
|
for row in ids:
|
|
assert_plan_can_arrange(_plan(db, user, row.id, lock=True))
|
|
db.query(PlTransportApproval).filter_by(id=plan_id, tenant_no=user.tenant_no, del_flag=0).with_for_update().populate_existing().one()
|
|
else:
|
|
_plan(db, user, plan_id, lock=True)
|
|
previous = db.query(PlCertOperation).filter_by(tenant_no=user.tenant_no, operation_id=operation_id).first()
|
|
if previous:
|
|
if previous.request_hash != digest:
|
|
raise HTTPException(409, '同一操作号不可用于不同业务请求')
|
|
return previous.result_json
|
|
operation = PlCertOperation(**_audit(user), operation_id=operation_id, action=action,
|
|
plan_id=plan_id, request_hash=digest)
|
|
db.add(operation)
|
|
try:
|
|
# 先占操作唯一键,再执行副作用;竞争者整个事务回滚后重读。
|
|
db.flush()
|
|
except IntegrityError as exc:
|
|
db.rollback()
|
|
previous = db.query(PlCertOperation).filter_by(tenant_no=user.tenant_no, operation_id=operation_id).first()
|
|
if previous and previous.request_hash == digest:
|
|
return previous.result_json
|
|
raise HTTPException(409, '同一操作号不可用于不同业务请求') from exc
|
|
result = fn(*args, **kwargs)
|
|
operation.result_json = jsonable_encoder(result)
|
|
db.commit()
|
|
return result
|
|
return retry_transaction(db, work)
|
|
return wrapped
|
|
return decorate
|
|
|
|
|
|
def validate_generic_status(payload, plan=None):
|
|
defaults = {'transport_status':'pending', 'archive_status':'unarchived',
|
|
'complete_status':'no', 'follow_status':'pending_arrange'}
|
|
for field, default in defaults.items():
|
|
if field in payload.model_fields_set:
|
|
value = getattr(payload, field, None)
|
|
if field == 'follow_status' and value in ('drafting', 'pending_arrange', 'wait_notice') and (plan is None or plan.follow_status in ('drafting', 'pending_arrange', 'wait_notice')):
|
|
continue
|
|
if value is not None and value != (getattr(plan, field) if plan else default):
|
|
raise HTTPException(409, '状态变更必须使用安排、归档或作废专用操作')
|
|
|
|
|
|
def apply_plan_quota(db, user, plan, action, payload=None):
|
|
from app.services.pl_quota_attachments import authorize_attachment
|
|
evidence_urls = getattr(payload, 'quota_evidence_urls', None)
|
|
if evidence_urls:
|
|
for url in evidence_urls.split(','):
|
|
if url.strip():
|
|
authorize_attachment(db, user, url.strip())
|
|
db.flush()
|
|
operation_id = getattr(payload, 'operation_id', None) or str(uuid4())
|
|
# 同一业务操作与内部账本命令有独立命名空间。
|
|
ledger_id = hashlib.sha256((operation_id + ':' + action + ':' + plan.id).encode()).hexdigest()
|
|
op = PlanQuotaOperation(operationId=ledger_id,
|
|
allowSupplement=getattr(payload, 'quota_allow_supplement', False),
|
|
configuration=getattr(payload, 'quota_configuration', None),
|
|
manualActuals=getattr(payload, 'quota_manual_actuals', []) or [],
|
|
reason=getattr(payload, 'quota_reason', '') or action,
|
|
evidenceUrls=getattr(payload, 'quota_evidence_urls', None),
|
|
sourceNote=getattr(payload, 'quota_source_note', None))
|
|
request, config = build_usage_request(db, user, plan.id, op, action, lock=True)
|
|
try:
|
|
result = execute_usage(db, user, request)
|
|
if action in ('reserve', 'resize') or op.allow_supplement:
|
|
# execute_usage持有按并集排序取得的证件锁,当前读再次核验确认版本。
|
|
certs = {key: _get_row(db, user, *key) for key in sorted(
|
|
[('purchase', cid) for cid in config.purchase_cert_ids] +
|
|
[('transport', cid) for cid in config.transport_cert_ids])}
|
|
validate_conditions(config, certs, plan_fingerprint(request.sources))
|
|
plan.cert_configuration = config.model_dump(mode='json', by_alias=True)
|
|
plan.cert_configuration = {**(plan.cert_configuration or {}),
|
|
'measurementVersion': config.measurement_version}
|
|
return result
|
|
except ValueError as exc:
|
|
raise HTTPException(409, str(exc)) from exc
|
|
|
|
|
|
def settle_plan_quota(db, user, plan, payload, *, adjustment=False):
|
|
"""实运事实先flush;额度失败仅撤销结转,预占及一次资格保持占用。"""
|
|
db.flush()
|
|
try:
|
|
with db.begin_nested():
|
|
apply_plan_quota(db, user, plan, 'actual_adjust' if adjustment else 'settle', payload)
|
|
rows = db.query(PlPlanCertUsage).filter_by(tenant_no=user.tenant_no, plan_id=plan.id, del_flag=0).all()
|
|
for row in rows:
|
|
snapshot = dict(row.confirmation_snapshot or {})
|
|
snapshot.pop('settlementError', None)
|
|
row.confirmation_snapshot = snapshot
|
|
return True
|
|
except (HTTPException, ValueError, AllocationIncomplete) as exc:
|
|
rows = db.query(PlPlanCertUsage).filter_by(tenant_no=user.tenant_no, plan_id=plan.id, del_flag=0).all()
|
|
for row in rows:
|
|
if not adjustment:
|
|
row.usage_status = 'exception'
|
|
row.confirmation_snapshot = {**(row.confirmation_snapshot or {}), 'executed': True,
|
|
'settlementError': str(getattr(exc, 'detail', exc))}
|
|
row.update_by = user.id
|
|
if not adjustment:
|
|
plan.archive_status = 'exception'
|
|
return False
|
|
|
|
|
|
def retain_executed_quota(db, user, plan, reason):
|
|
"""冲销现场/地磅证据前固化执行事实;撤销业务不能恢复一次资格。"""
|
|
db.flush()
|
|
rows = db.query(PlPlanCertUsage).filter_by(tenant_no=user.tenant_no, plan_id=plan.id, del_flag=0).with_for_update().populate_existing().all()
|
|
for row in rows:
|
|
row.confirmation_snapshot = {**(row.confirmation_snapshot or {}), 'executed': True,
|
|
'forceVoidReason': reason}
|
|
row.update_by = user.id
|
|
db.flush()
|
|
|
|
|
|
def assert_plan_can_arrange(plan):
|
|
if (plan.follow_status in ('cancelled', 'completed', 'exception')
|
|
or plan.archive_status in ('cancelled', 'archived', 'exception')
|
|
or plan.transport_status in ('cancelled', 'completed')
|
|
or getattr(plan, 'complete_status', None) == 'yes'):
|
|
raise HTTPException(409, '已作废、归档、完成或额度异常的计划不能安排运输')
|
|
|
|
|
|
def assert_transport_exclusive_to_plan(db, tenant_no, plan_id, transport_id):
|
|
"""调用者持有计划及运输行锁;当前锁读全部有效关联,禁止单计划改共享运输。"""
|
|
from app.models.pl_models import PlPlan, PlPlanTransport
|
|
linked = db.query(PlPlanTransport).join(PlPlan, PlPlan.id == PlPlanTransport.plan_id).filter(
|
|
PlPlanTransport.tenant_no == tenant_no, PlPlanTransport.transport_id == transport_id,
|
|
PlPlanTransport.del_flag == 0, PlPlan.tenant_no == tenant_no, PlPlan.del_flag == 0,
|
|
).order_by(PlPlanTransport.id).with_for_update().populate_existing().all()
|
|
# 同时保护历史上仅主单有transport_id、缺失关系行的数据。
|
|
plans = db.query(PlPlan).filter(
|
|
PlPlan.tenant_no == tenant_no, PlPlan.transport_id == transport_id, PlPlan.del_flag == 0,
|
|
).order_by(PlPlan.id).with_for_update().populate_existing().all()
|
|
if any(row.plan_id != plan_id for row in linked) or any(row.id != plan_id for row in plans):
|
|
raise HTTPException(409, '共享运输关联了其他有效计划,请先拆分为独立运输后再调整')
|