小程序检索沿用原有关键字,在编号和品名之外匹配证件主体以及计划供方、需方。 Co-authored-by: Cursor <cursoragent@cursor.com>
307 lines
12 KiB
Python
307 lines
12 KiB
Python
"""证书齐备:易制毒外部装送段可跳过购买证、运输证校验和扣减。"""
|
|
from datetime import date, datetime
|
|
|
|
from fastapi import HTTPException
|
|
from sqlalchemy import and_, func, or_
|
|
|
|
from app.models.pl_models import (
|
|
PlPlan,
|
|
PlPlanDelivery,
|
|
PlPlanDeliveryProduct,
|
|
PlPlanLoad,
|
|
PlPlanLoadProduct,
|
|
PlPlanProduct,
|
|
)
|
|
from app.models.pl_quota_models import PlPlanCertUsage
|
|
from app.services.pl_data_scope import apply_pl_scope
|
|
from app.services.pl_internal_customer import INTERNAL_CUSTOMER_NAMES, is_internal_customer_name
|
|
|
|
|
|
def quota_cert_waived(plan) -> bool:
|
|
return int(getattr(plan, "quota_cert_waived", 0) or 0) == 1
|
|
|
|
|
|
def needs_purchase_transport_cert(party_name, is_toxic) -> bool:
|
|
"""外部客户上的易制毒装送段才需要购买证和运输证。"""
|
|
return bool(is_toxic) and not is_internal_customer_name(party_name)
|
|
|
|
|
|
def _external_party(column):
|
|
trimmed = func.trim(column)
|
|
return or_(column.is_(None), trimmed == "", trimmed.notin_(sorted(INTERNAL_CUSTOMER_NAMES)))
|
|
|
|
|
|
def _toxic_exists(db, tenant_no):
|
|
def one(product_model, stop_model, stop_field):
|
|
return (
|
|
db.query(product_model.id)
|
|
.join(
|
|
stop_model,
|
|
and_(
|
|
stop_model.id == getattr(product_model, stop_field),
|
|
stop_model.tenant_no == tenant_no,
|
|
stop_model.del_flag == 0,
|
|
),
|
|
)
|
|
.join(
|
|
PlPlanProduct,
|
|
and_(
|
|
PlPlanProduct.id == product_model.plan_product_id,
|
|
PlPlanProduct.tenant_no == tenant_no,
|
|
PlPlanProduct.del_flag == 0,
|
|
PlPlanProduct.is_toxic == 1,
|
|
),
|
|
)
|
|
.filter(
|
|
product_model.plan_id == PlPlan.id,
|
|
product_model.tenant_no == tenant_no,
|
|
product_model.del_flag == 0,
|
|
_external_party(stop_model.customer_name),
|
|
)
|
|
.exists()
|
|
)
|
|
|
|
return or_(
|
|
one(PlPlanLoadProduct, PlPlanLoad, "load_id"),
|
|
one(PlPlanDeliveryProduct, PlPlanDelivery, "delivery_id"),
|
|
)
|
|
|
|
|
|
def assert_waived_sources(db, user, plan, *, lock=False):
|
|
"""齐备后仍要求装送数量、单位和合同完整,只跳过两证。"""
|
|
from app.services.pl_quota_planning import resolve_measurement_version
|
|
from app.services.pl_quota_sources import extract_sources
|
|
|
|
version = resolve_measurement_version(db, user, plan)
|
|
extract_sources(db, user, plan.id, None, lock=lock, measurement_version=version)
|
|
|
|
|
|
def _row(plan, product_names=""):
|
|
return {
|
|
"id": plan.id,
|
|
"planNo": plan.plan_no,
|
|
"planDate": plan.plan_date,
|
|
"licensePlate": plan.license_plate,
|
|
"supplierName": plan.supplier_name,
|
|
"customerName": plan.customer_name,
|
|
"productNames": product_names,
|
|
"followStatus": plan.follow_status,
|
|
"quotaCertWaived": quota_cert_waived(plan),
|
|
"quotaCertWaivedByName": plan.quota_cert_waived_by_name,
|
|
"quotaCertWaivedTime": plan.quota_cert_waived_time,
|
|
}
|
|
|
|
|
|
def _product_names(db, user, plan_ids):
|
|
names = {plan_id: [] for plan_id in plan_ids}
|
|
if not plan_ids:
|
|
return {}
|
|
|
|
def collect(product_model, stop_model, stop_field):
|
|
rows = (
|
|
db.query(product_model.plan_id, product_model.product_name)
|
|
.join(stop_model, and_(
|
|
stop_model.id == getattr(product_model, stop_field),
|
|
stop_model.tenant_no == user.tenant_no,
|
|
stop_model.del_flag == 0,
|
|
))
|
|
.join(PlPlanProduct, and_(
|
|
PlPlanProduct.id == product_model.plan_product_id,
|
|
PlPlanProduct.tenant_no == user.tenant_no,
|
|
PlPlanProduct.del_flag == 0,
|
|
PlPlanProduct.is_toxic == 1,
|
|
))
|
|
.filter(
|
|
product_model.tenant_no == user.tenant_no,
|
|
product_model.del_flag == 0,
|
|
product_model.plan_id.in_(plan_ids),
|
|
_external_party(stop_model.customer_name),
|
|
)
|
|
.all()
|
|
)
|
|
for plan_id, name in rows:
|
|
text = (name or "").strip()
|
|
if text and text not in names[plan_id]:
|
|
names[plan_id].append(text)
|
|
|
|
collect(PlPlanLoadProduct, PlPlanLoad, "load_id")
|
|
collect(PlPlanDeliveryProduct, PlPlanDelivery, "delivery_id")
|
|
return {plan_id: "、".join(values) for plan_id, values in names.items()}
|
|
|
|
|
|
FOLLOW_STATUSES = {'drafting', 'wait_notice', 'pending_arrange', 'arranged', 'completed', 'cancelled'}
|
|
|
|
|
|
def _text(value):
|
|
text = str(value or '').strip()
|
|
return text or None
|
|
|
|
|
|
def _choices(value, allowed):
|
|
if value in (None, ''):
|
|
return None
|
|
selected = [part.strip() for part in str(value).split(',') if part.strip()]
|
|
if not selected:
|
|
return None
|
|
if any(part not in allowed for part in selected):
|
|
raise HTTPException(400, '未知筛选值')
|
|
return selected
|
|
|
|
|
|
def _day(value, label):
|
|
if value in (None, ''):
|
|
return None
|
|
if isinstance(value, datetime):
|
|
return value.date()
|
|
if isinstance(value, date):
|
|
return value
|
|
try:
|
|
return date.fromisoformat(str(value)[:10])
|
|
except ValueError:
|
|
raise HTTPException(400, f'{label}格式无效') from None
|
|
|
|
|
|
def _between(start, end, label):
|
|
left, right = _day(start, label), _day(end, label)
|
|
if left and right and left > right:
|
|
raise HTTPException(400, f'{label}起始不能晚于结束')
|
|
return left, right
|
|
|
|
|
|
def _product_name_match(db, tenant_no, text):
|
|
def one(product_model, stop_model, stop_field):
|
|
return (
|
|
db.query(product_model.id)
|
|
.join(stop_model, and_(
|
|
stop_model.id == getattr(product_model, stop_field),
|
|
stop_model.tenant_no == tenant_no,
|
|
stop_model.del_flag == 0,
|
|
))
|
|
.join(PlPlanProduct, and_(
|
|
PlPlanProduct.id == product_model.plan_product_id,
|
|
PlPlanProduct.tenant_no == tenant_no,
|
|
PlPlanProduct.del_flag == 0,
|
|
PlPlanProduct.is_toxic == 1,
|
|
))
|
|
.filter(
|
|
product_model.plan_id == PlPlan.id,
|
|
product_model.tenant_no == tenant_no,
|
|
product_model.del_flag == 0,
|
|
product_model.product_name.contains(text, autoescape=True),
|
|
_external_party(stop_model.customer_name),
|
|
)
|
|
.exists()
|
|
)
|
|
|
|
return or_(
|
|
one(PlPlanLoadProduct, PlPlanLoad, 'load_id'),
|
|
one(PlPlanDeliveryProduct, PlPlanDelivery, 'delivery_id'),
|
|
)
|
|
|
|
|
|
def list_ready_plans(db, user, keyword="", waived=None, page=1, page_size=20, plan_no=None,
|
|
license_plate=None, supplier_name=None, customer_name=None, product_name=None,
|
|
plan_date_from=None, plan_date_to=None, follow_status_in=None, waived_in=None,
|
|
waived_by_name=None, waived_time_from=None, waived_time_to=None):
|
|
if waived not in (None, "", 0, 1, "0", "1"):
|
|
raise HTTPException(400, "未知齐备状态")
|
|
query = db.query(PlPlan).filter(
|
|
PlPlan.tenant_no == user.tenant_no,
|
|
PlPlan.del_flag == 0,
|
|
PlPlan.follow_status != "cancelled",
|
|
PlPlan.archive_status != "cancelled",
|
|
_toxic_exists(db, user.tenant_no),
|
|
)
|
|
query = apply_pl_scope(query, PlPlan, user, db, user.tenant_no)
|
|
if keyword:
|
|
query = query.filter(or_(
|
|
PlPlan.plan_no.contains(keyword, autoescape=True),
|
|
PlPlan.supplier_name.contains(keyword, autoescape=True),
|
|
PlPlan.customer_name.contains(keyword, autoescape=True),
|
|
))
|
|
for column, value in (
|
|
(PlPlan.plan_no, plan_no),
|
|
(PlPlan.license_plate, license_plate),
|
|
(PlPlan.supplier_name, supplier_name),
|
|
(PlPlan.customer_name, customer_name),
|
|
(PlPlan.quota_cert_waived_by_name, waived_by_name),
|
|
):
|
|
text = _text(value)
|
|
if text:
|
|
query = query.filter(column.contains(text, autoescape=True))
|
|
product = _text(product_name)
|
|
if product:
|
|
query = query.filter(_product_name_match(db, user.tenant_no, product))
|
|
start, end = _between(plan_date_from, plan_date_to, "计划日期")
|
|
if start:
|
|
query = query.filter(PlPlan.plan_date >= start)
|
|
if end:
|
|
query = query.filter(PlPlan.plan_date <= end)
|
|
ready_start, ready_end = _between(waived_time_from, waived_time_to, "确认时间")
|
|
if ready_start:
|
|
query = query.filter(func.date(PlPlan.quota_cert_waived_time) >= ready_start)
|
|
if ready_end:
|
|
query = query.filter(func.date(PlPlan.quota_cert_waived_time) <= ready_end)
|
|
statuses = _choices(follow_status_in, FOLLOW_STATUSES)
|
|
if statuses:
|
|
query = query.filter(PlPlan.follow_status.in_(statuses))
|
|
selected_waived = _choices(waived_in, {"0", "1"})
|
|
if selected_waived and len(set(selected_waived)) == 1:
|
|
query = query.filter(PlPlan.quota_cert_waived == int(selected_waived[0]))
|
|
elif waived not in (None, ""):
|
|
query = query.filter(PlPlan.quota_cert_waived == int(waived))
|
|
total = query.count()
|
|
rows = (
|
|
query.order_by(PlPlan.plan_date.is_(None), PlPlan.plan_date.asc(), PlPlan.id.asc())
|
|
.offset((page - 1) * page_size)
|
|
.limit(page_size)
|
|
.all()
|
|
)
|
|
labels = _product_names(db, user, [row.id for row in rows])
|
|
return {"total": total, "list": [_row(plan, labels.get(plan.id, "")) for plan in rows]}
|
|
|
|
|
|
def mark_ready(db, user, plan_id):
|
|
from app.services.pl_plan_service import record_plan_change
|
|
from app.services.pl_quota_business import apply_plan_quota
|
|
from app.services.pl_quota_planning import _plan
|
|
|
|
plan = _plan(db, user, plan_id, lock=True)
|
|
if plan.follow_status == "cancelled" or plan.archive_status == "cancelled":
|
|
raise HTTPException(409, "已作废的计划不能标记证书齐备")
|
|
if quota_cert_waived(plan):
|
|
labels = _product_names(db, user, [plan.id])
|
|
return _row(plan, labels.get(plan.id, ""))
|
|
if not db.query(PlPlan.id).filter(PlPlan.id == plan.id, _toxic_exists(db, user.tenant_no)).first():
|
|
raise HTTPException(409, "这条计划没有需要购买证和运输证的易制毒装送段")
|
|
usages = (
|
|
db.query(PlPlanCertUsage)
|
|
.filter_by(tenant_no=user.tenant_no, plan_id=plan.id, del_flag=0)
|
|
.all()
|
|
)
|
|
# 过磅、回传后仍可在归档时齐备。只有额度已经结转才不能再跳过。
|
|
# 结转失败留下的 exception 没有入账,不挡住证书齐备。
|
|
if any(row.usage_status in ("settled", "in_transit") for row in usages):
|
|
raise HTTPException(409, "证件额度已经入账,不能再标记证书齐备")
|
|
if any(row.usage_status == "reserved" for row in usages):
|
|
apply_plan_quota(db, user, plan, "release")
|
|
name = ((getattr(user, "name", None) or "").strip() or None)
|
|
plan.quota_cert_waived = 1
|
|
plan.quota_cert_waived_by = user.id
|
|
plan.quota_cert_waived_by_name = name[:100] if name else None
|
|
plan.quota_cert_waived_time = datetime.now()
|
|
plan.update_by = user.id
|
|
record_plan_change(
|
|
db,
|
|
tenant_no=user.tenant_no,
|
|
plan_id=plan.id,
|
|
change_type="quota_cert_waived",
|
|
change_content="标记证书齐备:安排和归档不再校验、不扣购买证与运输证额度",
|
|
user_id=user.id,
|
|
user_name=plan.quota_cert_waived_by_name,
|
|
dept_id=user.dept_id or "",
|
|
)
|
|
db.flush()
|
|
labels = _product_names(db, user, [plan.id])
|
|
return _row(plan, labels.get(plan.id, ""))
|