diff --git a/backend/app/services/pl_quota_planning.py b/backend/app/services/pl_quota_planning.py index 32ed8e606..baa104ec4 100644 --- a/backend/app/services/pl_quota_planning.py +++ b/backend/app/services/pl_quota_planning.py @@ -34,6 +34,13 @@ def plan_fingerprint(sources): return hashlib.sha256(json.dumps(sorted((s.source_id, s.fingerprint) for s in sources)).encode()).hexdigest() +def plan_cert_on_date(plan) -> date: + """购买证、运输证有效期只按计划日期比对。""" + if getattr(plan, "plan_date", None) is None: + raise HTTPException(409, "请先填写计划日期") + return plan.plan_date + + def classify_contract_cert_bindings(sources, bindings_by_contract, contract_labels): """按合同产品的可用绑定选出购买证、运输证。同市段只要求购买证。""" purchase_ids, transport_ids = [], [] @@ -140,7 +147,7 @@ def build_usage_request(db, user, plan_id, operation, action, *, lock=False, che vehicle = str( (preview_vehicle or {}).get('licensePlate', plan.license_plate) or '' ).strip() - on_date = max(date.today(), plan.plan_date or date.today()) + on_date = plan_cert_on_date(plan) purchase_ids, transport_ids, manuals = select_whole_cover_certs( db, user, sources, vehicle_no=vehicle, on_date=on_date, manual_allocations=config.manual_allocations, @@ -187,7 +194,7 @@ def build_usage_request(db, user, plan_id, operation, action, *, lock=False, che operation_id=op.operation_id, action=action, plan_id=plan_id, sources=sources, allow_supplement=op.allow_supplement, purchase_cert_ids=config.purchase_cert_ids, transport_cert_ids=config.transport_cert_ids, - vehicle_no=str((preview_vehicle or {}).get('licensePlate', plan.license_plate) or '').strip(), on_date=max(date.today(), plan.plan_date or date.today()), + vehicle_no=str((preview_vehicle or {}).get('licensePlate', plan.license_plate) or '').strip(), on_date=plan_cert_on_date(plan), executed=executed, manual_allocations=[UsageManual(**r.model_dump()) for r in config.manual_allocations], actual_by_source=actuals, manual_actuals=[UsageManual(**r.model_dump()) for r in op.manual_actuals], reason=op.reason, evidence_urls=op.evidence_urls or '', source_note=op.source_note or '', diff --git a/backend/app/services/pl_quota_usage_service.py b/backend/app/services/pl_quota_usage_service.py index 65d26f3df..273ac09af 100644 --- a/backend/app/services/pl_quota_usage_service.py +++ b/backend/app/services/pl_quota_usage_service.py @@ -217,8 +217,9 @@ def _candidate_context(db,user,r,plan,certs,usages,items,selected,preview=False, if product is None or product.product_id!=s.product_id: raise ValueError('合同产品归属不符') scopes={}; candidates={'purchase':[],'transport':[]} skipped_for_vehicle=False - 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 + # 安排前 version 常为空;须按 effective_at 前瞻,不能把空当 legacy(否则人工行会报「不适用」)。 + customer_rule = plan_applies_customer_category_rule(db, getattr(user, 'tenant_no', None) or '', plan) from app.services.pl_quota_cert_service import ensure_zero_opening for k in sorted(selected): kind,pid=k; c=certs[k] @@ -416,8 +417,8 @@ ARCHIVE_CONVERSION_EXCESS_BLOCK = ( def _settle_cover_cert_ids(db, user, plan, sources): """归档超额补扣证件池:新规则按客户+品类,旧规则按合同绑证。""" - from app.services.pl_cert_quota_rule_config_service import plan_uses_customer_category - if plan_uses_customer_category(plan): + from app.services.pl_cert_quota_rule_config_service import plan_applies_customer_category_rule + if plan_applies_customer_category_rule(db, getattr(user, 'tenant_no', None) or '', plan): from app.services.pl_quota_customer_select import resolve_customer_category_cover_certs return resolve_customer_category_cover_certs(db, user, sources) from app.services.pl_quota_planning import resolve_contract_bound_certs @@ -440,7 +441,7 @@ def _settlement_cover_reject_reason(db, user, r, plan, kind, cert): if cert.status != 'active' or not cert.verified_time or not cert.verified_by: return f'{label} {no} 未启用或未复核' if cert.valid_from is None or cert.valid_to is None or not cert.valid_from <= r.on_date <= cert.valid_to: - return f'{label} {no} 不在归档日期 {r.on_date.isoformat()} 的有效期内' + return f'{label} {no} 不在计划日期 {r.on_date.isoformat()} 的有效期内' policy = usage_policy(cert.valid_use_text) if policy == 'needs_confirmation': return f'{label} {no} 有效次数待确认' @@ -463,8 +464,8 @@ def _settlement_cover_reject_reason(db, user, r, plan, kind, cert): def _archive_cover_block_message(db, user, r, plan, certs, candidate_keys): """补证候选全被跳过时,汇总具体原因,避免笼统额度不足。""" - 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, getattr(user, 'tenant_no', None) or '', plan) reasons = [] for kind, cid in candidate_keys: key = (kind, cid) @@ -650,8 +651,8 @@ def _settle(db,user,r,certs,usages,items,plan): supplemental=[] if excess: if auto_cover: - 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, getattr(user, 'tenant_no', None) or '', plan) try: purchase_ids, transport_ids = _settle_cover_cert_ids(db, user, plan, r.sources) except HTTPException as exc: diff --git a/backend/tests/test_pl_customer_cert_quota.py b/backend/tests/test_pl_customer_cert_quota.py index 97fb07853..897c89344 100644 --- a/backend/tests/test_pl_customer_cert_quota.py +++ b/backend/tests/test_pl_customer_cert_quota.py @@ -125,17 +125,13 @@ def test_apply_plan_quota_new_rule_waive_skips_reserve_not_settle(monkeypatch): called['assert'] = True monkeypatch.setattr('app.services.pl_quota_waiver.assert_waived_sources', fake_assert) - monkeypatch.setattr( - 'app.services.pl_cert_quota_rule_config_service.plan_uses_customer_category', - lambda p: True, - ) - result = biz.apply_plan_quota(MagicMock(), SimpleNamespace(id='u'), plan, 'reserve', None) + result = biz.apply_plan_quota(MagicMock(), SimpleNamespace(id='u', tenant_no='t'), plan, 'reserve', None) assert result.get('waived') is True assert called.get('assert') is True with pytest.raises(HTTPException) as exc: - biz.apply_plan_quota(MagicMock(), SimpleNamespace(id='u'), plan, 'settle', None) + biz.apply_plan_quota(MagicMock(), SimpleNamespace(id='u', tenant_no='t'), plan, 'settle', None) assert '待完善' in str(exc.value.detail) @@ -346,14 +342,15 @@ def test_legacy_waive_still_skips_settle(monkeypatch): quota_cert_waived=1, quota_cert_pending_fulfill=0, cert_quota_rule_version='legacy', + cert_quota_arranged_at=datetime(2026, 11, 10), cert_configuration={}, ) monkeypatch.setattr( - 'app.services.pl_cert_quota_rule_config_service.plan_uses_customer_category', - lambda p: False, + 'app.services.pl_cert_quota_rule_config_service.plan_skips_archive_cert_quota', + lambda p, db=None, tenant_no=None: False, ) monkeypatch.setattr('app.services.pl_quota_waiver.assert_waived_sources', lambda *a, **k: None) - result = biz.apply_plan_quota(MagicMock(), SimpleNamespace(id='u'), plan, 'settle', None) + result = biz.apply_plan_quota(MagicMock(), SimpleNamespace(id='u', tenant_no='t'), plan, 'settle', None) assert result.get('waived') is True @@ -510,7 +507,13 @@ def test_candidate_context_customer_rule_skips_contract_scope(monkeypatch): from app.services import pl_quota_usage_service as usage from app.schemas.pl.quota_usage import UsageSource - plan = SimpleNamespace(id='plan', cert_quota_rule_version='customer_category', plan_no='P1') + # 安排前 version/arranged_at 均为空;必须按前瞻新规则,不能查合同 scope。 + plan = SimpleNamespace( + id='plan', + cert_quota_rule_version=None, + cert_quota_arranged_at=None, + plan_no='P1', + ) source = UsageSource( source_stop_type='delivery', source_stop_id='s1', @@ -563,8 +566,8 @@ def test_candidate_context_customer_rule_skips_contract_scope(monkeypatch): monkeypatch.setattr(usage, '_query', fake_query) monkeypatch.setattr(usage, '_contract', lambda *a, **k: SimpleNamespace(status='executing', contract_type='sale')) monkeypatch.setattr( - 'app.services.pl_cert_quota_rule_config_service.plan_uses_customer_category', - lambda p: True, + 'app.services.pl_cert_quota_rule_config_service.plan_applies_customer_category_rule', + lambda db, tenant_no, p: True, ) # product ownership check uses _query for CrmContractProduct def fake_query2(db, user, model, lock=False, **filters): @@ -584,6 +587,102 @@ def test_candidate_context_customer_rule_skips_contract_scope(monkeypatch): assert candidates['purchase'][0].product_ids == frozenset({'delivery:sp1'}) +def test_candidate_context_unstamped_with_manual_allocates(monkeypatch): + """未打戳计划 + 新规则人工行:候选 product_ids 须含 source_id,allocate 才不会报人工分配不适用。""" + from datetime import date + from decimal import Decimal + from types import SimpleNamespace + from app.services import pl_quota_usage_service as usage + from app.services.pl_quota_allocation import allocate_plan, SourceDemand + from app.schemas.pl.quota_usage import UsageSource, UsageManual + + plan = SimpleNamespace( + id='plan', + cert_quota_rule_version=None, + cert_quota_arranged_at=None, + plan_no='PO20261113031', + ) + 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('33'), + unit='dun', + fingerprint='f' * 64, + snapshot={'customerId': 'cust1'}, + requires_transport=False, + ) + request = SimpleNamespace( + sources=[source], + on_date=date(2026, 11, 15), + vehicle_no='皖A9TEST1', + manual_allocations=[ + UsageManual( + permit_kind='purchase', + source_id='delivery:sp1', + permit_id='buy1', + source_quantity=Decimal('33'), + permit_quantity=Decimal('33'), + ), + ], + ) + cert = SimpleNamespace( + id='buy1', status='active', verified_time=date(2026, 11, 1), verified_by='u', + valid_from=date(2026, 11, 1), valid_to=date(2027, 1, 1), valid_use_text='多次有效', + total_qty=Decimal('100'), used_qty=Decimal('0'), reserved_qty=Decimal('0'), + quantity_unit='dun', vehicle_numbers_json=['皖A9TEST1'], opening_single_use_consumed=0, + revision=1, cert_no='G1', + ) + + class Q: + def __init__(self, row=None, rows=None): + self._row = row + self._rows = rows or ([] if row is None else [row]) + + def first(self): + return self._row + + def all(self): + return self._rows + + def fake_query(db, user, model, lock=False, **filters): + name = getattr(model, '__name__', '') + if name == 'CrmContractProduct': + return Q(SimpleNamespace(product_id='prod1')) + if name == 'PlCertQtyLog': + return Q(SimpleNamespace(id='opening')) + if name == 'PlTransportCertPurchaseRef': + return Q(rows=[]) + if name in ('PlContractCertLink', 'PlContractCertProduct'): + raise AssertionError('未打戳新规则不应查合同绑证 scope') + return Q() + + monkeypatch.setattr(usage, '_query', fake_query) + monkeypatch.setattr(usage, '_contract', lambda *a, **k: SimpleNamespace(status='executing', contract_type='sale')) + monkeypatch.setattr( + 'app.services.pl_cert_quota_rule_config_service.plan_applies_customer_category_rule', + lambda db, tenant_no, p: True, + ) + + sources, scopes, candidates = usage._candidate_context( + MagicMock(), SimpleNamespace(tenant_no='t', id='u'), request, plan, + {('purchase', 'buy1'): cert}, {}, {}, {('purchase', 'buy1')}, + ) + assert 'delivery:sp1' in candidates['purchase'][0].product_ids + demands = [ + SourceDemand(s.source_id, s.source_id, s.quantity, s.unit, s.requires_transport) + for s in sources.values() + ] + manuals = usage._manual(request.manual_allocations) + allocation = allocate_plan(demands, candidates['purchase'], candidates['transport'], manual_allocations=manuals) + assert allocation.purchase_allocations + assert allocation.purchase_allocations[0].permit_id == 'buy1' + + def test_list_certs_filters_by_customer_id(monkeypatch): from app.services import pl_quota_cert_service as svc @@ -1306,11 +1405,6 @@ def test_settle_cover_cert_ids_customer_rule_skips_contract_bindings(monkeypatch 'app.services.pl_quota_planning.resolve_contract_bound_certs', fake_contract, ) - monkeypatch.setattr( - 'app.services.pl_cert_quota_rule_config_service.plan_uses_customer_category', - lambda p: True, - ) - purchase_ids, transport_ids = usage._settle_cover_cert_ids( MagicMock(), SimpleNamespace(tenant_no='t'), plan, [_remote_source()], ) @@ -1324,10 +1418,6 @@ def test_archive_cover_block_message_customer_rule_wording(monkeypatch): plan = SimpleNamespace(id='plan', cert_quota_rule_version='customer_category') r = SimpleNamespace(vehicle_no='皖A1', on_date=date(2026, 11, 15)) - monkeypatch.setattr( - 'app.services.pl_cert_quota_rule_config_service.plan_uses_customer_category', - lambda p: True, - ) message = svc._archive_cover_block_message( MagicMock(), SimpleNamespace(tenant_no='t'), r, plan, {}, [], ) @@ -1623,3 +1713,67 @@ def test_arranged_legacy_plan_build_usage_keeps_contract_bind(monkeypatch): ) assert called['contract_bind'] == 1 assert called['customer_select'] == 0 + + +def _past_plan_usage_source(): + from app.schemas.pl.quota_usage import UsageSource + + return 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('1'), + unit='dun', + fingerprint='f' * 64, + snapshot={'customerId': 'cust1'}, + requires_transport=False, + ) + + +def test_purchase_and_transport_certs_use_plan_date_even_when_it_is_past(monkeypatch): + """安排选证和归档扣证都按计划日期比对,计划日期早于今天时不改用当天。""" + from app.services import pl_quota_planning as planning + from app.schemas.pl.quota_planning import PlanQuotaOperation + + plan = SimpleNamespace( + id='p1', + plan_date=date(2026, 9, 2), + license_plate='客户自提', + transport_status='pending', + archive_status='unarchived', + cert_quota_rule_version='customer_category', + cert_configuration={'measurementVersion': 'per_stop_v2'}, + tenant_no='t', + ) + captured = {} + + def fake_select(db, user, sources, *, vehicle_no, on_date, manual_allocations=(), plan_id=None): + captured['on_date'] = on_date + return ['buy1'], [], [] + + monkeypatch.setattr(planning, '_plan', lambda *a, **k: plan) + monkeypatch.setattr(planning, 'extract_sources', lambda *a, **k: ([_past_plan_usage_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)) + user = SimpleNamespace(id='u', tenant_no='t', dept_id='') + + request, _ = planning.build_usage_request( + MagicMock(), user, 'p1', PlanQuotaOperation(operationId='arrange'), 'reserve', check_conditions=False, + ) + archived, _ = planning.build_usage_request( + MagicMock(), user, 'p1', PlanQuotaOperation(operationId='archive'), 'settle', check_conditions=False, + ) + + assert captured['on_date'] == date(2026, 9, 2) + assert request.on_date == date(2026, 9, 2) + assert archived.on_date == date(2026, 9, 2) diff --git a/backend/tests/test_pl_quota_usage.py b/backend/tests/test_pl_quota_usage.py index 7ab315146..b2dd6e295 100644 --- a/backend/tests/test_pl_quota_usage.py +++ b/backend/tests/test_pl_quota_usage.py @@ -17,7 +17,7 @@ def case(request): db = Session(engine, autoflush=request.param) user = SimpleNamespace(id='u',dept_id='d',tenant_no='t',to_user_info=lambda: {'role':'super_admin','user_id':'u'}) for pid in ['plan','other']: - db.add(PlPlan(id=pid,plan_no=pid,create_date=date.today(),belongs_company='shanxia',plan_type='direct',tenant_no='t')) + db.add(PlPlan(id=pid,plan_no=pid,create_date=date.today(),plan_date=date.today(),belongs_company='shanxia',plan_type='direct',tenant_no='t')) db.add(CrmContract(id='c',contract_no='c',contract_name='c',customer_id='customer',contract_type='sale',status='approved',tenant_no='t')) db.add(CrmContractProduct(id='cp',contract_id='c',product_id='product',product_name='酸',quantity=100,tenant_no='t')) for kind,model,pid in [('purchase',m.PlPurchaseCert,'p'),('transport',m.PlTransportCert,'t')]: @@ -587,6 +587,10 @@ def test_archive_cover_block_message_names_vehicle(monkeypatch): return SimpleNamespace(id='opening') db = SimpleNamespace() + monkeypatch.setattr( + 'app.services.pl_cert_quota_rule_config_service.plan_applies_customer_category_rule', + lambda db, tenant_no, plan: False, + ) monkeypatch.setattr( svc, '_query',