避免已安排计划再次保存时,把本单预占的一次有效购买证误判为已使用。 Co-authored-by: Cursor <cursoragent@cursor.com>
657 lines
24 KiB
Python
657 lines
24 KiB
Python
"""新规则:按段次客户+品类整笔选证(不拆购买证)。"""
|
||
from datetime import date
|
||
from decimal import Decimal
|
||
|
||
from fastapi import HTTPException
|
||
|
||
from app.models.pl_quota_models import (
|
||
PlPurchaseCert,
|
||
PlTransportCert,
|
||
PlTransportCertPurchaseRef,
|
||
PlCertQtyLog,
|
||
PlPlanCertUsage,
|
||
)
|
||
from app.schemas.pl.quota_planning import ManualQuantity
|
||
from app.services.pl_cert_category_service import category_ids_for_product
|
||
from app.services.pl_quota_cert_service import is_single_use_consumed
|
||
from app.services.pl_quota_units import same_quantity_unit, standard_conversion_ratio
|
||
|
||
|
||
def _plan_own_reserved(db, user, plan_id, cert_type, cert_id) -> Decimal:
|
||
"""本计划对该证的预占量;再安排时加回余量,避免把本单占用当成他人占用。"""
|
||
if not plan_id:
|
||
return Decimal('0')
|
||
row = (
|
||
db.query(PlPlanCertUsage)
|
||
.filter_by(
|
||
tenant_no=user.tenant_no,
|
||
plan_id=plan_id,
|
||
cert_type=cert_type,
|
||
cert_id=cert_id,
|
||
del_flag=0,
|
||
)
|
||
.first()
|
||
)
|
||
if row is None:
|
||
return Decimal('0')
|
||
return Decimal(row.reserved_qty or 0)
|
||
|
||
|
||
def _available(cert, *, own_reserved=None):
|
||
own = Decimal(own_reserved if own_reserved is not None else 0)
|
||
return Decimal(cert.total_qty) - Decimal(cert.used_qty) - Decimal(cert.reserved_qty) + own
|
||
|
||
|
||
def _in_force(cert, on_date: date) -> bool:
|
||
if cert.valid_from and on_date < cert.valid_from:
|
||
return False
|
||
if cert.valid_to and on_date > cert.valid_to:
|
||
return False
|
||
return True
|
||
|
||
|
||
def _has_opening(db, user, cert_type, cert_id) -> bool:
|
||
return (
|
||
db.query(PlCertQtyLog.id)
|
||
.filter_by(
|
||
tenant_no=user.tenant_no,
|
||
cert_type=cert_type,
|
||
cert_id=cert_id,
|
||
event_type='opening',
|
||
del_flag=0,
|
||
)
|
||
.first()
|
||
is not None
|
||
)
|
||
|
||
|
||
def _ensure_opening_quiet(db, user, cert_type, cert_id, row):
|
||
"""选证前尽量自动补期初;单元测试 mock 库失败时静默跳过。"""
|
||
try:
|
||
from app.services.pl_quota_cert_service import ensure_zero_opening
|
||
|
||
ensure_zero_opening(db, user, cert_type, cert_id, row=row)
|
||
except Exception:
|
||
return
|
||
|
||
|
||
def _vehicle_ok(cert, vehicle_no: str) -> bool:
|
||
plates = cert.vehicle_numbers_json or []
|
||
if not isinstance(plates, list):
|
||
return False
|
||
plate = (vehicle_no or '').strip()
|
||
if not plate:
|
||
return False
|
||
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
|
||
ratio = standard_conversion_ratio(source_unit, cert_unit)
|
||
if ratio is None:
|
||
raise HTTPException(409, f'来源单位「{source_unit}」与证件单位「{cert_unit}」无法自动换算,请调整单位或证件')
|
||
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')
|
||
if cid:
|
||
return str(cid)
|
||
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=(),
|
||
plan_id=None,
|
||
):
|
||
"""选证失败时按证据优先给出单一可执行原因,避免笼统兜底句。"""
|
||
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, exclude_plan_id=plan_id):
|
||
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
|
||
buy_own = _plan_own_reserved(db, user, plan_id, 'purchase', purchase.id)
|
||
if _available(purchase, own_reserved=buy_own) < need:
|
||
short_buy.append((purchase, need))
|
||
continue
|
||
|
||
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, exclude_plan_id=plan_id):
|
||
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
|
||
move_own = _plan_own_reserved(db, user, plan_id, 'transport', transport.id)
|
||
if _available(transport, own_reserved=move_own) < t_need:
|
||
short_move.append((transport, t_need))
|
||
continue
|
||
purchase_had_ready_transport = True
|
||
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=(),
|
||
plan_id=None,
|
||
):
|
||
"""返回 purchase_cert_ids, transport_cert_ids, manual_allocations。
|
||
|
||
每个来源必须由一张购买证整笔覆盖;异地再配一张关联且车号/余量够的运输证。
|
||
单位无法自动换算时,使用计划段次用证已保存的人工换算量。
|
||
plan_id:再安排时排除本计划已占用的一次有效证,并把本单预占加回可选余量。
|
||
"""
|
||
if not sources:
|
||
return [], [], []
|
||
|
||
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)
|
||
|
||
chosen_purchase = None
|
||
chosen_transport = None
|
||
purchase_permit_qty = None
|
||
transport_permit_qty = None
|
||
|
||
for purchase in candidates:
|
||
if not purchase.verified_by or not purchase.verified_time:
|
||
continue
|
||
_ensure_opening_quiet(db, user, 'purchase', purchase.id, purchase)
|
||
if not _has_opening(db, user, 'purchase', purchase.id):
|
||
continue
|
||
if not _in_force(purchase, on_date):
|
||
continue
|
||
if is_single_use_consumed(db, user, 'purchase', purchase, exclude_plan_id=plan_id):
|
||
continue
|
||
try:
|
||
need = _need_permit_qty(
|
||
source.quantity, source.unit, purchase.quantity_unit,
|
||
saved_manuals, 'purchase', source.source_id, purchase.id,
|
||
)
|
||
except HTTPException:
|
||
continue
|
||
buy_own = _plan_own_reserved(db, user, plan_id, 'purchase', purchase.id)
|
||
if _available(purchase, own_reserved=buy_own) < need:
|
||
continue
|
||
|
||
if not source.requires_transport:
|
||
chosen_purchase = purchase
|
||
purchase_permit_qty = need
|
||
break
|
||
|
||
transports = _linked_transports(db, user, customer_id, purchase.id)
|
||
if not transports:
|
||
continue
|
||
for transport in transports:
|
||
if not transport.verified_by or not transport.verified_time:
|
||
continue
|
||
_ensure_opening_quiet(db, user, 'transport', transport.id, transport)
|
||
if not _has_opening(db, user, 'transport', transport.id):
|
||
continue
|
||
if not _in_force(transport, on_date):
|
||
continue
|
||
if is_single_use_consumed(db, user, 'transport', transport, exclude_plan_id=plan_id):
|
||
continue
|
||
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,
|
||
)
|
||
except HTTPException:
|
||
continue
|
||
move_own = _plan_own_reserved(db, user, plan_id, 'transport', transport.id)
|
||
if _available(transport, own_reserved=move_own) < t_need:
|
||
continue
|
||
chosen_purchase = purchase
|
||
chosen_transport = transport
|
||
purchase_permit_qty = need
|
||
transport_permit_qty = t_need
|
||
break
|
||
if chosen_purchase and chosen_transport:
|
||
break
|
||
|
||
if chosen_purchase is None:
|
||
raise HTTPException(
|
||
409,
|
||
_diagnose_select_failure(
|
||
db, user, source, vehicle_no=vehicle_no, on_date=on_date,
|
||
candidates=candidates, manual_allocations=saved_manuals,
|
||
plan_id=plan_id,
|
||
),
|
||
)
|
||
|
||
purchase_ids.append(chosen_purchase.id)
|
||
manuals.append(
|
||
ManualQuantity(
|
||
permit_kind='purchase',
|
||
source_id=source.source_id,
|
||
permit_id=chosen_purchase.id,
|
||
source_quantity=Decimal(source.quantity),
|
||
permit_quantity=purchase_permit_qty,
|
||
)
|
||
)
|
||
if chosen_transport is not None:
|
||
transport_ids.append(chosen_transport.id)
|
||
manuals.append(
|
||
ManualQuantity(
|
||
permit_kind='transport',
|
||
source_id=source.source_id,
|
||
permit_id=chosen_transport.id,
|
||
source_quantity=Decimal(source.quantity),
|
||
permit_quantity=transport_permit_qty,
|
||
)
|
||
)
|
||
|
||
def unique(values):
|
||
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)
|