Compare commits
6
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8ac835fa96 | ||
|
|
e9f3602459 | ||
|
|
d2b8a573a1 | ||
|
|
79d1242d25 | ||
|
|
7e515d9ccd | ||
|
|
12652b826d |
No files matched your search
@@ -83,6 +83,13 @@ def stamp_plan_rule_on_arrange(
|
||||
version = resolve_rule_version_for_arrange(db, user.tenant_no, when)
|
||||
plan.cert_quota_arranged_at = when
|
||||
plan.cert_quota_rule_version = version
|
||||
# 安排前已按旧判定齐备时,打成新规则后回补待完善,避免待完善列表漏单。
|
||||
if (
|
||||
version == VERSION_CUSTOMER_CATEGORY
|
||||
and int(getattr(plan, 'quota_cert_waived', 0) or 0) == 1
|
||||
and int(getattr(plan, 'quota_cert_pending_fulfill', 0) or 0) != 1
|
||||
):
|
||||
plan.quota_cert_pending_fulfill = 1
|
||||
return version
|
||||
|
||||
|
||||
@@ -92,9 +99,28 @@ def stamp_plan_rule_version(db: Session, user, plan) -> str:
|
||||
|
||||
|
||||
def plan_uses_customer_category(plan) -> bool:
|
||||
"""仅看已落库版本;空版本视为 legacy。安排前请用 plan_applies_customer_category_rule。"""
|
||||
return (getattr(plan, 'cert_quota_rule_version', None) or VERSION_LEGACY) == VERSION_CUSTOMER_CATEGORY
|
||||
|
||||
|
||||
def plan_applies_customer_category_rule(db: Session, tenant_no: str, plan) -> bool:
|
||||
"""业务是否按新规则:已打 customer_category,或尚未安排且按当前时刻将落入新规则。
|
||||
|
||||
安排前 `cert_quota_rule_version` 常为空;不能把空当成 legacy,否则会误走合同绑证、
|
||||
漏写齐备待完善。已首次安排并打成 legacy 的计划保持旧规则。
|
||||
"""
|
||||
if plan_uses_customer_category(plan):
|
||||
return True
|
||||
if getattr(plan, 'cert_quota_arranged_at', None) is not None:
|
||||
return False
|
||||
return resolve_rule_version_for_arrange(db, tenant_no) == VERSION_CUSTOMER_CATEGORY
|
||||
|
||||
|
||||
def plan_requires_cert_fulfill(db: Session, tenant_no: str, plan) -> bool:
|
||||
"""齐备后是否须进待完善;与安排是否走新规则同一判定。"""
|
||||
return plan_applies_customer_category_rule(db, tenant_no, plan)
|
||||
|
||||
|
||||
def infer_arranged_at(db: Session, plan) -> Optional[datetime]:
|
||||
"""历史缺字段时用关联运输单创建时间推断首次安排。"""
|
||||
stamped = getattr(plan, 'cert_quota_arranged_at', None)
|
||||
|
||||
@@ -80,6 +80,49 @@ def _permit_qty_for(source_qty: Decimal, source_unit: str, cert_unit: str) -> De
|
||||
return (source_qty * Decimal(str(ratio))).quantize(Decimal('0.000001'))
|
||||
|
||||
|
||||
def _manual_field(row, *names):
|
||||
if isinstance(row, dict):
|
||||
for name in names:
|
||||
if name in row and row[name] is not None:
|
||||
return row[name]
|
||||
return None
|
||||
for name in names:
|
||||
value = getattr(row, name, None)
|
||||
if value is not None:
|
||||
return value
|
||||
return None
|
||||
|
||||
|
||||
def _saved_permit_qty(manuals, kind, source_id, permit_id, source_qty: Decimal):
|
||||
"""计划段次用证已保存的人工换算;来源量变化时按原比例缩放。"""
|
||||
for row in manuals or ():
|
||||
if (
|
||||
str(_manual_field(row, 'permit_kind', 'permitKind') or '') != kind
|
||||
or str(_manual_field(row, 'source_id', 'sourceId') or '') != str(source_id)
|
||||
or str(_manual_field(row, 'permit_id', 'permitId') or '') != str(permit_id)
|
||||
):
|
||||
continue
|
||||
saved_src = Decimal(str(_manual_field(row, 'source_quantity', 'sourceQuantity') or '0'))
|
||||
saved_permit = Decimal(str(_manual_field(row, 'permit_quantity', 'permitQuantity') or '0'))
|
||||
if saved_src <= 0 or saved_permit <= 0:
|
||||
return None
|
||||
current = Decimal(source_qty)
|
||||
if saved_src == current:
|
||||
return saved_permit
|
||||
return (saved_permit * current / saved_src).quantize(Decimal('0.000001'))
|
||||
return None
|
||||
|
||||
|
||||
def _need_permit_qty(source_qty, source_unit, cert_unit, manuals, kind, source_id, permit_id):
|
||||
try:
|
||||
return _permit_qty_for(Decimal(source_qty), source_unit, cert_unit)
|
||||
except HTTPException:
|
||||
manual_qty = _saved_permit_qty(manuals, kind, source_id, permit_id, Decimal(source_qty))
|
||||
if manual_qty is None:
|
||||
raise
|
||||
return manual_qty
|
||||
|
||||
|
||||
def _customer_id_from_source(source) -> str:
|
||||
snap = source.snapshot or {}
|
||||
cid = snap.get('customerId') or snap.get('customer_id')
|
||||
@@ -181,13 +224,16 @@ def _linked_transports(db, user, customer_id, purchase_id):
|
||||
)
|
||||
|
||||
|
||||
def _diagnose_select_failure(db, user, source, *, vehicle_no: str, on_date: date, candidates):
|
||||
def _diagnose_select_failure(
|
||||
db, user, source, *, vehicle_no: str, on_date: date, candidates, manual_allocations=(),
|
||||
):
|
||||
"""选证失败时按证据优先给出单一可执行原因,避免笼统兜底句。"""
|
||||
place = '同市' if not source.requires_transport else '异地'
|
||||
plate = (vehicle_no or '').strip()
|
||||
need_qty = Decimal(source.quantity)
|
||||
customer_label = _source_customer_label(source)
|
||||
product_label = _source_product_label(db, user, source)
|
||||
manuals = manual_allocations or ()
|
||||
|
||||
if not candidates:
|
||||
product_part = f'产品「{product_label}」' if product_label else '该产品'
|
||||
@@ -227,7 +273,10 @@ def _diagnose_select_failure(db, user, source, *, vehicle_no: str, on_date: date
|
||||
consumed_buy.append(purchase)
|
||||
continue
|
||||
try:
|
||||
need = _permit_qty_for(need_qty, source.unit, purchase.quantity_unit)
|
||||
need = _need_permit_qty(
|
||||
need_qty, source.unit, purchase.quantity_unit,
|
||||
manuals, 'purchase', source.source_id, purchase.id,
|
||||
)
|
||||
except HTTPException:
|
||||
unit_buy.append(purchase)
|
||||
continue
|
||||
@@ -263,7 +312,10 @@ def _diagnose_select_failure(db, user, source, *, vehicle_no: str, on_date: date
|
||||
vehicle_miss.append(transport)
|
||||
continue
|
||||
try:
|
||||
t_need = _permit_qty_for(need_qty, source.unit, transport.quantity_unit)
|
||||
t_need = _need_permit_qty(
|
||||
need_qty, source.unit, transport.quantity_unit,
|
||||
manuals, 'transport', source.source_id, transport.id,
|
||||
)
|
||||
except HTTPException:
|
||||
unit_move.append(transport)
|
||||
continue
|
||||
@@ -374,10 +426,13 @@ def _diagnose_select_failure(db, user, source, *, vehicle_no: str, on_date: date
|
||||
)
|
||||
|
||||
|
||||
def select_whole_cover_certs(db, user, sources, *, vehicle_no: str, on_date: date):
|
||||
def select_whole_cover_certs(
|
||||
db, user, sources, *, vehicle_no: str, on_date: date, manual_allocations=(),
|
||||
):
|
||||
"""返回 purchase_cert_ids, transport_cert_ids, manual_allocations。
|
||||
|
||||
每个来源必须由一张购买证整笔覆盖;异地再配一张关联且车号/余量够的运输证。
|
||||
单位无法自动换算时,使用计划段次用证已保存的人工换算量。
|
||||
"""
|
||||
if not sources:
|
||||
return [], [], []
|
||||
@@ -385,6 +440,7 @@ def select_whole_cover_certs(db, user, sources, *, vehicle_no: str, on_date: dat
|
||||
purchase_ids = []
|
||||
transport_ids = []
|
||||
manuals = []
|
||||
saved_manuals = manual_allocations or ()
|
||||
|
||||
for source in sources:
|
||||
customer_id = _customer_id_from_source(source)
|
||||
@@ -414,7 +470,10 @@ def select_whole_cover_certs(db, user, sources, *, vehicle_no: str, on_date: dat
|
||||
if is_single_use_consumed(db, user, 'purchase', purchase):
|
||||
continue
|
||||
try:
|
||||
need = _permit_qty_for(Decimal(source.quantity), source.unit, purchase.quantity_unit)
|
||||
need = _need_permit_qty(
|
||||
source.quantity, source.unit, purchase.quantity_unit,
|
||||
saved_manuals, 'purchase', source.source_id, purchase.id,
|
||||
)
|
||||
except HTTPException:
|
||||
continue
|
||||
if _available(purchase) < need:
|
||||
@@ -441,7 +500,10 @@ def select_whole_cover_certs(db, user, sources, *, vehicle_no: str, on_date: dat
|
||||
if not _vehicle_ok(transport, vehicle_no):
|
||||
continue
|
||||
try:
|
||||
t_need = _permit_qty_for(Decimal(source.quantity), source.unit, transport.quantity_unit)
|
||||
t_need = _need_permit_qty(
|
||||
source.quantity, source.unit, transport.quantity_unit,
|
||||
saved_manuals, 'transport', source.source_id, transport.id,
|
||||
)
|
||||
except HTTPException:
|
||||
continue
|
||||
if _available(transport) < t_need:
|
||||
@@ -458,7 +520,8 @@ def select_whole_cover_certs(db, user, sources, *, vehicle_no: str, on_date: dat
|
||||
raise HTTPException(
|
||||
409,
|
||||
_diagnose_select_failure(
|
||||
db, user, source, vehicle_no=vehicle_no, on_date=on_date, candidates=candidates,
|
||||
db, user, source, vehicle_no=vehicle_no, on_date=on_date,
|
||||
candidates=candidates, manual_allocations=saved_manuals,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
@@ -131,8 +131,8 @@ def build_usage_request(db, user, plan_id, operation, action, *, lock=False, che
|
||||
sources, actuals = [], {}
|
||||
else:
|
||||
sources, actuals = extract_sources(db, user, plan_id, mapping, actual=action in ('settle', 'actual_adjust'), lock=lock, preview_vehicle=preview_vehicle, measurement_version=config.measurement_version)
|
||||
from app.services.pl_cert_quota_rule_config_service import plan_uses_customer_category
|
||||
customer_rule = plan_uses_customer_category(plan)
|
||||
from app.services.pl_cert_quota_rule_config_service import plan_applies_customer_category_rule
|
||||
customer_rule = plan_applies_customer_category_rule(db, user.tenant_no, plan)
|
||||
if action in ('reserve', 'resize') and not explicit and sources:
|
||||
if customer_rule:
|
||||
# 新规则:禁止手工选证;按客户+品类整笔自动选证
|
||||
@@ -143,6 +143,7 @@ def build_usage_request(db, user, plan_id, operation, action, *, lock=False, che
|
||||
on_date = max(date.today(), plan.plan_date or date.today())
|
||||
purchase_ids, transport_ids, manuals = select_whole_cover_certs(
|
||||
db, user, sources, vehicle_no=vehicle, on_date=on_date,
|
||||
manual_allocations=config.manual_allocations,
|
||||
)
|
||||
config = config.model_copy(update={
|
||||
'purchase_cert_ids': purchase_ids,
|
||||
@@ -227,10 +228,10 @@ def preview_plan(db, user, plan_id, config, preview_vehicle=None):
|
||||
|
||||
def save_configuration(db, user, plan_id, config):
|
||||
from app.services.pl_plan_service import record_plan_change
|
||||
from app.services.pl_cert_quota_rule_config_service import plan_uses_customer_category
|
||||
from app.services.pl_cert_quota_rule_config_service import plan_applies_customer_category_rule
|
||||
config = config if isinstance(config, PlanQuotaConfiguration) else PlanQuotaConfiguration.model_validate(config)
|
||||
plan = _plan(db, user, plan_id, lock=True)
|
||||
if plan_uses_customer_category(plan):
|
||||
if plan_applies_customer_category_rule(db, user.tenant_no, plan):
|
||||
raise HTTPException(409, '新规则下安排仅自动选证,不支持手工保存用证配置')
|
||||
if plan.transport_status == 'arranged' or plan.archive_status == 'archived':
|
||||
raise HTTPException(409, '已安排计划请通过调整运输在同一事务重算用证')
|
||||
@@ -337,11 +338,22 @@ def get_plan_quota(db, user, plan_id):
|
||||
options.append(item)
|
||||
usages = db.query(PlPlanCertUsage).filter_by(tenant_no=user.tenant_no, plan_id=plan_id, del_flag=0).order_by(PlPlanCertUsage.create_time.desc()).all()
|
||||
version = resolve_measurement_version(db, user, plan)
|
||||
from app.services.pl_cert_quota_rule_config_service import plan_uses_customer_category
|
||||
customer_rule = plan_uses_customer_category(plan)
|
||||
from app.services.pl_cert_quota_rule_config_service import (
|
||||
VERSION_LEGACY,
|
||||
plan_applies_customer_category_rule,
|
||||
resolve_rule_version_for_arrange,
|
||||
)
|
||||
customer_rule = plan_applies_customer_category_rule(db, user.tenant_no, plan)
|
||||
stamped = getattr(plan, 'cert_quota_rule_version', None)
|
||||
if stamped:
|
||||
rule_version = stamped
|
||||
elif getattr(plan, 'cert_quota_arranged_at', None) is None:
|
||||
rule_version = resolve_rule_version_for_arrange(db, user.tenant_no)
|
||||
else:
|
||||
rule_version = VERSION_LEGACY
|
||||
result = {'planId': plan.id, 'planNo': plan.plan_no, 'licensePlate': plan.license_plate,
|
||||
'quotaCertWaived': int(getattr(plan, 'quota_cert_waived', 0) or 0) == 1,
|
||||
'certQuotaRuleVersion': getattr(plan, 'cert_quota_rule_version', None) or 'legacy',
|
||||
'certQuotaRuleVersion': rule_version or VERSION_LEGACY,
|
||||
'measurementVersion': version,
|
||||
'configuration': {**(plan.cert_configuration or {}), 'measurementVersion': version}, 'sourceOptions': options,
|
||||
'stopProducts': stop_products,
|
||||
|
||||
@@ -269,7 +269,17 @@ def mark_ready(db, user, plan_id):
|
||||
plan = _plan(db, user, plan_id, lock=True)
|
||||
if plan.follow_status == "cancelled" or plan.archive_status == "cancelled":
|
||||
raise HTTPException(409, "已作废的计划不能标记证书齐备")
|
||||
from app.services.pl_cert_quota_rule_config_service import plan_requires_cert_fulfill
|
||||
|
||||
if quota_cert_waived(plan):
|
||||
# 历史:安排前齐备按空版本当成 legacy,漏写 pending;再次调用时回补。
|
||||
if (
|
||||
plan_requires_cert_fulfill(db, user.tenant_no, plan)
|
||||
and int(getattr(plan, "quota_cert_pending_fulfill", 0) or 0) != 1
|
||||
):
|
||||
plan.quota_cert_pending_fulfill = 1
|
||||
plan.update_by = user.id
|
||||
db.flush()
|
||||
labels = _product_names(db, user, [plan.id])
|
||||
return _row(plan, labels.get(plan.id, ""))
|
||||
if not db.query(PlPlan.id).filter(PlPlan.id == plan.id, _toxic_exists(db, user.tenant_no)).first():
|
||||
@@ -290,8 +300,7 @@ def mark_ready(db, user, plan_id):
|
||||
plan.quota_cert_waived_by = user.id
|
||||
plan.quota_cert_waived_by_name = name[:100] if name else None
|
||||
plan.quota_cert_waived_time = datetime.now()
|
||||
from app.services.pl_cert_quota_rule_config_service import plan_uses_customer_category
|
||||
if plan_uses_customer_category(plan):
|
||||
if plan_requires_cert_fulfill(db, user.tenant_no, plan):
|
||||
plan.quota_cert_pending_fulfill = 1
|
||||
change_content = "标记证书齐备:可安排运输;归档前须在证书齐备中完善并关闭"
|
||||
else:
|
||||
@@ -313,15 +322,15 @@ def mark_ready(db, user, plan_id):
|
||||
|
||||
|
||||
def list_pending_fulfill_plans(db, user, page=1, page_size=20, keyword=""):
|
||||
"""新规则下已齐备、待完善挂证的计划。"""
|
||||
from app.services.pl_cert_quota_rule_config_service import VERSION_CUSTOMER_CATEGORY
|
||||
"""新规则下已齐备、待完善挂证的计划。
|
||||
|
||||
以 pending 为准;安排前版本可能仍为空,不能再要求 cert_quota_rule_version。
|
||||
"""
|
||||
query = db.query(PlPlan).filter(
|
||||
PlPlan.tenant_no == user.tenant_no,
|
||||
PlPlan.del_flag == 0,
|
||||
PlPlan.follow_status != "cancelled",
|
||||
PlPlan.archive_status != "cancelled",
|
||||
PlPlan.cert_quota_rule_version == VERSION_CUSTOMER_CATEGORY,
|
||||
PlPlan.quota_cert_pending_fulfill == 1,
|
||||
PlPlan.quota_cert_waived == 1,
|
||||
)
|
||||
@@ -345,14 +354,14 @@ def list_pending_fulfill_plans(db, user, page=1, page_size=20, keyword=""):
|
||||
|
||||
def fulfill_plan_certs(db, user, plan_id, *, operation_id=None):
|
||||
"""完善并关闭:按安排同款自动选证并 reserve,成功后出队。"""
|
||||
from app.services.pl_cert_quota_rule_config_service import plan_uses_customer_category
|
||||
from app.services.pl_cert_quota_rule_config_service import plan_requires_cert_fulfill
|
||||
from app.services.pl_plan_service import record_plan_change
|
||||
from app.services.pl_quota_business import apply_plan_quota
|
||||
from app.services.pl_quota_planning import _plan
|
||||
from types import SimpleNamespace
|
||||
|
||||
plan = _plan(db, user, plan_id, lock=True)
|
||||
if not plan_uses_customer_category(plan):
|
||||
if not plan_requires_cert_fulfill(db, user.tenant_no, plan):
|
||||
raise HTTPException(409, '仅新规则计划支持完善并关闭')
|
||||
if int(getattr(plan, 'quota_cert_pending_fulfill', 0) or 0) != 1:
|
||||
raise HTTPException(409, '该计划不在证书齐备待完善列表中')
|
||||
|
||||
@@ -1232,3 +1232,291 @@ def test_archive_cover_block_message_customer_rule_wording(monkeypatch):
|
||||
)
|
||||
assert '客户名下' in message
|
||||
assert '合同' not in message
|
||||
|
||||
|
||||
def test_whole_cover_uses_saved_manual_when_units_need_conversion(monkeypatch):
|
||||
"""计划段次用证已填瓶→升换算时,同市自动选证应采用该证面量,不能因无法自动换算失败。"""
|
||||
from app.services import pl_quota_customer_select as sel
|
||||
from app.schemas.pl.quota_planning import ManualQuantity
|
||||
|
||||
purchase = _ok_purchase(
|
||||
id='78bde6ea',
|
||||
cert_no='G34280697302194',
|
||||
quantity_unit='sheng',
|
||||
total_qty=Decimal('2.5'),
|
||||
)
|
||||
db = _mock_select_db([purchase], [], [])
|
||||
monkeypatch.setattr(sel, 'category_ids_for_product', lambda *a, **k: {'cat1'})
|
||||
source = _remote_source(
|
||||
requires_transport=False,
|
||||
quantity=Decimal('5'),
|
||||
unit='ping',
|
||||
source_stop_type='delivery',
|
||||
source_stop_id='d1',
|
||||
source_stop_product_id='012423E0',
|
||||
)
|
||||
saved = [
|
||||
ManualQuantity(
|
||||
permit_kind='purchase',
|
||||
source_id=source.source_id,
|
||||
permit_id='78bde6ea',
|
||||
source_quantity=Decimal('5'),
|
||||
permit_quantity=Decimal('2.5'),
|
||||
)
|
||||
]
|
||||
|
||||
purchase_ids, transport_ids, manuals = sel.select_whole_cover_certs(
|
||||
db,
|
||||
SimpleNamespace(tenant_no='t'),
|
||||
[source],
|
||||
vehicle_no='皖H21522',
|
||||
on_date=date(2026, 11, 16),
|
||||
manual_allocations=saved,
|
||||
)
|
||||
assert purchase_ids == ['78bde6ea']
|
||||
assert transport_ids == []
|
||||
assert len(manuals) == 1
|
||||
assert manuals[0].permit_id == '78bde6ea'
|
||||
assert manuals[0].permit_quantity == Decimal('2.5')
|
||||
assert manuals[0].source_quantity == Decimal('5')
|
||||
|
||||
|
||||
def test_whole_cover_hetero_unit_without_manual_still_blocks(monkeypatch):
|
||||
from app.services import pl_quota_customer_select as sel
|
||||
|
||||
purchase = _ok_purchase(quantity_unit='sheng', total_qty=Decimal('2.5'))
|
||||
db = _mock_select_db([purchase], [], [])
|
||||
monkeypatch.setattr(sel, 'category_ids_for_product', lambda *a, **k: {'cat1'})
|
||||
|
||||
with pytest.raises(HTTPException) as exc:
|
||||
sel.select_whole_cover_certs(
|
||||
db,
|
||||
SimpleNamespace(tenant_no='t'),
|
||||
[_remote_source(requires_transport=False, quantity=Decimal('5'), unit='ping')],
|
||||
vehicle_no='皖H21522',
|
||||
on_date=date(2026, 11, 16),
|
||||
)
|
||||
assert exc.value.status_code == 409
|
||||
assert '无法自动换算' in str(exc.value.detail)
|
||||
|
||||
|
||||
def test_build_usage_request_passes_saved_manuals_to_customer_select(monkeypatch):
|
||||
"""安排预占在客户品类规则下应把已保存换算传给自动选证。"""
|
||||
from app.services import pl_quota_planning as planning
|
||||
from app.schemas.pl.quota_planning import ManualQuantity, PlanQuotaOperation
|
||||
from app.schemas.pl.quota_usage import UsageSource
|
||||
|
||||
source = UsageSource(
|
||||
source_stop_type='delivery',
|
||||
source_stop_id='d1',
|
||||
source_stop_product_id='sp1',
|
||||
plan_product_id='pp1',
|
||||
contract_id='c1',
|
||||
contract_product_id='cp1',
|
||||
product_id='prod1',
|
||||
quantity=Decimal('5'),
|
||||
unit='ping',
|
||||
fingerprint='f' * 64,
|
||||
snapshot={'customerId': 'cust1'},
|
||||
requires_transport=False,
|
||||
)
|
||||
saved = [
|
||||
ManualQuantity(
|
||||
permit_kind='purchase',
|
||||
source_id=source.source_id,
|
||||
permit_id='buy1',
|
||||
source_quantity=Decimal('5'),
|
||||
permit_quantity=Decimal('2.5'),
|
||||
)
|
||||
]
|
||||
plan = SimpleNamespace(
|
||||
id='p1',
|
||||
plan_date=date(2026, 11, 16),
|
||||
license_plate='皖H21522',
|
||||
transport_status='pending',
|
||||
archive_status='unarchived',
|
||||
cert_quota_rule_version='customer_category',
|
||||
cert_configuration={
|
||||
'measurementVersion': 'per_stop_v2',
|
||||
'manualAllocations': [row.model_dump(by_alias=True) for row in saved],
|
||||
},
|
||||
)
|
||||
captured = {}
|
||||
|
||||
def fake_select(db, user, sources, *, vehicle_no, on_date, manual_allocations=()):
|
||||
captured['manual_allocations'] = list(manual_allocations)
|
||||
return ['buy1'], [], list(manual_allocations)
|
||||
|
||||
monkeypatch.setattr(planning, '_plan', lambda *a, **k: plan)
|
||||
monkeypatch.setattr(planning, 'extract_sources', lambda *a, **k: ([source], {}))
|
||||
monkeypatch.setattr(planning, 'resolve_measurement_version', lambda *a, **k: 'per_stop_v2')
|
||||
monkeypatch.setattr(planning, 'plan_execution_lock_reason', lambda *a, **k: None)
|
||||
monkeypatch.setattr(
|
||||
'app.services.pl_cert_quota_rule_config_service.plan_uses_customer_category',
|
||||
lambda p: True,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.pl_quota_customer_select.select_whole_cover_certs',
|
||||
fake_select,
|
||||
)
|
||||
monkeypatch.setattr(planning, '_get_row', lambda *a, **k: SimpleNamespace(id='buy1', revision=1))
|
||||
|
||||
request, config = planning.build_usage_request(
|
||||
MagicMock(),
|
||||
SimpleNamespace(id='u', tenant_no='t', dept_id=''),
|
||||
'p1',
|
||||
PlanQuotaOperation(operationId='op1'),
|
||||
'reserve',
|
||||
check_conditions=False,
|
||||
)
|
||||
assert captured['manual_allocations']
|
||||
assert captured['manual_allocations'][0].permit_id == 'buy1'
|
||||
assert config.purchase_cert_ids == ['buy1']
|
||||
assert request.manual_allocations[0].permit_quantity == Decimal('2.5')
|
||||
|
||||
|
||||
def test_unarranged_plan_build_usage_uses_customer_rule_by_effective_at(monkeypatch):
|
||||
"""尚未安排且版本为空时,按生效时间走新规则自动选证,不查合同绑证。"""
|
||||
from app.services import pl_quota_planning as planning
|
||||
from app.schemas.pl.quota_planning import PlanQuotaOperation
|
||||
from app.schemas.pl.quota_usage import UsageSource
|
||||
|
||||
source = UsageSource(
|
||||
source_stop_type='delivery',
|
||||
source_stop_id='d1',
|
||||
source_stop_product_id='sp1',
|
||||
plan_product_id='pp1',
|
||||
contract_id='c1',
|
||||
contract_product_id='cp1',
|
||||
product_id='prod1',
|
||||
quantity=Decimal('33'),
|
||||
unit='dun',
|
||||
fingerprint='f' * 64,
|
||||
snapshot={'customerId': 'cust1'},
|
||||
requires_transport=True,
|
||||
)
|
||||
plan = SimpleNamespace(
|
||||
id='p1',
|
||||
plan_date=date(2026, 11, 14),
|
||||
license_plate='皖R48299',
|
||||
transport_status='pending',
|
||||
archive_status='unarchived',
|
||||
cert_quota_rule_version=None,
|
||||
cert_quota_arranged_at=None,
|
||||
cert_configuration={'measurementVersion': 'per_stop_v2'},
|
||||
tenant_no='t',
|
||||
)
|
||||
called = {'customer_select': 0, 'contract_bind': 0}
|
||||
|
||||
def fake_select(*args, **kwargs):
|
||||
called['customer_select'] += 1
|
||||
return ['buy1'], ['move1'], []
|
||||
|
||||
def fake_contract_bind(*args, **kwargs):
|
||||
called['contract_bind'] += 1
|
||||
raise AssertionError('未安排计划不应再走合同绑证')
|
||||
|
||||
monkeypatch.setattr(planning, '_plan', lambda *a, **k: plan)
|
||||
monkeypatch.setattr(planning, 'extract_sources', lambda *a, **k: ([source], {}))
|
||||
monkeypatch.setattr(planning, 'resolve_measurement_version', lambda *a, **k: 'per_stop_v2')
|
||||
monkeypatch.setattr(planning, 'plan_execution_lock_reason', lambda *a, **k: None)
|
||||
monkeypatch.setattr(
|
||||
'app.services.pl_cert_quota_rule_config_service.get_effective_at',
|
||||
lambda *a, **k: datetime(2026, 11, 15, 20, 0, 0),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.pl_quota_customer_select.select_whole_cover_certs',
|
||||
fake_select,
|
||||
)
|
||||
monkeypatch.setattr(planning, 'resolve_contract_bound_certs', fake_contract_bind)
|
||||
monkeypatch.setattr(
|
||||
planning,
|
||||
'_get_row',
|
||||
lambda *a, **k: SimpleNamespace(id='x', revision=1),
|
||||
)
|
||||
|
||||
request, config = planning.build_usage_request(
|
||||
MagicMock(),
|
||||
SimpleNamespace(id='u', tenant_no='t', dept_id=''),
|
||||
'p1',
|
||||
PlanQuotaOperation(operationId='arrange-check'),
|
||||
'reserve',
|
||||
check_conditions=False,
|
||||
)
|
||||
assert called['customer_select'] == 1
|
||||
assert called['contract_bind'] == 0
|
||||
assert config.purchase_cert_ids == ['buy1']
|
||||
assert config.transport_cert_ids == ['move1']
|
||||
assert request.purchase_cert_ids == ['buy1']
|
||||
|
||||
|
||||
def test_arranged_legacy_plan_build_usage_keeps_contract_bind(monkeypatch):
|
||||
"""已首次安排并打成 legacy 的计划,安排/改派预占仍走合同绑证。"""
|
||||
from app.services import pl_quota_planning as planning
|
||||
from app.schemas.pl.quota_planning import PlanQuotaOperation
|
||||
from app.schemas.pl.quota_usage import UsageSource
|
||||
|
||||
source = UsageSource(
|
||||
source_stop_type='delivery',
|
||||
source_stop_id='d1',
|
||||
source_stop_product_id='sp1',
|
||||
plan_product_id='pp1',
|
||||
contract_id='c1',
|
||||
contract_product_id='cp1',
|
||||
product_id='prod1',
|
||||
quantity=Decimal('33'),
|
||||
unit='dun',
|
||||
fingerprint='f' * 64,
|
||||
snapshot={'customerId': 'cust1'},
|
||||
requires_transport=True,
|
||||
)
|
||||
plan = SimpleNamespace(
|
||||
id='p1',
|
||||
plan_date=date(2026, 11, 14),
|
||||
license_plate='皖R48299',
|
||||
transport_status='arranged',
|
||||
archive_status='unarchived',
|
||||
cert_quota_rule_version='legacy',
|
||||
cert_quota_arranged_at=datetime(2026, 11, 14, 10, 0, 0),
|
||||
cert_configuration={'measurementVersion': 'per_stop_v2'},
|
||||
tenant_no='t',
|
||||
)
|
||||
called = {'customer_select': 0, 'contract_bind': 0}
|
||||
|
||||
def fake_select(*args, **kwargs):
|
||||
called['customer_select'] += 1
|
||||
return ['buy1'], ['move1'], []
|
||||
|
||||
def fake_contract_bind(*args, **kwargs):
|
||||
called['contract_bind'] += 1
|
||||
return ['buy1'], ['move1']
|
||||
|
||||
monkeypatch.setattr(planning, '_plan', lambda *a, **k: plan)
|
||||
monkeypatch.setattr(planning, 'extract_sources', lambda *a, **k: ([source], {}))
|
||||
monkeypatch.setattr(planning, 'resolve_measurement_version', lambda *a, **k: 'per_stop_v2')
|
||||
monkeypatch.setattr(planning, 'plan_execution_lock_reason', lambda *a, **k: None)
|
||||
monkeypatch.setattr(
|
||||
'app.services.pl_cert_quota_rule_config_service.get_effective_at',
|
||||
lambda *a, **k: datetime(2026, 11, 15, 20, 0, 0),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.pl_quota_customer_select.select_whole_cover_certs',
|
||||
fake_select,
|
||||
)
|
||||
monkeypatch.setattr(planning, 'resolve_contract_bound_certs', fake_contract_bind)
|
||||
monkeypatch.setattr(
|
||||
planning,
|
||||
'_get_row',
|
||||
lambda *a, **k: SimpleNamespace(id='x', revision=1),
|
||||
)
|
||||
|
||||
planning.build_usage_request(
|
||||
MagicMock(),
|
||||
SimpleNamespace(id='u', tenant_no='t', dept_id=''),
|
||||
'p1',
|
||||
PlanQuotaOperation(operationId='arrange-check'),
|
||||
'resize',
|
||||
check_conditions=False,
|
||||
)
|
||||
assert called['contract_bind'] == 1
|
||||
assert called['customer_select'] == 0
|
||||
@@ -113,6 +113,9 @@ def test_mark_ready_allows_weighed_plan_until_quota_is_posted(monkeypatch):
|
||||
quota_cert_waived_by=None,
|
||||
quota_cert_waived_by_name=None,
|
||||
quota_cert_waived_time=None,
|
||||
quota_cert_pending_fulfill=0,
|
||||
cert_quota_rule_version="legacy",
|
||||
cert_quota_arranged_at=__import__("datetime").datetime(2026, 11, 1, 10, 0, 0),
|
||||
update_by=None,
|
||||
plan_no="PO1",
|
||||
plan_date=None,
|
||||
@@ -173,6 +176,173 @@ def test_mark_ready_allows_weighed_plan_until_quota_is_posted(monkeypatch):
|
||||
raise AssertionError("已入账仍允许证书齐备")
|
||||
|
||||
|
||||
def test_mark_ready_before_arrange_uses_effective_at_for_pending(monkeypatch):
|
||||
"""安排前版本未打标时,仍按生效时间走新规则并进入待完善。"""
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
from app.models.pl_quota_models import PlPlanCertUsage
|
||||
from app.services.pl_quota_waiver import mark_ready
|
||||
|
||||
plan = SimpleNamespace(
|
||||
id="p1",
|
||||
follow_status="draft",
|
||||
archive_status="unarchived",
|
||||
quota_cert_waived=0,
|
||||
quota_cert_waived_by=None,
|
||||
quota_cert_waived_by_name=None,
|
||||
quota_cert_waived_time=None,
|
||||
quota_cert_pending_fulfill=0,
|
||||
cert_quota_rule_version=None,
|
||||
cert_quota_arranged_at=None,
|
||||
update_by=None,
|
||||
plan_no="PO1",
|
||||
plan_date=None,
|
||||
license_plate=None,
|
||||
supplier_name=None,
|
||||
customer_name=None,
|
||||
)
|
||||
user = SimpleNamespace(id="u1", tenant_no="shanxia2.0", name="齐备员", dept_id="")
|
||||
changes = []
|
||||
|
||||
class Query:
|
||||
def __init__(self, rows):
|
||||
self.rows = rows
|
||||
|
||||
def filter(self, *args, **kwargs):
|
||||
return self
|
||||
|
||||
def filter_by(self, **kwargs):
|
||||
return self
|
||||
|
||||
def all(self):
|
||||
return list(self.rows)
|
||||
|
||||
def first(self):
|
||||
return self.rows[0] if self.rows else None
|
||||
|
||||
class DB:
|
||||
def query(self, model):
|
||||
if model is PlPlanCertUsage:
|
||||
return Query([])
|
||||
return Query([plan])
|
||||
|
||||
def flush(self):
|
||||
return None
|
||||
|
||||
monkeypatch.setattr("app.services.pl_quota_planning._plan", lambda *args, **kwargs: plan)
|
||||
monkeypatch.setattr("app.services.pl_quota_waiver._toxic_exists", lambda *args, **kwargs: True)
|
||||
monkeypatch.setattr("app.services.pl_quota_waiver._product_names", lambda *args, **kwargs: {})
|
||||
monkeypatch.setattr(
|
||||
"app.services.pl_plan_service.record_plan_change",
|
||||
lambda *args, **kwargs: changes.append(kwargs),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"app.services.pl_cert_quota_rule_config_service.get_effective_at",
|
||||
lambda *args, **kwargs: datetime.now() - timedelta(hours=1),
|
||||
)
|
||||
|
||||
mark_ready(DB(), user, "p1")
|
||||
assert plan.quota_cert_waived == 1
|
||||
assert plan.quota_cert_pending_fulfill == 1
|
||||
assert changes and "完善并关闭" in (changes[-1].get("change_content") or "")
|
||||
|
||||
|
||||
def test_mark_ready_stamped_legacy_skips_pending(monkeypatch):
|
||||
"""已按首次安排打成 legacy 的计划,齐备不进待完善。"""
|
||||
from datetime import datetime
|
||||
|
||||
from app.models.pl_quota_models import PlPlanCertUsage
|
||||
from app.services.pl_quota_waiver import mark_ready
|
||||
|
||||
plan = SimpleNamespace(
|
||||
id="p1",
|
||||
follow_status="arranged",
|
||||
archive_status="unarchived",
|
||||
quota_cert_waived=0,
|
||||
quota_cert_waived_by=None,
|
||||
quota_cert_waived_by_name=None,
|
||||
quota_cert_waived_time=None,
|
||||
quota_cert_pending_fulfill=0,
|
||||
cert_quota_rule_version="legacy",
|
||||
cert_quota_arranged_at=datetime(2026, 11, 1, 10, 0, 0),
|
||||
update_by=None,
|
||||
plan_no="PO1",
|
||||
plan_date=None,
|
||||
license_plate=None,
|
||||
supplier_name=None,
|
||||
customer_name=None,
|
||||
)
|
||||
user = SimpleNamespace(id="u1", tenant_no="shanxia2.0", name="齐备员", dept_id="")
|
||||
changes = []
|
||||
|
||||
class Query:
|
||||
def __init__(self, rows):
|
||||
self.rows = rows
|
||||
|
||||
def filter(self, *args, **kwargs):
|
||||
return self
|
||||
|
||||
def filter_by(self, **kwargs):
|
||||
return self
|
||||
|
||||
def all(self):
|
||||
return list(self.rows)
|
||||
|
||||
def first(self):
|
||||
return self.rows[0] if self.rows else None
|
||||
|
||||
class DB:
|
||||
def query(self, model):
|
||||
if model is PlPlanCertUsage:
|
||||
return Query([])
|
||||
return Query([plan])
|
||||
|
||||
def flush(self):
|
||||
return None
|
||||
|
||||
monkeypatch.setattr("app.services.pl_quota_planning._plan", lambda *args, **kwargs: plan)
|
||||
monkeypatch.setattr("app.services.pl_quota_waiver._toxic_exists", lambda *args, **kwargs: True)
|
||||
monkeypatch.setattr("app.services.pl_quota_waiver._product_names", lambda *args, **kwargs: {})
|
||||
monkeypatch.setattr(
|
||||
"app.services.pl_plan_service.record_plan_change",
|
||||
lambda *args, **kwargs: changes.append(kwargs),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"app.services.pl_cert_quota_rule_config_service.get_effective_at",
|
||||
lambda *args, **kwargs: datetime(2026, 11, 15, 20, 0, 0),
|
||||
)
|
||||
|
||||
mark_ready(DB(), user, "p1")
|
||||
assert plan.quota_cert_waived == 1
|
||||
assert plan.quota_cert_pending_fulfill == 0
|
||||
assert changes and "不再校验" in (changes[-1].get("change_content") or "")
|
||||
|
||||
|
||||
def test_stamp_arrange_backfills_pending_when_already_waived(monkeypatch):
|
||||
"""安排打成新规则时,若已齐备则回补待完善。"""
|
||||
from datetime import datetime
|
||||
|
||||
from app.services.pl_cert_quota_rule_config_service import (
|
||||
VERSION_CUSTOMER_CATEGORY,
|
||||
stamp_plan_rule_on_arrange,
|
||||
)
|
||||
|
||||
plan = SimpleNamespace(
|
||||
cert_quota_arranged_at=None,
|
||||
cert_quota_rule_version=None,
|
||||
quota_cert_waived=1,
|
||||
quota_cert_pending_fulfill=0,
|
||||
)
|
||||
user = SimpleNamespace(tenant_no="shanxia2.0")
|
||||
monkeypatch.setattr(
|
||||
"app.services.pl_cert_quota_rule_config_service.resolve_rule_version_for_arrange",
|
||||
lambda *args, **kwargs: VERSION_CUSTOMER_CATEGORY,
|
||||
)
|
||||
version = stamp_plan_rule_on_arrange(None, user, plan, arrange_time=datetime(2026, 11, 16, 14, 0, 0))
|
||||
assert version == VERSION_CUSTOMER_CATEGORY
|
||||
assert plan.quota_cert_pending_fulfill == 1
|
||||
|
||||
|
||||
def test_waived_arrange_check_keeps_source_errors_and_skips_cert_balance(monkeypatch):
|
||||
from app.services.pl_quota_planning import contract_cert_arrange_block
|
||||
|
||||
|
||||
Reference in new issue
Block a user