Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
937a857347 |
No files matched your search
@@ -127,16 +127,12 @@ def save_category(db: Session, user, data: dict, category_id=None):
|
||||
submitted = data['products']
|
||||
if submitted is None:
|
||||
raise HTTPException(400, '产品关联集合不可为 null;清空请提交 []')
|
||||
# uk_cert_category_product 不含 del_flag,软删行仍占唯一键;无 id 再加须复用。
|
||||
all_links = (
|
||||
db.query(PlCertCategoryProduct)
|
||||
.filter_by(tenant_no=user.tenant_no, category_id=row.id)
|
||||
.with_for_update()
|
||||
.populate_existing()
|
||||
.all()
|
||||
)
|
||||
existing = {r.id: r for r in all_links if r.del_flag == 0}
|
||||
by_product = {r.product_id: r for r in all_links}
|
||||
existing = {
|
||||
r.id: r
|
||||
for r in db.query(PlCertCategoryProduct).filter_by(
|
||||
tenant_no=user.tenant_no, category_id=row.id, del_flag=0,
|
||||
).with_for_update().populate_existing().all()
|
||||
}
|
||||
seen = set()
|
||||
product_ids = set()
|
||||
for item in submitted:
|
||||
@@ -154,46 +150,20 @@ def save_category(db: Session, user, data: dict, category_id=None):
|
||||
raise HTTPException(400, '产品关联明细不属于当前品类')
|
||||
if rid in seen:
|
||||
raise HTTPException(400, '产品关联明细 ID 重复')
|
||||
if pid != link.product_id:
|
||||
conflict = by_product.get(pid)
|
||||
if conflict is not None and conflict.id != link.id:
|
||||
if conflict.del_flag == 0:
|
||||
raise HTTPException(400, '同一品类不能重复关联同一产品')
|
||||
# 目标 product_id 被软删行占用:恢复该行并软删当前行
|
||||
conflict.del_flag = 0
|
||||
conflict.scope_status = scope
|
||||
conflict.update_by = user.id
|
||||
link.del_flag = 1
|
||||
link.update_by = user.id
|
||||
seen.add(conflict.id)
|
||||
continue
|
||||
if by_product.get(link.product_id) is link:
|
||||
del by_product[link.product_id]
|
||||
link.product_id = pid
|
||||
by_product[pid] = link
|
||||
seen.add(rid)
|
||||
link.product_id = pid
|
||||
link.scope_status = scope
|
||||
link.update_by = user.id
|
||||
else:
|
||||
# 关联表业务键 (category_id, product_id):复用有效或软删行,避免 uk 冲突
|
||||
link = by_product.get(pid)
|
||||
if link is not None:
|
||||
if link.del_flag == 0:
|
||||
seen.add(link.id)
|
||||
link.del_flag = 0
|
||||
link.scope_status = scope
|
||||
link.update_by = user.id
|
||||
else:
|
||||
link = PlCertCategoryProduct(
|
||||
**_audit(user),
|
||||
category_id=row.id,
|
||||
product_id=pid,
|
||||
scope_status=scope,
|
||||
)
|
||||
db.add(link)
|
||||
by_product[pid] = link
|
||||
link = PlCertCategoryProduct(
|
||||
**_audit(user),
|
||||
category_id=row.id,
|
||||
product_id=pid,
|
||||
scope_status=scope,
|
||||
)
|
||||
db.add(link)
|
||||
for rid, link in existing.items():
|
||||
if rid not in seen and link.del_flag == 0:
|
||||
if rid not in seen:
|
||||
link.del_flag = 1
|
||||
link.update_by = user.id
|
||||
db.flush()
|
||||
|
||||
@@ -337,11 +337,7 @@ def settle_allocations(reserved: Sequence[Allocation], actual_by_source: Mapping
|
||||
|
||||
异单位来源须逐行重新确认全部实际量(含零量行),不按预占比例推算。
|
||||
超来源量或超任一证件预占量均要求先补充分配。
|
||||
同市等仅购买证场景下,调用方仍可能对本函数传入空的运输证分组与全量实运量;
|
||||
无预占行时直接空结转,不把「缺实际量」套到另一类证件上。
|
||||
"""
|
||||
if not reserved:
|
||||
return ()
|
||||
keys, seqs, grouped = set(), set(), {}
|
||||
kinds = {r.permit_kind for r in reserved}
|
||||
if len(kinds) > 1 or kinds - {'purchase', 'transport'}:
|
||||
|
||||
@@ -155,6 +155,4 @@ def save_cert(db, user, cert_type, data, cert_id=None):
|
||||
for scope in prepared:
|
||||
scopes.apply_contract_bindings(db, user, scope)
|
||||
db.flush()
|
||||
# 与无合同集合的 save_cert 一致:建档/保存后自动期初并启用;current=True 的读回不会再跑启用。
|
||||
row = certs.ensure_zero_opening(db, user, cert_type, row.id, row=row)
|
||||
return get_cert(db, user, cert_type, row.id, current=True)
|
||||
@@ -136,30 +136,11 @@ def _customer_display_name(db, user, customer_id):
|
||||
return (row[0] if row else None) or None
|
||||
|
||||
|
||||
def _category_display_names(db, user, category_ids):
|
||||
"""按证用品类 ID 顺序返回启用中的品类名称;未知 ID 跳过。"""
|
||||
from app.models.pl_quota_models import PlCertCategory
|
||||
|
||||
ids = [str(item or '').strip() for item in (category_ids or []) if str(item or '').strip()]
|
||||
if not ids:
|
||||
return []
|
||||
rows = (
|
||||
db.query(PlCertCategory.id, PlCertCategory.category_name)
|
||||
.filter(
|
||||
PlCertCategory.tenant_no == user.tenant_no,
|
||||
PlCertCategory.del_flag == 0,
|
||||
PlCertCategory.id.in_(ids),
|
||||
)
|
||||
.all()
|
||||
)
|
||||
names = {row.id: (row.category_name or '').strip() for row in rows}
|
||||
return [names[item] for item in ids if names.get(item)]
|
||||
|
||||
|
||||
def get_cert(db, user, cert_type, cert_id, current=False):
|
||||
row = _get_row(db, user, cert_type, cert_id, lock=current)
|
||||
# 只读列表/详情不得在未提交事务里改状态,否则会出现「页面已启用、库仍 draft」。
|
||||
# 自动期初与启用仅在 save_cert / confirm 等写入路径执行。
|
||||
# 存量未期初确认的证件在读取时自动补期初0并启用(void/closed 除外)。
|
||||
if not current:
|
||||
row = ensure_zero_opening(db, user, cert_type, cert_id, row=row)
|
||||
result = _row_to_dict(row)
|
||||
result['usagePolicy'] = usage_policy(row.valid_use_text)
|
||||
opening_query = db.query(PlCertQtyLog.id).filter_by(
|
||||
@@ -171,17 +152,12 @@ def get_cert(db, user, cert_type, cert_id, current=False):
|
||||
result['availableQty'] = row.total_qty - row.used_qty - row.reserved_qty
|
||||
result['singleUseConsumed'] = is_single_use_consumed(db, user, cert_type, row)
|
||||
result['customerName'] = _customer_display_name(db, user, getattr(row, 'customer_id', None))
|
||||
if cert_type == 'purchase':
|
||||
names = _category_display_names(db, user, [getattr(row, 'category_id', None)])
|
||||
result['categoryName'] = names[0] if names else None
|
||||
if cert_type == 'transport':
|
||||
result['purchaseRefs'] = [_row_to_dict(r) for r in _refs(db, user, cert_id, lock=current)]
|
||||
result['referencesEditable'] = not _has_usage_beyond_zero_opening(
|
||||
db, user, cert_type, cert_id, lock=current
|
||||
)
|
||||
derived_ids = _transport_derived_categories(db, user, cert_id)
|
||||
result['derivedCategoryIds'] = derived_ids
|
||||
result['derivedCategoryNames'] = _category_display_names(db, user, derived_ids)
|
||||
result['derivedCategoryIds'] = _transport_derived_categories(db, user, cert_id)
|
||||
return result
|
||||
|
||||
|
||||
@@ -207,9 +183,7 @@ def list_certs(db, user, cert_type, keyword=None, status=None, customer_id=None)
|
||||
result = [get_cert(db, user, cert_type, r.id) for r in query.order_by(model.create_time.desc()).all()]
|
||||
if cert_type == 'transport':
|
||||
for item in result:
|
||||
derived_ids = _transport_derived_categories(db, user, item['id'])
|
||||
item['derivedCategoryIds'] = derived_ids
|
||||
item['derivedCategoryNames'] = _category_display_names(db, user, derived_ids)
|
||||
item['derivedCategoryIds'] = _transport_derived_categories(db, user, item['id'])
|
||||
return result
|
||||
|
||||
|
||||
|
||||
@@ -63,14 +63,6 @@ def _vehicle_ok(cert, vehicle_no: str) -> bool:
|
||||
return plate in {str(p).strip() for p in plates if p}
|
||||
|
||||
|
||||
def _cert_no(cert) -> str:
|
||||
return str(getattr(cert, 'cert_no', None) or getattr(cert, 'id', '') or '').strip()
|
||||
|
||||
|
||||
def _join_cert_nos(certs) -> str:
|
||||
return '、'.join(dict.fromkeys(_cert_no(c) for c in certs if _cert_no(c)))
|
||||
|
||||
|
||||
def _permit_qty_for(source_qty: Decimal, source_unit: str, cert_unit: str) -> Decimal:
|
||||
if same_quantity_unit(source_unit, cert_unit):
|
||||
return source_qty
|
||||
@@ -80,49 +72,6 @@ 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')
|
||||
@@ -131,308 +80,10 @@ def _customer_id_from_source(source) -> str:
|
||||
raise HTTPException(409, '用证段次缺少客户,无法按客户选证')
|
||||
|
||||
|
||||
def _snap_text(source, *keys) -> str:
|
||||
snap = source.snapshot or {}
|
||||
for key in keys:
|
||||
value = snap.get(key)
|
||||
if value is not None and str(value).strip():
|
||||
return str(value).strip()
|
||||
return ''
|
||||
|
||||
|
||||
def _source_customer_label(source) -> str:
|
||||
return _snap_text(
|
||||
source, 'customerName', 'customer_name', 'customerNo', 'customer_no'
|
||||
) or _customer_id_from_source(source)
|
||||
|
||||
|
||||
def _source_product_label(db, user, source) -> str:
|
||||
name = _snap_text(source, 'productName', 'product_name')
|
||||
if name:
|
||||
return name
|
||||
product_id = getattr(source, 'product_id', None)
|
||||
if not product_id:
|
||||
return ''
|
||||
try:
|
||||
from app.models.crm_models import CrmProduct
|
||||
|
||||
row = (
|
||||
db.query(CrmProduct)
|
||||
.filter(
|
||||
CrmProduct.id == product_id,
|
||||
CrmProduct.tenant_no == user.tenant_no,
|
||||
CrmProduct.del_flag == 0,
|
||||
)
|
||||
.first()
|
||||
)
|
||||
except Exception:
|
||||
return ''
|
||||
product_name = getattr(row, 'product_name', None) if row is not None else None
|
||||
if isinstance(product_name, str) and product_name.strip():
|
||||
return product_name.strip()
|
||||
return str(product_id)
|
||||
|
||||
|
||||
def _purchase_candidates(db, user, customer_id, categories):
|
||||
# MySQL ASC 会把 NULL 排最前;无到期证应排在末尾,优先消耗更早到期的证(D5)
|
||||
return (
|
||||
db.query(PlPurchaseCert)
|
||||
.filter(
|
||||
PlPurchaseCert.tenant_no == user.tenant_no,
|
||||
PlPurchaseCert.del_flag == 0,
|
||||
PlPurchaseCert.status == 'active',
|
||||
PlPurchaseCert.customer_id == customer_id,
|
||||
PlPurchaseCert.category_id.in_(categories),
|
||||
)
|
||||
.order_by(
|
||||
PlPurchaseCert.valid_to.is_(None).asc(),
|
||||
PlPurchaseCert.valid_to.asc(),
|
||||
PlPurchaseCert.id.asc(),
|
||||
)
|
||||
.all()
|
||||
)
|
||||
|
||||
|
||||
def _linked_transports(db, user, customer_id, purchase_id):
|
||||
refs = (
|
||||
db.query(PlTransportCertPurchaseRef)
|
||||
.filter_by(
|
||||
tenant_no=user.tenant_no,
|
||||
purchase_cert_id=purchase_id,
|
||||
del_flag=0,
|
||||
)
|
||||
.all()
|
||||
)
|
||||
transport_cert_ids = [r.transport_cert_id for r in refs if r.transport_cert_id]
|
||||
if not transport_cert_ids:
|
||||
return []
|
||||
return (
|
||||
db.query(PlTransportCert)
|
||||
.filter(
|
||||
PlTransportCert.tenant_no == user.tenant_no,
|
||||
PlTransportCert.del_flag == 0,
|
||||
PlTransportCert.status == 'active',
|
||||
PlTransportCert.customer_id == customer_id,
|
||||
PlTransportCert.id.in_(transport_cert_ids),
|
||||
)
|
||||
.order_by(
|
||||
PlTransportCert.valid_to.is_(None).asc(),
|
||||
PlTransportCert.valid_to.asc(),
|
||||
PlTransportCert.id.asc(),
|
||||
)
|
||||
.all()
|
||||
)
|
||||
|
||||
|
||||
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 '该产品'
|
||||
return (
|
||||
f'{place}段客户「{customer_label}」下没有{product_part}匹配品类的有效购买证,'
|
||||
'请先建档购买证或核对客户/证用品类后再安排'
|
||||
)
|
||||
|
||||
unverified_buy = []
|
||||
no_opening_buy = []
|
||||
expired_buy = []
|
||||
consumed_buy = []
|
||||
unit_buy = []
|
||||
short_buy = []
|
||||
ready_buy = []
|
||||
no_transport_link = []
|
||||
unverified_move = []
|
||||
no_opening_move = []
|
||||
expired_move = []
|
||||
consumed_move = []
|
||||
vehicle_miss = []
|
||||
unit_move = []
|
||||
short_move = []
|
||||
|
||||
for purchase in candidates:
|
||||
if not purchase.verified_by or not purchase.verified_time:
|
||||
unverified_buy.append(purchase)
|
||||
continue
|
||||
_ensure_opening_quiet(db, user, 'purchase', purchase.id, purchase)
|
||||
if not _has_opening(db, user, 'purchase', purchase.id):
|
||||
no_opening_buy.append(purchase)
|
||||
continue
|
||||
if not _in_force(purchase, on_date):
|
||||
expired_buy.append(purchase)
|
||||
continue
|
||||
if is_single_use_consumed(db, user, 'purchase', purchase):
|
||||
consumed_buy.append(purchase)
|
||||
continue
|
||||
try:
|
||||
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
|
||||
if _available(purchase) < need:
|
||||
short_buy.append((purchase, need))
|
||||
continue
|
||||
|
||||
if not source.requires_transport:
|
||||
ready_buy.append(purchase)
|
||||
continue
|
||||
|
||||
transports = _linked_transports(db, user, purchase.customer_id, purchase.id)
|
||||
if not transports:
|
||||
no_transport_link.append(purchase)
|
||||
continue
|
||||
|
||||
purchase_had_ready_transport = False
|
||||
for transport in transports:
|
||||
if not transport.verified_by or not transport.verified_time:
|
||||
unverified_move.append(transport)
|
||||
continue
|
||||
_ensure_opening_quiet(db, user, 'transport', transport.id, transport)
|
||||
if not _has_opening(db, user, 'transport', transport.id):
|
||||
no_opening_move.append(transport)
|
||||
continue
|
||||
if not _in_force(transport, on_date):
|
||||
expired_move.append(transport)
|
||||
continue
|
||||
if is_single_use_consumed(db, user, 'transport', transport):
|
||||
consumed_move.append(transport)
|
||||
continue
|
||||
if not _vehicle_ok(transport, vehicle_no):
|
||||
vehicle_miss.append(transport)
|
||||
continue
|
||||
try:
|
||||
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
|
||||
if _available(transport) < t_need:
|
||||
short_move.append((transport, t_need))
|
||||
continue
|
||||
purchase_had_ready_transport = True
|
||||
break
|
||||
if purchase_had_ready_transport:
|
||||
ready_buy.append(purchase)
|
||||
|
||||
if source.requires_transport and not plate:
|
||||
return (
|
||||
f'{place}段安排运输须填写车牌号;当前计划未填写车牌,'
|
||||
'无法匹配运输证车号,请先填写车牌后再安排'
|
||||
)
|
||||
|
||||
if vehicle_miss and not short_move and not unit_move:
|
||||
nos = _join_cert_nos(vehicle_miss)
|
||||
listed = '、'.join(
|
||||
dict.fromkeys(
|
||||
str(p).strip()
|
||||
for t in vehicle_miss
|
||||
for p in (t.vehicle_numbers_json or [])
|
||||
if str(p).strip()
|
||||
)
|
||||
)
|
||||
suffix = f'(证上现有车号:{listed})' if listed else ''
|
||||
return (
|
||||
f'{place}段运输证 {nos} 未包含车牌号「{plate}」{suffix}。'
|
||||
'请到运输证中补充该车号,或更换已登记该车号的车辆后再安排'
|
||||
)
|
||||
|
||||
if short_move:
|
||||
parts = []
|
||||
for cert, need in short_move[:3]:
|
||||
left = _available(cert)
|
||||
parts.append(
|
||||
f'{_cert_no(cert)}剩余{left}{cert.quantity_unit},本次需要{need}{cert.quantity_unit}'
|
||||
)
|
||||
return (
|
||||
f'{place}段运输证{";".join(parts)}。'
|
||||
'运输证余量不足,请先补充额度或调整计划量后再安排'
|
||||
)
|
||||
|
||||
if short_buy and not ready_buy:
|
||||
parts = []
|
||||
for cert, need in short_buy[:3]:
|
||||
left = _available(cert)
|
||||
parts.append(
|
||||
f'{_cert_no(cert)}剩余{left}{cert.quantity_unit},本次需要{need}{cert.quantity_unit}'
|
||||
)
|
||||
return (
|
||||
f'{place}段购买证{";".join(parts)}。'
|
||||
'购买证余量不足,请先补充额度或调整计划量后再安排'
|
||||
)
|
||||
|
||||
if no_transport_link and not vehicle_miss and not short_move:
|
||||
nos = _join_cert_nos(no_transport_link)
|
||||
return (
|
||||
f'{place}段购买证 {nos} 尚未关联运输证。'
|
||||
'请打开运输证,在「关联购买证」中选择该购买证后再安排'
|
||||
)
|
||||
|
||||
if expired_move and not vehicle_miss:
|
||||
nos = _join_cert_nos(expired_move)
|
||||
return (
|
||||
f'{place}段运输证 {nos} 不在计划日期 {on_date.isoformat()} 的有效期内,'
|
||||
'请更换有效运输证后再安排'
|
||||
)
|
||||
|
||||
if expired_buy and not ready_buy:
|
||||
nos = _join_cert_nos(expired_buy)
|
||||
return (
|
||||
f'{place}段购买证 {nos} 不在计划日期 {on_date.isoformat()} 的有效期内,'
|
||||
'请更换有效购买证后再安排'
|
||||
)
|
||||
|
||||
if unverified_move and not vehicle_miss:
|
||||
nos = _join_cert_nos(unverified_move)
|
||||
return f'{place}段运输证 {nos} 尚未复核启用,请先复核后再安排'
|
||||
|
||||
if unverified_buy and not ready_buy:
|
||||
nos = _join_cert_nos(unverified_buy)
|
||||
return f'{place}段购买证 {nos} 尚未复核启用,请先复核后再安排'
|
||||
|
||||
if consumed_move:
|
||||
nos = _join_cert_nos(consumed_move)
|
||||
return f'{place}段运输证 {nos} 为一次有效且已使用,请更换证件后再安排'
|
||||
|
||||
if consumed_buy and not ready_buy:
|
||||
nos = _join_cert_nos(consumed_buy)
|
||||
return f'{place}段购买证 {nos} 为一次有效且已使用,请更换证件后再安排'
|
||||
|
||||
if unit_buy or unit_move:
|
||||
return (
|
||||
f'{place}段证件单位与计划单位无法自动换算,'
|
||||
'请调整单位或到「计划段次用证」填写换算后再安排'
|
||||
)
|
||||
|
||||
if no_opening_buy or no_opening_move:
|
||||
return f'{place}段证件尚未确认期初用量,请先确认期初后再安排'
|
||||
|
||||
return (
|
||||
f'{place}段找不到可用的购买证'
|
||||
f'{"和运输证" if source.requires_transport else ""},'
|
||||
'请补充证件或标记证书齐备后再安排'
|
||||
)
|
||||
|
||||
|
||||
def select_whole_cover_certs(
|
||||
db, user, sources, *, vehicle_no: str, on_date: date, manual_allocations=(),
|
||||
):
|
||||
def select_whole_cover_certs(db, user, sources, *, vehicle_no: str, on_date: date):
|
||||
"""返回 purchase_cert_ids, transport_cert_ids, manual_allocations。
|
||||
|
||||
每个来源必须由一张购买证整笔覆盖;异地再配一张关联且车号/余量够的运输证。
|
||||
单位无法自动换算时,使用计划段次用证已保存的人工换算量。
|
||||
"""
|
||||
if not sources:
|
||||
return [], [], []
|
||||
@@ -440,19 +91,33 @@ def select_whole_cover_certs(
|
||||
purchase_ids = []
|
||||
transport_ids = []
|
||||
manuals = []
|
||||
saved_manuals = manual_allocations or ()
|
||||
|
||||
for source in sources:
|
||||
customer_id = _customer_id_from_source(source)
|
||||
categories = category_ids_for_product(db, user.tenant_no, source.product_id)
|
||||
if not categories:
|
||||
product_label = _source_product_label(db, user, source) or '该产品'
|
||||
raise HTTPException(
|
||||
409,
|
||||
f'产品「{product_label}」未配置证用品类,请先在证用品类中关联系统产品后再安排运输',
|
||||
'产品未配置证用品类,请先在证用品类中关联系统产品后再安排运输',
|
||||
)
|
||||
|
||||
candidates = _purchase_candidates(db, user, customer_id, categories)
|
||||
# MySQL ASC 会把 NULL 排最前;无到期证应排在末尾,优先消耗更早到期的证(D5)
|
||||
candidates = (
|
||||
db.query(PlPurchaseCert)
|
||||
.filter(
|
||||
PlPurchaseCert.tenant_no == user.tenant_no,
|
||||
PlPurchaseCert.del_flag == 0,
|
||||
PlPurchaseCert.status == 'active',
|
||||
PlPurchaseCert.customer_id == customer_id,
|
||||
PlPurchaseCert.category_id.in_(categories),
|
||||
)
|
||||
.order_by(
|
||||
PlPurchaseCert.valid_to.is_(None).asc(),
|
||||
PlPurchaseCert.valid_to.asc(),
|
||||
PlPurchaseCert.id.asc(),
|
||||
)
|
||||
.all()
|
||||
)
|
||||
|
||||
chosen_purchase = None
|
||||
chosen_transport = None
|
||||
@@ -470,10 +135,7 @@ def select_whole_cover_certs(
|
||||
if is_single_use_consumed(db, user, 'purchase', purchase):
|
||||
continue
|
||||
try:
|
||||
need = _need_permit_qty(
|
||||
source.quantity, source.unit, purchase.quantity_unit,
|
||||
saved_manuals, 'purchase', source.source_id, purchase.id,
|
||||
)
|
||||
need = _permit_qty_for(Decimal(source.quantity), source.unit, purchase.quantity_unit)
|
||||
except HTTPException:
|
||||
continue
|
||||
if _available(purchase) < need:
|
||||
@@ -484,9 +146,34 @@ def select_whole_cover_certs(
|
||||
purchase_permit_qty = need
|
||||
break
|
||||
|
||||
transports = _linked_transports(db, user, customer_id, purchase.id)
|
||||
if not transports:
|
||||
refs = (
|
||||
db.query(PlTransportCertPurchaseRef)
|
||||
.filter_by(
|
||||
tenant_no=user.tenant_no,
|
||||
purchase_cert_id=purchase.id,
|
||||
del_flag=0,
|
||||
)
|
||||
.all()
|
||||
)
|
||||
transport_cert_ids = [r.transport_cert_id for r in refs if r.transport_cert_id]
|
||||
if not transport_cert_ids:
|
||||
continue
|
||||
transports = (
|
||||
db.query(PlTransportCert)
|
||||
.filter(
|
||||
PlTransportCert.tenant_no == user.tenant_no,
|
||||
PlTransportCert.del_flag == 0,
|
||||
PlTransportCert.status == 'active',
|
||||
PlTransportCert.customer_id == customer_id,
|
||||
PlTransportCert.id.in_(transport_cert_ids),
|
||||
)
|
||||
.order_by(
|
||||
PlTransportCert.valid_to.is_(None).asc(),
|
||||
PlTransportCert.valid_to.asc(),
|
||||
PlTransportCert.id.asc(),
|
||||
)
|
||||
.all()
|
||||
)
|
||||
for transport in transports:
|
||||
if not transport.verified_by or not transport.verified_time:
|
||||
continue
|
||||
@@ -500,10 +187,7 @@ def select_whole_cover_certs(
|
||||
if not _vehicle_ok(transport, vehicle_no):
|
||||
continue
|
||||
try:
|
||||
t_need = _need_permit_qty(
|
||||
source.quantity, source.unit, transport.quantity_unit,
|
||||
saved_manuals, 'transport', source.source_id, transport.id,
|
||||
)
|
||||
t_need = _permit_qty_for(Decimal(source.quantity), source.unit, transport.quantity_unit)
|
||||
except HTTPException:
|
||||
continue
|
||||
if _available(transport) < t_need:
|
||||
@@ -517,12 +201,11 @@ def select_whole_cover_certs(
|
||||
break
|
||||
|
||||
if chosen_purchase is None:
|
||||
place = '同市' if not source.requires_transport else '异地'
|
||||
raise HTTPException(
|
||||
409,
|
||||
_diagnose_select_failure(
|
||||
db, user, source, vehicle_no=vehicle_no, on_date=on_date,
|
||||
candidates=candidates, manual_allocations=saved_manuals,
|
||||
),
|
||||
f'{place}段找不到余量足够、有效期内且匹配品类/车号的购买证'
|
||||
f'{"和运输证" if source.requires_transport else ""},请补充证件或标记证书齐备后再安排',
|
||||
)
|
||||
|
||||
purchase_ids.append(chosen_purchase.id)
|
||||
@@ -551,76 +234,3 @@ def select_whole_cover_certs(
|
||||
return list(dict.fromkeys(values))
|
||||
|
||||
return unique(purchase_ids), unique(transport_ids), manuals
|
||||
|
||||
|
||||
def resolve_customer_category_cover_certs(db, user, sources):
|
||||
"""归档超额补扣:按客户+品类收集证件池,不查合同绑证。
|
||||
|
||||
与 select_whole_cover_certs 不同,这里不按数量筛证,把客户下匹配品类的
|
||||
有效购买证及其关联运输证全部纳入候选,由结转阶段结合本计划返还额度分配。
|
||||
"""
|
||||
if not sources:
|
||||
return [], []
|
||||
|
||||
purchase_ids = []
|
||||
transport_ids = []
|
||||
missing_both = []
|
||||
missing_purchase = []
|
||||
missing_transport = []
|
||||
|
||||
for source in sources:
|
||||
customer_id = _customer_id_from_source(source)
|
||||
snap = source.snapshot or {}
|
||||
customer_label = (
|
||||
snap.get('customerName')
|
||||
or snap.get('customer_name')
|
||||
or snap.get('customerNo')
|
||||
or snap.get('customer_no')
|
||||
or customer_id
|
||||
)
|
||||
categories = category_ids_for_product(db, user.tenant_no, source.product_id)
|
||||
if not categories:
|
||||
product_label = _source_product_label(db, user, source) or '该产品'
|
||||
raise HTTPException(
|
||||
409,
|
||||
f'产品「{product_label}」未配置证用品类,请先在证用品类中关联系统产品后再归档',
|
||||
)
|
||||
purchases = _purchase_candidates(db, user, customer_id, categories)
|
||||
needs_transport = getattr(source, 'requires_transport', True)
|
||||
if not purchases:
|
||||
(missing_both if needs_transport else missing_purchase).append(str(customer_label))
|
||||
continue
|
||||
purchase_ids.extend(p.id for p in purchases)
|
||||
if not needs_transport:
|
||||
continue
|
||||
linked = []
|
||||
for purchase in purchases:
|
||||
linked.extend(_linked_transports(db, user, customer_id, purchase.id))
|
||||
if not linked:
|
||||
missing_transport.append(str(customer_label))
|
||||
continue
|
||||
transport_ids.extend(t.id for t in linked)
|
||||
|
||||
messages = []
|
||||
if missing_both:
|
||||
names = '、'.join(dict.fromkeys(missing_both))
|
||||
messages.append(
|
||||
f'客户{names}下尚未建档匹配品类的购买证和运输证,请先建档证件后再归档'
|
||||
)
|
||||
if missing_purchase:
|
||||
names = '、'.join(dict.fromkeys(missing_purchase))
|
||||
messages.append(
|
||||
f'客户{names}下尚未建档匹配品类的购买证,请先建档证件后再归档'
|
||||
)
|
||||
if missing_transport:
|
||||
names = '、'.join(dict.fromkeys(missing_transport))
|
||||
messages.append(
|
||||
f'客户{names}下购买证尚未关联可用运输证,请先关联运输证后再归档'
|
||||
)
|
||||
if messages:
|
||||
raise HTTPException(409, ';'.join(messages))
|
||||
|
||||
def unique(values):
|
||||
return list(dict.fromkeys(values))
|
||||
|
||||
return unique(purchase_ids), unique(transport_ids)
|
||||
@@ -137,13 +137,10 @@ def build_usage_request(db, user, plan_id, operation, action, *, lock=False, che
|
||||
if customer_rule:
|
||||
# 新规则:禁止手工选证;按客户+品类整笔自动选证
|
||||
from app.services.pl_quota_customer_select import select_whole_cover_certs
|
||||
vehicle = str(
|
||||
(preview_vehicle or {}).get('licensePlate', plan.license_plate) or ''
|
||||
).strip()
|
||||
vehicle = (preview_vehicle or {}).get('licensePlate', plan.license_plate) or ''
|
||||
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,
|
||||
@@ -174,7 +171,7 @@ def build_usage_request(db, user, plan_id, operation, action, *, lock=False, che
|
||||
certs = {key: _get_row(db, user, *key, lock=False) for key in sorted(keys)}
|
||||
if sources and not keys:
|
||||
msg = (
|
||||
'未选到可用的购买证和运输证。请核对证件余量、有效期、品类与车牌号后补充证件,或标记证书齐备后再安排运输'
|
||||
'找不到适用的购买证和运输证,请补充证件或标记证书齐备后再安排运输'
|
||||
if customer_rule else
|
||||
'请先在合同中绑定购买证和运输证后再安排运输'
|
||||
)
|
||||
@@ -186,7 +183,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=(preview_vehicle or {}).get('licensePlate', plan.license_plate) or '', on_date=max(date.today(), plan.plan_date or date.today()),
|
||||
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 '',
|
||||
|
||||
@@ -168,10 +168,6 @@ def extract_sources(db, user, plan_id, mapping=None, *, actual=False, lock=False
|
||||
snapshot['vehicle'] = preview_vehicle.get('licensePlate', plan.license_plate)
|
||||
snapshot['trailer'] = preview_vehicle.get('trailerNo', plan.trailer_no)
|
||||
fingerprint = hashlib.sha256(json.dumps(snapshot, sort_keys=True, ensure_ascii=False).encode()).hexdigest()
|
||||
# 展示字段不参与 fingerprint,避免仅补产品名就触发来源指纹变化
|
||||
product_name = getattr(row, 'product_name', None)
|
||||
if product_name is not None and str(product_name).strip():
|
||||
snapshot = {**snapshot, 'productName': str(product_name).strip()}
|
||||
source = UsageSource(source_stop_type=side, source_stop_id=stop.id, source_stop_product_id=row.id,
|
||||
plan_product_id=row.plan_product_id, contract_id=row.contract_id,
|
||||
contract_product_id=row.contract_product_id, product_id=row.product_id,
|
||||
|
||||
@@ -26,26 +26,6 @@ from app.services.pl_quota_units import same_quantity_unit, standard_conversion_
|
||||
ZERO = Decimal('0')
|
||||
|
||||
|
||||
def _normalize_vehicle_no(vehicle_no) -> str:
|
||||
return str(vehicle_no or '').strip()
|
||||
|
||||
|
||||
def _vehicle_on_cert(cert, vehicle_no) -> bool:
|
||||
"""计划车牌与证上车号比对时两侧都去空白,避免尾部空格误判。"""
|
||||
plate = _normalize_vehicle_no(vehicle_no)
|
||||
if not plate:
|
||||
return False
|
||||
plates = getattr(cert, 'vehicle_numbers_json', None) or []
|
||||
if isinstance(plates, str):
|
||||
try:
|
||||
plates = json.loads(plates)
|
||||
except Exception:
|
||||
plates = [plates]
|
||||
if not isinstance(plates, list):
|
||||
return False
|
||||
return plate in {str(p).strip() for p in plates if p is not None and str(p).strip()}
|
||||
|
||||
|
||||
def _reserve_input_mode(source_unit, cert_unit):
|
||||
if same_quantity_unit(source_unit, cert_unit):
|
||||
return 'same_unit'
|
||||
@@ -151,8 +131,9 @@ def _execute(db,user,r,digest,plan):
|
||||
selected={('purchase',x) for x in r.purchase_cert_ids}|{('transport',x) for x in r.transport_cert_ids}
|
||||
keys=selected|{(u.cert_type,u.cert_id) for u in old_rows}
|
||||
if r.action in ('settle', 'actual_adjust') and not r.allow_supplement and r.sources:
|
||||
from app.services.pl_quota_planning import resolve_contract_bound_certs
|
||||
try:
|
||||
purchase_ids, transport_ids = _settle_cover_cert_ids(db, user, plan, r.sources)
|
||||
purchase_ids, transport_ids = resolve_contract_bound_certs(db, user, r.sources)
|
||||
except HTTPException:
|
||||
purchase_ids, transport_ids = [], []
|
||||
keys |= {('purchase', cert_id) for cert_id in purchase_ids} | {('transport', cert_id) for cert_id in transport_ids}
|
||||
@@ -231,7 +212,7 @@ def _candidate_context(db,user,r,plan,certs,usages,items,selected,preview=False,
|
||||
policy=usage_policy(c.valid_use_text)
|
||||
if policy=='needs_confirmation': raise ValueError('有效次数待确认')
|
||||
# 合同上常有多张运输证。车号对不上的证不参与本次分配,只要还有一张覆盖该主车号即可安排。
|
||||
if kind=='transport' and not _vehicle_on_cert(c, r.vehicle_no):
|
||||
if kind=='transport' and (not r.vehicle_no or r.vehicle_no not in (c.vehicle_numbers_json or [])):
|
||||
skipped_for_vehicle=True
|
||||
continue
|
||||
if policy=='once' and is_single_use_consumed(db, user, kind, c, exclude_plan_id=plan.id):
|
||||
@@ -252,21 +233,7 @@ def _candidate_context(db,user,r,plan,certs,usages,items,selected,preview=False,
|
||||
own=usages[k].reserved_qty if k in usages else ZERO
|
||||
candidates[kind].append(PermitCandidate(pid,c.total_qty-c.used_qty-c.reserved_qty+own,c.quantity_unit,c.valid_to,frozenset(eligible),refs))
|
||||
if skipped_for_vehicle and not candidates['transport']:
|
||||
plate = _normalize_vehicle_no(r.vehicle_no)
|
||||
if not plate:
|
||||
raise ValueError('安排运输须填写车牌号;当前未填写车牌,无法匹配运输证车号')
|
||||
nos = '、'.join(
|
||||
dict.fromkeys(
|
||||
str(certs[k].cert_no or k[1])
|
||||
for k in sorted(selected)
|
||||
if k[0] == 'transport' and k in certs
|
||||
)
|
||||
)
|
||||
suffix = f'(已选运输证 {nos})' if nos else ''
|
||||
raise ValueError(
|
||||
f'车牌号「{plate}」不在运输证车号范围内{suffix},'
|
||||
'请到运输证中补充该车号或更换车辆后再安排'
|
||||
)
|
||||
raise ValueError('车号不在运输证范围')
|
||||
return sources,scopes,candidates
|
||||
|
||||
def _reserve(db,user,r,plan,certs,usages,items,selected,preview=False,lock_preview=False):
|
||||
@@ -395,88 +362,30 @@ def _validate_current_sources(r,active):
|
||||
raise ValueError('当前权威来源身份、计划量、单位或指纹已变化,请重新核对用证')
|
||||
|
||||
class ArchiveQuotaBlocked(ValueError):
|
||||
"""可用购买证、运输证仍不够本次实际量,归档必须整单回滚。"""
|
||||
"""合同上的购买证、运输证仍不够本次实际量,归档必须整单回滚。"""
|
||||
|
||||
|
||||
ARCHIVE_QUOTA_BLOCK = '合同绑定的购买证和运输证剩余额度不够覆盖本次实际数量,不能归档。请先补充证件额度或调整实际数量后再归档。'
|
||||
CUSTOMER_ARCHIVE_QUOTA_BLOCK = (
|
||||
'客户名下购买证和运输证剩余额度不够覆盖本次实际数量,不能归档。'
|
||||
'请先补充证件额度或调整实际数量后再归档。'
|
||||
)
|
||||
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_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
|
||||
return resolve_contract_bound_certs(db, user, sources)
|
||||
|
||||
|
||||
def _settlement_cover_cert(db, user, r, plan, kind, cert):
|
||||
"""合同上另有证件时,不合格的证跳过,不因此挡住其余还能扣的证。"""
|
||||
return _settlement_cover_reject_reason(db, user, r, plan, kind, cert) is None
|
||||
|
||||
|
||||
def _settlement_cover_reject_reason(db, user, r, plan, kind, cert):
|
||||
"""返回不可用于归档补扣的具体原因;可用时返回 None。"""
|
||||
from app.services.pl_quota_cert_service import ensure_zero_opening
|
||||
cert = ensure_zero_opening(db, user, kind, cert.id, row=cert)
|
||||
label = '购买证' if kind == 'purchase' else '运输证'
|
||||
no = str(cert.cert_no or cert.id)
|
||||
if not _query(db, user, m.PlCertQtyLog, cert_type=kind, cert_id=cert.id, event_type='opening', del_flag=0).first():
|
||||
return f'{label} {no} 尚未确认期初用量'
|
||||
return False
|
||||
if cert.status != 'active' or not cert.verified_time or not cert.verified_by:
|
||||
return f'{label} {no} 未启用或未复核'
|
||||
return False
|
||||
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 False
|
||||
policy = usage_policy(cert.valid_use_text)
|
||||
if policy == 'needs_confirmation':
|
||||
return f'{label} {no} 有效次数待确认'
|
||||
if kind == 'transport':
|
||||
plate = _normalize_vehicle_no(r.vehicle_no)
|
||||
if not plate:
|
||||
return f'运输证 {no} 需要车牌号,当前计划未填写车牌'
|
||||
if not _vehicle_on_cert(cert, plate):
|
||||
raw = cert.vehicle_numbers_json or []
|
||||
if isinstance(raw, str):
|
||||
listed = raw
|
||||
else:
|
||||
listed = '、'.join(str(p).strip() for p in raw if str(p).strip())
|
||||
suffix = f'(证上现有车号:{listed})' if listed else ''
|
||||
return f'运输证 {no} 未包含车牌号「{plate}」{suffix}'
|
||||
return False
|
||||
if kind == 'transport' and (not r.vehicle_no or r.vehicle_no not in (cert.vehicle_numbers_json or [])):
|
||||
return False
|
||||
if policy == 'once' and is_single_use_consumed(db, user, kind, cert, exclude_plan_id=plan.id):
|
||||
return f'{label} {no} 为一次有效且已使用'
|
||||
return None
|
||||
|
||||
|
||||
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)
|
||||
reasons = []
|
||||
for kind, cid in candidate_keys:
|
||||
key = (kind, cid)
|
||||
cert = certs.get(key)
|
||||
if cert is None:
|
||||
label = '购买证' if kind == 'purchase' else '运输证'
|
||||
reasons.append(f'{label} {cid} 不存在或不可用')
|
||||
continue
|
||||
reason = _settlement_cover_reject_reason(db, user, r, plan, kind, cert)
|
||||
if reason:
|
||||
reasons.append(reason)
|
||||
if not reasons:
|
||||
return CUSTOMER_ARCHIVE_QUOTA_BLOCK if customer_rule else ARCHIVE_QUOTA_BLOCK
|
||||
unique = list(dict.fromkeys(reasons))
|
||||
detail = ';'.join(unique[:4])
|
||||
scope = '客户名下' if customer_rule else '合同上'
|
||||
return f'{detail}。{scope}没有其他可用证件覆盖本次实际数量,不能归档。请先处理上述问题后再归档。'
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
_QTY = Decimal('0.000001')
|
||||
@@ -533,7 +442,7 @@ def _prepare_saved_conversion(groups, actual_by_source, certs):
|
||||
proposals[kind] = [row for row in rows if row.source_id != sid] + updated
|
||||
mine = updated
|
||||
if need > 0:
|
||||
return groups, [], ARCHIVE_CONVERSION_EXCESS_BLOCK
|
||||
return groups, [], ARCHIVE_QUOTA_BLOCK
|
||||
remaining = actual
|
||||
for row in sorted(mine, key=lambda item: item.allocation_seq):
|
||||
take = min(remaining, row.source_quantity)
|
||||
@@ -574,8 +483,8 @@ def _settle(db,user,r,certs,usages,items,plan):
|
||||
raise ArchiveQuotaBlocked(conversion_error)
|
||||
if generated:
|
||||
r = r.model_copy(update={'manual_actuals': generated})
|
||||
# 同单位超出预占时,自动改用补扣证件池(新规则客户+品类,旧规则合同绑证),含原证剩余额度。
|
||||
auto_cover = False
|
||||
# 同单位超出预占时,自动改用合同上已绑定的购买证和运输证,含原证剩余额度。
|
||||
contract_cover = False
|
||||
if not r.allow_supplement:
|
||||
for sid, value in r.actual_by_source.items():
|
||||
mine = [a for rows in groups.values() for a in rows if a.source_id == sid]
|
||||
@@ -583,7 +492,7 @@ def _settle(db,user,r,certs,usages,items,plan):
|
||||
continue
|
||||
capacity = sum((a.source_quantity for a in groups['purchase'] if a.source_id == sid), ZERO)
|
||||
if value > capacity:
|
||||
auto_cover = True
|
||||
contract_cover = True
|
||||
break
|
||||
# 原始容量不随补量扩大;新增证件原始容量为零,后续纠错始终先用原分配。
|
||||
base_actual=dict(r.actual_by_source)
|
||||
@@ -592,7 +501,7 @@ def _settle(db,user,r,certs,usages,items,plan):
|
||||
capacity=sum((a.source_quantity for a in groups['purchase'] if a.source_id==sid),ZERO)
|
||||
if value>capacity:
|
||||
excess[sid]=value-capacity
|
||||
if r.allow_supplement or auto_cover: base_actual[sid]=capacity
|
||||
if r.allow_supplement or contract_cover: base_actual[sid]=capacity
|
||||
# 人工显式补量可从当前实运来源拆出一段(如原证24、新证5),两段合计仍是29。
|
||||
# 两证有一侧同单位时由联合分配器配对;异单位补量仍须完整人工输入。
|
||||
if r.allow_supplement and r.manual_allocations:
|
||||
@@ -644,52 +553,35 @@ def _settle(db,user,r,certs,usages,items,plan):
|
||||
settled={kind:settle_allocations(rows,base_actual,manual_actuals=[a for a in _manual(r.manual_actuals) if a.permit_kind==kind]) for kind,rows in groups.items()}
|
||||
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)
|
||||
if contract_cover:
|
||||
from app.services.pl_quota_planning import resolve_contract_bound_certs
|
||||
try:
|
||||
purchase_ids, transport_ids = _settle_cover_cert_ids(db, user, plan, r.sources)
|
||||
purchase_ids, transport_ids = resolve_contract_bound_certs(db, user, r.sources)
|
||||
except HTTPException as exc:
|
||||
raise ArchiveQuotaBlocked(str(getattr(exc, 'detail', exc))) from exc
|
||||
candidate_keys=[('purchase', x) for x in purchase_ids] + [('transport', x) for x in transport_ids]
|
||||
selected=set()
|
||||
for kind, cid in candidate_keys:
|
||||
for kind, cid in [('purchase', x) for x in purchase_ids] + [('transport', x) for x in transport_ids]:
|
||||
key=(kind, cid)
|
||||
if key not in certs:
|
||||
raise ArchiveQuotaBlocked(
|
||||
_archive_cover_block_message(db, user, r, plan, certs, candidate_keys)
|
||||
)
|
||||
raise ArchiveQuotaBlocked(ARCHIVE_QUOTA_BLOCK)
|
||||
if _settlement_cover_cert(db, user, r, plan, kind, certs[key]):
|
||||
selected.add(key)
|
||||
if not selected:
|
||||
raise ArchiveQuotaBlocked(
|
||||
_archive_cover_block_message(db, user, r, plan, certs, candidate_keys)
|
||||
)
|
||||
raise ArchiveQuotaBlocked(ARCHIVE_QUOTA_BLOCK)
|
||||
else:
|
||||
if not r.reason.strip() or not (r.evidence_urls.strip() or r.source_note.strip()):
|
||||
raise ValueError('补分配必须有理由及依据')
|
||||
selected={('purchase',x) for x in r.purchase_cert_ids}|{('transport',x) for x in r.transport_cert_ids}
|
||||
customer_rule = False
|
||||
# 校验器看到的是扣除原量、返还本计划旧账后的净可用量。
|
||||
base_totals={k:ZERO for k in usages}
|
||||
for kind,rows in settled.items():
|
||||
for row in rows: base_totals[(kind,row.allocation.permit_id)]+=row.actual_permit_quantity
|
||||
credits={k:SimpleNamespace(reserved_qty=u.reserved_qty+u.used_qty-base_totals[k]) for k,u in usages.items()}
|
||||
# 超额补扣需求仅为超出预占的部分。安排/完善并关闭写入的 manual_allocations
|
||||
# 是整笔计划量,若原样带入会与超额需求冲突(证件明明够却报额度不足)。
|
||||
extra_update = {
|
||||
'sources': [
|
||||
source.model_copy(update={'quantity': excess[source.source_id]})
|
||||
for source in r.sources if source.source_id in excess
|
||||
],
|
||||
}
|
||||
if auto_cover:
|
||||
extra_update['manual_allocations'] = []
|
||||
extra_request = r.model_copy(update=extra_update)
|
||||
extra_request=r.model_copy(update={'sources':[source.model_copy(update={'quantity':excess[source.source_id]}) for source in r.sources if source.source_id in excess]})
|
||||
try:
|
||||
result=_reserve(db,user,extra_request,plan,certs,credits,{},selected,preview=True,lock_preview=True)
|
||||
except InsufficientQuota as exc:
|
||||
if not auto_cover:
|
||||
if not contract_cover:
|
||||
raise
|
||||
from app.services.pl_quota_diagnostics import archive_quantity_shortfall_message
|
||||
cert_rows=[]
|
||||
@@ -703,8 +595,7 @@ def _settle(db,user,r,certs,usages,items,plan):
|
||||
message=archive_quantity_shortfall_message(
|
||||
getattr(exc, 'diagnostics', None), cert_rows, r.actual_by_source, excess,
|
||||
{source.source_id: source.unit for source in r.sources})
|
||||
fallback = CUSTOMER_ARCHIVE_QUOTA_BLOCK if customer_rule else ARCHIVE_QUOTA_BLOCK
|
||||
raise ArchiveQuotaBlocked(message or fallback) from exc
|
||||
raise ArchiveQuotaBlocked(message or ARCHIVE_QUOTA_BLOCK) from exc
|
||||
for kind in ('purchase','transport'):
|
||||
for row in result[kind+'Allocations']:
|
||||
supplemental.append((kind,row))
|
||||
|
||||
@@ -1,117 +0,0 @@
|
||||
"""证用品类产品关联差量保存:软删后再加回须复用唯一键行。"""
|
||||
from datetime import datetime
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
from fastapi import HTTPException
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.models.pl_quota_models import PlCertCategory, PlCertCategoryProduct
|
||||
from app.services import pl_cert_category_service as svc
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def db(monkeypatch):
|
||||
engine = create_engine('sqlite://')
|
||||
PlCertCategory.__table__.create(engine)
|
||||
PlCertCategoryProduct.__table__.create(engine)
|
||||
monkeypatch.setattr(svc, '_product_labels', lambda *a, **k: {})
|
||||
with Session(engine) as session:
|
||||
yield session
|
||||
engine.dispose()
|
||||
|
||||
|
||||
def user(tenant='t', uid='editor'):
|
||||
return SimpleNamespace(id=uid, tenant_no=tenant, dept_id='dept')
|
||||
|
||||
|
||||
def seed_category(db, id='cat', **extra):
|
||||
values = dict(
|
||||
id=id, category_name='硫酸', category_code='H2SO4', status='1',
|
||||
tenant_no='t', create_by='creator', create_dept_id='dept',
|
||||
create_time=datetime(2020, 1, 1), del_flag=0,
|
||||
)
|
||||
values.update(extra)
|
||||
row = PlCertCategory(**values)
|
||||
db.add(row)
|
||||
db.flush()
|
||||
return row
|
||||
|
||||
|
||||
def seed_link(db, id='link', product_id='339E64E02E7C41F3', del_flag=0, **extra):
|
||||
values = dict(
|
||||
id=id, category_id='cat', product_id=product_id, scope_status='active',
|
||||
tenant_no='t', create_by='creator', create_dept_id='dept',
|
||||
create_time=datetime(2020, 1, 1), del_flag=del_flag,
|
||||
)
|
||||
values.update(extra)
|
||||
row = PlCertCategoryProduct(**values)
|
||||
db.add(row)
|
||||
db.flush()
|
||||
return row
|
||||
|
||||
|
||||
def test_readd_soft_deleted_product_reuses_unique_key_row(db):
|
||||
seed_category(db)
|
||||
link = seed_link(db, del_flag=1)
|
||||
result = svc.save_category(
|
||||
db, user(),
|
||||
{'categoryName': '硫酸', 'products': [{'productId': link.product_id}]},
|
||||
category_id='cat',
|
||||
)
|
||||
db.flush()
|
||||
assert db.query(PlCertCategoryProduct).count() == 1
|
||||
assert link.del_flag == 0
|
||||
assert link.create_by == 'creator'
|
||||
assert link.create_time == datetime(2020, 1, 1)
|
||||
assert link.update_by == 'editor'
|
||||
assert result['products'][0]['id'] == link.id
|
||||
assert result['products'][0]['productId'] == link.product_id
|
||||
|
||||
|
||||
def test_remove_then_readd_without_id_keeps_one_row(db):
|
||||
seed_category(db)
|
||||
link = seed_link(db)
|
||||
svc.save_category(
|
||||
db, user(),
|
||||
{'categoryName': '硫酸', 'products': []},
|
||||
category_id='cat',
|
||||
)
|
||||
assert link.del_flag == 1
|
||||
svc.save_category(
|
||||
db, user(),
|
||||
{'categoryName': '硫酸', 'products': [{'productId': link.product_id, 'scopeStatus': 'active'}]},
|
||||
category_id='cat',
|
||||
)
|
||||
db.flush()
|
||||
assert db.query(PlCertCategoryProduct).count() == 1
|
||||
assert link.del_flag == 0
|
||||
assert link.scope_status == 'active'
|
||||
|
||||
|
||||
def test_no_id_reuses_active_row_by_product_id(db):
|
||||
seed_category(db)
|
||||
link = seed_link(db)
|
||||
svc.save_category(
|
||||
db, user(),
|
||||
{'categoryName': '硫酸', 'products': [{'productId': link.product_id}]},
|
||||
category_id='cat',
|
||||
)
|
||||
db.flush()
|
||||
assert db.query(PlCertCategoryProduct).filter_by(del_flag=0).count() == 1
|
||||
assert link.del_flag == 0
|
||||
assert link.id == 'link'
|
||||
|
||||
|
||||
def test_deleted_explicit_id_is_rejected(db):
|
||||
seed_category(db)
|
||||
link = seed_link(db, del_flag=1)
|
||||
with pytest.raises(HTTPException) as exc:
|
||||
svc.save_category(
|
||||
db, user(),
|
||||
{'categoryName': '硫酸', 'products': [{'id': link.id, 'productId': link.product_id}]},
|
||||
category_id='cat',
|
||||
)
|
||||
assert exc.value.status_code == 400
|
||||
assert link.del_flag == 1
|
||||
@@ -752,546 +752,3 @@ def test_get_cert_customer_name_from_crm_not_consignee(monkeypatch):
|
||||
assert result['customerName'] == '滁州康华电子材料有限公司'
|
||||
assert result['consigneeName'] == '国能宿州热电有限公司'
|
||||
assert result['customerId'] == 'cust-kanghua'
|
||||
|
||||
|
||||
def test_get_cert_purchase_category_name(monkeypatch):
|
||||
"""购买证详情回填证用品类名称,便于 H5/Web 只读展示。"""
|
||||
from app.services import pl_quota_cert_service as svc
|
||||
|
||||
class Col:
|
||||
def __init__(self, name):
|
||||
self.name = name
|
||||
|
||||
row = SimpleNamespace(
|
||||
id='p1',
|
||||
cert_no='G1',
|
||||
customer_id='cust1',
|
||||
category_id='cat-hcl',
|
||||
buyer_name='安庆市山峡化工有限公司',
|
||||
valid_use_text='多次有效',
|
||||
total_qty=Decimal('100'),
|
||||
used_qty=Decimal('0'),
|
||||
reserved_qty=Decimal('0'),
|
||||
__table__=SimpleNamespace(
|
||||
columns=[
|
||||
Col('id'),
|
||||
Col('cert_no'),
|
||||
Col('customer_id'),
|
||||
Col('category_id'),
|
||||
Col('buyer_name'),
|
||||
Col('valid_use_text'),
|
||||
Col('total_qty'),
|
||||
Col('used_qty'),
|
||||
Col('reserved_qty'),
|
||||
]
|
||||
),
|
||||
)
|
||||
monkeypatch.setattr(svc, '_get_row', lambda *a, **k: row)
|
||||
monkeypatch.setattr(svc, 'is_single_use_consumed', lambda *a, **k: False)
|
||||
monkeypatch.setattr(svc, '_customer_display_name', lambda *a, **k: '甲客户')
|
||||
monkeypatch.setattr(svc, '_category_display_names', lambda *a, **k: ['盐酸'])
|
||||
|
||||
opening = MagicMock()
|
||||
opening.filter_by.return_value.first.return_value = None
|
||||
db = MagicMock()
|
||||
db.query.return_value = opening
|
||||
|
||||
result = svc.get_cert(db, SimpleNamespace(tenant_no='t'), 'purchase', 'p1')
|
||||
assert result['customerName'] == '甲客户'
|
||||
assert result['categoryName'] == '盐酸'
|
||||
assert result['categoryId'] == 'cat-hcl'
|
||||
|
||||
|
||||
def test_get_cert_transport_derived_category_names(monkeypatch):
|
||||
"""运输证详情回填引用购买证品类名称并集。"""
|
||||
from app.services import pl_quota_cert_service as svc
|
||||
|
||||
class Col:
|
||||
def __init__(self, name):
|
||||
self.name = name
|
||||
|
||||
row = SimpleNamespace(
|
||||
id='t1',
|
||||
cert_no='Y1',
|
||||
customer_id='cust1',
|
||||
valid_use_text='多次有效',
|
||||
total_qty=Decimal('10'),
|
||||
used_qty=Decimal('0'),
|
||||
reserved_qty=Decimal('0'),
|
||||
__table__=SimpleNamespace(
|
||||
columns=[
|
||||
Col('id'),
|
||||
Col('cert_no'),
|
||||
Col('customer_id'),
|
||||
Col('valid_use_text'),
|
||||
Col('total_qty'),
|
||||
Col('used_qty'),
|
||||
Col('reserved_qty'),
|
||||
]
|
||||
),
|
||||
)
|
||||
monkeypatch.setattr(svc, '_get_row', lambda *a, **k: row)
|
||||
monkeypatch.setattr(svc, 'is_single_use_consumed', lambda *a, **k: False)
|
||||
monkeypatch.setattr(svc, '_customer_display_name', lambda *a, **k: '甲客户')
|
||||
monkeypatch.setattr(svc, '_refs', lambda *a, **k: [])
|
||||
monkeypatch.setattr(svc, '_has_usage_beyond_zero_opening', lambda *a, **k: False)
|
||||
monkeypatch.setattr(svc, '_transport_derived_categories', lambda *a, **k: ['c1', 'c2'])
|
||||
monkeypatch.setattr(svc, '_category_display_names', lambda *a, **k: ['硫酸', '盐酸'])
|
||||
|
||||
opening = MagicMock()
|
||||
opening.filter_by.return_value.first.return_value = None
|
||||
db = MagicMock()
|
||||
db.query.return_value = opening
|
||||
|
||||
result = svc.get_cert(db, SimpleNamespace(tenant_no='t'), 'transport', 't1')
|
||||
assert result['derivedCategoryIds'] == ['c1', 'c2']
|
||||
assert result['derivedCategoryNames'] == ['硫酸', '盐酸']
|
||||
|
||||
|
||||
def _remote_source(**kw):
|
||||
from app.schemas.pl.quota_usage import UsageSource
|
||||
|
||||
base = dict(
|
||||
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('30'),
|
||||
unit='吨',
|
||||
fingerprint='r' * 64,
|
||||
snapshot={'customerId': 'cust1'},
|
||||
requires_transport=True,
|
||||
)
|
||||
base.update(kw)
|
||||
return UsageSource(**base)
|
||||
|
||||
|
||||
def _ok_purchase(**kw):
|
||||
data = dict(
|
||||
id='buy1',
|
||||
cert_no='G-BUY-1',
|
||||
customer_id='cust1',
|
||||
category_id='cat1',
|
||||
status='active',
|
||||
verified_by='u',
|
||||
verified_time=datetime.now(),
|
||||
valid_from=None,
|
||||
valid_to=date(2027, 1, 1),
|
||||
total_qty=Decimal('100'),
|
||||
used_qty=Decimal('0'),
|
||||
reserved_qty=Decimal('0'),
|
||||
quantity_unit='吨',
|
||||
opening_single_use_consumed=0,
|
||||
)
|
||||
data.update(kw)
|
||||
return SimpleNamespace(**data)
|
||||
|
||||
|
||||
def _ok_transport(**kw):
|
||||
data = dict(
|
||||
id='tr1',
|
||||
cert_no='Y-TR-1',
|
||||
customer_id='cust1',
|
||||
status='active',
|
||||
verified_by='u',
|
||||
verified_time=datetime.now(),
|
||||
valid_from=None,
|
||||
valid_to=date(2027, 1, 1),
|
||||
total_qty=Decimal('100'),
|
||||
used_qty=Decimal('0'),
|
||||
reserved_qty=Decimal('0'),
|
||||
quantity_unit='吨',
|
||||
opening_single_use_consumed=0,
|
||||
vehicle_numbers_json=['皖A11111'],
|
||||
)
|
||||
data.update(kw)
|
||||
return SimpleNamespace(**data)
|
||||
|
||||
|
||||
def _mock_select_db(purchases, transports, refs):
|
||||
from app.models.pl_quota_models import (
|
||||
PlPurchaseCert,
|
||||
PlTransportCert,
|
||||
PlTransportCertPurchaseRef,
|
||||
PlCertQtyLog,
|
||||
)
|
||||
|
||||
class PurchaseQuery:
|
||||
def filter(self, *a, **k):
|
||||
return self
|
||||
|
||||
def order_by(self, *a, **k):
|
||||
return self
|
||||
|
||||
def all(self):
|
||||
return list(purchases)
|
||||
|
||||
class TransportQuery:
|
||||
def filter(self, *a, **k):
|
||||
return self
|
||||
|
||||
def order_by(self, *a, **k):
|
||||
return self
|
||||
|
||||
def all(self):
|
||||
return list(transports)
|
||||
|
||||
class RefQuery:
|
||||
def filter_by(self, **k):
|
||||
return self
|
||||
|
||||
def all(self):
|
||||
return list(refs)
|
||||
|
||||
class LogQuery:
|
||||
def filter_by(self, **k):
|
||||
return self
|
||||
|
||||
def first(self):
|
||||
return SimpleNamespace(id='opening')
|
||||
|
||||
db = MagicMock()
|
||||
|
||||
def q_side(model):
|
||||
if model is PlPurchaseCert:
|
||||
return PurchaseQuery()
|
||||
if model is PlTransportCert:
|
||||
return TransportQuery()
|
||||
if model is PlTransportCertPurchaseRef:
|
||||
return RefQuery()
|
||||
if model is PlCertQtyLog:
|
||||
return LogQuery()
|
||||
return MagicMock()
|
||||
|
||||
db.query.side_effect = q_side
|
||||
return db
|
||||
|
||||
|
||||
def test_whole_cover_vehicle_mismatch_message_is_precise(monkeypatch):
|
||||
"""异地段购买证够用但运输证未含该车牌时,应点名车牌与证号。"""
|
||||
from app.services import pl_quota_customer_select as sel
|
||||
|
||||
purchase = _ok_purchase()
|
||||
transport = _ok_transport(vehicle_numbers_json=['皖A00000'])
|
||||
ref = SimpleNamespace(transport_cert_id='tr1', purchase_cert_id='buy1')
|
||||
db = _mock_select_db([purchase], [transport], [ref])
|
||||
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()],
|
||||
vehicle_no='皖A9BE91',
|
||||
on_date=date(2026, 11, 14),
|
||||
)
|
||||
detail = str(exc.value.detail)
|
||||
assert exc.value.status_code == 409
|
||||
assert '皖A9BE91' in detail
|
||||
assert 'Y-TR-1' in detail
|
||||
assert '车号' in detail or '车牌' in detail
|
||||
assert '余量足够、有效期内且匹配品类/车号' not in detail
|
||||
|
||||
|
||||
def test_whole_cover_empty_vehicle_message_is_precise(monkeypatch):
|
||||
from app.services import pl_quota_customer_select as sel
|
||||
|
||||
purchase = _ok_purchase()
|
||||
transport = _ok_transport()
|
||||
ref = SimpleNamespace(transport_cert_id='tr1', purchase_cert_id='buy1')
|
||||
db = _mock_select_db([purchase], [transport], [ref])
|
||||
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()],
|
||||
vehicle_no=' ',
|
||||
on_date=date(2026, 11, 14),
|
||||
)
|
||||
detail = str(exc.value.detail)
|
||||
assert '车牌' in detail
|
||||
assert '余量足够、有效期内且匹配品类/车号' not in detail
|
||||
|
||||
|
||||
def test_whole_cover_purchase_insufficient_message_is_precise(monkeypatch):
|
||||
from app.services import pl_quota_customer_select as sel
|
||||
|
||||
purchase = _ok_purchase(total_qty=Decimal('10'), cert_no='G-SMALL')
|
||||
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('30'))],
|
||||
vehicle_no='皖A1',
|
||||
on_date=date(2026, 11, 14),
|
||||
)
|
||||
detail = str(exc.value.detail)
|
||||
assert 'G-SMALL' in detail
|
||||
assert '余量' in detail or '不够' in detail
|
||||
assert '余量足够、有效期内且匹配品类/车号' not in detail
|
||||
|
||||
|
||||
def test_whole_cover_no_purchase_message_includes_customer_and_product(monkeypatch):
|
||||
"""无匹配购买证时,提示须点名异地客户与产品,便于对照建档。"""
|
||||
from app.services import pl_quota_customer_select as sel
|
||||
|
||||
db = _mock_select_db([], [], [])
|
||||
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(
|
||||
snapshot={
|
||||
'customerId': 'cust1',
|
||||
'customerName': '滁州康华电子材料有限公司',
|
||||
'productName': '98% 工业硫酸',
|
||||
}
|
||||
)
|
||||
],
|
||||
vehicle_no='皖A9BE91',
|
||||
on_date=date(2026, 11, 14),
|
||||
)
|
||||
detail = str(exc.value.detail)
|
||||
assert exc.value.status_code == 409
|
||||
assert '异地段客户' in detail
|
||||
assert '滁州康华电子材料有限公司' in detail
|
||||
assert '98% 工业硫酸' in detail
|
||||
assert '匹配品类的有效购买证' in detail
|
||||
|
||||
|
||||
def test_resolve_customer_category_cover_certs_lists_pool(monkeypatch):
|
||||
from app.services import pl_quota_customer_select as sel
|
||||
|
||||
purchase = _ok_purchase()
|
||||
transport = _ok_transport()
|
||||
ref = SimpleNamespace(transport_cert_id='tr1', purchase_cert_id='buy1')
|
||||
db = _mock_select_db([purchase], [transport], [ref])
|
||||
monkeypatch.setattr(sel, 'category_ids_for_product', lambda *a, **k: {'cat1'})
|
||||
|
||||
purchase_ids, transport_ids = sel.resolve_customer_category_cover_certs(
|
||||
db,
|
||||
SimpleNamespace(tenant_no='t'),
|
||||
[_remote_source(snapshot={'customerId': 'cust1', 'customerName': '昆腾'})],
|
||||
)
|
||||
assert purchase_ids == ['buy1']
|
||||
assert transport_ids == ['tr1']
|
||||
|
||||
|
||||
def test_resolve_customer_category_cover_certs_missing_uses_customer_wording(monkeypatch):
|
||||
from app.services import pl_quota_customer_select as sel
|
||||
|
||||
db = _mock_select_db([], [], [])
|
||||
monkeypatch.setattr(sel, 'category_ids_for_product', lambda *a, **k: {'cat1'})
|
||||
|
||||
with pytest.raises(HTTPException) as exc:
|
||||
sel.resolve_customer_category_cover_certs(
|
||||
db,
|
||||
SimpleNamespace(tenant_no='t'),
|
||||
[_remote_source(snapshot={'customerId': 'cust1', 'customerName': '昆腾'})],
|
||||
)
|
||||
detail = str(exc.value.detail)
|
||||
assert '客户昆腾' in detail
|
||||
assert '合同' not in detail
|
||||
|
||||
|
||||
def test_settle_cover_cert_ids_customer_rule_skips_contract_bindings(monkeypatch):
|
||||
from app.services import pl_quota_usage_service as usage
|
||||
|
||||
plan = SimpleNamespace(id='plan', cert_quota_rule_version='customer_category')
|
||||
called = {'contract': 0, 'customer': 0}
|
||||
|
||||
def fake_customer(db, user, sources):
|
||||
called['customer'] += 1
|
||||
return ['buy1'], ['tr1']
|
||||
|
||||
def fake_contract(db, user, sources):
|
||||
called['contract'] += 1
|
||||
raise AssertionError('customer_category 归档超额不应查合同绑证')
|
||||
|
||||
monkeypatch.setattr(
|
||||
'app.services.pl_quota_customer_select.resolve_customer_category_cover_certs',
|
||||
fake_customer,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'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()],
|
||||
)
|
||||
assert purchase_ids == ['buy1']
|
||||
assert transport_ids == ['tr1']
|
||||
assert called == {'contract': 0, 'customer': 1}
|
||||
|
||||
|
||||
def test_archive_cover_block_message_customer_rule_wording(monkeypatch):
|
||||
from app.services import pl_quota_usage_service as svc
|
||||
|
||||
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, {}, [],
|
||||
)
|
||||
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')
|
||||
@@ -249,11 +249,6 @@ def test_same_city_settlement_does_not_require_transport_pairing():
|
||||
assert validate_allocation_pairing([demand], [purchase], [], []) is None
|
||||
|
||||
|
||||
def test_empty_transport_kind_settle_ignores_source_actuals():
|
||||
"""同市只结转购买证时,空的运输证分组对实运量应直接空结果,不报缺实际量。"""
|
||||
assert settle_allocations([], {'city': D(10)}) == ()
|
||||
|
||||
|
||||
@pytest.mark.parametrize('manual_values', [(8,10,0),(18,0,0)])
|
||||
def test_zero_capacity_foreign_row_cannot_unlock_manual_reordering(manual_values):
|
||||
from app.services.pl_quota_allocation import Allocation
|
||||
|
||||
@@ -64,44 +64,6 @@ def test_create_with_bindings_and_bad_create_has_no_pending_row(case):
|
||||
assert result['id'] not in ('g1', 'g2')
|
||||
|
||||
|
||||
def test_create_with_empty_contract_bindings_auto_enables(case):
|
||||
"""前端保存常带 contractBindings:[];必须与无合同集合路径一样自动启用并落库。"""
|
||||
c = case
|
||||
body = dict(
|
||||
certNo='G-AUTO',
|
||||
productNameOnCert='硫酸',
|
||||
totalQty='300',
|
||||
quantityUnit='吨',
|
||||
validUseText='多次有效',
|
||||
buyerName='买方',
|
||||
sellerName='卖方',
|
||||
contractBindings=[],
|
||||
)
|
||||
result = save(c, body, None)
|
||||
assert result['status'] == 'active'
|
||||
assert result['openingConfirmed'] is True
|
||||
assert result['verifiedBy'] == 'u'
|
||||
row = c.db.query(c.m.PlPurchaseCert).filter_by(id=result['id']).one()
|
||||
assert row.status == 'active'
|
||||
assert row.verified_by == 'u'
|
||||
assert c.db.query(c.m.PlCertQtyLog).filter_by(
|
||||
cert_id=result['id'], event_type='opening', del_flag=0,
|
||||
).count() == 1
|
||||
|
||||
|
||||
def test_get_cert_read_does_not_fake_enable_draft(case):
|
||||
"""只读详情/列表不得在未提交事务里把 draft 伪装成 active。"""
|
||||
from app.services import pl_quota_cert_service as certs
|
||||
|
||||
c = case
|
||||
row = c.db.query(c.m.PlPurchaseCert).filter_by(id='g1').one()
|
||||
assert row.status == 'draft'
|
||||
detail = certs.get_cert(c.db, c.user, 'purchase', 'g1')
|
||||
assert detail['status'] == 'draft'
|
||||
assert c.db.query(c.m.PlPurchaseCert).filter_by(id='g1').one().status == 'draft'
|
||||
assert c.db.query(c.m.PlCertQtyLog).filter_by(cert_id='g1', del_flag=0).count() == 0
|
||||
|
||||
|
||||
def test_hidden_contract_cannot_be_cleared_but_face_can_change(case, monkeypatch):
|
||||
from app.services import pl_quota_cert_bindings as svc
|
||||
from app.models.crm_models import CrmContract
|
||||
|
||||
@@ -98,31 +98,6 @@ def test_zero_reservation_consumes_once_slot(case):
|
||||
assert c.db.query(c.m.PlPlanCertUsage).count()==2
|
||||
with pytest.raises(ValueError): run(c,operation_id='other',plan_id='other',sources=sources)
|
||||
|
||||
def test_same_city_purchase_only_settle_without_transport(case):
|
||||
"""同市段只预占购买证时,归档结转不得因空运输证分组误报缺实际量。"""
|
||||
c = case
|
||||
sources = [dict(
|
||||
source_stop_type='delivery', source_stop_id='stop', source_stop_product_id='sp',
|
||||
plan_product_id='pp', contract_id='c', contract_product_id='cp', product_id='product',
|
||||
quantity='1', unit='吨', fingerprint='fp', requires_transport=False,
|
||||
)]
|
||||
run(c, purchase_cert_ids=['p'], transport_cert_ids=[], sources=sources)
|
||||
assert c.db.query(c.m.PlPlanCertUsage).count() == 1
|
||||
assert c.db.get(c.m.PlPurchaseCert, 'p').reserved_qty == 1
|
||||
run(
|
||||
c,
|
||||
operation_id='settle-same-city',
|
||||
action='settle',
|
||||
purchase_cert_ids=['p'],
|
||||
transport_cert_ids=[],
|
||||
sources=sources,
|
||||
actual_by_source={'delivery:sp': '1'},
|
||||
)
|
||||
assert c.db.get(c.m.PlPurchaseCert, 'p').used_qty == 1
|
||||
assert c.db.get(c.m.PlPurchaseCert, 'p').reserved_qty == 0
|
||||
assert c.db.query(c.m.PlTransportCert).filter_by(id='t').one().used_qty == 0
|
||||
|
||||
|
||||
def test_same_cert_balance_covers_actual_above_reservation(case):
|
||||
c = case
|
||||
run(c)
|
||||
@@ -133,27 +108,6 @@ def test_same_cert_balance_covers_actual_above_reservation(case):
|
||||
assert c.db.query(c.m.PlPlanCertUsage).count() == 2
|
||||
|
||||
|
||||
def test_auto_cover_ignores_arrangement_manuals_when_actual_exceeds_reservation(case):
|
||||
"""安排/完善并关闭写入的整笔 manual_allocations 不得挡住归档超额补扣。"""
|
||||
c = case
|
||||
manuals = [
|
||||
dict(permit_kind='purchase', source_id='load:sp', permit_id='p', source_quantity='29', permit_quantity='29'),
|
||||
dict(permit_kind='transport', source_id='load:sp', permit_id='t', source_quantity='29', permit_quantity='29'),
|
||||
]
|
||||
run(c, manual_allocations=manuals)
|
||||
# 归档请求仍带着计划量人工行(与完善并关闭后 cert_configuration 回灌一致)
|
||||
run(
|
||||
c,
|
||||
operation_id='settle-with-stale-manuals',
|
||||
action='settle',
|
||||
actual_by_source={'load:sp': '35'},
|
||||
manual_allocations=manuals,
|
||||
)
|
||||
assert c.db.get(c.m.PlPurchaseCert, 'p').used_qty == 35
|
||||
assert c.db.get(c.m.PlPurchaseCert, 'p').reserved_qty == 0
|
||||
assert c.db.get(c.m.PlTransportCert, 't').used_qty == 35
|
||||
|
||||
|
||||
def test_same_cert_without_enough_balance_asks_for_another_certificate(case):
|
||||
c = case
|
||||
c.db.get(c.m.PlPurchaseCert, 'p').total_qty = 30
|
||||
@@ -291,7 +245,7 @@ def test_opening_consumed_and_expiry_vehicle_block(case):
|
||||
p.opening_single_use_consumed=0; p.valid_to=date(2000,1,1); c.db.flush()
|
||||
with pytest.raises(ValueError): run(c)
|
||||
p.valid_to=date(2099,12,31); c.db.flush()
|
||||
with pytest.raises(ValueError, match='车牌号「unknown」不在运输证车号范围内'): run(c,vehicle_no='unknown')
|
||||
with pytest.raises(ValueError, match='车号不在运输证范围'): run(c,vehicle_no='unknown')
|
||||
|
||||
|
||||
def test_reserve_uses_transport_cert_that_lists_the_vehicle(case):
|
||||
@@ -308,19 +262,9 @@ def test_reserve_uses_transport_cert_that_lists_the_vehicle(case):
|
||||
assert c.db.get(c.m.PlPurchaseCert, 'p2').reserved_qty == 0
|
||||
transport_usages = c.db.query(c.m.PlPlanCertUsage).filter_by(cert_type='transport', del_flag=0).all()
|
||||
assert [u.cert_id for u in transport_usages if u.usage_status == 'reserved'] == ['t']
|
||||
with pytest.raises(ValueError, match='车牌号「NONE」不在运输证车号范围内'):
|
||||
with pytest.raises(ValueError, match='车号不在运输证范围'):
|
||||
run(c, operation_id='none', vehicle_no='NONE', purchase_cert_ids=['p', 'p2'], transport_cert_ids=['t', 't2'])
|
||||
|
||||
|
||||
def test_reserve_accepts_vehicle_no_with_trailing_spaces(case):
|
||||
"""计划车牌尾部空格不得误判为不在运输证车号范围。"""
|
||||
c = case
|
||||
# 证上车号无空格;计划侧常带尾部空格(与 PO20261115096 现场一致)
|
||||
assert c.db.get(c.m.PlTransportCert, 't').vehicle_numbers_json == ['CAR']
|
||||
run(c, vehicle_no='CAR ')
|
||||
assert c.db.get(c.m.PlTransportCert, 't').reserved_qty == 29
|
||||
|
||||
|
||||
def test_no_cert_operation_is_still_idempotent(case):
|
||||
c=case
|
||||
first=run(c,sources=[],purchase_cert_ids=[],transport_cert_ids=[])
|
||||
@@ -554,50 +498,3 @@ def test_new_current_usage_rejects_without_out_of_order_cert_lock(case,monkeypat
|
||||
assert c.db.get(c.m.PlPurchaseCert,'p').reserved_qty==29
|
||||
assert all(u.reserved_qty==29 for u in c.db.query(c.m.PlPlanCertUsage).all())
|
||||
assert c.db.query(c.m.PlCertOperation).count()==1
|
||||
|
||||
|
||||
def test_archive_cover_block_message_names_vehicle(monkeypatch):
|
||||
"""归档补证被车号挡住时,应点名车牌与运输证,而不是笼统额度不足。"""
|
||||
from types import SimpleNamespace
|
||||
from datetime import date
|
||||
from app.services import pl_quota_usage_service as svc
|
||||
|
||||
transport = SimpleNamespace(
|
||||
id='t1',
|
||||
cert_no='Y-ARCH-1',
|
||||
status='active',
|
||||
verified_by='u',
|
||||
verified_time=date(2026, 1, 1),
|
||||
valid_from=date(2026, 1, 1),
|
||||
valid_to=date(2027, 12, 31),
|
||||
valid_use_text='多次有效',
|
||||
vehicle_numbers_json=['皖A00000'],
|
||||
)
|
||||
r = SimpleNamespace(vehicle_no='皖A9BE91', on_date=date(2026, 11, 15))
|
||||
plan = SimpleNamespace(id='plan1')
|
||||
user = SimpleNamespace(tenant_no='t')
|
||||
|
||||
class OpeningQuery:
|
||||
def first(self):
|
||||
return SimpleNamespace(id='opening')
|
||||
|
||||
db = SimpleNamespace()
|
||||
monkeypatch.setattr(
|
||||
svc,
|
||||
'_query',
|
||||
lambda db, user, model, lock=True, **filters: OpeningQuery(),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.pl_quota_cert_service.ensure_zero_opening',
|
||||
lambda db, user, kind, cert_id, row=None: row or transport,
|
||||
)
|
||||
monkeypatch.setattr(svc, 'usage_policy', lambda text: 'multi')
|
||||
monkeypatch.setattr(svc, 'is_single_use_consumed', lambda *a, **k: False)
|
||||
|
||||
message = svc._archive_cover_block_message(
|
||||
db, user, r, plan, {('transport', 't1'): transport}, [('transport', 't1')],
|
||||
)
|
||||
assert '皖A9BE91' in message
|
||||
assert 'Y-ARCH-1' in message
|
||||
assert '未包含车牌号' in message
|
||||
assert '剩余额度不够覆盖本次实际数量' not in message
|
||||
@@ -9,5 +9,5 @@ allowBuilds:
|
||||
core-js: false
|
||||
es5-ext: false
|
||||
esbuild: true
|
||||
protobufjs: true
|
||||
protobufjs: false
|
||||
vue-demi: true
|
||||
@@ -31,24 +31,17 @@ test('pending keywords still force alert mode without plan flags', () => {
|
||||
)
|
||||
})
|
||||
|
||||
test('unmarked quota block only alerts, never offers certificate ready', () => {
|
||||
test('unmarked legacy quota block still offers certificate ready', () => {
|
||||
assert.equal(
|
||||
resolveArchiveQuotaBlockMode(
|
||||
'实际数量已保存,证件没有扣减。请把实际数量改小,或先补充购买证和运输证,再重新归档。',
|
||||
'用证没有完成',
|
||||
{ quotaCertPendingFulfill: 0, quotaCertWaived: 0 }
|
||||
),
|
||||
'alert-plain'
|
||||
'confirm-ready'
|
||||
)
|
||||
})
|
||||
|
||||
test('non quota-title blocks stay plain alert', () => {
|
||||
assert.equal(resolveArchiveQuotaBlockMode('不能归档:缺证', '不能归档', {}), 'alert-plain')
|
||||
})
|
||||
|
||||
test('missing actual-quantity settle error does not offer certificate ready', () => {
|
||||
assert.equal(
|
||||
resolveArchiveQuotaBlockMode('必须明确提交每个来源的实际量', '用证没有完成', {}),
|
||||
'alert-plain'
|
||||
)
|
||||
})
|
||||
@@ -65,38 +65,6 @@ test('web customer quota panel uses toQueryParams from useServerColumnFilters',
|
||||
assert.match(panel, /watchVisibleColumns/)
|
||||
})
|
||||
|
||||
test('web customer quota panel computes visibleDefs locally (not from composable)', () => {
|
||||
const panel = readFileSync(
|
||||
new URL('../src/views/pl/contract-quota/CustomerQuotaPanel.vue', import.meta.url),
|
||||
'utf8'
|
||||
)
|
||||
assert.doesNotMatch(
|
||||
panel,
|
||||
/const \{[^}]*\bvisibleDefs\b[^}]*\} = usePersistedListColumns/
|
||||
)
|
||||
assert.match(
|
||||
panel,
|
||||
/const \{ visibleColumns, checkAll, isIndeterminate, resetToDefault \} = usePersistedListColumns/
|
||||
)
|
||||
assert.match(
|
||||
panel,
|
||||
/const visibleDefs = computed\(\(\) =>\s*columns\.filter\(\(column\) => visibleColumns\.value\.includes\(column\.prop\)\)/
|
||||
)
|
||||
assert.match(panel, /v-for="column in visibleDefs"/)
|
||||
})
|
||||
|
||||
test('h5 customer tab renders customer fields without persisted column defs', () => {
|
||||
const tab = readFileSync(
|
||||
new URL('../src/views/m/pl/plan-cert/CustomerTab.vue', import.meta.url),
|
||||
'utf8'
|
||||
)
|
||||
assert.doesNotMatch(tab, /usePersistedListColumns/)
|
||||
assert.doesNotMatch(tab, /visibleDefs/)
|
||||
assert.match(tab, /row\.customerName/)
|
||||
assert.match(tab, /row\.customerNo/)
|
||||
assert.match(tab, /row\.certCount/)
|
||||
})
|
||||
|
||||
test('h5 customer quota tab does not call buildQuery', () => {
|
||||
const tab = readFileSync(
|
||||
new URL('../src/views/m/pl/plan-cert/CustomerTab.vue', import.meta.url),
|
||||
@@ -105,22 +73,3 @@ test('h5 customer quota tab does not call buildQuery', () => {
|
||||
assert.doesNotMatch(tab, /\bbuildQuery\b/)
|
||||
assert.match(tab, /quotaStatisticsApi\.customers/)
|
||||
})
|
||||
|
||||
test('web customer quota panel wires viewport height like StatisticsPanel', () => {
|
||||
const panel = readFileSync(
|
||||
new URL('../src/views/pl/contract-quota/CustomerQuotaPanel.vue', import.meta.url),
|
||||
'utf8'
|
||||
)
|
||||
assert.match(panel, /useElementSize\(tableWrapRef\)/)
|
||||
assert.match(
|
||||
panel,
|
||||
/const expansionStyle = computed\(\(\) => \(\{[\s\S]*width: tableViewportWidth/
|
||||
)
|
||||
assert.match(panel, /tableEl: tableWrapRef/)
|
||||
assert.match(panel, /pagerEl: pagerRef/)
|
||||
assert.doesNotMatch(panel, /\bwrapRef\s*:/)
|
||||
assert.doesNotMatch(
|
||||
panel,
|
||||
/const \{[^}]*\bexpansionStyle\b[^}]*\} = useListTableViewportHeight/
|
||||
)
|
||||
})
|
||||
@@ -39,34 +39,6 @@ test('H5 客户用证按客户列表展示证件', () => {
|
||||
assert.match(contractTab, /\/m\/pl\/plan-cert\/customer\//)
|
||||
assert.match(contractTab, /暂无客户用证数据/)
|
||||
assert.match(planCertIndex, /title: '客户用证'/)
|
||||
assert.match(planCertIndex, /客户名称 \/ 编号/)
|
||||
assert.doesNotMatch(planCertIndex, /合同编号 \/ 名称 \/ 销售或购买单位/)
|
||||
})
|
||||
|
||||
test('H5 客户用证详情显式导入 WebView 壳,避免空白页', () => {
|
||||
const customerDetail = readFileSync(
|
||||
new URL('../src/views/m/pl/plan-cert/customer-detail.vue', import.meta.url),
|
||||
'utf8'
|
||||
)
|
||||
assert.match(customerDetail, /import MpWebviewShell from '@\/layouts\/MpWebviewShell\.vue'/)
|
||||
assert.match(customerDetail, /import MpBusinessHeader from '@\/components\/mp\/MpBusinessHeader\.vue'/)
|
||||
assert.match(customerDetail, /@ready="onShellReady"/)
|
||||
})
|
||||
|
||||
test('H5 证件详情与建档列表展示系统客户和证用品类', () => {
|
||||
const faceModel = readFileSync(
|
||||
new URL('../src/views/m/pl/plan-cert/face-model.ts', import.meta.url),
|
||||
'utf8'
|
||||
)
|
||||
const archiveTab = readFileSync(
|
||||
new URL('../src/views/m/pl/plan-cert/ArchiveTab.vue', import.meta.url),
|
||||
'utf8'
|
||||
)
|
||||
assert.match(faceModel, /label: '证用品类'/)
|
||||
assert.match(faceModel, /certCategoryLabel/)
|
||||
assert.match(archiveTab, /系统客户/)
|
||||
assert.match(archiveTab, /证用品类/)
|
||||
assert.match(archiveTab, /certCategoryLabel/)
|
||||
})
|
||||
|
||||
test('H5 建档页使用关联购买证且无证面引用残留', () => {
|
||||
|
||||
@@ -1,91 +0,0 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { existsSync, readFileSync } from 'node:fs'
|
||||
import test from 'node:test'
|
||||
import ts from 'typescript'
|
||||
import * as vue from 'vue'
|
||||
|
||||
function loadFreightCalc() {
|
||||
const path = new URL('../src/composables/usePlFreightCalc.ts', import.meta.url)
|
||||
assert.ok(existsSync(path), 'usePlFreightCalc must exist')
|
||||
const source = readFileSync(path, 'utf8')
|
||||
const ast = ts.createSourceFile('usePlFreightCalc.ts', source, ts.ScriptTarget.Latest, true)
|
||||
const code = ast.statements
|
||||
.filter((node) => !ts.isImportDeclaration(node))
|
||||
.map((node) => node.getText(ast))
|
||||
.join('\n')
|
||||
const compiled = ts.transpileModule(code, {
|
||||
compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS }
|
||||
}).outputText
|
||||
const module = { exports: {} as Record<string, unknown> }
|
||||
const requireStub = () => {
|
||||
throw new Error('unexpected require in freight calc test harness')
|
||||
}
|
||||
// eslint-disable-next-line no-new-func
|
||||
const factory = new Function(
|
||||
'exports',
|
||||
'require',
|
||||
'module',
|
||||
'__filename',
|
||||
'__dirname',
|
||||
'computed',
|
||||
'ref',
|
||||
'watch',
|
||||
compiled + '\nmodule.exports = { usePlFreightCalc, sumProductActualQuantities };'
|
||||
)
|
||||
factory(
|
||||
module.exports,
|
||||
requireStub,
|
||||
module,
|
||||
'usePlFreightCalc.ts',
|
||||
'.',
|
||||
vue.computed,
|
||||
vue.ref,
|
||||
vue.watch
|
||||
)
|
||||
return module.exports as {
|
||||
usePlFreightCalc: typeof import('../src/composables/usePlFreightCalc').usePlFreightCalc
|
||||
}
|
||||
}
|
||||
|
||||
test('resetFreightCalc re-sums transport qty from existing product actuals', async () => {
|
||||
const { usePlFreightCalc } = loadFreightCalc()
|
||||
const products = vue.ref([{ actualQty: 0.04, unit: '吨' }, { actualQty: 0.04, unit: '吨' }])
|
||||
const hasFreight = vue.ref(1)
|
||||
const freightType = vue.ref('by_weight')
|
||||
|
||||
const scope = vue.effectScope()
|
||||
const calc = scope.run(() => usePlFreightCalc({ products, hasFreight, freightType }))
|
||||
assert.ok(calc)
|
||||
await vue.nextTick()
|
||||
assert.equal(calc!.transportQty.value, 0.08)
|
||||
|
||||
calc!.resetFreightCalc()
|
||||
await vue.nextTick()
|
||||
assert.equal(calc!.transportQtyTouched.value, false)
|
||||
assert.equal(
|
||||
calc!.transportQty.value,
|
||||
0.08,
|
||||
'reset after products already loaded must not leave transport qty empty'
|
||||
)
|
||||
scope.stop()
|
||||
})
|
||||
|
||||
test('resetFreightCalc restores product sum after manual transport qty edit', async () => {
|
||||
const { usePlFreightCalc } = loadFreightCalc()
|
||||
const products = vue.ref([{ actualQty: 0.04, unit: '吨' }])
|
||||
const hasFreight = vue.ref(1)
|
||||
const freightType = vue.ref('by_weight')
|
||||
|
||||
const scope = vue.effectScope()
|
||||
const calc = scope.run(() => usePlFreightCalc({ products, hasFreight, freightType }))
|
||||
assert.ok(calc)
|
||||
await vue.nextTick()
|
||||
|
||||
calc!.transportQty.value = 9.9
|
||||
calc!.markTransportQtyTouched()
|
||||
calc!.resetFreightCalc()
|
||||
await vue.nextTick()
|
||||
assert.equal(calc!.transportQtyTouched.value, false)
|
||||
assert.equal(calc!.transportQty.value, 0.04)
|
||||
scope.stop()
|
||||
})
|
||||
@@ -65,9 +65,7 @@ export interface QuotaCert extends Omit<CertBody, 'status'> {
|
||||
createTime?: string
|
||||
certType?: CertType
|
||||
derivedCategoryIds?: string[]
|
||||
derivedCategoryNames?: string[]
|
||||
customerName?: string | null
|
||||
categoryName?: string | null
|
||||
}
|
||||
export interface ScopeProduct {
|
||||
id?: string
|
||||
|
||||
@@ -1604,17 +1604,36 @@
|
||||
async function showArchiveQuotaBlockDialog(message: string, title = '不能归档') {
|
||||
const html = `<p class="pl-arrange-block-text">${escapeArchiveBlockText(message)}</p>`
|
||||
const mode = resolveArchiveQuotaBlockMode(message, title, plan.value)
|
||||
const guide =
|
||||
mode === 'alert-pending'
|
||||
? `${html}<p class="pl-arrange-block-text">该运输计划已走证书齐备,归档前须完善证件。请到「证书齐备 → 已标记待完善证书」上传购买证/运输证并执行完善并关闭后再归档。</p>`
|
||||
: html
|
||||
await ElMessageBox.alert(guide, title, {
|
||||
type: 'warning',
|
||||
confirmButtonText: '知道了',
|
||||
dangerouslyUseHTMLString: true,
|
||||
customClass: 'pl-arrange-block-msgbox',
|
||||
closeOnClickModal: false
|
||||
}).catch(() => undefined)
|
||||
if (mode !== 'confirm-ready') {
|
||||
const guide =
|
||||
mode === 'alert-pending'
|
||||
? `${html}<p class="pl-arrange-block-text">该运输计划已走证书齐备,归档前须完善证件。请到「证书齐备 → 已标记待完善证书」上传购买证/运输证并执行完善并关闭后再归档。</p>`
|
||||
: html
|
||||
await ElMessageBox.alert(guide, title, {
|
||||
type: 'warning',
|
||||
confirmButtonText: '知道了',
|
||||
dangerouslyUseHTMLString: true,
|
||||
customClass: 'pl-arrange-block-msgbox',
|
||||
closeOnClickModal: false
|
||||
}).catch(() => undefined)
|
||||
return undefined
|
||||
}
|
||||
// 仅旧规则(legacy)允许在归档时标记证书齐备以跳过额度
|
||||
const readyHtml = `${html}<p class="pl-arrange-block-text">如果购买证、运输证还没上传,可以标记证书齐备。仅旧规则计划标记后这次归档不再校验、不扣这两证额度;新规则计划请走「证书齐备 → 已标记待完善证书」。</p>`
|
||||
try {
|
||||
await ElMessageBox.confirm(readyHtml, title, {
|
||||
type: 'warning',
|
||||
confirmButtonText: '证书齐备',
|
||||
cancelButtonText: '知道了',
|
||||
dangerouslyUseHTMLString: true,
|
||||
customClass: 'pl-arrange-block-msgbox',
|
||||
closeOnClickModal: false,
|
||||
distinguishCancelAndClose: true
|
||||
})
|
||||
return 'ready' as const
|
||||
} catch {
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
|
||||
function applyArchiveOverageHighlight(items: Array<Record<string, unknown>>) {
|
||||
@@ -1649,7 +1668,13 @@
|
||||
// 业务异常已作为一次请求提交;补齐条件后允许新尝试,不回放旧异常。
|
||||
quotaArchiveAttempt = { signature: '', id: '' }
|
||||
const message = saved.quotaSettlementError
|
||||
await showArchiveQuotaBlockDialog(message, '用证没有完成')
|
||||
const choice = await showArchiveQuotaBlockDialog(message, '用证没有完成')
|
||||
if (choice === 'ready' && current()) {
|
||||
await planApi.markQuotaCertReady(targetId)
|
||||
if (!current()) return
|
||||
await submitArchiveWithOverageConfirm(targetId, frozenBody, current, confirmOverage)
|
||||
return
|
||||
}
|
||||
const error = new Error(message) as Error & { cancelled?: boolean }
|
||||
error.cancelled = true
|
||||
throw error
|
||||
|
||||
@@ -86,13 +86,11 @@ export function usePlFreightCalc(options: {
|
||||
)
|
||||
|
||||
function resetFreightCalc() {
|
||||
transportQty.value = null
|
||||
transportQtyTouched.value = false
|
||||
freightAmount.value = null
|
||||
freightAmountTouched.value = false
|
||||
freightPrice.value = null
|
||||
// 产品已加载时 watch 不会因 reset 重跑;须立即按当前实际数量回填,
|
||||
// 否则归档弹窗再次打开会误报「运输量须大于0」。
|
||||
transportQty.value = defaultTransportQty.value || null
|
||||
}
|
||||
|
||||
function markTransportQtyTouched() {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
/** 归档用证拦截弹窗:只提醒,不在归档界面提供「证书齐备」操作。 */
|
||||
/** 归档用证拦截弹窗:已齐备/待完善只提醒,未齐备旧规则才可再点证书齐备。 */
|
||||
|
||||
export type ArchiveQuotaBlockMode = 'alert-pending' | 'alert-plain'
|
||||
export type ArchiveQuotaBlockMode = 'alert-pending' | 'alert-plain' | 'confirm-ready'
|
||||
|
||||
export type ArchiveQuotaBlockPlanFlags = {
|
||||
quotaCertPendingFulfill?: number | boolean | null
|
||||
@@ -23,5 +23,5 @@ export function resolveArchiveQuotaBlockMode(
|
||||
const pendingByPlan = flagOn(plan?.quotaCertPendingFulfill) || flagOn(plan?.quotaCertWaived)
|
||||
if (title !== '用证没有完成') return 'alert-plain'
|
||||
if (pendingByPlan || pendingByMessage) return 'alert-pending'
|
||||
return 'alert-plain'
|
||||
return 'confirm-ready'
|
||||
}
|
||||
@@ -25,12 +25,6 @@
|
||||
}}</span>
|
||||
</div>
|
||||
<div class="mp-wv-card__kv">
|
||||
<div class="mp-wv-card__kv-row"
|
||||
><span>系统客户</span><span>{{ row.customerName || '—' }}</span></div
|
||||
>
|
||||
<div class="mp-wv-card__kv-row"
|
||||
><span>证用品类</span><span>{{ certCategoryLabel(row) }}</span></div
|
||||
>
|
||||
<div class="mp-wv-card__kv-row"
|
||||
><span>销售单位</span><span>{{ salePartyName(row) || '—' }}</span></div
|
||||
>
|
||||
@@ -125,7 +119,7 @@
|
||||
} from '@/views/pl/quota-cert/cert-list-face'
|
||||
import { useDictStore } from '@/store/modules/dict'
|
||||
import { getProductUnitLabel } from '@/utils/crm-product-display'
|
||||
import { certCategoryLabel, certStatusLabels } from './face-model'
|
||||
import { certStatusLabels } from './face-model'
|
||||
|
||||
const props = defineProps<{
|
||||
keyword: string
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<template>
|
||||
<MpWebviewShell @ready="onShellReady">
|
||||
<MpWebviewShell @ready="ready = true">
|
||||
<MpBusinessHeader title="客户用证" back-label="返回运输证件管理" @back="router.back()" />
|
||||
<main v-if="ready" class="mp-h5-list-content mp-h5-detail-page mp-plan-cert-list">
|
||||
<p v-if="error" class="mp-wv-empty" role="alert">
|
||||
@@ -34,19 +34,11 @@
|
||||
import { useRoute, useRouter } from 'vue-router'
|
||||
import { fetchGetMenuCodes } from '@/api/auth'
|
||||
import { quotaStatisticsApi, type CustomerStatistics } from '@/api/pl/quota-cert'
|
||||
import MpWebviewShell from '@/layouts/MpWebviewShell.vue'
|
||||
import MpBusinessHeader from '@/components/mp/MpBusinessHeader.vue'
|
||||
import CustomerCertQuotaTab from '@/views/m/crm/contract/CustomerCertQuotaTab.vue'
|
||||
import '@/styles/mp-webview.scss'
|
||||
import './cert-mobile.scss'
|
||||
|
||||
const route = useRoute()
|
||||
const router = useRouter()
|
||||
const ready = ref(false)
|
||||
|
||||
function onShellReady() {
|
||||
ready.value = true
|
||||
}
|
||||
const authReady = ref(false)
|
||||
const allowed = ref(false)
|
||||
const loading = ref(true)
|
||||
|
||||
@@ -30,22 +30,6 @@ const longFaceKeys = new Set([
|
||||
export type FaceField = { label: string; value: string; wide?: boolean }
|
||||
export type FaceGroup = { title: string; fields: FaceField[] }
|
||||
|
||||
export function certCategoryLabel(
|
||||
cert: Pick<QuotaCert, 'certType' | 'categoryName' | 'derivedCategoryNames'> & {
|
||||
certType?: CertType | null
|
||||
},
|
||||
kind?: CertType
|
||||
) {
|
||||
const certKind = kind || cert.certType
|
||||
if (certKind === 'transport') {
|
||||
const names = (cert.derivedCategoryNames || [])
|
||||
.map((item) => String(item || '').trim())
|
||||
.filter(Boolean)
|
||||
return names.join('、') || '—'
|
||||
}
|
||||
return String(cert.categoryName || '').trim() || '—'
|
||||
}
|
||||
|
||||
export function certFaceGroups(
|
||||
cert: QuotaCert,
|
||||
kind: CertType,
|
||||
@@ -67,11 +51,6 @@ export function certFaceGroups(
|
||||
label: '系统客户',
|
||||
value: String(cert.customerName || '').trim() || '—',
|
||||
wide: true
|
||||
},
|
||||
{
|
||||
label: '证用品类',
|
||||
value: certCategoryLabel(cert, kind),
|
||||
wide: true
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
@@ -361,7 +361,7 @@
|
||||
]
|
||||
const placeholder = computed(() =>
|
||||
tab.value === 'contract'
|
||||
? '客户名称 / 编号'
|
||||
? '合同编号 / 名称 / 销售或购买单位'
|
||||
: tab.value === 'plan' || tab.value === 'ready'
|
||||
? '计划编号 / 供方 / 需方'
|
||||
: '证件编号 / 品名 / 销售或购买单位'
|
||||
|
||||
@@ -183,28 +183,16 @@
|
||||
toQueryParams,
|
||||
watchVisibleColumns
|
||||
} = useServerColumnFilters(columns, { onChange: search })
|
||||
const { visibleColumns, checkAll, isIndeterminate, resetToDefault } = usePersistedListColumns(
|
||||
'pl-customer-quota-columns-v1',
|
||||
columns
|
||||
)
|
||||
// usePersistedListColumns 不返回 visibleDefs;须本地按可见列过滤,否则只剩展开列
|
||||
const visibleDefs = computed(() =>
|
||||
columns.filter((column) => visibleColumns.value.includes(column.prop))
|
||||
)
|
||||
const { visibleColumns, checkAll, isIndeterminate, visibleDefs, resetToDefault } =
|
||||
usePersistedListColumns('pl-customer-quota-columns-v1', columns)
|
||||
watchVisibleColumns(visibleColumns)
|
||||
const tableWrapRef = ref<HTMLElement | null>(null)
|
||||
const pagerRef = ref<HTMLElement | null>(null)
|
||||
const tableWrapRef = ref<HTMLElement>()
|
||||
const pagerRef = ref<HTMLElement>()
|
||||
const tableRef = ref()
|
||||
// 展开区只锁宽度,高度随证件明细撑开;表体高度须走 tableEl/pagerEl,否则卡在 240 下限裁切展开
|
||||
const { width: tableViewportWidth } = useElementSize(tableWrapRef)
|
||||
const expansionStyle = computed(() => ({
|
||||
width: tableViewportWidth.value > 0 ? `${tableViewportWidth.value}px` : undefined
|
||||
}))
|
||||
const { tableHeight, recalc: recalcTableHeight } = useListTableViewportHeight({
|
||||
tableEl: tableWrapRef,
|
||||
pagerEl: pagerRef,
|
||||
tableRef,
|
||||
enabled: computed(() => !props.embedded)
|
||||
const { tableHeight, expansionStyle } = useListTableViewportHeight({
|
||||
wrapRef: tableWrapRef,
|
||||
pagerRef,
|
||||
tableRef
|
||||
})
|
||||
|
||||
async function init() {
|
||||
@@ -270,7 +258,6 @@
|
||||
? expanded.some((item: any) => item?.id === row.id)
|
||||
: Boolean(expanded)
|
||||
if (open) void loadDetail(row)
|
||||
else nextTick(() => recalcTableHeight())
|
||||
}
|
||||
|
||||
async function loadDetail(row: { id: string }) {
|
||||
@@ -280,12 +267,6 @@
|
||||
details[row.id] = { loading: false, ready: true }
|
||||
} catch {
|
||||
details[row.id] = { loading: false, error: true }
|
||||
} finally {
|
||||
nextTick(() => {
|
||||
recalcTableHeight()
|
||||
const inst = tableRef.value
|
||||
if (inst && typeof inst.doLayout === 'function') inst.doLayout()
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -310,9 +291,6 @@
|
||||
}
|
||||
|
||||
.statistics-expansion {
|
||||
box-sizing: border-box;
|
||||
max-width: 100%;
|
||||
padding: 12px 16px 16px;
|
||||
text-align: left;
|
||||
padding: 8px 12px 16px;
|
||||
}
|
||||
</style>
|
||||
@@ -1656,7 +1656,7 @@ async function handleArchive(row: Plan) {
|
||||
ElMessage.warning('无运输计划归档操作权限')
|
||||
return
|
||||
}
|
||||
// 打开归档弹窗:已归档走调整;未归档/已暂存可直接打开(用证校验在「确认归档」时执行,以便支持暂存)
|
||||
// 打开归档弹窗:已归档走调整;未归档/已暂存可直接打开(证书齐备仅在「确认归档」时校验,以便支持暂存)
|
||||
archivePlanId.value = row.id
|
||||
archiveDialogVisible.value = true
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user