merge: issue #45 再安排排除本单一次有效占用。

This commit is contained in:
wuzilong committed 2026-11-17 12:39:55 +08:00
commit 366c69b8a3
3 files changed
+145 -11

No files matched your search

@@ -9,6 +9,7 @@ from app.models.pl_quota_models import (
PlTransportCert,
PlTransportCertPurchaseRef,
PlCertQtyLog,
PlPlanCertUsage,
)
from app.schemas.pl.quota_planning import ManualQuantity
from app.services.pl_cert_category_service import category_ids_for_product
@@ -16,8 +17,29 @@ from app.services.pl_quota_cert_service import is_single_use_consumed
from app.services.pl_quota_units import same_quantity_unit, standard_conversion_ratio
def _available(cert):
return Decimal(cert.total_qty) - Decimal(cert.used_qty) - Decimal(cert.reserved_qty)
def _plan_own_reserved(db, user, plan_id, cert_type, cert_id) -> Decimal:
"""本计划对该证的预占量;再安排时加回余量,避免把本单占用当成他人占用。"""
if not plan_id:
return Decimal('0')
row = (
db.query(PlPlanCertUsage)
.filter_by(
tenant_no=user.tenant_no,
plan_id=plan_id,
cert_type=cert_type,
cert_id=cert_id,
del_flag=0,
)
.first()
)
if row is None:
return Decimal('0')
return Decimal(row.reserved_qty or 0)
def _available(cert, *, own_reserved=None):
own = Decimal(own_reserved if own_reserved is not None else 0)
return Decimal(cert.total_qty) - Decimal(cert.used_qty) - Decimal(cert.reserved_qty) + own
def _in_force(cert, on_date: date) -> bool:
@@ -226,6 +248,7 @@ def _linked_transports(db, user, customer_id, purchase_id):
def _diagnose_select_failure(
db, user, source, *, vehicle_no: str, on_date: date, candidates, manual_allocations=(),
plan_id=None,
):
"""选证失败时按证据优先给出单一可执行原因,避免笼统兜底句。"""
place = '同市' if not source.requires_transport else '异地'
@@ -269,7 +292,7 @@ def _diagnose_select_failure(
if not _in_force(purchase, on_date):
expired_buy.append(purchase)
continue
if is_single_use_consumed(db, user, 'purchase', purchase):
if is_single_use_consumed(db, user, 'purchase', purchase, exclude_plan_id=plan_id):
consumed_buy.append(purchase)
continue
try:
@@ -280,7 +303,8 @@ def _diagnose_select_failure(
except HTTPException:
unit_buy.append(purchase)
continue
if _available(purchase) < need:
buy_own = _plan_own_reserved(db, user, plan_id, 'purchase', purchase.id)
if _available(purchase, own_reserved=buy_own) < need:
short_buy.append((purchase, need))
continue
@@ -305,7 +329,7 @@ def _diagnose_select_failure(
if not _in_force(transport, on_date):
expired_move.append(transport)
continue
if is_single_use_consumed(db, user, 'transport', transport):
if is_single_use_consumed(db, user, 'transport', transport, exclude_plan_id=plan_id):
consumed_move.append(transport)
continue
if not _vehicle_ok(transport, vehicle_no):
@@ -319,7 +343,8 @@ def _diagnose_select_failure(
except HTTPException:
unit_move.append(transport)
continue
if _available(transport) < t_need:
move_own = _plan_own_reserved(db, user, plan_id, 'transport', transport.id)
if _available(transport, own_reserved=move_own) < t_need:
short_move.append((transport, t_need))
continue
purchase_had_ready_transport = True
@@ -428,11 +453,13 @@ def _diagnose_select_failure(
def select_whole_cover_certs(
db, user, sources, *, vehicle_no: str, on_date: date, manual_allocations=(),
plan_id=None,
):
"""返回 purchase_cert_ids, transport_cert_ids, manual_allocations。
每个来源必须由一张购买证整笔覆盖;异地再配一张关联且车号/余量够的运输证。
单位无法自动换算时,使用计划段次用证已保存的人工换算量。
plan_id:再安排时排除本计划已占用的一次有效证,并把本单预占加回可选余量。
"""
if not sources:
return [], [], []
@@ -467,7 +494,7 @@ def select_whole_cover_certs(
continue
if not _in_force(purchase, on_date):
continue
if is_single_use_consumed(db, user, 'purchase', purchase):
if is_single_use_consumed(db, user, 'purchase', purchase, exclude_plan_id=plan_id):
continue
try:
need = _need_permit_qty(
@@ -476,7 +503,8 @@ def select_whole_cover_certs(
)
except HTTPException:
continue
if _available(purchase) < need:
buy_own = _plan_own_reserved(db, user, plan_id, 'purchase', purchase.id)
if _available(purchase, own_reserved=buy_own) < need:
continue
if not source.requires_transport:
@@ -495,7 +523,7 @@ def select_whole_cover_certs(
continue
if not _in_force(transport, on_date):
continue
if is_single_use_consumed(db, user, 'transport', transport):
if is_single_use_consumed(db, user, 'transport', transport, exclude_plan_id=plan_id):
continue
if not _vehicle_ok(transport, vehicle_no):
continue
@@ -506,7 +534,8 @@ def select_whole_cover_certs(
)
except HTTPException:
continue
if _available(transport) < t_need:
move_own = _plan_own_reserved(db, user, plan_id, 'transport', transport.id)
if _available(transport, own_reserved=move_own) < t_need:
continue
chosen_purchase = purchase
chosen_transport = transport
@@ -522,6 +551,7 @@ def select_whole_cover_certs(
_diagnose_select_failure(
db, user, source, vehicle_no=vehicle_no, on_date=on_date,
candidates=candidates, manual_allocations=saved_manuals,
plan_id=plan_id,
),
)
@@ -144,6 +144,7 @@ def build_usage_request(db, user, plan_id, operation, action, *, lock=False, che
purchase_ids, transport_ids, manuals = select_whole_cover_certs(
db, user, sources, vehicle_no=vehicle, on_date=on_date,
manual_allocations=config.manual_allocations,
plan_id=plan.id,
)
config = config.model_copy(update={
'purchase_cert_ids': purchase_ids,
+104 -1
View File
@@ -741,6 +741,107 @@ def test_whole_cover_skips_once_used_purchase_with_remaining(monkeypatch):
assert manuals[0].permit_id == 'buy-fresh'
def test_whole_cover_rearrange_reuses_once_cert_reserved_by_same_plan(monkeypatch):
"""已安排计划再次选证:本单已预占的一次有效证不得误判为已使用,并归还本单预占余量。"""
from app.services import pl_quota_customer_select as sel
from app.schemas.pl.quota_usage import UsageSource
from app.models.pl_quota_models import PlPurchaseCert, PlCertQtyLog, PlPlanCertUsage
source = UsageSource(
source_stop_type='delivery',
source_stop_id='s1',
source_stop_product_id='sp1',
plan_product_id='pp1',
contract_id='c1',
contract_product_id='cp1',
product_id='prod1',
quantity=Decimal('5'),
unit='吨',
fingerprint='y' * 64,
snapshot={'customerId': 'cust1'},
requires_transport=False,
)
# 与 PO20261116021 现场一致:证面一次有效、本单已预占满额
own_cert = SimpleNamespace(
id='buy-own', cert_no='G-OWN', customer_id='cust1', category_id='cat1', status='active',
verified_by='u', verified_time=datetime.now(), valid_from=None, valid_to=date(2026, 12, 31),
total_qty=Decimal('5'), used_qty=Decimal('0'), reserved_qty=Decimal('5'),
quantity_unit='吨', opening_single_use_consumed=0, valid_use_text='一次有效',
)
own_usage = SimpleNamespace(
plan_id='plan-self', cert_id='buy-own', usage_status='reserved',
reserved_qty=Decimal('5'), confirmation_snapshot=None, del_flag=0,
)
class PurchaseQuery:
def filter(self, *a, **k):
return self
def order_by(self, *a, **k):
return self
def all(self):
return [own_cert]
class LogQuery:
def filter_by(self, **k):
return self
def first(self):
return SimpleNamespace(id='opening')
class UsageQuery:
def __init__(self):
self._filters = {}
def filter_by(self, **k):
self._filters.update(k)
return self
def all(self):
# is_single_use_consumed 查全部用量
return [own_usage]
def first(self):
# _plan_own_reserved 按 plan+cert 查本单预占
if self._filters.get('plan_id') == 'plan-self' and self._filters.get('cert_id') == 'buy-own':
return own_usage
return None
db = MagicMock()
def q_side(model):
if model is PlPurchaseCert:
return PurchaseQuery()
if model is PlCertQtyLog:
return LogQuery()
if model is PlPlanCertUsage:
return UsageQuery()
return MagicMock()
db.query.side_effect = q_side
user = SimpleNamespace(tenant_no='t')
monkeypatch.setattr(sel, 'category_ids_for_product', lambda db, tenant, pid: {'cat1'})
# 使用真实占用判定,验证必须传 exclude_plan_id
monkeypatch.setattr(sel, 'is_single_use_consumed', __import__(
'app.services.pl_quota_cert_service', fromlist=['is_single_use_consumed']
).is_single_use_consumed)
with pytest.raises(HTTPException) as blocked:
sel.select_whole_cover_certs(
db, user, [source], vehicle_no='皖A12345', on_date=date(2026, 11, 17),
)
assert '一次有效且已使用' in str(blocked.value.detail)
purchase_ids, transport_ids, manuals = sel.select_whole_cover_certs(
db, user, [source], vehicle_no='皖A12345', on_date=date(2026, 11, 17),
plan_id='plan-self',
)
assert purchase_ids == ['buy-own']
assert transport_ids == []
assert manuals[0].permit_quantity == Decimal('5')
def test_list_customers_requires_customer_cert_counts(monkeypatch):
from app.services import pl_quota_statistics as stats
@@ -1343,8 +1444,9 @@ def test_build_usage_request_passes_saved_manuals_to_customer_select(monkeypatch
)
captured = {}
def fake_select(db, user, sources, *, vehicle_no, on_date, manual_allocations=()):
def fake_select(db, user, sources, *, vehicle_no, on_date, manual_allocations=(), plan_id=None):
captured['manual_allocations'] = list(manual_allocations)
captured['plan_id'] = plan_id
return ['buy1'], [], list(manual_allocations)
monkeypatch.setattr(planning, '_plan', lambda *a, **k: plan)
@@ -1371,6 +1473,7 @@ def test_build_usage_request_passes_saved_manuals_to_customer_select(monkeypatch
)
assert captured['manual_allocations']
assert captured['manual_allocations'][0].permit_id == 'buy1'
assert captured['plan_id'] == 'p1'
assert config.purchase_cert_ids == ['buy1']
assert request.manual_allocations[0].permit_quantity == Decimal('2.5')