Compare commits

..
Author SHA1 Message Date
wuzilongandCursor bf47a26ba0 fix(pl): 计划详情用关联证件附件替换危化品证书区。
Web 与 H5 详情将关联购买证/运输证移到装送货后并以附件卡片展示;用证接口回填证件附件 URL。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-15 14:46:31 +08:00
76 changed files with 617 additions and 4767 deletions

No files matched your search

+7 -4
View File
@@ -2206,7 +2206,8 @@ def create_plan(
create_by=user.id, create_by=user.id,
create_dept_id=user.dept_id, create_dept_id=user.dept_id,
) )
# 证件额度规则版本在首次安排时按生效时间打标,创建不打标。 from app.services.pl_cert_quota_rule_config_service import stamp_plan_rule_version
stamp_plan_rule_version(db, user, plan)
db.add(plan) db.add(plan)
# 添加产品明细 # 添加产品明细
@@ -2378,7 +2379,8 @@ def create_plan_full(
create_by=user.id, create_by=user.id,
create_dept_id=user.dept_id, create_dept_id=user.dept_id,
) )
# 证件额度规则版本在首次安排时按生效时间打标,创建不打标。 from app.services.pl_cert_quota_rule_config_service import stamp_plan_rule_version
stamp_plan_rule_version(db, user, plan)
db.add(plan) db.add(plan)
db.flush() db.flush()
@@ -2529,7 +2531,8 @@ def create_from_contract(
create_by=user.id, create_by=user.id,
create_dept_id=user.dept_id, create_dept_id=user.dept_id,
) )
# 证件额度规则版本在首次安排时按生效时间打标,创建不打标。 from app.services.pl_cert_quota_rule_config_service import stamp_plan_rule_version
stamp_plan_rule_version(db, user, plan)
db.add(plan) db.add(plan)
# 查询合同产品明细 # 查询合同产品明细
@@ -3804,7 +3807,7 @@ def archive_plan(
db.flush() db.flush()
result = get_plan(id, db, user) result = get_plan(id, db, user)
if not quota_settled: if not quota_settled:
result.quota_settlement_error = read_quota_settlement_error(db, tenant_no, plan.id, plan=plan) result.quota_settlement_error = read_quota_settlement_error(db, tenant_no, plan.id)
return result return result
+1 -25
View File
@@ -320,23 +320,6 @@ def contract_statistics_list(keyword: str = Query('', max_length=200),
cert_count=cert_count, cert_count_min=cert_count_min, cert_count_max=cert_count_max)) cert_count=cert_count, cert_count_min=cert_count_min, cert_count_max=cert_count_max))
@router.get('/statistics/customers')
def customer_statistics_list(keyword: str = Query('', max_length=200),
customer_no: str = Query('', alias='customerNo', max_length=200),
customer_name: str = Query('', alias='customerName', max_length=200),
cert_count_op: str = Query('', alias='certCountOp', max_length=20),
cert_count: str = Query('', alias='certCount', max_length=40),
cert_count_min: str = Query('', alias='certCountMin', max_length=40),
cert_count_max: str = Query('', alias='certCountMax', max_length=40),
page: int = Query(1, ge=1),
page_size: int = Query(20, alias='pageSize', ge=1, le=100),
db: Session = Depends(get_db), user: DbUserContext = Depends(current_user)):
return _wire(statistics.list_customers(
db, user, keyword=keyword, page=page, page_size=page_size, customer_no=customer_no,
customer_name=customer_name, cert_count_op=cert_count_op, cert_count=cert_count,
cert_count_min=cert_count_min, cert_count_max=cert_count_max))
@router.get('/statistics/certificates') @router.get('/statistics/certificates')
def certificate_statistics_list(keyword: str = Query('', max_length=200), def certificate_statistics_list(keyword: str = Query('', max_length=200),
cert_no: str = Query('', alias='certNo', max_length=200), cert_no: str = Query('', alias='certNo', max_length=200),
@@ -395,12 +378,6 @@ def contract_statistics(contract_id: str, db: Session = Depends(get_db),
return _wire(statistics.contract_statistics(db, user, contract_id)) return _wire(statistics.contract_statistics(db, user, contract_id))
@router.get('/customers/{customer_id}/statistics')
def customer_statistics(customer_id: str, db: Session = Depends(get_db),
user: DbUserContext = Depends(current_user)):
return _wire(statistics.customer_statistics(db, user, customer_id))
@router.get('/{cert_type}/{cert_id}/statistics') @router.get('/{cert_type}/{cert_id}/statistics')
def certificate_statistics(cert_type: CertType, cert_id: str, db: Session = Depends(get_db), def certificate_statistics(cert_type: CertType, cert_id: str, db: Session = Depends(get_db),
user: DbUserContext = Depends(current_user)): user: DbUserContext = Depends(current_user)):
@@ -409,9 +386,8 @@ def certificate_statistics(cert_type: CertType, cert_id: str, db: Session = Depe
@router.get('/{cert_type}') @router.get('/{cert_type}')
def list_certs(cert_type: CertType, keyword: Optional[str] = None, status: Optional[str] = None, def list_certs(cert_type: CertType, keyword: Optional[str] = None, status: Optional[str] = None,
customer_id: Optional[str] = Query(None, alias='customerId', max_length=64),
db: Session = Depends(get_db), user: DbUserContext = Depends(current_user)): db: Session = Depends(get_db), user: DbUserContext = Depends(current_user)):
return _wire(certs.list_certs(db, user, cert_type, keyword, status, customer_id=customer_id)) return _wire(certs.list_certs(db, user, cert_type, keyword, status))
@router.post('/{cert_type}/recognize', dependencies=[Depends(require_menu_code('pl:quota-cert:edit'))]) @router.post('/{cert_type}/recognize', dependencies=[Depends(require_menu_code('pl:quota-cert:edit'))])
-5
View File
@@ -888,10 +888,7 @@ def arrange_transport(
) )
apply_resource_snapshot_json(plan=plan, transport=transport, snapshot=snapshot) apply_resource_snapshot_json(plan=plan, transport=transport, snapshot=snapshot)
from app.services.pl_quota_planning import pin_measurement_version from app.services.pl_quota_planning import pin_measurement_version
from app.services.pl_cert_quota_rule_config_service import stamp_plan_rule_on_arrange
pin_measurement_version(db, user, plan) pin_measurement_version(db, user, plan)
# 首次安排按生效时间打标并冻结;改派不重打。
stamp_plan_rule_on_arrange(db, user, plan)
plan.transport_status = "arranged" plan.transport_status = "arranged"
plan.follow_status = "arranged" plan.follow_status = "arranged"
plan.freight_amount = freight_amount or 0 plan.freight_amount = freight_amount or 0
@@ -1307,13 +1304,11 @@ def process_approval(
transport.carrier_name = vehicle_info['carrier_name'] transport.carrier_name = vehicle_info['carrier_name']
snapshot = build_transport_resource_snapshot(db, tenant_no, transport.vehicle_id, snapshot = build_transport_resource_snapshot(db, tenant_no, transport.vehicle_id,
selected_driver_id=transport.driver_id, selected_escort_id=transport.escort_id) selected_driver_id=transport.driver_id, selected_escort_id=transport.escort_id)
from app.services.pl_cert_quota_rule_config_service import stamp_plan_rule_on_arrange
for plan in plans: for plan in plans:
assert_pl_row_in_scope(db, plan, PlPlan, user, tenant_no) assert_pl_row_in_scope(db, plan, PlPlan, user, tenant_no)
plan.vehicle_id = transport.vehicle_id plan.vehicle_id = transport.vehicle_id
plan.license_plate = transport.license_plate plan.license_plate = transport.license_plate
apply_resource_snapshot_json(plan=plan, transport=transport, snapshot=snapshot) apply_resource_snapshot_json(plan=plan, transport=transport, snapshot=snapshot)
stamp_plan_rule_on_arrange(db, user, plan)
apply_plan_quota(db, user, plan, "reserve", payload) apply_plan_quota(db, user, plan, "reserve", payload)
plan.transport_status = "arranged" plan.transport_status = "arranged"
plan.follow_status = "arranged" plan.follow_status = "arranged"
+1 -2
View File
@@ -370,8 +370,7 @@ class PlPlan(Base):
quota_cert_waived_by = Column(String(64), nullable=True, comment="证书齐备确认人ID") quota_cert_waived_by = Column(String(64), nullable=True, comment="证书齐备确认人ID")
quota_cert_waived_by_name = Column(String(100), nullable=True, comment="证书齐备确认人姓名") quota_cert_waived_by_name = Column(String(100), nullable=True, comment="证书齐备确认人姓名")
quota_cert_waived_time = Column(DateTime, nullable=True, comment="证书齐备确认时间") quota_cert_waived_time = Column(DateTime, nullable=True, comment="证书齐备确认时间")
cert_quota_rule_version = Column(String(32), nullable=True, comment="证件额度规则版本 legacy|customer_category;首次安排时打标并冻结") cert_quota_rule_version = Column(String(32), nullable=True, comment="证件额度规则版本 legacy|customer_category;创建时打标")
cert_quota_arranged_at = Column(DateTime, nullable=True, comment="首次安排时间(证件额度切点用);再次安排不改")
quota_cert_pending_fulfill = Column(SmallInteger, nullable=False, default=0, comment="新规则证书齐备待完善 0-否 1-是") quota_cert_pending_fulfill = Column(SmallInteger, nullable=False, default=0, comment="新规则证书齐备待完善 0-否 1-是")
erp_entered = Column(SmallInteger, nullable=False, default=0, comment="是否已录入ERP 0-否 1-是") erp_entered = Column(SmallInteger, nullable=False, default=0, comment="是否已录入ERP 0-否 1-是")
cancel_reason = Column(String(500), nullable=True, comment="作废原因") cancel_reason = Column(String(500), nullable=True, comment="作废原因")
+1 -2
View File
@@ -417,8 +417,7 @@ class PlanRead(PlanBase, PlanResourceSnapshotMixin):
quota_cert_waived_by: Optional[str] = Field(default=None, alias="quotaCertWaivedBy", description="证书齐备确认人ID") quota_cert_waived_by: Optional[str] = Field(default=None, alias="quotaCertWaivedBy", description="证书齐备确认人ID")
quota_cert_waived_by_name: Optional[str] = Field(default=None, alias="quotaCertWaivedByName", description="证书齐备确认人姓名") quota_cert_waived_by_name: Optional[str] = Field(default=None, alias="quotaCertWaivedByName", description="证书齐备确认人姓名")
quota_cert_waived_time: Optional[datetime] = Field(default=None, alias="quotaCertWaivedTime", description="证书齐备确认时间") quota_cert_waived_time: Optional[datetime] = Field(default=None, alias="quotaCertWaivedTime", description="证书齐备确认时间")
cert_quota_rule_version: Optional[str] = Field(default=None, alias="certQuotaRuleVersion", description="legacy|customer_category;首次安排打标") cert_quota_rule_version: Optional[str] = Field(default=None, alias="certQuotaRuleVersion", description="legacy|customer_category")
cert_quota_arranged_at: Optional[datetime] = Field(default=None, alias="certQuotaArrangedAt", description="首次安排时间(证件额度切点)")
quota_cert_pending_fulfill: int = Field(default=0, alias="quotaCertPendingFulfill", description="新规则齐备待完善 0否 1是") quota_cert_pending_fulfill: int = Field(default=0, alias="quotaCertPendingFulfill", description="新规则齐备待完善 0否 1是")
erp_entered: int = Field(default=0, alias="erpEntered", description="是否已录入ERP 0-否 1-是") erp_entered: int = Field(default=0, alias="erpEntered", description="是否已录入ERP 0-否 1-是")
cancel_reason: Optional[str] = Field(default=None, alias="cancelReason", description="作废原因") cancel_reason: Optional[str] = Field(default=None, alias="cancelReason", description="作废原因")
@@ -127,16 +127,12 @@ def save_category(db: Session, user, data: dict, category_id=None):
submitted = data['products'] submitted = data['products']
if submitted is None: if submitted is None:
raise HTTPException(400, '产品关联集合不可为 null;清空请提交 []') raise HTTPException(400, '产品关联集合不可为 null;清空请提交 []')
# uk_cert_category_product 不含 del_flag,软删行仍占唯一键;无 id 再加须复用。 existing = {
all_links = ( r.id: r
db.query(PlCertCategoryProduct) for r in db.query(PlCertCategoryProduct).filter_by(
.filter_by(tenant_no=user.tenant_no, category_id=row.id) tenant_no=user.tenant_no, category_id=row.id, del_flag=0,
.with_for_update() ).with_for_update().populate_existing().all()
.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}
seen = set() seen = set()
product_ids = set() product_ids = set()
for item in submitted: for item in submitted:
@@ -154,46 +150,20 @@ def save_category(db: Session, user, data: dict, category_id=None):
raise HTTPException(400, '产品关联明细不属于当前品类') raise HTTPException(400, '产品关联明细不属于当前品类')
if rid in seen: if rid in seen:
raise HTTPException(400, '产品关联明细 ID 重复') 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) seen.add(rid)
link.product_id = pid
link.scope_status = scope link.scope_status = scope
link.update_by = user.id link.update_by = user.id
else: else:
# 关联表业务键 (category_id, product_id):复用有效或软删行,避免 uk 冲突 link = PlCertCategoryProduct(
link = by_product.get(pid) **_audit(user),
if link is not None: category_id=row.id,
if link.del_flag == 0: product_id=pid,
seen.add(link.id) scope_status=scope,
link.del_flag = 0 )
link.scope_status = scope db.add(link)
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
for rid, link in existing.items(): 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.del_flag = 1
link.update_by = user.id link.update_by = user.id
db.flush() db.flush()
@@ -1,4 +1,4 @@
"""客户品类额度规则切点:按首次安排时间打标;切点前已安排归档跳过校证。""" """客户品类额度规则切点:系统信息配置;未配置则拦住安排。"""
from datetime import datetime from datetime import datetime
from typing import Optional from typing import Optional
from uuid import uuid4 from uuid import uuid4
@@ -58,103 +58,20 @@ def assert_cert_quota_rule_configured(db: Session, tenant_no: str) -> datetime:
return effective_at return effective_at
def resolve_rule_version_for_arrange( def resolve_rule_version_for_create(db: Session, tenant_no: str, create_time: Optional[datetime] = None) -> str:
db: Session, tenant_no: str, arrange_time: Optional[datetime] = None """计划创建时打标;未配置生效时间时仍标 legacy(安排会被拦住)。"""
) -> str:
"""首次安排时打标:安排时刻 >= 生效时间 → 新规则,否则祖父 legacy。"""
effective_at = get_effective_at(db, tenant_no) effective_at = get_effective_at(db, tenant_no)
when = arrange_time or datetime.now() when = create_time or datetime.now()
if effective_at is not None and when >= effective_at: if effective_at is not None and when >= effective_at:
return VERSION_CUSTOMER_CATEGORY return VERSION_CUSTOMER_CATEGORY
return VERSION_LEGACY return VERSION_LEGACY
# 兼容旧测试/调用名;语义已改为安排时刻。 def stamp_plan_rule_version(db: Session, user, plan) -> str:
resolve_rule_version_for_create = resolve_rule_version_for_arrange version = resolve_rule_version_for_create(db, user.tenant_no, getattr(plan, 'create_time', None) or datetime.now())
def stamp_plan_rule_on_arrange(
db: Session, user, plan, *, arrange_time: Optional[datetime] = None
) -> str:
"""首次安排写入版本与安排时刻;再次安排冻结,不改版本。"""
if getattr(plan, 'cert_quota_arranged_at', None) is not None:
return getattr(plan, 'cert_quota_rule_version', None) or VERSION_LEGACY
when = arrange_time or datetime.now()
version = resolve_rule_version_for_arrange(db, user.tenant_no, when)
plan.cert_quota_arranged_at = when
plan.cert_quota_rule_version = version plan.cert_quota_rule_version = version
# 安排前已按旧判定齐备时,打成新规则后回补待完善,避免待完善列表漏单。
if (
version == VERSION_CUSTOMER_CATEGORY
and int(getattr(plan, 'quota_cert_waived', 0) or 0) == 1
and int(getattr(plan, 'quota_cert_pending_fulfill', 0) or 0) != 1
):
plan.quota_cert_pending_fulfill = 1
return version return version
def stamp_plan_rule_version(db: Session, user, plan) -> str:
"""兼容旧名:等价于首次安排打标(创建路径不应再调用)。"""
return stamp_plan_rule_on_arrange(db, user, plan)
def plan_uses_customer_category(plan) -> bool: def plan_uses_customer_category(plan) -> bool:
"""仅看已落库版本;空版本视为 legacy。安排前请用 plan_applies_customer_category_rule。"""
return (getattr(plan, 'cert_quota_rule_version', None) or VERSION_LEGACY) == VERSION_CUSTOMER_CATEGORY return (getattr(plan, 'cert_quota_rule_version', None) or VERSION_LEGACY) == VERSION_CUSTOMER_CATEGORY
def plan_applies_customer_category_rule(db: Session, tenant_no: str, plan) -> bool:
"""业务是否按新规则:已打 customer_category,或尚未安排且按当前时刻将落入新规则。
安排前 `cert_quota_rule_version` 常为空;不能把空当成 legacy,否则会误走合同绑证、
漏写齐备待完善。已首次安排并打成 legacy 的计划保持旧规则。
"""
if plan_uses_customer_category(plan):
return True
if getattr(plan, 'cert_quota_arranged_at', None) is not None:
return False
return resolve_rule_version_for_arrange(db, tenant_no) == VERSION_CUSTOMER_CATEGORY
def plan_requires_cert_fulfill(db: Session, tenant_no: str, plan) -> bool:
"""齐备后是否须进待完善;与安排是否走新规则同一判定。"""
return plan_applies_customer_category_rule(db, tenant_no, plan)
def infer_arranged_at(db: Session, plan) -> Optional[datetime]:
"""历史缺字段时用关联运输单创建时间推断首次安排。"""
stamped = getattr(plan, 'cert_quota_arranged_at', None)
if stamped is not None:
return stamped
transport_id = getattr(plan, 'transport_id', None)
tenant_no = getattr(plan, 'tenant_no', None)
if not transport_id or not tenant_no or db is None:
return None
from app.models.pl_models import PlTransport
transport = (
db.query(PlTransport)
.filter_by(id=transport_id, tenant_no=tenant_no, del_flag=0)
.first()
)
return getattr(transport, 'create_time', None) if transport else None
def plan_skips_archive_cert_quota(plan, db: Session = None, tenant_no: str = None) -> bool:
"""首次安排早于生效时间则归档跳过校证。
优先比较安排时刻与生效时间;若无生效配置或无法得到安排时刻,则不因空版本自动跳过
(避免误伤仍走合同绑证结转的历史路径;迁移/安排打标会补齐 arranged_at)。
"""
tn = tenant_no or getattr(plan, 'tenant_no', None)
arranged_at = getattr(plan, 'cert_quota_arranged_at', None)
if arranged_at is None and db is not None:
arranged_at = infer_arranged_at(db, plan)
if arranged_at is None:
return False
if db is not None and tn:
effective_at = get_effective_at(db, tn)
if effective_at is not None:
return arranged_at < effective_at
# 已记录首次安排且版本为 legacy(安排时未达生效点)→ 跳过
return not plan_uses_customer_category(plan)
-2
View File
@@ -1166,9 +1166,7 @@ def create_transport_for_plan(
escort_id=escort_id, escort_id=escort_id,
) )
from app.services.pl_quota_planning import pin_measurement_version from app.services.pl_quota_planning import pin_measurement_version
from app.services.pl_cert_quota_rule_config_service import stamp_plan_rule_on_arrange
pin_measurement_version(db, user, plan) pin_measurement_version(db, user, plan)
stamp_plan_rule_on_arrange(db, user, plan)
plan.transport_status = "arranged" plan.transport_status = "arranged"
plan.follow_status = "arranged" plan.follow_status = "arranged"
plan.freight_amount = freight_amount or 0 plan.freight_amount = freight_amount or 0
@@ -337,11 +337,7 @@ def settle_allocations(reserved: Sequence[Allocation], actual_by_source: Mapping
异单位来源须逐行重新确认全部实际量(含零量行),不按预占比例推算。 异单位来源须逐行重新确认全部实际量(含零量行),不按预占比例推算。
超来源量或超任一证件预占量均要求先补充分配。 超来源量或超任一证件预占量均要求先补充分配。
同市等仅购买证场景下,调用方仍可能对本函数传入空的运输证分组与全量实运量;
无预占行时直接空结转,不把「缺实际量」套到另一类证件上。
""" """
if not reserved:
return ()
keys, seqs, grouped = set(), set(), {} keys, seqs, grouped = set(), set(), {}
kinds = {r.permit_kind for r in reserved} kinds = {r.permit_kind for r in reserved}
if len(kinds) > 1 or kinds - {'purchase', 'transport'}: if len(kinds) > 1 or kinds - {'purchase', 'transport'}:
+4 -27
View File
@@ -120,21 +120,12 @@ def apply_plan_quota(db, user, plan, action, payload=None):
evidenceUrls=getattr(payload, 'quota_evidence_urls', None), evidenceUrls=getattr(payload, 'quota_evidence_urls', None),
sourceNote=getattr(payload, 'quota_source_note', None)) sourceNote=getattr(payload, 'quota_source_note', None))
from app.services.pl_quota_waiver import assert_waived_sources, quota_cert_waived from app.services.pl_quota_waiver import assert_waived_sources, quota_cert_waived
from app.services.pl_cert_quota_rule_config_service import ( from app.services.pl_cert_quota_rule_config_service import plan_uses_customer_category
plan_skips_archive_cert_quota,
plan_uses_customer_category,
)
# 新规则:齐备仅放行安排/改派预占;归档与实际调整必须真证结转。 # 新规则:齐备仅放行安排/改派预占;归档与实际调整必须真证结转。
# 切点前首次安排:归档/实调不校证件(无需齐备);齐备仍可跳过安排预占。 # 旧规则(legacy):齐备仍跳过安排与归档(祖父兼容)。
skip_actions = ('reserve', 'resize') skip_actions = ('reserve', 'resize')
if not plan_uses_customer_category(plan): if not plan_uses_customer_category(plan):
skip_actions = ('reserve', 'resize', 'settle', 'actual_adjust') skip_actions = ('reserve', 'resize', 'settle', 'actual_adjust')
grandfather_archive_skip = (
action in ('settle', 'actual_adjust')
and plan_skips_archive_cert_quota(plan, db, getattr(user, 'tenant_no', None))
)
if grandfather_archive_skip:
return {'operationId': ledger_id, 'usageIds': [], 'waived': True, 'skippedCertQuota': True}
if quota_cert_waived(plan) and action in skip_actions: if quota_cert_waived(plan) and action in skip_actions:
if action in ('reserve', 'resize'): if action in ('reserve', 'resize'):
assert_waived_sources(db, user, plan, lock=True) assert_waived_sources(db, user, plan, lock=True)
@@ -180,40 +171,26 @@ def settle_plan_quota(db, user, plan, payload, *, adjustment=False):
except ArchiveQuotaBlocked as exc: except ArchiveQuotaBlocked as exc:
raise HTTPException(409, str(exc)) from exc raise HTTPException(409, str(exc)) from exc
except (HTTPException, ValueError, AllocationIncomplete) as exc: except (HTTPException, ValueError, AllocationIncomplete) as exc:
message = str(getattr(exc, 'detail', exc))
# 无用量行(如证书齐备仅放行安排)时仍保留原因,供同请求读回。
setattr(plan, '_quota_settlement_error', message)
rows = db.query(PlPlanCertUsage).filter_by(tenant_no=user.tenant_no, plan_id=plan.id, del_flag=0).all() rows = db.query(PlPlanCertUsage).filter_by(tenant_no=user.tenant_no, plan_id=plan.id, del_flag=0).all()
for row in rows: for row in rows:
if not adjustment: if not adjustment:
row.usage_status = 'exception' row.usage_status = 'exception'
row.confirmation_snapshot = {**(row.confirmation_snapshot or {}), 'executed': True, row.confirmation_snapshot = {**(row.confirmation_snapshot or {}), 'executed': True,
'settlementError': message} 'settlementError': str(getattr(exc, 'detail', exc))}
row.update_by = user.id row.update_by = user.id
if not adjustment: if not adjustment:
plan.archive_status = 'exception' plan.archive_status = 'exception'
return False return False
def read_quota_settlement_error(db, tenant_no, plan_id, plan=None): def read_quota_settlement_error(db, tenant_no, plan_id):
"""结转失败时返回已经写在用量快照上的原因。""" """结转失败时返回已经写在用量快照上的原因。"""
from app.models.pl_models import PlPlan
from app.models.pl_quota_models import PlPlanCertUsage from app.models.pl_quota_models import PlPlanCertUsage
if plan is not None:
cached = getattr(plan, '_quota_settlement_error', None)
if isinstance(cached, str) and cached.strip():
return cached.strip()
rows = db.query(PlPlanCertUsage).filter_by(tenant_no=tenant_no, plan_id=plan_id, del_flag=0).all() rows = db.query(PlPlanCertUsage).filter_by(tenant_no=tenant_no, plan_id=plan_id, del_flag=0).all()
for row in rows: for row in rows:
message = (row.confirmation_snapshot or {}).get('settlementError') message = (row.confirmation_snapshot or {}).get('settlementError')
if isinstance(message, str) and message.strip(): if isinstance(message, str) and message.strip():
return message.strip() return message.strip()
target = plan
if target is None:
target = db.query(PlPlan).filter_by(id=plan_id, tenant_no=tenant_no, del_flag=0).first()
if target is not None and int(getattr(target, 'quota_cert_pending_fulfill', 0) or 0) == 1:
return '该计划仍处于证书齐备待完善,请先在证书齐备中完善并关闭后再归档'
return '实际数量已保存,证件没有扣减。请把实际数量改小,或先补充购买证和运输证,再重新归档。' return '实际数量已保存,证件没有扣减。请把实际数量改小,或先补充购买证和运输证,再重新归档。'
@@ -155,6 +155,4 @@ def save_cert(db, user, cert_type, data, cert_id=None):
for scope in prepared: for scope in prepared:
scopes.apply_contract_bindings(db, user, scope) scopes.apply_contract_bindings(db, user, scope)
db.flush() 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) return get_cert(db, user, cert_type, row.id, current=True)
+8 -223
View File
@@ -9,7 +9,6 @@ from fastapi import HTTPException
from pydantic import BaseModel from pydantic import BaseModel
from sqlalchemy import or_ from sqlalchemy import or_
from sqlalchemy.exc import IntegrityError from sqlalchemy.exc import IntegrityError
from app.models.crm_models import CrmCustomer
from app.models.pl_quota_models import ( from app.models.pl_quota_models import (
PlPurchaseCert, PlTransportCert, PlTransportCertPurchaseRef, PlPurchaseCert, PlTransportCert, PlTransportCertPurchaseRef,
PlCertQtyLog, PlPlanCertUsage, PlContractCertLink, PlCertOperation, PlCertQtyLog, PlPlanCertUsage, PlContractCertLink, PlCertOperation,
@@ -48,39 +47,6 @@ def usage_policy(valid_use_text):
return {'一次有效': 'once', '多次有效': 'multiple'}.get((valid_use_text or '').strip(), 'needs_confirmation') return {'一次有效': 'once', '多次有效': 'multiple'}.get((valid_use_text or '').strip(), 'needs_confirmation')
_ONCE_USAGE_STATUSES = ('reserved', 'in_transit', 'settled', 'exception')
def is_single_use_consumed(db, user, cert_type, cert, *, exclude_plan_id=None):
"""一次有效证是否已不可再用:期初已使用,或其它计划已占用/已执行。
exclude_plan_id:当前计划自身的用量不计入占用(安排/结转同一计划可续用)。
多次有效或待确认原文返回 False,由调用方另行校验 policy。
"""
if usage_policy(getattr(cert, 'valid_use_text', None)) != 'once':
return False
if getattr(cert, 'opening_single_use_consumed', 0):
return True
previous = (
db.query(PlPlanCertUsage)
.filter_by(
tenant_no=user.tenant_no,
cert_type=cert_type,
cert_id=cert.id,
del_flag=0,
)
.all()
)
for usage in previous:
if exclude_plan_id is not None and usage.plan_id == exclude_plan_id:
continue
if usage.usage_status in _ONCE_USAGE_STATUSES:
return True
if (usage.confirmation_snapshot or {}).get('executed'):
return True
return False
def _assert_known_usage_policy(row): def _assert_known_usage_policy(row):
if usage_policy(row.valid_use_text) == 'needs_confirmation': if usage_policy(row.valid_use_text) == 'needs_confirmation':
raise HTTPException(400, '有效次数原文待确认,明确一次或多次有效后才能启用') raise HTTPException(400, '有效次数原文待确认,明确一次或多次有效后才能启用')
@@ -119,47 +85,8 @@ def _transport_derived_categories(db, user, transport_cert_id):
return list(dict.fromkeys(r.category_id for r in rows if r.category_id)) return list(dict.fromkeys(r.category_id for r in rows if r.category_id))
def _customer_display_name(db, user, customer_id):
"""按证件绑定的系统客户 ID 取 CRM 名称;与证面收货/购买单位无关。"""
cid = str(customer_id or '').strip()
if not cid:
return None
row = (
db.query(CrmCustomer.customer_name)
.filter(
CrmCustomer.id == cid,
CrmCustomer.tenant_no == user.tenant_no,
CrmCustomer.del_flag == 0,
)
.first()
)
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): def get_cert(db, user, cert_type, cert_id, current=False):
row = _get_row(db, user, cert_type, cert_id, lock=current) row = _get_row(db, user, cert_type, cert_id, lock=current)
# 只读列表/详情不得在未提交事务里改状态,否则会出现「页面已启用、库仍 draft」。
# 自动期初与启用仅在 save_cert / confirm 等写入路径执行。
result = _row_to_dict(row) result = _row_to_dict(row)
result['usagePolicy'] = usage_policy(row.valid_use_text) result['usagePolicy'] = usage_policy(row.valid_use_text)
opening_query = db.query(PlCertQtyLog.id).filter_by( opening_query = db.query(PlCertQtyLog.id).filter_by(
@@ -169,28 +96,17 @@ def get_cert(db, user, cert_type, cert_id, current=False):
opening_query = opening_query.with_for_update() opening_query = opening_query.with_for_update()
result['openingConfirmed'] = opening_query.first() is not None result['openingConfirmed'] = opening_query.first() is not None
result['availableQty'] = row.total_qty - row.used_qty - row.reserved_qty 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': if cert_type == 'transport':
result['purchaseRefs'] = [_row_to_dict(r) for r in _refs(db, user, cert_id, lock=current)] result['purchaseRefs'] = [_row_to_dict(r) for r in _refs(db, user, cert_id, lock=current)]
result['referencesEditable'] = not _has_usage_beyond_zero_opening( result['referencesEditable'] = not _has_history(db, user, cert_type, cert_id, lock=current)
db, user, cert_type, cert_id, lock=current result['derivedCategoryIds'] = _transport_derived_categories(db, user, cert_id)
)
derived_ids = _transport_derived_categories(db, user, cert_id)
result['derivedCategoryIds'] = derived_ids
result['derivedCategoryNames'] = _category_display_names(db, user, derived_ids)
return result return result
def list_certs(db, user, cert_type, keyword=None, status=None, customer_id=None): def list_certs(db, user, cert_type, keyword=None, status=None):
model = _model(cert_type) model = _model(cert_type)
query = db.query(model).filter(model.tenant_no == user.tenant_no, model.del_flag == 0) query = db.query(model).filter(model.tenant_no == user.tenant_no, model.del_flag == 0)
query = apply_pl_scope(query, model, user, db, user.tenant_no) query = apply_pl_scope(query, model, user, db, user.tenant_no)
if customer_id:
query = query.filter(model.customer_id == customer_id)
if keyword: if keyword:
sale_name = model.seller_name if cert_type == 'purchase' else model.shipper_name sale_name = model.seller_name if cert_type == 'purchase' else model.shipper_name
buy_name = model.buyer_name if cert_type == 'purchase' else model.consignee_name buy_name = model.buyer_name if cert_type == 'purchase' else model.consignee_name
@@ -207,9 +123,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()] result = [get_cert(db, user, cert_type, r.id) for r in query.order_by(model.create_time.desc()).all()]
if cert_type == 'transport': if cert_type == 'transport':
for item in result: for item in result:
derived_ids = _transport_derived_categories(db, user, item['id']) item['derivedCategoryIds'] = _transport_derived_categories(db, user, item['id'])
item['derivedCategoryIds'] = derived_ids
item['derivedCategoryNames'] = _category_display_names(db, user, derived_ids)
return result return result
@@ -255,11 +169,8 @@ def _refs_keep_verified(pending, removed):
def _has_history(db, user, cert_type, cert_id, lock=True): def _has_history(db, user, cert_type, cert_id, lock=True):
"""任意额度流水或计划占用均视为已有历史(含自动期初),用于锁证号/核定量等身份。"""
for model in (PlCertQtyLog, PlPlanCertUsage): for model in (PlCertQtyLog, PlPlanCertUsage):
query = db.query(model.id).filter_by( query = db.query(model.id).filter_by(tenant_no=user.tenant_no, cert_type=cert_type, cert_id=cert_id)
tenant_no=user.tenant_no, cert_type=cert_type, cert_id=cert_id, del_flag=0,
)
if lock: if lock:
query = query.with_for_update() query = query.with_for_update()
if query.first() is not None: if query.first() is not None:
@@ -267,35 +178,6 @@ def _has_history(db, user, cert_type, cert_id, lock=True):
return False return False
def _has_usage_beyond_zero_opening(db, user, cert_type, cert_id, lock=True):
"""真实用量/占用才锁运输证引用;期初已用=0 的 opening 仍可补全关联购买证。"""
usage_q = db.query(PlPlanCertUsage.id).filter_by(
tenant_no=user.tenant_no, cert_type=cert_type, cert_id=cert_id, del_flag=0,
)
if lock:
usage_q = usage_q.with_for_update()
if usage_q.first() is not None:
return True
log_q = db.query(PlCertQtyLog).filter_by(
tenant_no=user.tenant_no, cert_type=cert_type, cert_id=cert_id, del_flag=0,
)
if lock:
log_q = log_q.with_for_update()
for log in log_q.all():
snap = log.event_snapshot or {}
# 仅建档自动期初(已用0)不锁引用;手工期初或其它流水仍锁。
if (
log.event_type == 'opening'
and snap.get('auto')
and (log.used_delta or 0) == 0
and (log.reserved_delta or 0) == 0
and (log.total_delta or 0) == 0
):
continue
return True
return False
def _validate_refs(db, user, cert_id, submitted, historical, purchases, current=False): def _validate_refs(db, user, cert_id, submitted, historical, purchases, current=False):
if submitted is None: if submitted is None:
raise HTTPException(400, '引用集合不可为null;清空请提交[]') raise HTTPException(400, '引用集合不可为null;清空请提交[]')
@@ -400,8 +282,7 @@ def prepare_cert(db, user, cert_type, data, cert_id=None, *, locked=None, effect
if duplicate and duplicate.id != cert_id: if duplicate and duplicate.id != cert_id:
raise HTTPException(400, '证号已存在,删除后也不得重建额度池') raise HTTPException(400, '证号已存在,删除后也不得重建额度池')
effective_id = cert_id or effective_id or str(uuid4()) effective_id = cert_id or effective_id or str(uuid4())
refs_locked = bool(row and _has_usage_beyond_zero_opening(db, user, cert_type, cert_id)) pending, removed = _validate_refs(db,user,effective_id,refs,historical,purchases,current=bool(cert_id)) if refs_present else ([],[])
pending, removed = _validate_refs(db,user,effective_id,refs,refs_locked,purchases,current=bool(cert_id)) if refs_present else ([],[])
changed = {key for key, value in values.items() if row is None or getattr(row, key) != value} changed = {key for key, value in values.items() if row is None or getattr(row, key) != value}
refs_changed = bool(removed) or any(previous is None or previous.del_flag == 1 or any(getattr(previous, key) != value for key, value in item.items() if key != 'id') for previous, item in pending) refs_changed = bool(removed) or any(previous is None or previous.del_flag == 1 or any(getattr(previous, key) != value for key, value in item.items() if key != 'id') for previous, item in pending)
return dict(model=model, row=row, values=values, cert_id=cert_id, effective_id=effective_id, return dict(model=model, row=row, values=values, cert_id=cert_id, effective_id=effective_id,
@@ -448,98 +329,19 @@ def apply_cert(db, user, prepared):
return row return row
def ensure_zero_opening(db, user, cert_type, cert_id, *, row=None):
"""建档后无需手工期初确认:缺 opening 流水时写入期初已用=0;draft 直接启用。"""
if row is None:
row = _get_row(db, user, cert_type, cert_id)
if row.status in ('void', 'closed'):
return row
existing = 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()
if existing:
return row
row = _get_row(db, user, cert_type, cert_id, lock=True)
if row.status in ('void', 'closed'):
return row
if 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,
).with_for_update().first():
return row
# 有效次数原文未识别时保留 draft,不自动启用;明确一次/多次后保存或读取再启用。
if usage_policy(row.valid_use_text) == 'needs_confirmation':
return row
used = Decimal(row.used_qty or 0)
op_id = f'auto-opening:{cert_type}:{cert_id}'
digest = hashlib.sha256(op_id.encode()).hexdigest()
operation, replay = _claim_operation(db, user, 'opening', op_id, digest)
if replay:
return row
db.add(PlCertQtyLog(
**_audit(user),
operation_id=op_id,
request_hash=digest,
cert_type=cert_type,
cert_id=cert_id,
event_type='opening',
quantity_unit=row.quantity_unit,
total_delta=Decimal(0),
reserved_delta=Decimal(0),
used_delta=used,
before_total_qty=row.total_qty,
after_total_qty=row.total_qty,
before_reserved_qty=row.reserved_qty,
after_reserved_qty=row.reserved_qty,
before_used_qty=used,
after_used_qty=used,
reason='建档自动启用',
evidence_urls=None,
event_snapshot={'singleUseConsumed': False, 'sourceNote': 'auto', 'auto': True},
))
if row.status == 'draft':
row.status = 'active'
row.verified_by = user.id
row.verified_time = datetime.now()
row.update_by = user.id
operation.result_json = {'certType': cert_type, 'certId': cert_id, 'auto': True}
db.flush()
return row
def save_cert(db, user, cert_type, data, cert_id=None): def save_cert(db, user, cert_type, data, cert_id=None):
row = apply_cert(db, user, prepare_cert(db, user, cert_type, data, cert_id)) row = apply_cert(db, user, prepare_cert(db, user, cert_type, data, cert_id))
ensure_zero_opening(db, user, cert_type, row.id, row=row)
return get_cert(db, user, cert_type, row.id) return get_cert(db, user, cert_type, row.id)
def delete_cert(db, user, cert_type, cert_id): def delete_cert(db, user, cert_type, cert_id):
row = _get_row(db,user,cert_type,cert_id,lock=True) row = _get_row(db,user,cert_type,cert_id,lock=True)
if row.reserved_qty or row.used_qty: if _has_history(db,user,cert_type,cert_id) or row.reserved_qty or row.used_qty:
raise HTTPException(400, '已有用量或流水的证件只能停用、核销或作废')
if db.query(PlPlanCertUsage.id).filter_by(
tenant_no=user.tenant_no, cert_type=cert_type, cert_id=cert_id, del_flag=0,
).with_for_update().first():
raise HTTPException(400, '已有用量或流水的证件只能停用、核销或作废')
logs = (
db.query(PlCertQtyLog)
.filter_by(tenant_no=user.tenant_no, cert_type=cert_type, cert_id=cert_id, del_flag=0)
.with_for_update()
.all()
)
# 仅建档自动期初(或无流水)仍允许删除;手工期初或其它额度流水则禁止。
def _auto_opening(log):
snap = log.event_snapshot or {}
return log.event_type == 'opening' and bool(snap.get('auto')) and (log.used_delta or 0) == 0
if any(not _auto_opening(log) for log in logs):
raise HTTPException(400, '已有用量或流水的证件只能停用、核销或作废') raise HTTPException(400, '已有用量或流水的证件只能停用、核销或作废')
if db.query(PlContractCertLink.id).filter_by(tenant_no=user.tenant_no,cert_type=cert_type,cert_id=cert_id,del_flag=0).with_for_update().first(): if db.query(PlContractCertLink.id).filter_by(tenant_no=user.tenant_no,cert_type=cert_type,cert_id=cert_id,del_flag=0).with_for_update().first():
raise HTTPException(400, '证件已绑定合同') raise HTTPException(400, '证件已绑定合同')
if cert_type == 'purchase' and db.query(PlTransportCertPurchaseRef.id).filter_by(tenant_no=user.tenant_no,purchase_cert_id=cert_id,del_flag=0).with_for_update().first(): if cert_type == 'purchase' and db.query(PlTransportCertPurchaseRef.id).filter_by(tenant_no=user.tenant_no,purchase_cert_id=cert_id,del_flag=0).with_for_update().first():
raise HTTPException(400, '证件被运输证引用') raise HTTPException(400, '证件被运输证引用')
for log in logs:
log.del_flag = 1
log.update_by = user.id
row.del_flag = 1 row.del_flag = 1
row.update_by = user.id row.update_by = user.id
if cert_type == 'transport': if cert_type == 'transport':
@@ -586,24 +388,7 @@ def _confirm_cert(db, user, cert_type, cert_id, data):
_assert_known_usage_policy(row) _assert_known_usage_policy(row)
if row.status == 'void': raise HTTPException(400, '作废证件不能启用') if row.status == 'void': raise HTTPException(400, '作废证件不能启用')
if row.status == 'closed': raise HTTPException(400, '已核销证件不能启用') if row.status == 'closed': raise HTTPException(400, '已核销证件不能启用')
# 建档自动期初(used=0)可被手工/接口期初覆盖;已有真实用量或非自动期初则拒绝。 if row.verified_time or _has_history(db,user,cert_type,cert_id):
openings = (
db.query(PlCertQtyLog)
.filter_by(
tenant_no=user.tenant_no, cert_type=cert_type, cert_id=cert_id,
event_type='opening', del_flag=0,
)
.with_for_update()
.all()
)
for log in openings:
snap = log.event_snapshot or {}
if snap.get('auto') and (log.used_delta or 0) == 0:
log.del_flag = 1
log.update_by = user.id
else:
raise HTTPException(400, '期初已确认,不能重复初始化额度')
if _has_history(db, user, cert_type, cert_id):
raise HTTPException(400, '期初已确认,不能重复初始化额度') raise HTTPException(400, '期初已确认,不能重复初始化额度')
if body.used_qty > row.total_qty: if body.used_qty > row.total_qty:
raise HTTPException(400, '期初已用量不能超过核定量') raise HTTPException(400, '期初已用量不能超过核定量')
+53 -456
View File
@@ -12,7 +12,6 @@ from app.models.pl_quota_models import (
) )
from app.schemas.pl.quota_planning import ManualQuantity from app.schemas.pl.quota_planning import ManualQuantity
from app.services.pl_cert_category_service import category_ids_for_product 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 from app.services.pl_quota_units import same_quantity_unit, standard_conversion_ratio
@@ -43,16 +42,6 @@ def _has_opening(db, user, cert_type, cert_id) -> bool:
) )
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: def _vehicle_ok(cert, vehicle_no: str) -> bool:
plates = cert.vehicle_numbers_json or [] plates = cert.vehicle_numbers_json or []
if not isinstance(plates, list): if not isinstance(plates, list):
@@ -63,14 +52,6 @@ def _vehicle_ok(cert, vehicle_no: str) -> bool:
return plate in {str(p).strip() for p in plates if p} 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: def _permit_qty_for(source_qty: Decimal, source_unit: str, cert_unit: str) -> Decimal:
if same_quantity_unit(source_unit, cert_unit): if same_quantity_unit(source_unit, cert_unit):
return source_qty return source_qty
@@ -80,49 +61,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')) 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: def _customer_id_from_source(source) -> str:
snap = source.snapshot or {} snap = source.snapshot or {}
cid = snap.get('customerId') or snap.get('customer_id') cid = snap.get('customerId') or snap.get('customer_id')
@@ -131,308 +69,10 @@ def _customer_id_from_source(source) -> str:
raise HTTPException(409, '用证段次缺少客户,无法按客户选证') raise HTTPException(409, '用证段次缺少客户,无法按客户选证')
def _snap_text(source, *keys) -> str: def select_whole_cover_certs(db, user, sources, *, vehicle_no: str, on_date: date):
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=(),
):
"""返回 purchase_cert_ids, transport_cert_ids, manual_allocations。 """返回 purchase_cert_ids, transport_cert_ids, manual_allocations。
每个来源必须由一张购买证整笔覆盖;异地再配一张关联且车号/余量够的运输证。 每个来源必须由一张购买证整笔覆盖;异地再配一张关联且车号/余量够的运输证。
单位无法自动换算时,使用计划段次用证已保存的人工换算量。
""" """
if not sources: if not sources:
return [], [], [] return [], [], []
@@ -440,19 +80,33 @@ def select_whole_cover_certs(
purchase_ids = [] purchase_ids = []
transport_ids = [] transport_ids = []
manuals = [] manuals = []
saved_manuals = manual_allocations or ()
for source in sources: for source in sources:
customer_id = _customer_id_from_source(source) customer_id = _customer_id_from_source(source)
categories = category_ids_for_product(db, user.tenant_no, source.product_id) categories = category_ids_for_product(db, user.tenant_no, source.product_id)
if not categories: if not categories:
product_label = _source_product_label(db, user, source) or '该产品'
raise HTTPException( raise HTTPException(
409, 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_purchase = None
chosen_transport = None chosen_transport = None
@@ -462,18 +116,14 @@ def select_whole_cover_certs(
for purchase in candidates: for purchase in candidates:
if not purchase.verified_by or not purchase.verified_time: if not purchase.verified_by or not purchase.verified_time:
continue continue
_ensure_opening_quiet(db, user, 'purchase', purchase.id, purchase)
if not _has_opening(db, user, 'purchase', purchase.id): if not _has_opening(db, user, 'purchase', purchase.id):
continue continue
if not _in_force(purchase, on_date): if not _in_force(purchase, on_date):
continue continue
if is_single_use_consumed(db, user, 'purchase', purchase): if purchase.opening_single_use_consumed:
continue continue
try: try:
need = _need_permit_qty( need = _permit_qty_for(Decimal(source.quantity), source.unit, purchase.quantity_unit)
source.quantity, source.unit, purchase.quantity_unit,
saved_manuals, 'purchase', source.source_id, purchase.id,
)
except HTTPException: except HTTPException:
continue continue
if _available(purchase) < need: if _available(purchase) < need:
@@ -484,26 +134,47 @@ def select_whole_cover_certs(
purchase_permit_qty = need purchase_permit_qty = need
break break
transports = _linked_transports(db, user, customer_id, purchase.id) refs = (
if not transports: 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 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: for transport in transports:
if not transport.verified_by or not transport.verified_time: if not transport.verified_by or not transport.verified_time:
continue continue
_ensure_opening_quiet(db, user, 'transport', transport.id, transport)
if not _has_opening(db, user, 'transport', transport.id): if not _has_opening(db, user, 'transport', transport.id):
continue continue
if not _in_force(transport, on_date): if not _in_force(transport, on_date):
continue continue
if is_single_use_consumed(db, user, 'transport', transport): if transport.opening_single_use_consumed:
continue continue
if not _vehicle_ok(transport, vehicle_no): if not _vehicle_ok(transport, vehicle_no):
continue continue
try: try:
t_need = _need_permit_qty( t_need = _permit_qty_for(Decimal(source.quantity), source.unit, transport.quantity_unit)
source.quantity, source.unit, transport.quantity_unit,
saved_manuals, 'transport', source.source_id, transport.id,
)
except HTTPException: except HTTPException:
continue continue
if _available(transport) < t_need: if _available(transport) < t_need:
@@ -517,12 +188,11 @@ def select_whole_cover_certs(
break break
if chosen_purchase is None: if chosen_purchase is None:
place = '同市' if not source.requires_transport else '异地'
raise HTTPException( raise HTTPException(
409, 409,
_diagnose_select_failure( f'{place}段找不到余量足够、有效期内且匹配品类/车号的购买证'
db, user, source, vehicle_no=vehicle_no, on_date=on_date, f'{"和运输证" if source.requires_transport else ""},请补充证件或标记证书齐备后再安排',
candidates=candidates, manual_allocations=saved_manuals,
),
) )
purchase_ids.append(chosen_purchase.id) purchase_ids.append(chosen_purchase.id)
@@ -551,76 +221,3 @@ def select_whole_cover_certs(
return list(dict.fromkeys(values)) return list(dict.fromkeys(values))
return unique(purchase_ids), unique(transport_ids), manuals 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)
+10 -24
View File
@@ -131,19 +131,16 @@ def build_usage_request(db, user, plan_id, operation, action, *, lock=False, che
sources, actuals = [], {} sources, actuals = [], {}
else: else:
sources, actuals = extract_sources(db, user, plan_id, mapping, actual=action in ('settle', 'actual_adjust'), lock=lock, preview_vehicle=preview_vehicle, measurement_version=config.measurement_version) sources, actuals = extract_sources(db, user, plan_id, mapping, actual=action in ('settle', 'actual_adjust'), lock=lock, preview_vehicle=preview_vehicle, measurement_version=config.measurement_version)
from app.services.pl_cert_quota_rule_config_service import plan_applies_customer_category_rule from app.services.pl_cert_quota_rule_config_service import plan_uses_customer_category
customer_rule = plan_applies_customer_category_rule(db, user.tenant_no, plan) customer_rule = plan_uses_customer_category(plan)
if action in ('reserve', 'resize') and not explicit and sources: if action in ('reserve', 'resize') and not explicit and sources:
if customer_rule: if customer_rule:
# 新规则:禁止手工选证;按客户+品类整笔自动选证 # 新规则:禁止手工选证;按客户+品类整笔自动选证
from app.services.pl_quota_customer_select import select_whole_cover_certs from app.services.pl_quota_customer_select import select_whole_cover_certs
vehicle = str( vehicle = (preview_vehicle or {}).get('licensePlate', plan.license_plate) or ''
(preview_vehicle or {}).get('licensePlate', plan.license_plate) or ''
).strip()
on_date = max(date.today(), plan.plan_date or date.today()) on_date = max(date.today(), plan.plan_date or date.today())
purchase_ids, transport_ids, manuals = select_whole_cover_certs( purchase_ids, transport_ids, manuals = select_whole_cover_certs(
db, user, sources, vehicle_no=vehicle, on_date=on_date, db, user, sources, vehicle_no=vehicle, on_date=on_date,
manual_allocations=config.manual_allocations,
) )
config = config.model_copy(update={ config = config.model_copy(update={
'purchase_cert_ids': purchase_ids, '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)} certs = {key: _get_row(db, user, *key, lock=False) for key in sorted(keys)}
if sources and not keys: if sources and not keys:
msg = ( msg = (
'未选到可用的购买证和运输证。请核对证件余量、有效期、品类与车牌号后补充证件,或标记证书齐备后再安排运输' '找不到适用的购买证和运输证,请补充证件或标记证书齐备后再安排运输'
if customer_rule else 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, operation_id=op.operation_id, action=action, plan_id=plan_id, sources=sources,
allow_supplement=op.allow_supplement, allow_supplement=op.allow_supplement,
purchase_cert_ids=config.purchase_cert_ids, transport_cert_ids=config.transport_cert_ids, 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], 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], 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 '', reason=op.reason, evidence_urls=op.evidence_urls or '', source_note=op.source_note or '',
@@ -228,10 +225,10 @@ def preview_plan(db, user, plan_id, config, preview_vehicle=None):
def save_configuration(db, user, plan_id, config): def save_configuration(db, user, plan_id, config):
from app.services.pl_plan_service import record_plan_change from app.services.pl_plan_service import record_plan_change
from app.services.pl_cert_quota_rule_config_service import plan_applies_customer_category_rule from app.services.pl_cert_quota_rule_config_service import plan_uses_customer_category
config = config if isinstance(config, PlanQuotaConfiguration) else PlanQuotaConfiguration.model_validate(config) config = config if isinstance(config, PlanQuotaConfiguration) else PlanQuotaConfiguration.model_validate(config)
plan = _plan(db, user, plan_id, lock=True) plan = _plan(db, user, plan_id, lock=True)
if plan_applies_customer_category_rule(db, user.tenant_no, plan): if plan_uses_customer_category(plan):
raise HTTPException(409, '新规则下安排仅自动选证,不支持手工保存用证配置') raise HTTPException(409, '新规则下安排仅自动选证,不支持手工保存用证配置')
if plan.transport_status == 'arranged' or plan.archive_status == 'archived': if plan.transport_status == 'arranged' or plan.archive_status == 'archived':
raise HTTPException(409, '已安排计划请通过调整运输在同一事务重算用证') raise HTTPException(409, '已安排计划请通过调整运输在同一事务重算用证')
@@ -338,22 +335,11 @@ def get_plan_quota(db, user, plan_id):
options.append(item) options.append(item)
usages = db.query(PlPlanCertUsage).filter_by(tenant_no=user.tenant_no, plan_id=plan_id, del_flag=0).order_by(PlPlanCertUsage.create_time.desc()).all() usages = db.query(PlPlanCertUsage).filter_by(tenant_no=user.tenant_no, plan_id=plan_id, del_flag=0).order_by(PlPlanCertUsage.create_time.desc()).all()
version = resolve_measurement_version(db, user, plan) version = resolve_measurement_version(db, user, plan)
from app.services.pl_cert_quota_rule_config_service import ( from app.services.pl_cert_quota_rule_config_service import plan_uses_customer_category
VERSION_LEGACY, customer_rule = plan_uses_customer_category(plan)
plan_applies_customer_category_rule,
resolve_rule_version_for_arrange,
)
customer_rule = plan_applies_customer_category_rule(db, user.tenant_no, plan)
stamped = getattr(plan, 'cert_quota_rule_version', None)
if stamped:
rule_version = stamped
elif getattr(plan, 'cert_quota_arranged_at', None) is None:
rule_version = resolve_rule_version_for_arrange(db, user.tenant_no)
else:
rule_version = VERSION_LEGACY
result = {'planId': plan.id, 'planNo': plan.plan_no, 'licensePlate': plan.license_plate, result = {'planId': plan.id, 'planNo': plan.plan_no, 'licensePlate': plan.license_plate,
'quotaCertWaived': int(getattr(plan, 'quota_cert_waived', 0) or 0) == 1, 'quotaCertWaived': int(getattr(plan, 'quota_cert_waived', 0) or 0) == 1,
'certQuotaRuleVersion': rule_version or VERSION_LEGACY, 'certQuotaRuleVersion': getattr(plan, 'cert_quota_rule_version', None) or 'legacy',
'measurementVersion': version, 'measurementVersion': version,
'configuration': {**(plan.cert_configuration or {}), 'measurementVersion': version}, 'sourceOptions': options, 'configuration': {**(plan.cert_configuration or {}), 'measurementVersion': version}, 'sourceOptions': options,
'stopProducts': stop_products, 'stopProducts': stop_products,
-4
View File
@@ -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['vehicle'] = preview_vehicle.get('licensePlate', plan.license_plate)
snapshot['trailer'] = preview_vehicle.get('trailerNo', plan.trailer_no) snapshot['trailer'] = preview_vehicle.get('trailerNo', plan.trailer_no)
fingerprint = hashlib.sha256(json.dumps(snapshot, sort_keys=True, ensure_ascii=False).encode()).hexdigest() 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, 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, plan_product_id=row.plan_product_id, contract_id=row.contract_id,
contract_product_id=row.contract_product_id, product_id=row.product_id, contract_product_id=row.contract_product_id, product_id=row.product_id,
+2 -107
View File
@@ -4,12 +4,12 @@ from decimal import Decimal
from sqlalchemy import and_, or_, literal, func from sqlalchemy import and_, or_, literal, func
from fastapi import HTTPException from fastapi import HTTPException
from app.crud.crm.data_scope_helpers import apply_crm_owner_scope from app.crud.crm.data_scope_helpers import apply_crm_owner_scope
from app.models.crm_models import CrmContract, CrmContractProduct, CrmCustomer from app.models.crm_models import CrmContract, CrmContractProduct
from app.models.pl_models import PlPlan from app.models.pl_models import PlPlan
from app.models.pl_quota_models import (PlContractCertLink as Link, PlContractCertProduct as Scope, from app.models.pl_quota_models import (PlContractCertLink as Link, PlContractCertProduct as Scope,
PlPlanCertUsage as Usage, PlPlanCertUsageItem as Item, PlCertQtyLog as Log) PlPlanCertUsage as Usage, PlPlanCertUsageItem as Item, PlCertQtyLog as Log)
from app.services.pl_data_scope import apply_pl_scope from app.services.pl_data_scope import apply_pl_scope
from app.services.pl_quota_cert_service import MODELS, _get_row, get_cert, usage_policy from app.services.pl_quota_cert_service import MODELS, _get_row
ZERO = Decimal('0') ZERO = Decimal('0')
CONTRACT_TYPES = {'sale', 'purchase', 'framework_sale', 'framework_purchase', 'framework'} CONTRACT_TYPES = {'sale', 'purchase', 'framework_sale', 'framework_purchase', 'framework'}
@@ -109,39 +109,6 @@ def _contracts(db, user):
user.to_user_info(), db, user.tenant_no) user.to_user_info(), db, user.tenant_no)
def _customers(db, user):
return apply_crm_owner_scope(_active(db, user, CrmCustomer), CrmCustomer,
user.to_user_info(), db, user.tenant_no)
def _customer_cert_counts(db, user):
"""按客户汇总购买证+运输证数量;默认排除已核销/作废,与证件列表一致。"""
parts = []
for model in MODELS.values():
query = apply_pl_scope(_active(db, user, model), model, user, db, user.tenant_no)
query = query.filter(
model.customer_id.isnot(None),
model.customer_id != '',
model.status.notin_(('closed', 'void')),
)
parts.append(query.with_entities(model.customer_id.label('customer_id'), literal(1).label('one')))
combined = parts[0].union_all(*parts[1:]).subquery()
return (
db.query(combined.c.customer_id.label('customer_id'), func.count().label('cert_count'))
.group_by(combined.c.customer_id)
.subquery()
)
def _customer_summary(row):
return {
'id': row.id,
'customerId': row.id,
'customerNo': row.customer_no or '',
'customerName': row.customer_name or '',
}
def _certificates(db, user, keyword=None, cert_type=None, cert_no=None, cert_types=None): def _certificates(db, user, keyword=None, cert_type=None, cert_no=None, cert_types=None):
queries = [] queries = []
for kind, model in MODELS.items(): for kind, model in MODELS.items():
@@ -384,78 +351,6 @@ def contract_statistics(db, user, contract_id):
return {**_contract_summary(contract), 'certificates': result} return {**_contract_summary(contract), 'certificates': result}
def list_customers(db, user, keyword=None, page=1, page_size=20, customer_no=None, customer_name=None,
cert_count_op=None, cert_count=None, cert_count_min=None, cert_count_max=None):
counts = _customer_cert_counts(db, user)
query = _customers(db, user).join(counts, counts.c.customer_id == CrmCustomer.id)
if keyword:
query = query.filter(or_(
CrmCustomer.customer_no.contains(keyword, autoescape=True),
CrmCustomer.customer_name.contains(keyword, autoescape=True),
CrmCustomer.short_name.contains(keyword, autoescape=True),
))
if _text(customer_no):
query = query.filter(CrmCustomer.customer_no.contains(_text(customer_no), autoescape=True))
if _text(customer_name):
query = query.filter(CrmCustomer.customer_name.contains(_text(customer_name), autoescape=True))
for clause in _number_clauses(counts.c.cert_count, cert_count_op, cert_count, cert_count_min, cert_count_max):
query = query.filter(clause)
total = query.count()
rows = query.with_entities(CrmCustomer, counts.c.cert_count).order_by(
CrmCustomer.create_time.desc(), CrmCustomer.id
).offset((page - 1) * page_size).limit(page_size).all()
return {
'list': [{**_customer_summary(customer), 'certCount': int(count or 0)} for customer, count in rows],
'total': total,
'page': page,
'pageSize': page_size,
}
def customer_statistics(db, user, customer_id):
customer = _customers(db, user).filter(CrmCustomer.id == customer_id).first()
if customer is None:
raise HTTPException(404, '客户不存在或无权访问')
certificates = []
for kind, model in MODELS.items():
query = apply_pl_scope(_active(db, user, model), model, user, db, user.tenant_no)
query = query.filter(
model.customer_id == customer_id,
model.status.notin_(('closed', 'void')),
)
for row in query.order_by(model.create_time.desc(), model.id).all():
item = get_cert(db, user, kind, row.id)
sale = item.get('sellerName') if kind == 'purchase' else item.get('shipperName')
buy = item.get('buyerName') if kind == 'purchase' else item.get('consigneeName')
certificates.append({
'id': row.id,
'certId': row.id,
'certType': kind,
'certNo': item.get('certNo') or '',
'productNameOnCert': item.get('productNameOnCert') or '',
'quantityUnit': item.get('quantityUnit') or '',
'totalQty': item.get('totalQty'),
'reservedQty': item.get('reservedQty'),
'usedQty': item.get('usedQty'),
'availableQty': item.get('availableQty'),
'status': item.get('status') or '',
'validFrom': item.get('validFrom'),
'validTo': item.get('validTo'),
'salePartyName': sale or '',
'buyPartyName': buy or '',
'validUseText': item.get('validUseText') or '',
'usagePolicy': item.get('usagePolicy') or usage_policy(row.valid_use_text),
'singleUseConsumed': bool(item.get('singleUseConsumed')),
'openingConfirmed': bool(item.get('openingConfirmed')),
'createTime': item.get('createTime'),
})
certificates.sort(
key=lambda row: (str(row.get('createTime') or ''), row.get('certNo') or ''),
reverse=True,
)
return {**_customer_summary(customer), 'certificates': certificates}
def certificate_statistics(db, user, cert_type, cert_id): def certificate_statistics(db, user, cert_type, cert_id):
_get_row(db, user, cert_type, cert_id) _get_row(db, user, cert_type, cert_id)
certs = _certificates(db, user, cert_type=cert_type) certs = _certificates(db, user, cert_type=cert_type)
+40 -144
View File
@@ -16,7 +16,7 @@ from app.models.pl_models import PlPlan
from app.models.crm_models import CrmContractProduct from app.models.crm_models import CrmContractProduct
from app.schemas.pl.quota_usage import UsageManual, UsageRequest from app.schemas.pl.quota_usage import UsageManual, UsageRequest
from app.services.pl_data_scope import assert_pl_row_in_scope from app.services.pl_data_scope import assert_pl_row_in_scope
from app.services.pl_quota_cert_service import _audit, _get_row, is_single_use_consumed, usage_policy from app.services.pl_quota_cert_service import _audit, _get_row, usage_policy
from app.services.pl_quota_contract_service import _contract from app.services.pl_quota_contract_service import _contract
from app.services.pl_quota_allocation import (SourceDemand, PermitCandidate, ManualAllocation, Allocation, from app.services.pl_quota_allocation import (SourceDemand, PermitCandidate, ManualAllocation, Allocation,
allocate_plan, settle_allocations, validate_allocation_pairing, InsufficientQuota) allocate_plan, settle_allocations, validate_allocation_pairing, InsufficientQuota)
@@ -26,26 +26,6 @@ from app.services.pl_quota_units import same_quantity_unit, standard_conversion_
ZERO = Decimal('0') 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): def _reserve_input_mode(source_unit, cert_unit):
if same_quantity_unit(source_unit, cert_unit): if same_quantity_unit(source_unit, cert_unit):
return 'same_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} 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} 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: 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: 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: except HTTPException:
purchase_ids, transport_ids = [], [] purchase_ids, transport_ids = [], []
keys |= {('purchase', cert_id) for cert_id in purchase_ids} | {('transport', cert_id) for cert_id in transport_ids} keys |= {('purchase', cert_id) for cert_id in purchase_ids} | {('transport', cert_id) for cert_id in transport_ids}
@@ -219,10 +200,8 @@ def _candidate_context(db,user,r,plan,certs,usages,items,selected,preview=False,
skipped_for_vehicle=False skipped_for_vehicle=False
from app.services.pl_cert_quota_rule_config_service import plan_uses_customer_category from app.services.pl_cert_quota_rule_config_service import plan_uses_customer_category
customer_rule = plan_uses_customer_category(plan) customer_rule = plan_uses_customer_category(plan)
from app.services.pl_quota_cert_service import ensure_zero_opening
for k in sorted(selected): for k in sorted(selected):
kind,pid=k; c=certs[k] kind,pid=k; c=certs[k]
c = certs[k] = ensure_zero_opening(db, user, kind, pid, row=c)
if not query(m.PlCertQtyLog,cert_type=kind,cert_id=pid,event_type='opening',del_flag=0).first(): raise ValueError('证件尚未确认期初') if not query(m.PlCertQtyLog,cert_type=kind,cert_id=pid,event_type='opening',del_flag=0).first(): raise ValueError('证件尚未确认期初')
if c.status=='closed': raise ValueError('已核销证件不能再安排用证') if c.status=='closed': raise ValueError('已核销证件不能再安排用证')
if c.status!='active' or not c.verified_time or not c.verified_by: raise ValueError('证件尚未启用复核') if c.status!='active' or not c.verified_time or not c.verified_by: raise ValueError('证件尚未启用复核')
@@ -231,11 +210,13 @@ def _candidate_context(db,user,r,plan,certs,usages,items,selected,preview=False,
policy=usage_policy(c.valid_use_text) policy=usage_policy(c.valid_use_text)
if policy=='needs_confirmation': raise ValueError('有效次数待确认') 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 skipped_for_vehicle=True
continue continue
if policy=='once' and is_single_use_consumed(db, user, kind, c, exclude_plan_id=plan.id): if policy=='once':
raise ValueError('一次有效证件已使用或已占用') previous=query(m.PlPlanCertUsage,cert_type=kind,cert_id=pid,del_flag=0).all()
if c.opening_single_use_consumed or any(u.plan_id!=plan.id and (u.usage_status in ('reserved','in_transit','settled','exception') or (u.confirmation_snapshot or {}).get('executed')) for u in previous):
raise ValueError('一次有效证件已使用或已占用')
eligible=set() eligible=set()
if customer_rule: if customer_rule:
# 新规则已由客户+品类整笔选证;账本不再依赖合同绑证 scope。 # 新规则已由客户+品类整笔选证;账本不再依赖合同绑证 scope。
@@ -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 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)) 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']: if skipped_for_vehicle and not candidates['transport']:
plate = _normalize_vehicle_no(r.vehicle_no) raise ValueError('车号不在运输证范围')
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},'
'请到运输证中补充该车号或更换车辆后再安排'
)
return sources,scopes,candidates return sources,scopes,candidates
def _reserve(db,user,r,plan,certs,usages,items,selected,preview=False,lock_preview=False): def _reserve(db,user,r,plan,certs,usages,items,selected,preview=False,lock_preview=False):
@@ -395,88 +362,35 @@ def _validate_current_sources(r,active):
raise ValueError('当前权威来源身份、计划量、单位或指纹已变化,请重新核对用证') raise ValueError('当前权威来源身份、计划量、单位或指纹已变化,请重新核对用证')
class ArchiveQuotaBlocked(ValueError): class ArchiveQuotaBlocked(ValueError):
"""可用购买证、运输证仍不够本次实际量,归档必须整单回滚。""" """合同上的购买证、运输证仍不够本次实际量,归档必须整单回滚。"""
ARCHIVE_QUOTA_BLOCK = '合同绑定的购买证和运输证剩余额度不够覆盖本次实际数量,不能归档。请先补充证件额度或调整实际数量后再归档。' 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): 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(): 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: 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: 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) policy = usage_policy(cert.valid_use_text)
if policy == 'needs_confirmation': if policy == 'needs_confirmation':
return f'{label} {no} 有效次数待确认' return False
if kind == 'transport': if kind == 'transport' and (not r.vehicle_no or r.vehicle_no not in (cert.vehicle_numbers_json or [])):
plate = _normalize_vehicle_no(r.vehicle_no) return False
if not plate: if policy == 'once':
return f'运输证 {no} 需要车牌号,当前计划未填写车牌' previous = _query(db, user, m.PlPlanCertUsage, cert_type=kind, cert_id=cert.id, del_flag=0).all()
if not _vehicle_on_cert(cert, plate): if cert.opening_single_use_consumed or any(
raw = cert.vehicle_numbers_json or [] u.plan_id != plan.id and (
if isinstance(raw, str): u.usage_status in ('reserved', 'in_transit', 'settled', 'exception')
listed = raw or (u.confirmation_snapshot or {}).get('executed')
else: ) for u in previous
listed = '、'.join(str(p).strip() for p in raw if str(p).strip()) ):
suffix = f'(证上现有车号:{listed})' if listed else '' return False
return f'运输证 {no} 未包含车牌号「{plate}」{suffix}' return True
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}没有其他可用证件覆盖本次实际数量,不能归档。请先处理上述问题后再归档。'
_QTY = Decimal('0.000001') _QTY = Decimal('0.000001')
@@ -533,7 +447,7 @@ def _prepare_saved_conversion(groups, actual_by_source, certs):
proposals[kind] = [row for row in rows if row.source_id != sid] + updated proposals[kind] = [row for row in rows if row.source_id != sid] + updated
mine = updated mine = updated
if need > 0: if need > 0:
return groups, [], ARCHIVE_CONVERSION_EXCESS_BLOCK return groups, [], ARCHIVE_QUOTA_BLOCK
remaining = actual remaining = actual
for row in sorted(mine, key=lambda item: item.allocation_seq): for row in sorted(mine, key=lambda item: item.allocation_seq):
take = min(remaining, row.source_quantity) take = min(remaining, row.source_quantity)
@@ -574,8 +488,8 @@ def _settle(db,user,r,certs,usages,items,plan):
raise ArchiveQuotaBlocked(conversion_error) raise ArchiveQuotaBlocked(conversion_error)
if generated: if generated:
r = r.model_copy(update={'manual_actuals': generated}) r = r.model_copy(update={'manual_actuals': generated})
# 同单位超出预占时,自动改用补扣证件池(新规则客户+品类,旧规则合同绑证),含原证剩余额度。 # 同单位超出预占时,自动改用合同上已绑定的购买证和运输证,含原证剩余额度。
auto_cover = False contract_cover = False
if not r.allow_supplement: if not r.allow_supplement:
for sid, value in r.actual_by_source.items(): 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] mine = [a for rows in groups.values() for a in rows if a.source_id == sid]
@@ -583,7 +497,7 @@ def _settle(db,user,r,certs,usages,items,plan):
continue continue
capacity = sum((a.source_quantity for a in groups['purchase'] if a.source_id == sid), ZERO) capacity = sum((a.source_quantity for a in groups['purchase'] if a.source_id == sid), ZERO)
if value > capacity: if value > capacity:
auto_cover = True contract_cover = True
break break
# 原始容量不随补量扩大;新增证件原始容量为零,后续纠错始终先用原分配。 # 原始容量不随补量扩大;新增证件原始容量为零,后续纠错始终先用原分配。
base_actual=dict(r.actual_by_source) base_actual=dict(r.actual_by_source)
@@ -592,7 +506,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) capacity=sum((a.source_quantity for a in groups['purchase'] if a.source_id==sid),ZERO)
if value>capacity: if value>capacity:
excess[sid]=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。 # 人工显式补量可从当前实运来源拆出一段(如原证24、新证5),两段合计仍是29。
# 两证有一侧同单位时由联合分配器配对;异单位补量仍须完整人工输入。 # 两证有一侧同单位时由联合分配器配对;异单位补量仍须完整人工输入。
if r.allow_supplement and r.manual_allocations: if r.allow_supplement and r.manual_allocations:
@@ -644,52 +558,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()} 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=[] supplemental=[]
if excess: if excess:
if auto_cover: if contract_cover:
from app.services.pl_cert_quota_rule_config_service import plan_uses_customer_category from app.services.pl_quota_planning import resolve_contract_bound_certs
customer_rule = plan_uses_customer_category(plan)
try: 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: except HTTPException as exc:
raise ArchiveQuotaBlocked(str(getattr(exc, 'detail', exc))) from 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() 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) key=(kind, cid)
if key not in certs: if key not in certs:
raise ArchiveQuotaBlocked( raise ArchiveQuotaBlocked(ARCHIVE_QUOTA_BLOCK)
_archive_cover_block_message(db, user, r, plan, certs, candidate_keys)
)
if _settlement_cover_cert(db, user, r, plan, kind, certs[key]): if _settlement_cover_cert(db, user, r, plan, kind, certs[key]):
selected.add(key) selected.add(key)
if not selected: if not selected:
raise ArchiveQuotaBlocked( raise ArchiveQuotaBlocked(ARCHIVE_QUOTA_BLOCK)
_archive_cover_block_message(db, user, r, plan, certs, candidate_keys)
)
else: else:
if not r.reason.strip() or not (r.evidence_urls.strip() or r.source_note.strip()): if not r.reason.strip() or not (r.evidence_urls.strip() or r.source_note.strip()):
raise ValueError('补分配必须有理由及依据') raise ValueError('补分配必须有理由及依据')
selected={('purchase',x) for x in r.purchase_cert_ids}|{('transport',x) for x in r.transport_cert_ids} 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} base_totals={k:ZERO for k in usages}
for kind,rows in settled.items(): for kind,rows in settled.items():
for row in rows: base_totals[(kind,row.allocation.permit_id)]+=row.actual_permit_quantity 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()} credits={k:SimpleNamespace(reserved_qty=u.reserved_qty+u.used_qty-base_totals[k]) for k,u in usages.items()}
# 超额补扣需求仅为超出预占的部分。安排/完善并关闭写入的 manual_allocations 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]})
# 是整笔计划量,若原样带入会与超额需求冲突(证件明明够却报额度不足)。
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)
try: try:
result=_reserve(db,user,extra_request,plan,certs,credits,{},selected,preview=True,lock_preview=True) result=_reserve(db,user,extra_request,plan,certs,credits,{},selected,preview=True,lock_preview=True)
except InsufficientQuota as exc: except InsufficientQuota as exc:
if not auto_cover: if not contract_cover:
raise raise
from app.services.pl_quota_diagnostics import archive_quantity_shortfall_message from app.services.pl_quota_diagnostics import archive_quantity_shortfall_message
cert_rows=[] cert_rows=[]
@@ -703,8 +600,7 @@ def _settle(db,user,r,certs,usages,items,plan):
message=archive_quantity_shortfall_message( message=archive_quantity_shortfall_message(
getattr(exc, 'diagnostics', None), cert_rows, r.actual_by_source, excess, getattr(exc, 'diagnostics', None), cert_rows, r.actual_by_source, excess,
{source.source_id: source.unit for source in r.sources}) {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 ARCHIVE_QUOTA_BLOCK) from exc
raise ArchiveQuotaBlocked(message or fallback) from exc
for kind in ('purchase','transport'): for kind in ('purchase','transport'):
for row in result[kind+'Allocations']: for row in result[kind+'Allocations']:
supplemental.append((kind,row)) supplemental.append((kind,row))
+7 -16
View File
@@ -269,17 +269,7 @@ def mark_ready(db, user, plan_id):
plan = _plan(db, user, plan_id, lock=True) plan = _plan(db, user, plan_id, lock=True)
if plan.follow_status == "cancelled" or plan.archive_status == "cancelled": if plan.follow_status == "cancelled" or plan.archive_status == "cancelled":
raise HTTPException(409, "已作废的计划不能标记证书齐备") raise HTTPException(409, "已作废的计划不能标记证书齐备")
from app.services.pl_cert_quota_rule_config_service import plan_requires_cert_fulfill
if quota_cert_waived(plan): if quota_cert_waived(plan):
# 历史:安排前齐备按空版本当成 legacy,漏写 pending;再次调用时回补。
if (
plan_requires_cert_fulfill(db, user.tenant_no, plan)
and int(getattr(plan, "quota_cert_pending_fulfill", 0) or 0) != 1
):
plan.quota_cert_pending_fulfill = 1
plan.update_by = user.id
db.flush()
labels = _product_names(db, user, [plan.id]) labels = _product_names(db, user, [plan.id])
return _row(plan, labels.get(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(): if not db.query(PlPlan.id).filter(PlPlan.id == plan.id, _toxic_exists(db, user.tenant_no)).first():
@@ -300,7 +290,8 @@ def mark_ready(db, user, plan_id):
plan.quota_cert_waived_by = user.id plan.quota_cert_waived_by = user.id
plan.quota_cert_waived_by_name = name[:100] if name else None plan.quota_cert_waived_by_name = name[:100] if name else None
plan.quota_cert_waived_time = datetime.now() plan.quota_cert_waived_time = datetime.now()
if plan_requires_cert_fulfill(db, user.tenant_no, plan): from app.services.pl_cert_quota_rule_config_service import plan_uses_customer_category
if plan_uses_customer_category(plan):
plan.quota_cert_pending_fulfill = 1 plan.quota_cert_pending_fulfill = 1
change_content = "标记证书齐备:可安排运输;归档前须在证书齐备中完善并关闭" change_content = "标记证书齐备:可安排运输;归档前须在证书齐备中完善并关闭"
else: else:
@@ -322,15 +313,15 @@ def mark_ready(db, user, plan_id):
def list_pending_fulfill_plans(db, user, page=1, page_size=20, keyword=""): def list_pending_fulfill_plans(db, user, page=1, page_size=20, keyword=""):
"""新规则下已齐备、待完善挂证的计划。 """新规则下已齐备、待完善挂证的计划。"""
from app.services.pl_cert_quota_rule_config_service import VERSION_CUSTOMER_CATEGORY
以 pending 为准;安排前版本可能仍为空,不能再要求 cert_quota_rule_version。
"""
query = db.query(PlPlan).filter( query = db.query(PlPlan).filter(
PlPlan.tenant_no == user.tenant_no, PlPlan.tenant_no == user.tenant_no,
PlPlan.del_flag == 0, PlPlan.del_flag == 0,
PlPlan.follow_status != "cancelled", PlPlan.follow_status != "cancelled",
PlPlan.archive_status != "cancelled", PlPlan.archive_status != "cancelled",
PlPlan.cert_quota_rule_version == VERSION_CUSTOMER_CATEGORY,
PlPlan.quota_cert_pending_fulfill == 1, PlPlan.quota_cert_pending_fulfill == 1,
PlPlan.quota_cert_waived == 1, PlPlan.quota_cert_waived == 1,
) )
@@ -354,14 +345,14 @@ def list_pending_fulfill_plans(db, user, page=1, page_size=20, keyword=""):
def fulfill_plan_certs(db, user, plan_id, *, operation_id=None): def fulfill_plan_certs(db, user, plan_id, *, operation_id=None):
"""完善并关闭:按安排同款自动选证并 reserve,成功后出队。""" """完善并关闭:按安排同款自动选证并 reserve,成功后出队。"""
from app.services.pl_cert_quota_rule_config_service import plan_requires_cert_fulfill from app.services.pl_cert_quota_rule_config_service import plan_uses_customer_category
from app.services.pl_plan_service import record_plan_change 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_business import apply_plan_quota
from app.services.pl_quota_planning import _plan from app.services.pl_quota_planning import _plan
from types import SimpleNamespace from types import SimpleNamespace
plan = _plan(db, user, plan_id, lock=True) plan = _plan(db, user, plan_id, lock=True)
if not plan_requires_cert_fulfill(db, user.tenant_no, plan): if not plan_uses_customer_category(plan):
raise HTTPException(409, '仅新规则计划支持完善并关闭') raise HTTPException(409, '仅新规则计划支持完善并关闭')
if int(getattr(plan, 'quota_cert_pending_fulfill', 0) or 0) != 1: if int(getattr(plan, 'quota_cert_pending_fulfill', 0) or 0) != 1:
raise HTTPException(409, '该计划不在证书齐备待完善列表中') raise HTTPException(409, '该计划不在证书齐备待完善列表中')
@@ -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
File diff suppressed because it is too large. Load diff
@@ -249,11 +249,6 @@ def test_same_city_settlement_does_not_require_transport_pairing():
assert validate_allocation_pairing([demand], [purchase], [], []) is None 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)]) @pytest.mark.parametrize('manual_values', [(8,10,0),(18,0,0)])
def test_zero_capacity_foreign_row_cannot_unlock_manual_reordering(manual_values): def test_zero_capacity_foreign_row_cannot_unlock_manual_reordering(manual_values):
from app.services.pl_quota_allocation import Allocation from app.services.pl_quota_allocation import Allocation
+2 -3
View File
@@ -57,7 +57,7 @@ def test_permission_guards_validation_and_atomic_creation(api):
saved = client.post(path, json=payload()) saved = client.post(path, json=payload())
assert saved.status_code == 200 assert saved.status_code == 200
row = saved.json() row = saved.json()
assert row['tenantNo'] == 't' and row['status'] == 'active' and row['openingConfirmed'] is True assert row['tenantNo'] == 't' and row['status'] == 'draft' and row['openingConfirmed'] is False
assert client.put(path + '/' + row['id'], json={'totalQty': '-1'}).status_code == 422 assert client.put(path + '/' + row['id'], json={'totalQty': '-1'}).status_code == 422
assert client.get(path + '/' + row['id']).json()['totalQty'] == '30.000000' assert client.get(path + '/' + row['id']).json()['totalQty'] == '30.000000'
app.dependency_overrides[auth] = lambda: {'role': 'admin', 'user_id': 'u', 'tenant_no': 'other'} app.dependency_overrides[auth] = lambda: {'role': 'admin', 'user_id': 'u', 'tenant_no': 'other'}
@@ -130,8 +130,7 @@ def test_total_adjust_requires_provenance_and_replays_without_duplicate_log(api)
assert response.status_code == 200 assert response.status_code == 200
assert client.post(path, json=body).status_code == 200 assert client.post(path, json=body).status_code == 200
logs = client.get(base + '/' + row['id'] + '/logs').json() logs = client.get(base + '/' + row['id'] + '/logs').json()
adjust_logs = [item for item in logs if item.get('eventType') == 'total_adjust'] assert len(logs) == 1 and logs[0]['totalDelta'] == '5.000000'
assert len(adjust_logs) == 1 and adjust_logs[0]['totalDelta'] == '5.000000'
assert client.post(path, json={**body,'totalQty':'40'}).status_code == 409 assert client.post(path, json={**body,'totalQty':'40'}).status_code == 409
assert client.post(path, json={**body,'operationId':'adjust-2','sourceNote':''}).status_code == 409 assert client.post(path, json={**body,'operationId':'adjust-2','sourceNote':''}).status_code == 409
assert client.get(base + '/' + row['id']).json()['totalQty'] == '35.000000' assert client.get(base + '/' + row['id']).json()['totalQty'] == '35.000000'
+17 -39
View File
@@ -41,31 +41,14 @@ def transport(**kw):
return data return data
def test_save_auto_enables_with_zero_opening(ctx):
"""建档即启用:期初已用默认 0,无需手工期初确认。"""
db, u, s, m = ctx
row = s.save_cert(db, u, 'purchase', purchase())
assert row['status'] == 'active'
assert row['openingConfirmed'] is True
assert row['usedQty'] == Decimal('0')
assert row['verifiedBy'] == 'u'
assert row['verifiedTime'] is not None
log = db.query(m.PlCertQtyLog).filter_by(del_flag=0, event_type='opening').one()
assert (log.event_snapshot or {}).get('auto') is True
transport_row = s.save_cert(db, u, 'transport', transport())
assert transport_row['status'] == 'active' and transport_row['openingConfirmed'] is True
def test_manual_optional_image_complete_fields(ctx): def test_manual_optional_image_complete_fields(ctx):
db,u,s,m = ctx db,u,s,m = ctx
data = purchase(buyerAddress='地址', buyerPhone='电话', buyerLegalRepresentative='甲', sellerAddress='乙址', sellerPhone='乙电话', sellerLegalRepresentative='乙', purchasePurpose='用途', issueDate='2026-01-01', validFrom='2026-01-01', validTo='2027-01-01') data = purchase(buyerAddress='地址', buyerPhone='电话', buyerLegalRepresentative='甲', sellerAddress='乙址', sellerPhone='乙电话', sellerLegalRepresentative='乙', purchasePurpose='用途', issueDate='2026-01-01', validFrom='2026-01-01', validTo='2027-01-01')
row = s.save_cert(db,u,'purchase',data) row = s.save_cert(db,u,'purchase',data)
assert row['buyerAddress'] == '地址' and row['attachmentUrls'] is None assert row['buyerAddress'] == '地址' and row['attachmentUrls'] is None
assert row['totalQty'] == Decimal('100.123456') assert row['totalQty'] == Decimal('100.123456')
assert row['status'] == 'active' assert row['status'] == 'draft'
assert row['openingConfirmed'] is True assert db.query(m.PlCertQtyLog).count() == 0
assert row['usedQty'] == Decimal('0')
assert db.query(m.PlCertQtyLog).filter_by(del_flag=0, event_type='opening').count() == 1
db.rollback() db.rollback()
assert db.query(m.PlPurchaseCert).count() == 0 assert db.query(m.PlPurchaseCert).count() == 0
@@ -73,8 +56,9 @@ def test_manual_optional_image_complete_fields(ctx):
def test_opening_confirmation_remains_visible_after_reverification_required(ctx): def test_opening_confirmation_remains_visible_after_reverification_required(ctx):
db, user, svc, models = ctx db, user, svc, models = ctx
row = svc.save_cert(db, user, 'purchase', purchase()) row = svc.save_cert(db, user, 'purchase', purchase())
assert row['openingConfirmed'] is True assert row['openingConfirmed'] is False
assert row['status'] == 'active' row = svc.confirm_cert(db, user, 'purchase', row['id'], {
'operationId': 'op-ui', 'usedQty': '0', 'singleUseConsumed': False, 'reason': '全新证'})
changed = svc.save_cert(db, user, 'purchase', {'buyerAddress': '更正地址'}, row['id']) changed = svc.save_cert(db, user, 'purchase', {'buyerAddress': '更正地址'}, row['id'])
assert changed['verifiedTime'] is None assert changed['verifiedTime'] is None
assert changed['openingConfirmed'] is True assert changed['openingConfirmed'] is True
@@ -105,12 +89,10 @@ def test_reference_delta_omitted_empty_and_invalid_prewrite(ctx):
def test_confirmation_and_history_protection(ctx): def test_confirmation_and_history_protection(ctx):
db,u,s,m=ctx db,u,s,m=ctx
row=s.save_cert(db,u,'purchase',purchase()) row=s.save_cert(db,u,'purchase',purchase())
assert row['status']=='active' and row['openingConfirmed'] is True
with pytest.raises((HTTPException,ValidationError)): s.confirm_cert(db,u,'purchase',row['id'],{'usedQty':'0','singleUseConsumed':True,'reason':'核对','operationId':'op'}) with pytest.raises((HTTPException,ValidationError)): s.confirm_cert(db,u,'purchase',row['id'],{'usedQty':'0','singleUseConsumed':True,'reason':'核对','operationId':'op'})
row=s.confirm_cert(db,u,'purchase',row['id'],{'usedQty':'0','singleUseConsumed':True,'reason':'核对','evidenceUrls':'https://minio/evidence','operationId':'op'}) row=s.confirm_cert(db,u,'purchase',row['id'],{'usedQty':'0','singleUseConsumed':True,'reason':'核对','evidenceUrls':'https://minio/evidence','operationId':'op'})
assert row['openingSingleUseConsumed']==1 and row['status']=='active' assert row['openingSingleUseConsumed']==1 and row['status']=='active'
assert db.query(m.PlCertQtyLog).filter_by(del_flag=0).one().event_type=='opening' assert db.query(m.PlCertQtyLog).one().event_type=='opening'
# 建档自动期初后身份已锁定;手工覆盖期初后同样不可改核定量/证号。
for data in ({'quantityUnit':'千克'},{'certNo':'new'},{'totalQty':'90'}): for data in ({'quantityUnit':'千克'},{'certNo':'new'},{'totalQty':'90'}):
with pytest.raises(HTTPException): s.save_cert(db,u,'purchase',data,row['id']) with pytest.raises(HTTPException): s.save_cert(db,u,'purchase',data,row['id'])
with pytest.raises(HTTPException): s.delete_cert(db,u,'purchase',row['id']) with pytest.raises(HTTPException): s.delete_cert(db,u,'purchase',row['id'])
@@ -169,9 +151,8 @@ def test_opening_retry_preserves_balance_and_operation_identity(ctx):
db.query(m.PlPurchaseCert).one().used_qty=Decimal('5') db.query(m.PlPurchaseCert).one().used_qty=Decimal('5')
retry=s.confirm_cert(db,u,'purchase',row['id'],opening()) retry=s.confirm_cert(db,u,'purchase',row['id'],opening())
assert retry['usedQty']==Decimal('5') assert retry['usedQty']==Decimal('5')
assert db.query(m.PlCertQtyLog).filter_by(del_flag=0).count()==1 assert db.query(m.PlCertQtyLog).count()==1
# 自动期初操作号 + 手工期初操作号;重放不新增手工操作 assert db.query(m.PlCertOperation).count()==1
assert db.query(m.PlCertOperation).filter_by(operation_id='opening').count()==1
with pytest.raises(HTTPException): s.confirm_cert(db,u,'purchase',row['id'],opening(usedQty='7')) with pytest.raises(HTTPException): s.confirm_cert(db,u,'purchase',row['id'],opening(usedQty='7'))
with pytest.raises(HTTPException): s.confirm_cert(db,u,'purchase',row['id'],opening(operationId='second')) with pytest.raises(HTTPException): s.confirm_cert(db,u,'purchase',row['id'],opening(operationId='second'))
@@ -228,11 +209,10 @@ def test_reverify_after_correction_keeps_opening_and_balances(ctx):
assert corrected['status']=='suspended' and corrected['verifiedBy'] is None assert corrected['status']=='suspended' and corrected['verifiedBy'] is None
result=s.verify_cert(db,u,'purchase',row['id'],{'operationId':'verify-1','reason':'地址更正核对','evidenceUrls':'https://minio/evidence'}) result=s.verify_cert(db,u,'purchase',row['id'],{'operationId':'verify-1','reason':'地址更正核对','evidenceUrls':'https://minio/evidence'})
assert result['status']=='active' and result['usedQty']==Decimal('5') assert result['status']=='active' and result['usedQty']==Decimal('5')
assert db.query(m.PlCertQtyLog).filter_by(del_flag=0).count()==1 assert db.query(m.PlCertQtyLog).count()==1
# 自动期初 + 手工期初 + 复核 assert db.query(m.PlCertOperation).count()==2
assert db.query(m.PlCertOperation).count()==3
result=s.verify_cert(db,u,'purchase',row['id'],{'operationId':'verify-1','reason':'地址更正核对','evidenceUrls':'https://minio/evidence'}) result=s.verify_cert(db,u,'purchase',row['id'],{'operationId':'verify-1','reason':'地址更正核对','evidenceUrls':'https://minio/evidence'})
assert db.query(m.PlCertOperation).count()==3 assert db.query(m.PlCertOperation).count()==2
def test_actual_scope_denies_user_without_roles(ctx): def test_actual_scope_denies_user_without_roles(ctx):
@@ -281,7 +261,7 @@ def test_historical_opening_accepts_written_source_without_image(ctx):
row=s.save_cert(db,u,'purchase',purchase()) row=s.save_cert(db,u,'purchase',purchase())
result=s.confirm_cert(db,u,'purchase',row['id'],{'operationId':'written-source','usedQty':'5','singleUseConsumed':True,'reason':'历史核对','sourceNote':'2026年10月纸质台账第3页,经张三核实'}) result=s.confirm_cert(db,u,'purchase',row['id'],{'operationId':'written-source','usedQty':'5','singleUseConsumed':True,'reason':'历史核对','sourceNote':'2026年10月纸质台账第3页,经张三核实'})
assert result['usedQty']==Decimal('5') and result['status']=='active' assert result['usedQty']==Decimal('5') and result['status']=='active'
assert db.query(m.PlCertQtyLog).filter_by(del_flag=0).one().event_snapshot['sourceNote'].startswith('2026') assert db.query(m.PlCertQtyLog).one().event_snapshot['sourceNote'].startswith('2026')
def test_unknown_use_text_is_preserved_and_requires_confirmation(ctx): def test_unknown_use_text_is_preserved_and_requires_confirmation(ctx):
@@ -443,7 +423,7 @@ def test_opening_verify_stale_operation_snapshot_uses_unique_insert_arbitration(
result=fn(db,u,'purchase',p['id'],body) result=fn(db,u,'purchase',p['id'],body)
assert missed and result['id']==p['id'] assert missed and result['id']==p['id']
assert db.query(m.PlCertOperation).count()==count assert db.query(m.PlCertOperation).count()==count
assert db.query(m.PlCertQtyLog).filter_by(del_flag=0).count()==1 assert db.query(m.PlCertQtyLog).count()==1
def test_opening_and_verify_allow_blank_reason(ctx): def test_opening_and_verify_allow_blank_reason(ctx):
@@ -451,7 +431,7 @@ def test_opening_and_verify_allow_blank_reason(ctx):
p=s.save_cert(db,u,'purchase',purchase()) p=s.save_cert(db,u,'purchase',purchase())
row=s.confirm_cert(db,u,'purchase',p['id'],{**opening(),'reason':' '}) row=s.confirm_cert(db,u,'purchase',p['id'],{**opening(),'reason':' '})
assert row['status']=='active' assert row['status']=='active'
assert db.query(m.PlCertQtyLog).filter_by(del_flag=0).one().reason=='' assert db.query(m.PlCertQtyLog).one().reason==''
s.save_cert(db,u,'purchase',{'buyerAddress':'更正地址'},p['id']) s.save_cert(db,u,'purchase',{'buyerAddress':'更正地址'},p['id'])
verified=s.verify_cert(db,u,'purchase',p['id'],{'operationId':'verify-blank','reason':''}) verified=s.verify_cert(db,u,'purchase',p['id'],{'operationId':'verify-blank','reason':''})
assert verified['status']=='active' and verified['verifiedTime'] assert verified['status']=='active' and verified['verifiedTime']
@@ -460,12 +440,10 @@ def test_opening_and_verify_allow_blank_reason(ctx):
def test_rejected_opening_rolls_back_claimed_operation(ctx): def test_rejected_opening_rolls_back_claimed_operation(ctx):
db,u,s,m=ctx db,u,s,m=ctx
p=s.save_cert(db,u,'purchase',purchase()) p=s.save_cert(db,u,'purchase',purchase())
auto_ops = db.query(m.PlCertOperation).count()
auto_logs = db.query(m.PlCertQtyLog).filter_by(del_flag=0).count()
with pytest.raises(HTTPException): with pytest.raises(HTTPException):
s.confirm_cert(db,u,'purchase',p['id'],{**opening(),'usedQty':'999'}) s.confirm_cert(db,u,'purchase',p['id'],{**opening(),'usedQty':'999'})
assert db.query(m.PlCertOperation).count()==auto_ops assert db.query(m.PlCertOperation).count()==0
assert db.query(m.PlCertQtyLog).filter_by(del_flag=0).count()==auto_logs assert db.query(m.PlCertQtyLog).count()==0
def test_replay_reads_current_certificate_and_opening_not_old_snapshot(ctx,monkeypatch): def test_replay_reads_current_certificate_and_opening_not_old_snapshot(ctx,monkeypatch):
@@ -494,7 +472,7 @@ def test_closed_certificate_keeps_history_and_cannot_be_reopened(ctx):
used = confirmed['usedQty'] used = confirmed['usedQty']
closed = s.save_cert(db, u, 'purchase', {'status': 'closed'}, row['id']) closed = s.save_cert(db, u, 'purchase', {'status': 'closed'}, row['id'])
assert closed['status'] == 'closed' and closed['usedQty'] == used assert closed['status'] == 'closed' and closed['usedQty'] == used
assert db.query(m.PlCertQtyLog).filter_by(del_flag=0).count() == 1 assert db.query(m.PlCertQtyLog).count() == 1
for action, payload in ( for action, payload in (
('confirm', {**opening(), 'operationId': 'reopen-opening'}), ('confirm', {**opening(), 'operationId': 'reopen-opening'}),
('verify', {'operationId': 'reopen-verify', 'reason': '重新启用'}), ('verify', {'operationId': 'reopen-verify', 'reason': '重新启用'}),
@@ -64,44 +64,6 @@ def test_create_with_bindings_and_bad_create_has_no_pending_row(case):
assert result['id'] not in ('g1', 'g2') 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): 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.services import pl_quota_cert_bindings as svc
from app.models.crm_models import CrmContract from app.models.crm_models import CrmContract
+2 -105
View File
@@ -98,31 +98,6 @@ def test_zero_reservation_consumes_once_slot(case):
assert c.db.query(c.m.PlPlanCertUsage).count()==2 assert c.db.query(c.m.PlPlanCertUsage).count()==2
with pytest.raises(ValueError): run(c,operation_id='other',plan_id='other',sources=sources) 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): def test_same_cert_balance_covers_actual_above_reservation(case):
c = case c = case
run(c) 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 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): def test_same_cert_without_enough_balance_asks_for_another_certificate(case):
c = case c = case
c.db.get(c.m.PlPurchaseCert, 'p').total_qty = 30 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() p.opening_single_use_consumed=0; p.valid_to=date(2000,1,1); c.db.flush()
with pytest.raises(ValueError): run(c) with pytest.raises(ValueError): run(c)
p.valid_to=date(2099,12,31); c.db.flush() 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): 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 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() 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'] 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']) 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): def test_no_cert_operation_is_still_idempotent(case):
c=case c=case
first=run(c,sources=[],purchase_cert_ids=[],transport_cert_ids=[]) 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 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 all(u.reserved_qty==29 for u in c.db.query(c.m.PlPlanCertUsage).all())
assert c.db.query(c.m.PlCertOperation).count()==1 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
-170
View File
@@ -113,9 +113,6 @@ def test_mark_ready_allows_weighed_plan_until_quota_is_posted(monkeypatch):
quota_cert_waived_by=None, quota_cert_waived_by=None,
quota_cert_waived_by_name=None, quota_cert_waived_by_name=None,
quota_cert_waived_time=None, quota_cert_waived_time=None,
quota_cert_pending_fulfill=0,
cert_quota_rule_version="legacy",
cert_quota_arranged_at=__import__("datetime").datetime(2026, 11, 1, 10, 0, 0),
update_by=None, update_by=None,
plan_no="PO1", plan_no="PO1",
plan_date=None, plan_date=None,
@@ -176,173 +173,6 @@ def test_mark_ready_allows_weighed_plan_until_quota_is_posted(monkeypatch):
raise AssertionError("已入账仍允许证书齐备") raise AssertionError("已入账仍允许证书齐备")
def test_mark_ready_before_arrange_uses_effective_at_for_pending(monkeypatch):
"""安排前版本未打标时,仍按生效时间走新规则并进入待完善。"""
from datetime import datetime, timedelta
from app.models.pl_quota_models import PlPlanCertUsage
from app.services.pl_quota_waiver import mark_ready
plan = SimpleNamespace(
id="p1",
follow_status="draft",
archive_status="unarchived",
quota_cert_waived=0,
quota_cert_waived_by=None,
quota_cert_waived_by_name=None,
quota_cert_waived_time=None,
quota_cert_pending_fulfill=0,
cert_quota_rule_version=None,
cert_quota_arranged_at=None,
update_by=None,
plan_no="PO1",
plan_date=None,
license_plate=None,
supplier_name=None,
customer_name=None,
)
user = SimpleNamespace(id="u1", tenant_no="shanxia2.0", name="齐备员", dept_id="")
changes = []
class Query:
def __init__(self, rows):
self.rows = rows
def filter(self, *args, **kwargs):
return self
def filter_by(self, **kwargs):
return self
def all(self):
return list(self.rows)
def first(self):
return self.rows[0] if self.rows else None
class DB:
def query(self, model):
if model is PlPlanCertUsage:
return Query([])
return Query([plan])
def flush(self):
return None
monkeypatch.setattr("app.services.pl_quota_planning._plan", lambda *args, **kwargs: plan)
monkeypatch.setattr("app.services.pl_quota_waiver._toxic_exists", lambda *args, **kwargs: True)
monkeypatch.setattr("app.services.pl_quota_waiver._product_names", lambda *args, **kwargs: {})
monkeypatch.setattr(
"app.services.pl_plan_service.record_plan_change",
lambda *args, **kwargs: changes.append(kwargs),
)
monkeypatch.setattr(
"app.services.pl_cert_quota_rule_config_service.get_effective_at",
lambda *args, **kwargs: datetime.now() - timedelta(hours=1),
)
mark_ready(DB(), user, "p1")
assert plan.quota_cert_waived == 1
assert plan.quota_cert_pending_fulfill == 1
assert changes and "完善并关闭" in (changes[-1].get("change_content") or "")
def test_mark_ready_stamped_legacy_skips_pending(monkeypatch):
"""已按首次安排打成 legacy 的计划,齐备不进待完善。"""
from datetime import datetime
from app.models.pl_quota_models import PlPlanCertUsage
from app.services.pl_quota_waiver import mark_ready
plan = SimpleNamespace(
id="p1",
follow_status="arranged",
archive_status="unarchived",
quota_cert_waived=0,
quota_cert_waived_by=None,
quota_cert_waived_by_name=None,
quota_cert_waived_time=None,
quota_cert_pending_fulfill=0,
cert_quota_rule_version="legacy",
cert_quota_arranged_at=datetime(2026, 11, 1, 10, 0, 0),
update_by=None,
plan_no="PO1",
plan_date=None,
license_plate=None,
supplier_name=None,
customer_name=None,
)
user = SimpleNamespace(id="u1", tenant_no="shanxia2.0", name="齐备员", dept_id="")
changes = []
class Query:
def __init__(self, rows):
self.rows = rows
def filter(self, *args, **kwargs):
return self
def filter_by(self, **kwargs):
return self
def all(self):
return list(self.rows)
def first(self):
return self.rows[0] if self.rows else None
class DB:
def query(self, model):
if model is PlPlanCertUsage:
return Query([])
return Query([plan])
def flush(self):
return None
monkeypatch.setattr("app.services.pl_quota_planning._plan", lambda *args, **kwargs: plan)
monkeypatch.setattr("app.services.pl_quota_waiver._toxic_exists", lambda *args, **kwargs: True)
monkeypatch.setattr("app.services.pl_quota_waiver._product_names", lambda *args, **kwargs: {})
monkeypatch.setattr(
"app.services.pl_plan_service.record_plan_change",
lambda *args, **kwargs: changes.append(kwargs),
)
monkeypatch.setattr(
"app.services.pl_cert_quota_rule_config_service.get_effective_at",
lambda *args, **kwargs: datetime(2026, 11, 15, 20, 0, 0),
)
mark_ready(DB(), user, "p1")
assert plan.quota_cert_waived == 1
assert plan.quota_cert_pending_fulfill == 0
assert changes and "不再校验" in (changes[-1].get("change_content") or "")
def test_stamp_arrange_backfills_pending_when_already_waived(monkeypatch):
"""安排打成新规则时,若已齐备则回补待完善。"""
from datetime import datetime
from app.services.pl_cert_quota_rule_config_service import (
VERSION_CUSTOMER_CATEGORY,
stamp_plan_rule_on_arrange,
)
plan = SimpleNamespace(
cert_quota_arranged_at=None,
cert_quota_rule_version=None,
quota_cert_waived=1,
quota_cert_pending_fulfill=0,
)
user = SimpleNamespace(tenant_no="shanxia2.0")
monkeypatch.setattr(
"app.services.pl_cert_quota_rule_config_service.resolve_rule_version_for_arrange",
lambda *args, **kwargs: VERSION_CUSTOMER_CATEGORY,
)
version = stamp_plan_rule_on_arrange(None, user, plan, arrange_time=datetime(2026, 11, 16, 14, 0, 0))
assert version == VERSION_CUSTOMER_CATEGORY
assert plan.quota_cert_pending_fulfill == 1
def test_waived_arrange_check_keeps_source_errors_and_skips_cert_balance(monkeypatch): def test_waived_arrange_check_keeps_source_errors_and_skips_cert_balance(monkeypatch):
from app.services.pl_quota_planning import contract_cert_arrange_block from app.services.pl_quota_planning import contract_cert_arrange_block
@@ -1,28 +0,0 @@
-- 证件额度切点改为首次安排时间:补 arranged_at 列,并按运输单创建时间回填已安排计划。
-- MySQL 5.7。可重复执行。
SET NAMES utf8mb4;
SET @schema_name = DATABASE();
SET @col = (SELECT COUNT(*) FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA=@schema_name AND TABLE_NAME='pl_plan' AND COLUMN_NAME='cert_quota_arranged_at');
SET @sql = IF(@col=0,
'ALTER TABLE pl_plan ADD COLUMN cert_quota_arranged_at datetime DEFAULT NULL COMMENT ''首次安排时间(证件额度切点用);再次安排不改'' AFTER cert_quota_rule_version',
'SELECT 1');
PREPARE s FROM @sql; EXECUTE s; DEALLOCATE PREPARE s;
-- 已安排:回填首次安排时刻,并按「安排时刻 vs 生效时间」校正规则版本(修正历史按创建打标)。
UPDATE pl_plan p
INNER JOIN pl_transport t
ON t.id = p.transport_id AND t.tenant_no = p.tenant_no AND t.del_flag = 0
LEFT JOIN pl_cert_quota_rule_config cfg
ON cfg.tenant_no = p.tenant_no AND cfg.del_flag = 0
SET
p.cert_quota_arranged_at = COALESCE(p.cert_quota_arranged_at, t.create_time),
p.cert_quota_rule_version = CASE
WHEN cfg.effective_at IS NOT NULL
AND COALESCE(p.cert_quota_arranged_at, t.create_time) >= cfg.effective_at
THEN 'customer_category'
ELSE 'legacy'
END
WHERE p.del_flag = 0
AND p.transport_status = 'arranged';
@@ -1,28 +0,0 @@
-- 证件额度切点改为首次安排时间:补 arranged_at 列,并按运输单创建时间回填已安排计划。
-- MySQL 5.7。可重复执行。
SET NAMES utf8mb4;
SET @schema_name = DATABASE();
SET @col = (SELECT COUNT(*) FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA=@schema_name AND TABLE_NAME='pl_plan' AND COLUMN_NAME='cert_quota_arranged_at');
SET @sql = IF(@col=0,
'ALTER TABLE pl_plan ADD COLUMN cert_quota_arranged_at datetime DEFAULT NULL COMMENT ''首次安排时间(证件额度切点用);再次安排不改'' AFTER cert_quota_rule_version',
'SELECT 1');
PREPARE s FROM @sql; EXECUTE s; DEALLOCATE PREPARE s;
-- 已安排:回填首次安排时刻,并按「安排时刻 vs 生效时间」校正规则版本(修正历史按创建打标)。
UPDATE pl_plan p
INNER JOIN pl_transport t
ON t.id = p.transport_id AND t.tenant_no = p.tenant_no AND t.del_flag = 0
LEFT JOIN pl_cert_quota_rule_config cfg
ON cfg.tenant_no = p.tenant_no AND cfg.del_flag = 0
SET
p.cert_quota_arranged_at = COALESCE(p.cert_quota_arranged_at, t.create_time),
p.cert_quota_rule_version = CASE
WHEN cfg.effective_at IS NOT NULL
AND COALESCE(p.cert_quota_arranged_at, t.create_time) >= cfg.effective_at
THEN 'customer_category'
ELSE 'legacy'
END
WHERE p.del_flag = 0
AND p.transport_status = 'arranged';
@@ -1,16 +0,0 @@
-- 合同用证 → 客户用证(菜单展示名);保留菜单 ID 与权限码。
SET NAMES utf8mb4;
START TRANSACTION;
UPDATE sys_menu
SET menu_name = '客户用证', update_time = NOW()
WHERE del_flag = 0
AND (
id = 'PL_CONTRACT_QUOTA'
OR (path = 'contract-quota' AND perms = 'pl:quota-cert:list')
OR id = 'MINI_PL_CERT_CONTRACT'
OR perms = 'mini:pl:contract-quota:list'
)
AND menu_name = '合同用证';
COMMIT;
@@ -1,30 +0,0 @@
# 证件额度切点:按首次安排时间(设计)
工单:[#40](https://gitea.aichengyan.com/cykj/shanxia2.0/issues/40)
## 背景
原设计按计划 `create_time` 与 `effective_at` 比较打 `cert_quota_rule_version`。业务要求改为按**首次安排运输**时刻切点;切点前已安排的计划归档不再校购买证/运输证。
## 定稿规则
1. **未配置 `effective_at`**:安排仍 409 拦住(不变)。
2. **首次安排**时写入:
- `cert_quota_arranged_at = 安排时刻`
- `cert_quota_rule_version = customer_category` 若 `安排时刻 >= effective_at`,否则 `legacy`
3. **再次调整运输**:不重打 `cert_quota_arranged_at` / `cert_quota_rule_version`(冻结首次安排)。
4. **创建计划**:不再按创建时间打标(可空,待安排时写入)。
5. **归档**:
- `legacy`(切点前首次安排):不校验、不扣购买证/运输证,额度结转按跳过处理,允许直接归档。
- `customer_category`:保持现有最新业务逻辑(选证、齐备仅放行安排、归档须真证等)。
6. **历史已安排且缺 `cert_quota_arranged_at`**:归档/读规则时用关联 `pl_transport.create_time` 推断;若推断时刻 `< effective_at` 视为 `legacy` 祖父。
## 范围
- backend:切点服务、安排打标、归档跳过、迁移列
- web-admin:系统信息「运输证件规则」说明文案
## 非目标
- 不批量改历史 `quota_cert_waived`
- 不改选证算法本身
+1 -1
View File
@@ -9,5 +9,5 @@ allowBuilds:
core-js: false core-js: false
es5-ext: false es5-ext: false
esbuild: true esbuild: true
protobufjs: true protobufjs: false
vue-demi: true vue-demi: true
@@ -1,54 +0,0 @@
import assert from 'node:assert/strict'
import test from 'node:test'
import { resolveArchiveQuotaBlockMode } from '../src/utils/pl-archive-quota-block'
test('pending fulfill plan only alerts, no certificate-ready confirm', () => {
assert.equal(
resolveArchiveQuotaBlockMode(
'实际数量已保存,证件没有扣减。请把实际数量改小,或先补充购买证和运输证,再重新归档。',
'用证没有完成',
{ quotaCertPendingFulfill: 1, quotaCertWaived: 1 }
),
'alert-pending'
)
})
test('already waived plan does not offer archive-time certificate ready', () => {
assert.equal(
resolveArchiveQuotaBlockMode('余额不足', '用证没有完成', { quotaCertWaived: 1 }),
'alert-pending'
)
})
test('pending keywords still force alert mode without plan flags', () => {
assert.equal(
resolveArchiveQuotaBlockMode(
'该计划仍处于证书齐备待完善,请先在证书齐备中完善并关闭后再归档',
'用证没有完成',
{}
),
'alert-pending'
)
})
test('unmarked quota block only alerts, never offers certificate ready', () => {
assert.equal(
resolveArchiveQuotaBlockMode(
'实际数量已保存,证件没有扣减。请把实际数量改小,或先补充购买证和运输证,再重新归档。',
'用证没有完成',
{ quotaCertPendingFulfill: 0, quotaCertWaived: 0 }
),
'alert-plain'
)
})
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'
)
})
@@ -25,20 +25,6 @@ test('incomplete certificate filter is sent as quotaCertWaivedIn=0', () => {
assert.deepEqual(params, { quotaCertWaivedIn: '0' }) assert.deepEqual(params, { quotaCertWaivedIn: '0' })
}) })
test('fulfill tab selection column is first among table columns', () => {
const web = readFileSync(new URL('../src/views/pl/cert-ready/index.vue', import.meta.url), 'utf8')
const selectionIdx = web.indexOf('type="selection"')
const columnsIdx = web.indexOf('v-for="column in columns"')
const actionsIdx = web.indexOf('label="操作"')
assert.ok(selectionIdx > 0, 'selection column missing')
assert.ok(columnsIdx > selectionIdx, 'selection must precede business columns')
assert.ok(actionsIdx > columnsIdx, 'actions must follow business columns')
assert.match(
web,
/v-if="listMode === 'fulfill'"[\s\S]*?type="selection"[\s\S]*?v-for="column in columns"/
)
})
test('web funnel and miniprogram status dropdown default to incomplete', () => { test('web funnel and miniprogram status dropdown default to incomplete', () => {
const web = readFileSync(new URL('../src/views/pl/cert-ready/index.vue', import.meta.url), 'utf8') const web = readFileSync(new URL('../src/views/pl/cert-ready/index.vue', import.meta.url), 'utf8')
const mobile = readFileSync( const mobile = readFileSync(
+4 -17
View File
@@ -203,14 +203,13 @@ test('real template keeps plans quota proof order and separate lazy contract sco
canViewQuotaCert: true, canViewQuotaCert: true,
canViewProof: true, canViewProof: true,
detailActiveTab: 'proof', detailActiveTab: 'proof',
detailContract: { id: 42, customerId: 'cust-42' } detailContract: { id: 42 }
} }
const rows = panes(ctx) const rows = panes(ctx)
assert.deepEqual( assert.deepEqual(
rows.map((v: any) => v.props.name), rows.map((v: any) => v.props.name),
['plans', 'quota', 'proof'] ['plans', 'quota', 'proof']
) )
assert.equal(rows[1].props.label, '客户证件与额度')
assert.equal(rows[2].props.label, '运输计划合法使用证明') assert.equal(rows[2].props.label, '运输计划合法使用证明')
assert.equal(rows[2].props.lazy, '') assert.equal(rows[2].props.lazy, '')
assert.equal(panel(rows[1]), undefined) assert.equal(panel(rows[1]), undefined)
@@ -220,19 +219,14 @@ test('real template keeps plans quota proof order and separate lazy contract sco
assert.equal(proof.props.active, true) assert.equal(proof.props.active, true)
assert.equal(proof.props.embedded, '') assert.equal(proof.props.embedded, '')
ctx.detailContract.id = 43 ctx.detailContract.id = 43
ctx.detailContract.customerId = 'cust-43'
ctx.currentDetailId = 43 ctx.currentDetailId = 43
assert.equal(panel(panes(ctx)[2]).key, 43) assert.equal(panel(panes(ctx)[2]).key, 43)
ctx.detailActiveTab = 'quota'
const quota = panel(panes(ctx)[1])
assert.equal(quota.type?.name || quota.type, 'CustomerCertQuotaPanel')
assert.equal(quota.props['customer-id'] ?? quota.props.customerId, 'cust-43')
assert.equal(quota.props.active, true)
ctx.canViewQuotaCert = false ctx.canViewQuotaCert = false
assert.deepEqual( assert.deepEqual(
panes(ctx).map((v: any) => v.props.name), panes(ctx).map((v: any) => v.props.name),
['plans', 'proof'] ['plans', 'proof']
) )
ctx.detailActiveTab = 'quota'
assert.equal(panel(panes(ctx)[1]), undefined) assert.equal(panel(panes(ctx)[1]), undefined)
}) })
@@ -271,14 +265,7 @@ test('mounted template unmounts old contract and never mounts quota for proof-on
} }
}), }),
StopDocuments: Child('proof'), StopDocuments: Child('proof'),
CustomerCertQuotaPanel: vue.defineComponent({ ContractQuotaPanel: Child('quota'),
props: ['customerId', 'active'],
setup(props) {
lifecycle.push(`mount:quota:${props.customerId}`)
vue.onBeforeUnmount(() => lifecycle.push(`unmount:quota:${props.customerId}`))
return () => vue.h('span')
}
}),
PlContractLinkedPlansPanel: vue.defineComponent({ PlContractLinkedPlansPanel: vue.defineComponent({
setup() { setup() {
return () => vue.h('span') return () => vue.h('span')
@@ -295,7 +282,7 @@ test('mounted template unmounts old contract and never mounts quota for proof-on
canViewQuotaCert: false, canViewQuotaCert: false,
canViewProof: true, canViewProof: true,
detailActiveTab: 'proof', detailActiveTab: 'proof',
detailContract: { id: 'A', customerId: 'cust-A' } detailContract: { id: 'A' }
}) })
const renderer = vue.createRenderer<any, any>({ const renderer = vue.createRenderer<any, any>({
createElement: () => ({ children: [] }), createElement: () => ({ children: [] }),
@@ -1,126 +0,0 @@
import test from 'node:test'
import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
test('web contract detail embeds customer cert panel and renamed tab', () => {
const source = readFileSync(
new URL('../src/views/crm/contract/components/ContractDetailDialog.vue', import.meta.url),
'utf8'
)
assert.match(source, /label="客户证件与额度"/)
assert.match(source, /CustomerCertQuotaPanel/)
assert.doesNotMatch(source, /ContractQuotaPanel/)
assert.match(source, /:customer-id="detailContract\.customerId"/)
})
test('h5 contract detail includes customer cert tab', () => {
const source = readFileSync(
new URL('../src/views/m/crm/contract/detail.vue', import.meta.url),
'utf8'
)
assert.match(source, /CustomerCertQuotaTab/)
assert.match(source, /客户证件与额度/)
assert.match(source, /canViewQuotaCert/)
assert.match(source, /:customer-id="contract\.customerId"/)
})
test('customer cert panel lists by customerId without contract bindings', () => {
const source = readFileSync(
new URL('../src/views/pl/contract-quota/CustomerCertQuotaPanel.vue', import.meta.url),
'utf8'
)
assert.match(source, /quotaCertApi\.list\('purchase', \{ customerId \}\)/)
assert.match(source, /quotaCertApi\.list\('transport', \{ customerId \}\)/)
assert.match(source, /有效次数/)
assert.match(source, /singleUseConsumed/)
assert.doesNotMatch(source, /saveBindings|openCreate|bindings\(/)
})
test('standalone contract-quota page is customer quota list', () => {
const panel = readFileSync(
new URL('../src/views/pl/contract-quota/CustomerQuotaPanel.vue', import.meta.url),
'utf8'
)
const wrapper = readFileSync(
new URL('../src/views/pl/contract-quota/ContractQuotaPanel.vue', import.meta.url),
'utf8'
)
const router = readFileSync(new URL('../src/router/modules/pl.ts', import.meta.url), 'utf8')
assert.match(panel, /客户用证/)
assert.match(panel, /quotaStatisticsApi\.customers/)
assert.match(wrapper, /CustomerQuotaPanel/)
assert.match(router, /title: '客户用证'/)
})
test('web customer quota panel uses toQueryParams from useServerColumnFilters', () => {
const panel = readFileSync(
new URL('../src/views/pl/contract-quota/CustomerQuotaPanel.vue', import.meta.url),
'utf8'
)
assert.match(panel, /toQueryParams/)
assert.match(panel, /\.\.\.toQueryParams\(\)/)
assert.doesNotMatch(panel, /\bbuildQuery\b/)
assert.doesNotMatch(panel, /\bresetFilters\b/)
assert.match(panel, /clearAllFilters/)
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),
'utf8'
)
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/
)
})
@@ -1,46 +0,0 @@
/**
* 顶栏侧栏收起按钮必须始终可见:
* - persist afterRestore 强制 ensureMenuButtonVisible(禁止 toggle)
* - AppLayout 挂载时再次兜底
* - 设置面板不再提供可关闭开关
*/
import test from 'node:test'
import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
import { dirname, join } from 'node:path'
import { fileURLToPath } from 'node:url'
const root = join(dirname(fileURLToPath(import.meta.url)), '..')
test('setting store forces menu button visible on restore', () => {
const src = readFileSync(join(root, 'src/store/modules/setting.ts'), 'utf8')
assert.match(src, /ensureMenuButtonVisible\s*=\s*\(\)\s*=>\s*\{[\s\S]*?showMenuButton\.value\s*=\s*true/)
assert.match(src, /afterRestore:\s*\(ctx\)\s*=>\s*\{[\s\S]*?ensureMenuButtonVisible\(\)/)
assert.doesNotMatch(
src,
/afterRestore:[\s\S]*?if\s*\(\s*!ctx\.store\.showMenuButton\s*\)[\s\S]*?setButton\(\)/,
'afterRestore must not rely on setButton toggle'
)
assert.match(
src,
/const setButton = \(\) => \{\s*showMenuButton\.value = true/,
'setButton must assign true, not toggle'
)
})
test('AppLayout mount ensures menu button visible', () => {
const src = readFileSync(join(root, 'src/views/index/index.vue'), 'utf8')
assert.match(src, /ensureMenuButtonVisible\(\)/)
})
test('settings panel does not expose showMenuButton switch', () => {
const src = readFileSync(
join(root, 'src/components/core/layouts/art-settings-panel/composables/useSettingsConfig.ts'),
'utf8'
)
assert.doesNotMatch(
src,
/key:\s*'showMenuButton'/,
'settings UI must not allow turning off the fold control'
)
})
@@ -12,36 +12,18 @@ import { parse } from '@vue/compiler-sfc'
const root = join(dirname(fileURLToPath(import.meta.url)), '..') const root = join(dirname(fileURLToPath(import.meta.url)), '..')
test('ArtSvgIcon: icon roots must not use Tailwind inline class', () => { test('ArtSvgIcon: el-icon branch must not use Tailwind inline class', () => {
const src = readFileSync(join(root, 'src/components/core/base/art-svg-icon/index.vue'), 'utf8') const src = readFileSync(join(root, 'src/components/core/base/art-svg-icon/index.vue'), 'utf8')
const { descriptor } = parse(src) const { descriptor } = parse(src)
const template = descriptor.template?.content || '' const template = descriptor.template?.content || ''
assert.match(template, /<el-icon\b[^>]*class="[^"]*art-svg-icon/) assert.match(template, /<el-icon\b[^>]*class="[^"]*art-svg-icon/)
assert.doesNotMatch( assert.doesNotMatch(
template, template,
/<(?:el-icon|Icon)\b[^>]*class="[^"]*\binline\b/, /<el-icon\b[^>]*class="[^"]*\binline\b/,
'icon roots must not include Tailwind inline (breaks display in prod CSS order)' 'el-icon must not include Tailwind inline (breaks display:inline-flex in prod CSS order)'
) )
}) })
test('header fold button uses inline SVG button (Chrome-safe)', () => {
const src = readFileSync(
join(root, 'src/components/core/layouts/art-header-bar/index.vue'),
'utf8'
)
const { descriptor } = parse(src)
const template = descriptor.template?.content || ''
assert.match(template, /class="menu-fold-btn/)
assert.match(template, /menu-fold-btn__icon/)
assert.match(template, /<svg[\s\S]*viewBox="0 0 24 24"/)
assert.doesNotMatch(
template,
/<ArtIconButton[\s\S]*menu-fold/,
'fold control must not rely on ArtIconButton/iconify in Chrome'
)
assert.match(template, /<button[\s\S]*class="menu-fold-btn/)
})
test('plan-archive: planNo is in column defs and table visibility gate', () => { test('plan-archive: planNo is in column defs and table visibility gate', () => {
const src = readFileSync(join(root, 'src/views/pl/plan-archive/index.vue'), 'utf8') const src = readFileSync(join(root, 'src/views/pl/plan-archive/index.vue'), 'utf8')
assert.match(src, /prop:\s*'planNo',\s*label:\s*'计划编号'/) assert.match(src, /prop:\s*'planNo',\s*label:\s*'计划编号'/)
@@ -1,66 +0,0 @@
/**
* #41 回归:运输归档绿色合计行须与表头列一一对应。
* planNo 可隐藏后,不得再无条件硬编码插入 planNo,否则按索引错位。
*/
import test from 'node:test'
import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
import { dirname, join } from 'node:path'
import { fileURLToPath } from 'node:url'
import { buildStatsRowColumns } from '../src/utils/list-column-stats.ts'
const root = join(dirname(fileURLToPath(import.meta.url)), '..')
const ARCHIVE_DEFS = [
{ prop: 'planNo' },
{ prop: 'planDate' },
{ prop: 'planQty' },
{ prop: 'actualQty' },
{ prop: 'amount' }
]
test('buildStatsRowColumns: hidden planNo must not leave a phantom stats cell', () => {
const visible = new Set(['planDate', 'planQty', 'actualQty', 'amount'])
const cols = buildStatsRowColumns({
leadingSpacers: 2,
optionalDefs: ARCHIVE_DEFS,
isColumnVisible: (prop) => visible.has(prop),
moneyProps: ['amount']
})
const props = cols.map((c) => c.prop || c.key)
assert.deepEqual(props, [
'__spacer_0',
'__spacer_1',
'planDate',
'planQty',
'actualQty',
'amount'
])
assert.equal(cols.filter((c) => c.prop === 'planNo').length, 0)
})
test('buildStatsRowColumns: visible planNo appears once after spacers', () => {
const visible = new Set(['planNo', 'planDate', 'planQty'])
const cols = buildStatsRowColumns({
leadingSpacers: 2,
optionalDefs: ARCHIVE_DEFS,
isColumnVisible: (prop) => visible.has(prop)
})
const props = cols.map((c) => c.prop || c.key)
assert.deepEqual(props, ['__spacer_0', '__spacer_1', 'planNo', 'planDate', 'planQty'])
assert.equal(cols.filter((c) => c.prop === 'planNo').length, 1)
})
test('plan-archive: stats row builds from visible columns without always-on planNo', () => {
const src = readFileSync(join(root, 'src/views/pl/plan-archive/index.vue'), 'utf8')
assert.match(
src,
/archiveStatsRowColumns[\s\S]*?buildStatsRowColumns\s*\(/,
'archive stats columns should use buildStatsRowColumns so visibility stays in sync'
)
assert.doesNotMatch(
src,
/archiveStatsRowColumns[\s\S]*?key:\s*'__index'[\s\S]*?key:\s*'planNo'[\s\S]*?for\s*\(\s*const\s+def\s+of\s+listColumnDefs/,
'must not hardcode planNo before looping listColumnDefs (causes off-by-one when hidden)'
)
})
+4 -38
View File
@@ -7,11 +7,7 @@ const readyTab = readFileSync(
'utf8' 'utf8'
) )
const contractTab = readFileSync( const contractTab = readFileSync(
new URL('../src/views/m/pl/plan-cert/CustomerTab.vue', import.meta.url), new URL('../src/views/m/pl/plan-cert/ContractTab.vue', import.meta.url),
'utf8'
)
const planCertIndex = readFileSync(
new URL('../src/views/m/pl/plan-cert/index.vue', import.meta.url),
'utf8' 'utf8'
) )
const archiveForm = readFileSync( const archiveForm = readFileSync(
@@ -34,39 +30,9 @@ test('H5 证书齐备对齐 2.0:待完善列表与完善并关闭,且文案
assert.doesNotMatch(readyTab, /也不扣减额度/) assert.doesNotMatch(readyTab, /也不扣减额度/)
}) })
test('H5 客户用证按客户列表展示证件', () => { test('H5 合同用证页对新规则给出只读提示', () => {
assert.match(contractTab, /quotaStatisticsApi\.customers/) assert.match(contractTab, /客户\+证用品类/)
assert.match(contractTab, /\/m\/pl\/plan-cert\/customer\//) assert.match(contractTab, /仅供历史查看/)
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 建档页使用关联购买证且无证面引用残留', () => { 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()
})
+66 -61
View File
@@ -105,9 +105,6 @@ function harness(fixed?: string) {
useServerColumnFilters, useServerColumnFilters,
createStatisticsLoader, createStatisticsLoader,
quotaStatisticsApi: api, quotaStatisticsApi: api,
certQuotaRuleApi: {
get: async () => ({ configured: false })
},
onBeforeUnmount: (fn: Function) => unmount.push(fn) onBeforeUnmount: (fn: Function) => unmount.push(fn)
} }
const src = ts.createSourceFile( const src = ts.createSourceFile(
@@ -157,21 +154,16 @@ test('cert tabs keep their identities and legal proof is a sibling menu', () =>
assert.equal(legal.meta!.title, '合法使用证明') assert.equal(legal.meta!.title, '合法使用证明')
assert.deepEqual( assert.deepEqual(
group.children!.filter((r) => !r.meta?.isHide).map((r) => r.path), group.children!.filter((r) => !r.meta?.isHide).map((r) => r.path),
['quota-cert', 'cert-category', 'contract-quota', 'certificate-usage', 'plan-cert', 'cert-ready'] ['quota-cert', 'contract-quota', 'certificate-usage', 'plan-cert', 'cert-ready']
) )
assert.equal(group.children![0].id, 'PL_QUOTA_CERT') assert.equal(group.children![0].id, 'PL_QUOTA_CERT')
assert.equal(group.children!.find((r) => r.path === 'contract-quota')?.meta?.title, '客户用证') assert.equal(group.children![3].id, 'PL00000000000000000000000000015')
assert.equal(
group.children!.find((r) => r.path === 'plan-cert')?.id,
'PL00000000000000000000000000015'
)
assert.deepEqual( assert.deepEqual(
group.children!.filter((r) => !r.meta?.isHide).map((r) => r.meta!.menuCode), group.children!.filter((r) => !r.meta?.isHide).map((r) => r.meta!.menuCode),
[ [
'pl:quota-cert:list', 'pl:quota-cert:list',
'pl:quota-cert:list', 'pl:quota-cert:list',
'pl:quota-cert:list', 'pl:quota-cert:list',
'pl:quota-cert:list',
'pl:plan-cert:list', 'pl:plan-cert:list',
'pl:cert-ready:list' 'pl:cert-ready:list'
] ]
@@ -656,58 +648,71 @@ function compiledSfc(path: string, dependencies: Record<string, any>, inlineTemp
) )
return new Function(...Object.keys(env), `${code}; return component`)(...Object.values(env)) return new Function(...Object.keys(env), `${code}; return component`)(...Object.values(env))
} }
for (const active of [undefined, false]) for (const wrapper of [
test(`compiled certificate-usage/CertificateUsagePanel.vue ${active === false ? 'inactive skips requests' : 'defaults to active and loads'}`, async () => { 'contract-quota/ContractQuotaPanel.vue',
const calls: string[] = [] 'certificate-usage/CertificateUsagePanel.vue'
const dependencies = { ]) {
useUserStore: () => vue.reactive({ accessToken: 'token', getUserInfo: { tenantNo: 'a' } }), for (const active of [undefined, false])
useRouter: () => ({ push() {}, replace() {} }), test(`compiled ${wrapper} ${active === false ? 'inactive skips requests' : 'defaults to active and loads'}`, async () => {
fetchGetMenuCodes: async () => { const calls: string[] = []
calls.push('permissions') const dependencies = {
return { all: true } useUserStore: () => vue.reactive({ accessToken: 'token', getUserInfo: { tenantNo: 'a' } }),
}, useRouter: () => ({ push() {}, replace() {} }),
quotaStatisticsApi: { fetchGetMenuCodes: async () => {
certificates: async () => { calls.push('permissions')
calls.push('certificates') return { all: true }
return { list: [], total: 0 } },
} quotaStatisticsApi: {
}, contracts: async () => {
usePersistedListColumns, calls.push('contracts')
useServerColumnFilters, return { list: [], total: 0 }
createStatisticsLoader, },
useElementSize: () => ({ width: vue.ref(1120) }), certificates: async () => {
useListTableViewportHeight: () => ({ tableHeight: vue.ref(400) }), calls.push('certificates')
statusLabel: statisticsLabels.statusLabel, return { list: [], total: 0 }
contractTypeLabel: statisticsLabels.contractTypeLabel }
} },
const StatisticsPanel = compiledSfc( usePersistedListColumns,
'../src/views/pl/quota-statistics/StatisticsPanel.vue', useServerColumnFilters,
dependencies, createStatisticsLoader,
false useElementSize: () => ({ width: vue.ref(1120) }),
) useListTableViewportHeight: () => ({ tableHeight: vue.ref(400) }),
StatisticsPanel.render = () => null statusLabel: statisticsLabels.statusLabel,
const Wrapper = compiledSfc('../src/views/pl/certificate-usage/CertificateUsagePanel.vue', { contractTypeLabel: statisticsLabels.contractTypeLabel
StatisticsPanel }
// Compile the real inner setup too; only its visual child tree is omitted here.
const StatisticsPanel = compiledSfc(
'../src/views/pl/quota-statistics/StatisticsPanel.vue',
dependencies,
false
)
StatisticsPanel.render = () => null
const Wrapper = compiledSfc(`../src/views/pl/${wrapper}`, { StatisticsPanel })
const renderer = vue.createRenderer<any, any>({
createElement: () => ({}),
createText: () => ({}),
createComment: () => ({}),
setText: () => {},
setElementText: () => {},
parentNode: () => null,
nextSibling: () => null,
insert: () => {},
remove: () => {},
patchProp: () => {}
})
const app = renderer.createApp(Wrapper, active === undefined ? {} : { active })
app.mount({})
await flush()
await vue.nextTick()
assert.deepEqual(
calls,
active === false
? []
: ['permissions', wrapper.startsWith('contract') ? 'contracts' : 'certificates']
)
app.unmount()
}) })
const renderer = vue.createRenderer<any, any>({ }
createElement: () => ({}),
createText: () => ({}),
createComment: () => ({}),
setText: () => {},
setElementText: () => {},
parentNode: () => null,
nextSibling: () => null,
insert: () => {},
remove: () => {},
patchProp: () => {}
})
const app = renderer.createApp(Wrapper, active === undefined ? {} : { active })
app.mount({})
await flush()
await vue.nextTick()
assert.deepEqual(calls, active === false ? [] : ['permissions', 'certificates'])
app.unmount()
})
test('expanded content follows the table viewport width and keeps alignment local', () => { test('expanded content follows the table viewport width and keeps alignment local', () => {
const h = harness() const h = harness()
+1 -1
View File
@@ -111,7 +111,7 @@
const panelTitleClassList = [...panelTitleIconByText.map(([, cls]) => cls), 'auto-title-list'] const panelTitleClassList = [...panelTitleIconByText.map(([, cls]) => cls), 'auto-title-list']
const panelTitleBarClass = 'title-bar-heading' const panelTitleBarClass = 'title-bar-heading'
const panelTitleBarTextRules = [/^(购买证与运输证|合法使用证明|计划用证|证件建档|证用品类|合同用证|客户用证|证件用量|计划段次用证|证书齐备|合同证件与额度|客户证件与额度|运输证件规则)$/] const panelTitleBarTextRules = [/^(购买证与运输证|合法使用证明|计划用证|证件建档|证用品类|合同用证|证件用量|计划段次用证|证书齐备|合同证件与额度|运输证件规则)$/]
const panelTitleHeadingSelector = const panelTitleHeadingSelector =
'.page-container .panel-top h2, .page-container .panel-top h3, .page-container .storage-content-header h3, .page-container .storage-aside__head h2, .page-container .user-dept-aside__head h2, .console-container .panel-top h2' '.page-container .panel-top h2, .page-container .panel-top h3, .page-container .storage-content-header h3, .page-container .storage-aside__head h2, .page-container .user-dept-aside__head h2, .console-container .panel-top h2'
-7
View File
@@ -624,13 +624,6 @@ export interface Plan {
hazardCertReady?: number hazardCertReady?: number
hazardCertReadyBy?: string hazardCertReadyBy?: string
hazardCertReadyTime?: string hazardCertReadyTime?: string
/** 证书齐备:新规则仅放行安排 */
quotaCertWaived?: number
quotaCertWaivedBy?: string
quotaCertWaivedByName?: string
quotaCertWaivedTime?: string
/** 新规则证书齐备待完善 */
quotaCertPendingFulfill?: number
erpEntered?: number erpEntered?: number
remark?: string remark?: string
createBy?: string createBy?: string
+2 -30
View File
@@ -61,13 +61,10 @@ export interface QuotaCert extends Omit<CertBody, 'status'> {
verifiedTime?: string | null verifiedTime?: string | null
openingConfirmed: boolean openingConfirmed: boolean
usagePolicy: 'once' | 'multiple' | 'needs_confirmation' usagePolicy: 'once' | 'multiple' | 'needs_confirmation'
singleUseConsumed?: boolean
createTime?: string createTime?: string
certType?: CertType certType?: CertType
derivedCategoryIds?: string[] derivedCategoryIds?: string[]
derivedCategoryNames?: string[]
customerName?: string | null customerName?: string | null
categoryName?: string | null
} }
export interface ScopeProduct { export interface ScopeProduct {
id?: string id?: string
@@ -135,10 +132,8 @@ export interface LegalDocument {
} }
const base = '/transport/quota-certs' const base = '/transport/quota-certs'
export const quotaCertApi = { export const quotaCertApi = {
list: ( list: (kind: CertType, params: { keyword?: string; status?: string } = {}) =>
kind: CertType, request.get(`${base}/${kind}`, { params }).then(pickBxData<QuotaCert[]>),
params: { keyword?: string; status?: string; customerId?: string } = {}
) => request.get(`${base}/${kind}`, { params }).then(pickBxData<QuotaCert[]>),
get: (kind: CertType, id: string) => get: (kind: CertType, id: string) =>
request.get(`${base}/${kind}/${id}`).then(pickBxData<QuotaCert>), request.get(`${base}/${kind}/${id}`).then(pickBxData<QuotaCert>),
save: (kind: CertType, body: CertBody, id?: string) => save: (kind: CertType, body: CertBody, id?: string) =>
@@ -509,13 +504,6 @@ export interface StatisticsPage<T> {
export interface ContractStatisticsSummary extends ContractOption { export interface ContractStatisticsSummary extends ContractOption {
certCount: number certCount: number
} }
export interface CustomerStatisticsSummary {
id: string
customerId: string
customerNo: string
customerName: string
certCount: number
}
export interface CertificateStatisticsSummary { export interface CertificateStatisticsSummary {
id: string id: string
certId: string certId: string
@@ -534,14 +522,6 @@ export interface CertificateStatisticsSummary {
buyPartyName?: string | null buyPartyName?: string | null
validUseText?: string | null validUseText?: string | null
} }
export interface CustomerStatistics extends CustomerStatisticsSummary {
certificates: (CertificateStatisticsSummary & {
usagePolicy?: QuotaCert['usagePolicy']
singleUseConsumed?: boolean
openingConfirmed?: boolean
createTime?: string
})[]
}
export interface StatisticsProduct { export interface StatisticsProduct {
id: string id: string
contractProductId: string contractProductId: string
@@ -599,8 +579,6 @@ export interface StatisticsQuery {
contractNo?: string contractNo?: string
contractName?: string contractName?: string
contractTypeIn?: string contractTypeIn?: string
customerNo?: string
customerName?: string
certCountOp?: string certCountOp?: string
certCount?: string certCount?: string
certCountMin?: string certCountMin?: string
@@ -644,18 +622,12 @@ export const quotaStatisticsApi = {
request request
.get(`${base}/statistics/contracts`, { params }) .get(`${base}/statistics/contracts`, { params })
.then(pickBxData<StatisticsPage<ContractStatisticsSummary>>), .then(pickBxData<StatisticsPage<ContractStatisticsSummary>>),
customers: (params: StatisticsQuery) =>
request
.get(`${base}/statistics/customers`, { params })
.then(pickBxData<StatisticsPage<CustomerStatisticsSummary>>),
certificates: (params: StatisticsQuery) => certificates: (params: StatisticsQuery) =>
request request
.get(`${base}/statistics/certificates`, { params }) .get(`${base}/statistics/certificates`, { params })
.then(pickBxData<StatisticsPage<CertificateStatisticsSummary>>), .then(pickBxData<StatisticsPage<CertificateStatisticsSummary>>),
contract: (id: string) => contract: (id: string) =>
request.get(`${base}/contracts/${id}/statistics`).then(pickBxData<ContractStatistics>), request.get(`${base}/contracts/${id}/statistics`).then(pickBxData<ContractStatistics>),
customer: (id: string) =>
request.get(`${base}/customers/${id}/statistics`).then(pickBxData<CustomerStatistics>),
certificate: (kind: CertType, id: string) => certificate: (kind: CertType, id: string) =>
request.get(`${base}/${kind}/${id}/statistics`).then(pickBxData<CertificateStatistics>) request.get(`${base}/${kind}/${id}/statistics`).then(pickBxData<CertificateStatistics>)
} }
@@ -299,7 +299,6 @@
extractArchiveLineOverageDetail, extractArchiveLineOverageDetail,
showArchiveLineOverageConfirm showArchiveLineOverageConfirm
} from '@/utils/pl-contract-qty-reminder' } from '@/utils/pl-contract-qty-reminder'
import { resolveArchiveQuotaBlockMode } from '@/utils/pl-archive-quota-block'
const props = defineProps<{ const props = defineProps<{
visible: boolean visible: boolean
@@ -1603,18 +1602,37 @@
async function showArchiveQuotaBlockDialog(message: string, title = '不能归档') { async function showArchiveQuotaBlockDialog(message: string, title = '不能归档') {
const html = `<p class="pl-arrange-block-text">${escapeArchiveBlockText(message)}</p>` const html = `<p class="pl-arrange-block-text">${escapeArchiveBlockText(message)}</p>`
const mode = resolveArchiveQuotaBlockMode(message, title, plan.value) const pendingFulfill =
const guide = message.includes('待完善') || message.includes('完善并关闭') || message.includes('证书齐备待完善')
mode === 'alert-pending' if (title !== '用证没有完成' || pendingFulfill) {
? `${html}<p class="pl-arrange-block-text">该运输计划已走证书齐备,归档前须完善证件。请到「证书齐备 → 已标记待完善证书」上传购买证/运输证并执行完善并关闭后再归档。</p>` const guide = pendingFulfill
? `${html}<p class="pl-arrange-block-text">新规则下证书齐备只放行安排,不能绕过归档挂证。请到「证书齐备 → 已标记待完善证书」上传证件并执行完善并关闭后再归档。</p>`
: html : html
await ElMessageBox.alert(guide, title, { await ElMessageBox.alert(guide, title, {
type: 'warning', type: 'warning',
confirmButtonText: '知道了', confirmButtonText: '知道了',
dangerouslyUseHTMLString: true, dangerouslyUseHTMLString: true,
customClass: 'pl-arrange-block-msgbox', customClass: 'pl-arrange-block-msgbox',
closeOnClickModal: false closeOnClickModal: false
}).catch(() => undefined) }).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>>) { function applyArchiveOverageHighlight(items: Array<Record<string, unknown>>) {
@@ -1649,7 +1667,13 @@
// 业务异常已作为一次请求提交;补齐条件后允许新尝试,不回放旧异常。 // 业务异常已作为一次请求提交;补齐条件后允许新尝试,不回放旧异常。
quotaArchiveAttempt = { signature: '', id: '' } quotaArchiveAttempt = { signature: '', id: '' }
const message = saved.quotaSettlementError 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 } const error = new Error(message) as Error & { cancelled?: boolean }
error.cancelled = true error.cancelled = true
throw error throw error
@@ -1,11 +1,11 @@
<!-- 图标组件:支持 Element Plus 图标(无 : 前缀)与 Iconify 图标(含 : 前缀) --> <!-- 图标组件:支持 Element Plus 图标(无 : 前缀)与 Iconify 图标(含 : 前缀) -->
<template> <template>
<!-- 勿给图标根节点加 Tailwind `inline`:生产 CSS 中 `.inline{display:inline}` <!-- el-icon 勿加 Tailwind `inline`:生产 CSS 中 `.inline{display:inline}` 会覆盖
会覆盖 flex/尺寸,部分 Chrome 下 Fold 等图标不可见 --> `.el-icon{display:inline-flex}`,导致 Fold 等图标在打包后不可见 -->
<el-icon v-if="epIcon" v-bind="iconAttrs" class="art-svg-icon"> <el-icon v-if="epIcon" v-bind="iconAttrs" class="art-svg-icon">
<component :is="epIcon" /> <component :is="epIcon" />
</el-icon> </el-icon>
<Icon v-else-if="icon" :icon="icon" v-bind="iconAttrs" class="art-svg-icon" /> <Icon v-else-if="icon" :icon="icon" v-bind="iconAttrs" class="art-svg-icon inline" />
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
@@ -21,31 +21,17 @@
@click="toHome" @click="toHome"
/> />
<!-- 菜单按钮:内联 SVG,避开 Chrome 下 el-icon / Iconify 偶发不绘制 --> <!-- 菜单按钮 -->
<button <ArtIconButton
v-if="isLeftMenu && shouldShowMenuButton" v-if="isLeftMenu && shouldShowMenuButton"
type="button" icon="fold"
class="menu-fold-btn" class="ml-3 max-sm:ml-[7px] menu-fold-btn"
:class="{ 'is-menu-collapsed': !menuOpen }" :class="{ 'is-menu-collapsed': !menuOpen }"
:title="menuOpen ? '收起菜单' : '展开菜单'" :title="menuOpen ? '收起菜单' : '展开菜单'"
:aria-label="menuOpen ? '收起菜单' : '展开菜单'" :aria-label="menuOpen ? '收起菜单' : '展开菜单'"
:aria-expanded="menuOpen" :aria-expanded="menuOpen"
@click="visibleMenu" @click="visibleMenu"
> />
<svg
class="menu-fold-btn__icon"
viewBox="0 0 24 24"
width="20"
height="20"
aria-hidden="true"
focusable="false"
>
<path
fill="currentColor"
d="M21 18v2H3v-2zm0-5v2h-9v-2zm0-5v2h-9V8zM3 3.5v10l5-5z"
/>
</svg>
</button>
<!-- 刷新按钮 - 已隐藏 --> <!-- 刷新按钮 - 已隐藏 -->
<ArtIconButton <ArtIconButton
@@ -402,47 +388,12 @@
} }
} }
/* 顶栏折叠按钮:原生 button + 内联 SVG,保证 Chrome/Safari 一致可见 */ .menu-fold-btn :deep(.art-svg-icon) {
.menu-fold-btn {
box-sizing: border-box;
display: inline-flex;
flex-shrink: 0;
align-items: center;
justify-content: center;
width: 34px;
height: 34px;
margin-left: 12px;
padding: 0;
color: #64748b;
cursor: pointer;
background: transparent;
border: 0;
border-radius: 8px;
appearance: none;
}
@media (max-width: 640px) {
.menu-fold-btn {
margin-left: 7px;
}
}
.menu-fold-btn:hover {
color: #1e293b;
background: var(--mint-row-alt, #f1f5f9);
}
.menu-fold-btn__icon {
display: block;
width: 20px;
height: 20px;
transition: transform 0.3s ease; transition: transform 0.3s ease;
/* 展开态默认旋转,与收起态对调 */
transform: rotate(180deg);
} }
.menu-fold-btn.is-menu-collapsed .menu-fold-btn__icon { .menu-fold-btn.is-menu-collapsed :deep(.art-svg-icon) {
transform: rotate(0deg); transform: rotate(180deg);
} }
/* Hover animation classes */ /* Hover animation classes */
@@ -119,7 +119,13 @@ export function useSettingsConfig() {
handler: 'uniqueOpened', handler: 'uniqueOpened',
headerBarKey: null // 不依赖headerBar配置 headerBarKey: null // 不依赖headerBar配置
}, },
// showMenuButton 不提供开关:顶栏收起侧栏按钮为产品必显能力 {
key: 'showMenuButton',
label: t('setting.basics.list.collapseSidebar'),
type: 'switch' as const,
handler: 'menuButton',
headerBarKey: 'menuButton' as const
},
{ {
key: 'showFastEnter', key: 'showFastEnter',
label: t('setting.basics.list.fastEnter'), label: t('setting.basics.list.fastEnter'),
@@ -67,7 +67,7 @@ export function useSettingsHandlers() {
uniqueOpened: createToggleHandler(() => settingStore.setUniqueOpened()), uniqueOpened: createToggleHandler(() => settingStore.setUniqueOpened()),
// 显示菜单按钮 // 显示菜单按钮
menuButton: createToggleHandler(() => settingStore.ensureMenuButtonVisible()), menuButton: createToggleHandler(() => settingStore.setButton()),
// 显示快速入口 // 显示快速入口
fastEnter: createToggleHandler(() => settingStore.setFastEnter()), fastEnter: createToggleHandler(() => settingStore.setFastEnter()),
@@ -185,8 +185,9 @@
settingStore.setElementTheme(config.systemThemeColor) settingStore.setElementTheme(config.systemThemeColor)
// 界面显示(切换类方法) // 界面显示(切换类方法)
// 顶栏收起按钮为必显,导入配置时也强制打开 toggleIfDifferent(settingStore.showMenuButton, config.showMenuButton, () =>
settingStore.ensureMenuButtonVisible() settingStore.setButton()
)
toggleIfDifferent(settingStore.showFastEnter, config.showFastEnter, () => toggleIfDifferent(settingStore.showFastEnter, config.showFastEnter, () =>
settingStore.setFastEnter() settingStore.setFastEnter()
) )
@@ -86,13 +86,11 @@ export function usePlFreightCalc(options: {
) )
function resetFreightCalc() { function resetFreightCalc() {
transportQty.value = null
transportQtyTouched.value = false transportQtyTouched.value = false
freightAmount.value = null freightAmount.value = null
freightAmountTouched.value = false freightAmountTouched.value = false
freightPrice.value = null freightPrice.value = null
// 产品已加载时 watch 不会因 reset 重跑;须立即按当前实际数量回填,
// 否则归档弹窗再次打开会误报「运输量须大于0」。
transportQty.value = defaultTransportQty.value || null
} }
function markTransportQtyTouched() { function markTransportQtyTouched() {
+1 -1
View File
@@ -133,7 +133,7 @@
mode: 'list', mode: 'list',
title: '运输证件管理', title: '运输证件管理',
search: '证件编号 / 品名', search: '证件编号 / 品名',
tabs: ['证件建档', '客户用证', '证件用量', '计划段次用证', '证书齐备'], tabs: ['证件建档', '合同用证', '证件用量', '计划段次用证', '证书齐备'],
filters: [], filters: [],
caption: '正在加载运输证件管理' caption: '正在加载运输证件管理'
} }
+1 -1
View File
@@ -80,7 +80,7 @@ export const plRoutes: AppRouteRecord[] = [
name: 'PlContractQuota', name: 'PlContractQuota',
path: 'contract-quota', path: 'contract-quota',
component: '/pl/contract-quota/index', component: '/pl/contract-quota/index',
meta: { title: '客户用证', keepAlive: false, menuCode: 'pl:quota-cert:list' } meta: { title: '合同用证', keepAlive: false, menuCode: 'pl:quota-cert:list' }
}, },
{ {
id: 'PL_CERTIFICATE_USAGE', id: 'PL_CERTIFICATE_USAGE',
+2 -8
View File
@@ -171,17 +171,11 @@ export const staticRoutes: AppRouteRecordRaw[] = [
component: () => import('@views/m/pl/plan-cert/archive-detail.vue'), component: () => import('@views/m/pl/plan-cert/archive-detail.vue'),
meta: { title: '证件建档', isHideTab: true, isMpWebview: true } meta: { title: '证件建档', isHideTab: true, isMpWebview: true }
}, },
{
path: '/m/pl/plan-cert/customer/:id',
name: 'MpPlPlanCertCustomer',
component: () => import('@views/m/pl/plan-cert/customer-detail.vue'),
meta: { title: '客户用证', isHideTab: true, isMpWebview: true }
},
{ {
path: '/m/pl/plan-cert/contract/:id', path: '/m/pl/plan-cert/contract/:id',
name: 'MpPlPlanCertContract', name: 'MpPlPlanCertContract',
redirect: { name: 'MpPlPlanCert', query: { tab: 'contract' } }, component: () => import('@views/m/pl/plan-cert/contract-detail.vue'),
meta: { title: '客户用证', isHideTab: true, isMpWebview: true } meta: { title: '合同用证', isHideTab: true, isMpWebview: true }
}, },
{ {
path: '/m/pl/plan-cert/usage/:kind/:id', path: '/m/pl/plan-cert/usage/:kind/:id',
+6 -10
View File
@@ -227,15 +227,10 @@ export const useSettingStore = defineStore(
} }
/** /**
* 切换菜单按钮显示(产品要求顶栏始终可收起侧栏,禁止关闭) * 切换菜单按钮显示
*/ */
const setButton = () => { const setButton = () => {
showMenuButton.value = true showMenuButton.value = !showMenuButton.value
}
/** 强制显示顶栏侧栏收起按钮,修复旧 localStorage 中 false 残留 */
const ensureMenuButtonVisible = () => {
showMenuButton.value = true
} }
/** /**
@@ -428,7 +423,6 @@ export const useSettingStore = defineStore(
setContainerWidth, setContainerWidth,
setUniqueOpened, setUniqueOpened,
setButton, setButton,
ensureMenuButtonVisible,
setFastEnter, setFastEnter,
setAutoClose, setAutoClose,
setShowRefreshButton, setShowRefreshButton,
@@ -464,8 +458,10 @@ export const useSettingStore = defineStore(
} else if (width === 290) { } else if (width === 290) {
ctx.store.setMenuOpenWidth(270) ctx.store.setMenuOpenWidth(270)
} }
// 旧本地配置(sys-v*-setting)可能残留 showMenuButton:false;必须赋值 true,禁止用 toggle // 旧本地配置把收起按钮关掉了;产品需要顶栏始终能收起侧栏
ctx.store.ensureMenuButtonVisible() if (!ctx.store.showMenuButton) {
ctx.store.setButton()
}
} }
} }
} }
@@ -1,27 +0,0 @@
/** 归档用证拦截弹窗:只提醒,不在归档界面提供「证书齐备」操作。 */
export type ArchiveQuotaBlockMode = 'alert-pending' | 'alert-plain'
export type ArchiveQuotaBlockPlanFlags = {
quotaCertPendingFulfill?: number | boolean | null
quotaCertWaived?: number | boolean | null
}
function flagOn(value: number | boolean | null | undefined) {
return value === true || Number(value || 0) === 1
}
export function resolveArchiveQuotaBlockMode(
message: string,
title: string,
plan?: ArchiveQuotaBlockPlanFlags | null
): ArchiveQuotaBlockMode {
const pendingByMessage =
message.includes('待完善') ||
message.includes('完善并关闭') ||
message.includes('证书齐备待完善')
const pendingByPlan = flagOn(plan?.quotaCertPendingFulfill) || flagOn(plan?.quotaCertWaived)
if (title !== '用证没有完成') return 'alert-plain'
if (pendingByPlan || pendingByMessage) return 'alert-pending'
return 'alert-plain'
}
@@ -504,12 +504,13 @@
/> />
</el-tab-pane> </el-tab-pane>
<el-tab-pane v-if="canViewQuotaCert" label="客户证件与额度" name="quota" lazy> <el-tab-pane v-if="canViewQuotaCert" label="合同证件与额度" name="quota" lazy>
<CustomerCertQuotaPanel <ContractQuotaPanel
v-if="visible && detailActiveTab === 'quota' && detailContract?.id && String(detailContract.id) === String(currentDetailId)" v-if="visible && detailActiveTab === 'quota' && detailContract?.id && String(detailContract.id) === String(currentDetailId)"
:key="String(detailContract.customerId || detailContract.id)" :key="detailContract.id"
:customer-id="detailContract.customerId" :contract-id="String(detailContract.id)"
:active="detailActiveTab === 'quota'" :active="detailActiveTab === 'quota'"
embedded
/> />
</el-tab-pane> </el-tab-pane>
@@ -1059,7 +1060,7 @@ import UploadDialog from './UploadDialog.vue';
import ContractFormDialog from './ContractFormDialog.vue'; import ContractFormDialog from './ContractFormDialog.vue';
import ViewKvTable from '@/components/business/system-view-dialog/ViewKvTable.vue'; import ViewKvTable from '@/components/business/system-view-dialog/ViewKvTable.vue';
import type { ViewField } from '@/components/business/system-view-dialog/types'; import type { ViewField } from '@/components/business/system-view-dialog/types';
import CustomerCertQuotaPanel from '@/views/pl/contract-quota/CustomerCertQuotaPanel.vue'; import ContractQuotaPanel from '@/views/pl/contract-quota/ContractQuotaPanel.vue';
import StopDocuments from '@/views/pl/legal-use-document/StopDocuments.vue'; import StopDocuments from '@/views/pl/legal-use-document/StopDocuments.vue';
import PlContractLinkedPlansPanel from '@/components/business/pl-contract-linked-plans-panel/index.vue'; import PlContractLinkedPlansPanel from '@/components/business/pl-contract-linked-plans-panel/index.vue';
import { import {
-2
View File
@@ -75,8 +75,6 @@
if (!settingStore.showCrumbs) { if (!settingStore.showCrumbs) {
settingStore.setCrumbs() settingStore.setCrumbs()
} }
// 纠正版本化 localStorage 中 showMenuButton:false,保证折叠钮始终可见
settingStore.ensureMenuButtonVisible()
}) })
</script> </script>
@@ -1,180 +0,0 @@
<template>
<div class="mp-customer-cert-quota">
<p v-if="!customerId" class="mp-wv-empty">合同未关联客户,无法展示证件</p>
<p v-else-if="error" class="mp-wv-empty" role="alert">
{{ error }}
<button class="mp-wv-btn" type="button" @click="load">重试</button>
</p>
<div v-else-if="loading" class="mp-cert-page-loading"><van-loading /></div>
<template v-else>
<p class="mp-customer-cert-quota__tip">
展示该客户全部购买证、运输证;证件关联客户,不再按合同绑定。
</p>
<van-empty v-if="!rows.length" description="该客户暂无购买证或运输证" />
<article
v-for="row in rows"
:key="row.certType + row.id"
class="mp-wv-section"
role="button"
tabindex="0"
@click="openDetail(row)"
@keydown.enter.prevent="openDetail(row)"
>
<div class="mp-wv-card__head">
<div>
<h3>{{ row.certNo || '—' }}</h3>
<p>{{ row.productNameOnCert || '未填写证面品名' }}</p>
<p>有效期:{{ row.validFrom || '—' }} 至 {{ row.validTo || '—' }}</p>
</div>
</div>
<div class="mp-cert-tags">
<span
class="status-tag mp-cert-kind-tag"
:class="`status-tag--${certKindMobileTone(row.certType)}`"
>{{ certKindLabel(row.certType) }}</span
>
<span class="status-tag" :class="`status-tag--${statusTone(row.status)}`">{{
certStatusLabel(row.status)
}}</span>
<span v-if="row.singleUseConsumed" class="status-tag status-tag--danger"
>已使用不可再用</span
>
</div>
<div class="mp-wv-card__kv">
<div class="mp-wv-card__kv-row"
><span>有效次数</span><span>{{ row.validUseText || '—' }}</span></div
>
<div class="mp-wv-card__kv-row"
><span>核定</span><span>{{ qtyText(row.totalQty, row.quantityUnit) }}</span></div
>
<div class="mp-wv-card__kv-row"
><span>预占</span><span>{{ qtyText(row.reservedQty, row.quantityUnit) }}</span></div
>
<div class="mp-wv-card__kv-row"
><span>已用</span><span>{{ qtyText(row.usedQty, row.quantityUnit) }}</span></div
>
<div class="mp-wv-card__kv-row"
><span>余量</span><span>{{ qtyText(row.availableQty, row.quantityUnit) }}</span></div
>
</div>
</article>
</template>
</div>
</template>
<script setup lang="ts">
import { useRouter } from 'vue-router'
import { useDictStore } from '@/store/modules/dict'
import { getProductUnitLabel } from '@/utils/crm-product-display'
import { quotaCertApi, type CertType, type QuotaCert } from '@/api/pl/quota-cert'
import { certKindLabel, certKindMobileTone } from '@/views/pl/quota-cert/cert-list-face'
import { formatCertQty } from '@/views/pl/quota-cert/model'
type CustomerCertRow = QuotaCert & { certType: CertType }
const props = withDefaults(
defineProps<{ customerId?: string | number | null; active?: boolean }>(),
{ active: true }
)
const router = useRouter()
const dictStore = useDictStore()
const loading = ref(false)
const error = ref('')
const rows = ref<CustomerCertRow[]>([])
let loadEpoch = 0
function unitLabel(unit?: string | null) {
const label = getProductUnitLabel(dictStore.getLabel, unit)
return !label || label === '—' ? '' : label
}
function qtyText(value: unknown, unit?: string | null) {
const text = formatCertQty(value)
const name = unitLabel(unit)
return name ? `${text} ${name}` : text
}
function certStatusLabel(status?: string | null) {
return (
{
draft: '待核对',
active: '证件已启用',
suspended: '证件已停用',
closed: '证件已核销',
void: '证件已作废'
}[status || ''] ||
status ||
'—'
)
}
function statusTone(status?: string | null) {
if (status === 'active') return 'success'
if (status === 'suspended') return 'warning'
if (status === 'closed' || status === 'void') return 'danger'
return 'info'
}
async function load() {
const customerId = props.customerId == null ? '' : String(props.customerId).trim()
const epoch = ++loadEpoch
if (!customerId) {
rows.value = []
error.value = ''
loading.value = false
return
}
loading.value = true
error.value = ''
try {
const [purchase, transport] = await Promise.all([
quotaCertApi.list('purchase', { customerId }),
quotaCertApi.list('transport', { customerId })
])
if (epoch !== loadEpoch) return
rows.value = [
...(purchase || []).map((item) => ({ ...item, certType: 'purchase' as const })),
...(transport || []).map((item) => ({ ...item, certType: 'transport' as const }))
].sort((a, b) => String(b.createTime || '').localeCompare(String(a.createTime || '')))
} catch (e: any) {
if (epoch !== loadEpoch) return
rows.value = []
error.value = e?.message || '加载客户证件失败'
} finally {
if (epoch === loadEpoch) loading.value = false
}
}
function openDetail(row: CustomerCertRow) {
void router.push(`/m/pl/plan-cert/archive/${row.certType}/${row.id}`)
}
watch(
() => [props.customerId, props.active],
([, active]) => {
if (active) void load()
},
{ immediate: true }
)
</script>
<style scoped lang="scss">
.mp-customer-cert-quota__tip {
margin: 0 0 12px;
font-size: 12px;
line-height: 1.5;
color: var(--mp-text-muted, #64748b);
}
.mp-wv-section {
cursor: pointer;
}
.mp-cert-tags {
display: flex;
flex-wrap: wrap;
gap: 8px;
margin: 8px 0 12px;
}
</style>
+9 -46
View File
@@ -342,19 +342,6 @@
</div> </div>
<div v-show="activeTab === 'quota'" class="mp-contract-detail-pane">
<section class="mp-wv-section mp-contract-detail-card">
<h3>客户证件与额度</h3>
<CustomerCertQuotaTab
v-if="canViewQuotaCert && activeTab === 'quota'"
:key="String(contract.customerId || contract.id)"
:customer-id="contract.customerId"
:active="activeTab === 'quota'"
/>
<p v-else class="mp-wv-card__meta">无证件查看权限</p>
</section>
</div>
<div v-show="activeTab === 'plans'" class="mp-contract-detail-pane"> <div v-show="activeTab === 'plans'" class="mp-contract-detail-pane">
<section class="mp-wv-section mp-contract-detail-card"> <section class="mp-wv-section mp-contract-detail-card">
<h3>运输计划</h3> <h3>运输计划</h3>
@@ -946,8 +933,6 @@
} from '@/utils/mp-webview' } from '@/utils/mp-webview'
import { useUserStore } from '@/store/modules/user' import { useUserStore } from '@/store/modules/user'
import { useDictStore } from '@/store/modules/dict' import { useDictStore } from '@/store/modules/dict'
import { fetchGetMenuCodes } from '@/api/auth'
import CustomerCertQuotaTab from './CustomerCertQuotaTab.vue'
import '@/styles/mp-webview.scss' import '@/styles/mp-webview.scss'
import '../customer/customer.scss' import '../customer/customer.scss'
@@ -985,7 +970,6 @@
type DetailTabKey = type DetailTabKey =
| 'contract' | 'contract'
| 'plans' | 'plans'
| 'quota'
| 'payment' | 'payment'
| 'invoice' | 'invoice'
| 'approval' | 'approval'
@@ -995,7 +979,6 @@
const acting = ref(false) const acting = ref(false)
const errorText = ref('') const errorText = ref('')
const activeTab = ref<DetailTabKey>('contract') const activeTab = ref<DetailTabKey>('contract')
const canViewQuotaCert = ref(false)
const detailBody = ref<HTMLElement>() const detailBody = ref<HTMLElement>()
const partiesExpanded = ref(false) const partiesExpanded = ref(false)
const approverPickerOpen = ref(false) const approverPickerOpen = ref(false)
@@ -1073,34 +1056,14 @@
} }
} }
const detailTabs = computed(() => { const detailTabs: Array<{ key: DetailTabKey; label: string }> = [
const tabs: Array<{ key: DetailTabKey; label: string }> = [ { key: 'contract', label: '合同信息' },
{ key: 'contract', label: '合同信息' }, { key: 'plans', label: '运输计划' },
{ key: 'plans', label: '运输计划' } { key: 'payment', label: '回款记录' },
] { key: 'invoice', label: '开票记录' },
if (canViewQuotaCert.value) tabs.push({ key: 'quota', label: '客户证件与额度' }) { key: 'approval', label: '审批流程' },
tabs.push( { key: 'operation', label: '操作记录' }
{ key: 'payment', label: '回款记录' }, ]
{ key: 'invoice', label: '开票记录' },
{ key: 'approval', label: '审批流程' },
{ key: 'operation', label: '操作记录' }
)
return tabs
})
async function refreshQuotaCertPermission() {
try {
const permissions = await fetchGetMenuCodes()
const codes = permissions?.menuCodes || []
canViewQuotaCert.value =
!!permissions?.all || !!permissions?.isSuperAdmin || codes.includes('pl:quota-cert:list')
} catch {
canViewQuotaCert.value = false
}
if (!canViewQuotaCert.value && activeTab.value === 'quota') {
activeTab.value = 'contract'
}
}
const unreceivedAmount = computed(() => { const unreceivedAmount = computed(() => {
const amount = Number(contract.value?.amount) || 0 const amount = Number(contract.value?.amount) || 0
@@ -1610,7 +1573,7 @@
} }
loading.value = true loading.value = true
try { try {
const [res] = await Promise.all([getContract(id), refreshQuotaCertPermission()]) const res = await getContract(id)
if (!isCurrentLoad(requestSeq, id)) return if (!isCurrentLoad(requestSeq, id)) return
const data = ((res as any)?.data ?? res) as ContractVO const data = ((res as any)?.data ?? res) as ContractVO
if (String(data?.id || '') !== id) throw new Error('合同不存在或无权查看') if (String(data?.id || '') !== id) throw new Error('合同不存在或无权查看')
@@ -25,12 +25,6 @@
}}</span> }}</span>
</div> </div>
<div class="mp-wv-card__kv"> <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" <div class="mp-wv-card__kv-row"
><span>销售单位</span><span>{{ salePartyName(row) || '—' }}</span></div ><span>销售单位</span><span>{{ salePartyName(row) || '—' }}</span></div
> >
@@ -66,12 +60,12 @@
>编辑</button >编辑</button
> >
<button <button
v-if="canEdit && row.openingConfirmed && row.status !== 'void' && row.status !== 'closed'" v-if="canEdit && row.status !== 'void' && row.status !== 'closed'"
class="mp-wv-btn" class="mp-wv-btn"
type="button" type="button"
@click="confirmRow = row" @click="confirmRow = row"
> >
复核 {{ row.openingConfirmed ? '复核' : '期初确认' }}
</button> </button>
</div> </div>
</article> </article>
@@ -125,7 +119,7 @@
} from '@/views/pl/quota-cert/cert-list-face' } from '@/views/pl/quota-cert/cert-list-face'
import { useDictStore } from '@/store/modules/dict' import { useDictStore } from '@/store/modules/dict'
import { getProductUnitLabel } from '@/utils/crm-product-display' import { getProductUnitLabel } from '@/utils/crm-product-display'
import { certCategoryLabel, certStatusLabels } from './face-model' import { certStatusLabels } from './face-model'
const props = defineProps<{ const props = defineProps<{
keyword: string keyword: string
@@ -8,21 +8,37 @@
:close-on-click-overlay="!saving" :close-on-click-overlay="!saving"
@update:show="onShow" @update:show="onShow"
> >
<van-nav-bar title="复核证件" left-text="关闭" @click-left="!saving && emit('close')" /> <van-nav-bar
:title="row?.openingConfirmed ? '复核证件' : '期初核对'"
left-text="关闭"
@click-left="!saving && emit('close')"
/>
<div v-if="row" class="mp-cert-confirm-sheet__body mp-cert-form"> <div v-if="row" class="mp-cert-confirm-sheet__body mp-cert-form">
<p class="plan-empty-hint">{{ row.certNo }} · 复核已启用的证件</p> <p class="plan-empty-hint">{{ row.certNo }} · {{ row.openingConfirmed ? '复核已启用的证件' : '核对历史用量后启用' }}</p>
<template v-if="!row.openingConfirmed">
<van-field v-model="opening.usedQty" label="历史已用量" label-align="top" type="number" :disabled="saving" />
<van-cell title="一次有效证已有使用记录" center>
<template #right-icon>
<van-switch v-model="opening.singleUseConsumed" :disabled="saving" size="20px" />
</template>
</van-cell>
<van-field v-model="opening.sourceNote" label="历史来源说明" label-align="top" type="textarea" rows="2" :disabled="saving" />
<p class="plan-empty-hint">核对凭据</p>
<AttachmentUploadField v-model="opening.evidenceUrls" folder="pl/quota-cert" :disabled="saving" hint="" />
</template>
<van-field v-model="opening.reason" label="核对说明" label-align="top" type="textarea" rows="2" :disabled="saving" /> <van-field v-model="opening.reason" label="核对说明" label-align="top" type="textarea" rows="2" :disabled="saving" />
</div> </div>
<footer> <footer>
<button class="mp-wv-btn" type="button" :disabled="saving" @click="emit('close')">取消</button> <button class="mp-wv-btn" type="button" :disabled="saving" @click="emit('close')">取消</button>
<button class="mp-wv-btn mp-wv-btn--primary" type="button" :disabled="saving" @click="submit"> <button class="mp-wv-btn mp-wv-btn--primary" type="button" :disabled="saving" @click="submit">
{{ saving ? '正在提交…' : '确认复核' }} {{ saving ? '正在提交…' : '确认启用' }}
</button> </button>
</footer> </footer>
</van-popup> </van-popup>
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import { ElMessage } from 'element-plus' import { ElMessage } from 'element-plus'
import AttachmentUploadField from '@/components/business/attachment-upload-field/index.vue'
import { quotaCertApi, type CertType, type QuotaCert } from '@/api/pl/quota-cert' import { quotaCertApi, type CertType, type QuotaCert } from '@/api/pl/quota-cert'
import { randomOperationId } from '@/utils/random-id' import { randomOperationId } from '@/utils/random-id'
import './cert-mobile.scss' import './cert-mobile.scss'
@@ -60,15 +76,19 @@
opening.reason = opening.reason.trim() opening.reason = opening.reason.trim()
saving.value = true saving.value = true
try { try {
await quotaCertApi.verify(kind, props.row.id, { if (props.row.openingConfirmed) {
operationId: opening.operationId, await quotaCertApi.verify(kind, props.row.id, {
reason: opening.reason operationId: opening.operationId,
}) reason: opening.reason
ElMessage.success('证件已复核') })
} else {
await quotaCertApi.confirm(kind, props.row.id, { ...opening })
}
ElMessage.success(props.row.openingConfirmed ? '证件已复核' : '期初已确认')
emit('saved') emit('saved')
emit('close') emit('close')
} catch { } catch {
ElMessage.error('复核没有提交,请重试') ElMessage.error('核对没有提交,请重试')
} finally { } finally {
saving.value = false saving.value = false
} }
@@ -1,7 +1,144 @@
<template> <template>
<CustomerTab :keyword="keyword" /> <main class="mp-h5-list-content mp-plan-cert-list">
<p class="mp-contract-quota-tip">
新规则已生效:安排选证改为客户+证用品类。本页合同用证仅供历史查看与旧规则计划,请勿再作为新计划的用证操作入口。
</p>
<p v-if="error" class="mp-wv-empty" role="alert">
{{ error }}
<button class="mp-wv-btn" type="button" @click="reload">重试</button>
</p>
<div v-else-if="authReady && !allowed" class="mp-wv-empty">
<div class="mp-wv-empty__title">无证件查看权限</div>
</div>
<van-list v-else v-model:loading="loading" :finished="finished" finished-text="" @load="load">
<article
v-for="row in rows"
:key="row.id"
class="mp-wv-card mp-wv-flat-card"
@click="open(row.id)"
>
<div class="mp-wv-card__head">
<div>
<div class="mp-wv-card__no">{{ row.contractNo || '未编号合同' }}</div>
<div class="mp-wv-card__sub">{{ row.contractName || '—' }}</div>
</div>
<span class="status-tag status-tag--info">{{ contractTypeLabel(row.contractType) }}</span>
</div>
<div class="mp-wv-card__kv">
<div class="mp-wv-card__kv-row">
<span>关联证件数</span><span>{{ row.certCount }}</span>
</div>
</div>
<div class="mp-wv-card-actions mp-wv-card-actions--single" @click.stop>
<button class="mp-wv-btn mp-wv-btn--primary" type="button" @click="open(row.id)">查看</button>
</div>
</article>
</van-list>
<van-empty
v-if="authReady && allowed && !loading && finished && !error && !rows.length"
description="暂无合同用证数据"
/>
</main>
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import CustomerTab from './CustomerTab.vue' import { fetchGetMenuCodes } from '@/api/auth'
defineProps<{ keyword: string }>() import { quotaStatisticsApi, type ContractStatisticsSummary } from '@/api/pl/quota-cert'
import { contractTypeLabel } from '@/views/pl/quota-statistics/labels'
const props = defineProps<{ keyword: string }>()
const router = useRouter()
const rows = ref<ContractStatisticsSummary[]>([])
const loading = ref(true)
const finished = ref(false)
const error = ref('')
const allowed = ref(false)
const authReady = ref(false)
const page = ref(1)
let epoch = 0
let checking = true
function open(id: string) {
void router.push(`/m/pl/plan-cert/contract/${id}`)
}
async function init() {
const current = epoch
try {
const permissions = await fetchGetMenuCodes()
if (current !== epoch) return
const codes = permissions?.menuCodes || []
allowed.value =
!!permissions?.all || !!permissions?.isSuperAdmin || codes.includes('pl:quota-cert:list')
authReady.value = true
checking = false
if (!allowed.value) {
finished.value = true
loading.value = false
return
}
await load()
} catch {
if (current !== epoch) return
checking = false
authReady.value = true
finished.value = true
loading.value = false
error.value = '权限加载失败,请重新打开页面'
}
}
function reload() {
if (!allowed.value) {
void init()
return
}
epoch++
page.value = 1
rows.value = []
loading.value = true
finished.value = false
error.value = ''
void load()
}
async function load() {
if (checking || !allowed.value) return
const current = epoch
loading.value = true
try {
const data = await quotaStatisticsApi.contracts({
page: page.value,
pageSize: 20,
keyword: props.keyword || undefined
})
if (current !== epoch) return
const list = data?.list || []
rows.value = page.value === 1 ? list : rows.value.concat(list)
finished.value = rows.value.length >= (data?.total || 0) || list.length < 20
page.value += 1
} catch {
if (current === epoch) {
error.value = '统计加载失败,请重试'
finished.value = true
}
} finally {
if (current === epoch) loading.value = false
}
}
watch(
() => props.keyword,
() => {
if (!checking && allowed.value) reload()
}
)
void init()
</script> </script>
<style scoped>
.mp-contract-quota-tip {
margin: 8px 12px 0;
padding: 10px 12px;
border-radius: 8px;
background: #ecfdf5;
color: #065f46;
font-size: 12px;
line-height: 1.5;
}
</style>
@@ -1,143 +0,0 @@
<template>
<main class="mp-h5-list-content mp-plan-cert-list">
<p class="mp-customer-quota-tip">按客户展示购买证、运输证;证件关联客户,不再按合同绑定。</p>
<p v-if="error" class="mp-wv-empty" role="alert">
{{ error }}
<button class="mp-wv-btn" type="button" @click="reload">重试</button>
</p>
<div v-else-if="authReady && !allowed" class="mp-wv-empty">
<div class="mp-wv-empty__title">无证件查看权限</div>
</div>
<van-list v-else v-model:loading="loading" :finished="finished" finished-text="" @load="load">
<article
v-for="row in rows"
:key="row.id"
class="mp-wv-card mp-wv-flat-card"
@click="open(row.id)"
>
<div class="mp-wv-card__head">
<div>
<div class="mp-wv-card__no">{{ row.customerName || '未命名客户' }}</div>
<div class="mp-wv-card__sub">{{ row.customerNo || '—' }}</div>
</div>
</div>
<div class="mp-wv-card__kv">
<div class="mp-wv-card__kv-row">
<span>关联证件数</span><span>{{ row.certCount }}</span>
</div>
</div>
<div class="mp-wv-card-actions mp-wv-card-actions--single" @click.stop>
<button class="mp-wv-btn mp-wv-btn--primary" type="button" @click="open(row.id)"
>查看</button
>
</div>
</article>
</van-list>
<van-empty
v-if="authReady && allowed && !loading && finished && !error && !rows.length"
description="暂无客户用证数据"
/>
</main>
</template>
<script setup lang="ts">
import { fetchGetMenuCodes } from '@/api/auth'
import { quotaStatisticsApi, type CustomerStatisticsSummary } from '@/api/pl/quota-cert'
const props = defineProps<{ keyword: string }>()
const router = useRouter()
const rows = ref<CustomerStatisticsSummary[]>([])
const loading = ref(true)
const finished = ref(false)
const error = ref('')
const allowed = ref(false)
const authReady = ref(false)
const page = ref(1)
let epoch = 0
let checking = true
function open(id: string) {
void router.push(`/m/pl/plan-cert/customer/${id}`)
}
async function init() {
const current = epoch
try {
const permissions = await fetchGetMenuCodes()
if (current !== epoch) return
const codes = permissions?.menuCodes || []
allowed.value =
!!permissions?.all || !!permissions?.isSuperAdmin || codes.includes('pl:quota-cert:list')
authReady.value = true
checking = false
if (!allowed.value) {
finished.value = true
loading.value = false
return
}
await load()
} catch {
if (current !== epoch) return
checking = false
authReady.value = true
finished.value = true
loading.value = false
error.value = '权限加载失败,请重新打开页面'
}
}
function reload() {
if (!allowed.value) {
void init()
return
}
epoch++
page.value = 1
rows.value = []
loading.value = true
finished.value = false
error.value = ''
void load()
}
async function load() {
if (checking || !allowed.value) return
const current = epoch
loading.value = true
try {
const data = await quotaStatisticsApi.customers({
page: page.value,
pageSize: 20,
keyword: props.keyword || undefined
})
if (current !== epoch) return
const list = data?.list || []
rows.value = page.value === 1 ? list : rows.value.concat(list)
finished.value = rows.value.length >= (data?.total || 0) || list.length < 20
page.value += 1
} catch {
if (current === epoch) {
error.value = '统计加载失败,请重试'
finished.value = true
}
} finally {
if (current === epoch) loading.value = false
}
}
watch(
() => props.keyword,
() => {
if (!checking && allowed.value) reload()
}
)
void init()
</script>
<style scoped>
.mp-customer-quota-tip {
margin: 8px 12px 0;
padding: 10px 12px;
border-radius: 8px;
background: #ecfdf5;
color: #065f46;
font-size: 12px;
line-height: 1.5;
}
</style>
@@ -1201,20 +1201,19 @@
return return
} }
const certRecord = (cert || {}) as Record<string, any> const certRecord = (cert || {}) as Record<string, any>
let name = '' let name =
try { String(certRecord.customerName || '').trim() ||
const detail = (await fetchCustomerDetail({ id })) as Record<string, any> systemCustomer.value.customerName ||
const data = detail?.data || detail customerOptions.value.find((item) => item.id === id)?.customerName ||
name = String(data?.customerName || '').trim() ''
} catch {
name = ''
}
// 系统客户以 CRM 为准;禁止用证面收货单位等缓存名顶替。
if (!name) { if (!name) {
name = try {
String(certRecord.customerName || '').trim() || const detail = (await fetchCustomerDetail({ id })) as Record<string, any>
customerOptions.value.find((item) => item.id === id)?.customerName || const data = detail?.data || detail
id name = String(data?.customerName || '').trim() || id
} catch {
name = id
}
} }
systemCustomer.value = { id, customerName: name } systemCustomer.value = { id, customerName: name }
form.value.customerId = id form.value.customerId = id
@@ -1,91 +0,0 @@
<template>
<MpWebviewShell @ready="onShellReady">
<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">
{{ error }}
<button class="mp-wv-btn" type="button" @click="retry">重试</button>
</p>
<div v-else-if="!authReady || loading" class="mp-cert-page-loading"><van-loading /></div>
<div v-else-if="!allowed" class="mp-wv-empty">
<div class="mp-wv-empty__title">无证件查看权限</div>
</div>
<template v-else-if="detail">
<section class="mp-wv-section">
<div class="mp-cert-contract-head">
<div class="mp-cert-contract-head__main">
<h3>{{ detail.customerName || '未命名客户' }}</h3>
<p>{{ detail.customerNo || '—' }}</p>
</div>
</div>
<div class="mp-wv-card__kv">
<div class="mp-wv-card__kv-row">
<span>关联证件数</span><span>{{ detail.certCount ?? certificates.length }}</span>
</div>
</div>
</section>
<CustomerCertQuotaTab :customer-id="customerId" :active="true" />
</template>
</main>
</MpWebviewShell>
</template>
<script setup lang="ts">
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)
const error = ref('')
const detail = ref<CustomerStatistics | null>(null)
const customerId = computed(() => String(route.params.id || '').trim())
const certificates = computed(() => detail.value?.certificates || [])
async function load() {
const id = customerId.value
if (!id) {
error.value = '缺少客户 ID'
loading.value = false
return
}
loading.value = true
error.value = ''
try {
const permissions = await fetchGetMenuCodes()
const codes = permissions?.menuCodes || []
allowed.value =
!!permissions?.all || !!permissions?.isSuperAdmin || codes.includes('pl:quota-cert:list')
authReady.value = true
if (!allowed.value) {
loading.value = false
return
}
detail.value = await quotaStatisticsApi.customer(id)
} catch (e: any) {
detail.value = null
error.value = e?.message || '加载失败'
} finally {
loading.value = false
}
}
function retry() {
void load()
}
watch(customerId, () => void load(), { immediate: true })
</script>
@@ -30,22 +30,6 @@ const longFaceKeys = new Set([
export type FaceField = { label: string; value: string; wide?: boolean } export type FaceField = { label: string; value: string; wide?: boolean }
export type FaceGroup = { title: string; fields: FaceField[] } 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( export function certFaceGroups(
cert: QuotaCert, cert: QuotaCert,
kind: CertType, kind: CertType,
@@ -60,21 +44,7 @@ export function certFaceGroups(
: display(cert, field[0]), : display(cert, field[0]),
wide: longFaceKeys.has(field[0]) || field[0] === 'vehicleNumbersJson' wide: longFaceKeys.has(field[0]) || field[0] === 'vehicleNumbersJson'
})) }))
if (index === 0) { if (index === 0) fields.unshift({ label: '状态', value: display(cert, 'status') })
fields.unshift(
{ label: '状态', value: display(cert, 'status') },
{
label: '系统客户',
value: String(cert.customerName || '').trim() || '—',
wide: true
},
{
label: '证用品类',
value: certCategoryLabel(cert, kind),
wide: true
}
)
}
return { title: group.title, fields } return { title: group.title, fields }
}) })
groups[groups.length - 1].fields.push({ groups[groups.length - 1].fields.push({
+2 -2
View File
@@ -183,7 +183,7 @@
const committed = ref('') const committed = ref('')
const CERT_TABS = [ const CERT_TABS = [
{ name: 'archive', title: '证件建档', perm: 'mini:pl:quota-cert:list' }, { name: 'archive', title: '证件建档', perm: 'mini:pl:quota-cert:list' },
{ name: 'contract', title: '客户用证', perm: 'mini:pl:contract-quota:list' }, { name: 'contract', title: '合同用证', perm: 'mini:pl:contract-quota:list' },
{ name: 'usage', title: '证件用量', perm: 'mini:pl:certificate-usage:list' }, { name: 'usage', title: '证件用量', perm: 'mini:pl:certificate-usage:list' },
{ name: 'plan', title: '计划段次用证', perm: 'mini:pl:plan-cert:segment' }, { name: 'plan', title: '计划段次用证', perm: 'mini:pl:plan-cert:segment' },
{ name: 'ready', title: '证书齐备', perm: 'mini:pl:cert-ready:list' } { name: 'ready', title: '证书齐备', perm: 'mini:pl:cert-ready:list' }
@@ -361,7 +361,7 @@
] ]
const placeholder = computed(() => const placeholder = computed(() =>
tab.value === 'contract' tab.value === 'contract'
? '客户名称 / 编号' ? '合同编号 / 名称 / 销售或购买单位'
: tab.value === 'plan' || tab.value === 'ready' : tab.value === 'plan' || tab.value === 'ready'
? '计划编号 / 供方 / 需方' ? '计划编号 / 供方 / 需方'
: '证件编号 / 品名 / 销售或购买单位' : '证件编号 / 品名 / 销售或购买单位'
+6 -8
View File
@@ -50,14 +50,6 @@
class="list-table" class="list-table"
@selection-change="onSelectionChange" @selection-change="onSelectionChange"
> >
<el-table-column
v-if="listMode === 'fulfill'"
type="selection"
width="48"
align="center"
header-align="center"
:reserve-selection="false"
/>
<el-table-column <el-table-column
v-for="column in columns" v-for="column in columns"
:key="column.prop" :key="column.prop"
@@ -101,6 +93,12 @@
<span v-else>{{ row[column.prop] || '—' }}</span> <span v-else>{{ row[column.prop] || '—' }}</span>
</template> </template>
</el-table-column> </el-table-column>
<el-table-column
v-if="listMode === 'fulfill'"
type="selection"
width="48"
:reserve-selection="false"
/>
<el-table-column label="操作" min-width="260" fixed="right"> <el-table-column label="操作" min-width="260" fixed="right">
<template #default="{ row }"> <template #default="{ row }">
<template v-if="listMode === 'fulfill'"> <template v-if="listMode === 'fulfill'">
@@ -1,8 +1,8 @@
<template><CustomerQuotaPanel v-bind="props" /></template> <template><StatisticsPanel mode="contract" v-bind="props" /></template>
<script setup lang="ts"> <script setup lang="ts">
import CustomerQuotaPanel from './CustomerQuotaPanel.vue' import StatisticsPanel from '../quota-statistics/StatisticsPanel.vue'
const props = withDefaults( const props = withDefaults(
defineProps<{ customerId?: string; embedded?: boolean; active?: boolean }>(), defineProps<{ contractId?: string; embedded?: boolean; active?: boolean }>(),
{ active: true } { active: true }
) )
</script> </script>
@@ -1,297 +0,0 @@
<template>
<div class="dialog-list-panel customer-cert-quota-panel">
<div class="list-toolbar">
<div class="list-toolbar-row contract-quota-toolbar">
<span class="contract-quota-toolbar__tip"
>展示该客户全部购买证、运输证(证件关联客户,不再按合同绑定)。额度按单张证件核算,多个合同共用共享余额。</span
>
<el-button :loading="loading" @click="load"
><el-icon><Refresh /></el-icon>刷新</el-button
>
</div>
</div>
<el-alert v-if="error" :title="error" type="error" :closable="false" class="mb-3"
><el-button @click="load"><el-icon><Refresh /></el-icon>重试</el-button></el-alert
>
<div v-loading="loading">
<el-empty
v-if="!customerId"
description="合同未关联客户,无法展示证件"
/>
<el-empty
v-else-if="!loading && !error && !rows.length"
description="该客户暂无购买证或运输证"
/>
<ListTable
v-else-if="rows.length"
table-key="crm-customer-cert-quota"
:data="rows"
class="list-table"
stripe
empty-text="该客户暂无购买证或运输证"
>
<el-table-column type="index" label="序号" width="68" align="center" header-align="center" />
<el-table-column label="证种" min-width="100" align="center" header-align="center">
<template #default="{ row }">
<el-tag size="small" :type="certKindTagType(row.certType)">{{
certKindLabel(row.certType)
}}</el-tag>
</template>
</el-table-column>
<el-table-column label="证号" min-width="160" align="center" header-align="center">
<template #default="{ row }">
<el-link type="primary" @click="openDetail(row)">{{ row.certNo || '—' }}</el-link>
</template>
</el-table-column>
<el-table-column
prop="productNameOnCert"
label="证面品名"
min-width="140"
:show-overflow-tooltip="true"
/>
<el-table-column label="有效次数" min-width="120" align="center" header-align="center">
<template #default="{ row }">
<span>{{ row.validUseText || '—' }}</span>
<el-tag
v-if="row.singleUseConsumed"
class="ml-1"
type="danger"
size="small"
>已使用不可再用</el-tag
>
</template>
</el-table-column>
<el-table-column label="核定" min-width="110" align="right" header-align="center">
<template #default="{ row }">{{ qtyText(row.totalQty, row.quantityUnit) }}</template>
</el-table-column>
<el-table-column label="预占" min-width="110" align="right" header-align="center">
<template #default="{ row }">{{ qtyText(row.reservedQty, row.quantityUnit) }}</template>
</el-table-column>
<el-table-column label="已用" min-width="110" align="right" header-align="center">
<template #default="{ row }">{{ qtyText(row.usedQty, row.quantityUnit) }}</template>
</el-table-column>
<el-table-column label="余量" min-width="110" align="right" header-align="center">
<template #default="{ row }">{{ qtyText(row.availableQty, row.quantityUnit) }}</template>
</el-table-column>
<el-table-column label="有效期" min-width="200" align="center" header-align="center">
<template #default="{ row }"
>{{ row.validFrom || '—' }} 至 {{ row.validTo || '—' }}</template
>
</el-table-column>
<el-table-column label="状态" min-width="110" align="center" header-align="center">
<template #default="{ row }">
<el-tag size="small" :type="statusTagType(row.status)">{{
certStatusLabel(row.status)
}}</el-tag>
</template>
</el-table-column>
</ListTable>
</div>
<el-dialog
v-model="detailVisible"
class="dialog-form-layout"
title="证件详情"
width="720px"
align-center
destroy-on-close
>
<div v-loading="detailLoading" class="customer-cert-detail">
<template v-if="detail">
<div class="customer-cert-detail__tags">
<el-tag size="small" :type="certKindTagType(detail.certType)">{{
certKindLabel(detail.certType)
}}</el-tag>
<el-tag size="small" :type="statusTagType(detail.status)">{{
certStatusLabel(detail.status)
}}</el-tag>
<el-tag v-if="detail.singleUseConsumed" size="small" type="danger"
>已使用不可再用</el-tag
>
</div>
<dl class="customer-cert-detail__kv">
<div v-for="item in detailFields" :key="item.label">
<dt>{{ item.label }}</dt>
<dd>{{ item.value }}</dd>
</div>
</dl>
</template>
</div>
</el-dialog>
</div>
</template>
<script setup lang="ts">
import { Refresh } from '@element-plus/icons-vue'
import { useDictStore } from '@/store/modules/dict'
import { getProductUnitLabel } from '@/utils/crm-product-display'
import { quotaCertApi, type CertType, type QuotaCert } from '@/api/pl/quota-cert'
import { certKindLabel, certKindTagType } from '@/views/pl/quota-cert/cert-list-face'
import { formatCertQty } from '@/views/pl/quota-cert/model'
type CustomerCertRow = QuotaCert & { certType: CertType }
const props = withDefaults(
defineProps<{ customerId?: string | number | null; active?: boolean }>(),
{ active: true }
)
const dictStore = useDictStore()
const loading = ref(false)
const error = ref('')
const rows = ref<CustomerCertRow[]>([])
const detailVisible = ref(false)
const detailLoading = ref(false)
const detail = ref<CustomerCertRow | null>(null)
let loadEpoch = 0
const detailFields = computed(() => {
const row = detail.value
if (!row) return []
return [
{ label: '证号', value: row.certNo || '—' },
{ label: '证面品名', value: row.productNameOnCert || '—' },
{ label: '有效次数', value: row.validUseText || '—' },
{ label: '核定', value: qtyText(row.totalQty, row.quantityUnit) },
{ label: '预占', value: qtyText(row.reservedQty, row.quantityUnit) },
{ label: '已用', value: qtyText(row.usedQty, row.quantityUnit) },
{ label: '余量', value: qtyText(row.availableQty, row.quantityUnit) },
{ label: '有效期起', value: row.validFrom || '—' },
{ label: '有效期止', value: row.validTo || '—' },
{ label: '状态', value: certStatusLabel(row.status) }
]
})
function unitLabel(unit?: string | null) {
const label = getProductUnitLabel(dictStore.getLabel, unit)
return !label || label === '—' ? '' : label
}
function qtyText(value: unknown, unit?: string | null) {
const text = formatCertQty(value)
const name = unitLabel(unit)
return name ? `${text} ${name}` : text
}
function certStatusLabel(status?: string | null) {
return (
{
draft: '待核对',
active: '证件已启用',
suspended: '证件已停用',
closed: '证件已核销',
void: '证件已作废'
}[status || ''] ||
status ||
'—'
)
}
function statusTagType(status?: string | null) {
if (status === 'active') return 'success'
if (status === 'suspended') return 'warning'
if (status === 'closed' || status === 'void') return 'danger'
return 'info'
}
async function load() {
const customerId = props.customerId == null ? '' : String(props.customerId).trim()
const epoch = ++loadEpoch
if (!customerId) {
rows.value = []
error.value = ''
loading.value = false
return
}
loading.value = true
error.value = ''
try {
const [purchase, transport] = await Promise.all([
quotaCertApi.list('purchase', { customerId }),
quotaCertApi.list('transport', { customerId })
])
if (epoch !== loadEpoch) return
rows.value = [
...(purchase || []).map((item) => ({ ...item, certType: 'purchase' as const })),
...(transport || []).map((item) => ({ ...item, certType: 'transport' as const }))
].sort((a, b) => String(b.createTime || '').localeCompare(String(a.createTime || '')))
} catch (e: any) {
if (epoch !== loadEpoch) return
rows.value = []
error.value = e?.message || '加载客户证件失败'
} finally {
if (epoch === loadEpoch) loading.value = false
}
}
async function openDetail(row: CustomerCertRow) {
detailVisible.value = true
detailLoading.value = true
detail.value = null
try {
const data = await quotaCertApi.get(row.certType, row.id)
detail.value = { ...data, certType: row.certType }
} catch (e: any) {
detailVisible.value = false
ElMessage.error(e?.message || '加载证件详情失败')
} finally {
detailLoading.value = false
}
}
watch(
() => [props.customerId, props.active],
([, active]) => {
if (active) void load()
},
{ immediate: true }
)
</script>
<style scoped lang="scss">
.contract-quota-toolbar {
width: 100%;
justify-content: space-between;
gap: 12px;
}
.contract-quota-toolbar__tip {
color: var(--mint-text-muted, #64748b);
font-size: 12px;
line-height: 1.5;
}
.customer-cert-detail__tags {
display: flex;
flex-wrap: wrap;
gap: 8px;
margin-bottom: 16px;
}
.customer-cert-detail__kv {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 12px 16px;
margin: 0;
div {
display: grid;
gap: 4px;
}
dt {
font-size: 12px;
color: var(--mint-text-muted, #64748b);
}
dd {
margin: 0;
font-size: 14px;
color: var(--mint-text, #0f172a);
}
}
.ml-1 {
margin-left: 4px;
}
</style>
@@ -1,318 +0,0 @@
<template>
<section :class="embedded ? 'dialog-list-panel' : 'panel'">
<div v-if="!embedded" class="panel-top"><h2 class="title-bar-heading">客户用证</h2></div>
<div v-if="!customerId" class="list-toolbar">
<div class="list-toolbar-row cert-list-toolbar-row">
<ListQuickSearchInput
v-model="keyword"
placeholder="客户编号 / 名称"
@search="search"
@clear="search"
/>
<el-button v-if="keyword || hasActiveFilters" @click="reset"
><el-icon><RefreshLeft /></el-icon>清除筛选</el-button
>
<ListToolbarEndActions
:loading="loading"
:column-defs="columns"
v-model:visible-columns="visibleColumns"
v-model:check-all="checkAll"
:is-indeterminate="isIndeterminate"
@refresh="load"
@reset-columns="resetToDefault"
/>
</div>
</div>
<div v-if="customerId" class="list-toolbar">
<div class="list-toolbar-row contract-quota-toolbar">
<span class="contract-quota-toolbar__tip"
>展示该客户全部购买证、运输证;额度按单张证件核算,多个合同共用共享余额。</span
>
</div>
</div>
<el-alert v-if="error" :title="error" type="error" :closable="false"
><el-button @click="allowed ? load() : init()"
><el-icon><Refresh /></el-icon>重试</el-button
></el-alert
>
<div v-if="customerId" v-loading="loading">
<CustomerCertQuotaPanel
v-if="fixedCustomerId"
:customer-id="fixedCustomerId"
:active="active && !loading"
/>
<el-empty
v-else-if="!loading && !error"
:description="allowed ? '客户不存在或无权查看' : '无证件查看权限'"
/>
</div>
<div v-else class="list-body list-wrap">
<div ref="tableWrapRef" class="table-scroll">
<ListTable
ref="tableRef"
table-key="pl-customer-quota-statistics"
:height="tableHeight"
:data="rows"
row-key="id"
stripe
class="list-table"
v-loading="loading"
@expand-change="expand"
>
<el-table-column type="expand">
<template #default="{ row }">
<div
v-loading="details[row.id]?.loading"
class="view-section statistics-expansion"
:style="expansionStyle"
>
<el-alert
v-if="details[row.id]?.error"
title="详情加载失败"
type="error"
:closable="false"
><el-button @click="loadDetail(row)"
><el-icon><Refresh /></el-icon>重试</el-button
></el-alert
>
<CustomerCertQuotaPanel
v-else-if="details[row.id]?.ready"
:customer-id="row.id"
:active="true"
/>
</div>
</template>
</el-table-column>
<el-table-column
v-for="column in visibleDefs"
:key="column.prop"
:prop="column.prop"
:label="column.label"
:min-width="column.type === 'text' ? 170 : 130"
>
<template #header>
<div class="col-header-with-filter">
<span class="col-header-with-filter__label">{{ column.label }}</span>
<ColumnHeaderFilter
:prop="column.prop"
:label="column.label"
:type="column.type"
:enable-sort="false"
:options="column.enumOptions || []"
:model-value="filters[column.prop] || null"
:is-active="isFilterActive(column.prop)"
@update:model-value="(v) => setFilterState(column.prop, v)"
/>
</div>
</template>
<template #default="{ row }">
<span>{{ row[column.prop] ?? '—' }}</span>
</template>
</el-table-column>
</ListTable>
</div>
<div ref="pagerRef" class="pagination list-pager-bar">
<el-pagination
v-model:current-page="page"
:page-size="20"
:total="total"
layout="total, prev, pager, next"
@current-change="load"
/>
</div>
</div>
</section>
</template>
<script setup lang="ts">
import { Refresh, RefreshLeft } from '@element-plus/icons-vue'
import { fetchGetMenuCodes } from '@/api/auth'
import { useUserStore } from '@/store/modules/user'
import { quotaStatisticsApi } from '@/api/pl/quota-cert'
import { usePersistedListColumns } from '@/composables/usePersistedListColumns'
import { useServerColumnFilters } from '@/composables/useServerColumnFilters'
import { useListTableViewportHeight } from '@/composables/useListTableViewportHeight'
import type { ColumnFilterDef } from '@/composables/useClientColumnFilters'
import ListQuickSearchInput from '@/components/business/list-quick-search-input/index.vue'
import ListToolbarEndActions from '@/components/business/list-toolbar-end-actions/index.vue'
import ColumnHeaderFilter from '@/components/business/column-header-filter/index.vue'
import CustomerCertQuotaPanel from './CustomerCertQuotaPanel.vue'
const props = withDefaults(
defineProps<{ customerId?: string; embedded?: boolean; active?: boolean }>(),
{ active: true }
)
const user = useUserStore()
const allowed = ref(false)
const loading = ref(false)
const error = ref('')
const keyword = ref('')
const page = ref(1)
const total = ref(0)
const rows = ref<Record<string, any>[]>([])
const fixedCustomerId = ref('')
const details = reactive<Record<string, { loading: boolean; error?: boolean; ready?: boolean }>>(
{}
)
let epoch = 0
const text = (prop: string, label: string): ColumnFilterDef => ({
prop,
label,
type: 'text',
queryKey: prop
})
const number = (prop: string, label: string): ColumnFilterDef => ({
prop,
label,
type: 'number',
queryKey: prop
})
const columns: ColumnFilterDef[] = [
text('customerNo', '客户编号'),
text('customerName', '客户名称'),
number('certCount', '关联证件数')
]
const {
filters,
hasActiveFilters,
isFilterActive,
setFilterState,
clearAllFilters,
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))
)
watchVisibleColumns(visibleColumns)
const tableWrapRef = ref<HTMLElement | null>(null)
const pagerRef = ref<HTMLElement | null>(null)
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)
})
async function init() {
try {
const p = await fetchGetMenuCodes()
allowed.value =
!!p?.all || !!p?.isSuperAdmin || (p?.menuCodes || []).includes('pl:quota-cert:list')
if (allowed.value) await load()
else error.value = '无证件查看权限'
} catch {
error.value = '权限加载失败'
}
}
function search() {
page.value = 1
void load()
}
function reset() {
keyword.value = ''
clearAllFilters()
search()
}
async function load() {
if (!props.active) return
const current = ++epoch
loading.value = true
error.value = ''
try {
if (props.customerId) {
const data = await quotaStatisticsApi.customer(String(props.customerId))
if (current !== epoch) return
fixedCustomerId.value = data?.id || String(props.customerId)
rows.value = []
total.value = 0
} else {
fixedCustomerId.value = ''
const data = await quotaStatisticsApi.customers({
page: page.value,
pageSize: 20,
keyword: keyword.value || undefined,
...toQueryParams()
})
if (current !== epoch) return
rows.value = data?.list || []
total.value = data?.total || 0
}
} catch (e: any) {
if (current !== epoch) return
error.value = e?.message || '加载失败'
rows.value = []
total.value = 0
fixedCustomerId.value = ''
} finally {
if (current === epoch) loading.value = false
}
}
function expand(row: { id: string }, expanded: unknown[]) {
const open = Array.isArray(expanded)
? expanded.some((item: any) => item?.id === row.id)
: Boolean(expanded)
if (open) void loadDetail(row)
else nextTick(() => recalcTableHeight())
}
async function loadDetail(row: { id: string }) {
details[row.id] = { loading: true, error: false, ready: false }
try {
await quotaStatisticsApi.customer(row.id)
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()
})
}
}
watch(
() => [props.customerId, props.active, JSON.stringify([user.accessToken, user.getUserInfo])],
() => {
if (props.active) void init()
},
{ immediate: true }
)
</script>
<style scoped lang="scss">
.contract-quota-toolbar {
width: 100%;
}
.contract-quota-toolbar__tip {
color: var(--mint-text-muted, #64748b);
font-size: 12px;
line-height: 1.5;
}
.statistics-expansion {
box-sizing: border-box;
max-width: 100%;
padding: 12px 16px 16px;
text-align: left;
}
</style>
+18 -11
View File
@@ -970,7 +970,7 @@ import {
overflowExportPlaceholder overflowExportPlaceholder
} from '@/utils/list-toolbar-overflow-items' } from '@/utils/list-toolbar-overflow-items'
import ListColumnStatsRow from '@/components/business/list-column-stats-row/index.vue' import ListColumnStatsRow from '@/components/business/list-column-stats-row/index.vue'
import { buildStatsRowColumns, type StatsRowColumn } from '@/utils/list-column-stats' import type { StatsRowColumn } from '@/utils/list-column-stats'
import { useContractDetailDialog } from '@/composables/useContractDetailDialog' import { useContractDetailDialog } from '@/composables/useContractDetailDialog'
import { usePersistedListColumns } from '@/composables/usePersistedListColumns' import { usePersistedListColumns } from '@/composables/usePersistedListColumns'
import { useListTableViewportHeight } from '@/composables/useListTableViewportHeight' import { useListTableViewportHeight } from '@/composables/useListTableViewportHeight'
@@ -1287,15 +1287,22 @@ const {
const archiveStatsRowRef = ref<{ resync?: () => void } | null>(null) const archiveStatsRowRef = ref<{ resync?: () => void } | null>(null)
/** 与表头可见列一一对应:勾选/序号占位 + 可见业务列(含可隐藏的 planNo) */ const archiveStatsRowColumns = computed((): StatsRowColumn[] => {
const archiveStatsRowColumns = computed((): StatsRowColumn[] => const cols: StatsRowColumn[] = [
buildStatsRowColumns({ { key: '__selection', interactive: false },
leadingSpacers: 2, { key: '__index', interactive: false },
optionalDefs: listColumnDefs.value, { key: 'planNo', interactive: true, prop: 'planNo' }
isColumnVisible: isArchiveColumnVisible, ]
moneyProps: PRICE_COLUMN_PROPS for (const def of listColumnDefs.value) {
}) if (!isArchiveColumnVisible(def.prop)) continue
) cols.push({
key: def.prop,
interactive: true,
prop: def.prop
})
}
return cols
})
function getArchiveStatCellValue(row: PlPlanListDisplayRow, prop: string): unknown { function getArchiveStatCellValue(row: PlPlanListDisplayRow, prop: string): unknown {
const plan = row.plan const plan = row.plan
@@ -1649,7 +1656,7 @@ async function handleArchive(row: Plan) {
ElMessage.warning('无运输计划归档操作权限') ElMessage.warning('无运输计划归档操作权限')
return return
} }
// 打开归档弹窗:已归档走调整;未归档/已暂存可直接打开(用证校验在「确认归档」时执行,以便支持暂存) // 打开归档弹窗:已归档走调整;未归档/已暂存可直接打开(证书齐备仅在「确认归档」时校验,以便支持暂存)
archivePlanId.value = row.id archivePlanId.value = row.id
archiveDialogVisible.value = true archiveDialogVisible.value = true
} }
+56 -43
View File
@@ -93,10 +93,11 @@
><el-icon><Edit /></el-icon>编辑</el-button ><el-icon><Edit /></el-icon>编辑</el-button
> >
<el-button <el-button
v-if="canEdit && row.openingConfirmed && row.status !== 'void' && row.status !== 'closed'" v-if="canEdit && row.status !== 'void' && row.status !== 'closed'"
size="small" size="small"
@click="openConfirm(row)" @click="openConfirm(row)"
><el-icon><Check /></el-icon>复核</el-button ><el-icon><Check /></el-icon
>{{ row.openingConfirmed ? '复核' : '期初确认' }}</el-button
> >
<el-button size="small" @click="view(row)" <el-button size="small" @click="view(row)"
><el-icon><View /></el-icon>查看</el-button ><el-icon><View /></el-icon>查看</el-button
@@ -590,12 +591,35 @@
</SystemViewDialog> </SystemViewDialog>
<el-dialog <el-dialog
v-model="confirmVisible" v-model="confirmVisible"
title="复核证件" :title="confirmRow?.openingConfirmed ? '复核证件' : '期初核对'"
width="640px" width="640px"
align-center align-center
class="dialog-form-layout quota-cert-confirm-dialog" class="dialog-form-layout quota-cert-confirm-dialog"
> >
<el-form label-position="top"> <el-form label-position="top">
<template v-if="!confirmRow?.openingConfirmed">
<div class="form-grid-2">
<el-form-item>
<template #label>
历史已用量(证面单位)<span v-if="confirmUnit" class="form-label-tip">{{
confirmUnit
}}</span>
</template>
<el-input v-model="opening.usedQty">
<template v-if="confirmUnit" #append>{{ confirmUnit }}</template>
</el-input>
</el-form-item>
<el-form-item label="一次有效证是否已有使用记录">
<el-switch v-model="opening.singleUseConsumed" />
</el-form-item>
</div>
<el-form-item label="历史来源说明">
<el-input v-model="opening.sourceNote" type="textarea" />
</el-form-item>
<el-form-item label="核对凭据">
<AttachmentUploadField v-model="opening.evidenceUrls" folder="pl/quota-cert" />
</el-form-item>
</template>
<el-form-item label="核对说明" <el-form-item label="核对说明"
><el-input v-model="opening.reason" type="textarea" ><el-input v-model="opening.reason" type="textarea"
/></el-form-item> /></el-form-item>
@@ -604,7 +628,7 @@
><el-button @click="confirmVisible = false" ><el-button @click="confirmVisible = false"
><el-icon><Close /></el-icon>取消</el-button ><el-icon><Close /></el-icon>取消</el-button
><el-button type="primary" :loading="saving" @click="confirm" ><el-button type="primary" :loading="saving" @click="confirm"
><el-icon><Check /></el-icon>确认复核</el-button ><el-icon><Check /></el-icon>确认启用</el-button
></template ></template
> >
</el-dialog> </el-dialog>
@@ -642,7 +666,7 @@
type ContractOption, type ContractOption,
type ScopeProduct type ScopeProduct
} from '@/api/pl/quota-cert' } from '@/api/pl/quota-cert'
import { fetchCustomerDetail, fetchCustomerOptions } from '@/api/crm/customer' import { fetchCustomerOptions } from '@/api/crm/customer'
import AttachmentUploadField from '@/components/business/attachment-upload-field/index.vue' import AttachmentUploadField from '@/components/business/attachment-upload-field/index.vue'
import CertContractBinder from './CertContractBinder.vue' import CertContractBinder from './CertContractBinder.vue'
import { import {
@@ -737,32 +761,28 @@
async function ensureCustomerOption(id?: string | null, nameHint = '') { async function ensureCustomerOption(id?: string | null, nameHint = '') {
if (!id) return if (!id) return
let name = '' if (customerOptions.value.some((c) => c.id === id)) return
if (nameHint) {
customerOptions.value = [{ id, customerName: nameHint }, ...customerOptions.value]
return
}
try { try {
const detail = (await fetchCustomerDetail({ id })) as Record<string, any> const result = await fetchCustomerOptions({ keyword: '', limit: 200 })
const data = detail?.data || detail const list = Array.isArray(result)
name = String(data?.customerName || data?.name || '').trim() ? result
} catch { : (result as any)?.list || (result as any)?.data || []
name = '' const hit = (list || []).find((row: any) => String(row.id) === id)
} if (hit) {
if (!name) { customerOptions.value = [
try { { id, customerName: String(hit.customerName || hit.name || id) },
const result = await fetchCustomerOptions({ keyword: nameHint || '', limit: 200 }) ...customerOptions.value
const list = Array.isArray(result) ]
? result } else {
: (result as any)?.list || (result as any)?.data || [] customerOptions.value = [{ id, customerName: id }, ...customerOptions.value]
const hit = (list || []).find((row: any) => String(row.id) === id)
name = String(hit?.customerName || hit?.name || '').trim()
} catch {
name = ''
} }
} catch {
customerOptions.value = [{ id, customerName: id }, ...customerOptions.value]
} }
// 系统客户名称以 CRM 为准;nameHint 仅作 CRM 不可用时的兜底(应为接口返回的 customerName)。
const label = name || String(nameHint || '').trim() || id
customerOptions.value = [
{ id, customerName: label },
...customerOptions.value.filter((c) => c.id !== id)
]
} }
async function loadCategories() { async function loadCategories() {
@@ -1028,17 +1048,8 @@
value: statusLabels[detail.value.status], value: statusLabels[detail.value.status],
tagType: tagType(detail.value.status) tagType: tagType(detail.value.status)
} }
const systemCustomerField: ViewField = {
label: '系统客户',
value: String(detail.value.customerName || '').trim() || '—',
span: 'full'
}
const groups = certFormGroups(kind.value).map((group, index) => const groups = certFormGroups(kind.value).map((group, index) =>
detailGroup( detailGroup(group.title, group.fields, index === 0 ? [statusField] : [])
group.title,
group.fields,
index === 0 ? [statusField, systemCustomerField] : []
)
) )
groups[groups.length - 1].fields.push({ groups[groups.length - 1].fields.push({
label: '系统备注', label: '系统备注',
@@ -1413,7 +1424,7 @@
applyCertForm(targetKind, cert) applyCertForm(targetKind, cert)
await ensureCustomerOption( await ensureCustomerOption(
form.value.customerId, form.value.customerId,
String((cert as QuotaCert).customerName || '').trim() formKind.value === 'purchase' ? form.value.buyerName : form.value.consigneeName
) )
if (targetKind === 'transport') purchases.value = purchaseOptions() if (targetKind === 'transport') purchases.value = purchaseOptions()
} catch (error) { } catch (error) {
@@ -1794,10 +1805,12 @@
saving.value = true saving.value = true
try { try {
const targetKind = rowCertType(confirmRow.value) const targetKind = rowCertType(confirmRow.value)
await quotaCertApi.verify(targetKind, confirmRow.value.id, { if (confirmRow.value.openingConfirmed)
operationId: opening.operationId, await quotaCertApi.verify(targetKind, confirmRow.value.id, {
reason: opening.reason operationId: opening.operationId,
}) reason: opening.reason
})
else await quotaCertApi.confirm(targetKind, confirmRow.value.id, opening)
confirmVisible.value = false confirmVisible.value = false
await load() await load()
} finally { } finally {
@@ -7,7 +7,7 @@
</div> </div>
<div class="p-6 max-w-xl"> <div class="p-6 max-w-xl">
<p class="text-sm text-slate-500 mb-4"> <p class="text-sm text-slate-500 mb-4">
配置「客户+品类」额度生效时间。未配置时无法安排运输。以计划首次安排时刻与该时间比较:之前已安排的归档不再校验购买证/运输证;之后安排的走客户+品类最新规则。首次安排后版本冻结,改派不重打;修改生效时间只影响尚未安排的计划。 配置「客户+品类」额度生效时间。未配置时无法安排运输。计划创建时按该时间打规则版本;修改后只影响之后新建的计划。
</p> </p>
<el-form label-position="top" class="dialog-form-layout"> <el-form label-position="top" class="dialog-form-layout">
<el-form-item label="客户品类额度生效时间"> <el-form-item label="客户品类额度生效时间">
-31
View File
@@ -84,7 +84,6 @@ server {
} }
# MinIO(bucket=ruoyi);兼容旧链接,推荐逐步切到 res.shanxiachem.com # MinIO(bucket=ruoyi);兼容旧链接,推荐逐步切到 res.shanxiachem.com
# 必须 proxy_hide_header 上游 CORS,否则 MinIO 的 Origin 与 nginx 的 * 叠成非法双头
location ^~ /ruoyi/ { location ^~ /ruoyi/ {
proxy_pass http://127.0.0.1:9000; proxy_pass http://127.0.0.1:9000;
@@ -97,15 +96,8 @@ server {
proxy_send_timeout 60s; proxy_send_timeout 60s;
proxy_read_timeout 60s; proxy_read_timeout 60s;
proxy_hide_header Access-Control-Allow-Origin;
proxy_hide_header Access-Control-Allow-Methods;
proxy_hide_header Access-Control-Allow-Headers;
proxy_hide_header Access-Control-Expose-Headers;
proxy_hide_header Access-Control-Allow-Credentials;
add_header Access-Control-Allow-Origin * always; add_header Access-Control-Allow-Origin * always;
add_header Access-Control-Allow-Methods 'GET, HEAD, OPTIONS' always; add_header Access-Control-Allow-Methods 'GET, HEAD, OPTIONS' always;
add_header Access-Control-Allow-Headers 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range,Authorization' always;
if ($request_method = 'OPTIONS') { if ($request_method = 'OPTIONS') {
return 204; return 204;
@@ -232,7 +224,6 @@ server {
} }
} }
# 必须 proxy_hide_header 上游 CORS,否则 MinIO 的 Origin 与 nginx 的 * 叠成非法双头
location ^~ /ruoyi/ { location ^~ /ruoyi/ {
proxy_pass http://127.0.0.1:9000; proxy_pass http://127.0.0.1:9000;
@@ -245,15 +236,8 @@ server {
proxy_send_timeout 60s; proxy_send_timeout 60s;
proxy_read_timeout 60s; proxy_read_timeout 60s;
proxy_hide_header Access-Control-Allow-Origin;
proxy_hide_header Access-Control-Allow-Methods;
proxy_hide_header Access-Control-Allow-Headers;
proxy_hide_header Access-Control-Expose-Headers;
proxy_hide_header Access-Control-Allow-Credentials;
add_header Access-Control-Allow-Origin * always; add_header Access-Control-Allow-Origin * always;
add_header Access-Control-Allow-Methods 'GET, HEAD, OPTIONS' always; add_header Access-Control-Allow-Methods 'GET, HEAD, OPTIONS' always;
add_header Access-Control-Allow-Headers 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range,Authorization' always;
if ($request_method = 'OPTIONS') { if ($request_method = 'OPTIONS') {
return 204; return 204;
@@ -380,7 +364,6 @@ server {
} }
} }
# 必须 proxy_hide_header 上游 CORS,否则 MinIO 的 Origin 与 nginx 的 * 叠成非法双头
location ^~ /ruoyi/ { location ^~ /ruoyi/ {
proxy_pass http://127.0.0.1:9000; proxy_pass http://127.0.0.1:9000;
@@ -393,15 +376,8 @@ server {
proxy_send_timeout 60s; proxy_send_timeout 60s;
proxy_read_timeout 60s; proxy_read_timeout 60s;
proxy_hide_header Access-Control-Allow-Origin;
proxy_hide_header Access-Control-Allow-Methods;
proxy_hide_header Access-Control-Allow-Headers;
proxy_hide_header Access-Control-Expose-Headers;
proxy_hide_header Access-Control-Allow-Credentials;
add_header Access-Control-Allow-Origin * always; add_header Access-Control-Allow-Origin * always;
add_header Access-Control-Allow-Methods 'GET, HEAD, OPTIONS' always; add_header Access-Control-Allow-Methods 'GET, HEAD, OPTIONS' always;
add_header Access-Control-Allow-Headers 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range,Authorization' always;
if ($request_method = 'OPTIONS') { if ($request_method = 'OPTIONS') {
return 204; return 204;
@@ -501,7 +477,6 @@ server {
add_header X-Content-Type-Options "nosniff" always; add_header X-Content-Type-Options "nosniff" always;
# 必须 proxy_hide_header 上游 CORS,否则 MinIO 的 Origin 与 nginx 的 * 叠成非法双头
location ^~ /ruoyi/ { location ^~ /ruoyi/ {
proxy_pass http://127.0.0.1:9000; proxy_pass http://127.0.0.1:9000;
@@ -514,12 +489,6 @@ server {
proxy_send_timeout 60s; proxy_send_timeout 60s;
proxy_read_timeout 60s; proxy_read_timeout 60s;
proxy_hide_header Access-Control-Allow-Origin;
proxy_hide_header Access-Control-Allow-Methods;
proxy_hide_header Access-Control-Allow-Headers;
proxy_hide_header Access-Control-Expose-Headers;
proxy_hide_header Access-Control-Allow-Credentials;
add_header Access-Control-Allow-Origin * always; add_header Access-Control-Allow-Origin * always;
add_header Access-Control-Allow-Methods 'GET, HEAD, OPTIONS' always; add_header Access-Control-Allow-Methods 'GET, HEAD, OPTIONS' always;
add_header Access-Control-Allow-Headers 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range,Authorization' always; add_header Access-Control-Allow-Headers 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range,Authorization' always;